text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.usiellau.messageforward">

    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:name=".other.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!--activity-->
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".activity.MonitorNumberActivity"/>
        <activity android:name=".activity.ForwardNumberActivity"/>
        <activity android:name=".activity.ForwardEmailActivity"/>
        <activity android:name=".activity.SettingActivity"/>

        <!--service-->
        <service android:name=".service.MonitorService"/>

        <!--receiver-->
        <receiver android:name=".receiver.MessageSendResReceiver">
            <intent-filter>
                <action android:name="com.usiellau.messageforward.SENT_MSG_ACTION"/>
            </intent-filter>
        </receiver>
        <receiver android:name=".receiver.BootCompleteReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
        <receiver android:name=".receiver.SmsReceiver">
            <intent-filter android:priority="999">
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>

    </application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "String.format and Arabic numbers"
date:   2013-06-04
tags: android tips
description: Avoid a simple localization mistake by explicitly using a Locale
---
About a simple mistake that can be made in the use of `String.format`. To illustrate this very common mistake, some android code from the `ContactsProvider`.

This code can be found here: <https://android.googlesource.com/platform/packages/providers/ContactsProvider/>

# Details

`String.format` allows formatting of Strings according to the following documentation <http://developer.android.com/reference/java/util/Formatter.html>

This is sometimes used for formatting SQLite queries in android. In particular, this is used in the `ContactsProvider`.

However, there is a pitfall in the use of `String.format` to format SQL queries.

Until Gingerbread release, the following lines are present in `ContactAggregator`:

```java
mRawContactsQueryByRawContactId = String.format(
        RawContactsQuery.SQL_FORMAT_BY_RAW_CONTACT_ID,
        MimeTypeIdPhoto, mMimeTypeIdPhone);
```

Where in `RawContactsQuery`, `SQL_FORMAT_BY_RAW_CONTACT_ID` contains 2 `%d` to be replaced by numbers in the `String.format`.

Here is the trap.

> 1. SQLite will expect these values to be Latin numbers or column names, because they are not quoted.
2. String.format uses the current locale unless explicitly specified.
3. In Arabic, %d results in Arabic numbers such as ١٢٣...

> Conclusion: If your locale is Arabic, SQLite searches for a column named after an Arabic number, which does not exist, and crashes.
This kind of issue will go totally unnoticed until you test your app with an Arabic locale.

Nota: the `Formatter` documentation clearly states this under the Number localization paragraph.

# Conclusion

The solution to avoid this is to force the locale to, for instance `Locale.US`. Incidentally, this is the solution implemented in ICS.

```java
mRawContactsQueryByRawContactId = String.format(Locale.US
        RawContactsQuery.SQL_FORMAT_BY_RAW_CONTACT_ID,
        mMimeTypeIdPhoto, mMimeTypeIdPhone);
```


text:
namespace BuildMonitor.Logic.BuildExplorer
{
   using System;
   using System.Collections.Generic;
   using System.Globalization;
   using System.Linq;
   using System.Net;
   using System.Net.Http;
   using System.Net.Http.Headers;
   using System.Text;
   using System.Threading.Tasks;

   using BuildMonitor.Logic.Contracts;
   using BuildMonitor.Logic.Interfaces;

   using Newtonsoft.Json;

   ///
   /// Implementation of the <see cref="IBuildExplorer"/> for TFS version 2013.
   ///
   internal class Tfs2013Explorer : IBuildExplorer
   {
      private readonly List<string> validTestTexts = new List<string> { "Run MSTest for Test Assemblies", "Run Tests on Environment" };

      /// Gets the build result.
      /// <param name="buildInformation">The build information.</param>
      /// <returns>The <see cref="BuildResult" />.</returns>
      public async Task<BuildResultCollection> GetBuildResultCollection(BuildInformation buildInformation)
      {
         var collectionResult = new BuildResultCollection();

         string response;
         using (var httpClient = WebClientFactory.CreateHttpClient(buildInformation.DomainName, buildInformation.Login, buildInformation.CryptedPassword))
         {
            HttpResponseMessage responseMessage;
            try
            {
               responseMessage = await httpClient.GetAsync(buildInformation.BuildDefinitionUrl);
            }
            catch (HttpRequestException ex)
            {
               collectionResult.ErrorMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
               return collectionResult;
            }

            if (!responseMessage.IsSuccessStatusCode)
            {
               collectionResult.ErrorMessage = string.Format("Error {0}:{1} - {2}", (int)responseMessage.StatusCode,
                  responseMessage.StatusCode, responseMessage.ReasonPhrase);
               return collectionResult;
            }

            response = await responseMessage.Content.ReadAsStringAsync();
         }

         try
         {
            dynamic jsonObject = JsonConvert.DeserializeObject(response);

            foreach (var jsonItem in jsonObject.value)
            {
               var buildResult = new BuildResult();
               collectionResult.BuildResults.Add(buildResult);

               buildResult.Name = jsonItem.definition.name;
               buildResult.Number = jsonItem.buildNumber;
               buildResult.TfsUri = jsonItem.uri;
               buildResult.RequestedBy = jsonItem.requests[0].requestedFor.displayName;

               string finishTimeString = jsonItem.finishTime == null ? string.Empty : string.Format("{0}", jsonItem.finishTime);
               var finishDate = DateTime.MinValue;
               if (!string.IsNullOrEmpty(finishTimeString))
               {
                  finishDate = DateTime.Parse(finishTimeString, CultureInfo.CurrentCulture,
                     DateTimeStyles.AssumeUniversal);
                  buildResult.FinishTime = finishDate.ToString("g", CultureInfo.CurrentCulture);
               }

               string startTimeString = jsonItem.startTime == null ? string.Empty : string.Format("{0}", jsonItem.startTime);
               if (!string.IsNullOrEmpty(startTimeString))
               {
                  var startTime = DateTime.Parse(startTimeString, CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);
                  if (finishDate != DateTime.MinValue)
                  {
                     var delta = finishDate - startTime;
                     buildResult.Duration = delta.TotalMinutes;
                  }
               }

               var buildstatusString = string.Format("{0}", jsonItem.status);
               buildResult.Status = (BuildStatus)Enum.Parse(typeof(BuildStatus), buildstatusString, true);
               if (buildResult.Status == BuildStatus.InProgress)
               {
                  await FillInProgressBuild(buildInformation, jsonItem, buildResult);
               }
            }

            return collectionResult;
         }
         catch (Exception ex)
         {
            collectionResult.ErrorMessage = ex.Message;
            return collectionResult;
         }
      }

      /// Gets the build definitions.
      /// <param name="buildServer">The build server.</param>
      /// <returns>The <see cref="TfsConnectResult" />.</returns>
      public async Task<TfsConnectResult> GetBuildDefinitions(BuildServer buildServer)
      {
         string response;
         using (var httpClient = WebClientFactory.CreateHttpClient(buildServer.DomainName, buildServer.Login, buildServer.PasswordBytes))
         {
            HttpResponseMessage responseMessage;
            try
            {
               responseMessage = await httpClient.GetAsync(buildServer.Url);
            }
            catch (HttpRequestException exception)
            {
               return new TfsConnectResult { Message = exception.InnerException != null ? exception.InnerException.Message : exception.Message };
            }

            if (!responseMessage.IsSuccessStatusCode)
            {
               return new TfsConnectResult
               {
                  Message = string.Format("Error {0}:{1} - {2}", (int)responseMessage.StatusCode, responseMessage.StatusCode, responseMessage.ReasonPhrase)
               };
            }

            response = await responseMessage.Content.ReadAsStringAsync();
         }

         dynamic jsonObject = JsonConvert.DeserializeObject(response);
         var result = new TfsConnectResult();
         try
         {
            foreach (var item in jsonObject.value)
            {
               var buildResult = new BuildDefinitionResult { Id = item.id, Name = item.name, Uri = item.uri, Url = item.url };
               if (buildServer.TfsVersion == TfsVersion.Version2015)
               {
                  buildResult.ProjectName = item.project.name;
               }

               result.BuildDefinitions.Add(buildResult);
            }
         }
         catch (Exception ex)
         {
            result.Message = "Error on getting list of builds - May be wrong TFS type - " + ex.Message;
         }

         return result;
      }

      /// Stops the build.
      /// <param name="buildInformation">The build information.</param>
      /// <param name="buildId">The build identifier.</param>
      /// <returns>True if stopping the build succeed; otherwise false.</returns>
      public async Task<BuildResult> StopBuild(BuildInformation buildInformation, string buildId)
      {
         string response;
         try
         {
            using (var httpClient = WebClientFactory.CreateHttpClient(buildInformation.DomainName, buildInformation.Login, buildInformation.CryptedPassword))
            {
               httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
               var requestUri = string.Format(buildInformation.StopBuildUrl, buildId);
               var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri) { Content = new StringContent("{ \"status\": \"Stopped\" }", Encoding.UTF8, "application/json") };

               var responseMessage = await httpClient.SendAsync(request);
               if (responseMessage.StatusCode != HttpStatusCode.OK)
               {
                  return new BuildResult { Name = responseMessage.StatusCode.ToString("G") };
               }

               response = await responseMessage.Content.ReadAsStringAsync();
            }
         }
         catch (Exception ex)
         {
            return new BuildResult { Name = ex.Message };
         }

         dynamic jsonObject = JsonConvert.DeserializeObject(response);
         var buildstatusString = string.Format("{0}", jsonObject.status);
         var buildStatus = (BuildStatus)Enum.Parse(typeof(BuildStatus), buildstatusString, true);
         return new BuildResult { Name = jsonObject.buildNumber, Status = buildStatus, RequestedBy = jsonObject.lastChangedBy.displayName, TfsUri = jsonObject.uri };
      }

      /// Requests the build.
      /// <param name="buildInformation">The build information.</param>
      /// <returns>True if requesting the build succeed; otherwise false.</returns>
      public async Task<BuildResult> RequestBuild(BuildInformation buildInformation)
      {
         string response;
         try
         {
            using (var httpClient = WebClientFactory.CreateHttpClient(buildInformation.DomainName, buildInformation.Login, buildInformation.CryptedPassword))
            {
               httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
               var json = string.Format("{{ \"definition\": {{ \"id\": {0} }}, \"reason\": \"Manual\", \"priority\": \"Normal\" }}", buildInformation.BuildDefinitionId);
               var request = new HttpRequestMessage(HttpMethod.Post, buildInformation.RequestBuildUrl) { Content = new StringContent(json, Encoding.UTF8, "application/json") };

               var responseMessage = await httpClient.SendAsync(request);
               if (responseMessage.StatusCode != HttpStatusCode.OK)
               {
                  return new BuildResult { Name = responseMessage.StatusCode.ToString("G") };
               }

               response = await responseMessage.Content.ReadAsStringAsync();
            }
         }
         catch (Exception ex)
         {
            return new BuildResult { Name = ex.Message };
         }

         dynamic jsonObject = JsonConvert.DeserializeObject(response);
         var buildstatusString = string.Format("{0}", jsonObject.status);
         var buildStatus = (BuildStatus)Enum.Parse(typeof(BuildStatus), buildstatusString, true);
         string buildId = string.Concat("vstfs:///Build/Build/", jsonObject.builds[0].id);
         return new BuildResult
         {
            Name = jsonObject.definition.name,
            Status = buildStatus,
            RequestedBy = jsonObject.requestedBy.displayName,
            TfsUri = buildId
         };
      }

      public Task GetTestResultAsync(BuildInformation buildInformation, BuildResult result)
      {
         // Todo: Implement me
         return null;
      }

      public Task<Changeset> GetChangesetAsync(BuildInformation buildInformation, int sourceVersion)
      {
         // Todo: Implement me
         throw new NotImplementedException();
      }

      private async Task FillInProgressBuild(BuildInformation buildInformation, dynamic jsonItem, BuildResult buildResult)
      {
         string response2;
         using (
            var httpClient = WebClientFactory.CreateHttpClient(buildInformation.DomainName, buildInformation.Login,
               buildInformation.CryptedPassword))
         {
            var buildIdUri = string.Format(buildInformation.TestResultUrl, jsonItem.id);
            var responseMsgs2 = await httpClient.GetAsync(buildIdUri);
            response2 = await responseMsgs2.Content.ReadAsStringAsync();
         }

         UpdateProperties(response2, buildResult);
         buildResult.IsRunning = true;
         var buildReason = string.Format("{0}", jsonItem.reason);
         buildResult.IsGatedCheckin = string.Equals(buildReason, "checkInShelveset",
            StringComparison.InvariantCultureIgnoreCase);
         buildResult.RunningTfsUri = jsonItem.uri;
         buildResult.RunningBuildId = jsonItem.id;
         buildResult.RunningBuildRequestedBy = jsonItem.requests[0].requestedFor.displayName;
         buildResult.RunningBuildNumber = jsonItem.buildNumber;
         buildResult.RunningBuildTfsUri = jsonItem.uri;
         var runningStartTimeString = string.Format("{0}", jsonItem.startTime);
         if (!string.IsNullOrEmpty(runningStartTimeString))
         {
            buildResult.RunningStartTime = DateTime.Parse(runningStartTimeString, CultureInfo.CurrentCulture,
               DateTimeStyles.AssumeUniversal);
         }
      }

      private void UpdateProperties(string response, BuildResult buildResult)
      {
         var rootObject = JsonConvert.DeserializeObject<RootObject>(response);
         foreach (var node in rootObject.information[0].nodes)
         {
            RecursivelyCheckBuildWaiting(buildResult, node);
         }

         foreach (var node in rootObject.information[0].nodes)
         {
            RecursivelyCheckTestsFailed(buildResult, node);
         }

         foreach (var node in rootObject.information[0].nodes)
         {
            RecursivelyCheckTestsRunning(buildResult, node);
         }
      }

      private void RecursivelyCheckBuildWaiting(BuildResult buildResult, Node node)
      {
         if (buildResult.Waiting || string.IsNullOrEmpty(node.text))
         {
            return;
         }

         if (node.text.Equals("Run On Agent (waiting for build agent)", StringComparison.InvariantCultureIgnoreCase))
         {
            buildResult.Waiting = true;
            return;
         }

         if (node.nodes == null)
         {
            return;
         }

         foreach (var subNode in node.nodes)
         {
            RecursivelyCheckBuildWaiting(buildResult, subNode);
         }
      }

      private void RecursivelyCheckTestsFailed(BuildResult buildResult, Node node)
      {
         if (buildResult.TestsFailed)
         {
            return;
         }

         AreTestsFailed(buildResult, node);
         if (node.nodes == null)
         {
            return;
         }

         foreach (var subNode in node.nodes)
         {
            RecursivelyCheckTestsFailed(buildResult, subNode);
         }
      }

      private void RecursivelyCheckTestsRunning(BuildResult buildResult, Node node)
      {
         if (buildResult.TestsRunning || buildResult.TestsFailed)
         {
            return;
         }

         AreTestsRunning(buildResult, node);
         if (node.nodes == null)
         {
            return;
         }

         foreach (var subNode in node.nodes)
         {
            RecursivelyCheckTestsRunning(buildResult, subNode);
         }
      }

      private static void AreTestsFailed(BuildResult buildResult, Node node)
      {
         var areTestsRunning = string.Format("{0}", node.status);
         if (areTestsRunning.Equals("error", StringComparison.InvariantCultureIgnoreCase) || node.errors > 0)
         {
            buildResult.TestsFailed = true;
         }
      }

      private void AreTestsRunning(BuildResult buildResult, Node node)
      {
         var text = string.Format("{0}", node.text);
         if (!validTestTexts.Any(x => x.Equals(text, StringComparison.InvariantCultureIgnoreCase)))
         {
            return;
         }

         var areTestsRunning = string.Format("{0}", node.status);
         if (areTestsRunning.Equals("inprogress", StringComparison.InvariantCultureIgnoreCase))
         {
            buildResult.TestsRunning = true;
         }

         if (areTestsRunning.Equals(string.Empty, StringComparison.InvariantCultureIgnoreCase))
         {
            buildResult.TestsFinished = true;
         }
      }
   }
}


text:
namespace Microsoft.Kubernetes
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Operations operations.
    /// </summary>
    public partial interface IOperations
    {
        /// <summary>
        /// Lists all of the available API operations for Connected Cluster
        /// resource.
        /// </summary>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<Operation>>> GetWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Lists all of the available API operations for Connected Cluster
        /// resource.
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<Operation>>> GetNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
import imdb
import time
import re
import csv

genres = ['Action', 'Adventure', 'Animation', 'Biography', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy', 'Film-Noir', 'History', 'Horror', 'Music', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Sport', 'Thriller', 'War', 'Western', 'Short']

ratings = ['USA:G', 'USA:PG', 'USA:PG-13', 'USA:R', 'USA:NC-17']

def genres2Vec(movie_genres):
	global genres
	genreVec = [None]*len(genres)

	for item in movie_genres:
		index = genres.index(item)
		genreVec[index] = 1

	for i, thing in enumerate(genreVec):
		if thing is None:
			genreVec[i] = 0

	return genreVec

def cert2Vec(certs):
	global ratings

	mv_rating = [None] * len(ratings)

	for cert in certs:
		for i, rate in enumerate(ratings):
			if rate in cert:
				mv_rating[i] = 1

	for i, thing in enumerate(mv_rating):
		if thing is None:
			mv_rating[i] = 0

	print mv_rating
	return mv_rating

def getBudget(bud_str):
	bud_chars = re.findall('[0-9]', bud_str[0])

	bud_str = ''.join(bud_chars)

	return int(bud_str)

ia = imdb.IMDb()
X = []
mv_genreVec = []
mv_ratingVec = []
mv_bud = 0
for index in range(32138, 32140):
	start = time.time()
	mv = ia.get_movie(index)
	print mv
	ia.update(mv)
	ia.update(mv, 'business')
	try:
		mv_genres = mv['genre']
		mv_certs = [s for s in mv['certificates'] if 'USA' in s]
		mv_bud = mv['business']['budget']
		mv_rating = mv['rating']

		mv_genreVec = genres2Vec(mv_genres)
		mv_ratingVec = cert2Vec(mv_certs)
		mv_bud = getBudget(mv_bud)

	except Exception as e:
		print "Error: %s, skipping..." %  (e.message)
		continue

	mv_overview = [index] + [mv_bud] + mv_genreVec + mv_ratingVec

	X.append(mv_overview)
	print mv_overview
	end = time.time()
	print str(end - start)

with open('movie_data_points.csv', 'w') as f:
	pointswriter = csv.writer(f, quoting=csv.QUOTE_NONE)
	pointswriter.writerows(X)


text:
package com.siyeh.ipp.concatenation;

import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.siyeh.ipp.base.PsiElementPredicate;
import consulo.java.module.util.JavaClassNames;

class StringConcatPredicate implements PsiElementPredicate {

  public boolean satisfiedBy(PsiElement element) {
    if (element instanceof PsiWhiteSpace) {
      element = element.getPrevSibling();
    }
    if (!(element instanceof PsiJavaToken)) {
      return false;
    }
    final PsiJavaToken token = (PsiJavaToken)element;
    final IElementType tokenType = token.getTokenType();
    if (!tokenType.equals(JavaTokenType.PLUS)) {
      return false;
    }
    final PsiElement parent = element.getParent();
    if (!(parent instanceof PsiPolyadicExpression)) {
      return false;
    }
    final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent;
    final PsiType type = polyadicExpression.getType();
    if (type == null || !type.equalsToText(JavaClassNames.JAVA_LANG_STRING)) {
      return false;
    }
    final PsiExpression[] operands = polyadicExpression.getOperands();
    PsiExpression previous = null;
    boolean stringTypeSeen = false;
    for (int i = 0, length = operands.length; i < length; i++) {
      final PsiExpression operand = operands[i];
      final PsiType operandType = operand.getType();
      final PsiJavaToken currentToken = polyadicExpression.getTokenBeforeOperand(operand);
      if (token == currentToken) {
        if (!(previous instanceof PsiLiteralExpression) || !(operand instanceof PsiLiteralExpression)) {
          return false;
        }
        return stringTypeSeen || (i == 1 && operandType != null && operandType.equalsToText(JavaClassNames.JAVA_LANG_STRING));
      }
      previous = operand;
      if (!stringTypeSeen) {
        stringTypeSeen = operandType != null && operandType.equalsToText(JavaClassNames.JAVA_LANG_STRING);
      }
    }
    return false;
  }
}


text:
import * as throttle from 'lodash/throttle'
import * as helper from '../../helper'
import { ErrorResponse } from '../../../http'
import redraw from '../../../utils/redraw'
import { handleXhrError } from '../../../utils'
import * as xhr from './../inboxXhr'
import { ComposeResponse } from '../interfaces'
import router from '../../../router'
import * as stream from 'mithril/stream'

interface SendError {
  username: Array<string>
  subject: Array<string>
  text: Array<string>
}

interface SendErrorResponse extends ErrorResponse {
  body: SendError
}

export interface IComposeCtrl {
  id: Mithril.Stream<string>
  errors: Mithril.Stream<SendError>
  send: (form: HTMLFormElement) => void
  onInput: (e: Event) => void
  autocompleteResults: Mithril.Stream<Array<string>>
}

export default function ComposeCtrl(userId: string): IComposeCtrl {

  const id = stream<string>(userId)
  const errors = stream<SendError>()
  const autocompleteResults = stream<string[]>([])

  function send(form: HTMLFormElement) {
    const recipient = (form[0] as HTMLInputElement).value
    const subject = (form[1] as HTMLInputElement).value
    const body = (form[2] as HTMLTextAreaElement).value
    xhr.newThread(recipient, subject, body)
    .then((data: ComposeResponse) => {
      if (data.ok) {
        router.set('/inbox/' + data.id)
      }
      else {
        redraw()
      }
    })
    .catch(handleSendError)
  }

  window.addEventListener('native.keyboardhide', helper.onKeyboardHide)
  window.addEventListener('native.keyboardshow', helper.onKeyboardShow)

  function handleSendError(error: SendErrorResponse) {
    if (error.body && (error.body.username || error.body.subject || error.body.text)) {
      errors(error.body)
      redraw()
    }
    else {
      handleXhrError(error)
    }
  }

  return {
    id,
    errors,
    send,
    onInput: throttle((e: Event) => {
      const term = (e.target as HTMLInputElement).value.trim()
      if (term.length >= 3) {
        xhr.autocomplete(term).then(data => {
          autocompleteResults(data)
          redraw()
        })
      }
      else {
        autocompleteResults([])
        redraw()
      }
    }, 250),
    autocompleteResults
  }
}


text:
#define _FILE_OFFSET_BITS 64

#include "memorymappedfile.h"

#include <sys/stat.h>
#include <sys/types.h>
#include <memory.h>

#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>

typedef struct BitableMemoryMappedFileHandle
{

    int fileDescriptor;

} BitableMemoryMappedFileHandle;

static void cleanup_mmf( BitableMemoryMappedFile* memoryMappedFile )
{
    if ( memoryMappedFile->address != NULL && memoryMappedFile->address != MAP_FAILED )
    {
        munmap( memoryMappedFile->address, memoryMappedFile->size );
    }

    memoryMappedFile->address = NULL;

    if ( memoryMappedFile->handle != NULL )
    {
        if ( memoryMappedFile->handle->fileDescriptor != -1 )
        {
            close( memoryMappedFile->handle->fileDescriptor );
            memoryMappedFile->handle->fileDescriptor = -1;
        }

        free( memoryMappedFile->handle );
        memoryMappedFile->handle = NULL;
    }
}

BitableResult bitable_mmf_open( BitableMemoryMappedFile* memoryMappedFile, const char* path, BitableReadOpenFlags openFlags )
{
    memset( memoryMappedFile, 0, sizeof( BitableMemoryMappedFile ) );

    memoryMappedFile->handle = malloc( sizeof( BitableMemoryMappedFileHandle ) );

    {
        struct stat fileStats;
        int advice = POSIX_FADV_NORMAL;

        memoryMappedFile->handle->fileDescriptor = open( path, O_RDONLY );

        if ( memoryMappedFile->handle->fileDescriptor == -1 )
        {
            cleanup_mmf( memoryMappedFile );
            return BR_FILE_OPEN_FAILED;
        }

        switch ( openFlags )
        {
        case BRO_NONE:

            advice = POSIX_FADV_NORMAL;
            break;

        case BRO_RANDOM:

            advice = POSIX_FADV_RANDOM;
            break;

        case BRO_SEQUENTIAL:

            advice = POSIX_FADV_SEQUENTIAL;
            break;

        }

        if ( posix_fadvise( memoryMappedFile->handle->fileDescriptor, 0, 0, advice ) != 0 )
        {
            cleanup_mmf( memoryMappedFile );
            return BR_FILE_OPERATION_FAILED;
        }

        if ( fstat( memoryMappedFile->handle->fileDescriptor, &fileStats ) == -1 )
        {
            cleanup_mmf( memoryMappedFile );
            return BR_FILE_OPERATION_FAILED;
        }

        if ( fileStats.st_size > ((size_t)-1) )
        {
            cleanup_mmf( memoryMappedFile );
            return BR_FILE_TOO_LARGE;
        }

        memoryMappedFile->size    = (size_t)fileStats.st_size;
        memoryMappedFile->address = mmap( NULL, memoryMappedFile->size, PROT_READ, MAP_SHARED, memoryMappedFile->handle->fileDescriptor, 0 );

        if ( memoryMappedFile->address == MAP_FAILED )
        {
            cleanup_mmf( memoryMappedFile );
            return BR_FILE_OPERATION_FAILED;
        }
    }

    return BR_SUCCESS;
}

BitableResult bitable_mmf_close( BitableMemoryMappedFile* memoryMappedFile )
{
    cleanup_mmf( memoryMappedFile );
    return BR_SUCCESS;
}


text:
var chokidar = require('chokidar');
var http = require('http');
var fs = require('fs-extra')
var winston = require('winston');
var path = require('path');

var utils = require('./utils');
var winston = require('./utils').winston;

module.exports = {
  start: function(serverAddress, serverPort, sharedDir, maxRetries) {

    maxRetries = maxRetries || 1;

    // We don't really need filesystem events.
    // We just need to state be able to produce the same state as on monitored direcotry.
    // Unlink doesn't really care if it is directory or file.
    // Changed doesnt really care if the file is changed or just craeted.
    var generateChange = function(file, retry) {
      var localFile = path.join(sharedDir, file);
      var sharedFile = file;
      fs.stat(localFile, function(err, stats) {
        // Just send event directly to the remote machine for missing files
        if (err && err.code === 'ENOENT') {
          sendChange('unlink', sharedFile, retry, null);
          return;
        }
        if (err) {
          winston.error('unexpected error occured ' + JSON.stringify(err));
          return;
        }

        winston.debug('stats for ' + file + ' are ' + JSON.stringify(stats));
        if(stats.isFile()) {
          utils.calcHash(localFile, function(error, sha1) {
            sendChange('copy', sharedFile, retry, sha1);
          });
        } else {
          sendChange('addDir', sharedFile, retry, null);
        }
      })
    }

    var sendChange = function(event, file, retry, checkSum) {
      winston.debug('sending ' + event + ' for ' + file + ' retried ' + retry);
      if (retry > maxRetries) {
        winston.error('unabled to syncronize ' + file + ' retried ' + retry + ' times.');
        return;
      }
      var options = {
        host: serverAddress,
        port: serverPort,
        path: '/',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        }
      };

      var req = http.request(options, function(res) {
        var data="";
        res.on('data', function (chunk) {
          data+=chunk;
        });

        res.on('end', function () {
          if (JSON.parse(data)["code"] === utils.ERROR_CODE) {
            winston.warn('error occured while syncing ' + file + ' ' + data);
            generateChange(file, retry + 1);
          } else {
            winston.debug('successful response received ' + data);
          }
        });
      });

      postData = JSON.stringify({
        event: event,
        file: file,
        checkSum: checkSum,
      });

      req.write(postData);

      req.end();
    };

    winston.info('watcher started');
    chokidar.watch(
      path.normalize(sharedDir),
      { ignored: /[\/\\]\./, ignoreInitial: true}
    ).on('all', function(event, file) {
      var sharedFile=file.replace(sharedDir, '');
      // replace all path.sep with / becuase in *nix file system \
      // and cause errors we have cross platform syncronization from windows to *nix
      // all commands thats should normalize the path before using it
      sharedFile = sharedFile.replace(path.sep, '/');
      generateChange(sharedFile, 0);
    }).on('error', function(err) {
      winston.error('unexpected error occured ' + JSON.stringify(err));
    });
  }
}


text:
using System.Collections.Generic;
using Tup.Cobar4Net.Parser.Visitor;

namespace Tup.Cobar4Net.Parser.Ast.Expression.Misc
{
    /// <author>
    ///     QIU Shuo
    /// </author>
    public class InExpressionList : AbstractExpression
    {
        private IList<IExpression> _exprList;

        private IList<IExpression> _replaceList;

        public InExpressionList(IList<IExpression> list)
        {
            if (list == null || list.Count == 0)
            {
                _exprList = new List<IExpression>(0);
            }
            else
            {
                if (list is List<IExpression>)
                {
                    _exprList = list;
                }
                else
                {
                    _exprList = new List<IExpression>(list);
                }
            }
        }

        /// <value>never null</value>
        public virtual IList<IExpression> ExprList
        {
            get { return _exprList; }
        }

        public override int Precedence
        {
            get { return ExpressionConstants.PrecedencePrimary; }
        }

        public virtual IList<IExpression> ReplaceExpr
        {
            set { _replaceList = value; }
        }

        protected override object EvaluationInternal(IDictionary<object, object> parameters)
        {
            return ExpressionConstants.Unevaluatable;
        }

        public virtual void ClearReplaceExpr()
        {
            _replaceList = null;
        }

        public override void Accept(ISqlAstVisitor visitor)
        {
            if (_replaceList == null)
            {
                visitor.Visit(this);
            }
            else
            {
                var temp = _exprList;
                _exprList = _replaceList;
                visitor.Visit(this);
                _exprList = temp;
            }
        }
    }
}


text:
- Function `NewWorkflowClient` parameter(s) have been changed from `(string, *string, azcore.TokenCredential, *arm.ClientOptions)` to `(string, azcore.TokenCredential, *arm.ClientOptions)`
- Function `NewDeveloperHubServiceClient` parameter(s) have been changed from `(string, string, string, azcore.TokenCredential, *arm.ClientOptions)` to `(string, azcore.TokenCredential, *arm.ClientOptions)`
- Function `*DeveloperHubServiceClient.GitHubOAuthCallback` parameter(s) have been changed from `(context.Context, string, *DeveloperHubServiceClientGitHubOAuthCallbackOptions)` to `(context.Context, string, string, string, *DeveloperHubServiceClientGitHubOAuthCallbackOptions)`

### Features Added

- New field `ManagedClusterResource` in struct `WorkflowClientListByResourceGroupOptions`

## 0.1.1 (2022-10-12)
### Other Changes
- Loosen Go version requirement.

## 0.1.0 (2022-09-24)

The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/devhub/armdevhub` is using our [next generation design principles](https://azure.github.io/azure-sdk/general_introduction.html) since version 0.1.0, which contains breaking changes.

To migrate the existing applications to the latest version, please refer to [Migration Guide](https://aka.ms/azsdk/go/mgmt/migration).

To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/go/mgmt).


text:
@interface XMLElement:NSObject {
   NSString			*tagName;
   NSMutableDictionary		*attributes;
   NSMutableArray		*children;
    XMLText * textContent;
}
@property (nonatomic, retain) NSString  *tagName;
@property (nonatomic, retain) NSMutableDictionary  *attributes;
@property (nonatomic, retain) NSMutableArray  *children;
@property (nonatomic)XMLText * textContent;

@end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.azureadexternalidentities.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The billing configuration for the tenant. */
@Fluent
public final class B2CTenantResourcePropertiesBillingConfig {
    /*
     * The type of billing. Will be MAU for all new customers. If 'Auths', it
     * can be updated to 'MAU'. Cannot be changed if value is 'MAU'. Learn more
     * about Azure AD B2C billing at
     * [aka.ms/b2cBilling](https://aka.ms/b2cbilling).
     */
    @JsonProperty(value = "billingType")
    private BillingType billingType;

    /*
     * The data from which the billing type took effect
     */
    @JsonProperty(value = "effectiveStartDateUtc", access = JsonProperty.Access.WRITE_ONLY)
    private String effectiveStartDateUtc;

    /**
     * Get the billingType property: The type of billing. Will be MAU for all new customers. If 'Auths', it can be
     * updated to 'MAU'. Cannot be changed if value is 'MAU'. Learn more about Azure AD B2C billing at
     * [aka.ms/b2cBilling](https://aka.ms/b2cbilling).
     *
     * @return the billingType value.
     */
    public BillingType billingType() {
        return this.billingType;
    }

    /**
     * Set the billingType property: The type of billing. Will be MAU for all new customers. If 'Auths', it can be
     * updated to 'MAU'. Cannot be changed if value is 'MAU'. Learn more about Azure AD B2C billing at
     * [aka.ms/b2cBilling](https://aka.ms/b2cbilling).
     *
     * @param billingType the billingType value to set.
     * @return the B2CTenantResourcePropertiesBillingConfig object itself.
     */
    public B2CTenantResourcePropertiesBillingConfig withBillingType(BillingType billingType) {
        this.billingType = billingType;
        return this;
    }

    /**
     * Get the effectiveStartDateUtc property: The data from which the billing type took effect.
     *
     * @return the effectiveStartDateUtc value.
     */
    public String effectiveStartDateUtc() {
        return this.effectiveStartDateUtc;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
Changelog                         {#changelog}
===============

Here's a list summarizing some of the key undergoing changes to our library
from earlier versions:

### v0.3.2

 * Introduced RPM package generation feature from cmake via cpack
 * Performed a thorough documentation review and merged resulting changes,
 includes last remaining images and grouping sensors by kits
 * Added support for Sparkfun Sensor Blocks (OLED & IMU)
 * Fully reworked API for at42qt1070, mpu9150 and lcd classes, while
 maintaining backwards compatibility for existing lcd displays.
 * Extended doxygen tags for better integration with automated documentation
 generators
 * New sensors: rgbringcoder, hp20x, pn532, sainsmartks, lsm9ds0, eboled

### v0.3.1

 * Updated index pages for API documentation and cross-linked them
 * More images were added for Grove, Adafruit and Sparkfun sensors along with
 licensing information
 * Applied a set of patches to improve code robustness
 * Added support for Grove NFC Tag sensor
 * Fixed several typos in library and sensor names
 * New sensor: m24lr64e

### v0.3.0

 * Provided automated, updated and comprehensive sensor API documentation for
 C++, Python and JavaScript
 * Edited sensor names, library descriptions and doxygen tags for consistency
 * Fixed the TH02 sensor driver and made major improvements to i2clcd driver
 * Added new and updated images for numerous new and existing sensors
 * Started this changelog
 * New sensors: sx6119, si114x, maxsonarez, hm11, ht9170, h3lis331dl, ad8232,
 grovescam

### v0.2.0

 * Passed 100 supported sensor drivers
 * Updated header files with new doxygen tags for improved API documentation
 generation
 * Added python examples for sensors
 * Fixed the buzzer and servo drivers for the Intel Edison
 * Renamed bmp and gp2y sensor classes to be more generic
 * Completely revamped implementation for tm1637
 * New sensors: mma7660, cjq4435, adxl335, hmtrp, nunchuck, otp538u, l298,
 groveelectromagnet, grovecollision, adis16448, at42qt1070, grovemd, ina132,
 grovegsr, groveo2, groveemg, pca9685, pca9685ss, adafruitms1438, hx711, flex,
 groveeldriver, mhz16, apds9002, waterlevel, zfm20, uln200xa, grovewfs, isd1820

### v0.1.9

 * Passed 50 supported sensor drivers
 * Starter Kit and Additional Roadshow and Hackaton sensors added
 * Several examples and documentation updates submitted
 * Wrote new proper SWIG typemaps for arrays
 * Fixed the i2clcd write function, improved several other sensors
 * New sensors: rpr220, rotaryencoder, biss0001, rfr359f, grovespeaker, mq303a,
 ppd42ns, wt5001, yg1006, ublox6, mpr121, groveloudness, guvas12d, grovewater,
 grovevdiv, grovelinefinder, ta12200, groveehr, grovemoisture, gp2y0a, a110x,
 ds1307, adc121c021, enc03r, ttp223, itg3200, am2315, tp401, ldt0028, htu21d,
 mpl3115a2, lsm303, joystick12, tsl2561, groverotary, groveslider, adxl345,
 grovebutton, lol, groverelay

### v0.1.8

 * Added MQ series gas sensors and a few others
 * Generated Doxygen layout file to improve API look and feel
 * Several sensor documentation updates

### v0.1.7

 * Fixed SWIG node build issues
 * Added lpd8806 digital led strip

### v0.1.6

 * Fixed SWIG python builds
 * Extended i2clcd devices with new functions
 * Made SWIG interface improvements and added extra types
 * Added nrf8001 BLE support
 * Few other sensor additions and fixes

### v0.1.5

 * New drivers for microphone and mpu9150
 * Added generic driver for stepper motors
 * Updated all code to use MRAA and version dependency

### v0.1.4

 * Added new bmp/gy pressure sensor and updated servo
 * Started UPM documentation and related pages
 * Updated MRAA dependencies

### v0.1.3

 * Updated SWIG support for some sensors
 * New sensor support for mma7455 accelerometer

### v0.1.2

 * Several new sensors added
 * Documentation fixes
 * IPK generation

### v0.1.1

 * Updated MRAA dependency

### v0.1.0

 * Initial release with some basic grove sensors and hmc5883
 * Doxygen and SWIG support implemented


text:
NeuroSky delivers fully integrated, single chip EEG biosensors. NeuroSky enables its partners and developers to bring their brainwave application ideas to market with the shortest amount of time, and lowest end consumer price.

This package contains the Gobot adaptor and driver for the [Neurosky Mindwave Mobile EEG](http://store.neurosky.com/products/mindwave-mobile).

## How to Install
Installing Gobot with Neurosky support is pretty easy.

```
go get -d -u github.com/hybridgroup/gobot/... && go install github.com/hybridgroup/gobot/platforms/neurosky
```

## How To Connect

### OSX

In order to allow Gobot running on your Mac to access the Mindwave, go to "Bluetooth > Open Bluetooth Preferences > Sharing Setup" and make sure that "Bluetooth Sharing" is checked.

Now you must pair with the Mindwave. Open System Preferences > Bluetooth. Now with the Bluetooth devices windows open, hold the On/Pair button on the Mindwave towards the On/Pair text until you see "Mindwave" pop up as available devices. Pair with that device. Once paired your Mindwave will be accessable through the serial device similarly named as `/dev/tty.MindWaveMobile-DevA`

### Ubuntu

Connecting to the Mindwave from Ubuntu or any other Linux-based OS can be done entirely from the command line using [Gort](https://github.com/hybridgroup/gort) CLI commands. Here are the steps.

Find the address of the Mindwave, by using:
```
gort scan bluetooth
```

Pair to Mindwave using this command (substituting the actual address of your Mindwave):
```
gort bluetooth pair <address>
```

Connect to the Mindwave using this command (substituting the actual address of your Mindwave):
```
gort bluetooth connect <address>
```

### Windows

You should be able to pair your Mindwave using your normal system tray applet for Bluetooth, and then connect to the COM port that is bound to the device, such as `COM3`.

## How to Use

This small program lets you connect the Neurosky an load data.

```go
package main

import (
	"fmt"

	"github.com/hybridgroup/gobot"
	"github.com/hybridgroup/gobot/platforms/neurosky"
)

func main() {
	gbot := gobot.NewGobot()

	adaptor := neurosky.NewNeuroskyAdaptor("neurosky", "/dev/rfcomm0")
	neuro := neurosky.NewNeuroskyDriver(adaptor, "neuro")

	work := func() {
		gobot.On(neuro.Event("extended"), func(data interface{}) {
			fmt.Println("Extended", data)
		})
		gobot.On(neuro.Event("signal"), func(data interface{}) {
			fmt.Println("Signal", data)
		})
		gobot.On(neuro.Event("attention"), func(data interface{}) {
			fmt.Println("Attention", data)
		})
		gobot.On(neuro.Event("meditation"), func(data interface{}) {
			fmt.Println("Meditation", data)
		})
		gobot.On(neuro.Event("blink"), func(data interface{}) {
			fmt.Println("Blink", data)
		})
		gobot.On(neuro.Event("wave"), func(data interface{}) {
			fmt.Println("Wave", data)
		})
		gobot.On(neuro.Event("eeg"), func(data interface{}) {
			eeg := data.(neurosky.EEG)
			fmt.Println("Delta", eeg.Delta)
			fmt.Println("Theta", eeg.Theta)
			fmt.Println("LoAlpha", eeg.LoAlpha)
			fmt.Println("HiAlpha", eeg.HiAlpha)
			fmt.Println("LoBeta", eeg.LoBeta)
			fmt.Println("HiBeta", eeg.HiBeta)
			fmt.Println("LoGamma", eeg.LoGamma)
			fmt.Println("MidGamma", eeg.MidGamma)
			fmt.Println("\n")
		})
	}

	robot := gobot.NewRobot("brainBot",
		[]gobot.Connection{adaptor},
		[]gobot.Device{neuro},
		work,
	)

	gbot.AddRobot(robot)
	gbot.Start()
}
```


text:
<?php

declare(strict_types=1);

namespace App;

final class UserNotFound extends \RuntimeException
{
}


text:
package com.example.demo.itemdecoration2.factories;

import android.support.annotation.IntDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Factory used to specify a custom logic to set visibility for each divider.
 *

 * You can add a custom {@link VisibilityFactory} in your {@link com.fondesa.recyclerviewdivider.RecyclerViewDivider.Builder} using
 * {@link com.fondesa.recyclerviewdivider.RecyclerViewDivider.Builder#visibilityFactory(VisibilityFactory)} method
 */
@SuppressWarnings("WeakerAccess")
public abstract class VisibilityFactory {

    public static final int SHOW_NONE = 0;
    public static final int SHOW_ITEMS_ONLY = 1;
    public static final int SHOW_GROUP_ONLY = 2;
    public static final int SHOW_ALL = 3;

    /**
     * Source annotation used to define different visibility types.
     *

     *
{@link #SHOW_NONE}: every divider won't be shown

     *
{@link #SHOW_ITEMS_ONLY}: divider will be shown only between items.
     * When the spanCount is equal to 1 (e.g. LinearLayoutManager), this property has the same effect of {@link #SHOW_NONE}

     *
{@link #SHOW_GROUP_ONLY}: divider will be shown only between groups.
     * When the spanCount is equal to 1 (e.g. LinearLayoutManager), this property has the same effect of {@link #SHOW_ALL}

     *
{@link #SHOW_ALL}: every divider will be shown

     *

     */
    @IntDef({SHOW_NONE, SHOW_ITEMS_ONLY, SHOW_GROUP_ONLY, SHOW_ALL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Show {
        // empty annotation body
    }

    private static VisibilityFactory defaultFactory;

    /**
     * Creates a singleton instance of a default {@link VisibilityFactory} to avoid multiple instance of the same class
     *
     * @return factory with default values
     */
    public static synchronized VisibilityFactory getDefault() {
        if (defaultFactory == null) {
            defaultFactory = new Default();
        }
        return defaultFactory;
    }

    /**
     * @return a new {@link VisibilityFactory} that will now show last divider.
     */
    public static VisibilityFactory getLastItemInvisibleFactory() {
        return new LastItemInvisible();
    }

    /**
     * Defines a visibility for each group of divider
     *
     * @param groupCount number of groups in a list.
     *                   The groupCount value is equal to the list size when the span count is 1 (e.g. LinearLayoutManager).
     * @param groupIndex position of the group. The value is between 0 and groupCount - 1.
     *                   The groupIndex is equal to the item position when the span count is 1 (e.g. LinearLayoutManager).
     * @return true if the divider will be visible, false instead
     */
    public abstract
    @Show
    int displayDividerForItem(int groupCount, int groupIndex);

    /**
     * Default instance of a {@link VisibilityFactory}
     */
    private static class Default extends VisibilityFactory {
        Default() {
            // empty constructor
        }

        @Override
        public
        @Show
        int displayDividerForItem(int groupCount, int groupIndex) {
            return SHOW_ALL;
        }
    }

    /**
     * Convenient instance to hide the last divider.
     *

     * Warning: when the spanCount is major than 1, only the divider after the last group will be hidden. This factory will not affect items' dividers.
     */
    private static class LastItemInvisible extends VisibilityFactory {
        LastItemInvisible() {
            // empty constructor
        }

        @Override
        public
        @Show
        int displayDividerForItem(int groupCount, int groupIndex) {
            return groupIndex == groupCount - 1 ? SHOW_ITEMS_ONLY : SHOW_ALL;
        }
    }
}


text:
#ifndef __CONFIG_H
#define __CONFIG_H

#include <linux/sizes.h>
#include "tegra20-common.h"

/* High-level configuration options */
#define CONFIG_TEGRA_BOARD_STRING	"NVIDIA Harmony"

/* Board-specific serial config */
#define CONFIG_TEGRA_ENABLE_UARTD

/* UARTD: keyboard satellite board UART, default */
#define CONFIG_SYS_NS16550_COM1		NV_PA_APB_UARTD_BASE
#ifdef CONFIG_TEGRA_ENABLE_UARTA
/* UARTA: debug board UART */
#define CONFIG_SYS_NS16550_COM2		NV_PA_APB_UARTA_BASE
#endif

#define CONFIG_MACH_TYPE		MACH_TYPE_HARMONY

/* SD/MMC */
#define CONFIG_MMC
#define CONFIG_GENERIC_MMC
#define CONFIG_TEGRA_MMC
#define CONFIG_CMD_MMC

/* NAND support */
#define CONFIG_CMD_NAND
#define CONFIG_TEGRA_NAND
#define CONFIG_SYS_MAX_NAND_DEVICE	1

/* Environment in NAND (which is 512M), aligned to start of last sector */
#define CONFIG_ENV_IS_IN_NAND
#define CONFIG_ENV_OFFSET	(SZ_512M - SZ_128K) /* 128K sector size */

/* USB Host support */
#define CONFIG_USB_MAX_CONTROLLER_COUNT 3
#define CONFIG_USB_EHCI
#define CONFIG_USB_EHCI_TEGRA
#define CONFIG_USB_ULPI
#define CONFIG_USB_ULPI_VIEWPORT
#define CONFIG_USB_STORAGE
#define CONFIG_CMD_USB

/* USB networking support */
#define CONFIG_USB_HOST_ETHER
#define CONFIG_USB_ETHER_ASIX
#define CONFIG_USB_ETHER_MCS7830
#define CONFIG_USB_ETHER_SMSC95XX

/* General networking support */
#define CONFIG_CMD_DHCP

/* LCD support */
#define CONFIG_LCD
#define CONFIG_PWM_TEGRA
#define CONFIG_VIDEO_TEGRA
#define LCD_BPP				LCD_COLOR16
#define CONFIG_SYS_WHITE_ON_BLACK
#define CONFIG_CONSOLE_SCROLL_LINES	10

#include "tegra-common-post.h"

#endif /* __CONFIG_H */


text:
package io.github.robolib.modes;

/**
 * The Enum GameMode.
 *
 * @author noriah <vix@noriah.dev>
 * @since 0.1.0
 */
public enum GameMode {

    /** The none. */
    NONE("Init", "I"),

    /** The disabled. */
    DISABLED("Disabled", "D"),

    /** The test. */
    TEST("Test", "T"),

    /** The auton. */
    AUTON("Autonomous", "A"),

    /** The teleop. */
    TELEOP("Teleop", "U");

    /** The m_name. */
    private final String m_name;

    /** The m_abbr. */
    private final String m_abbr;

    public final int value;

    /**
     * Instantiates a new game mode.
     *
     * @param modeName the mode name
     * @param abbr     the abbr
     */
    private GameMode(String modeName, String abbr) {
        m_name = modeName;
        m_abbr = abbr;
        value = ordinal();
    }

    /**
     * Get the name of the GameMode.
     *
     * @return the GameMode Name
     */
    public String getName() {
        return m_name;
    }

    /**
     * Get the abbreviation of the GameMode.
     *
     * @return the GameMode abbreviation
     */
    public String getAbbreviation() {
        return m_abbr;
    }
}


text:
package org.apache.stratos.common.partition;

import org.apache.stratos.common.Properties;
import org.apache.stratos.common.Property;

import java.io.Serializable;

/**
 * This is keep the partition information passed in deployment policy
 */
public class PartitionRef implements Serializable {

    private static final long serialVersionUID = 3725971287992010720L;

    private static final String KUBERNETES_CLUSTER = "cluster";

    /**
     * provider should match with an IaasProvider type.
     */
    private String uuid;
	private String id;
    private String description;
    private int partitionMax;
    private Properties properties = new Properties();
	private int tenantId;
    /**
     * Gets the value of the id property.
     *
     * @return possible object is
     * {@link String }
     */
    public String getUuid() {
        return uuid;
    }

    /**
     * Sets the value of the id property.
     *
     * @param uuid allowed object is
     *           {@link String }
     */
    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    /**
     * Gets the value of the description property.
     *
     * @return possible object is
     * {@link String }
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the value of the description property.
     *
     * @param description allowed object is
     *                    {@link String }
     */
    public void setDescription(String description) {
        this.description = description;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public String getKubernetesClusterId() {
        Property property = properties.getProperty(KUBERNETES_CLUSTER);
        if (property != null) {
            return property.getValue();
        }
        return null;
    }

    @Override
    public String toString() {
        return "Partition [id=" + uuid + ", description=" + description + ", properties=" + properties + "]";
    }

    public boolean equals(Object obj) {
        if (obj != null && obj instanceof PartitionRef) {
            return this.uuid.equals(((PartitionRef) obj).getUuid());
        }
        return false;

    }

    @Override
    public int hashCode() {
        return this.uuid.hashCode();
    }

    public int getPartitionMax() {
        return partitionMax;
    }

    public void setPartitionMax(int partitionMax) {
        this.partitionMax = partitionMax;
    }

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public int getTenantId() {
		return tenantId;
	}

	public void setTenantId(int tenantId) {
		this.tenantId = tenantId;
	}
}


text:
MIME-Version: 1.0
Server: CERN/3.0
Date: Monday, 16-Dec-96 22:01:28 GMT
Content-Type: text/html
Content-Length: 1316
Last-Modified: Thursday, 19-Oct-95 17:27:22 GMT

<HTML>
<TITLE> CS415 Groups </TITLE>

<H1> CS415 Groups </H1>
<UL>
<LI> Group 1: Eric Brandwine, George Hoffman, Kyle Rose.
<LI> Group 2: Donna Viggiano, Nikola Valerjev, Chris Zaccarelli.
<LI> Group 3: Gregg Baeckler, Aaron Stump, Gerry Toll.
<LI> Group 4: Nisheet Ranjan, Jay Krell, Gang Gong Moy .
<LI> Group 5: Justin Voskuhl, Yu-Lucy Wu, Mishaal Almashan.
<LI> Group 6: Ali Muhtaroglu, Maxim Turkenich, *******.
<LI> Group 7: Laurent Kirsch, Julian R. Diaz-Hurtado, *******.
<LI> Group 8: Min Huang, Joseluis Fernandez, Marcelo Blinder.
<LI> Group 9: Xun Wilson Huang,  Avinash Gupta, Kartik Kapadia.
<LI> Group 10: Seena Cherangara, Janeen Reich, Sukhpal Sanghera.
<LI> Group 11: Indira Vidyaprakash, Prashant Inamti, Shilpa Agarwal.
<LI> Group 12: Walker White, David Stephenson, Javier Pena.
<LI> Group 13: Francis Garcia, Oumung Mehrotra, Richard Vuduc.
<LI> Group 14: Janwun Lee, Kuen-Heng Lai, Wen-Hung Kao.
<LI> Group 15: Hsin Liu, I-Chin Chen, Jiun-hau Lin.
<LI> Group 16: Arshad Tayyeb, Todd Wheeler, William Pugh.
<LI> Group 17: Amit Ahuja, Mikio Sakurai, Nobuhiko Mukai.
<LI> Group 18: Bill Lewis, Adam Mayer, Chris Vaill.
<LI> Group 19: San-U Wong, Ivan Tam,   Kit-Yan Lee.
<LI> Group 20: Gleb Morein, Alex Zhukovsky, Ilya German.
<LI> Group 21: Jing Li, Markus Moberg, Vivek Kolla.
</UL>
</HTML>


text:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Router, Route, browserHistory } from 'react-router';
require('./sass/main.scss');

ReactDOM.render(
	<Router history={browserHistory}>
		<Route path="/" component={App}/>
	</Router>
	, document.getElementById('root'));


text:
A simple router for the Alexa `alexa-app` library.

[![NPM](https://img.shields.io/npm/v/alexa-app-router.svg)](https://www.npmjs.com/package/alexa-app-router/)
[![Build Status](https://travis-ci.org/alexa-js/alexa-app-router.svg?branch=master)](https://travis-ci.org/alexa-js/alexa-app-router)

# Table of Contents
* [Quick Start](#quick-start)
  * [Installation](#installation)
  * [Registering the Router](#registering-the-router)
  * [Routes](#routes)
  * [Intents](#intents)
  * [Config](#config)
* [Breaking Changes](#breaking-changes)
* [Gotchas and Important Notes](#gotchas-and-important-notes)
* [Going to a Route](#going-to-a-route)
* [Route Parameters](#route-parameters)
* [Backwards Compatibility](#backwards-compatibility)

## Quick Start
Read the [alexa-app](https://github.com/alexa-js/alexa-app) documentation before using this add-on utility.

Sample app with code usage available in the [alexa-adopt-a-pet](https://github.com/nickcoury/alexa-adopt-a-pet) project.

### Installation
```
npm install alexa-app alexa-app-router --save
```

### Registering the Router
```
var alexa = require('alexa-app');
var router = require('alexa-app-router');

var app = new alexa.app('app-name');

var config = {...};
var intents = {...};
var routes = {...};

router.addRouter(app, config, intents, routes);
```

## Routes
Ul-style routing is strongly recommended. Special processing is done with route variables (`{id}`) and query parameters (`?limit=10&offset=5`).
```
var routes = {
    '/': launchHandler,
    '/exit': exitHandler,
    '/help': helpHandler,
    '/menu': menuHandler,
    '/pets': findPetHandler,
    '/pets/{petId}': petDetailsHandler,
    '/shelters': findShelterHandler,
};
function launchHandler(request, response) {...}
...(more handler functions)
```

### Intents
`alexa-app-router` uses a special shorthand for registering intents, normal intent registration with `alexa-app` is not necessary.
```
var intents = {
  FindPetIntent: {
    slots: {ANIMAL_TYPE: 'ANIMAL_TYPE'},
    utterances: ['{adopt a |find a }{-|ANIMAL_TYPE}']
  },
  MenuIntent: {utterances: ['{menu|help}']},
  ...(more intents)
};
```

### Config
Configuration for the router.
```
var config = {
  defaultRoutes: {
    'AMAZON.CancelIntent': '/exit',
    'AMAZON.HelpIntent': '/help',
    'AMAZON.NextIntent': '/',
    'AMAZON.PreviousIntent': '/',
    'AMAZON.RepeatIntent': '/',
    'AMAZON.ResumeIntent': '/',
    'AMAZON.StartOverIntent': '/',
    'AMAZON.StopIntent': '/exit',
    'AMAZON.YesIntent': '/',
    PetDetailsIntent: '/pets/{petId}',
    FindPetIntent: '/pets?offset=0',
    FindShelterIntent: '/shelters?limit=5',
    MenuIntent: '/menu'
  },
  pre: preHandler,
  post: postHandler,
  launch: launchHandler
};
function preHandler(request, response) {...},
function postHandler(request, response) {...},
function launchHandler(request, response) {...}
```
#### defaultRoutes
Contains the default routes to use when no route is specified. These are used on first launch, and when no route has otherwise been specified.
#### pre
Shorthand for `app.pre = function preHandler(request, response) {...}`;
#### post
Shorthand for `app.post = function postHandler(request, response) {...}`;
#### launch
Shorthand for `app.launch = function launchHandler(request, response) {...}`;

## Breaking Changes
From `0.0.X` to `0.1.X` breaking changes were introduced:
  - The whole routing paradigm has been made more intuitive, flexible, and powerful. Read the docs below for updates.

## Gotchas and Important Notes
1. Every intent your app uses (including Amazon default intents) must be specified in `config.defaultRoutes`.

## Going to a Route
When prompting the user for a new response, provide the `.route()` command a map of routes to go to depending on the user's response. The route is chosen in the following way:
1. Exact intent match from `.route()`.
2. Route specified on the `default` entry.
3. Intent match on `config.defaultRoutes`.
```
function launchHandler(request, response) {
  var text = 'Welcome to my app. Would you like a list of commands?';
  response
    .say(text)
    .route({
      'default': '/'
      'AMAZON.CancelIntent': '/exit',
      'AMAZON.NoIntent': '/exit',
      'AMAZON.YesIntent': '/help',
      FindPetIntent: '/pets?offset=0',
      FindShelterIntent: '/shelters?limit=5'
    })
    .send();
}
```
This allows two useful features:
1. Since Alexa can receive any available intent at any time, you can stop unexpected intents by using the `default` route here.
2. You don't have to specify, for example, `'AMAZON.HelpIntent': '/help'` every time if it is set up on `config.defaultRoutes` and you don't use `default`;

Internally the route is saved on the `route` session variable.  `.route(routes)` is equivalent to:
```
response
  .shouldEndSession(false)
  .session('route', routes)
```

## Route Parameters
Routes support both url and query string parameters.

E.g. `.route('/pets/123/photos/45678?format=png&size=large')` will match the route `/pets/{petId}/photos/{photoId}`.

The current route info can be retrieved with `request.route`:
```
request.route = {
  params: {
    petId: '123',
    photoId: '45678'
  },
  query: {
    format: 'png',
    size: 'large'
  },
  route: '/pets/{petId}/photos/{photoId}',
  url: '/pets/123/photos/45678?format=png&size=large'
}
```

This allows easy management of complex state flows.  Consider the following interaction with the sample routes/intents above:
1. User calls the Pet skill and asks to view pets. The `config.defaultRoutes` handler for `PetIntent` is set to `'/pets?limit=1&offset=0'` which calls the `findPetHandler()`.
2. User asks for the next pet and `AMAZON.NextIntent` is triggered. In the `findPetHandler`, dynamically route `AMAZON.NextIntent` to `'/pets?limit=1&offset=' + (request.route.query.offset + 1)`.
3. Suppose this returns a pet with an internal Id of `123` in `findPetHandler()`.  When the user asks for more details, a `MoreDetailsIntent` is triggered.
4. The `MoreDetailsIntent` can be dynamically routed to `'/pets/' + pet.Id` which calls `petDetailsHandler()` with the pet Id.

## Backwards Compatibility
All functionality is backwards compatible with [alexa-app](https://github.com/alexa-js/alexa-app). Intents can be registered normally, the router intents are simply a shorthand for convenience.

Special thanks to [Matt Kruse](https://github.com/matt-kruse) for his excellent [alexa-app](https://github.com/alexa-js), and [Daniel Doubrovkine](https://github.com/dblock) for his work maintaining it!


text:
var fs = require('fs');
var jsonfile = require('jsonfile')
var yaml = require('js-yaml');

const BASE_DIR = 'templates/'
const templates = fs.readdirSync(BASE_DIR);

QUnit.test( "Validate template files", function( assert ) {
  var file
  for (var i = 0; i < templates.length; i++) {
    file = BASE_DIR + templates[i]
    if (file.endsWith(".json")) {
      assert.ok(jsonfile.readFileSync(file))
    } else if (file.endsWith(".yaml")) {
      assert.ok(yaml.safeLoad(fs.readFileSync(file)))
    } else {
      assert.ok(false, file + " is not a valid template file")
    }
  }
})


text:
<?php

require_once __DIR__ . '/../src/Wheniwork.php';

/**
* Test for the client library.
*
* Contributors:
* Daniel Olfelt <daniel@thisclicks.com>
*
* @author Daniel Olfelt <daniel@thisclicks.com>
* @version 0.1
*/

class WheniworkTest extends PHPUnit_Framework_TestCase {

  public function testSetEndpoint()
  {
    $new_endpoint = 'http://example.com/2';
    $wiw = new Wheniwork();
    $wiw->setEndpoint($new_endpoint);

    $this->assertEquals($new_endpoint, $wiw->getEndpoint());
  }

  public function testSetHeaders()
  {
    $headers = ['Sample-Header' => 'Test string'];
    $wiw = new Wheniwork(null, ['headers' => $headers]);

    $this->assertArrayHasKey('Sample-Header', $wiw->getHeaders());

    $wiw->setHeaders(['Another-Sample' => 'Test two']);
    $this->assertEquals(2, count($wiw->getHeaders()));

    $wiw->setHeaders(['another-sample' => 'Test three']);
    $this->assertEquals(2, count($wiw->getHeaders()));

    $this->assertArrayHasKey("another-sample", $wiw->getHeaders());
  }

  public function testSetToken()
  {
    $token = 'i-love-my-boss';
    $wiw = new Wheniwork($token);

    $this->assertEquals($token, $wiw->getToken());

    $wiw->setToken('wrong-value');

    $this->assertNotEquals($token, $wiw->getToken());
  }

  public function testOptionsSetAtConstruction(){
    $options = [
        "endpoint"=>"http://example.com/2",
        "verify_ssl"=>true,
        "ca_path"=>"/path/to/ca",
        "ca_info"=>"CA Cert"
    ];

    $wiw = new Wheniwork("test", $options);
    $refl = new ReflectionObject($wiw);

    $this->assertEquals($options["endpoint"], $this->getPrivatePropValue($refl, $wiw, "api_endpoint"));
    $this->assertEquals($options["verify_ssl"], $this->getPrivatePropValue($refl, $wiw, "verify_ssl"));
    $this->assertEquals($options["ca_path"], $this->getPrivatePropValue($refl, $wiw, "ca_path"));
    $this->assertEquals($options["ca_info"], $this->getPrivatePropValue($refl, $wiw, "ca_info"));
  }

  private function getPrivatePropValue(\ReflectionObject $refl, $obj, $property){
      $prop = $refl->getProperty($property);
      $prop->setAccessible(true);
      return $prop->getValue($obj);
  }

}


text:
def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums['reverse_mapping'] = reverse
    return type('Enum', (), enums)

ServiceProtocol = enum(ip=0, icmp=1, tcp=6, udp=17, eigrp=88)

GraphAttribute = enum(Type='type', Service='service',  Label='label', SubnetIpAddress='subnetip', SubnetMask='mask', IpAddress='ipaddress', VlanId='vlanid', HostIds='hostids', SwitchIds='switchids', RouterIds='routerids', InterfaceIds='interfaceids' ,ServerIds='serverids' )
SecurityElement = enum(Conduit="conduit", Zone="zone")
RuleEffect = enum(Permit=1, Deny=2)
RuleOperation = enum(Exclude=1, Intersect=2)
RuleInteractionType = enum(PartialOverlap=1, Conflict=2, Shadow=3, Generalisation=4)


text:
package at.fh_hagenberg.s1520237047.tictactoe.service.net;

import net.jodah.concurrentunit.Waiter;

import org.junit.Test;

import java.net.Inet4Address;
import java.net.InetAddress;

import at.fh_hagenberg.s1520237047.tictactoe.service.Game;
import at.fh_hagenberg.s1520237047.tictactoe.service.GameCreator;

import static org.junit.Assert.*;

/**
 * @author Kai Takac
 */
public class NetServerGameCreatorTest {

    @Test
    public void createGame() throws Exception {
        final Waiter waiter = new Waiter();
        final Waiter waiter2 = new Waiter();

        final String localPlayerName = "Ka0o0";
        final String remotePlayerName = "BadA**96";
        final int gameSize = 0;
        final boolean[] called = new boolean[]{false, false};

        NetServerGameCreator gameCreator = new NetServerGameCreator(localPlayerName);
        gameCreator.createGame(gameSize, new GameCreator.GameCreatorHandler() {
            @Override
            public void onGameCreated(Game game) {
                assertTrue(game.isMyTurn());
                assertEquals(gameSize, game.getField().getSize());
                assertEquals(remotePlayerName, game.getRemotePlayer().name);
                assertEquals(localPlayerName, game.getLocalPlayer().name);
                called[0] = true;
                waiter.resume();
            }

            @Override
            public void onGameCreationFailed() {
            }
        });

        NetClientGameCreator clientGameCreator = new NetClientGameCreator(remotePlayerName, InetAddress.getByName("localhost"));
        clientGameCreator.createGame(0, new GameCreator.GameCreatorHandler() {
            @Override
            public void onGameCreated(Game game) {
                assertFalse(game.isMyTurn());
                assertEquals(gameSize, game.getField().getSize());
                assertEquals(localPlayerName, game.getRemotePlayer().name);
                assertEquals(remotePlayerName, game.getLocalPlayer().name);
                called[1] = true;
                waiter2.resume();
            }

            @Override
            public void onGameCreationFailed() {

            }
        });

        waiter.await(2000);
        assertTrue(called[0]);
        waiter2.await(2000);
        assertTrue(called[1]);

    }

}


text:
[![Documentation][godoc-img]][godoc-url]
![License][license-img]
[![Build Status][travis-img]][travis-url]
[![Coverage Status][coverage-img]][coverage-url]
[![Report Status][goreport-img]][goreport-url]

An engine to manage your components lifecycle.

[![Lemon][lemon-img]][lemon-url]

## Introduction

Lemon is an engine that manage your components lifecycle using a startup and shutdown mechanism.

It will start every registered hook _(or daemon, service, etc...)_ and block until it receives a signal
(**SIGINT**, **SIGTERM** and **SIGQUIT** for example) or when a parent context is terminated...

> **NOTE:** startup and shutdown procedure will be executed in separated goroutine: so be very careful with
any race conditions or deadlocks.

## Example

```go
package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/novln/lemon"
)

// Let's define a simple Ping hook...
type Ping struct {}

// Start will be executed when lemon's engine will try to start this Hook.
// Your hook can perfectly use the given context (see example), or any blocking operation...
func (p *Ping) Start(ctx context.Context) error {

	fmt.Println("[ping] Start")

	for {
		select {
		case <-ctx.Done():
			return nil
		case <-time.After(2 * time.Second):
			fmt.Println("[ping] Echo Request")
		}
	}
}

// However, if you don't use <-ctx.Done(), you must cancel your blocking operation in Stop.
func (p *Ping) Stop(ctx context.Context) error {
	fmt.Println("[ping] Stop")
	return nil
}

func main() {

	timeout := 5 * time.Second
	ctx := context.Background()

	engine, err := lemon.New(ctx, lemon.Timeout(timeout), lemon.Logger(func(err error) {
		fmt.Fprintln(os.Stderr, err)
	}))

	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(255)
	}

	engine.Register(&Ping{})
	engine.Start()

}

```

## Versioning or Vendoring

Expect compatibility break from `master` branch.

Using [Go dependency management tool](https://github.com/golang/dep) is **highly recommended**.

> **NOTE:** semver tags or branches could be provided, if needed.

## License

This is Free Software, released under the [`MIT License`](LICENSE).

[lemon-url]: https://github.com/novln/lemon
[lemon-img]: https://raw.githubusercontent.com/novln/lemon/master/lemon.png
[godoc-url]: https://godoc.org/github.com/novln/lemon
[godoc-img]: https://godoc.org/github.com/novln/lemon?status.svg
[license-img]: https://img.shields.io/badge/license-MIT-blue.svg
[travis-url]: https://travis-ci.org/novln/lemon
[travis-img]: https://travis-ci.org/novln/lemon.svg?branch=master
[coverage-url]: https://codecov.io/gh/novln/lemon
[coverage-img]: https://codecov.io/gh/novln/lemon/branch/master/graph/badge.svg
[goreport-url]: https://goreportcard.com/report/novln/lemon
[goreport-img]: https://goreportcard.com/badge/novln/lemon


text:
package azkaban.scheduler;

import static azkaban.ServiceProvider.SERVICE_PROVIDER;
import static java.util.Objects.requireNonNull;

import azkaban.Constants.ConfigurationKeys;
import azkaban.utils.Props;
import com.google.common.annotations.VisibleForTesting;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Manages Quartz schedules. Azkaban regards QuartzJob and QuartzTrigger as an one-to-one
 * mapping.
 * Quartz job key naming standard:
 * Job key is composed of job name and group name. Job type denotes job name. Project id+flow
 * name denotes group name.
 * E.x FLOW_TRIGGER as job name, 1.flow1 as group name
 */
@Singleton
public class QuartzScheduler {

  private static final Logger logger = LoggerFactory.getLogger(QuartzScheduler.class);
  private Scheduler scheduler = null;

  @Inject
  public QuartzScheduler(final Props azProps) throws SchedulerException {
    if (!azProps.getBoolean(ConfigurationKeys.ENABLE_QUARTZ, false)) {
      return;
    }
    // TODO kunkun-tang: Many quartz properties should be defaulted such that not necessarily being
    // checked into azkaban.properties. Also, we need to only assemble Quartz related properties
    // here, which should be done in Azkaban WebServer Guice Module.
    final StdSchedulerFactory schedulerFactory =
        new StdSchedulerFactory(azProps.toAllProperties());
    this.scheduler = schedulerFactory.getScheduler();

    // Currently Quartz only support internal job schedules. When we migrate to User Production
    // flows, we need to construct a Guice-Free JobFactory for use.
    this.scheduler.setJobFactory(SERVICE_PROVIDER.getInstance(SchedulerJobFactory.class));
  }

  public void start() throws SchedulerException {
    this.scheduler.start();
    logger.info("Quartz Scheduler started.");
  }

  @VisibleForTesting
  void cleanup() throws SchedulerException {
    this.scheduler.clear();
  }

  public void shutdown() throws SchedulerException {
    this.scheduler.shutdown();
    logger.info("Quartz Scheduler shut down.");
  }

  /**
   * Pause a job if it's present.
   * @param jobName
   * @param groupName
   * @return true if job has been paused, no if job doesn't exist.
   * @throws SchedulerException
   */
  public synchronized boolean pauseJobIfPresent(final String jobName, final String groupName)
      throws SchedulerException {
    if (ifJobExist(jobName, groupName)) {
      this.scheduler.pauseJob(new JobKey(jobName, groupName));
      return true;
    } else {
      return false;
    }
  }

  /**
   * Check if job is paused.
   *
   * @return true if job is paused, false otherwise.
   */
  public synchronized boolean isJobPaused(final String jobName, final String groupName)
      throws SchedulerException {
    if (!ifJobExist(jobName, groupName)) {
      throw new SchedulerException(String.format("Job (job name %s, group name %s) doesn't "
          + "exist'", jobName, groupName));
    }
    final JobKey jobKey = new JobKey(jobName, groupName);
    final JobDetail jobDetail = this.scheduler.getJobDetail(jobKey);
    final List<? extends Trigger> triggers = this.scheduler.getTriggersOfJob(jobDetail.getKey());
    for (final Trigger trigger : triggers) {
      final TriggerState triggerState = this.scheduler.getTriggerState(trigger.getKey());
      if (TriggerState.PAUSED.equals(triggerState)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Resume a job.
   * @param jobName
   * @param groupName
   * @return true the job has been resumed, no if the job doesn't exist.
   * @throws SchedulerException
   */
  public synchronized boolean resumeJobIfPresent(final String jobName, final String groupName)
      throws SchedulerException {
    if (ifJobExist(jobName, groupName)) {
      this.scheduler.resumeJob(new JobKey(jobName, groupName));
      return true;
    } else {
      return false;
    }
  }

  /**
   * Unschedule a job.
   * @param jobName
   * @param groupName
   * @return true if job is found and unscheduled.
   * @throws SchedulerException
   */
  public synchronized boolean unscheduleJob(final String jobName, final String groupName) throws
      SchedulerException {
    return this.scheduler.deleteJob(new JobKey(jobName, groupName));
  }

  /**
   * Only cron schedule register is supported. Since register might be called when
   * concurrently uploading projects, so synchronized is added to ensure thread safety.
   *
   * @param cronExpression the cron schedule for this job
   * @param jobDescription Regarding QuartzJobDescription#groupName, in order to guarantee no
   * duplicate quartz schedules, we design the naming convention depending on use cases:

   *
User flow schedule: we use {@link JobKey#JobKey} to represent the identity of a
   * flow's schedule. The format follows "$projectID.$flowName" to guarantee no duplicates.
   *
Quartz schedule for AZ internal use: the groupName should start with letters, rather
   * than
   * number, which is the first case.

   *
   * @return true if job has been scheduled, false if the same job exists already.
   */
  public synchronized boolean scheduleJobIfAbsent(final String cronExpression, final QuartzJobDescription
      jobDescription) throws SchedulerException {

    requireNonNull(jobDescription, "jobDescription is null");

    if (ifJobExist(jobDescription.getJobName(), jobDescription.getGroupName())) {
      logger.warn(String.format("can not register existing job with job name: "
          + "%s and group name: %s", jobDescription.getJobName(), jobDescription.getGroupName()));
      return false;
    }

    if (!CronExpression.isValidExpression(cronExpression)) {
      throw new SchedulerException(
          "The cron expression string <" + cronExpression + "> is not valid.");
    }

    // TODO kunkun-tang: we will modify this when we start supporting multi schedules per flow.
    final JobDetail job = JobBuilder.newJob(jobDescription.getJobClass())
        .withIdentity(jobDescription.getJobName(), jobDescription.getGroupName()).build();

    // Add external dependencies to Job Data Map.
    job.getJobDataMap().putAll(jobDescription.getContextMap());

    // TODO kunkun-tang: Need management code to deal with different misfire policy
    final Trigger trigger = TriggerBuilder
        .newTrigger()
        .withSchedule(
            CronScheduleBuilder.cronSchedule(cronExpression)
                .withMisfireHandlingInstructionFireAndProceed()
//            .withMisfireHandlingInstructionDoNothing()
//            .withMisfireHandlingInstructionIgnoreMisfires()
        )
        .build();

    this.scheduler.scheduleJob(job, trigger);
    logger.info("Quartz Schedule with jobDetail " + job.getDescription() + " is registered.");
    return true;
  }

  @VisibleForTesting
  boolean ifJobExist(final String jobName, final String groupName)
      throws SchedulerException {
    return this.scheduler.getJobDetail(new JobKey(jobName, groupName)) != null;
  }

  public Scheduler getScheduler() {
    return this.scheduler;
  }
}


text:
package org.apereo.cas.configuration.model.support.redis;

import org.apereo.cas.configuration.support.RequiresModule;

import com.fasterxml.jackson.annotation.JsonFilter;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.io.Serial;

/**
 * Configuration properties for Redis.
 *
 * @author serv
 * @since 5.2.0
 */
@RequiresModule(name = "cas-server-support-redis-service-registry")
@Getter
@Setter
@Accessors(chain = true)
@JsonFilter("RedisServiceRegistryProperties")
public class RedisServiceRegistryProperties extends BaseRedisProperties {

    @Serial
    private static final long serialVersionUID = -9012996050439638782L;
}


text:
package kops

// NetworkingSpec allows selection and configuration of a networking plugin
type NetworkingSpec struct {
	Classic  *ClassicNetworkingSpec  `json:"classic,omitempty"`
	Kubenet  *KubenetNetworkingSpec  `json:"kubenet,omitempty"`
	External *ExternalNetworkingSpec `json:"external,omitempty"`
}

// ClassicNetworkingSpec is the specification of classic networking mode, integrated into kubernetes
type ClassicNetworkingSpec struct {
}

// KubenetNetworkingSpec is the specification for kubenet networking, largely integrated but intended to replace classic
type KubenetNetworkingSpec struct {
}

// ExternalNetworkingSpec is the specification for networking that is implemented by a Daemonset
// Networking is not managed by kops - we can create options here that directly configure e.g. weave
// but this is useful for arbitrary network modes or for modes that don't need additional configuration.
type ExternalNetworkingSpec struct {
}


text:
namespace {

class BluetoothTaskObserver : public device::BluetoothTaskManagerWin::Observer {
 public:
  BluetoothTaskObserver() : num_updates_(0) {
  }

  virtual ~BluetoothTaskObserver() {
  }

  virtual void AdapterStateChanged(
    const device::BluetoothTaskManagerWin::AdapterState& state) {
    num_updates_++;
  }

  int num_updates() const {
    return num_updates_;
  }

 private:
   int num_updates_;
};

}  // namespace

namespace device {

class BluetoothTaskManagerWinTest : public testing::Test {
 public:
  BluetoothTaskManagerWinTest()
      : ui_task_runner_(new base::TestSimpleTaskRunner()),
        bluetooth_task_runner_(new base::TestSimpleTaskRunner()),
        task_manager_(new BluetoothTaskManagerWin(ui_task_runner_,
                                                  bluetooth_task_runner_)),
        has_bluetooth_stack_(device::bluetooth_init_win::HasBluetoothStack()) {
  }

  virtual void SetUp() {
    task_manager_->AddObserver(&observer_);
  }

  virtual void TearDown() {
    task_manager_->RemoveObserver(&observer_);
  }

  int GetPollingIntervalMs() const {
    return BluetoothTaskManagerWin::kPollIntervalMs;
  }

 protected:
  scoped_refptr<base::TestSimpleTaskRunner> ui_task_runner_;
  scoped_refptr<base::TestSimpleTaskRunner> bluetooth_task_runner_;
  scoped_refptr<BluetoothTaskManagerWin> task_manager_;
  BluetoothTaskObserver observer_;
  const bool has_bluetooth_stack_;
};

TEST_F(BluetoothTaskManagerWinTest, StartPolling) {
  task_manager_->Initialize();
  const std::deque<base::TestPendingTask>& pending_tasks =
      bluetooth_task_runner_->GetPendingTasks();
  EXPECT_EQ(1, bluetooth_task_runner_->GetPendingTasks().size());
}

TEST_F(BluetoothTaskManagerWinTest, PollAdapterIfBluetoothStackIsAvailable) {
  task_manager_->Initialize();
  bluetooth_task_runner_->RunPendingTasks();
  int num_expected_pending_tasks = has_bluetooth_stack_ ? 1 : 0;
  EXPECT_EQ(num_expected_pending_tasks,
            bluetooth_task_runner_->GetPendingTasks().size());
}

TEST_F(BluetoothTaskManagerWinTest, Polling) {
  if (!has_bluetooth_stack_)
    return;

  task_manager_->Initialize();
  int expected_num_updates = 5;

  for (int i = 0; i < expected_num_updates; i++) {
    bluetooth_task_runner_->RunPendingTasks();
  }

  EXPECT_EQ(expected_num_updates, ui_task_runner_->GetPendingTasks().size());
  ui_task_runner_->RunPendingTasks();
  EXPECT_EQ(expected_num_updates, observer_.num_updates());
}

TEST_F(BluetoothTaskManagerWinTest, SetPowered) {
  if (!has_bluetooth_stack_)
    return;

  base::Closure closure;
  task_manager_->PostSetPoweredBluetoothTask(true, closure, closure);

  EXPECT_EQ(1, bluetooth_task_runner_->GetPendingTasks().size());
  bluetooth_task_runner_->RunPendingTasks();
  EXPECT_TRUE(ui_task_runner_->GetPendingTasks().size() >= 1);
}

}  // namespace device


text:
#ifndef TYPEDEFINES_H
#define TYPEDEFINES_H

typedef unsigned char uint8;
typedef unsigned int uint32;
typedef unsigned long long uint64;

typedef signed char int8;
typedef int int32;
typedef long long int64;

typedef long long integer_t;
typedef unsigned long long uinteger_t;

typedef int64 Time;
typedef uint64 physical_address_t;
typedef uint64 la_t;
typedef uint64 pa_t;
typedef integer_t simtime_t;

#endif


text:
package be.peterneyens.jerseyappengine.auth;

import be.peterneyens.jerseyappengine.core.Session;
import be.peterneyens.jerseyappengine.core.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import java.security.Principal;

public class MySecurityContext implements javax.ws.rs.core.SecurityContext {

    private static final Logger log = LoggerFactory.getLogger(MySecurityContext.class);

    private final User user;
    private final Session session;

    public MySecurityContext(Session session, User user) {
        log.info("constructor");
        this.session = session;
        this.user = user;
    }

    @Override
    public String getAuthenticationScheme() {
        return SecurityContext.BASIC_AUTH;
    }

    @Override
    public Principal getUserPrincipal() {
        return user;
    }

    @Override
    public boolean isSecure() {
        return (null != session) && session.isSecure();
    }

    @Override
    public boolean isUserInRole(String role) {

        log.info("isUserInRole {}", role);

        if (null == session || !session.isActive()) {
            // Forbidden
            Response denied = Response.status(Response.Status.FORBIDDEN).entity("Permission Denied").build();
            throw new WebApplicationException(denied);
        }

        // Registered role => user exists ?
        if (role.equals("Registered")) {
            return user != null;
        }

        try {
            // this user has this role?
            return user.getRoles().contains(User.Role.valueOf(role));
        } catch (Exception e) {
        }

        return false;
    }

    Session getSession() {
        return this.session;
    }
}


text:
'use strict';

/**
* Returns the data values.
*
* @private
* @returns {ArrayLike} data values
*/
function get() {
	/* eslint-disable no-invalid-this */
	return this._data;
}

// EXPORTS //

module.exports = get;


text:
package org.kie.workbench.drools.client.perspectives;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import com.google.gwt.user.client.Window;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.kie.workbench.common.widgets.client.handlers.NewResourcesMenu;
import org.kie.workbench.common.workbench.client.docks.AuthoringWorkbenchDocks;
import org.kie.workbench.drools.client.resources.i18n.AppConstants;
import org.uberfire.backend.vfs.Path;
import org.uberfire.backend.vfs.VFSService;
import org.uberfire.client.annotations.Perspective;
import org.uberfire.client.annotations.WorkbenchMenu;
import org.uberfire.client.annotations.WorkbenchPerspective;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.client.workbench.PanelManager;
import org.uberfire.client.workbench.panels.impl.MultiListWorkbenchPanelPresenter;
import org.uberfire.lifecycle.OnOpen;
import org.uberfire.mvp.PlaceRequest;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.PanelDefinition;
import org.uberfire.workbench.model.PartDefinition;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.impl.PerspectiveDefinitionImpl;
import org.uberfire.workbench.model.menu.MenuFactory;
import org.uberfire.workbench.model.menu.Menus;

@ApplicationScoped
@WorkbenchPerspective(identifier = "AuthoringPerspectiveNoContext", isTransient = false)
public class DroolsAuthoringNoContextNavigationPerspective {

    private AppConstants constants = AppConstants.INSTANCE;

    @Inject
    private NewResourcesMenu newResourcesMenu;

    @Inject
    private PlaceManager placeManager;

    @Inject
    private PanelManager panelManager;

    @Inject
    private Caller<VFSService> vfsServices;

    @Inject
    private AuthoringWorkbenchDocks docks;

    private String explorerMode;
    private String projectPathString;
    private boolean projectEditorDisableBuild;

    private final List<PlaceRequest> placesToClose = new ArrayList<PlaceRequest>();

    @PostConstruct
    public void init() {
        explorerMode = ( ( Window.Location.getParameterMap().containsKey( "explorer_mode" ) ) ? Window.Location.getParameterMap().get( "explorer_mode" ).get( 0 ) : "" ).trim();
        projectPathString = ( ( ( Window.Location.getParameterMap().containsKey( "path" ) ) ? Window.Location.getParameterMap().get( "path" ).get( 0 ) : "" ) ).trim();
        projectEditorDisableBuild = Window.Location.getParameterMap().containsKey("no_build");

        final PlaceRequest placeRequest = generateProjectExplorerPlaceRequest();

        docks.setup("AuthoringPerspectiveNoContext", placeRequest);

    }

    private PlaceRequest generateProjectExplorerPlaceRequest() {
        final PlaceRequest placeRequest = new DefaultPlaceRequest( "org.kie.guvnor.explorer" );
        if ( !explorerMode.isEmpty() ) {
            placeRequest.addParameter( "mode",
                    explorerMode );
        }
        if ( !projectPathString.isEmpty() ) {
            placeRequest.addParameter( "init_path",
                    projectPathString );
        }
        if ( projectEditorDisableBuild ) {
            placeRequest.addParameter( "no_build",
                    "true" );
        }

        placeRequest.addParameter("no_context",
                "true");
        return placeRequest;
    }

    @Perspective
    public PerspectiveDefinition getPerspective() {
        final PerspectiveDefinitionImpl perspective = new PerspectiveDefinitionImpl( MultiListWorkbenchPanelPresenter.class.getName() );
        perspective.setName( constants.project_authoring() );

        return perspective;
    }

    @OnOpen
    public void onOpen() {
        placesToClose.clear();
        if ( !projectPathString.isEmpty() ) {
            vfsServices.call( new RemoteCallback<Boolean>() {
                @Override
                public void callback( Boolean isRegularFile ) {
                    if ( isRegularFile ) {
                        vfsServices.call( new RemoteCallback<Path>() {
                            @Override
                            public void callback( Path path ) {
                                placeManager.goTo( path );
                            }
                        } ).get( projectPathString );
                    }
                }
            } ).isRegularFile( projectPathString );
        }
        if ( panelManager.getRoot() != null ) {
            process( panelManager.getRoot().getParts() );
            process( panelManager.getRoot().getChildren() );

            for ( final PlaceRequest placeRequest : placesToClose ) {
                placeManager.forceClosePlace( placeRequest );
            }
        }
    }

    private void process( final List<PanelDefinition> children ) {
        for ( final PanelDefinition child : children ) {
            process( child.getParts() );
            process( child.getChildren() );
        }
    }

    private void process( final Collection<PartDefinition> parts ) {
        for ( final PartDefinition partDefinition : parts ) {
            if ( !partDefinition.getPlace().getIdentifier().equals( "org.kie.guvnor.explorer" ) ) {
                placesToClose.add( partDefinition.getPlace() );
            }
        }
    }

    @WorkbenchMenu
    public Menus getMenus() {
        return MenuFactory.newTopLevelMenu( constants.newItem() )
                .withItems( newResourcesMenu.getMenuItemsWithoutProject() ).endMenu()
                .build();
    }
}


text:
import java.util.stream.Stream;

public class NestedFunctionParameters {
  private static long fun(long a, long b) {
    return a + b;
  }

  public static void main(String[] args) {
<caret>    long c = fun(Stream.of(1, 2).count(), fun(Stream.of(1, 2, 3).count(), Stream.of(1, 2, 3, 4).count()));
  }
}