text:
import { SkyNumericService } from './numeric.service';
import { CurrencyPipe, DecimalPipe } from '@angular/common';
import { NumericOptions} from './numeric.options';

let skyNumeric = new SkyNumericService(new CurrencyPipe('en-US'), new DecimalPipe('en-US'));

describe('formatNumber', () => {

  it('formats 0 with 0 digits as 0', () => {
    const value = 0;
    let options = new NumericOptions();
    options.digits = 0;

    expect(skyNumeric.formatNumber(value, options)).toBe('0');
  });

  it('formats 100 with 0 digits as 100', () => {
    const value = 100;
    let options = new NumericOptions();
    options.digits = 0;

    expect(skyNumeric.formatNumber(value, options)).toBe('100');
  });

  it('formats 1000 with 0 digits as 1K', () => {
    const value = 1000;
    let options = new NumericOptions();
    options.digits = 0;
    expect(skyNumeric.formatNumber(value, options)).toBe('1K');
  });

  it('formats 1000000 with 0 digits as 1M', () => {
    const value = 1000000;
    let options = new NumericOptions();
    options.digits = 0;
    expect(skyNumeric.formatNumber(value, options)).toBe('1M');
  });

  it('formats 1000000000 with 0 digits as 1B', () => {
    const value = 1000000000;
    let options = new NumericOptions();
    options.digits = 0;
    expect(skyNumeric.formatNumber(value, options)).toBe('1B');
  });

  it('formats 1000000000000 with 0 digits as 1T', () => {
    const value = 1000000000000;
    let options = new NumericOptions();
    options.digits = 0;
    expect(skyNumeric.formatNumber(value, options)).toBe('1T');
  });

  it('formats 999000000 as 999M', () => {
    const value = 999000000;
    let options = new NumericOptions();
    options.digits = 2;
    expect(skyNumeric.formatNumber(value, options)).toBe('999M');
  });

  it('formats 1234000 with 2 digits as 1.23M', () => {
    const value = 1234000;
    let options = new NumericOptions();
    options.digits = 2;
    expect(skyNumeric.formatNumber(value, options)).toBe('1.23M');
  });

  it('formats 1235000 with 2 digits as 1.24M', () => {
    const value = 1235000;
    let options = new NumericOptions();
    options.digits = 2;
    expect(skyNumeric.formatNumber(value, options)).toBe('1.24M');
  });

  it('formats 1450 with 1 digits as 1.5K', () => {
    const value = 1450;
    let options = new NumericOptions();
    options.digits = 1;
    expect(skyNumeric.formatNumber(value, options)).toBe('1.5K');
  });

  it('formats 1000 as US dollar with 0 digits as $1K', () => {
    const value = 1000;
    let options = new NumericOptions();
    options.digits = 0;
    options.iso = 'USD';
    options.format = 'currency';
    expect(skyNumeric.formatNumber(value, options)).toBe('$1K');
  });

  it('formats 1450 as US dollar with 1 digits as $1.5K', () => {
    const value = 1450;
    let options = new NumericOptions();
    options.digits = 1;
    options.iso = 'USD';
    options.format = 'currency';
    expect(skyNumeric.formatNumber(value, options)).toBe('$1.5K');
  });

  it('formats 1500 as Euro with 1 digits as €1.5K', () => {
    const value = 1500;
    let options = new NumericOptions();
    options.digits = 1;
    options.iso = 'EUR';
    options.format = 'currency';
    expect(skyNumeric.formatNumber(value, options)).toBe('€1.5K');
  });

  it('formats 15.50 as Pounds with 2 digits as £15.50', () => {
    const value = 15.50;
    let options = new NumericOptions();
    options.digits = 2;
    options.iso = 'GBP';
    options.format = 'currency';
    expect(skyNumeric.formatNumber(value, options)).toBe('£15.50');
  });
  // Adjusting test to expect either format of a negative.  MS browsers use system's Region
  // setting for Currency formatting.  For Negative currency, the windows default is parentheses
  // around the number. All other browsers use a preceeding negative sign (-).
  it('formats -15.50 as US dollar with 2 digits as -$15.50', () => {
    const value = -15.50;
    let options = new NumericOptions();
    options.digits = 2;
    options.iso = 'USD';
    options.format = 'currency';
    expect('-$15.50 ($15.50)').toContain(skyNumeric
    .formatNumber(value, options));
  });

  it('formats 145.45 with 1 digits as 145.5', () => {
    const value = 145.45;
    let options = new NumericOptions();
    options.digits = 1;
    expect(skyNumeric.formatNumber(value, options)).toBe('145.5');
  });

  it('formats 1.2345 with 3 digits as 1.235', () => {
    const value = 1.2345;
    let options = new NumericOptions();
    options.digits = 3;
    expect(skyNumeric.formatNumber(value, options)).toBe('1.235');
  });

});


text:
<!--
 Copyright 2020 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<AssignMessage name="AM.SetScope">
    <AssignVariable>
        <Name>gcp.scopes</Name>
        <Value>profile</Value>
    </AssignVariable>
    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
</AssignMessage>

redpajama_set_name: RedPajamaGithub


text:
package me.lucko.luckperms.commands.misc;

import me.lucko.luckperms.LuckPermsPlugin;
import me.lucko.luckperms.commands.CommandResult;
import me.lucko.luckperms.commands.Sender;
import me.lucko.luckperms.commands.SingleMainCommand;
import me.lucko.luckperms.constants.Message;
import me.lucko.luckperms.constants.Permission;
import me.lucko.luckperms.core.LPConfiguration;

import java.util.List;

import static me.lucko.luckperms.commands.Util.formatBoolean;

public class InfoCommand extends SingleMainCommand {
    public InfoCommand() {
        super("Info", "/%s info", 0, Permission.INFO);
    }

    @Override
    protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List<String> args, String label) {
        final LPConfiguration c = plugin.getConfiguration();
        Message.INFO.send(sender,
                plugin.getVersion(),
                plugin.getDatastore().getName(),
                c.getServer(),
                c.getSyncTime(),
                formatBoolean(c.getIncludeGlobalPerms()),
                formatBoolean(c.getOnlineMode()),
                formatBoolean(c.getApplyWildcards()),
                formatBoolean(c.getApplyRegex()),
                formatBoolean(c.getApplyShorthand())
        );

        return CommandResult.SUCCESS;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <!--<start id="interfaceBasedAssembler"/>-->
  <bean id="assembler"
	    class="org.springframework.jmx.export.assembler.InterfaceBasedMBeanInfoAssembler"
    p:managedInterfaces=
                   "com.habuma.spitter.jmx.HomeControllerManagedOperations"
  />
  <!--<end id="interfaceBasedAssembler"/>-->
</beans>


text:
title:  Podnety na zamyslenie
date:  18/11/2022
---

V knihe Skutky apoštolov si prečítajte kapitoly "Listy Tesaloničanom" (AA 255–268; SA 155–162) a "Vznešený cieľ" (AA 319–322; SA 191–193).

Filozof Stephen Cave napísal: "Rimania si boli dobre vedomí viery kresťanov, že jedného dňa budú vzkriesení. Zo všetkých síl sa preto tejto nádeji vysmievali a kládli jej prekážky. Správa o prenasledovaní v Galii v roku 177 uvádza, že mučeníci boli najskôr popravení, potom ich mŕtvoly nechali šesť dní hniť nepochované a potom boli spálené a popol hodený do rieky Rhôna. Teraz uvidíme, či opäť povstanú, povedali údajne Rimania." (CAVE, Stephen, Immortality, The Quest to Live Forever and How It Drives Civilization. New York, Crown Publishers, 2012, p. 104, 105)

Toto malé podobenstvo o teologickom skepticizme, akokoľvek dramatické, je nepodstatné. Nič totiž nedokázalo o biblickom zasľúbení vzkriesenia. Moc, ktorá vzkriesila Ježiša z mŕtvych, môže vykonať to isté aj pre nás, bez ohľadu na stav nášho tela. Veď napokon, ak tá istá moc stvorila a udržiavala celý vesmír, určite dokáže premeniť živých a vzkriesiť mŕtvych.

"Pavol napísal: Tak Boh aj tých, čo zosnuli skrze Ježiša, privedie s ním. (1 Tes 4,14) Mnohí tieto slová chápu v tom zmysle, že mŕtvych privedie Kristus z neba. Pavol tým však myslel spôsob: ako bol Kristus vzkriesený z mŕtvych, tak Boh povolá zosnulých svätých z ich hrobov a vezme ich so sebou do neba. Aká to skvelá útecha! Aká jedinečná nádej nielen pre tesalonických veriacich, ale pre všetkých kresťanov, nech žijú kdekoľvek! (AA 259; SA 157)

**Námety na spoločné uvažovanie**

`Ktosi raz napísal: "Smrť nás úplne vyhladí. ... Byť úplne vymazaný, bez stopy a pamiatky, vedie k zničeniu zmyslu života človeka." Ten výrok má pravdu. Akú nádej teda máme tvárou v tvár takejto bezvýznamnosti?`

`Ako môžeme zosúladiť potrebu rastu k dokonalosti (Flp 3,12–16) so skutočnosťou, že až pri Kristovom druhom príchode dostaneme neporušiteľnú a bezhriešnu prirodzenosť (1Kor 15,50–55)?`

`Ako by sme mohli pomôcť niekomu, kto je nadšený myšlienkou "tajného vytrhnutia", aby pochopil, že toto učenie je nesprávne?`

`Prečítajte si ešte raz text 1Kor 15,12–19. Čo v týchto veršoch predstavuje silný dôkaz učenia, že mŕtvi spia a nie sú v nebi s Ježišom? Aký zmysel by mali tieto verše, ak by spravodliví mŕtvi boli skutočne v nebi s Ježišom?`

Západ slnka: 16.01

---

#### Dodatečné otázky k diskuzi

`Našel jsi nějakou zajímavou myšlenku během studia v uplynulém týdnu? Čím tě oslovila?`

`Jak reaguješ, když se lidé smějí tvé víře ve vzkříšení?`

`Co tě nejvíc motivuje v tom, abys dále věřil ve vzkříšení k věčnému životu?`

`Která myšlenka tě naší diskuze nejvíc zaujala? Proč právě tato?`


text:
package com.ipastushenko.core.service;

import com.ipastushenko.core.service.exception.ServiceException;
import org.apache.log4j.Logger;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

/**
 * service for sends emails
 */
public class EmailService {
    private static final Logger log = Logger.getLogger(EmailService.class.getName());
    private MailSender mailSender;

    public void sendMail(String from, String to, String subject, String body) throws ServiceException {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(body);
        try {
            mailSender.send(message);
        } catch (MailException e) {
            log.error("Email did send", e);
            throw new ServiceException("Email did send");
        }
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }
}


text:
Serfnode deployer
=================

Deploy [serfnodes](http://github.com/waltermoreira/serfnode) via
ansible playbooks.

Quickstart
----------

- Create local alias with:
  ```
  $ eval $(docker run adama/serfnode-deployer /alias)
  ```

- Define `hosts`, `{host,group}_vars`, `roles/`, and playbook as usual
  for ansible. `serfnode-deployer` includes the role `serfnode` which
  deploys those kind of containers. Then run:
  ```
  $ serfnode-deployer my-playbook.yml
  ```

Build from source
-----------------

Clone this repository.

Pull [doit_in_docker](http://github.com/waltermoreira/doit_in_docker)
and execute:

```
$ eval $(docker run waltermoreira/doit_in_docker /alias)
$ cd serfnode-deployer
$ doit_in_docker doit
```


text:
import {join} from 'path';
import {pathToFileURL} from 'url';

import asyncLib from 'neo-async';

import ModuleDependency from 'webpack/lib/dependencies/ModuleDependency';
import NullDependency from 'webpack/lib/dependencies/NullDependency';
import Template from 'webpack/lib/Template';
import {
  sources,
  WebpackError,
  Compilation,
  AsyncDependenciesBlock,
} from 'webpack';

import isArray from 'shared/isArray';

class ClientReferenceDependency extends ModuleDependency {
  constructor(request) {
    super(request);
  }

  get type() {
    return 'client-reference';
  }
}

// This is the module that will be used to anchor all client references to.
// I.e. it will have all the client files as async deps from this point on.
// We use the Flight client implementation because you can't get to these
// without the client runtime so it's the first time in the loading sequence
// you might want them.
const clientImportName = 'react-server-dom-webpack';
const clientFileName = require.resolve('../');

type ClientReferenceSearchPath = {
  directory: string,
  recursive?: boolean,
  include: RegExp,
  exclude?: RegExp,
};

type ClientReferencePath = string | ClientReferenceSearchPath;

type Options = {
  isServer: boolean,
  clientReferences?: ClientReferencePath | $ReadOnlyArray<ClientReferencePath>,
  chunkName?: string,
  manifestFilename?: string,
};

const PLUGIN_NAME = 'React Server Plugin';

export default class ReactFlightWebpackPlugin {
  clientReferences: $ReadOnlyArray<ClientReferencePath>;
  chunkName: string;
  manifestFilename: string;

  constructor(options: Options) {
    if (!options || typeof options.isServer !== 'boolean') {
      throw new Error(
        PLUGIN_NAME + ': You must specify the isServer option as a boolean.',
      );
    }
    if (options.isServer) {
      throw new Error('TODO: Implement the server compiler.');
    }
    if (!options.clientReferences) {
      this.clientReferences = [
        {
          directory: '.',
          recursive: true,
          include: /\.client\.(js|ts|jsx|tsx)$/,
        },
      ];
    } else if (
      typeof options.clientReferences === 'string' ||
      !isArray(options.clientReferences)
    ) {
      this.clientReferences = [(options.clientReferences: $FlowFixMe)];
    } else {
      this.clientReferences = options.clientReferences;
    }
    if (typeof options.chunkName === 'string') {
      this.chunkName = options.chunkName;
      if (!/\[(index|request)\]/.test(this.chunkName)) {
        this.chunkName += '[index]';
      }
    } else {
      this.chunkName = 'client[index]';
    }
    this.manifestFilename =
      options.manifestFilename || 'react-client-manifest.json';
  }

  apply(compiler: any) {
    const _this = this;
    let resolvedClientReferences;
    let clientFileNameFound = false;

    // Find all client files on the file system
    compiler.hooks.beforeCompile.tapAsync(
      PLUGIN_NAME,
      ({contextModuleFactory}, callback) => {
        const contextResolver = compiler.resolverFactory.get('context', {});

        _this.resolveAllClientFiles(
          compiler.context,
          contextResolver,
          compiler.inputFileSystem,
          contextModuleFactory,
          function(err, resolvedClientRefs) {
            if (err) {
              callback(err);
              return;
            }

            resolvedClientReferences = resolvedClientRefs;
            callback();
          },
        );
      },
    );

    compiler.hooks.thisCompilation.tap(
      PLUGIN_NAME,
      (compilation, {normalModuleFactory}) => {
        compilation.dependencyFactories.set(
          ClientReferenceDependency,
          normalModuleFactory,
        );
        compilation.dependencyTemplates.set(
          ClientReferenceDependency,
          new NullDependency.Template(),
        );

        const handler = parser => {
          // We need to add all client references as dependency of something in the graph so
          // Webpack knows which entries need to know about the relevant chunks and include the
          // map in their runtime. The things that actually resolves the dependency is the Flight
          // client runtime. So we add them as a dependency of the Flight client runtime.
          // Anything that imports the runtime will be made aware of these chunks.
          parser.hooks.program.tap(PLUGIN_NAME, () => {
            const module = parser.state.module;

            if (module.resource !== clientFileName) {
              return;
            }

            clientFileNameFound = true;

            if (resolvedClientReferences) {
              for (let i = 0; i < resolvedClientReferences.length; i++) {
                const dep = resolvedClientReferences[i];

                const chunkName = _this.chunkName
                  .replace(/\[index\]/g, '' + i)
                  .replace(/\[request\]/g, Template.toPath(dep.userRequest));

                const block = new AsyncDependenciesBlock(
                  {
                    name: chunkName,
                  },
                  null,
                  dep.request,
                );

                block.addDependency(dep);
                module.addBlock(block);
              }
            }
          });
        };

        normalModuleFactory.hooks.parser
          .for('javascript/auto')
          .tap('HarmonyModulesPlugin', handler);

        normalModuleFactory.hooks.parser
          .for('javascript/esm')
          .tap('HarmonyModulesPlugin', handler);

        normalModuleFactory.hooks.parser
          .for('javascript/dynamic')
          .tap('HarmonyModulesPlugin', handler);
      },
    );

    compiler.hooks.make.tap(PLUGIN_NAME, compilation => {
      compilation.hooks.processAssets.tap(
        {
          name: PLUGIN_NAME,
          stage: Compilation.PROCESS_ASSETS_STAGE_REPORT,
        },
        function() {
          if (clientFileNameFound === false) {
            compilation.warnings.push(
              new WebpackError(
                `Client runtime at ${clientImportName} was not found. React Server Components module map file ${_this.manifestFilename} was not created.`,
              ),
            );
            return;
          }

          const json = {};
          compilation.chunkGroups.forEach(function(chunkGroup) {
            const chunkIds = chunkGroup.chunks.map(function(c) {
              return c.id;
            });

            function recordModule(id, module) {
              // TODO: Hook into deps instead of the target module.
              // That way we know by the type of dep whether to include.
              // It also resolves conflicts when the same module is in multiple chunks.

              if (!/\.client\.(js|ts)x?$/.test(module.resource)) {
                return;
              }

              const moduleProvidedExports = compilation.moduleGraph
                .getExportsInfo(module)
                .getProvidedExports();

              const moduleExports = {};
              ['', '*']
                .concat(
                  Array.isArray(moduleProvidedExports)
                    ? moduleProvidedExports
                    : [],
                )
                .forEach(function(name) {
                  moduleExports[name] = {
                    id,
                    chunks: chunkIds,
                    name: name,
                  };
                });
              const href = pathToFileURL(module.resource).href;

              if (href !== undefined) {
                json[href] = moduleExports;
              }
            }

            chunkGroup.chunks.forEach(function(chunk) {
              const chunkModules = compilation.chunkGraph.getChunkModulesIterable(
                chunk,
              );

              Array.from(chunkModules).forEach(function(module) {
                const moduleId = compilation.chunkGraph.getModuleId(module);

                recordModule(moduleId, module);
                // If this is a concatenation, register each child to the parent ID.
                if (module.modules) {
                  module.modules.forEach(concatenatedMod => {
                    recordModule(moduleId, concatenatedMod);
                  });
                }
              });
            });
          });

          const output = JSON.stringify(json, null, 2);
          compilation.emitAsset(
            _this.manifestFilename,
            new sources.RawSource(output, false),
          );
        },
      );
    });
  }

  // This attempts to replicate the dynamic file path resolution used for other wildcard
  // resolution in Webpack is using.
  resolveAllClientFiles(
    context: string,
    contextResolver: any,
    fs: any,
    contextModuleFactory: any,
    callback: (
      err: null | Error,
      result?: $ReadOnlyArray<ClientReferenceDependency>,
    ) => void,
  ) {
    asyncLib.map(
      this.clientReferences,
      (
        clientReferencePath: string | ClientReferenceSearchPath,
        cb: (
          err: null | Error,
          result?: $ReadOnlyArray<ClientReferenceDependency>,
        ) => void,
      ): void => {
        if (typeof clientReferencePath === 'string') {
          cb(null, [new ClientReferenceDependency(clientReferencePath)]);
          return;
        }
        const clientReferenceSearch: ClientReferenceSearchPath = clientReferencePath;
        contextResolver.resolve(
          {},
          context,
          clientReferencePath.directory,
          {},
          (err, resolvedDirectory) => {
            if (err) return cb(err);
            const options = {
              resource: resolvedDirectory,
              resourceQuery: '',
              recursive:
                clientReferenceSearch.recursive === undefined
                  ? true
                  : clientReferenceSearch.recursive,
              regExp: clientReferenceSearch.include,
              include: undefined,
              exclude: clientReferenceSearch.exclude,
            };
            contextModuleFactory.resolveDependencies(
              fs,
              options,
              (err2: null | Error, deps: Array<ModuleDependency>) => {
                if (err2) return cb(err2);
                const clientRefDeps = deps.map(dep => {
                  // use userRequest instead of request. request always end with undefined which is wrong
                  const request = join(resolvedDirectory, dep.userRequest);
                  const clientRefDep = new ClientReferenceDependency(request);
                  clientRefDep.userRequest = dep.userRequest;
                  return clientRefDep;
                });
                cb(null, clientRefDeps);
              },
            );
          },
        );
      },
      (
        err: null | Error,
        result: $ReadOnlyArray<$ReadOnlyArray<ClientReferenceDependency>>,
      ): void => {
        if (err) return callback(err);
        const flat = [];
        for (let i = 0; i < result.length; i++) {
          flat.push.apply(flat, result[i]);
        }
        callback(null, flat);
      },
    );
  }
}


text:
namespace SharpCompress.Compressors.Rar.UnpackV1.Decode
{
    internal static class PackDef
    {
        // 20171217 NOTE: these contants are gone from unrar src code
        // seems to be more dynamic
        public const int MAXWINSIZE = 0x400000;
        public const int MAXWINMASK = MAXWINSIZE - 1;

        public const uint MAX_LZ_MATCH = 0x1001;
        public const uint MAX3_LZ_MATCH = 0x101; // Maximum match length for RAR v3.
        public const int LOW_DIST_REP_COUNT = 16;

        public const int NC = 299; /* alphabet = {0, 1, 2, ..., NC - 1} */
        public const int DC = 60;
        public const int LDC = 17;
        public const int RC = 28;
        // 20171217: NOTE: these constants seem to have been updated in the unrar src code
        // at some unknown point.  updating causes decompression failure, not sure why.
        //        public const int NC    = 306; /* alphabet = {0, 1, 2, ..., NC - 1} */
        //        public const int DC    = 64;
        //        public const int LDC   = 16;
        //        public const int RC    = 44;
        public const int HUFF_TABLE_SIZE = NC + DC + RC + LDC;
        public const int BC = 20;

        public const uint NC30 = 299; /* alphabet = {0, 1, 2, ..., NC - 1} */
        public const uint DC30 = 60;
        public const uint LDC30 = 17;
        public const uint RC30 = 28;
        public const uint BC30 = 20;
        public const uint HUFF_TABLE_SIZE30 = NC30 + DC30 + RC30 + LDC30;

        public const int NC20 = 298; /* alphabet = {0, 1, 2, ..., NC - 1} */
        public const int DC20 = 48;
        public const int RC20 = 28;
        public const int BC20 = 19;
        public const int MC20 = 257;

        // Largest alphabet size among all values listed above.
        public const uint LARGEST_TABLE_SIZE = 306;

        //public enum {
        //    CODE_HUFFMAN, CODE_LZ, CODE_REPEATLZ, CODE_CACHELZ, CODE_STARTFILE,
        //    CODE_ENDFILE, CODE_FILTER, CODE_FILTERDATA
        //}
    }
}


text:
using System.Collections.Generic;
using UnityEngine;

namespace NodeCanvas.Framework.Internal{

	///The model used to serialize and deserialize graphs. This class serves no other purpose
	[System.Serializable]
	public class GraphSerializationData {

		private const float SERIALIZATION_VERSION = 2.6f;

		public float version;
		public System.Type type;
		public string name                      = string.Empty;
		public string comments                  = string.Empty;
		public Vector2 translation              = new Vector2(-5000, -5000);
		public float zoomFactor                 = 1f;
		public List<Node> nodes                 = new List<Node>();
		public List<Connection> connections     = new List<Connection>();
		public Node primeNode                   = null;
		public List<CanvasGroup> canvasGroups   = null;
		public BlackboardSource localBlackboard = null;

		public object derivedData;

		//required
		public GraphSerializationData(){}

		//Construct
		public GraphSerializationData(Graph graph){

			this.version         = SERIALIZATION_VERSION;
			this.type            = graph.GetType();
			// this.name            = graph.name;
			this.comments        = graph.graphComments;
			this.translation     = graph.translation;
			this.zoomFactor      = graph.zoomFactor;
			this.nodes           = graph.allNodes;
			this.canvasGroups    = graph.canvasGroups;
			this.localBlackboard = graph.localBlackboard;

			//connections are serialized seperately and not part of their parent node
			var structConnections = new List<Connection>();
			for (var i = 0; i < nodes.Count; i++){
				for (var j = 0; j < nodes[i].outConnections.Count; j++){
					structConnections.Add(nodes[i].outConnections[j]);
				}
			}

			this.connections = structConnections;
			this.primeNode   = graph.primeNode;

			//serialize derived data
			this.derivedData = graph.OnDerivedDataSerialization();
		}

		///MUST reconstruct before using the data
		public void Reconstruct(Graph graph){

			//check serialization versions here in the future if needed

			//re-link connections for deserialization
			for (var i = 0; i < this.connections.Count; i++){
				connections[i].sourceNode.outConnections.Add(connections[i]);
				connections[i].targetNode.inConnections.Add(connections[i]);
			}

			//re-set the node's owner and ID
			for (var i = 0; i < this.nodes.Count; i++){
				nodes[i].graph = graph;
				nodes[i].ID = i + 1;
			}

			//deserialize derived data
			graph.OnDerivedDataDeserialization(derivedData);
		}
	}
}


text:
#ifndef _JAVAJNI_H_INCLUDED_
#define _JAVAJNI_H_INCLUDED_

__APXBEGIN_DECLS

#define     APX_JVM_DESTROY 0x00000001

typedef struct stAPXJAVA_THREADARGS
{
    LPVOID      hJava;
    LPCSTR      szClassPath;
    LPCVOID     lpOptions;
    DWORD       dwMs;
    DWORD       dwMx;
    DWORD       dwSs;
    DWORD       bJniVfprintf;
    LPCSTR      szClassName;
    LPCSTR      szMethodName;
    LPCVOID     lpArguments;
    BOOL        setErrorOrOut;
    LPCWSTR     szStdErrFilename;
    LPCWSTR     szStdOutFilename;
} APXJAVA_THREADARGS, *LPAPXJAVA_THREADARGS;

APXHANDLE   apxCreateJava(APXHANDLE hPool, LPCWSTR szJvmDllPath);

BOOL        apxJavaInitialize(APXHANDLE hJava, LPCSTR szClassPath,
                              LPCVOID lpOptions, DWORD dwMs, DWORD dwMx,
                              DWORD dwSs, DWORD bJniVfprintf);
DWORD
apxJavaCmdInitialize(APXHANDLE hPool, LPCWSTR szClassPath, LPCWSTR szClass,
                     LPCWSTR szOptions, DWORD dwMs, DWORD dwMx,
                     DWORD dwSs, LPCWSTR szCmdArgs, LPWSTR **lppArray);

BOOL        apxJavaLoadMainClass(APXHANDLE hJava, LPCSTR szClassName,
                                 LPCSTR szMethodName,
                                 LPCVOID lpArguments);

BOOL        apxJavaStart(LPAPXJAVA_THREADARGS pArgs);

DWORD       apxJavaWait(APXHANDLE hJava, DWORD dwMilliseconds, BOOL bKill);

BOOL        apxJavaSetOut(APXHANDLE hJava, BOOL setErrorOrOut,
                          LPCWSTR szFilename);
DWORD       apxJavaSetOptions(APXHANDLE hJava, DWORD dwOptions);

BOOL        apxDestroyJvm(DWORD dwTimeout);

__APXEND_DECLS

#endif /* _JAVAJNI_H_INCLUDED_ */


text:
package com.github.terma.fastselect.data;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Representation of column of data.
 */
public interface Data {

    int STORAGE_FORMAT_VERSION = 1;

    int DEFAULT_SIZE = 16;

    int OBJECT_HEADER_BYTES = 16;
    int REFERENCE_BYTES = 8;
    int SHORT_BYTES = 2;
    int INT_BYTES = 4;
    int LONG_BYTES = 8;
    int DOUBLE_BYTES = 8;

    /**
     * @return - amount of bytes which column data will take in {@link FileChannel}
     */
    int getDiskSpace();

    /**
     * Opposite to {@link Data#load(String, ByteBuffer, int)}
     *

     * To save entire {@link com.github.terma.fastselect.FastSelect} use
     * {@link com.github.terma.fastselect.FastSelect#save(FileChannel)}
     *
     * @param buffer - b
     * @throws IOException - IO exception
     */
    void save(ByteBuffer buffer) throws IOException;

    /**
     * Opposite to {@link Data#save(ByteBuffer)}
     *

     * To load entire {@link com.github.terma.fastselect.FastSelect} use
     * {@link com.github.terma.fastselect.FastSelect#load(FileChannel, int)}
     *
     * @param dataClass - dc
     * @param buffer    - b
     * @param size      - s
     * @throws IOException - IO exception
     */
    void load(String dataClass, ByteBuffer buffer, int size) throws IOException;

    /**
     * Returns value store at position for that data (column)
     * Type of value will be exact of type your field in data class.
     *
     * @param position - position
     * @return - value store at position
     */
    Object get(int position);

    /**
     * Effective method to compare two data inside column and avoid data extracting (unboxing/boxing)
     * Method logic same as {@link Comparable#compareTo(Object)}
     *
     * @param position1 - position of first item to compare
     * @param position2 - position of second item to compare
     * @return - comparision result same logic as {@link Comparable#compareTo(Object)}
     */
    int compare(int position1, int position2);

    /**
     * Result depends on implementation and in general doesn't guarantee same value as direct call to object.
     * For example if you store "AAA" to {@link StringData} and ask hashCode it's not required to be same
     * with "AAA".hashCode()
     *

     * Method is no trying to create better hashCode strategy, instead is trying to speed up
     * hashing by avoiding as much as possible extracting data from {@link Data}.
     *
     * @param position - position of data
     * @return hashCode
     * @since 3.2.0
     */
    int hashCode(int position);

    /**
     * Init data with default value for requested size.
     *
     * @param size - requested size
     */
    void init(int size);

    void compact();

    /**
     * Count of items in column
     *
     * @return - count of items in column
     */
    int size();

    int allocatedSize();

    /**
     * Approximate size of Data structure in heap memory. Bytes.
     *
     * @return - size in bytes
     */
    long mem();

    int inc();

    Data copy(byte[] needToCopy);

}


text:
<?php

namespace Scholarship\Forms;

use Laracasts\Validation\FormValidator;

class ApplicationForm extends FormValidator
{
    /**
     * @var array
     */
    protected $rules = [
  'accomplishments' => 'required',
  'participation'   => 'required',
  'gpa'             => 'required|numeric',
  'test_score'      => 'numeric',
  'activities'      => 'required',
  'essay1'          => 'required',
  'essay2'          => 'required',
  'link'            => 'url',
 ];

    protected $messages = [
  'accomplishments.required' => 'This question is required.',
  'participation.required'   => 'This question is required.',
  'gpa.required'             => 'GPA is required.',
  'gpa.numeric'              => 'Please enter your GPA as a number.',
  'test_score.numeric'       => 'Please enter your test score as a number.',
  'activities.required'      => 'This question is required.',
  'essay1.required'          => 'This essay is required.',
  'essay2.required'          => 'This essay is required.',
  'link.url'                 => 'Please enter a valid link.',
 ];
}


text:
class UtmTerm(object):
    """The utm term of an Ganalytics object."""

    def __init__(self, utm_term=None):
        """Create a UtmTerm object

        :param utm_term: Used to identify any paid keywords.

        :type utm_term: string, optional
        """
        self._utm_term = None

        if utm_term is not None:
            self.utm_term = utm_term

    @property
    def utm_term(self):
        """Used to identify any paid keywords.

        :rtype: string
        """
        return self._utm_term

    @utm_term.setter
    def utm_term(self, value):
        """Used to identify any paid keywords.

        :param value: Used to identify any paid keywords.
        :type value: string
        """
        self._utm_term = value

    def get(self):
        """
        Get a JSON-ready representation of this UtmTerm.

        :returns: This UtmTerm, ready for use in a request body.
        :rtype: string
        """
        return self.utm_term


text:
require_relative '../spec_helper'

# rubocop:disable Metrics/BlockLength
module RASN1
  module Types
    describe Sequence do
      before(:each) do
        @seq = Sequence.new
        @bool = Boolean.new(default: true)
        @int = Integer.new
        @bs = BitString.new
        @seq.value = [@bool, @int, @bs]
        @no_bool_der = "\x30\x09\x02\x01\x2A\x03\x04\x01\x01\x04\x06".b
        @der = "\x30\x0c\x01\x01\x00\x02\x01\x2A\x03\x04\x01\x01\x04\x06".b
      end

      describe '.type' do
        it 'gets ASN.1 type' do
          expect(Sequence.type).to eq('SEQUENCE')
        end
      end

      describe '#initialize' do
        it 'creates an Sequence with default values' do
          seq = Sequence.new
          expect(seq).to be_constructed
          expect(seq).to_not be_optional
          expect(seq.asn1_class).to eq(:universal)
          expect(seq.default).to eq(nil)
        end
      end

      describe '#initialize_copy' do
        it 'deeply copie self' do
          seq = Sequence.new
          rand(10).times do
            seq.value << Integer.new(value: rand(1_000_000))
          end

          seq2 = seq.dup
          expect(seq2).to eq(seq)
          seq.value.size.times do |idx|
            expect(seq2[idx]).to_not eql(seq[idx])
          end
        end
      end

      describe '#to_der' do
        it 'generates a DER string' do
          @int.value = 42
          @bs.value = [1, 4, 6].pack('C3')
          @bs.bit_length = 23
          expect(@seq.to_der).to eq(@no_bool_der)

          @bool.value = false
          expect(@seq.to_der).to eq(@der)
        end

        it 'generates a DER string from a DER-valued SEQUENCE' do
          seq2 = Sequence.new
          seq2.value = @no_bool_der[2, @no_bool_der.length]
          expect(seq2.to_der).to eq(@no_bool_der)
        end

        it 'does not generate a DER string for an optional SEQUENCE which subelements have no value' do
          seq = Sequence.new(optional: true, value: [@bool, @int, @bs])
          expect(seq.to_der).to eq('')
        end
      end

      describe '#parse!' do
        it 'parses DER string' do
          @seq.parse!(@der)
          expect(@bool.value).to be(false)
          expect(@int.value).to eq(42)
          expect(@bs.value).to eq([1, 4, 6].pack('C3'))
          expect(@bs.bit_length).to eq(23)

          @seq.parse!(@no_bool_der)
          expect(@bool.value).to be(true)
          expect(@int.value).to eq(42)
          expect(@bs.value).to eq([1, 4, 6].pack('C3'))
          expect(@bs.bit_length).to eq(23)
        end

        it 'parses a DER string without parsing SEQUENCE content' do
          seq2 = Sequence.new
          seq2.parse!(@der)
          expect(seq2.value).to eq(@der[2, @der.length])
        end
      end

      describe '#inspect' do
        let(:inspect_str) { @seq.inspect }

        it 'prints a line per value' do
          expect(inspect_str.split("\n").size).to eq(4)
        end

        it 'prints optional values' do
          @seq.value[1] = Integer.new(optional: true)
          expect(@seq.inspect.split("\n").size).to eq(4)
        end
      end
    end
  end
end
# rubocop:enable Metrics/BlockLength


text:
package org.keycloak.authorization.client;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.keycloak.representations.adapters.config.AdapterConfig;
import org.keycloak.util.BasicAuthHelper;
import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * @author Pedro Igor
 */
public class Configuration extends AdapterConfig {

    @JsonIgnore
    private HttpClient httpClient;

    public Configuration() {

    }

    public Configuration(String authServerUrl, String realm, String clientId, Map<String, Object> clientCredentials, HttpClient httpClient) {
        this.authServerUrl = authServerUrl;
        setAuthServerUrl(authServerUrl);
        setRealm(realm);
        setResource(clientId);
        setCredentials(clientCredentials);
        this.httpClient = httpClient;
    }

    @JsonIgnore
    private ClientAuthenticator clientAuthenticator = new ClientAuthenticator() {
        @Override
        public void configureClientCredentials(HashMap<String, String> requestParams, HashMap<String, String> requestHeaders) {
            String secret = (String) getCredentials().get("secret");

            if (secret == null) {
                throw new RuntimeException("Client secret not provided.");
            }

            requestHeaders.put("Authorization", BasicAuthHelper.createHeader(getResource(), secret));
        }
    };

    public HttpClient getHttpClient() {
        if (this.httpClient == null) {
            this.httpClient = HttpClients.createDefault();
        }

        return httpClient;
    }

    public ClientAuthenticator getClientAuthenticator() {
        return this.clientAuthenticator;
    }
}


text:
$('#inputEmail').hide();
$('#inputPassword').hide();
$('.checkbox').hide();
$('#inputSubmit').hide();


text:
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/util/LinkedHashMap_LinkedEntryIterator.hpp>

#include <java/util/LinkedHashMap.hpp>

extern void unimplemented_(const char16_t* name);
java::util::LinkedHashMap_LinkedEntryIterator::LinkedHashMap_LinkedEntryIterator(LinkedHashMap *LinkedHashMap_this, const ::default_init_tag&)
    : super(LinkedHashMap_this, *static_cast< ::default_init_tag* >(0))
{
    clinit();
}

java::util::LinkedHashMap_LinkedEntryIterator::LinkedHashMap_LinkedEntryIterator(LinkedHashMap *LinkedHashMap_this)
    : LinkedHashMap_LinkedEntryIterator(LinkedHashMap_this, *static_cast< ::default_init_tag* >(0))
{
    ctor();
}

void ::java::util::LinkedHashMap_LinkedEntryIterator::ctor()
{ /* stub */
    /* super::ctor(); */
    unimplemented_(u"void ::java::util::LinkedHashMap_LinkedEntryIterator::ctor()");
}

java::util::Map_Entry* java::util::LinkedHashMap_LinkedEntryIterator::next()
{ /* stub */
    unimplemented_(u"java::util::Map_Entry* java::util::LinkedHashMap_LinkedEntryIterator::next()");
    return 0;
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* java::util::LinkedHashMap_LinkedEntryIterator::class_()
{
    static ::java::lang::Class* c = ::class_(u"java.util.LinkedHashMap.LinkedEntryIterator", 43);
    return c;
}

bool java::util::LinkedHashMap_LinkedEntryIterator::hasNext()
{
    return LinkedHashMap_LinkedHashIterator::hasNext();
}

void java::util::LinkedHashMap_LinkedEntryIterator::remove()
{
    LinkedHashMap_LinkedHashIterator::remove();
}

java::lang::Class* java::util::LinkedHashMap_LinkedEntryIterator::getClass0()
{
    return class_();
}


text:
=begin
 rhev_delete_snapshot_check.rb

 Author: Kevin Morey <kevin@redhat.com>

 Description: This is method checks that snapshots identified in $evm.get_state_var(:deleted_snapshots)
              have been deleted in RHEV
-------------------------------------------------------------------------------
   Copyright 2016 Kevin Morey <kevin@redhat.com>

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-------------------------------------------------------------------------------
=end
def log(level, msg, update_message = false)
  $evm.log(level, "#{msg}")
  @task.message = msg if @task && (update_message || level == 'error')
end

def retry_method(retry_time='1.minute', msg='RETRYING', update_message=false)
  log(:info, "#{msg} - retrying in #{retry_time}}", update_message)
  $evm.root['ae_result'] = 'retry'
  $evm.root['ae_retry_interval'] = retry_time
  exit MIQ_OK
end

def call_rhev(action, ref=nil, body_type=:json, body=nil)
  require 'rest_client'
  require 'json'

  servername = @vm.ext_management_system.hostname
  username   = @vm.ext_management_system.authentication_userid
  password   = @vm.ext_management_system.authentication_password

  unless ref.nil?
    url = ref if ref.include?('http')
  end
  url ||= "https://#{servername}"+"#{ref}"

  params = {
    :method=>action, :url=>url,:user=>username, :password=>password,
    :verify_ssl=>false, :headers=>{ :content_type=>body_type, :accept=>:json }
  }
  body_type == :json ? (params[:payload] = JSON.generate(body) if body) : (params[:payload] = body if body)
  log(:info, "Calling url: #{url} action: #{action} payload: #{params[:payload]}")

  response = RestClient::Request.new(params).execute
  log(:info, "response headers: #{response.headers.inspect}")
  log(:info, "response code: #{response.code}")
  log(:info, "response: #{response.inspect}")
  return JSON.parse(response) rescue (return response)
end

begin
  $evm.root.attributes.sort.each { |k, v| log(:info, "\t $evm.root Attribute - #{k}: #{v}")}

  case $evm.root['vmdb_object_type']
  when 'vm'
    # get vm from root
    @vm = $evm.root['vm']
  else
    exit MIQ_OK
  end

  deleted_snapshots = $evm.get_state_var(:deleted_snapshots)
  log(:info, "{:deleted_snapshots=>#{deleted_snapshots}}")

  deleted_snapshots.each do |snapshot_ref|
    log(:info, "Checking status for snapshot_ref: #{snapshot_ref} ")

    list_snapshot_response_hash = call_rhev(:get, "#{@vm['ems_ref']}/snapshots/")
    log(:info, "list_snapshot_response_hash: #{list_snapshot_response_hash}")

    snapshots_array = list_snapshot_response_hash['snapshot']

    snapshot_hash = snapshots_array.detect {|ss| ss['href'] == snapshot_ref }

    unless snapshot_hash.blank?
      snapshot_status = snapshot_hash["snapshot_status"]
      log(:info, "snapshot_status: #{snapshot_status}")
    else
      snapshot_status = 'ok'
    end

    if snapshot_status == 'ok'
      log(:info, "Successfully deleted snapshot", true)
      @vm.custom_set(:SNAPSHOT_DELETE_STATUS, nil)
    else
      @vm.custom_set(:SNAPSHOT_DELETE_STATUS, snapshot_status)
      retry_method('90.seconds', "snapshot_status: #{snapshot_status}")
    end
  end

  # Ruby rescue
rescue => err
  log(:error, "[#{err}]\n#{err.backtrace.join("\n")}")
  exit MIQ_ABORT
end


text:
class Bug1174Layer : public BugsTestBaseLayer
{
public:
    virtual bool init();
};

#endif // __BUG_1174_H__


text:
{-# LANGUAGE MultiWayIf, ScopedTypeVariables #-}
module Spec.VirtualMemory ( translate, getVPN, getMode, translateHelper, VirtualMemoryMode(..)) where
import Spec.Machine
import Utility.Utility
import qualified Spec.CSRField as Field
import Data.Bits
import Prelude
import Data.Int

data VirtualMemoryMode = None | Sv32 | Sv39 | Sv48 deriving (Eq, Show)

getMode :: (Integral s) => s -> VirtualMemoryMode
getMode 0 = None
getMode 1 = Sv32
getMode 8 = Sv39
getMode 9 = Sv48

-- Return the number of page table levels for a given mode.
pageTableLevels Sv32 = 2
pageTableLevels Sv39 = 3
pageTableLevels Sv48 = 4

-- Return the size of a PTE (in bytes) for a given mode.
pteSize Sv32 = 4
pteSize Sv39 = 8
pteSize Sv48 = 8

-- Return the size (in bits) of a PPN field (except the last) for a given mode.
ppnBits Sv32 = 10
ppnBits Sv39 = 9
ppnBits Sv48 = 9

-- Return the total length of all PPN fields for a given mode.
ppnLength Sv32 = 22
ppnLength Sv39 = 44
ppnLength Sv48 = 44

getVPN mode va i = bitSlice va (12 + i * ppnBits mode) (12 + (i + 1) * ppnBits mode)

loadXLEN :: (RiscvMachine p t) => t -> p MachineInt
loadXLEN addr = do
  xlen <- getXLEN
  if xlen == 32
    then fmap (fromIntegral:: Int32 -> MachineInt) (loadWord VirtualMemory addr)
    else fmap (fromIntegral:: Int64 -> MachineInt) (loadDouble VirtualMemory addr)

storeXLEN :: (RiscvMachine p t) => t -> MachineInt -> p ()
storeXLEN addr val = do
  xlen <- getXLEN
  if xlen == 32
    then storeWord VirtualMemory addr ((fromIntegral:: MachineInt -> Int32) val)
    else storeDouble VirtualMemory addr ((fromIntegral:: MachineInt -> Int64) val)

pageFault :: forall a p t. (RiscvMachine p t) => AccessType -> MachineInt -> p a
pageFault Instruction va = raiseExceptionWithInfo 0 12 va
pageFault Load va = raiseExceptionWithInfo 0 13 va
pageFault Store va = raiseExceptionWithInfo 0 15 va

-- Recursively traverse the page table to find the leaf entry for a given virtual address.
findLeafEntry :: forall p t. (RiscvMachine p t) => (VirtualMemoryMode, AccessType, MachineInt, MachineInt) -> Int -> p (Maybe (Int, MachineInt, MachineInt))
findLeafEntry (mode,accessType,va,addr) level = do
  let pteAddr = addr + (getVPN mode va level * pteSize mode)
  pte <- loadXLEN ((fromIntegral:: MachineInt -> t) pteAddr)
  let v = testBit pte 0
  let r = testBit pte 1
  let w = testBit pte 2
  let x = testBit pte 3
  -- TODO: PMA and PMP checks.
  if | not v || (not r && w) -> do
         pageFault accessType va
         return Nothing
     | r || x ->
         return (Just (level, pte, pteAddr))
     | level <= 0 -> do
         pageFault accessType va
         return Nothing
     -- This is duplicated for clash's sake.
     | level == 1 ->
         findLeafEntry (mode, accessType, va, (shift (bitSlice pte 10 (10 + ppnLength mode)) 12)) 0
     | level == 2 ->
         findLeafEntry (mode, accessType, va, (shift (bitSlice pte 10 (10 + ppnLength mode)) 12)) 1
     | level == 3 ->
         findLeafEntry (mode, accessType, va, (shift (bitSlice pte 10 (10 + ppnLength mode)) 12)) 2
     | level == 4 ->
         findLeafEntry (mode, accessType, va, (shift (bitSlice pte 10 (10 + ppnLength mode)) 12)) 3
     | otherwise -> return Nothing

translateHelper :: VirtualMemoryMode -> MachineInt -> MachineInt -> Int -> MachineInt
translateHelper mode va pte level = vaSlice .|. shift ptePPN vaSplit
  where vaSplit = 12 + level * (ppnBits mode)
        vaSlice = bitSlice va 0 vaSplit
        ptePPN = shiftR pte (10 + level * (ppnBits mode))

calculateAddress :: (RiscvMachine p t) => AccessType -> MachineInt -> p (MachineInt)
calculateAddress accessType va = do
  nmode <- (getCSRField Field.MODE)
  let mode = getMode nmode
  privMode <- getPrivMode
  mprv <- getCSRField Field.MPRV
  mpp <- getCSRField Field.MPP
  let effectPriv = if mprv == 1 then decodePrivMode mpp else privMode
  if mode == None || (effectPriv == Machine) || (privMode == Machine && accessType == Instruction)
    then return va
    else -- First the translation may be in a cache, possibly stalled, cacheAccess use the typeclass defined "TLB"
      cacheAccess accessType va $  do
    ppn <- getCSRField Field.PPN
    maybePTE <- findLeafEntry (mode, accessType, va, (shift ppn 12)) (pageTableLevels mode - 1)
    case maybePTE of
      Nothing -> pageFault accessType va
      Just (level, pte, addr) -> do
        let r = testBit pte 1
        let w = testBit pte 2
        let x = testBit pte 3
        let u = testBit pte 4
        let a = testBit pte 6
        let d = testBit pte 7
        sum <- getCSRField Field.SUM
        mxr <- getCSRField Field.MXR
        -- Note that effectPriv must be either Supervisor or User at this point.
        let validUserAccess = (u && (effectPriv == User || sum == 1))
        let validSupervisorAccess = (not u && effectPriv == Supervisor)
        let validRead = (accessType == Load && (r || (x && mxr == 1)))
        let validExecute = (accessType == Instruction && x)
        let validWrite = (accessType == Store && w)
        if | not ((validUserAccess || validSupervisorAccess) && (validRead || validExecute || validWrite)) -> do
               -- Bad permissions.
               pageFault accessType va
           | level > 0 && bitSlice pte 10 (10 + level * ppnBits mode) /= 0 -> do
               -- Misaligned superpage.
               pageFault accessType va
           | not a || (accessType == Store && not d) -> do
              inHardware <- hardwareDirtyBit
              if inHardware then do
               -- Set dirty/access bits in hardware:
                let newPTE = (pte .|. (bit 6) .|. (if accessType == Store then bit 7 else 0))
                storeXLEN (fromIntegral addr) newPTE
                return (translateHelper mode va newPTE level, newPTE, level)
              else do
               -- Set dirty/access bits in software:
               pageFault accessType va
           | otherwise -> do
               -- Successful translation.
               return (translateHelper mode va pte level, pte, level)

translate :: forall p t. (RiscvMachine p t) => AccessType -> Int -> t -> p t
translate accessType alignment va = do
  pa <- calculateAddress accessType ((fromIntegral :: t -> MachineInt) va)
  if mod pa ((fromIntegral:: Int -> MachineInt) alignment) /= 0  -- Check alignment.
      -- TODO: Figure out if mtval should be set to pa or va here.
      then raiseExceptionWithInfo 0 misalignCode pa
      else return ((fromIntegral :: MachineInt -> t) pa)
  where misalignCode =
          case accessType of
            Instruction -> 0
            Load -> 4
            Store -> 6


text:
{% extends "/base.html" %}
{% set active_page = "create" %}
{% set active_link  = "newproject" %}
{% from "_formhelpers.html" import render_field %}

{% block content %}

Sync a Project with GitHub

            <form role="form" method="post" action="{{ url_for('github.import_repo', github_url=github_url, short_name=project.short_name)}}" enctype="multipart/form-data">
                {{ form.hidden_tag() }}
                <fieldset>
                    {{ render_field(form.description, class_="form-control", show_label=True, placeholder='Some details about the project') }}
                    {{ render_field(form.long_description, class_="form-control", show_label=True) }}
                    {{ render_field(form.webhook, class_="form-control", show_label=True) }}
                    {{ render_field(form.task_presenter, class_="form-control", show_label=True) }}
                    {{ render_field(form.tutorial, class_="form-control", show_label=True) }}
                    {{ render_field(form.results, class_="form-control", show_label=True) }}
                    {{ render_field(form.thumbnail, class_="form-control", show_label=True) }}
                    {{ render_field(form.category_id, class_="form-control", show_label=True) }}
                    {{ render_field(form.additional_properties, rows="10", class_="form-control", show_label=True) }}

                        Cancel
                        <button type="submit" value="Update" class="btn btn-danger">Update</button>

                </fieldset>
            </form>

{% endblock %}


text:
#ifndef THIRD_PARTY_TENSORFLOW_COMPILER_XLA_SERVICE_HLO_MODULE_METADATA_H_
#define THIRD_PARTY_TENSORFLOW_COMPILER_XLA_SERVICE_HLO_MODULE_METADATA_H_

#include <functional>

#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/service/hlo.pb.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/platform/env.h"

namespace xla {

// Wrapper class for HloModuleMetadataProto to avoid allowing callers to mutate
// arbitrary fields. Specifically, callers cannot set timestamps or ids or
// set the fields of any pass not currently running.
class HloModuleMetadata {
 public:
  explicit HloModuleMetadata(tensorflow::Env* env) : env_(env) {}

  const HloModuleMetadataProto& proto() const { return module_metadata_; }

  // Creates a new HloPassMetadata. All calls to RecordPassStart should be
  // matched by a later call to RecordPassEnd.
  void RecordPassStart();

  // Marks the currently running pass as finished. Returns NotFound if metadata
  // for the currently running pass cannot be found.
  Status RecordPassEnd();

  const absl::optional<HloModuleMetadataProto>& prepartitioning_metadata()
      const {
    return prepartitioning_metadata_;
  }
  void set_prepartitioning_metadata(
      const HloModuleMetadata& prepartitioning_metadata);

  // Setters for HloModuleMetadataProto.
  void set_module_group_name(const std::string& name) {
    module_metadata_.set_module_group_name(name);
  }
  void set_canonical_module_id(int64_t id) {
    module_metadata_.set_canonical_module_id(id);
  }
  void add_partitioned_module_id(int64_t id) {
    module_metadata_.add_partitioned_module_ids(id);
  }

  StatusOr<int64_t> current_pass_id() {
    TF_ASSIGN_OR_RETURN(HloPassMetadata * pass_metadata,
                        GetCurrentHloPassMetadata());
    return pass_metadata->pass_id();
  }

  // Setters for the current HloPassMetadata.
  Status set_current_pass_name(const std::string& pass_name) {
    return MutateCurrentHloPassMetadata(
        [&pass_name](HloPassMetadata* pass_metadata) {
          pass_metadata->set_pass_name(pass_name);
        });
  }
  Status set_current_pass_pipeline_name(const std::string& pipeline_name) {
    return MutateCurrentHloPassMetadata(
        [&pipeline_name](HloPassMetadata* pass_metadata) {
          pass_metadata->set_pipeline_name(pipeline_name);
        });
  }
  Status add_current_pass_dump_filename(const std::string& dump_filename) {
    return MutateCurrentHloPassMetadata(
        [&dump_filename](HloPassMetadata* pass_metadata) {
          pass_metadata->add_dump_filenames(dump_filename);
        });
  }
  Status set_current_pass_module_changed(bool module_changed) {
    return MutateCurrentHloPassMetadata(
        [&module_changed](HloPassMetadata* pass_metadata) {
          pass_metadata->set_module_changed(module_changed);
        });
  }
  Status set_current_pass_module_id(int64_t module_id) {
    return MutateCurrentHloPassMetadata(
        [&module_id](HloPassMetadata* pass_metadata) {
          pass_metadata->set_module_id(module_id);
        });
  }
  Status add_current_pass_module_group_module_id(int64_t module_id) {
    return MutateCurrentHloPassMetadata(
        [&module_id](HloPassMetadata* pass_metadata) {
          pass_metadata->add_module_group_module_ids(module_id);
        });
  }

 private:
  // Gets mutable metadata for the currently running pass. If passes are nested,
  // finds the deepest one still running. Returns NotFound if metadata for the
  // currently running pass cannot be found.
  StatusOr<HloPassMetadata*> GetCurrentHloPassMetadata();

  Status MutateCurrentHloPassMetadata(
      const std::function<void(HloPassMetadata*)>& mutator);

  HloModuleMetadataProto module_metadata_;
  tensorflow::Env* env_;
  int64_t next_pass_id_ = 1;

  // Stack of metadata for passes that are currently running. Size > 1 iff
  // passes are nested.
  std::vector<HloPassMetadata*> running_passes_;

  // Metadata from before the module was partitioned, if applicable.
  absl::optional<HloModuleMetadataProto> prepartitioning_metadata_ =
      absl::nullopt;
};

}  // namespace xla

#endif  // THIRD_PARTY_TENSORFLOW_COMPILER_XLA_SERVICE_HLO_MODULE_METADATA_H_


text:
const LoginPage = require('./pages/login.page');
const logOut = require('./preparations/logout');
const HomePage = require('./pages/home.page');

jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

describe('Login', () => {
  afterEach(() => {
    logOut();
  });

  it('should be able to login with correct credentials', () => {
    LoginPage.open();
    LoginPage.waitForLoad();
    LoginPage.emailInput.setValue('js@mail.com');
    LoginPage.passwordInput.setValue('password');
    LoginPage.loginButton.click();
    HomePage.waitForLoad();

    const actual = HomePage.isOpen();

    expect(actual).toEqual(true);
  });

  it('should not be able to login with incorrect email', () => {
    LoginPage.open();
    LoginPage.waitForLoad();
    LoginPage.emailInput.setValue('js1@mail.com');
    LoginPage.passwordInput.setValue('password');
    LoginPage.loginButton.click();

    const actual = HomePage.wasNotLoad();

    expect(actual).toEqual(true);
  });

  it('should not be able to login with incorrect password', () => {
    LoginPage.open();
    LoginPage.waitForLoad();
    LoginPage.emailInput.setValue('js@mail.com');
    LoginPage.passwordInput.setValue('pass1word');
    LoginPage.loginButton.click();

    const actual = HomePage.wasNotLoad();

    expect(actual).toEqual(true);
  });

  it('should show error message if password is incorrect', () => {
    LoginPage.open();
    LoginPage.waitForLoad();
    LoginPage.emailInput.setValue('js@mail.com');
    LoginPage.passwordInput.setValue('pass1word');
    LoginPage.loginButton.click();
    LoginPage.passwordError.waitForExist();

    const actual = LoginPage.passwordError.getText();

    expect(actual).toEqual('Invalid email or password');
  });

  it('should show error message if email is incorrect', () => {
    LoginPage.open();
    LoginPage.waitForLoad();
    LoginPage.emailInput.setValue('js1@mail.com');
    LoginPage.passwordInput.setValue('password');
    LoginPage.loginButton.click();
    LoginPage.emailError.waitForExist();

    const actual = LoginPage.emailError.getText();

    expect(actual).toEqual('Invalid email or password');
  });
});


text:
VERAout-tools
=============

HDF Tools to post-process VERA output files

VERA stands for the "Virtual Environment for Reactor Analysis" and is
a product of the Consortium for Advanced Simulation of LWR's (CASL).
More information about CASL can be found at [http://www.casl.gov]

The latest version of this repository can be found at
[https://github.com/palmtag/VERAout-tools]

This repository contains the following source files:

* Mod_hdftools.f90 - Wrapper routines for performing basic HDF functions
* hunittest.f90 - Simple program to perform unit tests
* makehdf.f90 - Simple program to create a sample VERAout file for testing
* mpactread.f90 - Simple program to read VERAout file created by MPACT
* ctfread.f90 - Simple program to read HDF output file created by CTF

#### See the Wiki for information on installing HDF5

#### See the Wiki to learn more about the "mpactread" utility


text:
class MainWindow: public QMainWindow
{
public:
    MainWindow( QWidget * = NULL );
};

MainWindow::MainWindow( QWidget *parent ):
    QMainWindow( parent )
{
    Plot *plot = new Plot( this );
    setCentralWidget( plot );

    QToolBar *toolBar = new QToolBar( this );

    QComboBox *modeBox = new QComboBox( toolBar );
    modeBox->addItem( "No Mask" );
    modeBox->addItem( "Mask" );
    modeBox->addItem( "Alpha Mask" );
    modeBox->addItem( "Alpha Mask/Redraw" );
    modeBox->addItem( "Alpha Mask/Copy Mask" );
    modeBox->setCurrentIndex( 1 );
    modeBox->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );

    connect( modeBox, SIGNAL( currentIndexChanged( int ) ),
             plot, SLOT( setMode( int ) ) );

    QToolButton *btnExport = new QToolButton( toolBar );
    btnExport->setText( "Export" );
    btnExport->setToolButtonStyle( Qt::ToolButtonTextUnderIcon );
    connect( btnExport, SIGNAL( clicked() ), plot, SLOT( exportPlot() ) );

    toolBar->addWidget( modeBox );
    toolBar->addWidget( btnExport );
    addToolBar( toolBar );

}

int main( int argc, char **argv )
{
    QApplication app( argc, argv );

    MainWindow window;
    window.resize( 600, 400 );
    window.show();

    return app.exec();
}


text:
module Azure::Web::Mgmt::V2016_03_01
  module Models
    #
    # Body of the error response returned from the API.
    #
    class ErrorEntity

      include MsRestAzure

      # @return [String] Type of error.
      attr_accessor :extended_code

      # @return [String] Message template.
      attr_accessor :message_template

      # @return [Array<String>] Parameters for the template.
      attr_accessor :parameters

      # @return [Array<ErrorEntity>] Inner errors.
      attr_accessor :inner_errors

      # @return [String] Basic error code.
      attr_accessor :code

      # @return [String] Any details of the error.
      attr_accessor :message

      #
      # Mapper for ErrorEntity class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ErrorEntity',
          type: {
            name: 'Composite',
            class_name: 'ErrorEntity',
            model_properties: {
              extended_code: {
                client_side_validation: true,
                required: false,
                serialized_name: 'extendedCode',
                type: {
                  name: 'String'
                }
              },
              message_template: {
                client_side_validation: true,
                required: false,
                serialized_name: 'messageTemplate',
                type: {
                  name: 'String'
                }
              },
              parameters: {
                client_side_validation: true,
                required: false,
                serialized_name: 'parameters',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              inner_errors: {
                client_side_validation: true,
                required: false,
                serialized_name: 'innerErrors',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ErrorEntityElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'ErrorEntity'
                      }
                  }
                }
              },
              code: {
                client_side_validation: true,
                required: false,
                serialized_name: 'code',
                type: {
                  name: 'String'
                }
              },
              message: {
                client_side_validation: true,
                required: false,
                serialized_name: 'message',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
import actionTypes from '../action-types';
import partition from '../utils/partition';
import isPlainObject from '../utils/is-plain-object';
import { trackable } from '../utils/track';

import NULL_ACTION from '../constants/null-action';

const batch = trackable((model, actions) => {
  const dispatchableActions = actions.filter((action) => !!action);

  if (!dispatchableActions.length) return NULL_ACTION;

  if (dispatchableActions.length && dispatchableActions.every(isPlainObject)) {
    if (dispatchableActions.length === 1) {
      return dispatchableActions[0];
    }

    return {
      type: actionTypes.BATCH,
      model,
      actions: dispatchableActions,
    };
  }

  const [plainActions, actionThunks] = partition(dispatchableActions,
    (action) => typeof action !== 'function');

  if (!actionThunks.length) {
    if (plainActions.length > 1) {
      return {
        type: actionTypes.BATCH,
        model,
        actions: plainActions,
      };
    } else if (plainActions.length === 1) {
      return plainActions[0];
    }
  }

  return (dispatch) => {
    if (plainActions.length > 1) {
      dispatch({
        type: actionTypes.BATCH,
        model,
        actions: plainActions,
      });
    } else if (plainActions.length === 1) {
      dispatch(plainActions[0]);
    }
    actionThunks.forEach(dispatch);
  };
});

function dispatchBatchIfNeeded(model, actions, dispatch) {
  if (!actions.length) return void 0;

  const dispatchableActions = actions.filter((action) => !!action);

  if (!dispatchableActions.length) return void 0;

  return dispatch(batch(model, dispatchableActions));
}

export default batch;
export {
  dispatchBatchIfNeeded,
};


text:
using System.ServiceModel;
using System.Threading.Tasks;
using DevelopmentInProgress.DipCore.Service;
using DevelopmentInProgress.DipSecure;

namespace DevelopmentInProgress.AuthorisationManager.Service
{
    [ServiceContract]
    public interface IAuthorisationManagerServiceAsync
    {
        [OperationContract]
        Task<ServiceResponse<Authorisation>> GetAuthorisation();

        [OperationContract]
        Task<ServiceResponse<UserAuthorisation>> GetUserAuthorisation(string userName);

        [OperationContract]
        Task<ServiceResponse<Activity>> SaveActivity(Activity activity);

        [OperationContract]
        Task<ServiceResponse<Role>> SaveRole(Role role);

        [OperationContract]
        Task<ServiceResponse<UserAuthorisation>> SaveUserAuthorisation(UserAuthorisation userAuthorisation);

        [OperationContract]
        Task<ServiceResponse<bool>> DeleteActivity(int id);

        [OperationContract]
        Task<ServiceResponse<bool>> DeleteRole(int id);

        [OperationContract]
        Task<ServiceResponse<bool>> DeleteUserAuthorisation(int id);

        [OperationContract]
        Task<ServiceResponse<bool>> RemoveActivityFromActivity(int activityId, int parentId);

        [OperationContract]
        Task<ServiceResponse<bool>> RemoveActivityFromRole(int activityId, int roleId);

        [OperationContract]
        Task<ServiceResponse<bool>> RemoveRoleFromRole(int roleId, int parentId);

        [OperationContract]
        Task<ServiceResponse<bool>> RemoveRoleFromUser(int roleId, int userId);

        [OperationContract]
        Task<ServiceResponse<bool>> AddActivityToRole(int roleId, int activityId);

        [OperationContract]
        Task<ServiceResponse<bool>> AddActivityToActivity(int parentActivityId, int activityId);

        [OperationContract]
        Task<ServiceResponse<bool>> AddRoleToUser(int userId, int roleId);

        [OperationContract]
        Task<ServiceResponse<bool>> AddRoleToRole(int parentRoleId, int roleId);
    }
}


text:
#ifndef _HTTP_SERVER_
#define _HTTP_SERVER_

#include <stdlib.h>
#include <prnetdb.h>
#include <prio.h>
#include "support/SimpleHash.h"
#include "ptrlist.h"

#ifdef WIN32
#define __EXPORT __declspec(dllexport)
#else
#define __EXPORT
#endif

class HttpRequest;

class __EXPORT HttpServer
{
public:
    HttpServer(const char *addr, PRUint16 af);
    ~HttpServer();

    const char *getAddrString() const;
    const PRNetAddr * getAddr() const;
    void setSSL(PRBool SSLstate);
    PRBool isSSL() const;

    // put a file on the server of size bytes
    PRBool putFile(const char *uri, int size) const;
    PRBool putFile(const char* uri, const char* localFile) const;

private:
    char *_addr;
    PRNetAddr *_netAddr;
    PRBool SSLOn;
    PRBool _putFile(HttpRequest& rq) const;
};

typedef __EXPORT enum HttpProtocol_e { HTTPNA    = 0x0,
                                       HTTP09    = 0x1,
                                       HTTP10    = 0x2,
                                       HTTP11    = 0x4,
                                       HTTPBOGUS = 0x8 } HttpProtocol;

#define NUM_PROTOS 5 // needed for arrays of tests

__EXPORT char *HttpProtocolToString(HttpProtocol);

class HttpMessage
{
    public:
        HttpMessage(long len = 0, const char* buf = NULL);
        ~HttpMessage();

        PRBool          operator == (const HttpMessage& rhs);

        void addData(long len, const void* buf);

        // set data on the message
        void            setProtocol(HttpProtocol prot);
        PRBool          addHeader(const char *name, const char *value);

        // get data about the message
        HttpProtocol    getProtocol() const;
        const char*     getHeader(const char *name);

    protected:
        char*               firstline; // first line - may be the request-line or server status
        HttpProtocol        proto;
        SimpleStringHash    headers;
        long                cl;
};

class SecurityProtocols
{
    public:
        SecurityProtocols(PRBool s2 = PR_TRUE, PRBool s3 = PR_TRUE, PRBool t = PR_TRUE);
        const SecurityProtocols& operator = (const SecurityProtocols& rhs);
        const SecurityProtocols& operator = (const PtrList<char>& protlist);

        PRBool ssl2, ssl3, tls;
};

#endif


text:
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
import React from 'react';
import ReactDOM from 'react-dom';
import Animate from 'rc-animate';
import classNames from 'classnames';
import omit from 'omit.js';
import Icon from '../icon';
import CheckableTag from './CheckableTag';
export default class Tag extends React.Component {
    constructor(props) {
        super(props);
        this.close = (e) => {
            const onClose = this.props.onClose;
            if (onClose) {
                onClose(e);
            }
            if (e.defaultPrevented) {
                return;
            }
            const dom = ReactDOM.findDOMNode(this);
            dom.style.width = `${dom.getBoundingClientRect().width}px`;
            // It's Magic Code, don't know why
            dom.style.width = `${dom.getBoundingClientRect().width}px`;
            this.setState({
                closing: true,
            });
        };
        this.animationEnd = (_, existed) => {
            if (!existed && !this.state.closed) {
                this.setState({
                    closed: true,
                    closing: false,
                });
                const afterClose = this.props.afterClose;
                if (afterClose) {
                    afterClose();
                }
            }
        };
        this.state = {
            closing: false,
            closed: false,
        };
    }
    isPresetColor(color) {
        if (!color) {
            return false;
        }
        return /^(pink|red|yellow|orange|cyan|green|blue|purple)(-inverse)?$/.test(color);
    }
    render() {
        const _a = this.props, { prefixCls, closable, color, className, children, style } = _a, otherProps = __rest(_a, ["prefixCls", "closable", "color", "className", "children", "style"]);
        const closeIcon = closable ? React.createElement(Icon, { type: "cross", onClick: this.close }) : '';
        const isPresetColor = this.isPresetColor(color);
        const classString = classNames(prefixCls, {
            [`${prefixCls}-${color}`]: isPresetColor,
            [`${prefixCls}-has-color`]: (color && !isPresetColor),
            [`${prefixCls}-close`]: this.state.closing,
        }, className);
        // fix https://fb.me/react-unknown-prop
        const divProps = omit(otherProps, [
            'onClose',
            'afterClose',
        ]);
        const tagStyle = Object.assign({ backgroundColor: (color && !isPresetColor) ? color : null }, style);
        const tag = this.state.closed ? null : (React.createElement("div", Object.assign({ "data-show": !this.state.closing }, divProps, { className: classString, style: tagStyle }),
            React.createElement("span", { className: `${prefixCls}-text` }, children),
            closeIcon));
        return (React.createElement(Animate, { component: "", showProp: "data-show", transitionName: `${prefixCls}-zoom`, transitionAppear: true, onEnd: this.animationEnd }, tag));
    }
}
Tag.CheckableTag = CheckableTag;
Tag.defaultProps = {
    prefixCls: 'ant-tag',
    closable: false,
};


text:
/* Ross Baehr
   R@M 2017
   ross.baehr@gmail.com
*/

#include "tasks/include/blink_red.h"

static void blink_red_task(void* params) {

  for (;;) {

    blink_rgb(RED_LED, 1);
    vTaskDelay(250 / portTICK_RATE_MS);
  }

}

bool blink_red_init(void) {
  // Setup code done in main already
  /*
  ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
  while(!ROM_SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOF))
    {
    }

  //
  // Configure the GPIO port for the LED operation.
  //
  ROM_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, RED_LED|BLUE_LED|GREEN_LED);
  */

  if ( xTaskCreate(blink_red_task, (const portCHAR *)"Blink red", 128, NULL,
                   tskIDLE_PRIORITY + 1, NULL) != pdTRUE) {
    return true;

  }
  return false;
}


text:
package quota

import "context"

var (
	_ QuotaStorage = &MockQuotaStorage{}
	_ QuotaService = &MockQuotaService{}
)

type MockQuotaStorage struct {
	OnSet      func(string, int) error
	OnSetLimit func(string, int) error
	OnGet      func(string) (*Quota, error)
}

func (m *MockQuotaStorage) Set(ctx context.Context, name string, limit int) error {
	return m.OnSet(name, limit)
}

func (m *MockQuotaStorage) SetLimit(ctx context.Context, name string, limit int) error {
	return m.OnSetLimit(name, limit)
}

func (m *MockQuotaStorage) Get(ctx context.Context, name string) (*Quota, error) {
	return m.OnGet(name)
}

type MockQuotaService struct {
	OnInc      func(QuotaItem, int) error
	OnSet      func(QuotaItem, int) error
	OnSetLimit func(QuotaItem, int) error
	OnGet      func(QuotaItem) (*Quota, error)
}

func (m *MockQuotaService) Inc(ctx context.Context, item QuotaItem, delta int) error {
	if m.OnInc == nil {
		return nil
	}
	return m.OnInc(item, delta)
}

func (m *MockQuotaService) SetLimit(ctx context.Context, item QuotaItem, limit int) error {
	if m.OnSetLimit == nil {
		return nil
	}
	return m.OnSetLimit(item, limit)
}

func (m *MockQuotaService) Set(ctx context.Context, item QuotaItem, quantity int) error {
	if m.OnSet == nil {
		return nil
	}
	return m.OnSet(item, quantity)
}

func (m *MockQuotaService) Get(ctx context.Context, item QuotaItem) (*Quota, error) {
	return m.OnGet(item)
}


text:
/,
                                                             CFRangeMake(0, CFStringGetLength(string) - 3),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyCount(tokenizer, 4);
    CFRelease(locale);
    CFRelease(tokenizer);
}

TEST(CFStringTokenizer, EnglishWordBreak2) {
    CFStringRef string = CFSTR("hello\r\n world. \r new line?\rn");
    CFLocaleRef locale = CFLocaleCopyCurrent();
    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyCount(tokenizer, 14);
    CFRelease(locale);
    CFRelease(tokenizer);
}

TEST(CFStringTokenizer, EnglishSentenceBreak2) {
    CFStringRef string = CFSTR("hello\r\n world. \r new line?\rn");
    CFLocaleRef locale = CFLocaleCopyCurrent();
    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitSentence,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyCount(tokenizer, 4);

    CFRelease(locale);
    CFRelease(tokenizer);
}

TEST(CFStringTokenizer, ChineseWordBreak) {
    CFStringRef string = CFSTR(/*I love Microsoft*/ "我爱微软");

    CFLocaleRef locale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("zh-cn"));

    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyRange(tokenizer, 0, 1); // 我 I
    verifyRange(tokenizer, 1, 1); // 爱 love
    verifyRange(tokenizer, 2, 2); // 微软 microsoft

    CFRelease(tokenizer);
    CFRelease(locale);
}
TEST(CFStringTokenizer, ChineseWordBreakRange) {
    CFStringRef string = CFSTR(/*I love Microsoft*/ "我爱微软");

    CFLocaleRef locale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("zh-cn"));

    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string /*I love*/,
                                                             CFRangeMake(0, CFStringGetLength(string) - 2),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyRange(tokenizer, 0, 1); // 我 I
    verifyRange(tokenizer, 1, 1); // 爱 love
    ASSERT_EQ(CFStringTokenizerAdvanceToNextToken(tokenizer), kCFStringTokenizerTokenNone);

    CFRelease(tokenizer);
    CFRelease(locale);
}

TEST(CFStringTokenizer, ArabicWordBreak) {
    CFStringRef string = CFSTR(/*System Preferences*/ "تفضيلات النظام");

    CFLocaleRef locale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("az-Arab"));

    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyRange(tokenizer, 0, 7); // تفضيلات
    verifyRange(tokenizer, 7, 1); // space
    verifyRange(tokenizer, 8, 6); // النظام

    CFRelease(tokenizer);
    CFRelease(locale);
}

TEST(CFStringTokenizer, ArabicWordBreakRange) {
    CFStringRef string = CFSTR(/*System Preferences*/ "تفضيلات النظام");

    CFLocaleRef locale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("az-Arab"));

    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string) - 4),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyRange(tokenizer, 0, 7); // تفضيلات
    verifyRange(tokenizer, 7, 1); // space
    verifyRange(tokenizer, 8, 2); // ظام
    ASSERT_EQ(CFStringTokenizerAdvanceToNextToken(tokenizer), kCFStringTokenizerTokenNone);

    CFRelease(tokenizer);
    CFRelease(locale);
}

TEST(CFStringTokenizer, ArabicSentenceBreak) {
    CFStringRef string = CFSTR(
        "هم الغرب ونحن العرب .. والفرق بيننا نقطة..هم يتفاهمون بالحوار ونحن بالخوار .. والفرق بيننا نقطة .. هم يعيشون مع بعضهم البعض "
        "في حالة تحالف ونحن في تخالف .. والفرق بيننا نقطة . ");
    CFLocaleRef locale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("az-Arab"));
    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitSentence,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyCount(tokenizer, 6);

    CFRelease(tokenizer);
    CFRelease(locale);
}

TEST(CFStringTokenizer, ArabicLineBreak) {
    CFStringRef string = CFSTR(
        "هم الغرب ونحن العرب .. والفرق بيننا نقطة..هم يتفاهمون بالحوار ونحن بالخوار .. والفرق بيننا نقطة .. هم يعيشون مع بعضهم البعض "
        "في حالة تحالف ونحن في تخالف .. والفرق بيننا نقطة . ");
    CFLocaleRef locale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("az-Arab"));
    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitLineBreak,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    verifyCount(tokenizer, 28);

    CFRelease(tokenizer);
    CFRelease(locale);
}

TEST(CFStringTokenizer, EnglishWordBreakGoToIndex) {
    CFStringRef string = CFSTR("Hello World");
    CFLocaleRef locale = CFLocaleCopyCurrent();
    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    ASSERT_NE(kCFStringTokenizerTokenNone, CFStringTokenizerGoToTokenAtIndex(tokenizer, 10));

    CFRange range = CFStringTokenizerGetCurrentTokenRange(tokenizer);
    ASSERT_EQ(6, range.location);
    ASSERT_EQ(5, range.length);
    CFRelease(locale);
    CFRelease(tokenizer);
}

TEST(CFStringTokenizer, ArabicWordBreakGoToIndex) {
    CFStringRef string = CFSTR(/*System Preferences*/ "تفضيلات النظام");

    CFLocaleRef locale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("az-Arab"));

    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    ASSERT_NE(kCFStringTokenizerTokenNone, CFStringTokenizerGoToTokenAtIndex(tokenizer, 10));
    CFRange range = CFStringTokenizerGetCurrentTokenRange(tokenizer);
    ASSERT_EQ(range.location, 8);
    ASSERT_EQ(range.length, 6);
    CFRelease(tokenizer);
    CFRelease(locale);
}

TEST(CFStringTokenizer, EnglishWordBreakGoToIndex2) {
    CFStringRef string = CFSTR("Hello World");
    CFLocaleRef locale = CFLocaleCopyCurrent();
    CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault,
                                                             string,
                                                             CFRangeMake(0, CFStringGetLength(string)),
                                                             kCFStringTokenizerUnitWordBoundary,
                                                             locale);
    ASSERT_TRUE(NULL != tokenizer);
    ASSERT_NE(kCFStringTokenizerTokenNone, CFStringTokenizerGoToTokenAtIndex(tokenizer, 8));

    CFRange range = CFStringTokenizerGetCurrentTokenRange(tokenizer);
    ASSERT_EQ(6, range.location);
    ASSERT_EQ(5, range.length);
    CFRelease(locale);
    CFRelease(tokenizer);
}

TEST(CFStringTokenizer, EnglishSetText) {
    CFLocaleRef locale = CFLocaleCopyCurrent();
    CFStringTokenizerRef tokenizer =
        CFStringTokenizerCreate(kCFAllocatorDefault, NULL, CFRangeMake(0, -1), kCFStringTokenizerUnitWordBoundary, locale);

    ASSERT_TRUE(NULL != tokenizer);

    CFStringRef string = CFSTR("Hello World");
    ASSERT_NO_THROW({ CFStringTokenizerSetString(tokenizer, string, CFRangeMake(0, CFStringGetLength(string))); });

    ASSERT_NE(kCFStringTokenizerTokenNone, CFStringTokenizerGoToTokenAtIndex(tokenizer, 8));

    CFRange range = CFStringTokenizerGetCurrentTokenRange(tokenizer);
    ASSERT_EQ(6, range.location);
    ASSERT_EQ(5, range.length);
    CFRelease(locale);
    CFRelease(tokenizer);
}

TEST(CFStringTokenizer, ArabicWordSetText) {
    CFStringRef string = NULL;

    CFLocaleRef locale = CFLocaleCreate(kCFAllocatorDefault, CFSTR("az-Arab"));

    CFStringTokenizerRef tokenizer =
        CFStringTokenizerCreate(kCFAllocatorDefault, string, CFRangeMake(0, -1), kCFStringTokenizerUnitWordBoundary, locale);
    ASSERT_TRUE(NULL != tokenizer);

    string = CFSTR(/*System Preferences*/ "تفضيلات النظام");
    ASSERT_NO_THROW({ CFStringTokenizerSetString(tokenizer, string, CFRangeMake(0, CFStringGetLength(string))); });

    ASSERT_NE(kCFStringTokenizerTokenNone, CFStringTokenizerGoToTokenAtIndex(tokenizer, 10));
    CFRange range = CFStringTokenizerGetCurrentTokenRange(tokenizer);
    ASSERT_EQ(range.location, 8);
    ASSERT_EQ(range.length, 6);
    CFRelease(tokenizer);
    CFRelease(locale);
}


text:
cask 'mweb' do
  version '3.2.7'
  sha256 '77f5f76b364a33c1668c5a83586c2d94ca97ac4ad2f29a104c89b51fecc05d4b'

  # dl.devmate.com/com.coderforart.MWeb3 was verified as official when first introduced to the cask
  url 'https://dl.devmate.com/com.coderforart.MWeb3/MWeb3-ProMarkdownwriting,notetakingandstaticbloggeneratorApp.dmg'
  appcast 'https://updates.devmate.com/com.coderforart.MWeb3.xml'
  name 'MWeb'
  homepage 'https://www.mweb.im/'

  app 'MWeb.app'
end


text:
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    RestInspector restInspector;
    restInspector.show();
    return app.exec();
}