text:
"""Tests utils.py."""

import os
import unittest
from mock import call
from mock import MagicMock
from mock import patch
import perfzero.utils as utils
import tensorflow as tf  # pylint: disable=g-bad-import-order

class TestUtils(unittest.TestCase, tf.test.Benchmark):

  def test_protobuf_read(self):
    output_dir = '/tmp/'
    os.environ['TEST_REPORT_FILE_PREFIX'] = output_dir
    benchmark_result_file_path = os.path.join(output_dir,
                                              'TestUtils.testReportBenchmark')
    if os.path.exists(benchmark_result_file_path):
      os.remove(benchmark_result_file_path)

    self.report_benchmark(
        iters=2000,
        wall_time=1000,
        name='testReportBenchmark',
        metrics=[{'name': 'metric_name_1', 'value': 0, 'min_value': 1},
                 {'name': 'metric_name_2', 'value': 90, 'min_value': 0,
                  'max_value': 95}])

    actual_result = utils.read_benchmark_result(
        benchmark_result_file_path)
    os.remove(benchmark_result_file_path)

    expected_result = {
        'name': 'TestUtils.testReportBenchmark',
        # google.protobuf.json_format.MessageToDict() will convert
        # int64 field to string.
        'iters': '2000',
        'wall_time': 1000,
        'cpu_time': 0,
        'throughput': 0,
        'extras': {},
        'metrics': [
            {
                'name': 'metric_name_1',
                'value': 0,
                'min_value': 1
            },
            {
                'name': 'metric_name_2',
                'value': 90,
                'min_value': 0,
                'max_value': 95
            }
        ]
    }

    self.assertDictEqual(expected_result, actual_result)

  @patch('perfzero.utils.get_git_repo_info')
  @patch('perfzero.utils.run_commands')
  def test_checkout_git_repos(self, run_commands_mock, get_git_repo_info_mock):
    git_repo_1 = {}
    git_repo_1['url'] = 'url_1'
    git_repo_1['local_path'] = 'local_path_1'
    git_repo_1['dir_name'] = 'dir_name_1'
    git_repo_1['branch'] = 'branch_1'
    git_repo_1['git_hash'] = 'git_hash_1'

    git_repo_2 = {}
    git_repo_2['url'] = 'url_2'
    git_repo_2['local_path'] = 'local_path_2'
    git_repo_2['dir_name'] = 'dir_name_2'
    git_repo_2['branch'] = 'branch_2'

    git_repo_info_1 = {'url': 'url_1'}
    git_repo_info_2 = {'url': 'url_2'}
    get_git_repo_info_mock.side_effect = \
        lambda local_path: git_repo_info_1 if local_path == 'local_path_1' else git_repo_info_2  # pylint: disable=line-too-long
    site_package_info = utils.checkout_git_repos([git_repo_1, git_repo_2],
                                                 False)

    self.assertEqual(2, len(site_package_info))
    self.assertEqual(git_repo_info_1, site_package_info['dir_name_1'])
    self.assertEqual(git_repo_info_2, site_package_info['dir_name_2'])

    run_commands_mock.assert_has_calls(any_order=False, calls=[
        call(['git clone url_1 local_path_1']),
        call(['git -C local_path_1 checkout branch_1']),
        call(['git -C local_path_1 pull --rebase']),
        call(['git -C local_path_1 reset --hard git_hash_1']),
        call(['git clone url_2 local_path_2']),
        call(['git -C local_path_2 checkout branch_2'])
    ])

  @patch('perfzero.utils.run_command')
  def test_get_git_repo_info(self, run_command_mock):
    run_command_mock.side_effect = [
        [0, 'git_url'],
        [0, 'branch_name'],
        [0, 'git_hash']
    ]

    git_repo_info = utils.get_git_repo_info('local_path_1')
    self.assertEqual(
        {'url': 'git_url', 'branch': 'branch_name', 'hash': 'git_hash'},
        git_repo_info)
    run_command_mock.assert_has_calls(any_order=False, calls=[
        call('git -C local_path_1 config --get remote.origin.url'),
        call('git -C local_path_1 rev-parse --abbrev-ref HEAD'),
        call('git -C local_path_1 rev-parse HEAD')
    ])

  @patch('builtins.open')
  @patch('perfzero.utils.make_dir_if_not_exist')
  @patch('requests.get')
  @patch('perfzero.utils.run_commands')
  def test_download_data(self, run_commands_mock, requests_get_mock,
                         make_dir_mock, open_mock):  # pylint: disable=unused-argument
    get_mock = MagicMock()
    get_mock.content = 'content'
    requests_get_mock.return_value = get_mock

    download_info_1 = {'url': 'gs://remote_path_1/name_1',
                       'local_path': 'local_path_1/modified_name_1'}
    download_info_2 = {'url': 'http://remote_path_2/name_2',
                       'local_path': 'local_path_2/modified_name_2'}
    utils.download_data([download_info_1, download_info_2])

    make_dir_mock.assert_has_calls(any_order=False, calls=[
        call('local_path_1'),
        call('local_path_2')
    ])
    requests_get_mock.assert_called_once_with('http://remote_path_2/name_2',
                                              allow_redirects=True)
    run_commands_mock.assert_has_calls(any_order=False, calls=[
        call([['gsutil', '-m', 'cp', '-r', '-n',
               'gs://remote_path_1/name_1', 'local_path_1']],
             shell=False),
        call(['mv local_path_1/name_1 local_path_1/modified_name_1']),
        call(['mv local_path_2/name_2 local_path_2/modified_name_2'])
    ])

  def test_parse_data_downloads_str(self):
    data_downloads_str = 'url_1;relative_path_1,url_2;relative_path_2'
    download_infos = utils.parse_data_downloads_str('/root_data_dir',
                                                    data_downloads_str)
    self.assertEqual(2, len(download_infos))
    self.assertEqual(download_infos[0],
                     {'url': 'url_1',
                      'local_path': '/root_data_dir/relative_path_1'})
    self.assertEqual(download_infos[1],
                     {'url': 'url_2',
                      'local_path': '/root_data_dir/relative_path_2'})

  @patch('perfzero.utils.run_command')
  def test_get_cpu_name(self, run_command_mock):
    """Tests extract the cpu model name."""
    run_command_mock.return_value = [
        0, 'model name  : Intel(R) Xeon(R) CPU E5-1650 v2 @ 3.50GHz\n'
    ]
    cpu_name = utils.get_cpu_name()
    self.assertEqual('Intel(R) Xeon(R) CPU E5-1650 v2 @ 3.50GHz', cpu_name)

  @patch('perfzero.utils.run_command')
  def test_get_cpu_socket_count(self, run_command_mock):
    """Tests get socket count."""
    run_command_mock.return_value = [0, '2\n']
    cpu_socket_count = utils.get_cpu_socket_count()
    self.assertEqual(2, cpu_socket_count)

  @patch('perfzero.utils.run_command')
  def test_get_gpu_model(self, run_command_mock):
    # Tests get gpu info parses expected value into expected components.
    run_command_mock.return_value = [
        0, 'driver_version, name\n381.99, GTX 1080 \n'
    ]
    gpu_model = utils.get_gpu_info()['gpu_model']
    self.assertEqual('GTX 1080', gpu_model)

    # Tests gpu info returns second entry if first entry is a Quadro.
    run_command_mock.return_value = [
        0, 'blah\n200.99, Quadro K900 \n381.99, GTX 1080\n'
    ]
    gpu_model = utils.get_gpu_info()['gpu_model']
    self.assertEqual('GTX 1080', gpu_model)

  @patch('perfzero.utils.run_command')
  def test_get_gpu_count(self, run_command_mock):
    """Tests gpu info returns second entry if first entry is a Quadro."""
    run_command_mock.return_value = [
        0, 'blah\n200.99, Quadro K900 \n381.99, GTX 1080\n'
    ]
    gpu_count = utils.get_gpu_info()['gpu_count']
    self.assertEqual(2, gpu_count)


text:
// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.cloudera.impala.catalog;

import com.cloudera.impala.thrift.TCatalogObjectType;
import com.cloudera.impala.thrift.THdfsCachePool;
import com.google.common.base.Preconditions;

/**
 * Represents an HDFS cache pool (CachePoolInfo class). Currently, the only metadata we
 * care about for cache pools is the cache pool name. In the future it may be desirable
 * to track additional metadata such as the owner, size, and current usage of the pool.
 */
public class HdfsCachePool implements CatalogObject {
  private long catalogVersion_;
  private final THdfsCachePool cachePool_;

  public HdfsCachePool(THdfsCachePool cachePool) {
    Preconditions.checkNotNull(cachePool);
    cachePool_ = cachePool;
  }

  @Override
  public TCatalogObjectType getCatalogObjectType() {
    return TCatalogObjectType.HDFS_CACHE_POOL;
  }

  public THdfsCachePool toThrift() {
    return cachePool_;
  }

  public static HdfsCachePool fromThrift(THdfsCachePool cachePool) {
    return new HdfsCachePool(cachePool);
  }

  @Override
  public String getName() { return cachePool_.getPool_name(); }
  @Override
  public long getCatalogVersion() { return catalogVersion_; }
  @Override
  public void setCatalogVersion(long newVersion) { catalogVersion_ = newVersion; }
  @Override
  public boolean isLoaded() { return true; }
}

redpajama_set_name: RedPajamaGithub


text:
import 'state/selectors/rooms';

test('placeholder', () => {
  expect(true).toEqual(true);
});


text:
'use strict';

var app = angular.module('app', [
    'ui.router',
    'ui.bootstrap'
])
.config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: '../views/example.html',
                controller: 'ExampleController'
            });

        $urlRouterProvider.otherwise("/");
    }
]);


text:
package org.apache.sqoop.json;

import java.util.List;

import org.apache.sqoop.classification.InterfaceAudience;
import org.apache.sqoop.classification.InterfaceStability;
import org.apache.sqoop.model.MSubmission;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@InterfaceAudience.Private
@InterfaceStability.Unstable
public class SubmissionsBean extends SubmissionBean {

  private static final String SUBMISSIONS = "submissions";

  // For "extract"
  public SubmissionsBean(MSubmission submission) {
    super(submission);
  }

  public SubmissionsBean(List<MSubmission> submissions) {
    super(submissions);

  }

  // For "restore"
  public SubmissionsBean() {
  }

  @Override
  @SuppressWarnings("unchecked")
  public JSONObject extract(boolean skipSensitive) {
    JSONArray submissionsArray = super.extractSubmissions();
    JSONObject submissions = new JSONObject();
    submissions.put(SUBMISSIONS, submissionsArray);
    return submissions;
  }

  @Override
  public void restore(JSONObject json) {
    JSONArray submissionsArray = (JSONArray) json.get(SUBMISSIONS);
    restoreSubmissions(submissionsArray);
  }

}


text:
#include <jansson.h>
#include "types.h"

void parse_file(char *);
void dump_config(void);


text:
package org.gradle.plugins.javascript.coffeescript;

import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Optional;

import java.io.Serializable;

public class CoffeeScriptCompileOptions implements Serializable {

    private String encoding = "UTF-8";

    @Optional @Input
    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }
}


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.

/*
 * @author max
 */
package com.intellij.psi.stubs;

import com.intellij.util.io.InlineKeyDescriptor;
import org.jetbrains.annotations.NotNull;

import java.util.stream.IntStream;

final class CharSequenceHashInlineKeyDescriptor extends InlineKeyDescriptor<CharSequence> {

  final static CharSequenceHashInlineKeyDescriptor INSTANCE = new CharSequenceHashInlineKeyDescriptor();

  @Override
  public CharSequence fromInt(int n) {
    return new HashWrapper(n);
  }

  @Override
  public int toInt(CharSequence s) {
    return s.hashCode();
  }

  private static class HashWrapper implements CharSequence {
    final int hashCode;

    HashWrapper(int hashCode) {
      this.hashCode = hashCode;
    }

    @Override
    public int hashCode() {
      return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
      throw new UnsupportedOperationException();
    }

    @Override
    public int length() {
      throw new UnsupportedOperationException();
    }

    @Override
    public char charAt(int index) {
      throw new UnsupportedOperationException();
    }

    @Override
    public @NotNull CharSequence subSequence(int start, int end) {
      throw new UnsupportedOperationException();
    }

    @Override
    public @NotNull IntStream chars() {
      throw new UnsupportedOperationException();
    }

    @Override
    public @NotNull IntStream codePoints() {
      throw new UnsupportedOperationException();
    }
  }
}


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Tests\Stempler\Transform;

use Spiral\Stempler\Builder;
use Spiral\Stempler\Directive\LoopDirective;
use Spiral\Stempler\Loader\LoaderInterface;
use Spiral\Stempler\Loader\StringLoader;
use Spiral\Stempler\Transform\Finalizer\DynamicToPHP;
use Spiral\Stempler\Transform\Finalizer\TrimRaw;
use Spiral\Stempler\Transform\Merge\ResolveImports;
use Spiral\Stempler\Transform\Visitor\DefineAttributes;
use Spiral\Stempler\Transform\Visitor\DefineBlocks;

class ImportInlineTest extends BaseTest
{
    public function testNoImport(): void
    {
        $loader = $loader ?? new StringLoader();
        $loader->set('root', '<url href="google.com">hello world</url>');
        $loader->set('import', '${context}');

        $builder = $this->getBuilder($loader, []);

        $this->assertSame(
            '<url href="google.com">hello world</url>',
            $builder->compile('root')->getContent()
        );
    }

    public function testInlineImport(): void
    {
        $loader = $loader ?? new StringLoader();
        $loader->set('root', '
<use:inline name="url">
    ${context}
</use:inline>
<url href="google.com">hello world</url>
');

        $builder = $this->getBuilder($loader, []);

        $this->assertSame(
            'hello world',
            $builder->compile('root')->getContent()
        );
    }

    public function testInlineImportN(): void
    {
        $loader = $loader ?? new StringLoader();
        $loader->set('root', '
<use:inline name="url">
    ${context}
</use:inline>
<url href="google.com">hello world</url>
<url href="spiralscout.com">foo bar</url>
');

        $builder = $this->getBuilder($loader, []);

        $this->assertSame(
            'hello worldfoo bar',
            $builder->compile('root')->getContent()
        );
    }

    protected function getBuilder(LoaderInterface $loader, array $visitors): Builder
    {
        $builder = parent::getBuilder($loader, $visitors);

        // import resolution
        $builder->addVisitor(new ResolveImports($builder), Builder::STAGE_TRANSFORM);

        // so we can inject into PHP
        $dynamic = new DynamicToPHP();
        $dynamic->addDirective(new LoopDirective());

        $builder->addVisitor($dynamic);
        $builder->addVisitor(new TrimRaw(), Builder::STAGE_FINALIZE);

        return $builder;
    }

    protected function getVisitors(): array
    {
        return [
            new DefineAttributes(),
            new DefineBlocks()
        ];
    }
}


text:
using System;

namespace DromundKaasII.Engine.Exceptions
{
    /// <summary>
    /// Thrown when the spawn point of a spawn candidate is occupied.
    /// </summary>
    public class SpawnOccupiedException : ApplicationException
    {
        /// <summary>
        /// Initializes a new SpawnOccupiedException.
        /// </summary>
        public SpawnOccupiedException()
            : base()
        { }

        /// <summary>
        /// Initializes a new SpawnOccupiedException.
        /// </summary>
        /// <param name="message">The exception's message.</param>
        public SpawnOccupiedException(string message)
            : base(message)
        { }

        /// <summary>
        /// Initializes a new SpawnOccupiedException.
        /// </summary>
        /// <param name="message">The exception's message.</param>
        /// <param name="inner">The exception's inner exception.</param>
        public SpawnOccupiedException(string message, Exception inner)
            : base(message, inner)
        { }
    }
}


text:
package org.jbb.board.web.forum.form;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ForumCategoryDeleteForm {
    private Long id;

    private Boolean removeWithForums;

    private Long newCategoryId;
}


text:
#include <fstream>
#include <iostream>
#include <unordered_map>

#include <format.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include <rxcpp/rx.hpp>

#include <rxcpp/rx-subjects.hpp>

#include <autograph/backend/opengl/backend.hpp>
#include <autograph/device.hpp>
#include <autograph/draw.hpp>
#include <autograph/pipeline.hpp>
#include <autograph/pixel_format.hpp>
#include <autograph/surface.hpp>

#include <extra/image_io/load_image.hpp>
#include <extra/input/input.hpp>
#include <extra/input/input_glfw.hpp>

#include "../common/sample.hpp"
#include "../common/uniforms.hpp"

using GL = ag::opengl::OpenGLBackend;

namespace input = ag::extra::input;

/*class InputSample : public samples::GLSample<InputSample> {
public:
  InputSample(unsigned width, unsigned height)
      : GLSample(width, height, "Input") {
    glfw_input_source =
        std::make_unique<input::GLFWInputEventSource>(gl.getWindow());
    texDefault = loadTexture2D("common/img/tonberry.jpg");

    input.registerEventSource(std::move(glfw_input_source));
    the_a_key = input.keys().filter([&](auto k) { return true; });
    the_a_key.subscribe([&](auto k) { fmt::print("Pressed A!\n"); });
  }

  void render() {
    using namespace glm;
    samples::uniforms::Object objectData;
	input.poll();
    auto out = device->getOutputSurface();
    ag::clear(*device, out, ag::ClearColor{1.0f, 0.0f, 1.0f, 1.0f});
    copyTex(texDefault, out, width, height, {20, 20}, 1.0);
  }

private:
  rxcpp::observable<input::KeyEvent> the_a_key;
  input::Input input;
  std::unique_ptr<input::GLFWInputEventSource> glfw_input_source;
  ag::Texture2D<ag::RGBA8, GL> texDefault;
};*/

int main() {
  /*InputSample sample(1000, 800);
  return sample.run();*/
    return 0;
}


text:
package com.dp1wms.spring.config;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ResourceBundle;

@Component
public class SpringFXMLLoader {
    private final ResourceBundle resourceBundle;
    private final ApplicationContext context;

    @Autowired
    public SpringFXMLLoader(ApplicationContext context, ResourceBundle resourceBundle) {
        this.resourceBundle = resourceBundle;
        this.context = context;
    }

    public Parent load(String fxmlPath) throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setControllerFactory(context::getBean); //Spring now FXML Controller Factory
        loader.setResources(resourceBundle);
        loader.setLocation(getClass().getResource(fxmlPath));
        return loader.load();
    }
}


text:
'use strict';

/**
 * touch_base.js
 *
 * Bulk inserts documents in batches of 100, uses the touch command on "data" and "index",
 * and queries to verify the number of documents inserted by the thread.
 */

load('jstests/concurrency/fsm_libs/extend_workload.js');            // for extendWorkload
load('jstests/concurrency/fsm_workloads/indexed_insert_where.js');  // for $config
// For isMongod, isMMAPv1, and isEphemeral.
load('jstests/concurrency/fsm_workload_helpers/server_types.js');

var $config = extendWorkload($config, function($config, $super) {
    $config.data.generateDocumentToInsert = function generateDocumentToInsert() {
        return {tid: this.tid, x: Random.randInt(10)};
    };

    $config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) {
        return {touch: collName, data: true, index: true};
    };

    $config.states.touch = function touch(db, collName) {
        var res = db.runCommand(this.generateTouchCmdObj(collName));
        if (isMongod(db) && (isMMAPv1(db) || isEphemeral(db))) {
            assertAlways.commandWorked(res);
        } else {
            // SERVER-16850 and SERVER-16797
            assertAlways.commandFailed(res);
        }
    };

    $config.states.query = function query(db, collName) {
        var count = db[collName].find({tid: this.tid}).itcount();
        assertWhenOwnColl.eq(count,
                             this.insertedDocuments,
                             'collection scan should return the number of documents this thread' +
                                 ' inserted');
    };

    $config.transitions = {
        insert: {insert: 0.2, touch: 0.4, query: 0.4},
        touch: {insert: 0.4, touch: 0.2, query: 0.4},
        query: {insert: 0.4, touch: 0.4, query: 0.2}
    };

    $config.setup = function setup(db, collName, cluster) {
        assertAlways.commandWorked(db[collName].ensureIndex({x: 1}));
    };

    return $config;
});


text:
/************************************
  * Parsley validation
  ***********************************/

input.parsley-success, textarea.parsley-success, select.parsley-success {
    color: #468847 !important;
    background-color: #DFF0D8 !important;
    border: 1px solid #D6E9C6 !important;
}
input.parsley-error, textarea.parsley-error, select.parsley-error {
    color: #B94A48 !important;
    background-color: #F2DEDE !important;
    border: 1px solid #EED3D7 !important;
}
ul.parsley-error-list {
    font-size: 10px;
    margin: -5px 0 0 0;
    width:200px;
    list-style-type:none;
}
ul.parsley-error-list li {
    line-height: 9px;
    width:200px;
}

/************************************
  * Media screenshots
  ***********************************/
#screenshot{
	position:absolute;
	border:1px solid #ccc;
	background:#333;
	padding:5px;
	display:none;
	color:#fff;
	}

/************************************
  * Some defaults
  ***********************************/

body {
  padding-top: 0px;
}

.content {
  margin-top: 0px;
}

form{
    display:inline;
}

#footer {
    margin-top: 50px;
}

/************************************
  * Page loader elements
  ***********************************/

#loadcover{
    display:none;
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:#333;
    opacity:0.8;
    filter:alpha(opacity=80);
}
#loading{
    display:none;
    position:absolute;
    top:250px;
    left:50%;
    width:300px;
    margin:0 0 0 -150px;
    z-index:10000;
}

/************************************
  * Flash notifications / messages
  ***********************************/

div.alert-messages {
  margin-top: 15px;
}

/************************************
  * Navigation elements
  ***********************************/

#navigation {
  /*background: -webkit-linear-gradient(180deg, blue, black);*/ /* For Safari 5.1 to 6.0 */
  /*background: -o-linear-gradient(180deg, blue, black);*/ /* For Opera 11.1 to 12.0 */
  /*background: -moz-linear-gradient(180deg, blue, black);*/ /* For Firefox 3.6 to 15 */
  /*background: linear-gradient(180deg, #003399, #011135);*/ /* Standard syntax */
  background: #00325b;
  color: white;
  height: 40px;
}

#navigation a {
    padding-top: 10px;
    color: white;
    font-weight: bold;
}

#navigation a:hover {

    border: 0;
    border-bottom: 5px solid #ffffff;
    background-color: transparent;
    padding-top: 10px;
    padding-bottom: 6px;
}

#navigation .logo_link:hover {
    border: none;
}

#navigation .active>a{
    border-bottom: 5px solid #9ab2e1;
    background-color: transparent;
    padding-top: 10px;
    padding-bottom: 6px;
}

/************************************
  * Straighten out google maps navigation
  ***********************************/

#map-canvas {
    height: 100%
}
#mappins-map img {
    max-width: none !important;
    height: auto !important;
    background: none !important;
    border: 0 !important;
    margin: 0 !important;
    padding: 0 !important;
}

.gm-style img { max-width: none; }
.gm-style label { width: auto; display: inline; }


text:
using System;
using PasPasPas.Globals.Runtime;
using PasPasPas.Globals.Types;

namespace PasPasPas.Typings.Serialization {

    internal static class CharKindHelper {

        internal static byte ToByte(this CharTypeKind kind)
            => (byte)kind;

        internal static CharTypeKind ToCharTypeKind(this byte typeKind)
            => (CharTypeKind)typeKind;

    }

    internal partial class TypeReader {

        internal IValue ReadCharValue() {
            var kind = ReadByte().ToCharTypeKind();

            switch (kind) {

                case CharTypeKind.AnsiChar:
                    return Types.Runtime.Chars.ToAnsiCharValue(ReadByte());

                case CharTypeKind.WideChar:
                    return Types.Runtime.Chars.ToWideCharValue((char)ReadUshort());

            }

            throw new InvalidOperationException();

        }

    }

    internal partial class TypeWriter {

        internal void WriteCharValue(ICharValue charValue) {
            var kind = charValue.Kind;
            WriteByte(kind.ToByte());

            switch (kind) {
                case CharTypeKind.AnsiChar:
                    WriteByte(charValue.AsAnsiChar);
                    return;

                case CharTypeKind.WideChar:
                    WriteUShort(charValue.AsWideChar);
                    return;

            }

            throw new InvalidOperationException();
        }

    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>AJAX Spider taba</title>

AJAX Spider taba

		The AJAX Spider tab shows you the set of unique URIs found by AJAX
			Spider.

 Za svaki zahtjev možete vidjeti:

			Indeks Zahtjev - svaki zahtjev je numerisan, počevši od 1

			The request timestamp

			HTML metod, npr.GET ili POST

			URL zahtjevani

			The HTTP response status code

			Kratki sažetak onoga šta kod HTTP odgovora znači

			Dužina vremena koliko čitavi zahtjev traje

			The size of the response header

			The size of the response body

			Any Alerts on the request

			Any Notes you have added to request

			Any Tags you have added to request

	SOdaberi zahtjeve koji će se prikazati u
	Zahtjevi tab and
	Tab odgovora iznad.

Desni klik meni

	Desni klik na nod će prikazati meni koji će vam dopustiti da:

Napad

	Napad meni ima sljedeće podmenije:

Active Scan Site

	This will initiate an
	Aktivno Skeniranje of the whole of the site containing the selected node.

 The
	Aktivni Sken tab will be display and will show the progress of the scan.

Aktivno Skeniranje Noda

	This will initiate an
	Aktivno Skeniranje of just the node selected.

 The
	Aktivni Sken tab will be display and will show the progress of the scan.

Spider Site

	This will initiate a
	pauk of the whole of the site containing the selected node.

 The
	Pauk tab will be display and will show the progress of the scan.

Forced Browse Site

	This will initiate a
	forced browse of the whole of the site containing the selected node.

 The
	Forsirano Pregledavanje tab will be display and will show the progress of the scan.

Forced Browse Directory

	This will initiate a
	forced browse on the selected directory.

 The
	Forsirano Pregledavanje tab will be displayed and will show the progress of the scan.

Forced Browse Directory (and children)

	This will initiate a
	forced browse on the selected directory and all children found.

 The
	Forsirano Pregledavanje tab will be displayed and will show the progress of the scan.

Isključi iz

	This menu has the following submenus:

Proxy

	This will exclude the selected nodes from the proxy. They will still be proxied via ZAP
	but will not be shown in any of the tabs.

 This can be used to ignore URLs that you know are not relevant to the system you
	are currently testing.

 The nodes can be included again via the
	Svojstva Sesije dialog

Skener

	This will prevent the selected nodes from being actively scanned.

 The nodes can be included again via the
	Svojstva Sesije dialog

Pauk

	This will prevent the selected nodes from being spidered.

 The nodes can be included again via the
	Svojstva Sesije dialog

Pokreni aplikaciju

	This menu allows you to
	invoke applications that you have configured via the
	Opcije Aplikacija prikaz which is also accessible via the 'Configure
	applications...' submenu.

Upravljaj Tagovima...

	This will bring up the
	Upravljaj Tagovima dijalog which allows you to change the
	tagovi associated with the request.

Zabilješka...

	This will bring up the
	Dodaj Zabilješku dijalog which allows you to record
	zabilješke related to the request.

Prekid...

	This will bring up the
	Dodaj Tačku Prekida dijalog which allows you to set a break point on that URL.

Upozorenja za ovaj nod

	If the URL selected has
	upozorenja associated with it then they will be listed under this menu.

 Selecting one of the alerts will cause it to be displayed.

Ponovno...

	This will bring up the
	Ponovno slanje dijalog which allows you to resend the request after making any changes to
	it that you want to.

Novo Upozorenje...

	This will bring up the
	Dodaj Upozorenje dijalog which allows you to manually record a new
	Alert against this request.

Otvori URL u Pretraživaču

	This will open the URL of the selected node in your default browser.

Još vidjeti

			AJAX Pauka
			for an overview of the AJAX Spider

			Ekran Opcija AJAX Pauka
			za pregled AJAX Pauk Opcija

			AJAX Spider dialog
			for an overview of the AJAX Spider Dialog


text:
'use strict';

module.exports = /*@ngInject*/
  function TimepickerController ($scope, $attrs, $parse, $log, $locale, timepickerConfig) {
    var selected = new Date(),
        ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
        meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;

    this.init = function( ngModelCtrl_, inputs ) {
      ngModelCtrl = ngModelCtrl_;
      ngModelCtrl.$render = this.render;

      var hoursInputEl = inputs.eq(0),
          minutesInputEl = inputs.eq(1);

      var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;
      if ( mousewheel ) {
        this.setupMousewheelEvents( hoursInputEl, minutesInputEl );
      }

      $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
      this.setupInputEvents( hoursInputEl, minutesInputEl );
    };

    var hourStep = timepickerConfig.hourStep;
    if ($attrs.hourStep) {
      $scope.$parent.$watch($parse($attrs.hourStep), function(value) {
        hourStep = parseInt(value, 10);
      });
    }

    var minuteStep = timepickerConfig.minuteStep;
    if ($attrs.minuteStep) {
      $scope.$parent.$watch($parse($attrs.minuteStep), function(value) {
        minuteStep = parseInt(value, 10);
      });
    }

    // 12H / 24H mode
    $scope.showMeridian = timepickerConfig.showMeridian;
    if ($attrs.showMeridian) {
      $scope.$parent.$watch($parse($attrs.showMeridian), function(value) {
        $scope.showMeridian = !!value;

        if ( ngModelCtrl.$error.time ) {
          // Evaluate from template
          var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
          if (angular.isDefined( hours ) && angular.isDefined( minutes )) {
            selected.setHours( hours );
            refresh();
          }
        } else {
          updateTemplate();
        }
      });
    }

    // Get $scope.hours in 24H mode if valid
    function getHoursFromTemplate ( ) {
      var hours = parseInt( $scope.hours, 10 );
      var valid = ( $scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
      if ( !valid ) {
        return undefined;
      }

      if ( $scope.showMeridian ) {
        if ( hours === 12 ) {
          hours = 0;
        }
        if ( $scope.meridian === meridians[1] ) {
          hours = hours + 12;
        }
      }
      return hours;
    }

    function getMinutesFromTemplate() {
      var minutes = parseInt($scope.minutes, 10);
      return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;
    }

    function pad( value ) {
      return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value;
    }

    // Respond on mousewheel spin
    this.setupMousewheelEvents = function( hoursInputEl, minutesInputEl ) {
      var isScrollingUp = function(e) {
        if (e.originalEvent) {
          e = e.originalEvent;
        }
        //pick correct delta variable depending on event
        var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
        return (e.detail || delta > 0);
      };

      hoursInputEl.bind('mousewheel wheel', function(e) {
        $scope.$apply( (isScrollingUp(e)) ? $scope.incrementHours() : $scope.decrementHours() );
        e.preventDefault();
      });

      minutesInputEl.bind('mousewheel wheel', function(e) {
        $scope.$apply( (isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes() );
        e.preventDefault();
      });

    };

    this.setupInputEvents = function( hoursInputEl, minutesInputEl ) {
      if ( $scope.readonlyInput ) {
        $scope.updateHours = angular.noop;
        $scope.updateMinutes = angular.noop;
        return;
      }

      var invalidate = function(invalidHours, invalidMinutes) {
        ngModelCtrl.$setViewValue( null );
        ngModelCtrl.$setValidity('time', false);
        if (angular.isDefined(invalidHours)) {
          $scope.invalidHours = invalidHours;
        }
        if (angular.isDefined(invalidMinutes)) {
          $scope.invalidMinutes = invalidMinutes;
        }
      };

      $scope.updateHours = function() {
        var hours = getHoursFromTemplate();

        if ( angular.isDefined(hours) ) {
          selected.setHours( hours );
          refresh( 'h' );
        } else {
          invalidate(true);
        }
      };

      hoursInputEl.bind('blur', function(e) {
        if ( !$scope.invalidHours && $scope.hours < 10) {
          $scope.$apply( function() {
            $scope.hours = pad( $scope.hours );
          });
        }
      });

      $scope.updateMinutes = function() {
        var minutes = getMinutesFromTemplate();

        if ( angular.isDefined(minutes) ) {
          selected.setMinutes( minutes );
          refresh( 'm' );
        } else {
          invalidate(undefined, true);
        }
      };

      minutesInputEl.bind('blur', function(e) {
        if ( !$scope.invalidMinutes && $scope.minutes < 10 ) {
          $scope.$apply( function() {
            $scope.minutes = pad( $scope.minutes );
          });
        }
      });

    };

    this.render = function() {
      var date = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : null;

      if ( isNaN(date) ) {
        ngModelCtrl.$setValidity('time', false);
        $log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
      } else {
        if ( date ) {
          selected = date;
        }
        makeValid();
        updateTemplate();
      }
    };

    // Call internally when we know that model is valid.
    function refresh( keyboardChange ) {
      makeValid();
      ngModelCtrl.$setViewValue( new Date(selected) );
      updateTemplate( keyboardChange );
    }

    function makeValid() {
      ngModelCtrl.$setValidity('time', true);
      $scope.invalidHours = false;
      $scope.invalidMinutes = false;
    }

    function updateTemplate( keyboardChange ) {
      var hours = selected.getHours(), minutes = selected.getMinutes();

      if ( $scope.showMeridian ) {
        hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system
      }

      $scope.hours = keyboardChange === 'h' ? hours : pad(hours);
      $scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes);
      $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
    }

    function addMinutes( minutes ) {
      var dt = new Date( selected.getTime() + minutes * 60000 );
      selected.setHours( dt.getHours(), dt.getMinutes() );
      refresh();
    }

    $scope.incrementHours = function() {
      addMinutes( hourStep * 60 );
    };
    $scope.decrementHours = function() {
      addMinutes( - hourStep * 60 );
    };
    $scope.incrementMinutes = function() {
      addMinutes( minuteStep );
    };
    $scope.decrementMinutes = function() {
      addMinutes( - minuteStep );
    };
    $scope.toggleMeridian = function() {
      addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) );
    };

  }


text:
package com.jetbrains.edu.java;

import com.intellij.execution.application.ApplicationConfiguration;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.edu.learning.core.EduNames;
import com.jetbrains.edu.learning.courseFormat.tasks.PyCharmTask;
import com.jetbrains.edu.learning.courseFormat.tasks.TaskWithSubtasks;
import com.jetbrains.edu.learning.intellij.EduIntelliJNames;
import com.jetbrains.edu.learning.intellij.EduPyCharmTasksChecker;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class EduJavaPyCharmTaskChecker extends EduPyCharmTasksChecker {
  public EduJavaPyCharmTaskChecker(@NotNull PyCharmTask task, @NotNull Project project) {
    super(task, project);
  }

  @Nullable
  @Override
  protected VirtualFile getTestsFile() {
    String testFileName = EduJavaPluginConfigurator.TEST_JAVA;
    if (myTask instanceof TaskWithSubtasks) {
      int activeSubtaskIndex = ((TaskWithSubtasks) myTask).getActiveSubtaskIndex();
      testFileName = FileUtil.getNameWithoutExtension(testFileName) + EduNames.SUBTASK_MARKER + activeSubtaskIndex + "." + FileUtilRt.getExtension(EduJavaPluginConfigurator.TEST_JAVA);
    }
    VirtualFile taskDir = myTask.getTaskDir(myProject);
    if (taskDir == null) {
      return null;
    }
    VirtualFile srcDir = taskDir.findChild(EduNames.SRC);
    if (srcDir != null) {
      taskDir = srcDir;
    }
    VirtualFile virtualFile = taskDir.findChild(testFileName);
    if (virtualFile != null) {
      return virtualFile;
    }
    return null;
  }

  @Override
  protected void setProcessParameters(Project project, ApplicationConfiguration configuration, Module module, @NotNull VirtualFile testsFile) {
    configuration.setMainClassName(EduIntelliJNames.TEST_RUNNER_CLASS);
    configuration.setModule(module);
    configuration.setProgramParameters(testsFile.getNameWithoutExtension());
  }
}


text:
from base64 import b85encode
from functools import wraps
from os import urandom

from flask_login import current_user
from flask_login import login_required
from scrypt import hash as shash
from sqlalchemy.exc import IntegrityError

from config import SSO_ADMINISTRATOR_GROUP
from config import SSO_ENABLED
from config import SSO_REPORTER_GROUP
from config import SSO_SECURITY_TEAM_GROUP
from config import TRACKER_PASSWORD_LENGTH_MIN
from tracker import db
from tracker import login_manager
from tracker.model.user import Guest
from tracker.model.user import User
from tracker.model.user import UserRole

login_manager.anonymous_user = Guest

def random_string(length=TRACKER_PASSWORD_LENGTH_MIN):
    salt = b85encode(urandom(length))
    return salt.decode()

def hash_password(password, salt):
    hashed = b85encode(shash(password, salt[:User.SALT_LENGTH]))
    return hashed.decode()[:User.PASSWORD_LENGTH]

@login_manager.user_loader
def load_user(session_token):
    if not session_token:
        return Guest()

    user = User.query.filter_by(token=session_token).first()
    if not user:
        return Guest()
    user.is_authenticated = True
    return user

def permission_required(permission):
    def decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if not permission.fget(current_user.role):
                from tracker.view.error import forbidden
                return forbidden()
            return func(*args, **kwargs)
        return login_required(decorated_view)
    return decorator

def reporter_required(func):
    return permission_required(UserRole.is_reporter)(func)

def security_team_required(func):
    return permission_required(UserRole.is_security_team)(func)

def administrator_required(func):
    return permission_required(UserRole.is_administrator)(func)

def require_expected_sso_state(expected):
    def decorator(func):
        @wraps(func)
        def decorated_view(*args, **kwargs):
            if SSO_ENABLED is not expected:
                from tracker.view.error import not_found
                return not_found()
            return func(*args, **kwargs)
        return decorated_view
    return decorator

def only_with_sso(func):
    return require_expected_sso_state(expected=True)(func)

def only_without_sso(func):
    return require_expected_sso_state(expected=False)(func)

def user_can_edit_issue(advisories=[]):
    role = current_user.role
    if not role.is_reporter:
        return False
    if role.is_security_team:
        return True
    return 0 == len(advisories)

def user_can_delete_issue(advisories=[]):
    role = current_user.role
    if not role.is_reporter:
        return False
    return 0 == len(advisories)

def user_can_edit_group(advisories=[]):
    return user_can_edit_issue(advisories)

def user_can_delete_group(advisories=[]):
    return user_can_delete_issue(advisories)

def user_can_handle_advisory():
    return current_user.role.is_security_team

def user_can_watch_log():
    return True

def user_can_watch_user_log():
    return current_user.role.is_reporter

def user_invalidate(user):
    user.token = None
    user.is_authenticated = False

def user_assign_new_token(user, max_tries=32):
    def assign_token(token):
        user.token = token
        return user
    return user_generate_new_token(assign_token, max_tries)

def user_generate_new_token(callback, max_tries=32):
    failed = 0
    while failed < max_tries:
        try:
            token = random_string(User.TOKEN_LENGTH)
            token_owners = User.query.filter_by(token=token).count()
            if 0 != token_owners:
                failed += 1
                continue
            user = callback(token)
            db.session.commit()
            return user
        except IntegrityError:
            db.session.rollback()
            failed += 1
    raise Exception('Failed to obtain unique token within {} tries'.format(max_tries))

def get_user_role_from_idp_groups(idp_groups):
    group_names_for_roles = {
        SSO_ADMINISTRATOR_GROUP: UserRole.administrator,
        SSO_SECURITY_TEAM_GROUP: UserRole.security_team,
        SSO_REPORTER_GROUP: UserRole.reporter
    }

    eligible_roles = [group_names_for_roles[group] for group in idp_groups if group in group_names_for_roles]

    if eligible_roles:
        return sorted(eligible_roles, reverse=False)[0]
    return None


text:
(function ($) {

  /***
   * Usage example:
   *
       // autoresize columns
        var responsivenessPlugin = new Slick.Plugins.Responsiveness({
        });
        responsivenessPlugin.onResize.subscribe(function (evt, args) {
            var columns = args.grid.getColumns();
            var isWide = (args.width > 768); // ipad orientation narrow / wide
            // Hide or show the last two columns, based on the layout.
            // XXX this is a little rough... we'd need to be smarter here
            // to conserve our current columns sizes and order.
            if (isWide) {
                if (columns.length < 5) {
                    columns.push(origColumns[3]);
                    columns.push(origColumns[4]);
                }
            } else {
                if (columns.length > 3) {
                    columns = origColumns.slice(0, 3);
                }
            }
            args.grid.setColumns(columns);
        });
        grid.registerPlugin(responsivenessPlugin);
   *
   *
   */

  function Responsiveness(options) {
    var _grid;
    var _self = this;
    var _defaults = {
        delay: 400         // delay of processing in ms
    };
    var _options;
    var _timer;

    function init(grid) {
        _options = $.extend(true, {}, _defaults, options);
        _grid = grid;
        $(window).on('resize.responsiveness', handleResize);
    }

    function destroy() {
        $(window).off('resize.responsiveness');
        clearTimeout(_timer);
    }

    function handleResize(evt) {
        if (_timer !== null) {
            clearTimeout(_timer);
        }
        _timer = setTimeout(timeoutResize, _options.delay);
    }

    function timeoutResize() {
        var width = $(window).width();

        // Let the caller do something, like hide and show columns.
        _self.onResize.notify({
            "grid": _grid,
            "width": width
        }, null, _self);

        // and resize.
        _grid.autosizeColumns();
        timer = null;

    }

    $.extend(this, {
      "init": init,
      "destroy": destroy,

      "onResize": new Slick.Event()
    });

  }

  // register namespace
  $.extend(true, window, {
    "Slick": {
      "Plugins": {
        "Responsiveness": Responsiveness
      }
    }
  });

})(jQuery);


text:
package de.ids_mannheim.korap.query.spans;

import java.io.IOException;
import java.util.Map;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermContext;
import org.apache.lucene.util.Bits;

import de.ids_mannheim.korap.query.SimpleSpanQuery;
import de.ids_mannheim.korap.query.SpanElementQuery;
import de.ids_mannheim.korap.query.SpanRelationQuery;

/**
 * RelationBaseSpans is a base class for relation spans containing
 * properties about the start and end positions of right side of the
 * relation. It can also store information about the id of the
 * left/right side, for instance, when it is an element or another
 * relation.
 *
 * @author margaretha
 *
 */
public abstract class RelationBaseSpans extends SimpleSpans {

    protected short leftId, rightId;
    protected int leftStart, leftEnd;
    protected int rightStart, rightEnd;

    public RelationBaseSpans () {
        this.hasSpanId = true;
    }

    /**
     * Constructs RelationBaseSpans based on the given
     * SpanWithIdQuery.
     *
     * @param spanWithIdQuery
     *            a SpanWithIdQuery, for instance a
     *            {@link SpanElementQuery} or
     *            {@link SpanRelationQuery}.
     * @param context
     * @param acceptDocs
     * @param termContexts
     * @throws IOException
     */
    public RelationBaseSpans (SimpleSpanQuery spanWithIdQuery,
                              LeafReaderContext context, Bits acceptDocs,
                              Map<Term, TermContext> termContexts)
            throws IOException {
        super(spanWithIdQuery, context, acceptDocs, termContexts);
        this.hasSpanId = true;
    }

    /**
     * Returns the id of the left hand side of the relation.
     *
     * @return an id
     */
    public short getLeftId () {
        return leftId;
    }

    /**
     * Sets the id of the left hand side of the relation.
     *
     * @param leftId
     *            the id of the left hand side of the relation.
     */
    public void setLeftId (short leftId) {
        this.leftId = leftId;
    }

    public int getLeftStart () {
        return leftStart;
    }

    public void setLeftStart (int leftStart) {
        this.leftStart = leftStart;
    }

    public int getLeftEnd () {
        return leftEnd;
    }

    public void setLeftEnd (int leftEnd) {
        this.leftEnd = leftEnd;
    }

    /**
     * Returns the id of the right hand side of the relation.
     *
     * @return an id
     */
    public short getRightId () {
        return rightId;
    }

    /**
     * Sets the id of the right hand side of the relation.
     *
     * @param rightId
     *            the id of the right hand side of the relation.
     */
    public void setRightId (short rightId) {
        this.rightId = rightId;
    }

    /**
     * Returns the start position of the right hand side of the
     * relation.
     *
     * @return the start position
     */
    public int getRightStart () {
        return rightStart;
    }

    /**
     * Sets the start position of the right hand side of the relation.
     *
     * @param rightStart
     *            the start position of the right hand side of the
     *            relation.
     */
    public void setRightStart (int rightStart) {
        this.rightStart = rightStart;
    }

    /**
     * Returns the end position of the right hand side of the
     * relation.
     *
     * @return the end position
     */
    public int getRightEnd () {
        return rightEnd;
    }

    /**
     * Sets the start position of the right hand side of the relation.
     *
     * @param rightEnd
     *            the end position of the right hand side of the
     *            relation.
     */
    public void setRightEnd (int rightEnd) {
        this.rightEnd = rightEnd;
    }
}


text:
<SageTVPlugin>

    <Name>Squeezeslave Player</Name>

    <Identifier>squeezeslaveplayer</Identifier>

    <Version>2.3.0</Version>

    <Description>This is the Squeezeslave Player which runs on a SageTV extender (Unlimited Free Trial) - no need to install separately.</Description>

    <Author>routerunner</Author>

    <PluginType>Library</PluginType>

    <CreationDate>2012-01-05</CreationDate>

    <ModificationDate>2013-04-05</ModificationDate>

    <ReleaseNotes>

1.0.0 - First Public Release. Supported extenders: HD200, HD300

2.0.0 - Added support for MediaMVP. Fixed digital noise on HDx00. Better synchronisation support. License required.

2.0.1 - Better mutual exclusion mechanism. Fixed audio static noise issue with HD200/HD300 - IMPORTANT! Please hard power cycle the extender after the update.

2.0.2 - Massively reduced CPU usage. Fixed Ogg Vorbis support issue.

2.1.0 - Add support to HD100 extender. Support older HD300 firmware. Pure Digital Audio (HD100 only).

2.2.0 - Add support to IR remote control (see Plugin: Squeezeslave v2 announcement thread for details). Capabilities registration mechanism (requires Squeeze Server v7.4 or above).

2.2.1 - Various issue introduced by the remote control. Fix HD300 S/PDIF issue after watching HDTV. Added support for remote control "Home" button. Honour the LMS "Power on Resume" setting. Added unlimited trial mode.

2.2.2 - Add support of Pure Digital Audio Output to MediaMVP. Add Wake-On-Line support to all extenders.

2.3.0 - Add support of Pure Digital Audio Output to HD200/HD300. Add support of HDMI audio output to HD200/HD300.

    </ReleaseNotes>

    <Desktop>false</Desktop>

    <Package>

        <PackageType>System</PackageType>

        <Location>https://github.com/OpenSageTV/sagetv-plugin-repo/releases/download/1/squeezeslaveplayer_2_3_0.zip</Location>

        <MD5>40BF43C57AD399685C72F7D4A70AB8FA</MD5>

        <Overwrite>true</Overwrite>

    </Package>

</SageTVPlugin>


text:
<!doctype html>

  <meta charset="UTF-8" />
  <link rel="canonical" href="https://allthefreestock.com" />
  <title>Free Stock Pictures & Videos ~ AllTheFreeStock.com</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles/introstyle.css" />
  <link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>

AllTheFreeStock.com

I am Saijo George. I work at Envato on sites like ThemeForest, PhotoDune and VideoHive, as an inhouse SEO Analyst. You can also usually find me at the local SEO Meetup in Melbourne. If you are a marketing professional, have a look at my SEO & Marketing Tools list. You can also check out my blog about SEO & design.

Big thanks to these guys for making this possible: Mukesh, Ying Zhang's CSS bouncing arrow, Particleground by Jonathan Nicol, jQuery custom content scroller by Manos Malihutsakis, the idea for this site from TheStocks.im, FREE hosting on Git Pages and Flat Minimalistic Social Icons by Lee Gargano.

You can get in touch with me on Twitter : @SaijoGeorge.


text:
package com.che58.ljb.rxjava.rxbus;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.che58.ljb.rxjava.R;
import com.che58.ljb.rxjava.act.MainActivity;
import com.trello.rxlifecycle.FragmentEvent;
import com.trello.rxlifecycle.components.support.RxFragment;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.ConnectableObservable;

public class RxBusDemo_Bottom3Fragment extends RxFragment {

    @Bind(R.id.demo_rxbus_tap_txt)
    TextView _tapEventTxtShow;
    @Bind(R.id.demo_rxbus_tap_count)
    TextView _tapEventCountShow;
    private RxBus _rxBus;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_rxbus_bottom, container, false);
        ButterKnife.bind(this, layout);
        return layout;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        _rxBus = ((MainActivity) getActivity()).getRxBusSingleton();
    }

    @Override
    public void onStart() {
        super.onStart();

        //将普通的Observable转换为可连接的Observable
        ConnectableObservable<Object> tapEventEmitter = _rxBus.toObserverable().publish();

        tapEventEmitter
                .compose(this.bindToLifecycle())
                .subscribe(new Action1<Object>() { //一个一旦被触发就会显示TapText的监听者
            @Override
            public void call(Object event) {
                if (event instanceof RxBusDemoFragment.TapEvent) {
                    _showTapText();
                }
            }
        });

        tapEventEmitter
                .compose(this.bindUntilEvent(FragmentEvent.DESTROY))
                .publish(new Func1<Observable<Object>, Observable<List<Object>>>() {//一个出发后缓存一秒内的点击数并显示的监听者
                    @Override
                    public Observable<List<Object>> call(Observable<Object> stream) {
                        return stream.buffer(stream.debounce(1, TimeUnit.SECONDS)); //进行缓冲1秒,打包发送
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<Object>>() {
            @Override
            public void call(List<Object> taps) {
                _showTapCount(taps.size());
            }
        });

        tapEventEmitter.connect();  //可连接的Observable并不在订阅时触发,而需手动调用connect()方法
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    // -----------------------------------------------------------------------------------
    // Helper to show the text via an animation

    /**
     * 显示TapText
     */
    private void _showTapText() {
        _tapEventTxtShow.setVisibility(View.VISIBLE);
        _tapEventTxtShow.setAlpha(1f);
        ViewCompat.animate(_tapEventTxtShow).alphaBy(-1f).setDuration(400);
    }

    private void _showTapCount(int size) {
        _tapEventCountShow.setText(String.valueOf(size));
        _tapEventCountShow.setVisibility(View.VISIBLE);
        _tapEventCountShow.setScaleX(1f);
        _tapEventCountShow.setScaleY(1f);
        ViewCompat.animate(_tapEventCountShow)
                .scaleXBy(-1f)
                .scaleYBy(-1f)
                .setDuration(800)
                .setStartDelay(100);
    }
}


text:
#include <jni.h>
#include "AbstractExecutor.h"
/* Header for class es_bsc_compss_nio_worker_executors_PersistentExternalExecutor */

#ifndef _BindingExecutor
#define _BindingExecutor

void init_executor(AbstractExecutor *aExecutor);

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     es_bsc_compss_nio_worker_executors_PersistentExternalExecutor
 * Method:    executeInBinding
 * Signature: (I[Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_es_bsc_compss_invokers_external_persistent_PersistentInvoker_executeInBinding
(JNIEnv *, jclass, jstring);
// (JNIEnv *, jclass, jint, jobjectArray);

/*
 * Class:     es_bsc_compss_nio_worker_executors_PersistentExternalExecutor
 * Method:    finishThread
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_es_bsc_compss_invokers_external_persistent_PersistentInvoker_finishThread
(JNIEnv *, jclass);

/*
 * Class:     es_bsc_compss_nio_worker_executors_PersistentExternalExecutor
 * Method:    initThread
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_es_bsc_compss_invokers_external_persistent_PersistentInvoker_initThread
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif


text:
using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;

namespace WinAPI
{
    public static class Managed
    {
        public static Structs.WindowInfo GetWindowInfo(IntPtr windowHandle)
        {
            var windowInfo = new Structs.WindowInfo();
            windowInfo.cbSize = (uint)Marshal.SizeOf(windowInfo);
            NativeMethods.GetWindowInfo(windowHandle, ref windowInfo);
            return windowInfo;
        }

        public static string GetClassName(IntPtr handle)
        {
            StringBuilder stringBuilder = new StringBuilder(256);
            NativeMethods.GetClassName(handle, stringBuilder, 256);
            return stringBuilder.ToString();
        }

        public static Point GetCursorPosition()
        {
            Structs.POINT point;
            NativeMethods.GetCursorPos(out point);
            return new Point(point.X, point.Y);
        }

        /// <summary>
        /// Returns a list of all windows or all windows of the specified process
        /// </summary>
        public static ArrayList GetAllWindows(Process process = null)
        {
            var windowHandles = new ArrayList();
            NativeMethods.EnumedWindow callBackPtr = GotWindowHandleCallBack;

            if (process == null)
                NativeMethods.EnumWindows(callBackPtr, windowHandles);
            else
            {
                foreach (ProcessThread pThread in process.Threads)
                {
                    NativeMethods.EnumThreadWindows((uint)pThread.Id, GotWindowHandleCallBack, windowHandles);
                }
            }

            foreach (IntPtr windowHandle in windowHandles.ToArray())
            {
                NativeMethods.EnumChildWindows(windowHandle, callBackPtr, windowHandles);
            }

            return windowHandles;
        }

        public static bool GotWindowHandleCallBack(IntPtr windowHandle, ArrayList windowHandlesArray)
        {
            windowHandlesArray.Add(windowHandle);
            return true;
        }

        public static string GetWindowText(IntPtr windowHandle)
        {
            // Allocate correct string length first
            int length = NativeMethods.GetWindowTextLength(windowHandle);
            StringBuilder sb = new StringBuilder(length + 1);
            NativeMethods.GetWindowText(windowHandle, sb, sb.Capacity);
            return sb.ToString();
        }

        public static string GetWindowTextRaw(IntPtr windowHandle)
        {
            int textLength = (int)NativeMethods.SendMessage(windowHandle, (uint)Enums.WMessages.GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
            var stringBuilder = new StringBuilder(textLength + 1);
            NativeMethods.SendMessage(windowHandle, (uint)Enums.WMessages.GETTEXT, (IntPtr)stringBuilder.Capacity, stringBuilder);
            return stringBuilder.ToString();
        }

        public static void ShowWindow(IntPtr handle, bool hide = false)
        {
            const int SW_HIDE = 0;
            const int SW_RESTORE = 9;
            NativeMethods.ShowWindow(handle, hide ? SW_HIDE : SW_RESTORE);
        }

        public static uint GetWindowThreadProcessId(IntPtr handle)
        {
            return NativeMethods.GetWindowThreadProcessId(handle, IntPtr.Zero);
        }

        /// <summary>
        ///   Retrieve the active window handle.
        /// </summary>
        public static IntPtr GetActiveWindowHandle()
        {
            return NativeMethods.GetForegroundWindow();
        }

        #region Resume, Suspend

        /// <summary>
        ///   Resume or Suspend a processes list
        /// </summary>
        public static void ResumeOrSuspend(Process hProcess, bool isSuspend = true)
        {
            foreach (ProcessThread hThread in hProcess.Threads)
            {
                IntPtr ThreadHandle = NativeMethods.OpenThread(Enums.ThreadAccess.SuspendResume, false,
                                                               (uint)hThread.Id);
                if (isSuspend)
                    NativeMethods.SuspendThread(ThreadHandle);
                else
                    NativeMethods.ResumeThread(ThreadHandle);
            }
        }

        /// <summary>
        ///   Resumes all threads in the target process.
        /// </summary>
        public static void Resume(Process process)
        {
            ResumeOrSuspend(process, isSuspend: false);
        }

        /// <summary>
        ///   Suspends all threads in the target process.
        /// </summary>
        public static void Suspend(Process process)
        {
            ResumeOrSuspend(process, isSuspend: true);
        }

        #endregion Resume, Suspend

        #region IconExtraction

        /// <summary>
        ///   GetClassLongPtr (64 bit version loses significant specific 64-bit information)
        /// </summary>
        private static IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex)
        {
            if (IntPtr.Size == 4)
                return new IntPtr(NativeMethods.GetClassLong32(hWnd, nIndex));
            else
                return NativeMethods.GetClassLong64(hWnd, nIndex);
        }

        /// <summary>
        ///   Get process icon by handle
        /// </summary>
        public static Bitmap GetSmallWindowIcon(IntPtr hWnd)
        {
            try
            {
                var IDI_APPLICATION = new IntPtr(0x7F00);
                int GCL_HICON = -14;
                IntPtr hIcon = default(IntPtr);

                hIcon = NativeMethods.SendMessage(hWnd, (uint)Enums.WMessages.GETICON, new IntPtr(2), IntPtr.Zero);

                if (hIcon == IntPtr.Zero)
                    hIcon = GetClassLongPtr(hWnd, GCL_HICON);

                if (hIcon == IntPtr.Zero)
                    hIcon = NativeMethods.LoadIcon(IntPtr.Zero, IDI_APPLICATION);

                if (hIcon != IntPtr.Zero)
                    return new Bitmap(Icon.FromHandle(hIcon).ToBitmap(), 16, 16);
                else
                    return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static Bitmap ExtractIconFromExe(string file, bool large)
        {
            int readIconCount = 0;
            var hDummy = new IntPtr[1] { IntPtr.Zero };
            var hIconEx = new IntPtr[1] { IntPtr.Zero };

            try
            {
                if (large)
                    readIconCount = NativeMethods.ExtractIconEx(file, 0, hIconEx, hDummy, 1);
                else
                    readIconCount = NativeMethods.ExtractIconEx(file, 0, hDummy, hIconEx, 1);

                if (readIconCount > 0 && hIconEx[0] != IntPtr.Zero)
                    return new Bitmap(Icon.FromHandle(hIconEx[0]).ToBitmap(), 16, 16);
                else
                    return null;
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Could not extract icon", ex);
            }
            finally
            {
                // RELEASE RESOURCES
                foreach (IntPtr ptr in hIconEx)
                    if (ptr != IntPtr.Zero)
                        NativeMethods.DestroyIcon(ptr);

                foreach (IntPtr ptr in hDummy)
                    if (ptr != IntPtr.Zero)
                        NativeMethods.DestroyIcon(ptr);
            }
        }

        private const uint SHGFI_ICON = 0x100;
        private const uint SHGFI_LARGEICON = 0x0;    // 'Large icon
        private const uint SHGFI_SMALLICON = 0x1;    // 'Small icon

        /// <summary>
        /// Get the icon used for a given, existing file.
        /// </summary>
        /// <param name="fileName">Name of the file</param>
        /// <param name="small">Whether to get the small icon instead of the large one</param>
        public static Icon GetIconForFilename(string fileName, bool small)
        {
            Structs.SHFILEINFO shinfo = new Structs.SHFILEINFO();

            if (small)
            {
                IntPtr hImgSmall = NativeMethods.SHGetFileInfo(fileName, 0, ref shinfo,
                                   (uint)Marshal.SizeOf(shinfo),
                                    SHGFI_ICON |
                                    SHGFI_SMALLICON);
            }
            else
            {
                IntPtr hImgLarge = NativeMethods.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo),
                    SHGFI_ICON | SHGFI_LARGEICON);
            }

            if (shinfo.hIcon == IntPtr.Zero) return null;

            System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
            return myIcon;
        }

        #endregion IconExtraction
    }
}


text:
package org.elasticsearch.xpack.slm;

import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest;
import org.elasticsearch.common.ValidationException;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractSerializingTestCase;
import org.elasticsearch.xpack.core.slm.SnapshotLifecyclePolicy;
import org.elasticsearch.xpack.core.slm.SnapshotLifecyclePolicyMetadataTests;
import org.elasticsearch.xpack.core.slm.SnapshotRetentionConfiguration;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.elasticsearch.xpack.core.slm.SnapshotLifecyclePolicyMetadataTests.randomSnapshotLifecyclePolicy;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;

public class SnapshotLifecyclePolicyTests extends AbstractSerializingTestCase<SnapshotLifecyclePolicy> {

    private String id;

    public void testToRequest() {
        SnapshotLifecyclePolicy p = new SnapshotLifecyclePolicy("id", "name", "0 1 2 3 4 ? 2099", "repo", Collections.emptyMap(),
            SnapshotRetentionConfiguration.EMPTY);
        CreateSnapshotRequest request = p.toRequest();
        CreateSnapshotRequest expected = new CreateSnapshotRequest().userMetadata(Collections.singletonMap("policy", "id"));

        p = new SnapshotLifecyclePolicy("id", "name", "0 1 2 3 4 ? 2099", "repo", null, null);
        request = p.toRequest();
        expected.waitForCompletion(true).snapshot(request.snapshot()).repository("repo");
        assertEquals(expected, request);
    }
    public void testNextExecutionTime() {
        SnapshotLifecyclePolicy p = new SnapshotLifecyclePolicy("id", "name", "0 1 2 3 4 ? 2099", "repo", Collections.emptyMap(),
            SnapshotRetentionConfiguration.EMPTY);
        assertThat(p.calculateNextExecution(), equalTo(4078864860000L));
    }

    public void testCalculateNextInterval() {
        {
            SnapshotLifecyclePolicy p = new SnapshotLifecyclePolicy("id", "name", "0 0/5 * * * ?", "repo", Collections.emptyMap(),
                SnapshotRetentionConfiguration.EMPTY);
            assertThat(p.calculateNextInterval(), equalTo(TimeValue.timeValueMinutes(5)));
        }

        {
            SnapshotLifecyclePolicy p = new SnapshotLifecyclePolicy("id", "name", "0 1 2 3 4 ? 2099", "repo", Collections.emptyMap(),
                SnapshotRetentionConfiguration.EMPTY);
            assertThat(p.calculateNextInterval(), equalTo(TimeValue.MINUS_ONE));
        }

        {
            SnapshotLifecyclePolicy p = new SnapshotLifecyclePolicy("id", "name", "* * * 31 FEB ? *", "repo", Collections.emptyMap(),
                SnapshotRetentionConfiguration.EMPTY);
            assertThat(p.calculateNextInterval(), equalTo(TimeValue.MINUS_ONE));
        }
    }

    public void testValidation() {
        {
            SnapshotLifecyclePolicy policy = new SnapshotLifecyclePolicy("a,b", "<my, snapshot-{now/M}>",
                "* * * * * L", "  ", Collections.emptyMap(), SnapshotRetentionConfiguration.EMPTY);

            ValidationException e = policy.validate();
            assertThat(e.validationErrors(),
                containsInAnyOrder(
                    "invalid policy id [a,b]: must not contain the following characters [ , \", *, \\, <, |, ,, >, /, ?]",
                    "invalid snapshot name [<my, snapshot-{now/M}>]: must not contain contain" +
                        " the following characters [ , \", *, \\, <, |, ,, >, /, ?]",
                    "invalid repository name [  ]: cannot be empty",
                    "invalid schedule: invalid cron expression [* * * * * L]"));
        }

        {
            SnapshotLifecyclePolicy policy = new SnapshotLifecyclePolicy("_my_policy", "mySnap",
                " ", "repo", Collections.emptyMap(), SnapshotRetentionConfiguration.EMPTY);

            ValidationException e = policy.validate();
            assertThat(e.validationErrors(),
                containsInAnyOrder("invalid policy id [_my_policy]: must not start with '_'",
                    "invalid snapshot name [mySnap]: must be lowercase",
                    "invalid schedule [ ]: must not be empty"));
        }

        {
            SnapshotLifecyclePolicy policy = new SnapshotLifecyclePolicy("my_policy", "my_snap",
                "0 0/30 * * * ?", "repo", Collections.emptyMap(), SnapshotRetentionConfiguration.EMPTY);
            ValidationException e = policy.validate();
            assertThat(e, nullValue());
        }
    }

    public void testMetadataValidation() {
        {
            Map<String, Object> configuration = new HashMap<>();
            final String metadataString = randomAlphaOfLength(10);
            configuration.put("metadata", metadataString);

            SnapshotLifecyclePolicy policy = new SnapshotLifecyclePolicy("mypolicy", "<mysnapshot-{now/M}>",
                "1 * * * * ?", "myrepo", configuration, SnapshotRetentionConfiguration.EMPTY);
            ValidationException e = policy.validate();
            assertThat(e.validationErrors(), contains("invalid configuration.metadata [" + metadataString +
                "]: must be an object if present"));
        }

        {
            Map<String, Object> metadata = new HashMap<>();
            metadata.put("policy", randomAlphaOfLength(5));
            Map<String, Object> configuration = new HashMap<>();
            configuration.put("metadata", metadata);

            SnapshotLifecyclePolicy policy = new SnapshotLifecyclePolicy("mypolicy", "<mysnapshot-{now/M}>",
                "1 * * * * ?", "myrepo", configuration, SnapshotRetentionConfiguration.EMPTY);
            ValidationException e = policy.validate();
            assertThat(e.validationErrors(), contains("invalid configuration.metadata: field name [policy] is reserved and " +
                "will be added automatically"));
        }

        {
            Map<String, Object> metadata = new HashMap<>();
            final int fieldCount = randomIntBetween(67, 100); // 67 is the smallest field count with these sizes that causes an error
            final int keyBytes = 5; // chosen arbitrarily
            final int valueBytes = 4; // chosen arbitrarily
            int totalBytes = fieldCount * (keyBytes + valueBytes + 6 /* bytes of overhead per key/value pair */) + 1;
            for (int i = 0; i < fieldCount; i++) {
                metadata.put(randomValueOtherThanMany(key -> "policy".equals(key) || metadata.containsKey(key),
                    () -> randomAlphaOfLength(keyBytes)), randomAlphaOfLength(valueBytes));
            }
            Map<String, Object> configuration = new HashMap<>();
            configuration.put("metadata", metadata);

            SnapshotLifecyclePolicy policy = new SnapshotLifecyclePolicy("mypolicy", "<mysnapshot-{now/M}>",
                "1 * * * * ?", "myrepo", configuration, SnapshotRetentionConfiguration.EMPTY);
            ValidationException e = policy.validate();
            assertThat(e.validationErrors(), contains("invalid configuration.metadata: must be smaller than [1004] bytes, but is [" +
                totalBytes + "] bytes"));
        }
    }

    @Override
    protected SnapshotLifecyclePolicy doParseInstance(XContentParser parser) throws IOException {
        return SnapshotLifecyclePolicy.parse(parser, id);
    }

    @Override
    protected SnapshotLifecyclePolicy createTestInstance() {
        id = randomAlphaOfLength(5);
        return randomSnapshotLifecyclePolicy(id);
    }

    @Override
    protected SnapshotLifecyclePolicy mutateInstance(SnapshotLifecyclePolicy instance) {
        switch (between(0, 5)) {
            case 0:
                return new SnapshotLifecyclePolicy(instance.getId() + randomAlphaOfLength(2),
                    instance.getName(),
                    instance.getSchedule(),
                    instance.getRepository(),
                    instance.getConfig(),
                    instance.getRetentionPolicy());
            case 1:
                return new SnapshotLifecyclePolicy(instance.getId(),
                    instance.getName() + randomAlphaOfLength(2),
                    instance.getSchedule(),
                    instance.getRepository(),
                    instance.getConfig(),
                    instance.getRetentionPolicy());
            case 2:
                return new SnapshotLifecyclePolicy(instance.getId(),
                    instance.getName(),
                    randomValueOtherThan(instance.getSchedule(), SnapshotLifecyclePolicyMetadataTests::randomSchedule),
                    instance.getRepository(),
                    instance.getConfig(),
                    instance.getRetentionPolicy());
            case 3:
                return new SnapshotLifecyclePolicy(instance.getId(),
                    instance.getName(),
                    instance.getSchedule(),
                    instance.getRepository() + randomAlphaOfLength(2),
                    instance.getConfig(),
                    instance.getRetentionPolicy());
            case 4:
                Map<String, Object> newConfig = new HashMap<>();
                for (int i = 0; i < randomIntBetween(2, 5); i++) {
                    newConfig.put(randomAlphaOfLength(3), randomAlphaOfLength(3));
                }
                return new SnapshotLifecyclePolicy(instance.getId(),
                    instance.getName() + randomAlphaOfLength(2),
                    instance.getSchedule(),
                    instance.getRepository(),
                    newConfig,
                    instance.getRetentionPolicy());
            case 5:
                return new SnapshotLifecyclePolicy(instance.getId(),
                    instance.getName(),
                    instance.getSchedule(),
                    instance.getRepository(),
                    instance.getConfig(),
                    randomValueOtherThan(instance.getRetentionPolicy(), SnapshotLifecyclePolicyMetadataTests::randomRetention));
            default:
                throw new AssertionError("failure, got illegal switch case");
        }
    }

    @Override
    protected Writeable.Reader<SnapshotLifecyclePolicy> instanceReader() {
        return SnapshotLifecyclePolicy::new;
    }
}


text:
`conflicts_with` is used to declare conflicts that keep a Cask from installing or working correctly.

## conflicts_with cask:

The value should be another Cask token.

Example use: [`wireshark`](https://github.com/Homebrew/homebrew-cask/blob/903493e09cf33b845e7cf497ecf9cfc9709087ee/Casks/wireshark.rb#L10), which conflicts with `wireshark-chmodbpf`.

```ruby
conflicts_with cask: 'wireshark-chmodbpf'
```

## conflicts_with formula:

Note: `conflicts_with formula:` is a stub and is not yet functional.

The value should be another formula name.

Example use: [`macvim`](https://github.com/Homebrew/homebrew-cask/blob/84b90afd7b571e581f8a48d4bdf9c7bb24ebff3b/Casks/macvim.rb#L10), which conflicts with the `macvim` formula.

```ruby
conflicts_with formula: 'macvim'
```


text:
void registryTypes ()
{
    qmlRegisterType<MapInfo>("Arkanoid", 1, 0, "MapInfo");
}


text:
import Rx, {Observable, Concat} from 'rx';
import cycle from 'cycle-react';
import {Map} from 'immutable';
import {history, author, quit, unexisting, reset, help, cv, cvjson} from './commandsHandler.js';

function modifications$(intent) {

    const clearInputMod$ = intent.clearInput$.map(() => (cmd) => cmd.remove('input'));

    const changeInputMod$ = intent.changeInput$.map((x) => (cmd) => cmd.set('input', x));

    const submitInputMod$ = intent.submitInput$.map((x) => (cmd) => {
        //TODO: rewrite this project with pure cyclejs
        //TODO: add local storage driver to project, to manipulate local storage
        //TODO: manipulate local storage to create file system

        function update() {
            switch (x) {
                case 'help': return help(cmd, x);
                case 'history': return history(cmd, x);
                case 'reset': return reset(cmd);
                case 'reset -a': return window.localStorage.removeItem('itemKey');
                case 'cv': return cv(cmd, x);
                case 'cv --json': return cvjson(cmd, x);
                case 'q':
                case 'quit': return quit(cmd, x);
                default: return unexisting(cmd, x);
            }
        }
        return update();
    });

    return Observable.merge(
        changeInputMod$,
        clearInputMod$,
        submitInputMod$
    );
}

export default function model(intent, state) {
    const mod$ = modifications$(intent);
    return state.concat(mod$)
           .scan((cmd, mod) => mod(cmd))
            .map(st => st.toObject());
}


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = r'''
---
module: vmware_host_facts
short_description: Gathers facts about remote ESXi hostsystem
description:
    - This module can be used to gathers facts like CPU, memory, datastore, network and system etc. about ESXi host system.
    - Please specify hostname or IP address of ESXi host system as C(hostname).
    - If hostname or IP address of vCenter is provided as C(hostname) and C(esxi_hostname) is not specified, then the
      module will throw an error.
    - VSAN facts added in 2.7 version.
version_added: 2.5
author:
    - Wei Gao (@woshihaoren)
requirements:
    - python >= 2.6
    - PyVmomi
options:
  esxi_hostname:
    description:
    - ESXi hostname.
    - Host facts about the specified ESXi server will be returned.
    - By specifying this option, you can select which ESXi hostsystem is returned if connecting to a vCenter.
    version_added: 2.8
extends_documentation_fragment: vmware.documentation
'''

EXAMPLES = r'''
- name: Gather vmware host facts
  vmware_host_facts:
    hostname: "{{ esxi_server }}"
    username: "{{ esxi_username }}"
    password: "{{ esxi_password }}"
  register: host_facts
  delegate_to: localhost

- name: Gather vmware host facts from vCenter
  vmware_host_facts:
    hostname: "{{ vcenter_server }}"
    username: "{{ vcenter_user }}"
    password: "{{ vcenter_pass }}"
    esxi_hostname: "{{ esxi_hostname }}"
  register: host_facts
  delegate_to: localhost

- name: Get VSAN Cluster UUID from host facts
  vmware_host_facts:
    hostname: "{{ esxi_server }}"
    username: "{{ esxi_username }}"
    password: "{{ esxi_password }}"
  register: host_facts
- set_fact:
    cluster_uuid: "{{ host_facts['ansible_facts']['vsan_cluster_uuid'] }}"
'''

RETURN = r'''
ansible_facts:
  description: system info about the host machine
  returned: always
  type: dict
  sample:
    {
        "ansible_all_ipv4_addresses": [
            "10.76.33.200"
        ],
        "ansible_bios_date": "2011-01-01T00:00:00+00:00",
        "ansible_bios_version": "0.5.1",
        "ansible_datastore": [
            {
                "free": "11.63 GB",
                "name": "datastore1",
                "total": "12.50 GB"
            }
        ],
        "ansible_distribution": "VMware ESXi",
        "ansible_distribution_build": "4887370",
        "ansible_distribution_version": "6.5.0",
        "ansible_hostname": "10.76.33.100",
        "ansible_interfaces": [
            "vmk0"
        ],
        "ansible_memfree_mb": 2702,
        "ansible_memtotal_mb": 4095,
        "ansible_os_type": "vmnix-x86",
        "ansible_processor": "Intel Xeon E312xx (Sandy Bridge)",
        "ansible_processor_cores": 2,
        "ansible_processor_count": 2,
        "ansible_processor_vcpus": 2,
        "ansible_product_name": "KVM",
        "ansible_product_serial": "NA",
        "ansible_system_vendor": "Red Hat",
        "ansible_vmk0": {
            "device": "vmk0",
            "ipv4": {
                "address": "10.76.33.100",
                "netmask": "255.255.255.0"
            },
            "macaddress": "52:54:00:56:7d:59",
            "mtu": 1500
        },
        "vsan_cluster_uuid": null,
        "vsan_node_uuid": null,
        "vsan_health": "unknown",
    }
'''

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.formatters import bytes_to_human
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec, find_obj

try:
    from pyVmomi import vim
except ImportError:
    pass

class VMwareHostFactManager(PyVmomi):
    def __init__(self, module):
        super(VMwareHostFactManager, self).__init__(module)
        esxi_host_name = self.params.get('esxi_hostname', None)
        if self.is_vcenter():
            if esxi_host_name is None:
                self.module.fail_json(msg="Connected to a vCenter system without specifying esxi_hostname")
            self.host = self.get_all_host_objs(esxi_host_name=esxi_host_name)
            if len(self.host) > 1:
                self.module.fail_json(msg="esxi_hostname matched multiple hosts")
            self.host = self.host[0]
        else:
            self.host = find_obj(self.content, [vim.HostSystem], None)

        if self.host is None:
            self.module.fail_json(msg="Failed to find host system.")

    def all_facts(self):
        ansible_facts = {}
        ansible_facts.update(self.get_cpu_facts())
        ansible_facts.update(self.get_memory_facts())
        ansible_facts.update(self.get_datastore_facts())
        ansible_facts.update(self.get_network_facts())
        ansible_facts.update(self.get_system_facts())
        ansible_facts.update(self.get_vsan_facts())
        ansible_facts.update(self.get_cluster_facts())
        self.module.exit_json(changed=False, ansible_facts=ansible_facts)

    def get_cluster_facts(self):
        cluster_facts = {'cluster': None}
        if self.host.parent and isinstance(self.host.parent, vim.ClusterComputeResource):
            cluster_facts.update(cluster=self.host.parent.name)
        return cluster_facts

    def get_vsan_facts(self):
        config_mgr = self.host.configManager.vsanSystem
        if config_mgr is None:
            return {
                'vsan_cluster_uuid': None,
                'vsan_node_uuid': None,
                'vsan_health': "unknown",
            }

        status = config_mgr.QueryHostStatus()
        return {
            'vsan_cluster_uuid': status.uuid,
            'vsan_node_uuid': status.nodeUuid,
            'vsan_health': status.health,
        }

    def get_cpu_facts(self):
        return {
            'ansible_processor': self.host.summary.hardware.cpuModel,
            'ansible_processor_cores': self.host.summary.hardware.numCpuCores,
            'ansible_processor_count': self.host.summary.hardware.numCpuPkgs,
            'ansible_processor_vcpus': self.host.summary.hardware.numCpuThreads,
        }

    def get_memory_facts(self):
        return {
            'ansible_memfree_mb': self.host.hardware.memorySize // 1024 // 1024 - self.host.summary.quickStats.overallMemoryUsage,
            'ansible_memtotal_mb': self.host.hardware.memorySize // 1024 // 1024,
        }

    def get_datastore_facts(self):
        facts = dict()
        facts['ansible_datastore'] = []
        for store in self.host.datastore:
            _tmp = {
                'name': store.summary.name,
                'total': bytes_to_human(store.summary.capacity),
                'free': bytes_to_human(store.summary.freeSpace),
            }
            facts['ansible_datastore'].append(_tmp)
        return facts

    def get_network_facts(self):
        facts = dict()
        facts['ansible_interfaces'] = []
        facts['ansible_all_ipv4_addresses'] = []
        for nic in self.host.config.network.vnic:
            device = nic.device
            facts['ansible_interfaces'].append(device)
            facts['ansible_all_ipv4_addresses'].append(nic.spec.ip.ipAddress)
            _tmp = {
                'device': device,
                'ipv4': {
                    'address': nic.spec.ip.ipAddress,
                    'netmask': nic.spec.ip.subnetMask,
                },
                'macaddress': nic.spec.mac,
                'mtu': nic.spec.mtu,
            }
            facts['ansible_' + device] = _tmp
        return facts

    def get_system_facts(self):
        sn = 'NA'
        for info in self.host.hardware.systemInfo.otherIdentifyingInfo:
            if info.identifierType.key == 'ServiceTag':
                sn = info.identifierValue
        facts = {
            'ansible_distribution': self.host.config.product.name,
            'ansible_distribution_version': self.host.config.product.version,
            'ansible_distribution_build': self.host.config.product.build,
            'ansible_os_type': self.host.config.product.osType,
            'ansible_system_vendor': self.host.hardware.systemInfo.vendor,
            'ansible_hostname': self.host.summary.config.name,
            'ansible_product_name': self.host.hardware.systemInfo.model,
            'ansible_product_serial': sn,
            'ansible_bios_date': self.host.hardware.biosInfo.releaseDate,
            'ansible_bios_version': self.host.hardware.biosInfo.biosVersion,
        }
        return facts

def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        esxi_hostname=dict(type='str', required=False),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    vm_host_manager = VMwareHostFactManager(module)
    vm_host_manager.all_facts()

if __name__ == '__main__':
    main()


text:
<?php

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
 * Description of home_controller
 *
 * @author Germán David Ruiz Figueroa
 */
View::template('home');
Load::models(
    'formato',
    'muestra',
    'tipoensayo',
    'tipomuestra',
    'lugartomamuestra',
    'muestramemoriacalculo',
    'tempformatotipoensayo'
);
class MemoriaController extends AppController
{
  public function variables()
  {
    $tipoEnsayo = new TipoEnsayo();

    $this->tiposEnsayo = $tipoEnsayo->find();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $tags2 = array_keys($_POST); // obtiene los nombres de las varibles
        $valores2 = array_values($_POST); // obtiene los valores de las varibles

        foreach ($tags2 as $index => $constId) {
          $id = explode("_", $constId);
          $id = $id[1];

          $constante = Load::model('constantetipoensayo')->find_first("id=$id");

          if (isset($constante) && $constante->valor != $valores2[$index]) {
            $constante->valor = $valores2[$index];

            $constante->save();
          }
        }
    }
  }
}


text:
<project name="SampleTestApplication" default="test">
    <!-- Project specific overrides -->
    <property name="root.dir" location="../../"/>

    <!-- Shared properties -->
    <property file="${root.dir}/build-user.properties" />

    <!-- Common properties and targets -->
    <import file="${root.dir}/tools/build-common-imports.xml" />
    <import file="${root.dir}/lib/build-assets.xml" />

    <!-- Build path -->
    <path id="flex.lib.path">
        <pathelement location="${flexunit.swc}"/>
        <pathelement location="${arc-flexunit.swc}"/>
    </path>

    <!-- Project specific targets -->
    <target name="build" depends="init,flex-test-application" description="Build the test application"/>
    <target name="test" depends="build,test-flexunit" description="Run the test application"/>
</project>