text:
function bsp_mass = bsp1(MASS,varargin)

repopath = '/Users/will/Repo/Biomech/body-segment-param/';
datapath = [repopath,'data/scaled-mass/'];

bsp_mass = table();

%% Proportional models
%
% col 1 = segment, column 2 = original data, column 3 = rescaled to 100%

modfilenames = {'harless1860','braune1889','dempster1955',...
  'fujikawa1963',...
  'clauser1969','zats-selu1979m','zats-selu1979f',...
  'jensen1989-6yr','jensen1986-12yr',...
  ...'jensen1986-15yr',...
  'jensen1989-18yr',...
  'jensen1994M','jensen1994F','cheng2000','pavol2002M','pavol2002F','chen2011','ma2011M','ma2011F'};

for mm = 1:numel(modfilenames)
  T = readtable([datapath,modfilenames{mm},'.csv']);
  modname = T.Properties.VariableNames{1};
  new = table(MASS*T{:,3}/100,'VariableNames',{modname},'RowNames',T{:,1});
  if mm == 1
    newtable = new;
  else
    newtable = fakejoin(bsp_mass,new);
  end
  bsp_mass = newtable;
end

%%

modnames = bsp_mass.Properties.VariableNames;

for mm = 1:numel(modnames)

  modname = modnames{mm};

  if not(isnan(bsp_mass{'shoulder',modname})) && not(isnan(bsp_mass{'chest',modname})) && not(not(isnan(bsp_mass{'thorax',modname})))
    bsp_mass{'thorax',modname} = 2*bsp_mass{'shoulder',modname} + bsp_mass{'chest',modname};
  end
  if not(isnan(bsp_mass{'abdo',modname})) && not(isnan(bsp_mass{'pelvis',modname})) && not(not(isnan(bsp_mass{'abdopelvis',modname})))
    bsp_mass{'abdopelvis',modname} = bsp_mass{'abdo',modname} + bsp_mass{'pelvis',modname};
  end
  if not(isnan(bsp_mass{'abdo',modname})) && not(isnan(bsp_mass{'thorax',modname})) && not(not(isnan(bsp_mass{'thoraxabdo',modname})))
    bsp_mass{'abdopelvis',modname} = bsp_mass{'abdo',modname} + bsp_mass{'pelvis',modname};
  end

  if (isnan(bsp_mass{'trunk',modname}))
    if not(isnan(bsp_mass{'abdopelvis',modname})) && not(isnan(bsp_mass{'thorax',modname}))
      bsp_mass{'trunk',modname} = ...
        bsp_mass{'abdopelvis',modname} + bsp_mass{'thorax',modname};
    elseif not(isnan(bsp_mass{'thoraxabdo',modname})) && not(isnan(bsp_mass{'pelvis',modname}))
      bsp_mass{'trunk',modname} = ...
        bsp_mass{'thoraxabdo',modname} + bsp_mass{'pelvis',modname};
    else
      warning('Cannot resolve TRUNK segment for model "%s".',modname);
    end
  end

end

%%

end

%%

function C = fakejoin(A,B)

fake = {'FakeRowNames'};

AT = array2table(A.Properties.RowNames,'VariableNames',fake);
BT = array2table(B.Properties.RowNames,'VariableNames',fake);

% these can't be inlined into outerjoin() for some reason!
AV = [AT, A];
BV = [BT, B];

CV = outerjoin(AV,BV,'Keys',1,'MergeKeys',true);

C = CV(:,2:end);
C.Properties.RowNames = CV{:,1};

end


text:
import React, { ChangeEvent, FocusEvent, PureComponent } from 'react';

import { IntervalVariableModel } from 'src/types';
import { VariableEditorProps } from '../editor/types';
import { InlineFormLabel, LegacyForms } from 'src/packages/datav-core/src/ui';
const { Switch } = LegacyForms;

export interface Props extends VariableEditorProps<IntervalVariableModel> {}

export class IntervalVariableEditor extends PureComponent<Props> {
  onAutoChange = (event: ChangeEvent<HTMLInputElement>) => {
    this.props.onPropChange({
      propName: 'auto',
      propValue: event.target.checked,
      updateOptions: true,
    });
  };

  onQueryChanged = (event: ChangeEvent<HTMLInputElement>) => {
    this.props.onPropChange({
      propName: 'query',
      propValue: event.target.value,
    });
  };

  onQueryBlur = (event: FocusEvent<HTMLInputElement>) => {
    this.props.onPropChange({
      propName: 'query',
      propValue: event.target.value,
      updateOptions: true,
    });
  };

  onAutoCountChanged = (event: ChangeEvent<HTMLSelectElement>) => {
    this.props.onPropChange({
      propName: 'auto_count',
      propValue: event.target.value,
      updateOptions: true,
    });
  };

  onAutoMinChanged = (event: ChangeEvent<HTMLInputElement>) => {
    this.props.onPropChange({
      propName: 'auto_min',
      propValue: event.target.value,
      updateOptions: true,
    });
  };

  render() {
    return (
      <>

Interval Options

            Values
            <input
              type="text"
              className="gf-form-input"
              value={this.props.variable.query}
              placeholder="1m,10m,1h,6h,1d,7d"
              onChange={this.onQueryChanged}
              onBlur={this.onQueryBlur}
              required
            />

            <Switch
              label="Auto Option"
              labelClass="width-9"
              checked={this.props.variable.auto}
              onChange={this.onAutoChange}
              tooltip={'Enables multiple values to be selected at the same time'}
            />

            {this.props.variable.auto && (
              <>

                  <InlineFormLabel
                    width={9}
                    tooltip={'How many times should the current time range be divided to calculate the value'}
                  >
                    Step count
                  </InlineFormLabel>

                    <select
                      className="gf-form-input"
                      value={this.props.variable.auto_count}
                      onChange={this.onAutoCountChanged}
                    >
                      {[1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 100, 200, 300, 400, 500].map(count => (
                        <option key={`auto_count_key-${count}`} label={`${count}`}>
                          {count}
                        </option>
                      ))}
                    </select>

                  <InlineFormLabel width={9} tooltip={'The calculated value will not go below this threshold'}>
                    Min interval
                  </InlineFormLabel>
                  <input
                    type="text"
                    className="gf-form-input max-width-10"
                    value={this.props.variable.auto_min}
                    onChange={this.onAutoMinChanged}
                    placeholder="10s"
                  />

              </>
            )}

      </>
    );
  }
}

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"

#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "zile.h"
#include "extern.h"

DEFUN("zile-version", zile_version)
/*+
Show the zile version.
+*/
{
  minibuf_write("Zile " VERSION " of " CONFIGURE_DATE " on " CONFIGURE_HOST);

  return TRUE;
}
END_DEFUN

static int show_file(char *filename)
{
  if (!exist_file(filename)) {
    minibuf_error("Unable to read file `%s'", filename);
    return FALSE;
  }

  find_file(filename);
  cur_bp->flags = BFLAG_READONLY | BFLAG_NOSAVE | BFLAG_NEEDNAME
    | BFLAG_NOUNDO;

  return TRUE;
}

DEFUN("help", help)
/*+
Show a help window.
+*/
{
  return show_file(PATH_DATA "/HELP");
}
END_DEFUN

DEFUN("view-zile-FAQ", view_zile_FAQ)
/*+
Show the Zile Frequently Asked Questions (FAQ).
+*/
{
  return show_file(PATH_DATA "/FAQ");
}
END_DEFUN

DEFUN("help-with-tutorial", help_with_tutorial)
/*+
Show a tutorial window.
+*/
{
  if (show_file(PATH_DATA "/TUTORIAL")) {
    astr buf = get_home_dir();

    cur_bp->flags = 0;
    astr_cat_cstr(buf, "/TUTORIAL");
    set_buffer_filename(cur_bp, astr_cstr(buf));
    astr_delete(buf);

    return TRUE;
  }

  return FALSE;
}
END_DEFUN

/*
 * Fetch the documentation of a function or variable from the
 * AUTODOC automatically generated file.
 */
static astr get_funcvar_doc(char *name, astr defval, int isfunc)
{
  FILE *f;
  astr buf, match, doc;
  int reading_doc = 0;

  if ((f = fopen(PATH_DATA "/AUTODOC", "r")) == NULL) {
    minibuf_error("Unable to read file `%s'",
                  PATH_DATA "/AUTODOC");
    return NULL;
  }

  match = astr_new();
  if (isfunc)
    astr_afmt(match, "\fF_%s", name);
  else
    astr_afmt(match, "\fV_%s", name);

  doc = astr_new();
  while ((buf = astr_fgets(f)) != NULL) {
    if (reading_doc) {
      if (*astr_char(buf, 0) == '\f') {
        astr_delete(buf);
        break;
      }
      if (isfunc || astr_len(defval) > 0) {
        astr_cat(doc, buf);
        astr_cat_char(doc, '\n');
      } else
        astr_cpy(defval, buf);
    } else if (!astr_cmp(buf, match))
      reading_doc = 1;
    astr_delete(buf);
  }

  fclose(f);
  astr_delete(match);

  if (!reading_doc) {
    minibuf_error("Cannot find documentation for `%s'", name);
    astr_delete(doc);
    return NULL;
  }

  return doc;
}

static void write_function_description(va_list ap)
{
  const char *name = va_arg(ap, const char *);
  astr doc = va_arg(ap, astr);

  bprintf("Function: %s\n\n"
          "Documentation:\n%s",
          name, astr_cstr(doc));
}

DEFUN("describe-function", describe_function)
/*+
Display the full documentation of a function.
+*/
{
  char *name;
  astr bufname, doc;

  name = minibuf_read_function_name("Describe function: ");
  if (name == NULL)
    return FALSE;

  if ((doc = get_funcvar_doc(name, NULL, TRUE)) == NULL)
    return FALSE;

  bufname = astr_new();
  astr_afmt(bufname, "*Help: function `%s'*", name);
  write_temp_buffer(astr_cstr(bufname), write_function_description,
                    name, doc);
  free(name);
  astr_delete(bufname);
  astr_delete(doc);

  return TRUE;
}
END_DEFUN

static void write_variable_description(va_list ap)
{
  char *name = va_arg(ap, char *);
  astr defval = va_arg(ap, astr);
  char *curval = va_arg(ap, char *);
  astr doc = va_arg(ap, astr);
  bprintf("Variable: %s\n\n"
          "Default value: %s\n"
          "Current value: %s\n\n"
          "Documentation:\n%s",
          name, astr_cstr(defval), curval, astr_cstr(doc));
}

DEFUN("describe-variable", describe_variable)
/*+
Display the full documentation of a variable.
+*/
{
  char *name;
  astr bufname, defval, doc;

  name = minibuf_read_variable_name("Describe variable: ");
  if (name == NULL)
    return FALSE;

  defval = astr_new();
  if ((doc = get_funcvar_doc(name, defval, FALSE)) == NULL) {
    astr_delete(defval);
    return FALSE;
  }

  bufname = astr_new();
  astr_afmt(bufname, "*Help: variable `%s'*", name);
  write_temp_buffer(astr_cstr(bufname), write_variable_description,
                    name, defval, get_variable(name), doc);
  astr_delete(bufname);
  astr_delete(doc);
  astr_delete(defval);

  return TRUE;
}
END_DEFUN

DEFUN("describe-key", describe_key)
/*+
Display documentation of the command invoked by a key sequence.
+*/
{
  char *name;
  astr bufname, doc, binding;
  size_t *keys;
  int numkeys;

  minibuf_write("Describe key:");
  name = get_function_by_key_sequence(&keys, &numkeys);
  binding = keyvectostr(keys, numkeys);
  free(keys);

  if (name == NULL) {
    minibuf_error("%s is undefined", astr_cstr(binding));
    astr_delete(binding);
    return FALSE;
  }

  minibuf_write("%s runs the command `%s'", astr_cstr(binding), name);
  astr_delete(binding);

  if ((doc = get_funcvar_doc(name, NULL, TRUE)) == NULL)
    return FALSE;

  bufname = astr_new();
  astr_afmt(bufname, "*Help: function `%s'*", name);
  write_temp_buffer(astr_cstr(bufname), write_function_description,
                    name, doc);
  astr_delete(bufname);
  astr_delete(doc);

  return TRUE;
}
END_DEFUN


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

namespace i18n.Extension.Tests.Resources {
    using System;

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

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

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

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

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

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

        /// <summary>
        ///   Looks up a localized string similar to Female.
        /// </summary>
        internal static string Gender_Female {
            get {
                return ResourceManager.GetString("Gender_Female", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Male.
        /// </summary>
        internal static string Male {
            get {
                return ResourceManager.GetString("Male", resourceCulture);
            }
        }
    }
}


text:
cask "universal-media-server" do
  arch arm: "-arm"

  version "11.5.0"
  sha256 arm:   "85926f2780a8ea14d3a2b6a3f0e744fe5f91caf1396603e2483b6f94dbb12a60",
         intel: "3fc8ee143bdb708221963ab4fd51905b057bae6fc1ef2342297c95057d706302"

  url "https://github.com/UniversalMediaServer/UniversalMediaServer/releases/download/#{version}/UMS-#{version}#{arch}.dmg",
      verified: "github.com/UniversalMediaServer/UniversalMediaServer/"
  name "Universal Media Server"
  desc "Media server supporting DLNA, UPnP and HTTP(S)"
  homepage "https://www.universalmediaserver.com/"

  livecheck do
    url :url
    strategy :github_latest
  end

  depends_on macos: ">= :catalina"

  app "Universal Media Server.app"

  zap trash: "~/Library/Application Support/UMS"
end


text:
set -e

for file in config/*.yml.example; do
  cp ${file} config/$(basename ${file} .example)
done

# Allow to override the GitLab URL from an environment variable, as this will avoid having to change the configuration file for simple deployments.
config=$(echo '<% gitlab_url = URI(ENV["GITLAB_URL"] || "http://localhost:80") %>' | cat - config/gitlab.yml)
echo "$config" > config/gitlab.yml
sed -i "s/host: localhost/host: <%= gitlab_url.host %>/" config/gitlab.yml
sed -i "s/port: 80/port: <%= gitlab_url.port %>/" config/gitlab.yml
sed -i "s/https: false/https: <%= gitlab_url.scheme == 'https' %>/" config/gitlab.yml

# No need for config file. Will be taken care of by REDIS_URL env variable
rm config/resque.yml

# Set default unicorn.rb file
echo "" > config/unicorn.rb


text:
import { Localized } from '@fluent/react';
import classNames from 'classnames';
import React, { useCallback, useContext, useEffect, useRef } from 'react';

import type { MachineryTranslation } from '~/api/machinery';
import { EditorActions } from '~/context/Editor';
import { HelperSelection } from '~/context/HelperSelection';
import { Locale } from '~/context/Locale';
import { GenericTranslation } from '~/core/translation';
import { useReadonlyEditor } from '~/hooks/useReadonlyEditor';

import { ConcordanceSearch } from './ConcordanceSearch';
import { TranslationSource } from './TranslationSource';

import './ConcordanceSearch.css';
import './Translation.css';

type Props = {
  sourceString: string;
  translation: MachineryTranslation;
  index: number;
};

/**
 * Render a Translation in the Machinery tab.
 *
 * Shows the original string and the translation, as well as a list of sources.
 * Similar translations (same original and translation) are shown only once
 * and their sources are merged.
 */
export function Translation({
  index,
  sourceString,
  translation,
}: Props): React.ReactElement<React.ElementType> {
  const { setEditorFromHelpers } = useContext(EditorActions);
  const { element, setElement } = useContext(HelperSelection);
  const isSelected = element === index;

  const copyTranslationIntoEditor = useCallback(() => {
    if (window.getSelection()?.isCollapsed !== false) {
      setElement(index);
      setEditorFromHelpers(translation.translation, translation.sources, true);
    }
  }, [index, setEditorFromHelpers, translation]);

  const className = classNames(
    'translation',
    useReadonlyEditor() && 'cannot-copy',
    isSelected && 'selected',
  );

  const translationRef = useRef<HTMLLIElement>(null);
  useEffect(() => {
    if (isSelected) {
      const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
      translationRef.current?.scrollIntoView({
        behavior: mediaQuery.matches ? 'auto' : 'smooth',
        block: 'nearest',
      });
    }
  }, [isSelected]);

  return (
    <Localized id='machinery-Translation--copy' attrs={{ title: true }}>

        {translation.sources.includes('concordance-search') ? (
          <ConcordanceSearch
            sourceString={sourceString}
            translation={translation}
          />
        ) : (
          <TranslationSuggestion
            sourceString={sourceString}
            translation={translation}
          />
        )}

    </Localized>
  );
}

function TranslationSuggestion({
  sourceString,
  translation,
}: {
  sourceString: string;
  translation: MachineryTranslation;
}) {
  const { code, direction, script } = useContext(Locale);
  return (
    <>

        {translation.quality && (
          {translation.quality + '%'}
        )}
        <TranslationSource translation={translation} />

        <GenericTranslation
          content={translation.original}
          diffTarget={
            // Caighdean takes `gd` translations as input, so we shouldn't
            // diff it against the `en-US` source string.
            translation.sources.includes('caighdean') ? null : sourceString
          }
        />

        <GenericTranslation content={translation.translation} />

    </>
  );
}


text:
SET(PRIZM 1)

# SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS ${CMAKE_EXE_LINKER_FLAGS})
# SET(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS ${CMAKE_EXE_LINKER_FLAGS})
SET(CMAKE_EXECUTABLE_SUFFIX ".bin")
SET(CMAKE_C_OUTPUT_EXTENSION ".o")
SET(CMAKE_CXX_OUTPUT_EXTENSION ".o")

LINK_LIBRARIES(c)

SET(CMAKE_C_FLAGS "-Os -Wall -mb  -mhitachi -nostdlib -ffunction-sections -fdata-sections -I${CMAKE_CURRENT_SOURCE_DIR}/../include")
SET(CMAKE_CXX_FLAGS "-Os -Wall -mb  -mhitachi -nostdlib -ffunction-sections -fdata-sections -I${CMAKE_CURRENT_SOURCE_DIR}/../include")

SET(CMAKE_EXE_LINKER_FLAGS "-L../lib -T../toolchain/prizm.x -Wl,-static -Wl,-gc-sections -nostdlib")


text:
/*
 * Author: 陈志杭 Caspar
 * Contact: 279397942@qq.com qq:279397942
 * Description: 数据接口契约文件
 * 文件由模板生成,请不要直接修改文件,如需修改请创建一个对应的partial文件
 */
using System;
using System.Collections;
using Zh.DAL.Define.Entities;
using Zh.DAL.Define;
using Zh.DAL.Base.Define;
using Zh.DAL.Define.Contracts;
namespace Zh.DAL.Define.Contracts.Imp
{
    /// <summary>
    /// Auth_PermissionResourceRef(权限资源关系表)表访问类
    /// </summary>
    public partial class AuthPermissionResourceRefDao : BaseDao<Auth_PermissionResourceRef>,IAuthPermissionResourceRefDao
    {

    }
}


text:
    {% include social-icons.html %}

    © {{ site.time | date: '%Y' }} Todos los derechos reservados. Hecho con Jekyll Y  por {{ site.author.name }}

    Tema creado por nandomoreira.me


text:
import random
# Bubble Sort

# randomly generate 10 integers from (-100, 100)
arr = [random.randrange(-100,100) for i in range(10)]

print('original %s' % arr)
def bubbleSort(array):
  n = len(array)
  # traverse thru all elements
  for i in range(n):
    swapped = False
    # traverse thru last i elements already sorted
    for j in range(0, n-i-1):
      # swap smaller to front
      if array[j] > array[j+1]:
        array[j], array[j+1] = array[j+1], array[j]
        swapped = True

    # IF no two elements were swapped
    # by inner loop, then break
    if swapped == False:
        break

  return array

a = bubbleSort(arr)
print(f"sorted {a}")


text:
NSFormatter subclass for formatting phone numbers.

## Usage

### Format a number

```objc
ECPhoneNumberFormatter *formatter = [[ECPhoneNumberFormatter alloc] init];
NSString *formattedNumber = [formatter stringForObjectValue:@"2345677890"]
// formattedNumber = @"(234) 567-7890"
```

### Remove formatting

```objc
ECPhoneNumberFormatter *formatter = [[ECPhoneNumberFormatter alloc] init];
id objectValue;
NSString *error;
[formatter getObjectValue:&objectValue forString:@"1 (234) 567-8900" errorDescription:&error];
// objectValue = @"12345678900"
```

### Format a NSTextField

```objc
ECPhoneNumberFormatter *formatter = [[ECPhoneNumberFormatter alloc] init];
textField.cell.formatter = formatter;

// textField.objectValue will be unformatted
// textField.stringValue will be formatted
```

## MIT License

Copyright (c) 2013 Michael Enriquez (http://enriquez.me)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
package org.xins.common;

/**
 * Utility class used to check mandatory method arguments.
 *
 * @version $Revision: 1.22 $ $Date: 2007/03/16 09:54:58 $
 * @author Ernst de Haan
 *
 * @since XINS 1.0.0
 */
public final class MandatoryArgumentChecker {

   /**
    * Constructs a new MandatoryArgumentChecker. This constructor
    * is private since this no instances of this class should be created.
    */
   private MandatoryArgumentChecker() {
      // empty
   }

   /**
    * Checks if the specified argument value is null. If it is
    * null, then an {@link IllegalArgumentException} is thrown.
    *
    * @param argName
    *    the name of the argument, cannot be null.
    *
    * @param argValue
    *    the value of the argument.
    *
    * @throws IllegalArgumentException
    *    if argValue == null.
    */
   public static void check(String argName, Object argValue)
   throws IllegalArgumentException {

      // If both are non-null everything is okay, just short-circuit
      if (argName != null && argValue != null) {
         return;
      }

      // Check if the name is null
      if (argName == null) {
         throw Utils.logProgrammingError("argName == null");
      }

      // Otherwise the value is null
      if (argValue == null) {
         throw new IllegalArgumentException(argName + " == null");
      }
   }

   /**
    * Checks if any of the two specified argument values is null.
    * If at least one value is null, then an
    * {@link IllegalArgumentException} is thrown.
    *
    * @param argName1
    *    the name of the first argument, cannot be null.
    *
    * @param argValue1
    *    the value of the first argument.
    *
    * @param argName2
    *    the name of the second argument, cannot be null.
    *
    * @param argValue2
    *    the value of the second argument.
    *
    * @throws IllegalArgumentException
    *    if argValue1 == null || argValue2 == null.
    */
   public static void check(String argName1, Object argValue1,
                            String argName2, Object argValue2)
   throws IllegalArgumentException {

      // If all are non-null everything is okay, just short-circuit
      if (argName1 != null && argValue1 != null &&
          argName2 != null && argValue2 != null) {
         return;
      }

      String message = "";

      // Check if any of the names is null
      if (argName1 == null && argName2 == null) {
         message = "argName1 == null && argName2 == null";
         throw Utils.logProgrammingError(message);
      }

      // Otherwise (at least) one of the values must be null
      if (argValue1 == null && argValue2 == null) {
         message = argName1 + " == null && "
                 + argName2 + " == null";
      } else {
         check(argName1, argValue1);
         check(argName2, argValue2);
      }
      throw new IllegalArgumentException(message);
   }

   /**
    * Checks if any of the three specified argument values is
    * null. If at least one value is null, then an
    * {@link IllegalArgumentException} is thrown.
    *
    * @param argName1
    *    the name of the first argument, cannot be null.
    *
    * @param argValue1
    *    the value of the first argument.
    *
    * @param argName2
    *    the name of the second argument, cannot be null.
    *
    * @param argValue2
    *    the value of the second argument.
    *
    * @param argName3
    *    the name of the third argument, cannot be null.
    *
    * @param argValue3
    *    the value of the third argument.
    *
    * @throws IllegalArgumentException
    *    if argValue1 == null
    *          || argValue2 == null
    *          || argValue3 == null.
    */
   public static void check(String argName1, Object argValue1,
                            String argName2, Object argValue2,
                            String argName3, Object argValue3)
   throws IllegalArgumentException {

      // If all are non-null everything is okay, just short-circuit
      if (argName1 != null && argValue1 != null &&
          argName2 != null && argValue2 != null &&
          argName3 != null && argValue3 != null) {
         return;
      }

      // Check if any of the names is null
      String message = "";
      if (argName1 == null && argName2 == null && argName3 == null) {
         message = "argName1 == null && "
                 + "argName2 == null && "
                 + "argName3 == null";
         throw Utils.logProgrammingError(message);
      }

      // Otherwise (at least) one of the values must be null
      if (argValue1 == null && argValue2 == null && argValue3 == null) {
         message = argName1 + " == null && "
                 + argName2 + " == null && "
                 + argName3 + " == null";
      } else {
         check(argName1, argValue1, argName2, argValue2);
         check(argName1, argValue1, argName3, argValue3);
         check(argName2, argValue2, argName3, argValue3);
      }
      throw new IllegalArgumentException(message);
   }

   /**
    * Checks if any of the four specified argument values is
    * null. If at least one value is null, then an
    * {@link IllegalArgumentException} is thrown.
    *
    * @param argName1
    *    the name of the first argument, cannot be null.
    *
    * @param argValue1
    *    the value of the first argument.
    *
    * @param argName2
    *    the name of the second argument, cannot be null.
    *
    * @param argValue2
    *    the value of the second argument.
    *
    * @param argName3
    *    the name of the third argument, cannot be null.
    *
    * @param argValue3
    *    the value of the third argument.
    *
    * @param argName4
    *    the name of the fourth argument, cannot be null.
    *
    * @param argValue4
    *    the value of the fourth argument.
    *
    * @throws IllegalArgumentException
    *    if argValue1 == null || argValue2 == null
    *          || argValue3 == null || argValue4 == null.
    */
   public static void check(String argName1, Object argValue1,
                            String argName2, Object argValue2,
                            String argName3, Object argValue3,
                            String argName4, Object argValue4)
   throws IllegalArgumentException {

      // If all are non-null everything is okay, just short-circuit
      if (argName1 != null && argValue1 != null &&
          argName2 != null && argValue2 != null &&
          argName3 != null && argValue3 != null &&
          argName4 != null && argValue4 != null) {
         return;
      }

      // Check if any of the names is null
      String message = "";
      if (argName1 == null && argName2 == null &&
          argName3 == null && argName4 == null) {
         message = "argName1 == null && argName2 == null && "
                 + "argName3 == null && argName4 == null";
         throw Utils.logProgrammingError(message);
      }

      // Otherwise (at least) one of the values must be null
      if (argValue1 == null && argValue2 == null && argValue3 == null && argValue4 == null) {
         message = argName1 + " == null && "
                 + argName2 + " == null && "
                 + argName3 + " == null && "
                 + argName4 + " == null";
      } else {
         check(argName1, argValue1, argName2, argValue2, argName3, argValue3);
         check(argName1, argValue1, argName2, argValue2, argName4, argValue4);
         check(argName2, argValue2, argName3, argValue3, argName4, argValue4);
      }
      throw new IllegalArgumentException(message);
   }
}


text:
import json
import os

import frappe
from frappe import _
from frappe.core.doctype.role.role import get_info_based_on_role, get_user_info
from frappe.core.doctype.sms_settings.sms_settings import send_sms
from frappe.desk.doctype.notification_log.notification_log import enqueue_create_notification
from frappe.integrations.doctype.slack_webhook_url.slack_webhook_url import send_slack_message
from frappe.model.document import Document
from frappe.modules.utils import export_module_json, get_doc_module
from frappe.utils import add_to_date, cast, is_html, nowdate, validate_email_address
from frappe.utils.jinja import validate_template
from frappe.utils.safe_exec import get_safe_globals

class Notification(Document):
	def onload(self):
		"""load message"""
		if self.is_standard:
			self.message = self.get_template()

	def autoname(self):
		if not self.name:
			self.name = self.subject

	def validate(self):
		if self.channel in ("Email", "Slack", "System Notification"):
			validate_template(self.subject)

		validate_template(self.message)

		if self.event in ("Days Before", "Days After") and not self.date_changed:
			frappe.throw(_("Please specify which date field must be checked"))

		if self.event == "Value Change" and not self.value_changed:
			frappe.throw(_("Please specify which value field must be checked"))

		self.validate_forbidden_types()
		self.validate_condition()
		self.validate_standard()
		frappe.cache().hdel("notifications", self.document_type)

	def on_update(self):
		path = export_module_json(self, self.is_standard, self.module)
		if path:
			# js
			if not os.path.exists(path + ".md") and not os.path.exists(path + ".html"):
				with open(path + ".md", "w") as f:
					f.write(self.message)

			# py
			if not os.path.exists(path + ".py"):
				with open(path + ".py", "w") as f:
					f.write(
						"""import frappe

def get_context(context):
	# do your magic here
	pass
"""
					)

	def validate_standard(self):
		if self.is_standard and self.enabled and not frappe.conf.developer_mode:
			frappe.throw(
				_("Cannot edit Standard Notification. To edit, please disable this and duplicate it")
			)

	def validate_condition(self):
		temp_doc = frappe.new_doc(self.document_type)
		if self.condition:
			try:
				frappe.safe_eval(self.condition, None, get_context(temp_doc.as_dict()))
			except Exception:
				frappe.throw(_("The Condition '{0}' is invalid").format(self.condition))

	def validate_forbidden_types(self):
		forbidden_document_types = ("Email Queue",)
		if self.document_type in forbidden_document_types or frappe.get_meta(self.document_type).istable:
			# currently notifications don't work on child tables as events are not fired for each record of child table

			frappe.throw(_("Cannot set Notification on Document Type {0}").format(self.document_type))

	def get_documents_for_today(self):
		"""get list of documents that will be triggered today"""
		docs = []

		diff_days = self.days_in_advance
		if self.event == "Days After":
			diff_days = -diff_days

		reference_date = add_to_date(nowdate(), days=diff_days)
		reference_date_start = reference_date + " 00:00:00.000000"
		reference_date_end = reference_date + " 23:59:59.000000"

		doc_list = frappe.get_all(
			self.document_type,
			fields="name",
			filters=[
				{self.date_changed: (">=", reference_date_start)},
				{self.date_changed: ("<=", reference_date_end)},
			],
		)

		for d in doc_list:
			doc = frappe.get_doc(self.document_type, d.name)

			if self.condition and not frappe.safe_eval(self.condition, None, get_context(doc)):
				continue

			docs.append(doc)

		return docs

	def send(self, doc):
		"""Build recipients and send Notification"""

		context = get_context(doc)
		context = {"doc": doc, "alert": self, "comments": None}
		if doc.get("_comments"):
			context["comments"] = json.loads(doc.get("_comments"))

		if self.is_standard:
			self.load_standard_properties(context)
		try:
			if self.channel == "Email":
				self.send_an_email(doc, context)

			if self.channel == "Slack":
				self.send_a_slack_msg(doc, context)

			if self.channel == "SMS":
				self.send_sms(doc, context)

			if self.channel == "System Notification" or self.send_system_notification:
				self.create_system_notification(doc, context)

		except Exception:
			self.log_error("Failed to send Notification")

		if self.set_property_after_alert:
			allow_update = True
			if (
				doc.docstatus.is_submitted()
				and not doc.meta.get_field(self.set_property_after_alert).allow_on_submit
			):
				allow_update = False
			try:
				if allow_update and not doc.flags.in_notification_update:
					fieldname = self.set_property_after_alert
					value = self.property_value
					if doc.meta.get_field(fieldname).fieldtype in frappe.model.numeric_fieldtypes:
						value = frappe.utils.cint(value)

					doc.reload()
					doc.set(fieldname, value)
					doc.flags.updater_reference = {
						"doctype": self.doctype,
						"docname": self.name,
						"label": _("via Notification"),
					}
					doc.flags.in_notification_update = True
					doc.save(ignore_permissions=True)
					doc.flags.in_notification_update = False
			except Exception:
				self.log_error("Document update failed")

	def create_system_notification(self, doc, context):
		subject = self.subject
		if "{" in subject:
			subject = frappe.render_template(self.subject, context)

		attachments = self.get_attachment(doc)

		recipients, cc, bcc = self.get_list_of_recipients(doc, context)

		users = recipients + cc + bcc

		if not users:
			return

		notification_doc = {
			"type": "Alert",
			"document_type": doc.doctype,
			"document_name": doc.name,
			"subject": subject,
			"from_user": doc.modified_by or doc.owner,
			"email_content": frappe.render_template(self.message, context),
			"attached_file": attachments and json.dumps(attachments[0]),
		}
		enqueue_create_notification(users, notification_doc)

	def send_an_email(self, doc, context):
		from email.utils import formataddr

		from frappe.core.doctype.communication.email import _make as make_communication

		subject = self.subject
		if "{" in subject:
			subject = frappe.render_template(self.subject, context)

		attachments = self.get_attachment(doc)
		recipients, cc, bcc = self.get_list_of_recipients(doc, context)
		if not (recipients or cc or bcc):
			return

		sender = None
		message = frappe.render_template(self.message, context)
		if self.sender and self.sender_email:
			sender = formataddr((self.sender, self.sender_email))
		frappe.sendmail(
			recipients=recipients,
			subject=subject,
			sender=sender,
			cc=cc,
			bcc=bcc,
			message=message,
			reference_doctype=doc.doctype,
			reference_name=doc.name,
			attachments=attachments,
			expose_recipients="header",
			print_letterhead=((attachments and attachments[0].get("print_letterhead")) or False),
		)

		# Add mail notification to communication list
		# No need to add if it is already a communication.
		if doc.doctype != "Communication":
			make_communication(
				doctype=doc.doctype,
				name=doc.name,
				content=message,
				subject=subject,
				sender=sender,
				recipients=recipients,
				communication_medium="Email",
				send_email=False,
				attachments=attachments,
				cc=cc,
				bcc=bcc,
				communication_type="Automated Message",
			)

	def send_a_slack_msg(self, doc, context):
		send_slack_message(
			webhook_url=self.slack_webhook_url,
			message=frappe.render_template(self.message, context),
			reference_doctype=doc.doctype,
			reference_name=doc.name,
		)

	def send_sms(self, doc, context):
		send_sms(
			receiver_list=self.get_receiver_list(doc, context),
			msg=frappe.render_template(self.message, context),
		)

	def get_list_of_recipients(self, doc, context):
		recipients = []
		cc = []
		bcc = []
		for recipient in self.recipients:
			if recipient.condition:
				if not frappe.safe_eval(recipient.condition, None, context):
					continue
			if recipient.receiver_by_document_field:
				fields = recipient.receiver_by_document_field.split(",")
				# fields from child table
				if len(fields) > 1:
					for d in doc.get(fields[1]):
						email_id = d.get(fields[0])
						if validate_email_address(email_id):
							recipients.append(email_id)
				# field from parent doc
				else:
					email_ids_value = doc.get(fields[0])
					if validate_email_address(email_ids_value):
						email_ids = email_ids_value.replace(",", "\n")
						recipients = recipients + email_ids.split("\n")

			if recipient.cc and "{" in recipient.cc:
				recipient.cc = frappe.render_template(recipient.cc, context)

			if recipient.cc:
				recipient.cc = recipient.cc.replace(",", "\n")
				cc = cc + recipient.cc.split("\n")

			if recipient.bcc and "{" in recipient.bcc:
				recipient.bcc = frappe.render_template(recipient.bcc, context)

			if recipient.bcc:
				recipient.bcc = recipient.bcc.replace(",", "\n")
				bcc = bcc + recipient.bcc.split("\n")

			# For sending emails to specified role
			if recipient.receiver_by_role:
				emails = get_info_based_on_role(recipient.receiver_by_role, "email")

				for email in emails:
					recipients = recipients + email.split("\n")

		if self.send_to_all_assignees:
			recipients = recipients + get_assignees(doc)

		return list(set(recipients)), list(set(cc)), list(set(bcc))

	def get_receiver_list(self, doc, context):
		"""return receiver list based on the doc field and role specified"""
		receiver_list = []
		for recipient in self.recipients:
			if recipient.condition:
				if not frappe.safe_eval(recipient.condition, None, context):
					continue

			# For sending messages to the owner's mobile phone number
			if recipient.receiver_by_document_field == "owner":
				receiver_list += get_user_info([dict(user_name=doc.get("owner"))], "mobile_no")
			# For sending messages to the number specified in the receiver field
			elif recipient.receiver_by_document_field:
				receiver_list.append(doc.get(recipient.receiver_by_document_field))

			# For sending messages to specified role
			if recipient.receiver_by_role:
				receiver_list += get_info_based_on_role(recipient.receiver_by_role, "mobile_no")

		return receiver_list

	def get_attachment(self, doc):
		"""check print settings are attach the pdf"""
		if not self.attach_print:
			return None

		print_settings = frappe.get_doc("Print Settings", "Print Settings")
		if (doc.docstatus == 0 and not print_settings.allow_print_for_draft) or (
			doc.docstatus == 2 and not print_settings.allow_print_for_cancelled
		):

			# ignoring attachment as draft and cancelled documents are not allowed to print
			status = "Draft" if doc.docstatus == 0 else "Cancelled"
			frappe.throw(
				_(
					"""Not allowed to attach {0} document, please enable Allow Print For {0} in Print Settings"""
				).format(status),
				title=_("Error in Notification"),
			)
		else:
			return [
				{
					"print_format_attachment": 1,
					"doctype": doc.doctype,
					"name": doc.name,
					"print_format": self.print_format,
					"print_letterhead": print_settings.with_letterhead,
					"lang": frappe.db.get_value("Print Format", self.print_format, "default_print_language")
					if self.print_format
					else "en",
				}
			]

	def get_template(self):
		module = get_doc_module(self.module, self.doctype, self.name)

		def load_template(extn):
			template = ""
			template_path = os.path.join(os.path.dirname(module.__file__), frappe.scrub(self.name) + extn)
			if os.path.exists(template_path):
				with open(template_path) as f:
					template = f.read()
			return template

		return load_template(".html") or load_template(".md")

	def load_standard_properties(self, context):
		"""load templates and run get_context"""
		module = get_doc_module(self.module, self.doctype, self.name)
		if module:
			if hasattr(module, "get_context"):
				out = module.get_context(context)
				if out:
					context.update(out)

		self.message = self.get_template()

		if not is_html(self.message):
			self.message = frappe.utils.md_to_html(self.message)

	def on_trash(self):
		frappe.cache().hdel("notifications", self.document_type)

@frappe.whitelist()
def get_documents_for_today(notification):
	notification = frappe.get_doc("Notification", notification)
	notification.check_permission("read")
	return [d.name for d in notification.get_documents_for_today()]

def trigger_daily_alerts():
	trigger_notifications(None, "daily")

def trigger_notifications(doc, method=None):
	if frappe.flags.in_import or frappe.flags.in_patch:
		# don't send notifications while syncing or patching
		return

	if method == "daily":
		doc_list = frappe.get_all(
			"Notification", filters={"event": ("in", ("Days Before", "Days After")), "enabled": 1}
		)
		for d in doc_list:
			alert = frappe.get_doc("Notification", d.name)

			for doc in alert.get_documents_for_today():
				evaluate_alert(doc, alert, alert.event)
				frappe.db.commit()

def evaluate_alert(doc: Document, alert, event):
	from jinja2 import TemplateError

	try:
		if isinstance(alert, str):
			alert = frappe.get_doc("Notification", alert)

		context = get_context(doc)

		if alert.condition:
			if not frappe.safe_eval(alert.condition, None, context):
				return

		if event == "Value Change" and not doc.is_new():
			if not frappe.db.has_column(doc.doctype, alert.value_changed):
				alert.db_set("enabled", 0)
				alert.log_error(f"Notification {alert.name} has been disabled due to missing field")
				return

			doc_before_save = doc.get_doc_before_save()
			field_value_before_save = doc_before_save.get(alert.value_changed) if doc_before_save else None

			fieldtype = doc.meta.get_field(alert.value_changed).fieldtype
			if cast(fieldtype, doc.get(alert.value_changed)) == cast(fieldtype, field_value_before_save):
				# value not changed
				return

		if event != "Value Change" and not doc.is_new():
			# reload the doc for the latest values & comments,
			# except for validate type event.
			doc.reload()
		alert.send(doc)
	except TemplateError:
		frappe.throw(
			_("Error while evaluating Notification {0}. Please fix your template.").format(alert)
		)
	except Exception as e:
		error_log = frappe.log_error(message=frappe.get_traceback(), title=str(e))
		frappe.throw(
			_("Error in Notification: {}").format(
				frappe.utils.get_link_to_form("Error Log", error_log.name)
			)
		)

def get_context(doc):
	return {
		"doc": doc,
		"nowdate": nowdate,
		"frappe": frappe._dict(utils=get_safe_globals().get("frappe").get("utils")),
	}

def get_assignees(doc):
	assignees = []
	assignees = frappe.get_all(
		"ToDo",
		filters={"status": "Open", "reference_name": doc.name, "reference_type": doc.doctype},
		fields=["allocated_to"],
	)

	recipients = [d.allocated_to for d in assignees]

	return recipients


text:
from distutils.core import setup

setup(name='PyAUNetReceive',
      version='1.0',
      description='Python client to receive AUNetSend output',
      author='Ricky Reusser',
      author_email='rsreusser@gmail.com',
      url='http://github.com/rreusser/pyaunetsend',
      packages=['pyaunetreceive'],
     )


text:
from . import domainresource

class DeviceRequest(domainresource.DomainResource):
    """ Medical device request.

    Represents a request for a patient to employ a medical device. The device
    may be an implantable device, or an external assistive device, such as a
    walker.
    """

    resource_type = "DeviceRequest"

    def __init__(self, jsondict=None, strict=True):
        """ Initialize all valid properties.

        :raises: FHIRValidationError on validation errors, unless strict is False
        :param dict jsondict: A JSON dictionary to use for initialization
        :param bool strict: If True (the default), invalid variables will raise a TypeError
        """

        self.authoredOn = None
        """ When recorded.
        Type `FHIRDate` (represented as `str` in JSON). """

        self.basedOn = None
        """ What request fulfills.
        List of `FHIRReference` items (represented as `dict` in JSON). """

        self.codeCodeableConcept = None
        """ Device requested.
        Type `CodeableConcept` (represented as `dict` in JSON). """

        self.codeReference = None
        """ Device requested.
        Type `FHIRReference` (represented as `dict` in JSON). """

        self.encounter = None
        """ Encounter motivating request.
        Type `FHIRReference` (represented as `dict` in JSON). """

        self.groupIdentifier = None
        """ Identifier of composite request.
        Type `Identifier` (represented as `dict` in JSON). """

        self.identifier = None
        """ External Request identifier.
        List of `Identifier` items (represented as `dict` in JSON). """

        self.instantiatesCanonical = None
        """ Instantiates FHIR protocol or definition.
        List of `str` items. """

        self.instantiatesUri = None
        """ Instantiates external protocol or definition.
        List of `str` items. """

        self.insurance = None
        """ Associated insurance coverage.
        List of `FHIRReference` items (represented as `dict` in JSON). """

        self.intent = None
        """ proposal | plan | original-order | encoded | reflex-order.
        Type `str`. """

        self.note = None
        """ Notes or comments.
        List of `Annotation` items (represented as `dict` in JSON). """

        self.occurrenceDateTime = None
        """ Desired time or schedule for use.
        Type `FHIRDate` (represented as `str` in JSON). """

        self.occurrencePeriod = None
        """ Desired time or schedule for use.
        Type `Period` (represented as `dict` in JSON). """

        self.occurrenceTiming = None
        """ Desired time or schedule for use.
        Type `Timing` (represented as `dict` in JSON). """

        self.parameter = None
        """ Device details.
        List of `DeviceRequestParameter` items (represented as `dict` in JSON). """

        self.performer = None
        """ Requested Filler.
        Type `FHIRReference` (represented as `dict` in JSON). """

        self.performerType = None
        """ Filler role.
        Type `CodeableConcept` (represented as `dict` in JSON). """

        self.priorRequest = None
        """ What request replaces.
        List of `FHIRReference` items (represented as `dict` in JSON). """

        self.priority = None
        """ Indicates how quickly the {{title}} should be addressed with
        respect to other requests.
        Type `str`. """

        self.reasonCode = None
        """ Coded Reason for request.
        List of `CodeableConcept` items (represented as `dict` in JSON). """

        self.reasonReference = None
        """ Linked Reason for request.
        List of `FHIRReference` items (represented as `dict` in JSON). """

        self.relevantHistory = None
        """ Request provenance.
        List of `FHIRReference` items (represented as `dict` in JSON). """

        self.requester = None
        """ Who/what is requesting diagnostics.
        Type `FHIRReference` (represented as `dict` in JSON). """

        self.status = None
        """ draft | active | suspended | completed | entered-in-error |
        cancelled.
        Type `str`. """

        self.subject = None
        """ Focus of request.
        Type `FHIRReference` (represented as `dict` in JSON). """

        self.supportingInfo = None
        """ Additional clinical information.
        List of `FHIRReference` items (represented as `dict` in JSON). """

        super(DeviceRequest, self).__init__(jsondict=jsondict, strict=strict)

    def elementProperties(self):
        js = super(DeviceRequest, self).elementProperties()
        js.extend([
            ("authoredOn", "authoredOn", fhirdate.FHIRDate, False, None, False),
            ("basedOn", "basedOn", fhirreference.FHIRReference, True, None, False),
            ("codeCodeableConcept", "codeCodeableConcept", codeableconcept.CodeableConcept, False, "code", True),
            ("codeReference", "codeReference", fhirreference.FHIRReference, False, "code", True),
            ("encounter", "encounter", fhirreference.FHIRReference, False, None, False),
            ("groupIdentifier", "groupIdentifier", identifier.Identifier, False, None, False),
            ("identifier", "identifier", identifier.Identifier, True, None, False),
            ("instantiatesCanonical", "instantiatesCanonical", str, True, None, False),
            ("instantiatesUri", "instantiatesUri", str, True, None, False),
            ("insurance", "insurance", fhirreference.FHIRReference, True, None, False),
            ("intent", "intent", str, False, None, True),
            ("note", "note", annotation.Annotation, True, None, False),
            ("occurrenceDateTime", "occurrenceDateTime", fhirdate.FHIRDate, False, "occurrence", False),
            ("occurrencePeriod", "occurrencePeriod", period.Period, False, "occurrence", False),
            ("occurrenceTiming", "occurrenceTiming", timing.Timing, False, "occurrence", False),
            ("parameter", "parameter", DeviceRequestParameter, True, None, False),
            ("performer", "performer", fhirreference.FHIRReference, False, None, False),
            ("performerType", "performerType", codeableconcept.CodeableConcept, False, None, False),
            ("priorRequest", "priorRequest", fhirreference.FHIRReference, True, None, False),
            ("priority", "priority", str, False, None, False),
            ("reasonCode", "reasonCode", codeableconcept.CodeableConcept, True, None, False),
            ("reasonReference", "reasonReference", fhirreference.FHIRReference, True, None, False),
            ("relevantHistory", "relevantHistory", fhirreference.FHIRReference, True, None, False),
            ("requester", "requester", fhirreference.FHIRReference, False, None, False),
            ("status", "status", str, False, None, False),
            ("subject", "subject", fhirreference.FHIRReference, False, None, True),
            ("supportingInfo", "supportingInfo", fhirreference.FHIRReference, True, None, False),
        ])
        return js

from . import backboneelement

class DeviceRequestParameter(backboneelement.BackboneElement):
    """ Device details.

    Specific parameters for the ordered item.  For example, the prism value for
    lenses.
    """

    resource_type = "DeviceRequestParameter"

    def __init__(self, jsondict=None, strict=True):
        """ Initialize all valid properties.

        :raises: FHIRValidationError on validation errors, unless strict is False
        :param dict jsondict: A JSON dictionary to use for initialization
        :param bool strict: If True (the default), invalid variables will raise a TypeError
        """

        self.code = None
        """ Device detail.
        Type `CodeableConcept` (represented as `dict` in JSON). """

        self.valueBoolean = None
        """ Value of detail.
        Type `bool`. """

        self.valueCodeableConcept = None
        """ Value of detail.
        Type `CodeableConcept` (represented as `dict` in JSON). """

        self.valueQuantity = None
        """ Value of detail.
        Type `Quantity` (represented as `dict` in JSON). """

        self.valueRange = None
        """ Value of detail.
        Type `Range` (represented as `dict` in JSON). """

        super(DeviceRequestParameter, self).__init__(jsondict=jsondict, strict=strict)

    def elementProperties(self):
        js = super(DeviceRequestParameter, self).elementProperties()
        js.extend([
            ("code", "code", codeableconcept.CodeableConcept, False, None, False),
            ("valueBoolean", "valueBoolean", bool, False, "value", False),
            ("valueCodeableConcept", "valueCodeableConcept", codeableconcept.CodeableConcept, False, "value", False),
            ("valueQuantity", "valueQuantity", quantity.Quantity, False, "value", False),
            ("valueRange", "valueRange", range.Range, False, "value", False),
        ])
        return js

import sys
try:
    from . import annotation
except ImportError:
    annotation = sys.modules[__package__ + '.annotation']
try:
    from . import codeableconcept
except ImportError:
    codeableconcept = sys.modules[__package__ + '.codeableconcept']
try:
    from . import fhirdate
except ImportError:
    fhirdate = sys.modules[__package__ + '.fhirdate']
try:
    from . import fhirreference
except ImportError:
    fhirreference = sys.modules[__package__ + '.fhirreference']
try:
    from . import identifier
except ImportError:
    identifier = sys.modules[__package__ + '.identifier']
try:
    from . import period
except ImportError:
    period = sys.modules[__package__ + '.period']
try:
    from . import quantity
except ImportError:
    quantity = sys.modules[__package__ + '.quantity']
try:
    from . import range
except ImportError:
    range = sys.modules[__package__ + '.range']
try:
    from . import timing
except ImportError:
    timing = sys.modules[__package__ + '.timing']


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var reward_detail_component_1 = require('./reward-detail.component');
var reward_service_1 = require('./reward.service');
var AppComponent = (function () {
    function AppComponent(rewardService) {
        this.rewardService = rewardService;
        this.title = 'Rewards';
    }
    AppComponent.prototype.getRewards = function () {
        var _this = this;
        this.rewardService.getReward().then(function (rewards) { return _this.rewards = rewards; });
    };
    AppComponent.prototype.ngOnInit = function () {
        this.getRewards();
    };
    AppComponent.prototype.onSelect = function (reward) {
        this.selected = reward;
    };
    AppComponent = __decorate([
        core_1.Component({
            selector: 'rewards',
            templateUrl: 'templates/rewards.html',
            directives: [reward_detail_component_1.RewardDetailComponent],
            providers: [reward_service_1.RewardService]
        })
    ], AppComponent);
    return AppComponent;
}());
exports.AppComponent = AppComponent;
//# sourceMappingURL=app.component.js.map


text:
"use strict";

var exitCodes = exports.exitCodes = {
    argMainRequired: [96, "'main' argument is required"],
    mainNotFound: [97, "Specified 'main' module cannot be found"],
    setsidFailed: [98, "Failed to create new session id"],
    chdirFailed: [99, "Failed to change working directory to root"],
    setgidNoPriv: [100, "No privilege to change group id"],
    setgidFailed: [101, "Failed to change group id"],
    setuidNoPriv: [102, "No privilege to change user id"],
    setuidFailed: [103, "Failed to change user id"]
};

exports.findExitCode = function(code) {
    for (var name in exitCodes)
        if (exitCodes[name][0] == code)
            return exitCodes[name][1];
    return code;
};


text:
<?php
/************************************************************************/
/* ATutor																*/
/************************************************************************/
/* Copyright (c) 2002-2010                                              */
/* Inclusive Design Institute                                           */
/* http://atutor.ca                                                     */
/* This program is free software. You can redistribute it and/or        */
/* modify it under the terms of the GNU General Public License          */
/* as published by the Free Software Foundation.                        */
/************************************************************************/

// $Id: theme.cfg.php 2813 2004-12-12 15:37:46Z greg $

/* This is the default configuration file for the default theme. */

/* The theme's name. */
	$_theme['name'] = 'Default 1.6';

/* The theme's version number. */
	$_theme['version'] = '2.0';

/* Which version of ATutor is this theme intended for. */
	$_theme['atutor-version'] = '2.0';

/* author information */
	$_theme['author_name']  = 'ATutor';
	$_theme['author_url']   = 'http://atutor.ca';
	$_theme['author_email'] = '';

/* theme default course banner styles: */
	$_theme['banner']['font-family'] = 'Verdana, Arial, sans-serif';
	$_theme['banner']['font-weight'] = 'bold';
	$_theme['banner']['color']       = 'black';
	$_theme['banner']['font-size']   = 'xx-large';
	$_theme['banner']['text-align']  = 'center';

	$_theme['banner']['background-color'] = 'white';
	$_theme['banner']['background-image'] = '';
	$_theme['banner']['vertical-align']   = 'middle';
	$_theme['banner']['padding']          = '3px';

?>


text:
package gnu.javax.crypto.prng;

import gnu.java.security.Configuration;
import gnu.java.security.Properties;
import gnu.java.security.Registry;
import gnu.java.security.hash.HashFactory;
import gnu.java.security.hash.IMessageDigest;
import gnu.java.security.prng.BasePRNG;
import gnu.java.security.prng.EntropySource;
import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;
import gnu.java.security.util.SimpleList;
import gnu.java.security.util.Util;
import gnu.javax.crypto.cipher.CipherFactory;
import gnu.javax.crypto.cipher.IBlockCipher;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessController;
import java.security.InvalidKeyException;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * An entropy pool-based pseudo-random number generator based on the PRNG in
 * Peter Gutmann's cryptlib (http://www.cs.auckland.ac.nz/~pgut001/cryptlib/).
 *

 * The basic properties of this generator are:
 *

 *
The internal state cannot be determined by knowledge of the input.

 *
It is resistant to bias introduced by specific inputs.

 *
The output does not reveal the state of the generator.

 *

 */
public class CSPRNG
    extends BasePRNG
{
  private static final Logger log = Logger.getLogger(CSPRNG.class.getName());
  /**
   * Property name for the list of files to read for random values. The mapped
   * value is a list with the following values:
   *

   *
A {@link Double}, indicating the suggested quality of this
   * source. This value must be between 0 and 100.

   *
An {@link Integer}, indicating the number of bytes to skip in the
   * file before reading bytes. This can be any nonnegative value.

   *
An {@link Integer}, indicating the number of bytes to read.

   *
A {@link String}, indicating the path to the file.

   *

   *
   * @see gnu.java.security.util.SimpleList
   */
  public static final String FILE_SOURCES = "gnu.crypto.prng.pool.files";
  /**
   * Property name for the list of URLs to poll for random values. The mapped
   * value is a list formatted similarly as in {@link #FILE_SOURCES}, but the
   * fourth member is a {@link URL}.
   */
  public static final String URL_SOURCES = "gnu.crypto.prng.pool.urls";
  /**
   * Property name for the list of programs to execute, and use the output as
   * new random bytes. The mapped property is formatted similarly an in
   * {@link #FILE_SOURCES} and {@link #URL_SOURCES}, except the fourth member
   * is a {@link String} of the program to execute.
   */
  public static final String PROGRAM_SOURCES = "gnu.crypto.prng.pool.programs";
  /**
   * Property name for a list of other sources of entropy. The mapped value must
   * be a list of {@link EntropySource} objects.
   */
  public static final String OTHER_SOURCES = "gnu.crypto.prng.pool.other";
  /**
   * Property name for whether or not to wait for the slow poll to complete,
   * passed as a {@link Boolean}. The default value is true.
   */
  public static final String BLOCKING = "gnu.crypto.prng.pool.blocking";
  private static final String FILES = "gnu.crypto.csprng.file.";
  private static final String URLS = "gnu.crypto.csprng.url.";
  private static final String PROGS = "gnu.crypto.csprng.program.";
  private static final String OTHER = "gnu.crypto.csprng.other.";
  private static final String BLOCK = "gnu.crypto.csprng.blocking";
  private static final int POOL_SIZE = 256;
  private static final int ALLOC_SIZE = 260;
  private static final int OUTPUT_SIZE = POOL_SIZE / 2;
  private static final int X917_POOL_SIZE = 16;
  private static final String HASH_FUNCTION = Registry.SHA160_HASH;
  private static final String CIPHER = Registry.AES_CIPHER;
  private static final int MIX_COUNT = 10;
  private static final int X917_LIFETIME = 8192;
  // FIXME this should be configurable.
  private static final int SPINNER_COUNT = 8;
  /**
   * The spinner group singleton. We use this to add a small amount of
   * randomness (in addition to the current time and the amount of free memory)
   * based on the randomness (if any) present due to system load and thread
   * scheduling.
   */
  private static final Spinner[] SPINNERS = new Spinner[SPINNER_COUNT];
  private static final Thread[] SPINNER_THREADS = new Thread[SPINNER_COUNT];
  static
    {
      for (int i = 0; i < SPINNER_COUNT; i++)
        {
          SPINNER_THREADS[i] = new Thread(SPINNERS[i] = new Spinner(),
                                          "spinner-" + i);
          SPINNER_THREADS[i].setDaemon(true);
          SPINNER_THREADS[i].setPriority(Thread.MIN_PRIORITY);
          SPINNER_THREADS[i].start();
        }
    }
  /** The message digest (SHA-1) used in the mixing function. */
  private final IMessageDigest hash;
  /** The cipher (AES) used in the output masking function. */
  private final IBlockCipher cipher;
  /** The number of times the pool has been mixed. */
  private int mixCount;
  /** The entropy pool. */
  private final byte[] pool;
  /** The quality of the random pool (percentage). */
  private double quality;
  /** The index of the next byte in the entropy pool. */
  private int index;
  /** The pool for the X9.17-like generator. */
  private byte[] x917pool;
  /** The number of iterations of the X9.17-like generators. */
  private int x917count;
  /** Whether or not the X9.17-like generator is initialized. */
  private boolean x917init;
  /** The list of file soures. */
  private final List files;
  /** The list of URL sources. */
  private final List urls;
  /** The list of program sources. */
  private final List progs;
  /** The list of other sources. */
  private final List other;
  /** Whether or not to wait for the slow poll to complete. */
  private boolean blocking;
  /** The thread that polls for random data. */
  private Poller poller;
  private Thread pollerThread;

  public CSPRNG()
  {
    super("CSPRNG");
    pool = new byte[ALLOC_SIZE];
    x917pool = new byte[X917_POOL_SIZE];
    x917count = 0;
    x917init = false;
    quality = 0.0;
    hash = HashFactory.getInstance(HASH_FUNCTION);
    cipher = CipherFactory.getInstance(CIPHER);
    buffer = new byte[OUTPUT_SIZE];
    ndx = 0;
    initialised = false;
    files = new LinkedList();
    urls = new LinkedList();
    progs = new LinkedList();
    other = new LinkedList();
  }

  /**
   * Create and initialize a CSPRNG instance with the "system" parameters; the
   * files, URLs, programs, and {@link EntropySource} sources used by the
   * instance are derived from properties set in the system {@link Properties}.
   *

   * All properties are of the from name.N, where name
   * is the name of the source, and N is an integer (staring at 1) that
   * indicates the preference number for that source.
   *

   * The following vales for name are used here:
   *

   *
gnu.crypto.csprng.file

   *

   *

   * These properties are file sources, passed as the {@link #FILE_SOURCES}
   * parameter of the instance. The property value is a 4-tuple formatted as:
   *

   *
quality ; offset ; count ; path

   *

   * The parameters are mapped to the parameters defined for {@link
   * #FILE_SOURCES}. Leading or trailing spaces on any item are trimmed off.
   *

   *

   *
gnu.crypto.csprng.url

   *

   *

   * These properties are URL sources, passed as the {@link #URL_SOURCES}
   * parameter of the instance. The property is formatted the same way as file
   * sources, but the path argument must be a valid URL.
   *

   *

   *
gnu.crypto.csprng.program

   *

   *

   * These properties are program sources, passed as the {@link
   * #PROGRAM_SOURCES} parameter of the instance. This property is formatted the
   * same way as file and URL sources, but the last argument is a program and
   * its arguments.
   *

   *

   *
gnu.crypto.cspring.other

   *

   *

   * These properties are other sources, passed as the {@link #OTHER_SOURCES}
   * parameter of the instance. The property value must be the full name of a
   * class that implements the {@link EntropySource} interface and has a public
   * no-argument constructor.
   *

   *

   *

   *

   * Finally, a boolean property "gnu.crypto.csprng.blocking" can be set to the
   * desired value of {@link #BLOCKING}.
   *

   * An example of valid properties would be:
   *

   *  gnu.crypto.csprng.blocking=true
   *
   *  gnu.crypto.csprng.file.1=75.0;0;256;/dev/random
   *  gnu.crypto.csprng.file.2=10.0;0;100;/home/user/file
   *
   *  gnu.crypto.csprng.url.1=5.0;0;256;http://www.random.org/cgi-bin/randbyte?nbytes=256
   *  gnu.crypto.csprng.url.2=0;256;256;http://slashdot.org/
   *
   *  gnu.crypto.csprng.program.1=0.5;0;10;last -n 50
   *  gnu.crypto.csprng.program.2=0.5;0;10;tcpdump -c 5
   *
   *  gnu.crypto.csprng.other.1=foo.bar.MyEntropySource
   *  gnu.crypto.csprng.other.2=com.company.OtherEntropySource
   *

   */
  public static IRandom getSystemInstance() throws ClassNotFoundException,
      MalformedURLException, NumberFormatException
  {
    CSPRNG instance = new CSPRNG();
    HashMap attrib = new HashMap();
    attrib.put(BLOCKING, Boolean.valueOf(getProperty(BLOCK)));
    String s = null;
    // Get each file source "gnu.crypto.csprng.file.N".
    List l = new LinkedList();
    for (int i = 0; (s = getProperty(FILES + i)) != null; i++)
      try
        {
          l.add(parseString(s.trim()));
        }
      catch (NumberFormatException nfe)
        {
        }
    attrib.put(FILE_SOURCES, l);
    l = new LinkedList();
    for (int i = 0; (s = getProperty(URLS + i)) != null; i++)
      try
        {
          l.add(parseURL(s.trim()));
        }
      catch (NumberFormatException nfe)
        {
        }
      catch (MalformedURLException mue)
        {
        }
    attrib.put(URL_SOURCES, l);
    l = new LinkedList();
    for (int i = 0; (s = getProperty(PROGS + i)) != null; i++)
      try
        {
          l.add(parseString(s.trim()));
        }
      catch (NumberFormatException nfe)
        {
        }
    attrib.put(PROGRAM_SOURCES, l);
    l = new LinkedList();
    for (int i = 0; (s = getProperty(OTHER + i)) != null; i++)
      try
        {
          Class c = Class.forName(s.trim());
          l.add(c.newInstance());
        }
      catch (ClassNotFoundException cnfe)
        {
        }
      catch (InstantiationException ie)
        {
        }
      catch (IllegalAccessException iae)
        {
        }
    attrib.put(OTHER_SOURCES, l);
    instance.init(attrib);
    return instance;
  }

  private static String getProperty(final String name)
  {
    return (String) AccessController.doPrivileged(new PrivilegedAction()
    {
      public Object run()
      {
        return Properties.getProperty(name);
      }
    });
  }

  private static List parseString(String s) throws NumberFormatException
  {
    StringTokenizer tok = new StringTokenizer(s, ";");
    if (tok.countTokens() != 4)
      throw new IllegalArgumentException("malformed property");
    Double quality = new Double(tok.nextToken());
    Integer offset = new Integer(tok.nextToken());
    Integer length = new Integer(tok.nextToken());
    String str = tok.nextToken();
    return new SimpleList(quality, offset, length, str);
  }

  private static List parseURL(String s) throws MalformedURLException,
      NumberFormatException
  {
    StringTokenizer tok = new StringTokenizer(s, ";");
    if (tok.countTokens() != 4)
      throw new IllegalArgumentException("malformed property");
    Double quality = new Double(tok.nextToken());
    Integer offset = new Integer(tok.nextToken());
    Integer length = new Integer(tok.nextToken());
    URL url = new URL(tok.nextToken());
    return new SimpleList(quality, offset, length, url);
  }

  public Object clone()
  {
    return new CSPRNG();
  }

  public void setup(Map attrib)
  {
    List list = null;
    if (Configuration.DEBUG)
      log.fine("attrib=" + String.valueOf(attrib));
    try
      {
        list = (List) attrib.get(FILE_SOURCES);
        if (Configuration.DEBUG)
          log.fine("list=" + String.valueOf(list));
        if (list != null)
          {
            files.clear();
            for (Iterator it = list.iterator(); it.hasNext();)
              {
                List l = (List) it.next();
                if (Configuration.DEBUG)
                  log.fine("l=" + l);
                if (l.size() != 4)
                  {
                    if (Configuration.DEBUG)
                      log.fine("file list too small: " + l.size());
                    throw new IllegalArgumentException("invalid file list");
                  }
                Double quality = (Double) l.get(0);
                Integer offset = (Integer) l.get(1);
                Integer length = (Integer) l.get(2);
                String source = (String) l.get(3);
                files.add(new SimpleList(quality, offset, length, source));
              }
          }
      }
    catch (ClassCastException cce)
      {
        if (Configuration.DEBUG)
          log.log(Level.FINE, "bad file list", cce);
        throw new IllegalArgumentException("invalid file list");
      }
    try
      {
        list = (List) attrib.get(URL_SOURCES);
        if (Configuration.DEBUG)
          log.fine("list=" + String.valueOf(list));
        if (list != null)
          {
            urls.clear();
            for (Iterator it = list.iterator(); it.hasNext();)
              {
                List l = (List) it.next();
                if (Configuration.DEBUG)
                  log.fine("l=" + l);
                if (l.size() != 4)
                  {
                    if (Configuration.DEBUG)
                      log.fine("URL list too small: " + l.size());
                    throw new IllegalArgumentException("invalid URL list");
                  }
                Double quality = (Double) l.get(0);
                Integer offset = (Integer) l.get(1);
                Integer length = (Integer) l.get(2);
                URL source = (URL) l.get(3);
                urls.add(new SimpleList(quality, offset, length, source));
              }
          }
      }
    catch (ClassCastException cce)
      {
        if (Configuration.DEBUG)
          log.log(Level.FINE, "bad URL list", cce);
        throw new IllegalArgumentException("invalid URL list");
      }
    try
      {
        list = (List) attrib.get(PROGRAM_SOURCES);
        if (Configuration.DEBUG)
          log.fine("list=" + String.valueOf(list));
        if (list != null)
          {
            progs.clear();
            for (Iterator it = list.iterator(); it.hasNext();)
              {
                List l = (List) it.next();
                if (Configuration.DEBUG)
                  log.fine("l=" + l);
                if (l.size() != 4)
                  {
                    if (Configuration.DEBUG)
                      log.fine("program list too small: " + l.size());
                    throw new IllegalArgumentException("invalid program list");
                  }
                Double quality = (Double) l.get(0);
                Integer offset = (Integer) l.get(1);
                Integer length = (Integer) l.get(2);
                String source = (String) l.get(3);
                progs.add(new SimpleList(quality, offset, length, source));
              }
          }
      }
    catch (ClassCastException cce)
      {
        if (Configuration.DEBUG)
          log.log(Level.FINE, "bad program list", cce);
        throw new IllegalArgumentException("invalid program list");
      }
    try
      {
        list = (List) attrib.get(OTHER_SOURCES);
        if (Configuration.DEBUG)
          log.fine("list=" + String.valueOf(list));
        if (list != null)
          {
            other.clear();
            for (Iterator it = list.iterator(); it.hasNext();)
              {
                EntropySource src = (EntropySource) it.next();
                if (Configuration.DEBUG)
                  log.fine("src=" + src);
                if (src == null)
                  throw new NullPointerException("null source in source list");
                other.add(src);
              }
          }
      }
    catch (ClassCastException cce)
      {
        throw new IllegalArgumentException("invalid source list");
      }

    try
      {
        Boolean block = (Boolean) attrib.get(BLOCKING);
        if (block != null)
          blocking = block.booleanValue();
        else
          blocking = true;
      }
    catch (ClassCastException cce)
      {
        throw new IllegalArgumentException("invalid blocking parameter");
      }
    poller = new Poller(files, urls, progs, other, this);
    try
      {
        fillBlock();
      }
    catch (LimitReachedException lre)
      {
        throw new RuntimeException("bootstrapping CSPRNG failed");
      }
  }

  public void fillBlock() throws LimitReachedException
  {
    if (Configuration.DEBUG)
      log.fine("fillBlock");
    if (getQuality() < 100.0)
      {
        if (Configuration.DEBUG)
          log.fine("doing slow poll");
        slowPoll();
      }
    do
      {
        fastPoll();
        mixRandomPool();
      }
    while (mixCount < MIX_COUNT);
    if (! x917init || x917count >= X917_LIFETIME)
      {
        mixRandomPool(pool);
        Map attr = new HashMap();
        byte[] key = new byte[32];
        System.arraycopy(pool, 0, key, 0, 32);
        cipher.reset();
        attr.put(IBlockCipher.KEY_MATERIAL, key);
        try
          {
            cipher.init(attr);
          }
        catch (InvalidKeyException ike)
          {
            throw new Error(ike.toString());
          }
        mixRandomPool(pool);
        generateX917(pool);
        mixRandomPool(pool);
        generateX917(pool);
        if (x917init)
          quality = 0.0;
        x917init = true;
        x917count = 0;
      }
    byte[] export = new byte[ALLOC_SIZE];
    for (int i = 0; i < ALLOC_SIZE; i++)
      export[i] = (byte)(pool[i] ^ 0xFF);
    mixRandomPool();
    mixRandomPool(export);
    generateX917(export);
    for (int i = 0; i < OUTPUT_SIZE; i++)
      buffer[i] = (byte)(export[i] ^ export[i + OUTPUT_SIZE]);
    Arrays.fill(export, (byte) 0);
  }

  /**
   * Add an array of bytes into the randomness pool. Note that this method will
   * not increment the pool's quality counter (this can only be done via
   * a source provided to the setup method).
   *
   * @param buf The byte array.
   * @param off The offset from whence to start reading bytes.
   * @param len The number of bytes to add.
   * @throws ArrayIndexOutOfBoundsException If off or len are
   *           out of the range of buf.
   */
  public synchronized void addRandomBytes(byte[] buf, int off, int len)
  {
    if (off < 0 || len < 0 || off + len > buf.length)
      throw new ArrayIndexOutOfBoundsException();
    if (Configuration.DEBUG)
      {
        log.fine("adding random bytes:");
        log.fine(Util.toString(buf, off, len));
      }
    final int count = off + len;
    for (int i = off; i < count; i++)
      {
        pool[index++] ^= buf[i];
        if (index == pool.length)
          {
            mixRandomPool();
            index = 0;
          }
      }
  }

  /**
   * Add a single random byte to the randomness pool. Note that this method will
   * not increment the pool's quality counter (this can only be done via
   * a source provided to the setup method).
   *
   * @param b The byte to add.
   */
  public synchronized void addRandomByte(byte b)
  {
    if (Configuration.DEBUG)
      log.fine("adding byte " + Integer.toHexString(b));
    pool[index++] ^= b;
    if (index >= pool.length)
      {
        mixRandomPool();
        index = 0;
      }
  }

  synchronized void addQuality(double quality)
  {
    if (Configuration.DEBUG)
      log.fine("adding quality " + quality);
    if (this.quality < 100)
      this.quality += quality;
    if (Configuration.DEBUG)
      log.fine("quality now " + this.quality);
  }

  synchronized double getQuality()
  {
    return quality;
  }

  /**
   * The mix operation. This method will, for every 20-byte block in the random
   * pool, hash that block, the previous 20 bytes, and the next 44 bytes with
   * SHA-1, writing the result back into that block.
   */
  private void mixRandomPool(byte[] buf)
  {
    int hashSize = hash.hashSize();
    for (int i = 0; i < buf.length; i += hashSize)
      {
        // First update the bytes [p-19..p-1].
        if (i == 0)
          hash.update(buf, buf.length - hashSize, hashSize);
        else
          hash.update(buf, i - hashSize, hashSize);
        // Now the next 64 bytes.
        if (i + 64 < buf.length)
          hash.update(buf, i, 64);
        else
          {
            hash.update(buf, i, buf.length - i);
            hash.update(buf, 0, 64 - (buf.length - i));
          }
        byte[] digest = hash.digest();
        System.arraycopy(digest, 0, buf, i, hashSize);
      }
  }

  private void mixRandomPool()
  {
    mixRandomPool(pool);
    mixCount++;
  }

  private void generateX917(byte[] buf)
  {
    int off = 0;
    for (int i = 0; i < buf.length; i += X917_POOL_SIZE)
      {
        int copy = Math.min(buf.length - i, X917_POOL_SIZE);
        for (int j = 0; j < copy; j++)
          x917pool[j] ^= pool[off + j];
        cipher.encryptBlock(x917pool, 0, x917pool, 0);
        System.arraycopy(x917pool, 0, buf, off, copy);
        cipher.encryptBlock(x917pool, 0, x917pool, 0);
        off += copy;
        x917count++;
      }
  }

  /**
   * Add random data always immediately available into the random pool, such as
   * the values of the eight asynchronous counters, the current time, the
   * current memory usage, the calling thread name, and the current stack trace.
   *

   * This method does not alter the quality counter, and is provided more to
   * maintain randomness, not to seriously improve the current random state.
   */
  private void fastPoll()
  {
    byte b = 0;
    for (int i = 0; i < SPINNER_COUNT; i++)
      b ^= SPINNERS[i].counter;
    addRandomByte(b);
    addRandomByte((byte) System.currentTimeMillis());
    addRandomByte((byte) Runtime.getRuntime().freeMemory());
    String s = Thread.currentThread().getName();
    if (s != null)
      {
        byte[] buf = s.getBytes();
        addRandomBytes(buf, 0, buf.length);
      }
    ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
    PrintStream pout = new PrintStream(bout);
    Throwable t = new Throwable();
    t.printStackTrace(pout);
    pout.flush();
    byte[] buf = bout.toByteArray();
    addRandomBytes(buf, 0, buf.length);
  }

  private void slowPoll() throws LimitReachedException
  {
    if (Configuration.DEBUG)
      log.fine("poller is alive? "
               + (pollerThread == null ? false : pollerThread.isAlive()));
    if (pollerThread == null || ! pollerThread.isAlive())
      {
        boolean interrupted = false;
        pollerThread = new Thread(poller);
        pollerThread.setDaemon(true);
        pollerThread.setPriority(Thread.NORM_PRIORITY - 1);
        pollerThread.start();
        if (blocking)
          try
            {
              pollerThread.join();
            }
          catch (InterruptedException ie)
            {
              interrupted = true;
            }
        // If the full slow poll has completed after we waited for it,
        // and there in insufficient randomness, throw an exception.
        if (! interrupted && blocking && quality < 100.0)
          {
            if (Configuration.DEBUG)
              log.fine("insufficient quality: " + quality);
            throw new LimitReachedException("insufficient randomness was polled");
          }
      }
  }

  protected void finalize() throws Throwable
  {
    if (poller != null && pollerThread != null && pollerThread.isAlive())
      {
        pollerThread.interrupt();
        poller.stopUpdating();
        pollerThread.interrupt();
      }
    Arrays.fill(pool, (byte) 0);
    Arrays.fill(x917pool, (byte) 0);
    Arrays.fill(buffer, (byte) 0);
  }

  /**
   * A simple thread that constantly updates a byte counter. This class is used
   * in a group of lowest-priority threads and the values of their counters
   * (updated in competition with all other threads) is used as a source of
   * entropy bits.
   */
  private static class Spinner
      implements Runnable
  {
    protected byte counter;

    private Spinner()
    {
    }

    public void run()
    {
      while (true)
        {
          counter++;
          try
            {
              Thread.sleep(100);
            }
          catch (InterruptedException ie)
            {
            }
        }
    }
  }

  private final class Poller
      implements Runnable
  {
    private final List files;
    private final List urls;
    private final List progs;
    private final List other;
    private final CSPRNG pool;
    private boolean running;

    Poller(List files, List urls, List progs, List other, CSPRNG pool)
    {
      super();
      this.files = Collections.unmodifiableList(files);
      this.urls = Collections.unmodifiableList(urls);
      this.progs = Collections.unmodifiableList(progs);
      this.other = Collections.unmodifiableList(other);
      this.pool = pool;
    }

    public void run()
    {
      running = true;
      if (Configuration.DEBUG)
        {
          log.fine("files: " + files);
          log.fine("URLs: " + urls);
          log.fine("progs: " + progs);
        }
      Iterator files_it = files.iterator();
      Iterator urls_it = urls.iterator();
      Iterator prog_it = progs.iterator();
      Iterator other_it = other.iterator();

      while (files_it.hasNext() || urls_it.hasNext() || prog_it.hasNext()
             || other_it.hasNext())
        {
          // There is enough random data. Go away.
          if (pool.getQuality() >= 100.0 || ! running)
            return;
          if (files_it.hasNext())
            try
              {
                List l = (List) files_it.next();
                if (Configuration.DEBUG)
                  log.fine(l.toString());
                double qual = ((Double) l.get(0)).doubleValue();
                int offset = ((Integer) l.get(1)).intValue();
                int count = ((Integer) l.get(2)).intValue();
                String src = (String) l.get(3);
                InputStream in = new FileInputStream(src);
                byte[] buf = new byte[count];
                if (offset > 0)
                  in.skip(offset);
                int len = in.read(buf);
                if (len >= 0)
                  {
                    pool.addRandomBytes(buf, 0, len);
                    pool.addQuality(qual * ((double) len / (double) count));
                  }
                if (Configuration.DEBUG)
                  log.fine("got " + len + " bytes from " + src);
              }
            catch (Exception x)
              {
                if (Configuration.DEBUG)
                  log.throwing(this.getClass().getName(), "run", x);
              }
          if (pool.getQuality() >= 100.0 || ! running)
            return;
          if (urls_it.hasNext())
            try
              {
                List l = (List) urls_it.next();
                if (Configuration.DEBUG)
                  log.fine(l.toString());
                double qual = ((Double) l.get(0)).doubleValue();
                int offset = ((Integer) l.get(1)).intValue();
                int count = ((Integer) l.get(2)).intValue();
                URL src = (URL) l.get(3);
                InputStream in = src.openStream();
                byte[] buf = new byte[count];
                if (offset > 0)
                  in.skip(offset);
                int len = in.read(buf);
                if (len >= 0)
                  {
                    pool.addRandomBytes(buf, 0, len);
                    pool.addQuality(qual * ((double) len / (double) count));
                  }
                if (Configuration.DEBUG)
                  log.fine("got " + len + " bytes from " + src);
              }
            catch (Exception x)
              {
                if (Configuration.DEBUG)
                  log.throwing(this.getClass().getName(), "run", x);
              }
          if (pool.getQuality() >= 100.0 || ! running)
            return;
          Process proc = null;
          if (prog_it.hasNext())
            try
              {
                List l = (List) prog_it.next();
                if (Configuration.DEBUG)
                  log.finer(l.toString());
                double qual = ((Double) l.get(0)).doubleValue();
                int offset = ((Integer) l.get(1)).intValue();
                int count = ((Integer) l.get(2)).intValue();
                String src = (String) l.get(3);
                proc = null;
                proc = Runtime.getRuntime().exec(src);
                InputStream in = proc.getInputStream();
                byte[] buf = new byte[count];
                if (offset > 0)
                  in.skip(offset);
                int len = in.read(buf);
                if (len >= 0)
                  {
                    pool.addRandomBytes(buf, 0, len);
                    pool.addQuality(qual * ((double) len / (double) count));
                  }
                proc.destroy();
                proc.waitFor();
                if (Configuration.DEBUG)
                  log.fine("got " + len + " bytes from " + src);
              }
            catch (Exception x)
              {
                if (Configuration.DEBUG)
                  log.throwing(this.getClass().getName(), "run", x);
                try
                  {
                    if (proc != null)
                      {
                        proc.destroy();
                        proc.waitFor();
                      }
                  }
                catch (Exception ignored)
                  {
                  }
              }
          if (pool.getQuality() >= 100.0 || ! running)
            return;
          if (other_it.hasNext())
            try
              {
                EntropySource src = (EntropySource) other_it.next();
                byte[] buf = src.nextBytes();
                if (pool == null)
                  return;
                pool.addRandomBytes(buf, 0, buf.length);
                pool.addQuality(src.quality());
                if (Configuration.DEBUG)
                  log.fine("got " + buf.length + " bytes from " + src);
              }
            catch (Exception x)
              {
                if (Configuration.DEBUG)
                  log.throwing(this.getClass().getName(), "run", x);
              }
        }
    }

    public void stopUpdating()
    {
      running = false;
    }
  }
}


text:
module RuboCop
  module Git
    class DiffParser
      class << self
        def parse(diff)
          new.parse(diff)
        end
      end

      def parse(diff)
        files    = []
        in_patch = false

        diff.each_line do |line|
          case line
          when /^diff --git/
            in_patch = false
          when %r{^\+{3} b/(?<path>[^\t\n\r]+)}
            files << PseudoResource.new(Regexp.last_match[:path])
          when /^@@/
            in_patch = true
          end

          files.last.patch << line if in_patch
        end

        files
      end
    end
  end
end


text:
using FluentAssertions;
using System;
using Toggl.Shared.Extensions;
using Xunit;

namespace Toggl.Shared.Tests
{
    public sealed class ClampExtensionTests
    {
        public abstract class TheClampMethodTest<T> where T : IComparable
        {
            public abstract T Min { get; }
            public abstract T Max { get; }

            public abstract T NumInInterval { get; }
            public abstract T NumLessThanMin { get; }
            public abstract T NumGreaterThanMax { get; }

            [Fact, LogIfTooSlow]
            public void ReturnsMinIfValueIsLessThanMin()
                => NumLessThanMin.Clamp(Min, Max).Should().Be(Min);

            [Fact, LogIfTooSlow]
            public void ReturnsMaxIfValueIsGreaterThanMax()
                => NumGreaterThanMax.Clamp(Min, Max).Should().Be(Max);

            [Fact, LogIfTooSlow]
            public void ReturnsTheSameValueIfValueIsInInterval()
                => NumInInterval.Clamp(Min, Max).Should().Be(NumInInterval);
        }

        public sealed class ClampIntTests : TheClampMethodTest<int>
        {
            public override int Min => 10;
            public override int Max => 20;
            public override int NumInInterval => 15;
            public override int NumLessThanMin => 5;
            public override int NumGreaterThanMax => 25;
        }

        public sealed class ClampFloatTests : TheClampMethodTest<float>
        {
            public override float Min => 12.45f;
            public override float Max => 24.898f;
            public override float NumInInterval => 19.999f;
            public override float NumLessThanMin => -20.1f;
            public override float NumGreaterThanMax => 1000.123f;
        }
    }
}