text:
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
//
package com.yahoo.bard.webservice.logging.blocks;

import com.yahoo.bard.webservice.logging.LogInfo;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

/**
 * Log that keep tracks for cache set failures.
 */
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class BardCacheInfo implements LogInfo {
    protected final String opType;
    protected final String cacheKeyCksum;
    protected final String signatureCksum;
    protected final int cacheKeyLen;
    protected final int cacheValLen;

    /**
     * Constructor.
     *
     * @param opType Type of activity like cache hit , miss or potential hit
     * @param cacheKeyLen The Length of the cache key
     * @param cacheKeyCksum  The cache Key MD5 checksum value
     * @param signatureCksum The query signature cksum.
     * @param cacheValLen  The cache value length
     */
    public BardCacheInfo(String opType, int cacheKeyLen, String cacheKeyCksum, String signatureCksum, int cacheValLen) {
        this.opType = opType;
        this.cacheKeyLen = cacheKeyLen;
        this.cacheKeyCksum = cacheKeyCksum;
        this.signatureCksum = signatureCksum;
        this.cacheValLen = cacheValLen;
    }
}


text:
This is an attempt to make a web map

Now is the time for all good people to come to the aid of their country.

Hopefully, this will turn into something I want to present and share. Until then, I appreciate any and all help others are willing to offer. Thanks for reading.

redpajama_set_name: RedPajamaGithub


text:
title: Your first React App
---
## Your first React App
### Installation

As specified in the previous artice (Installation), run the `Create React App` tool. After everything has finished, `cd` into the folder of your application and run `npm start`.
This will start a development server and you are all set to start developing your app!
```bash
npm install -g create-react-app
create-react-app my-first-app

cd my-first-app
npm start
```

### Editing the code

Start up your editor or IDE of choice and edit the `App.js` file in the `src` folder. When created with the `react-create-app` tool, there will already be some code in this file.

The code will consist of these parts:
#### imports
```JavaScript
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
```

This is used by [webpack](https://webpack.js.org/) to import all required modules so that your code can use them. This code imports 3 modules:
1) `React` and `Component`, which allow us to use React as it should be used. (With components)
2) `logo`, which allows us to use `logo.svg` in this file.
3) `./App.css`, which imports the stylesheet for this file.

#### classes/components
```JavaScript
class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}
```

React is a library that makes use of Components, which let you split up your UI into independent, reusable pieces, and think about each piece in isolation.
There is already 1 component created, the `App` component. If you used the `create-react-app` tool, this component is the main component in the project and you should build around this central class.

We will look at components more detailed in next chapters.

#### exports
When creating a class in react, you should export them after declaration, which allows you to use the component in another file by using the `import` keyword. You can use `default` after the `export` keyword to tell React that this is the main class of this file.

```JavaScript
export default App;
```
### View the results!
When you've started the development server by issuing the `npm start` command, you can view the changes you add to your project live in your browser. After issuing the command, npm should open a browser automatically displaying your app.

### Sources
[1. React documentation](https://reactjs.org/docs/hello-world.html)


text:
using System;
using System.Globalization;
using Xunit;

namespace System.Globalization.CalendarsTests
{
    // System.Globalization.TaiwanCalendar.GetDayOfYear(Int32,Int32,Int32)
    public class TaiwanCalendarGetDaysInMonth
    {
        private readonly int[] _DAYS_PER_MONTHS_IN_LEAP_YEAR = new int[13]
        {
            0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
        };
        private readonly int[] _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR = new int[13]
        {
            0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
        };

        #region Positive Tests
        // PosTest1: Verify the day is a random Date
        [Fact]
        public void PosTest1()
        {
            System.Globalization.Calendar tc = new TaiwanCalendar();
            Random rand = new Random(-55);
            int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911);
            int month = rand.Next(1, 12);
            int era;
            int actualDays;
            if (tc.IsLeapYear(year))
            {
                actualDays = _DAYS_PER_MONTHS_IN_LEAP_YEAR[month];
            }
            else
            {
                actualDays = _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month];
            }

            for (int i = 0; i < tc.Eras.Length; i++)
            {
                era = tc.Eras[i];
                Assert.Equal(tc.GetDaysInMonth(year, month, era), actualDays);
            }
        }

        // PosTest2: Verify year is TaiwanCalendar MinSupportedDateTime
        [Fact]
        public void PosTest2()
        {
            System.Globalization.Calendar tc = new TaiwanCalendar();
            DateTime dt = tc.MinSupportedDateTime;
            int year = dt.Year;
            int month = dt.Month;
            int era;
            int actualDays;
            if (tc.IsLeapYear(year))
            {
                actualDays = _DAYS_PER_MONTHS_IN_LEAP_YEAR[month];
            }
            else
            {
                actualDays = _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month];
            }

            for (int i = 0; i < tc.Eras.Length; i++)
            {
                era = tc.Eras[i];
                Assert.Equal(tc.GetDaysInMonth(year, month, era), actualDays);
            }
        }

        // PosTest3: Verify the DateTime is TaiwanCalendar MaxSupportDateTime
        [Fact]
        public void PosTest3()
        {
            System.Globalization.Calendar tc = new TaiwanCalendar();
            DateTime dt = tc.MaxSupportedDateTime;
            int year = dt.Year - 1911;
            int month = dt.Month;
            int era;
            int actualDays;
            if (tc.IsLeapYear(year))
            {
                actualDays = _DAYS_PER_MONTHS_IN_LEAP_YEAR[month];
            }
            else
            {
                actualDays = _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month];
            }

            for (int i = 0; i < tc.Eras.Length; i++)
            {
                era = tc.Eras[i];
                Assert.Equal(tc.GetDaysInMonth(year, month, era), actualDays);
            }
        }

        // PosTest4: Verify the DateTime is leap year
        [Fact]
        public void PosTest4()
        {
            System.Globalization.Calendar tc = new TaiwanCalendar();
            DateTime dt = new DateTime(2000, 12, 31);
            int year = dt.Year;
            int month = dt.Month;
            int era;
            int actualDays;
            if (tc.IsLeapYear(year))
            {
                actualDays = _DAYS_PER_MONTHS_IN_LEAP_YEAR[month];
            }
            else
            {
                actualDays = _DAYS_PER_MONTHS_IN_NO_LEAP_YEAR[month];
            }
            for (int i = 0; i < tc.Eras.Length; i++)
            {
                era = tc.Eras[i];
                Assert.Equal(tc.GetDaysInMonth(year, month, era), actualDays);
            }
        }
        #endregion

        #region Negative Tests
        // NegTest1: The year greater than max year
        [Fact]
        public void NegTest1()
        {
            System.Globalization.Calendar tc = new TaiwanCalendar();
            Random rand = new Random(-55);
            int year = tc.MaxSupportedDateTime.Year - 1911 + rand.Next(1, Int32.MaxValue);
            int month = rand.Next(1, 13);
            int era = Calendar.CurrentEra;
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                tc.GetDaysInMonth(year, month, era);
            });
        }

        // NegTest2: The year less than min year
        [Fact]
        public void NegTest2()
        {
            System.Globalization.Calendar tc = new TaiwanCalendar();
            Random rand = new Random(-55);
            int year = tc.MinSupportedDateTime.Year - rand.Next(1, Int32.MaxValue);
            int month = rand.Next(1, 13);
            int era = Calendar.CurrentEra;
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                tc.GetDaysInMonth(year, month, era);
            });
        }

        // NegTest3: The month greater than 12
        [Fact]
        public void NegTest3()
        {
            System.Globalization.Calendar tc = new TaiwanCalendar();
            Random rand = new Random(-55);
            int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year + 1);
            int month = rand.Next(12, Int32.MaxValue);
            int era = Calendar.CurrentEra;
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                tc.GetDaysInMonth(year, month, era);
            });
        }

        // NegTest4: The month less than 1
        [Fact]
        public void NegTest4()
        {
            System.Globalization.Calendar tc = new TaiwanCalendar();
            Random rand = new Random(-55);
            int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year + 1);
            int month = rand.Next(Int32.MinValue, 1);
            int era = Calendar.CurrentEra;
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                tc.GetDaysInMonth(year, month, era);
            });
        }
        #endregion
    }
}


text:
package com.dumu.housego.presenter;

import com.dumu.housego.entity.FourDataPrograma;

public interface IFourDataProgramePresenter {
	void LoadProgrameData(FourDataPrograma fourdata);
}


text:
<!DOCTYPE html>
<html>
<head>
	<title>Panels Sample</title>
	<!-- -->
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<!-- -->
	<script src="../../../../enyo/enyo.js" type="text/javascript"></script>
	<script src="../../../layout/package.js" type="text/javascript"></script>
	<script src="../../../onyx/package.js" type="text/javascript"></script>
	<script src="../../../onyx/source/wip-package.js" type="text/javascript"></script>
	<!-- -->
	<link href="PanelsSample.css" rel="stylesheet">
	<script src="PanelsSample.js" type="text/javascript"></script>
	<!-- -->
</head>
<body>
<script type="text/javascript">
	new enyo.sample.PanelsSample().write();
</script>
</body>
</html>


text:
/*
 * Created on Oct 21, 2005
 */
package bp.common.io;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import bp.common.fp.Generator;

/**
 * @author benedictpaten
 */
public class MultiFastaParser_Generator implements Generator {
    private final FastaParser_Generator_Int[] fPGA;
    private final InputStream[] iSA;
    private boolean finished;
    private final String[] iDs;

    public MultiFastaParser_Generator(final String mfa) throws IOException {
        final List<Integer> starts = new LinkedList<Integer>();
        InputStream iS;
        iS = new BufferedInputStream(new FileInputStream(mfa));
        int i = 0, j;
        while ((j = iS.read()) != -1) {
            if (j == '>') {
                starts.add(new Integer(i));
            }
            i++;
        }
        iS.close();
        i = 0;
        this.fPGA = new FastaParser_Generator_Int[starts.size()];
        this.iDs = new String[starts.size()];
        this.iSA = new InputStream[this.fPGA.length];
        for (final Iterator<Integer> it = starts.iterator(); it.hasNext();) {
            j = it.next().intValue();
            iS = new FileInputStream(mfa);
            iS.skip(j);
            iS = new BufferedInputStream(iS);
            this.iSA[i] = iS;
            final FastaParser_Generator_Int fPG = new FastaParser_Generator_Int(
                    iS, Integer.MAX_VALUE);
            this.fPGA[i] = fPG;
            this.iDs[i++] = fPG.getFastaID();
        }
        this.finished = this.fPGA.length == 0;
    }

    /*
     * (non-Javadoc)
     *
     * @see bp.common.fp.Generator#gen()
     */
    public Object gen() {
        if(this.finished) {
			return null;
		}
        final int[] iA = new int[this.fPGA.length];
        for (int i = 0; i < this.fPGA.length; i++) {
            iA[i] = this.fPGA[i].gen();
        }
        if (iA[0] == Integer.MAX_VALUE) {
            this.finished = true;
            if(false && Debug.DEBUGCODE) {
                for (int i = 1; i < iA.length; i++) {
					if (iA[i] != Integer.MAX_VALUE) {
						throw new IllegalStateException();
					}
				}
            }
            for (final InputStream element : this.iSA) {
				try {
                    element.close();
                } catch (final IOException e) {
                    e.printStackTrace();
                    throw new IllegalStateException();
                }
			}
            return null;
        }
        return iA;
    }

    public void close() throws IOException {
        for (final InputStream element : this.iSA) {
			element.close();
		}
    }

    public String[] getFastaIDs() {
        return this.iDs;
    }
}


text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.DotNet.Tools.Clean;
using FluentAssertions;
using Xunit;
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.DotNet.Tools.Tests.Utilities;

namespace Microsoft.DotNet.Cli.MSBuild.Tests
{
    public class GivenDotnetCleanInvocation : IClassFixture<NullCurrentSessionIdFixture>
    {
        const string ExpectedPrefix = "exec <msbuildpath> -maxcpucount -verbosity:m -verbosity:normal -target:Clean";

        private static readonly string WorkingDirectory =
            TestPathUtilities.FormatAbsolutePath(nameof(GivenDotnetCleanInvocation));

        [Fact]
        public void ItAddsProjectToMsbuildInvocation()
        {
            var msbuildPath = "<msbuildpath>";
            CleanCommand.FromArgs(new string[] { "<project>" }, msbuildPath)
                .GetProcessStartInfo().Arguments.Should().Be("exec <msbuildpath> -maxcpucount -verbosity:m -verbosity:normal <project> -target:Clean");
        }

        [Theory]
        [InlineData(new string[] { }, "")]
        [InlineData(new string[] { "-o", "<output>" }, "-property:OutputPath=<cwd><output>")]
        [InlineData(new string[] { "--output", "<output>" }, "-property:OutputPath=<cwd><output>")]
        [InlineData(new string[] { "-f", "<framework>" }, "-property:TargetFramework=<framework>")]
        [InlineData(new string[] { "--framework", "<framework>" }, "-property:TargetFramework=<framework>")]
        [InlineData(new string[] { "-c", "<configuration>" }, "-property:Configuration=<configuration>")]
        [InlineData(new string[] { "--configuration", "<configuration>" }, "-property:Configuration=<configuration>")]
        [InlineData(new string[] { "-v", "diag" }, "-verbosity:diag")]
        [InlineData(new string[] { "--verbosity", "diag" }, "-verbosity:diag")]
        public void MsbuildInvocationIsCorrect(string[] args, string expectedAdditionalArgs)
        {
            CommandDirectoryContext.PerformActionWithBasePath(WorkingDirectory, () =>
            {
                expectedAdditionalArgs =
                    (string.IsNullOrEmpty(expectedAdditionalArgs) ? "" : $" {expectedAdditionalArgs}")
                    .Replace("<cwd>", WorkingDirectory);

                var msbuildPath = "<msbuildpath>";
                CleanCommand.FromArgs(args, msbuildPath)
                    .GetProcessStartInfo().Arguments.Should().Be($"{ExpectedPrefix}{expectedAdditionalArgs}");
            });
        }
    }
}


text:
use std::str::FromStr;
use std::fmt::{Display, Formatter, Error};
use std::default::Default;
use self::EntityType::*;

#[derive(Clone, Copy)]
pub enum EntityType {
    Player,
    Ground,
    Wall
}

pub enum EntityError {
    UnknownEntity,
    InvalidEntity
}

impl Default for EntityType {
    fn default() -> EntityType {EntityType::Ground}
}

#[derive(Clone, Copy, Default)]
pub struct Entity {
    pub kind: EntityType,
    pub x: usize,
    pub y: usize
}

impl Display for Entity {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        Display::fmt(match self.kind {
            Player => "Ů",
            Wall   => "𝌆",
            Ground => ".",
        }, f)
    }
}

// impl FromStr for Entity {
//     type Err = &'static str;

//     fn from_str(s: &str) -> Result<Entity, &'static str> {
//         match s{
//             'Ů' => Ok(Entity{kind: Player, ..Default::default()}),
//             '.' => Ok(Entity{kind: Ground, ..Default::default()}),
//             '𝌆' => Ok(Entity{kind: Wall, ..Default::default()}),
//             _   => Err("invalid string (unkown entity type)"),
//         }
//     }
// }

impl Entity {
    pub fn new(x: usize, y: usize) -> Entity{
        Entity{x: x, y: y, ..Default::default()}
    }
    pub fn from_char(mut self, c: char) -> Result<Entity, String>{
        match c{
            'Ů' => {self.kind = Player; Ok(self)},
            '.' => {self.kind = Ground; Ok(self)},
            '𝌆' => {self.kind = Wall; Ok(self)},
            _   => Err(format!("unknown entity for: {}", c))
        }
    }
    pub fn kind(mut self, kind: EntityType) -> Entity{
        self.kind = kind;
        self
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>BelajarUjian | Registrasi</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link href="<?php echo $base_url;?>css/bootstrap/bootstrap.css?v=<?php echo $version;?>" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link href="<?php echo $base_url;?>css/AdminLTE.min.css?v=<?php echo $version;?>" rel="stylesheet">

    <link href="<?php echo $base_url;?>css/iCheck/square/blue.css?v=<?php echo $version;?>" rel="stylesheet">

        BelajarUjian

Registrasi

        <form action="../../index.html" method="post">

            <input type="text" class="form-control" placeholder="Nama Lengkap">

            <input type="email" class="form-control" placeholder="Email">

            <input type="password" class="form-control" placeholder="Password">

            <input type="password" class="form-control" placeholder="Ketik Ulang Password">

               <input type="tel" class="form-control" placeholder="Nomor HP">

                  <input type="checkbox"> I agree to the terms

              <button type="submit" class="btn btn-primary btn-block btn-flat">Daftar</button>

        </form>

        <a href="<?php echo $base_url;?>index.php/main/login" class="text-center">Saya sudah terdaftar


text:
import ThirdPartyFacades from '../../audits/third-party-facades.js';
import {networkRecordsToDevtoolsLog} from '../network-records-to-devtools-log.js';
import {createTestTrace} from '../create-test-trace.js';
import {getURLArtifactFromDevtoolsLog, readJson} from '../test-utils.js';

const pwaTrace = readJson('../fixtures/traces/progressive-app-m60.json', import.meta);
const pwaDevtoolsLog = readJson('../fixtures/traces/progressive-app-m60.devtools.log.json', import.meta);
const videoEmbedsTrace = readJson('../fixtures/traces/video-embeds-m84.json', import.meta);
const videoEmbedsDevtolsLog = readJson('../fixtures/traces/video-embeds-m84.devtools.log.json', import.meta);
const noThirdPartyTrace = readJson('../fixtures/traces/no-tracingstarted-m74.json', import.meta);

function intercomProductUrl(id) {
  return `https://widget.intercom.io/widget/${id}`;
}

function intercomResourceUrl(id) {
  return `https://js.intercomcdn.com/frame-modern.${id}.js`;
}

function youtubeProductUrl(id) {
  return `https://www.youtube.com/embed/${id}`;
}

function youtubeResourceUrl(id) {
  return `https://i.ytimg.com/${id}/maxresdefault.jpg`;
}
describe('Third party facades audit', () => {
  it('correctly identifies a third party product with facade alternative', async () => {
    const artifacts = {
      devtoolsLogs: {
        defaultPass: networkRecordsToDevtoolsLog([
          {transferSize: 2000, url: 'https://example.com'},
          {transferSize: 4000, url: intercomProductUrl('1')},
          {transferSize: 8000, url: intercomResourceUrl('a')},
        ]),
      },
      traces: {defaultPass: createTestTrace({timeOrigin: 0, traceEnd: 2000})},
      URL: {mainDocumentUrl: 'https://example.com'},
    };

    const settings = {throttlingMethod: 'simulate', throttling: {cpuSlowdownMultiplier: 4}};
    const results = await ThirdPartyFacades.audit(artifacts, {computedCache: new Map(), settings});

    expect(results.score).toBe(0);
    expect(results.displayValue).toBeDisplayString('1 facade alternative available');
    expect(results.details.items[0].product)
      .toBeDisplayString('Intercom Widget (Customer Success)');
    expect(results.details.items).toMatchObject([
      {
        transferSize: 12000,
        blockingTime: 0,
        subItems: {
          type: 'subitems',
          items: [
            {
              url: 'https://js.intercomcdn.com/frame-modern.a.js',
              mainThreadTime: 0,
              blockingTime: 0,
              transferSize: 8000,
            },
            {
              url: 'https://widget.intercom.io/widget/1',
              mainThreadTime: 0,
              blockingTime: 0,
              transferSize: 4000,
            },
          ],
        },
      },
    ]);
  });

  it('handles multiple products with facades', async () => {
    const artifacts = {
      devtoolsLogs: {
        defaultPass: networkRecordsToDevtoolsLog([
          {transferSize: 2000, url: 'https://example.com'},
          {transferSize: 4000, url: intercomProductUrl('1')},
          {transferSize: 3000, url: youtubeProductUrl('2')},
          {transferSize: 8000, url: intercomResourceUrl('a')},
          {transferSize: 7000, url: youtubeResourceUrl('b')},
        ]),
      },
      traces: {defaultPass: createTestTrace({timeOrigin: 0, traceEnd: 2000})},
      URL: {mainDocumentUrl: 'https://example.com'},
    };

    const settings = {throttlingMethod: 'simulate', throttling: {cpuSlowdownMultiplier: 4}};
    const results = await ThirdPartyFacades.audit(artifacts, {computedCache: new Map(), settings});

    expect(results.score).toBe(0);
    expect(results.displayValue).toBeDisplayString('2 facade alternatives available');
    expect(results.details.items[0].product)
      .toBeDisplayString('Intercom Widget (Customer Success)');
    expect(results.details.items[1].product).toBeDisplayString('YouTube Embedded Player (Video)');
    expect(results.details.items).toMatchObject([
      {
        transferSize: 12000,
        blockingTime: 0,
        subItems: {
          type: 'subitems',
          items: [
            {
              url: 'https://js.intercomcdn.com/frame-modern.a.js',
              mainThreadTime: 0,
              blockingTime: 0,
              transferSize: 8000,
            },
            {
              url: 'https://widget.intercom.io/widget/1',
              mainThreadTime: 0,
              blockingTime: 0,
              transferSize: 4000,
            },
          ],
        },
      },
      {
        transferSize: 10000,
        blockingTime: 0,
        subItems: {
          type: 'subitems',
          items: [
            {
              url: 'https://i.ytimg.com/b/maxresdefault.jpg',
              mainThreadTime: 0,
              blockingTime: 0,
              transferSize: 7000,
            },
            {
              url: 'https://www.youtube.com/embed/2',
              mainThreadTime: 0,
              blockingTime: 0,
              transferSize: 3000,
            },
          ],
        },
      },
    ]);
  });

  it('handle multiple requests to same product resource', async () => {
    const artifacts = {
      devtoolsLogs: {
        defaultPass: networkRecordsToDevtoolsLog([
          {transferSize: 2000, url: 'https://example.com'},
          {transferSize: 2000, url: intercomProductUrl('1')},
          {transferSize: 8000, url: intercomResourceUrl('a')},
          {transferSize: 2000, url: intercomProductUrl('1')},
        ]),
      },
      traces: {defaultPass: createTestTrace({timeOrigin: 0, traceEnd: 2000})},
      URL: {mainDocumentUrl: 'https://example.com'},
    };

    const settings = {throttlingMethod: 'simulate', throttling: {cpuSlowdownMultiplier: 4}};
    const results = await ThirdPartyFacades.audit(artifacts, {computedCache: new Map(), settings});

    expect(results.score).toBe(0);
    expect(results.displayValue).toBeDisplayString('1 facade alternative available');
    expect(results.details.items[0].product)
      .toBeDisplayString('Intercom Widget (Customer Success)');
    expect(results.details.items).toMatchObject([
      {
        transferSize: 12000,
        blockingTime: 0,
        subItems: {
          type: 'subitems',
          items: [
            {
              url: 'https://js.intercomcdn.com/frame-modern.a.js',
              mainThreadTime: 0,
              blockingTime: 0,
              transferSize: 8000,
            },
            {
              url: 'https://widget.intercom.io/widget/1',
              mainThreadTime: 0,
              blockingTime: 0,
              transferSize: 4000,
            },
          ],
        },
      },
    ]);
  });

  it('does not report first party resources', async () => {
    const artifacts = {
      devtoolsLogs: {
        defaultPass: networkRecordsToDevtoolsLog([
          {transferSize: 2000, url: 'https://intercomcdn.com'},
          {transferSize: 4000, url: intercomProductUrl('1')},
        ]),
      },
      traces: {defaultPass: createTestTrace({timeOrigin: 0, traceEnd: 2000})},
      URL: {mainDocumentUrl: 'https://intercomcdn.com'},
    };

    const settings = {throttlingMethod: 'simulate', throttling: {cpuSlowdownMultiplier: 4}};
    const results = await ThirdPartyFacades.audit(artifacts, {computedCache: new Map(), settings});

    expect(results).toEqual({
      score: 1,
      notApplicable: true,
    });
  });

  it('only reports resources which have facade alternatives', async () => {
    const artifacts = {
      // This devtools log has third party requests but none have facades
      devtoolsLogs: {defaultPass: pwaDevtoolsLog},
      traces: {defaultPass: pwaTrace},
      URL: getURLArtifactFromDevtoolsLog(pwaDevtoolsLog),
    };

    const settings = {throttlingMethod: 'simulate', throttling: {cpuSlowdownMultiplier: 4}};
    const results = await ThirdPartyFacades.audit(artifacts, {computedCache: new Map(), settings});

    expect(results).toEqual({
      score: 1,
      notApplicable: true,
    });
  });

  it('not applicable when no third party resources are present', async () => {
    const artifacts = {
      devtoolsLogs: {
        defaultPass: networkRecordsToDevtoolsLog([
          {transferSize: 2000, url: 'https://example.com'},
        ]),
      },
      traces: {defaultPass: noThirdPartyTrace},
      URL: {mainDocumentUrl: 'https://example.com'},
    };

    const settings = {throttlingMethod: 'simulate', throttling: {cpuSlowdownMultiplier: 4}};
    const results = await ThirdPartyFacades.audit(artifacts, {computedCache: new Map(), settings});

    expect(results).toEqual({
      score: 1,
      notApplicable: true,
    });
  });

  it('handles real trace', async () => {
    const artifacts = {
      devtoolsLogs: {defaultPass: videoEmbedsDevtolsLog},
      traces: {defaultPass: videoEmbedsTrace},
      URL: getURLArtifactFromDevtoolsLog(videoEmbedsDevtolsLog),
    };

    const settings = {throttlingMethod: 'simulate', throttling: {cpuSlowdownMultiplier: 4}};
    const results = await ThirdPartyFacades.audit(artifacts, {computedCache: new Map(), settings});

    expect(results.score).toBe(0);
    expect(results.displayValue).toBeDisplayString('2 facade alternatives available');
    expect(results.details.items[0].product).toBeDisplayString('YouTube Embedded Player (Video)');
    expect(results.details.items[1].product).toBeDisplayString('Vimeo Embedded Player (Video)');
    expect(results.details.items).toMatchObject(
      [
        {
          transferSize: 651350,
          blockingTime: 0,
          subItems: {
            items: [
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 459603,
                url: 'https://www.youtube.com/s/player/e0d83c30/player_ias.vflset/en_US/base.js',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 66273,
                url: 'https://i.ytimg.com/vi/tgbNymZ7vqY/maxresdefault.jpg',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 50213,
                url: 'https://www.youtube.com/s/player/e0d83c30/www-embed-player.vflset/www-embed-player.js',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 46813,
                url: 'https://www.youtube.com/s/player/e0d83c30/www-player.css',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 11477,
                url: 'https://www.youtube.com/s/player/e0d83c30/player_ias.vflset/en_US/embed.js',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 16971,
                url: {
                  formattedDefault: 'Other resources',
                },
              },
            ],
            type: 'subitems',
          },
        },
        {
          transferSize: 184495,
          blockingTime: 0,
          subItems: {
            items: [
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 145772,
                url: 'https://f.vimeocdn.com/p/3.22.3/js/player.js',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 17633,
                url: 'https://f.vimeocdn.com/p/3.22.3/css/player.css',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 9313,
                url: 'https://i.vimeocdn.com/video/784397921.webp?mw=1200&mh=675&q=70',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 8300,
                url: 'https://player.vimeo.com/video/336812660',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 1474,
                url: 'https://f.vimeocdn.com/js_opt/modules/utils/vuid.min.js',
              },
              {
                blockingTime: 0,
                mainThreadTime: 0,
                transferSize: 2003,
                url: {
                  formattedDefault: 'Other resources',
                },
              },
            ],
            type: 'subitems',
          },
        },
      ]
    );
  });

  describe('.condenseItems', () => {
    it('basic case', () => {
      const items = [
        {url: 'd', transferSize: 500, blockingTime: 5},
        {url: 'b', transferSize: 1000, blockingTime: 0},
        {url: 'c', transferSize: 500, blockingTime: 5},
        {url: 'e', transferSize: 500, blockingTime: 5},
        {url: 'a', transferSize: 5000, blockingTime: 0},
      ];
      ThirdPartyFacades.condenseItems(items);
      expect(items).toMatchObject([
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'b', transferSize: 1000, blockingTime: 0},
        {url: {formattedDefault: 'Other resources'}, transferSize: 1500, blockingTime: 15},
      ]);
    });

    it('only shown top 5 items', () => {
      const items = [
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 5},
        {url: 'a', transferSize: 5000, blockingTime: 5},
      ];
      ThirdPartyFacades.condenseItems(items);
      expect(items).toMatchObject([
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: {formattedDefault: 'Other resources'}, transferSize: 10000, blockingTime: 10},
      ]);
    });

    it('hide condensed row if total transfer size <1KB', () => {
      const items = [
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'b', transferSize: 100, blockingTime: 0},
        {url: 'c', transferSize: 100, blockingTime: 0},
      ];
      ThirdPartyFacades.condenseItems(items);
      expect(items).toMatchObject([
        {url: 'a', transferSize: 5000, blockingTime: 0},
      ]);
    });

    it('always show at least one item', () => {
      const items = [
        {url: 'a', transferSize: 500, blockingTime: 0},
        {url: 'b', transferSize: 500, blockingTime: 0},
        {url: 'c', transferSize: 500, blockingTime: 0},
      ];
      ThirdPartyFacades.condenseItems(items);
      expect(items).toMatchObject([
        {url: 'a', transferSize: 500, blockingTime: 0},
        {url: {formattedDefault: 'Other resources'}, transferSize: 1000, blockingTime: 0},
      ]);
    });

    it('single small item', () => {
      const items = [
        {url: 'a', transferSize: 500, blockingTime: 0},
      ];
      ThirdPartyFacades.condenseItems(items);
      expect(items).toMatchObject([
        {url: 'a', transferSize: 500, blockingTime: 0},
      ]);
    });

    it('do not condense if only one item to condense', () => {
      const items = [
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'c', transferSize: 500, blockingTime: 0},
      ];
      ThirdPartyFacades.condenseItems(items);
      expect(items).toMatchObject([
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'a', transferSize: 5000, blockingTime: 0},
        {url: 'c', transferSize: 500, blockingTime: 0},
      ]);
    });
  });
});


text:
var App = require('app');
var LZString = require('utils/lz-string');

/**
 * Small mixin for processing user preferences
 * Provide methods to save/load some values in persist storage
 * Save available only for admin users!
 * When using this mixin you should redeclare methods:
 *

 *
getUserPrefSuccessCallback

 *
getUserPrefErrorCallback

 *
postUserPrefSuccessCallback

 *
postUserPrefErrorCallback

 *

 * @type {Em.Mixin}
 */
App.Persist = Em.Mixin.create({

  /**
   * Additional to request data
   * @type {object}
   */
  additionalData: {},

  /**
   * Get persist value from server with persistKey
   * @param {String} key
   */
  getUserPref: function(key) {
    return App.ajax.send({
      name: 'persist.get',
      sender: this,
      data: {
        key: key,
        data: this.get('additionalData')
      },
      success: 'getUserPrefSuccessCallback',
      error: 'getUserPrefErrorCallback'
    });
  },

  /**
   *
   * @param {string} key
   * @returns {$.Deferred}
   */
  getDecompressedData: function(key) {
    var dfd = $.Deferred();
    App.ajax.send({
      name: 'persist.get.text',
      sender: this,
      data: {
        key: key
      }
    }).always(function(data, textStatus, error) {
      if (data && typeof data === 'string') {
        dfd.resolve(JSON.parse(LZString.decompressFromBase64(data)));
      } else {
        dfd.reject({error: error});
      }
    });
    return dfd.promise();
  },

  /**
   * Should be redefined in objects that use this mixin
   * @param {*} response
   * @param {Object} request
   * @param {Object} data
   * @returns {*}
   */
  getUserPrefSuccessCallback: function (response, request, data) {},

  /**
   * Should be redefined in objects that use this mixin
   * @param {Object} request
   * @param {Object} ajaxOptions
   * @param {String} error
   */
  getUserPrefErrorCallback: function (request, ajaxOptions, error) {},

  /**
   * Post persist key/value to server, value is object
   * Only for admin users!
   * @param {String} key
   * @param {Object} value
   */
  postUserPref: function (key, value) {
    if (!App.isAuthorized('CLUSTER.MANAGE_USER_PERSISTED_DATA')) {
      return $.Deferred().reject().promise();
    }
    var keyValuePair = {};
    keyValuePair[key] = JSON.stringify(value);
    return this.post(keyValuePair);
  },

  /**
   *
   * @param {string} key
   * @param {Object} value
   * @returns {$.ajax}
   */
  postCompressedData: function (key, value) {
    var keyValuePair = {};
    keyValuePair[key] = !Em.isEmpty(value) ? LZString.compressToBase64(JSON.stringify(value)) : '';
    return this.post(keyValuePair);
  },

  post: function(keyValuePair) {
    return App.ajax.send({
      'name': 'persist.post',
      'sender': this,
      'beforeSend': 'postUserPrefBeforeSend',
      'data': {
        'keyValuePair': keyValuePair
      },
      'success': 'postUserPrefSuccessCallback',
      'error': 'postUserPrefErrorCallback'
    });
  },

  /**
   * Should be redefined in objects that use this mixin
   * @param {*} response
   * @param {Object} request
   * @param {Object} data
   * @returns {*}
   */
  postUserPrefSuccessCallback: function (response, request, data) {},

  /**
   * Should be redefined in objects that use this mixin
   * @param {Object} request
   * @param {Object} ajaxOptions
   * @param {String} error
   */
  postUserPrefErrorCallback: function(request, ajaxOptions, error) {},

  /**
   * Little log before post request
   * @param {Object} request
   * @param {Object} ajaxOptions
   * @param {Object} data
   */
  postUserPrefBeforeSend: function(request, ajaxOptions, data){
  }

});


text:
Contributing
============

How to contribute
-----------------

The preferred way to contribute to `sed_eval` is to fork the
[main repository](https://github.com/TUT-ARG/sed_eval) on
GitHub:

1. Fork the [project repository](https://github.com/TUT-ARG/sed_eval):
   click on the 'Fork' button near the top of the page. This creates
   a copy of the code under your account on the GitHub server.

2. Clone this copy to your local disk:

        git clone git@github.com:[YOUR_LOGIN]/sed_eval.git
        cd sed_eval

3. Create a branch to hold your changes:

        git checkout -b my-new-feature

   and start making changes. You should never work in the ``master`` branch directly.

4. Work on this copy on your computer using Git to do the version
   control. When you're done editing, do:

        git add [MODIFIED FILES]
        git commit

   to record your changes in Git, then push them to GitHub with:

        git push -u origin my-new-feature

Finally, go to the web page of the your fork of the sed_eval repo,
and click 'Pull request' to send your changes to the maintainers for
review. This will send an email to the committers.

More information about this kind of process can be found in
[Git documentation](http://git-scm.com/documentation).

You should check that your contribution complies with the
following rules before submitting a pull request:

- All public methods should have informative docstrings
- Code should be sufficiently commented
- For major new features there should be also an unittest

You should check for common programming errors with the following
tools:

-  Check unittests:

        pip install nose coverage
        cd tests/
        nosetests -v --with-coverage --cover-erase --cover-html --cover-package=sed_eval --nocapture

-  There should be no major pyflakes warnings, check with:

        pip install pyflakes
        pyflakes path/to/module.py

-  There should be no major PEP8 warnings, check with:

        pip install pep8
        pep8 path/to/module.py

Creating an issue
-----------------

We use Github issues to track all bugs and feature requests; feel free to
open an issue if you have found a bug or wish to see a new feature implemented.

It is recommended to check that your issue complies with the
following rules before submitting:

-  Verify that your issue is not being currently addressed by other
   [issues](https://github.com/TUT-ARG/sed_eval/issues?q=)
   or [pull requests](https://github.com/TUT-ARG/sed_eval/pulls?q=).

-  Please ensure all code snippets and error messages are formatted in
   appropriate code blocks.
   See [Creating and highlighting code blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks).

-  Please include your operating system type and version number, as well
   as your Python, numpy, and dcase_util versions. You can get this
   information with following code:

    import platform; print(platform.platform())
    import sys; print("Python", sys.version)
    import numpy; print("NumPy", numpy.__version__)

Documentation
-------------

You can edit the documentation using any text editor and then generate
the HTML output by typing ``make html`` from the docs/ directory.
The resulting HTML files will be placed in docs/ and are viewable
in a web browser. See the README file in the documentation/ directory for more information.

Note
----
This document is based on contribution instructions for [LibROSA](https://github.com/librosa/librosa).


text:
"""
Test class for iRMC Deploy Driver
"""

import mock
import testtools

from ironic.common import exception
from ironic.drivers import irmc

class IRMCVirtualMediaIscsiTestCase(testtools.TestCase):

    def setUp(self):
        irmc.deploy._check_share_fs_mounted_patcher.start()
        super(IRMCVirtualMediaIscsiTestCase, self).setUp()

    @mock.patch.object(irmc.importutils, 'try_import', spec_set=True,
                       autospec=True)
    def test___init___share_fs_mounted_ok(self,
                                          mock_try_import):
        mock_try_import.return_value = True

        driver = irmc.IRMCVirtualMediaIscsiDriver()

        self.assertIsInstance(driver.power, irmc.power.IRMCPower)
        self.assertIsInstance(driver.deploy,
                              irmc.deploy.IRMCVirtualMediaIscsiDeploy)
        self.assertIsInstance(driver.console,
                              irmc.ipmitool.IPMIShellinaboxConsole)
        self.assertIsInstance(driver.management,
                              irmc.management.IRMCManagement)
        self.assertIsInstance(driver.vendor, irmc.deploy.VendorPassthru)

    @mock.patch.object(irmc.importutils, 'try_import')
    def test___init___try_import_exception(self, mock_try_import):
        mock_try_import.return_value = False

        self.assertRaises(exception.DriverLoadError,
                          irmc.IRMCVirtualMediaIscsiDriver)

    @mock.patch.object(irmc.deploy.IRMCVirtualMediaIscsiDeploy, '__init__',
                       spec_set=True, autospec=True)
    def test___init___share_fs_not_mounted_exception(self, __init___mock):
        __init___mock.side_effect = iter(
            [exception.IRMCSharedFileSystemNotMounted()])

        self.assertRaises(exception.IRMCSharedFileSystemNotMounted,
                          irmc.IRMCVirtualMediaIscsiDriver)

class IRMCVirtualMediaAgentTestCase(testtools.TestCase):

    def setUp(self):
        irmc.deploy._check_share_fs_mounted_patcher.start()
        super(IRMCVirtualMediaAgentTestCase, self).setUp()

    @mock.patch.object(irmc.importutils, 'try_import', spec_set=True,
                       autospec=True)
    def test___init___share_fs_mounted_ok(self,
                                          mock_try_import):
        mock_try_import.return_value = True

        driver = irmc.IRMCVirtualMediaAgentDriver()

        self.assertIsInstance(driver.power, irmc.power.IRMCPower)
        self.assertIsInstance(driver.deploy,
                              irmc.deploy.IRMCVirtualMediaAgentDeploy)
        self.assertIsInstance(driver.console,
                              irmc.ipmitool.IPMIShellinaboxConsole)
        self.assertIsInstance(driver.management,
                              irmc.management.IRMCManagement)
        self.assertIsInstance(driver.vendor,
                              irmc.deploy.IRMCVirtualMediaAgentVendorInterface)

    @mock.patch.object(irmc.importutils, 'try_import')
    def test___init___try_import_exception(self, mock_try_import):
        mock_try_import.return_value = False

        self.assertRaises(exception.DriverLoadError,
                          irmc.IRMCVirtualMediaAgentDriver)

    @mock.patch.object(irmc.deploy.IRMCVirtualMediaAgentDeploy, '__init__',
                       spec_set=True, autospec=True)
    def test___init___share_fs_not_mounted_exception(self, __init___mock):
        __init___mock.side_effect = iter([
            exception.IRMCSharedFileSystemNotMounted()])

        self.assertRaises(exception.IRMCSharedFileSystemNotMounted,
                          irmc.IRMCVirtualMediaAgentDriver)


text:
/**
 * Created on 2008-3-5 23:06:27
 */
package cn.net.openid.jos.dao.hibernate;

import java.util.Collection;

import cn.net.openid.jos.dao.PasswordDao;
import cn.net.openid.jos.domain.Password;
import cn.net.openid.jos.domain.User;

/**
 * The {@link PasswordDao} implementation using <a
 * href="https://www.hibernate.org/">Hibernate</a>.
 *
 * @author Sutra Zhou
 */
public class HibernatePasswordDao extends BaseHibernateEntityDao<Password>
		implements PasswordDao {
	/**
	 * The HQL query string for getting infinite passwor count.
	 */
	private static final String GET_INFINITE_PASSWORD_COUNT_QUERY_STRING
		= "select count(*) from Password"
			+ " where user = ? and maximumServiceTimes = "
			+ Password.INFINITE_SERVICE_TIMES;

	/**
	 * {@inheritDoc}
	 */
	public Password getPassword(final String id) {
		return get(id);
	}

	/**
	 * {@inheritDoc}
	 */
	public Collection<Password> getPasswords(final User user) {
		return findAll("from Password where user.id = ?", user.getId());
	}

	/**
	 * {@inheritDoc}
	 */
	public long getInfinitePasswordCount(final User user) {
		return count(GET_INFINITE_PASSWORD_COUNT_QUERY_STRING, user);
	}

	/**
	 * {@inheritDoc}
	 */
	public void deletePassword(final String id) {
		getHibernateTemplate().delete(this.get(id));
	}

	/**
	 * {@inheritDoc}
	 */
	public void insertPassword(final Password password) {
		getHibernateTemplate().save(password);
	}

	/**
	 * {@inheritDoc}
	 */
	public void updatePassword(final Password password) {
		getHibernateTemplate().update(password);
	}

}


text:
#ifndef MAIN_H_
#define MAIN_H_

namespace Main {
	extern Player player;
	extern Bunnyhop bhop;
	extern HWND window;
	extern DWORD pid;
	extern DWORD module_base;
	extern Util util;
	extern HANDLE process;
	extern DWORD player_base;
	extern DWORD mflags;
	extern POINT center;
	extern POINT cursor_pos;
	extern bool bhop_enabled;
}

#endif


text:
layout: post
title: "Como criar imagem de CD ROM para distirbuição no linux/windows"
description: ""
category: "linux"
tags: ["cd-rom","distribuição"]
---
{% include JB/setup %}

Comando para gerar imagem para distribuição (compatível com vários sistemas operacionais):

    genisoimage -f -J -joliet-long -r -allow-lowercase -allow-multidot -o ~/mpgoa-cd-rom.iso /home/eduardo/Dropbox/mpgoa/2-cd-rom/mpgoa-cd-rom-imagem


text:
#include "../Classes/AppDelegate.h"
#include "cocos2d.h"
#include "CCEGLView.h"

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string>

USING_NS_CC;

// 500 is enough?
#define MAXPATHLEN 500

int main(int argc, char **argv)
{
    // get application path
    int length;
    char fullpath[MAXPATHLEN];
    length = readlink("/proc/self/exe", fullpath, sizeof(fullpath));
    fullpath[length] = '\0';

    std::string resourcePath = fullpath;
    resourcePath = resourcePath.substr(0, resourcePath.find_last_of("/"));
    resourcePath += "/../../../Resources/";

    // create the application instance
    AppDelegate app;
    CCApplication::sharedApplication()->setResourceRootPath(resourcePath.c_str());
    CCEGLView* eglView = CCEGLView::sharedOpenGLView();
    eglView->setFrameSize(480, 320);
    return CCApplication::sharedApplication()->run();
}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

namespace Squidex.Infrastructure.UsageTracking;

public interface IApiUsageTracker
{
    Task DeleteAsync(string key,
        CancellationToken ct = default);

    Task TrackAsync(DateTime date, string key, string? category, double weight, long elapsedMs, long bytes,
        CancellationToken ct = default);

    Task<long> GetMonthCallsAsync(string key, DateTime date, string? category,
        CancellationToken ct = default);

    Task<long> GetMonthBytesAsync(string key, DateTime date, string? category,
        CancellationToken ct = default);

    Task<(ApiStatsSummary, Dictionary<string, List<ApiStats>> Details)> QueryAsync(string key, DateTime fromDate, DateTime toDate,
        CancellationToken ct = default);
}


text:
#pragma once

#if ENABLE(MEDIA_STREAM)

#include "RealtimeMediaSource.h"
#include <wtf/RefCounted.h>

namespace WebCore {

class MediaStreamConstraintsValidationClient : public RefCounted<MediaStreamConstraintsValidationClient> {
public:
    virtual ~MediaStreamConstraintsValidationClient() = default;

    virtual void constraintsAreValid() = 0;
    virtual void constraintsInvalid(const String& constraintName) = 0;
};

} // namespace WebCore

#endif // ENABLE(MEDIA_STREAM)


text:
namespace Microsoft.Azure.Management.Network.Fluent.HasHostName.Update
{
    /// <summary>
    /// The stage of an update allowing to specify a host name.
    /// </summary>
    /// <typeparam name="ReturnT">The next stage of the update.</typeparam>
    public interface IWithHostName<ReturnT>
    {
        /// <summary>
        /// Specifies the host name.
        /// </summary>
        /// <param name="hostName">An existing host name.</param>
        /// <return>The next stage of the update.</return>
        ReturnT WithHostName(string hostName);
    }
}


text:
package com.linecorp.bot.model.event;

import static org.assertj.core.api.Assertions.assertThat;

import java.lang.reflect.Method;

import org.junit.jupiter.api.Test;

import com.linecorp.bot.model.event.message.MessageContent;

public class MessageEventTest {
    @Test
    public void getMessageBinaryCompatibilityTest() throws NoSuchMethodException {
        Method method = MessageEvent.class.getMethod("getMessage");

        assertThat(method.getReturnType()).isEqualTo(MessageContent.class)
                                          .isNotEqualTo(Object.class);
    }
}


text:
import responses
from hamcrest import (
    assert_that,
    calling,
    has_entry,
    instance_of,
    raises,
    starts_with
)
from pydeform import six
from pydeform.client import ProjectClient, SessionAuthClient
from pydeform.exceptions import AuthError, ConflictError, NotFoundError
from testutils import DeformClientTestCaseMixin, TestCase

class ClientTest__user(DeformClientTestCaseMixin, TestCase):
    def test_login(self):
        response = self.deform_client.user.login(
            email=self.CONFIG['DEFORM']['EMAIL'],
            password=self.CONFIG['DEFORM']['PASSWORD']
        )
        assert_that(response, instance_of(six.text_type))

    def test_login__email_not_exists(self):
        assert_that(
            calling(self.deform_client.user.login).with_args(
                email='a' + self.CONFIG['DEFORM']['EMAIL'],
                password=self.CONFIG['DEFORM']['PASSWORD']
            ),
            raises(AuthError, '^Wrong credentials provided\.$')
        )

    def test_login__wrong_password(self):
        assert_that(
            calling(self.deform_client.user.login).with_args(
                email=self.CONFIG['DEFORM']['EMAIL'],
                password='a' + self.CONFIG['DEFORM']['PASSWORD']
            ),
            raises(AuthError, '^Wrong credentials provided\.$')
        )

    def test_create_new_user(self):
        with responses.RequestsMock() as rsps:
            rsps.add(
                self.deform_client.user.create.method.upper(),
                self.deform_client.user.create.get_context({})['url'],
                json={
                    'message': 'Check your email for confirmation code'
                },
                status=201
            )
            response = self.deform_client.user.create(
                email='a' + self.CONFIG['DEFORM']['EMAIL'],
                password=self.CONFIG['DEFORM']['PASSWORD']
            )
            assert_that(
                response,
                has_entry('message', 'Check your email for confirmation code')
            )

    def test_create_user_with_existing_email(self):
        assert_that(
            calling(self.deform_client.user.create).with_args(
                email=self.CONFIG['DEFORM']['EMAIL'],
                password=self.CONFIG['DEFORM']['PASSWORD']
            ),
            raises(ConflictError, '^User already exists.$')
        )

    def test_confirm(self):
        session_id = 'Qivjy3PW3dqxAOY9i4MeT1H0FHyGkw'
        with responses.RequestsMock() as rsps:
            rsps.add(
                self.deform_client.user.confirm.method.upper(),
                self.deform_client.user.confirm.get_context({})['url'],
                json={
                    'sessionId': session_id
                },
                status=200
            )
            response = self.deform_client.user.confirm(
                code='12345'
            )
            assert_that(
                response,
                has_entry('sessionId', session_id)
            )

    def test_confirm_not_existing_code(self):
        assert_that(
            calling(self.deform_client.user.confirm).with_args(
                code='12345'
            ),
            raises(NotFoundError, '^Confirmation code not found\.$')
        )

    def test_confirm_already_confirmed_code(self):
        with responses.RequestsMock() as rsps:
            rsps.add(
                self.deform_client.user.confirm.method.upper(),
                self.deform_client.user.confirm.get_context({})['url'],
                json={
                    'message': 'User already exists.'
                },
                status=409
            )
            assert_that(
                calling(self.deform_client.user.confirm).with_args(
                    code='12345'
                ),
                raises(ConflictError, '^User already exists\.$')
            )

class ClientTest__auth(DeformClientTestCaseMixin, TestCase):
    def test_auth_by_session(self):
        response = self.deform_client.auth(
            auth_type='session',
            auth_key='test'
        )
        assert_that(response, instance_of(SessionAuthClient))
        assert_that(response.auth_header, starts_with('SessionId'))

    def test_auth_by_token_without_project_id(self):
        assert_that(
            calling(self.deform_client.auth).with_args(
                auth_type='token',
                auth_key='test'
            ),
            raises(
                ValueError,
                '^You should provide project_id for token authentication$'
            )
        )

    def test_auth_by_token_with_project_id(self):
        response = self.deform_client.auth(
            auth_type='token',
            auth_key='test',
            project_id='some_project'
        )
        assert_that(response, instance_of(ProjectClient))
        assert_that(response.auth_header, starts_with('Token'))


text:
package org.jf.util;

import com.google.common.collect.Lists;

import java.io.FilterWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;

public class WrappedIndentingWriter extends FilterWriter {

    private final int maxIndent;
    private final int maxWidth;

    private int currentIndent = 0;
    private final StringBuilder line = new StringBuilder();

    public WrappedIndentingWriter(Writer out, int maxIndent, int maxWidth) {
        super(out);
        this.maxIndent = maxIndent;
        this.maxWidth = maxWidth;
    }

    private void writeIndent() throws IOException {
        for (int i=0; i<getIndent(); i++) {
            write(' ');
        }
    }

    private int getIndent() {
        if (currentIndent < 0) {
            return 0;
        }
        if (currentIndent > maxIndent) {
            return maxIndent;
        }
        return currentIndent;
    }

    public void indent(int indent) {
        currentIndent += indent;
    }

    public void deindent(int indent) {
        currentIndent -= indent;
    }

    private void wrapLine() throws IOException {
        List<String> wrapped = Lists.newArrayList(StringWrapper.wrapStringOnBreaks(line.toString(), maxWidth));
        out.write(wrapped.get(0), 0, wrapped.get(0).length());
        out.write('\n');

        line.replace(0, line.length(), "");
        writeIndent();
        for (int i=1; i<wrapped.size(); i++) {
            if (i > 1) {
                write('\n');
            }
            write(wrapped.get(i));
        }
    }

    @Override public void write(int c) throws IOException {
        if (c == '\n') {
            out.write(line.toString());
            out.write(c);
            line.replace(0, line.length(), "");
            writeIndent();
        } else {
            line.append((char)c);
            if (line.length() > maxWidth) {
                wrapLine();
            }
        }
    }

    @Override public void write(char[] cbuf, int off, int len) throws IOException {
        for (int i=0; i<len; i++) {
            write(cbuf[i+off]);
        }
    }

    @Override public void write(String str, int off, int len) throws IOException {
        for (int i=0; i<len; i++) {
            write(str.charAt(i+off));
        }
    }

    @Override public void flush() throws IOException {
        out.write(line.toString());
        line.replace(0, line.length(), "");
    }
}


text:
package com.migibert.kheo.healtcheck;

import org.jongo.Jongo;

import com.codahale.metrics.health.HealthCheck;

public class MongoHealthcheck extends HealthCheck {

    private Jongo jongo;

    public MongoHealthcheck(Jongo jongo) {
        super();
        this.jongo = jongo;
    }

    @Override
    protected Result check() throws Exception {
        jongo.getDatabase().getCollectionNames();
        return Result.healthy();
    }
}


text:
class ApplyLeave < ActiveRecord::Base
  validates_presence_of :employee_leave_types_id, :start_date, :end_date, :reason
  belongs_to :employee

  cattr_reader :per_page
  @@per_page = 12

end


text:
require File.expand_path('../subcontext_block', __FILE__)

module Poise
  module Provider
    module NotifyingBlock
      include SubContextBlock

      private
      def notifying_block(&block)
        # Make sure to mark the resource as updated-by-last-action if
        # any sub-run-context resources were updated (any actual
        # actions taken against the system) during the
        # sub-run-context convergence.
        begin
          subcontext = subcontext_block(&block)
          # Converge the new context.
          Poise::SubRunner.new(new_resource, subcontext).converge
        ensure
          new_resource.updated_by_last_action(
            subcontext && subcontext.resource_collection.any?(&:updated?)
          )
        end
      end
    end
  end
end


text:
package com.athena.meerkat.controller.web.resources.repositories;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.athena.meerkat.controller.web.entities.DatagridServer;
import com.athena.meerkat.controller.web.entities.DatagridServerGroup;
import com.athena.meerkat.controller.web.entities.DatagridServerPK;
import com.athena.meerkat.controller.web.entities.Server;

/**
 * DatagridServersRepository
 *
 * @author Bongjin Kwon
 * @version 1.0
 */
@Repository
public interface DatagridServersRepository extends JpaRepository<DatagridServer, DatagridServerPK> {

	List<DatagridServer> findByDatagridServerGroupId(Integer datagridServerGroupId);

//	@Query("select group from DatagridServerGroup group where group.datagridServers is null")
//	List<DatagridServerGroup> findByDatagridServersNotNull();

}


text:
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import Client, UserProfile

from django.http import HttpRequest, HttpResponse
from typing import Dict, Any, Optional, Text

from datetime import datetime

@api_key_only_webhook_view('Stripe')
@has_request_variables
def api_stripe_webhook(request, user_profile, client,
                       payload=REQ(argument_type='body'), stream=REQ(default='test'),
                       topic=REQ(default=None)):
    # type: (HttpRequest, UserProfile, Client, Dict[str, Any], Text, Optional[Text]) -> HttpResponse
    body = None
    event_type = payload["type"]
    try:
        data_object = payload["data"]["object"]
        if event_type.startswith('charge'):

            charge_url = "https://dashboard.stripe.com/payments/{}"
            amount_string = amount(payload["data"]["object"]["amount"], payload["data"]["object"]["currency"])

            if event_type.startswith('charge.dispute'):
                charge_id = data_object["charge"]
                link = charge_url.format(charge_id)
                body_template = "A charge dispute for **{amount}** has been {rest}.\n"\
                                "The charge in dispute {verb} **[{charge}]({link})**."

                if event_type == "charge.dispute.closed":
                    rest = "closed as **{}**".format(data_object['status'])
                    verb = 'was'
                else:
                    rest = "created"
                    verb = 'is'

                body = body_template.format(amount=amount_string, rest=rest, verb=verb, charge=charge_id, link=link)

            else:
                charge_id = data_object["id"]
                link = charge_url.format(charge_id)
                body_template = "A charge with id **[{charge_id}]({link})** for **{amount}** has {verb}."

                if event_type == "charge.failed":
                    verb = "failed"
                else:
                    verb = "succeeded"
                body = body_template.format(charge_id=charge_id, link=link, amount=amount_string, verb=verb)

            if topic is None:
                topic = "Charge {}".format(charge_id)

        elif event_type.startswith('customer'):
            object_id = data_object["id"]
            if event_type.startswith('customer.subscription'):
                link = "https://dashboard.stripe.com/subscriptions/{}".format(object_id)

                if event_type == "customer.subscription.created":
                    amount_string = amount(data_object["plan"]["amount"], data_object["plan"]["currency"])

                    body_template = "A new customer subscription for **{amount}** " \
                                    "every **{interval}** has been created.\n" \
                                    "The subscription has id **[{id}]({link})**."
                    body = body_template.format(
                        amount=amount_string,
                        interval=data_object['plan']['interval'],
                        id=object_id,
                        link=link
                    )

                elif event_type == "customer.subscription.deleted":
                    body_template = "The customer subscription with id **[{id}]({link})** was deleted."
                    body = body_template.format(id=object_id, link=link)

                else:
                    end_time = datetime.fromtimestamp(data_object["trial_end"]).strftime('%b %d %Y at %I:%M%p')
                    body_template = "The customer subscription trial with id **[{id}]({link})** will end on {time}"
                    body = body_template.format(id=object_id, link=link, time=end_time)

            else:
                link = "https://dashboard.stripe.com/customers/{}".format(object_id)
                body_template = "{beginning} customer with id **[{id}]({link})** {rest}."

                if event_type == "customer.created":
                    beginning = "A new"
                    if data_object["email"] is None:
                        rest = "has been created"
                    else:
                        rest = "and email **{}** has been created".format(data_object['email'])
                else:
                    beginning = "A"
                    rest = "has been deleted"
                body = body_template.format(beginning=beginning, id=object_id, link=link, rest=rest)

            if topic is None:
                topic = "Customer {}".format(object_id)

        elif event_type == "invoice.payment_failed":
            object_id = data_object['id']
            link = "https://dashboard.stripe.com/invoices/{}".format(object_id)
            amount_string = amount(data_object["amount_due"], data_object["currency"])
            body_template = "An invoice payment on invoice with id **[{id}]({link})** and "\
                            "with **{amount}** due has failed."
            body = body_template.format(id=object_id, amount=amount_string, link=link)

            if topic is None:
                topic = "Invoice {}".format(object_id)

        elif event_type.startswith('order'):
            object_id = data_object['id']
            link = "https://dashboard.stripe.com/orders/{}".format(object_id)
            amount_string = amount(data_object["amount"], data_object["currency"])
            body_template = "{beginning} order with id **[{id}]({link})** for **{amount}** has {end}."

            if event_type == "order.payment_failed":
                beginning = "An order payment on"
                end = "failed"
            elif event_type == "order.payment_succeeded":
                beginning = "An order payment on"
                end = "succeeded"
            else:
                beginning = "The"
                end = "been updated"

            body = body_template.format(beginning=beginning, id=object_id, link=link, amount=amount_string, end=end)

            if topic is None:
                topic = "Order {}".format(object_id)

        elif event_type.startswith('transfer'):
            object_id = data_object['id']
            link = "https://dashboard.stripe.com/transfers/{}".format(object_id)
            amount_string = amount(data_object["amount"], data_object["currency"])
            body_template = "The transfer with description **{description}** and id **[{id}]({link})** " \
                            "for amount **{amount}** has {end}."
            if event_type == "transfer.failed":
                end = 'failed'
            else:
                end = "been paid"
            body = body_template.format(
                description=data_object['description'],
                id=object_id,
                link=link,
                amount=amount_string,
                end=end
            )

            if topic is None:
                topic = "Transfer {}".format(object_id)
    except KeyError as e:
        return json_error(_("Missing key {} in JSON".format(str(e))))

    if body is None:
        return json_error(_("We don't support {} event".format(event_type)))

    check_send_message(user_profile, client, 'stream', [stream], topic, body)

    return json_success()

def amount(amount, currency):
    # type: (int, str) -> str
    # zero-decimal currencies
    zero_decimal_currencies = ["bif", "djf", "jpy", "krw", "pyg", "vnd", "xaf", "xpf", "clp", "gnf", "kmf", "mga", "rwf", "vuv", "xof"]
    if currency in zero_decimal_currencies:
        return str(amount) + currency
    else:
        return '{0:.02f}'.format(float(amount) * 0.01) + currency


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

namespace ServiceStack.Logging.Support.Logging {
    /// <summary>
    /// Tests logger which  stores all log messages in a member list which can be examined later
    ///
    /// Made public so its testable
    /// </summary>
    public class TestLogger : ILog {
        /// <summary>
        /// Initializes a new instance of the <see cref="TestLogger"/> class.
        /// </summary>
        /// <param name="type">The type.</param>
        public TestLogger(string type) {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TestLogger"/> class.
        /// </summary>
        /// <param name="type">The type.</param>
        public TestLogger(Type type) {
        }

        public enum Levels {
            DEBUG,
            ERROR,
            FATAL,
            INFO,
            WARN,
        };

        static private List<KeyValuePair<Levels, string>> _logs = new List<KeyValuePair<Levels, string>>();

        static public IList<KeyValuePair<Levels, string>> GetLogs() { return _logs; }

        #region ILog Members

        public bool IsDebugEnabled { get { return true; } }

        /// <summary>
        /// Logs the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="exception">The exception.</param>
        private static void Log(Levels level, object message, Exception exception) {
            string msg = message == null ? string.Empty : message.ToString();
            if(exception != null) {
                msg += ", Exception: " + exception.Message;
            }
            _logs.Add(new KeyValuePair<Levels, string>(level, msg));
        }

        /// <summary>
        /// Logs the format.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="args">The args.</param>
        private static void LogFormat(Levels level, object message, params object[] args) {
            string msg = message == null ? string.Empty : message.ToString();
            _logs.Add(new KeyValuePair<Levels, string>(level, string.Format(msg, args)));
        }

        /// <summary>
        /// Logs the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        private static void Log(Levels level, object message) {
            string msg = message == null ? string.Empty : message.ToString();
            _logs.Add(new KeyValuePair<Levels, string>(level, msg));
        }

        public void Debug(object message, Exception exception) {
            Log(Levels.DEBUG, message, exception);
        }

        public void Debug(object message) {
            Log(Levels.DEBUG, message);
        }

        public void DebugFormat(string format, params object[] args) {
            LogFormat(Levels.DEBUG, format, args);
        }

        public void Error(object message, Exception exception) {
            Log(Levels.ERROR, message, exception);
        }

        public void Error(object message) {
            Log(Levels.ERROR, message);
        }

        public void ErrorFormat(string format, params object[] args) {
            LogFormat(Levels.ERROR, format, args);
        }

        public void Fatal(object message, Exception exception) {
            Log(Levels.FATAL, message, exception);
        }

        public void Fatal(object message) {
            Log(Levels.FATAL, message);
        }

        public void FatalFormat(string format, params object[] args) {
            LogFormat(Levels.FATAL, format, args);
        }

        public void Info(object message, Exception exception) {
            Log(Levels.INFO, message, exception);
        }

        public void Info(object message) {
            Log(Levels.INFO, message);
        }

        public void InfoFormat(string format, params object[] args) {
            LogFormat(Levels.INFO, format, args);
        }

        public void Warn(object message, Exception exception) {
            Log(Levels.WARN, message, exception);
        }

        public void Warn(object message) {
            Log(Levels.WARN, message);
        }

        public void WarnFormat(string format, params object[] args) {
            LogFormat(Levels.WARN, format, args);
        }

        #endregion
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections.Concurrent;
using com.bitscopic.downstream.domain.reporting;

namespace com.bitscopic.downstream.domain
{
    [Serializable]
    public class QueryResults
    {
        public QueryResults()
        {
            this.DdrResults = new List<DataTable>();
           // this.Report = new ThreadSafeReport();
        }

        IList<Exceptional> _exceptionals = new List<Exceptional>();
        public IList<Exceptional> Exceptionals { get { return _exceptionals; } set { _exceptionals = value; } }

        public IList<DataTable> DdrResults { get; set; }

        public String StringResult { get; set; }

        public Object Result { get; set; }

        /// <summary>
        /// Subfile IEN queues stored like this
        /// ["/45.06"] [[1],[5],[6],[15],[34]]
        /// ["/45.07"] [[2],[3],[5],[6],[31]]
        /// </summary>
        public Dictionary<String, IList<String>> SubQueryIens { get; set; }

        public IList<String> LabChemIens { get; set; }

        public bool ExtractionComplete { get; set; }

        Report _rpt = new Report("QueryResults Report");
        public Report Report { get { return _rpt; } }
    }
}


text:
require 'alerty'
require 'aws-sdk'
require 'dotenv'
require 'json'
Dotenv.load

class Alerty
  class Plugin
    class AmazonCloudwatchLogs
      def initialize(config)
        params = {}
        params[:region] = config.aws_region if config.aws_region
        params[:access_key_id] = config.aws_access_key_id if config.aws_access_key_id
        params[:secret_access_key] = config.aws_secret_access_key if config.aws_secret_access_key
        params[:ssl_verify_peer] = false
        @client = Aws::CloudWatchLogs::Client.new(params)
        @subject = config.subject
        @log_group_name = config.log_group_name
        @log_stream_name = config.log_stream_name
	@state_file = config.state_file
        @num_retries = config.num_retries || 3
      end

      def alert(record)
        message = record[:output]
        subject = expand_placeholder(@subject, record)
	event_message = { "subject" => subject, "message" => message, "hostname" => record[:output], "exitstatus" => record[:exitstatus], "duration" => record[:duration] }
	timestamp = Time.now.instance_eval { self.to_i * 1000 + (usec/1000) }
	next_token = read_token
        retries = 0
        begin
          Alerty.logger.info "#{next_token}"
	  if next_token == ""
            resp = @client.put_log_events({
              log_group_name: @log_group_name,
              log_stream_name: @log_stream_name,
              log_events: [
                {
                  timestamp: timestamp,
                  message: event_message.to_json,
                },
              ]
            })
	    store_token(resp.next_sequence_token)
            Alerty.logger.info "Sent #{{subject: subject, message: message}} to log_group_name: #{@log_group_name} / log_stream_name: #{@log_stream_name} / next_sequence_token: #{resp.next_sequence_token}"
	  else
            resp = @client.put_log_events({
              log_group_name: @log_group_name,
              log_stream_name: @log_stream_name,
              log_events: [
                {
                  timestamp: timestamp,
                  message: event_message.to_json,
                },
              ],
	      sequence_token: next_token
            })
	    store_token(resp.next_sequence_token)
            Alerty.logger.info "Sent #{{subject: subject, message: message}} to log_group_name: #{@log_group_name} / log_stream_name: #{@log_stream_name} / next_sequence_token: #{resp.next_sequence_token}"
	  end
        rescue => e
          retries += 1
          sleep 1
          if retries <= @num_retries
            retry
          else
            raise e
          end
        end
      end

      private

      def expand_placeholder(str, record)
        str.gsub('${command}', record[:command]).gsub('${hostname}', record[:hostname])
      end

      def read_token
        return nil unless File.exist?(@state_file)
        File.read(@state_file).chomp
      end

      def store_token(sequence_token)
        open(@state_file, 'w') do |f|
          f.write sequence_token
        end
      end

    end
  end
end


text:
<module>
<source path=""/>
<super-source path="super"/>
<inherits name="com.google.common.annotations.Annotations"/>
<inherits name="com.google.common.base.Base"/>
<inherits name="com.google.common.collect.Collect"/>
<inherits name="com.google.common.collect.testing.Testing"/>
<inherits name="com.google.common.testing.Testing"/>
</module>


text:
/*jslint anon:true, sloppy:true, nomen:true, stupid:true, node:true */
/*global YUI*/

/**
 * The Resource Store is a Y.Base -- a host for Y.Plugins.
 * Each Addon provides additional functions through a namespace that is
 * attached directly to the resource store.
 * @module ResourceStoreAddon
 */

/**
 * @class RSAddonConfig
 * @extension ResourceStore.server
 */
YUI.add('addon-rs-config', function(Y, NAME) {

    'use strict';

    var libfs = require('fs'),
        libpath = require('path'),
        existsSync = libfs.existsSync || libpath.existsSync,
        libycb = require('ycb'),
        libyaml = require('js-yaml');

    function RSAddonConfig() {
        RSAddonConfig.superclass.constructor.apply(this, arguments);
    }
    RSAddonConfig.NS = 'config';

    Y.extend(RSAddonConfig, Y.Plugin.Base, {

        /**
         * This methods is part of Y.Plugin.Base.  See documentation for that for details.
         * @method initializer
         * @param {object} config Configuration object as per Y.Plugin.Base
         * @return {nothing}
         */
        initializer: function(config) {
            this.appRoot = config.appRoot;
            this.mojitoRoot = config.mojitoRoot;
            this.afterHostMethod('findResourceVersionByConvention', this.findResourceVersionByConvention, this);
            this.beforeHostMethod('parseResourceVersion', this.parseResourceVersion, this);

            this._jsonCache = {};   // fullPath: contents as JSON object
            this._simpleCache = {}; // fullPath: contents as JSON object
            this._ycbCache = {};    // fullPath: context: YCB config object
            this._ycbDims = this._readYcbDimensions();
            this._ycbAppConfig = this._readYcbAppConfig();
        },

        /**
         * Returns the YCB dimensions for the application.
         * @method getDimensions
         * @return {object} the YCB dimensions structure for the app
         */
        getDimensions: function() {
            return Y.mojito.util.copy(this._ycbDims);
        },

        /**
         * Returns the YCB library object for the application config.
         * @method getAppConfigYCB
         * @return {YCB} YCB library object for the application config
         */
        getAppConfigYCB: function() {
            return this._ycbAppConfig;
        },

        /**
         * Reads a JSON file.  In mojito, this should generally only be used for
         * package.json files, and all other mojito config files should instead
         * be read using readConfigSimple() or readConfigYCB().
         * @method readConfigJSON
         * @param {string} fullPath path to JSON file
         * @return {user-defined} contents of file as an object
         */
        readConfigJSON: function(fullPath) {
            var json,
                contents;
            if (!existsSync(fullPath)) {
                return {};
            }
            json = this._jsonCache[fullPath];
            if (!json) {
                try {
                    contents = libfs.readFileSync(fullPath, 'utf-8');
                    json = JSON.parse(contents);
                } catch (e) {
                    throw new Error('Error parsing JSON file: ' + fullPath);
                }
                this._jsonCache[fullPath] = json;
            }
            return Y.mojito.util.copy(json);
        },

        /**
         * Reads and parses a JSON or YAML structured file.
         * @method readConfigSimple
         * @param {string} fullPath path to JSON or YAML file
         * @return {user-defined} contents of file as an object
         */
        readConfigSimple: function(fullPath) {
            var extensions = ['.yml', '.yaml', '.json'],
                basename,   // everything except the extension
                i,
                json = false,
                raw,
                obj;

            obj = this._simpleCache[fullPath];
            if (!obj) {
                basename = fullPath;
                if (libpath.extname(fullPath)) {
                    basename = fullPath.slice(0, libpath.extname(fullPath).length * -1);
                }
                for (i = extensions.length - 1; i >= 0; i -= 1) {
                    try {
                        fullPath = basename + extensions[i];
                        raw = libfs.readFileSync(fullPath, 'utf8');
                        try {
                            if (i === 2) { // json
                                obj = JSON.parse(raw);
                                json = true;
                            } else { // yaml or yml
                                obj = libyaml.load(raw);
                                if (json) {
                                    Y.log(basename + extensions[2] + ' exists but ' + extensions[i] + ' file will be used instead', 'warn', NAME);
                                }
                            }
                            // TODO: what happen when one of them exists?
                            //       and what then more than one exists?
                        } catch (parseErr) {
                            throw new Error(parseErr);
                        }
                    } catch (err) {
                        if (err.errno !== 34) { // if the error was not "no such file or directory" report it
                            throw new Error("Error parsing file: " + fullPath + "\n" + err);
                        }
                    }
                }
                if (!obj) {
                    obj = {};
                }
                this._simpleCache[fullPath] = obj;
            }
            return Y.mojito.util.copy(obj);
        },

        /**
         * Reads a configuration file that is in YCB format.
         * @method readConfigYCB
         * @param {object} ctx runtime context
         * @param {string} fullPath path to the YCB file
         * @return {object} the contextualized configuration
         */
        // TODO:  async interface
        readConfigYCB: function(fullPath, ctx) {
            var store = this.get('host'),
                cacheKey,
                json,
                ycb;

            ctx = store.blendStaticContext(ctx);

            if (!this._ycbCache[fullPath]) {
                this._ycbCache[fullPath] = {};
            }

            cacheKey = JSON.stringify(ctx);
            ycb = this._ycbCache[fullPath][cacheKey];
            if (!ycb) {
                json = this.readConfigSimple(fullPath);
                json = this._ycbDims.concat(json);
                ycb = libycb.read(json, ctx);
                this._ycbCache[fullPath][cacheKey] = ycb;
            }
            return Y.mojito.util.copy(ycb);
        },

        /**
         * Creates a YCB configuration bundle using contents from multiple files.
         * The appropriate dimensions.json file will be mixed in, and doesn't need
         * to be part of the list of files. This method is tolerant to errors, and
         * will fallback to `{}` if a file does not exists or fails to load.
         * @method createMultipartYCB
         * @param {array} paths list of files to load
         * @return {YCB} return a YCB library object
         */
        createMultipartYCB: function(paths) {
            var p,
                path,
                config,
                s,
                section,
                settings = {},
                bundle = [];
            bundle.push(this.getDimensions()[0]);
            for (p = 0; p < paths.length; p += 1) {
                path = paths[p];
                config = this.readConfigSimple(path);
                if (!Y.Lang.isArray(config)) {
                    Y.log('not a YCB file: ' + path, 'error', NAME);
                    return;
                }
                for (s = 0; s < config.length; s += 1) {
                    section = config[s];
                    if (!Y.Lang.isArray(section.settings)) {
                        Y.log('missing "settings" in YCB file: ' + path, 'error', NAME);
                        return;
                    }
                    section.__ycb_source__ = path;
                    bundle.push(section);
                }
            }
            return new libycb.Ycb(bundle);
        },

        /**
         * Using AOP, this is called after the ResourceStore's version.
         * @method findResourceVersionByConvention
         * @param {object} source metadata about where the resource is located
         * @param {string} mojitType name of mojit to which the resource likely belongs
         * @return {object||null} for config file resources, returns metadata signifying that
         */
        findResourceVersionByConvention: function(source, mojitType) {
            var fs = source.fs,
                use = false;

            // we only care about files
            if (!fs.isFile) {
                return;
            }
            // we don't care about files in subdirectories
            if ('.' !== fs.subDir) {
                return;
            }
            // we only care about json or yaml files
            if ('.json' !== fs.ext && '.yaml' !== fs.ext && '.yml' !== fs.ext) {
                return;
            }
            // use package.json for the app and the mojit
            if ('package' === fs.basename && 'bundle' !== fs.rootType) {
                use = true;
            }
            // use all configs in the application
            if ('app' === fs.rootType) {
                use = true;
            }
            // use configs from non-shared mojit resources
            if (mojitType && 'shared' !== mojitType) {
                use = true;
            }
            if (!use) {
                return;
            }

            return new Y.Do.AlterReturn(null, {
                type: 'config'
            });
        },

        /**
         * Using AOP, this is called before the ResourceStore's version.
         * @method parseResourceVersion
         * @param {object} source metadata about where the resource is located
         * @param {string} type type of the resource
         * @param {string} subtype subtype of the resource
         * @param {string} mojitType name of mojit to which the resource likely belongs
         * @return {object||null} for config file resources, returns the resource metadata
         */
        parseResourceVersion: function(source, type, subtype, mojitType) {
            var baseParts,
                res;

            if ('config' !== type) {
                return;
            }

            baseParts = source.fs.basename.split('.');
            if (baseParts.length !== 1) {
                Y.log('invalid config filename. skipping ' + source.fs.fullPath, 'warn', NAME);
                return;
            }
            res = {
                source: source,
                type: 'config',
                affinity: 'common',
                selector: '*'
            };
            if ('app' !== source.fs.rootType) {
                res.mojit = mojitType;
            }
            res.name = libpath.join(source.fs.subDir, baseParts.join('.'));
            res.id = [res.type, res.subtype, res.name].join('-');
            return new Y.Do.Halt(null, res);
        },

        /**
         * Read the application's dimensions.json file for YCB processing. If not
         * available, fall back to the framework's default dimensions.json.
         * @private
         * @method _readYcbDimensions
         * @return {array} contents of the dimensions.json file
         */
        _readYcbDimensions: function() {
            var path = libpath.join(this.appRoot, 'dimensions.json');
            if (!existsSync(path)) {
                path = libpath.join(this.mojitoRoot, 'dimensions.json');
            }
            return this.readConfigSimple(path);
        },

        /**
         * Initializes the special multi-file YCB library for all the application
         * files. By default, we try to load `application.json`, then mix any other
         * relative config file specified in the master section under the
         * `applicationConfigFiles` array, which is optional.
         * @private
         * @method _readYcbAppConfig
         * @return {object} libycb object
         */
        _readYcbAppConfig: function() {
            var ycb,
                i,
                rootAppJSON = libpath.join(this.appRoot, 'application.json'),
                paths = [],
                relativePaths;

            // since application.json is optional, we should be careful
            // in any case there is a low-level cache mechanism going on here.
            if (Y.Lang.isArray(this.readConfigSimple(rootAppJSON))) {
                // ensuring the context runtime:server to read applicationConfigFiles,
                // it does not matter if runtime is not a dimension, it works just fine
                // since the purpose of this block is to read applicationConfigFiles
                // from /application.json, and the rest is part of this.createMultipartYCB
                ycb = this.readConfigYCB(rootAppJSON, {
                    runtime: 'server'
                });
                // adding the master application.json as the top level
                paths.push(rootAppJSON);
                // optional applicationConfigFiles to mix in more configs
                relativePaths = ycb.applicationConfigFiles || [];
                for (i = 0; i < relativePaths.length; i += 1) {
                    paths.push(libpath.resolve(this.appRoot, relativePaths[i]));
                }
            }

            // Note: it doesn't matter if we try to reach the same file multiple
            // times (application.json) because readConfigSimple will cache it anyway
            ycb = this.createMultipartYCB(paths);
            if (!ycb) {
                throw new Error("failed to create a YCB config from the following files:\n  " + paths.join("\n  "));
            }
            return ycb;
        }

    });
    Y.namespace('mojito.addons.rs');
    Y.mojito.addons.rs.config = RSAddonConfig;

}, '0.0.1', { requires: ['plugin', 'oop', 'mojito-util']});


text:
<?php
namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LoadUserData extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface
{
    private $container;

    function getOrder()
    {
        return 1;
    }

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {
        $manager = $this->getUserManager();
        $faker = $this->getFaker();

        $user = $manager->createUser();
        $user->setUsername('admin');
        $user->setEmail($faker->safeEmail);
        $user->setPlainPassword('admin');
        $user->setEnabled(true);
        $user->setSuperAdmin(true);
        $user->setLocked(false);

        $manager->updateUser($user);
        $this->addReference('user-admin', $user);

        foreach (range(1, 20) as $id) {
            $user = $manager->createUser();
            $user->setUsername($faker->userName . $id);
            $user->setEmail($faker->safeEmail);
            $user->setPlainPassword($faker->randomNumber());
            $user->setEnabled(true);
            $user->setLocked(false);
            $this->setReference('user-user', $user);
            $manager->updateUser($user);
        }

        $user = $manager->createUser();
        $user->setUsername('user');
        $user->setEmail($faker->safeEmail);
        $user->setPlainPassword('user');
        $user->setEnabled(true);
        $user->setSuperAdmin(false);
        $user->setLocked(false);
        $this->setReference('user-user', $user);
        $manager->updateUser($user);

    }

    /**
     * @return \FOS\UserBundle\Model\UserManagerInterface
     */
    public function getUserManager()
    {
        return $this->container->get('fos_user.user_manager');
    }

    /**
     * @return \Faker\Generator
     */
    public function getFaker()
    {
        return $this->container->get('faker.generator');
    }
}


text:
'use strict';

var dbCheckFn, filters;

filters = {
  isLoggedIn: function( req, res, next ) {
    if ( req.session.email ) {
      next();
    } else {
      res.json({
        error: 'unauthorized'
      }, 403 );
    }
  },
  isStorageAvailable: function( req, res, next ) {
    if ( dbCheckFn() ) {
      next();
    } else {
      res.json({
        error: 'storage service is not running'
      }, 500 );
    }
  },
  crossOriginAccessible: function( req, res, next ) {
    res.set( 'Access-Control-Allow-Origin', '*' );
    next();
  }
};

module.exports = function ctor( fn ) {
  dbCheckFn = fn;
  return filters;
};


text:
package capturas;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class Captura {

	/**
	 * @param args
	 */
	public static void init() {
		try
		{
			System.out.println("[ Captura iniciada ]");
			//sleep 5 sg
//			Thread.currentThread().sleep(5*1000);
//			String FILENAME="/home/jose/Desktop/captura01.png";
			String FILENAME="captura01.png";
			Captura.captureScreen(FILENAME);
			System.out.println("[ Captura finalizada ]");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void captureScreen(String fileName) throws Exception {
		Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
		Rectangle screenRectangle = new Rectangle(screenSize);
		Robot robot = new Robot();
		BufferedImage image = robot.createScreenCapture(screenRectangle);
		ImageIO.write(image, "png", new File(fileName));
	}

}