text:
import * as utils from "tsutils";
import * as ts from "typescript";

import * as Lint from "../index";

export class Rule extends Lint.Rules.TypedRule {
    /* tslint:disable:object-literal-sort-keys */
    public static metadata: Lint.IRuleMetadata = {
        ruleName: "no-unnecessary-qualifier",
        description: "Warns when a namespace qualifier (`A.x`) is unnecessary.",
        hasFix: true,
        optionsDescription: "Not configurable.",
        options: null,
        optionExamples: [true],
        type: "style",
        typescriptOnly: true,
        requiresTypeInfo: true,
    };
    /* tslint:enable:object-literal-sort-keys */

    public static FAILURE_STRING(name: string) {
        return `Qualifier is unnecessary since '${name}' is in scope.`;
    }

    public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
        return this.applyWithFunction(sourceFile, walk, undefined, program.getTypeChecker());
    }
}

function walk(ctx: Lint.WalkContext, checker: ts.TypeChecker): void {
    const namespacesInScope: Array<ts.ModuleDeclaration | ts.EnumDeclaration> = [];
    ts.forEachChild(ctx.sourceFile, cb);

    function cb(node: ts.Node): void {
        switch (node.kind) {
            case ts.SyntaxKind.ModuleDeclaration:
            case ts.SyntaxKind.EnumDeclaration:
                namespacesInScope.push(node as ts.ModuleDeclaration | ts.EnumDeclaration);
                ts.forEachChild(node, cb);
                namespacesInScope.pop();
                break;

            case ts.SyntaxKind.QualifiedName:
                const { left, right } = node as ts.QualifiedName;
                visitNamespaceAccess(node, left, right);
                break;

            case ts.SyntaxKind.PropertyAccessExpression:
                const { expression, name } = node as ts.PropertyAccessExpression;
                if (utils.isEntityNameExpression(expression)) {
                    visitNamespaceAccess(node, expression, name);
                    break;
                }
            // falls through

            default:
                ts.forEachChild(node, cb);
        }
    }

    function visitNamespaceAccess(
        node: ts.Node,
        qualifier: ts.EntityNameOrEntityNameExpression,
        name: ts.Identifier,
    ): void {
        if (qualifierIsUnnecessary(qualifier, name)) {
            const fix = Lint.Replacement.deleteFromTo(qualifier.getStart(), name.getStart());
            ctx.addFailureAtNode(qualifier, Rule.FAILURE_STRING(qualifier.getText()), fix);
        } else {
            // Only look for nested qualifier errors if we didn't already fail on the outer qualifier.
            ts.forEachChild(node, cb);
        }
    }

    function qualifierIsUnnecessary(
        qualifier: ts.EntityNameOrEntityNameExpression,
        name: ts.Identifier,
    ): boolean {
        const namespaceSymbol = checker.getSymbolAtLocation(qualifier);
        if (namespaceSymbol === undefined || !symbolIsNamespaceInScope(namespaceSymbol)) {
            return false;
        }

        const accessedSymbol = checker.getSymbolAtLocation(name);
        if (accessedSymbol === undefined) {
            return false;
        }

        // If the symbol in scope is different, the qualifier is necessary.
        const fromScope = getSymbolInScope(qualifier, accessedSymbol.flags, name.text);
        return fromScope === undefined || symbolsAreEqual(accessedSymbol, fromScope);
    }

    function getSymbolInScope(
        node: ts.Node,
        flags: ts.SymbolFlags,
        name: string,
    ): ts.Symbol | undefined {
        // TODO:PERF `getSymbolsInScope` gets a long list. Is there a better way?
        const scope = checker.getSymbolsInScope(node, flags);
        return scope.find(scopeSymbol => scopeSymbol.name === name);
    }

    function symbolIsNamespaceInScope(symbol: ts.Symbol): boolean {
        const symbolDeclarations = symbol.getDeclarations();
        if (symbolDeclarations === undefined) {
            return false;
        } else if (symbolDeclarations.some(decl => namespacesInScope.some(ns => ns === decl))) {
            return true;
        }

        const alias = tryGetAliasedSymbol(symbol, checker);
        return alias !== undefined && symbolIsNamespaceInScope(alias);
    }

    function symbolsAreEqual(accessed: ts.Symbol, inScope: ts.Symbol): boolean {
        if (checker.getExportSymbolOfSymbol !== undefined) {
            inScope = checker.getExportSymbolOfSymbol(inScope);
            return accessed === inScope;
        }
        return (
            accessed === inScope ||
            // For compatibility with typescript@2.5: compare declarations because the symbols don't have the same reference
            Lint.Utils.arraysAreEqual(
                accessed.declarations,
                inScope.declarations,
                (a, b) => a === b,
            )
        );
    }
}

function tryGetAliasedSymbol(symbol: ts.Symbol, checker: ts.TypeChecker): ts.Symbol | undefined {
    return utils.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias)
        ? checker.getAliasedSymbol(symbol)
        : undefined;
}


text:
#ifndef __TestCpp__PageViewReader__
#define __TestCpp__PageViewReader__

#include "cocostudio/WidgetReader/LayoutReader/LayoutReader.h"
#include "cocostudio/CocosStudioExport.h"

namespace cocostudio
{
    class CC_STUDIO_DLL PageViewReader : public LayoutReader
    {
        DECLARE_CLASS_NODE_READER_INFO

    public:
        PageViewReader();
        virtual ~PageViewReader();

        static PageViewReader* getInstance();
        static void purge();

        virtual void setPropsFromJsonDictionary(cocos2d::ui::Widget* widget, const rapidjson::Value& options);
        virtual void setPropsFromBinary(cocos2d::ui::Widget* widget, CocoLoader* cocoLoader,  stExpCocoNode* cocoNode) ;
        flatbuffers::Offset<flatbuffers::Table> createOptionsWithFlatBuffers(const tinyxml2::XMLElement* objectData,
                                                                             flatbuffers::FlatBufferBuilder* builder);
        void setPropsWithFlatBuffers(cocos2d::Node* node, const flatbuffers::Table* pageViewOptions);
        cocos2d::Node* createNodeWithFlatBuffers(const flatbuffers::Table* pageViewOptions);

        int getResourceType(std::string key);

    };
}

#endif /* defined(__TestCpp__PageViewReader__) */

redpajama_set_name: RedPajamaGithub


text:
package com.maxcriser.hw_jsonpareser;

import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.maxcriser.hw_jsonpareser.gson.DateConverter;
import com.maxcriser.hw_jsonpareser.gson.GSONParser;
import com.maxcriser.hw_jsonpareser.gson.GSONParserUserInfo;
import com.maxcriser.hw_jsonpareser.json.JSONParser;
import com.maxcriser.hw_jsonpareser.json.JSONParserUserInfo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

class JSONReader extends AsyncTask<Object, Object, String> {

    public static final String SOLUTION_TAG = "Solution: ";
    HttpURLConnection mHttpURLConnection;
    BufferedReader inputReader;
    StringBuffer mStringBuffer;

    String urlPage;
    String row;

    URL mURL;

    public JSONReader(String str) {
        urlPage = str;
    }

    @Override
    protected String doInBackground(Object... params) {

        mStringBuffer = new StringBuffer();

        try {
            mURL = new URL(urlPage);

            mHttpURLConnection = (HttpURLConnection) mURL.openConnection();
            mHttpURLConnection.setRequestMethod("GET");
            mHttpURLConnection.connect();

            InputStream inputStream = mHttpURLConnection.getInputStream();

            inputReader = new BufferedReader(new InputStreamReader(inputStream));

            while ((row = inputReader.readLine()) != null) {
                mStringBuffer.append(row);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mStringBuffer.toString();
    }

    @Override
    protected void onPostExecute(String pS) {
        super.onPostExecute(pS);

        Log.d(SOLUTION_TAG, "Parse is done - " + pS);

        JSONParser friendsInfo = new JSONParser(pS);
        List<JSONParserUserInfo> listJSON = friendsInfo.getJSONParserUserInfo();

        // listJSON (type: JSONParserUserInfo) consist of Getters: name (getName), city(getCity), email(getEmail)

        Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateConverter()).create();

        GSONParser twitterSearchResponse = gson.fromJson(pS, GSONParser.class);
        List<GSONParserUserInfo> listGSON = twitterSearchResponse.getGSONParserUserInfo();

        // listGSON (type: GSONParserUserInfo) consist of Getters: name (getName), city(getCity), email(getEmail)
    }
}


text:
package auth_test

import (
	"context"
	"net/http"
	"testing"

	"github.com/almighty/almighty-core/auth"
	"github.com/almighty/almighty-core/resource"
	"github.com/goadesign/goa"
	"github.com/satori/go.uuid"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"

	_ "github.com/lib/pq"
)

func TestPolicy(t *testing.T) {
	resource.Require(t, resource.Remote)
	suite.Run(t, new(TestPolicySuite))
}

type TestPolicySuite struct {
	suite.Suite
	policyManager *auth.KeycloakPolicyManager
}

func (s *TestPolicySuite) SetupSuite() {
	s.policyManager = auth.NewKeycloakPolicyManager(configuration)
}

func (s *TestPolicySuite) TearDownSuite() {
	cleanKeycloakResources(s.T())
}

func (s *TestPolicySuite) TestGetPolicyOK() {
	policy, policyID := createPermissionWithPolicy(s)

	r := &goa.RequestData{
		Request: &http.Request{Host: "domain.io"},
	}
	obtainedPolicy, newPat, err := s.policyManager.GetPolicy(context.Background(), r, policyID)
	require.Nil(s.T(), err)
	require.NotNil(s.T(), obtainedPolicy)
	require.NotNil(s.T(), newPat)
	require.NotNil(s.T(), obtainedPolicy.ID)
	require.Equal(s.T(), policyID, *obtainedPolicy.ID)
	require.Equal(s.T(), policy.Config.UserIDs, obtainedPolicy.Config.UserIDs)
	require.Equal(s.T(), policy.Type, obtainedPolicy.Type)
	require.Equal(s.T(), policy.Name, obtainedPolicy.Name)
}

func (s *TestPolicySuite) TestUpdatePolicyOK() {
	policy, policyID := createPermissionWithPolicy(s)
	policy.AddUserToPolicy(uuid.NewV4().String())
	policy.ID = &policyID
	r := &goa.RequestData{
		Request: &http.Request{Host: "domain.io"},
	}
	pat := getProtectedAPITokenOK(s.T())
	err := s.policyManager.UpdatePolicy(context.Background(), r, *policy, pat)
	require.Nil(s.T(), err)
	obtainedPolicy, newPat, err := s.policyManager.GetPolicy(context.Background(), r, policyID)
	require.Nil(s.T(), err)
	require.NotNil(s.T(), obtainedPolicy)
	require.NotNil(s.T(), newPat)
	require.NotNil(s.T(), obtainedPolicy.ID)
	require.Equal(s.T(), policyID, *obtainedPolicy.ID)
	require.Equal(s.T(), policy.Config.UserIDs, obtainedPolicy.Config.UserIDs)
	require.Equal(s.T(), policy.Type, obtainedPolicy.Type)
	require.Equal(s.T(), policy.Name, obtainedPolicy.Name)
}

func createPermissionWithPolicy(s *TestPolicySuite) (*auth.KeycloakPolicy, string) {
	ctx := context.Background()
	pat := getProtectedAPITokenOK(s.T())

	resourceID, _ := createResource(s.T(), ctx, pat)
	clientId, clientsEndpoint := getClientIDAndEndpoint(s.T())
	policyID, policy := createPolicy(s.T(), ctx, pat)
	require.NotNil(s.T(), policy)

	permission := auth.KeycloakPermission{
		Name:             "test-" + uuid.NewV4().String(),
		Type:             auth.PermissionTypeResource,
		Logic:            auth.PolicyLogicPossitive,
		DecisionStrategy: auth.PolicyDecisionStrategyUnanimous,
		// "config":{"resources":"[\"<ResourceID>\"]","applyPolicies":"[\"<PolicyID>\"]"}
		Config: auth.PermissionConfigData{
			Resources:     "[\"" + resourceID + "\"]",
			ApplyPolicies: "[\"" + policyID + "\"]",
		},
	}

	permissionID, err := auth.CreatePermission(ctx, clientsEndpoint, clientId, permission, pat)
	require.Nil(s.T(), err)
	require.NotEqual(s.T(), "", permissionID)

	return &policy, policyID
}


text:
insert into site_rs_staff_roles (id,role_code,site_research_staffs_id,start_date)
select nextval('site_rs_staff_roles_id_seq'), cg.group_name, srs.id, '2008-01-01'
from
	csm_user cu,csm_user_group cug,csm_group cg,research_staffs rs,site_research_staffs srs
where
	cu.user_id = cug.user_id and
	cug.group_id IN (-4,-5,-13,-14,-7942,-7943) and
	cug.group_id = cg.group_id and
	rs.login_id = cu.login_name and
	rs.email_address = cu.email_id and
	rs.id = srs.researchstaff_id
group by cu.user_id,cg.group_name,srs.id
order by cu.user_id


text:
package com.lucadev.mcprotocol.auth.yggdrasil.cache;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lucadev.mcprotocol.auth.yggdrasil.YggdrasilSession;
import com.lucadev.mcprotocol.util.StringUtil;

import java.io.File;
import java.io.IOException;

/**
 * Implementation of the YggdrasilSessionStorage using a file to store it.
 *
 * @author Luca Camphuisen < Luca.Camphuisen@hva.nl >
 */
public class FileYggdrasilSessionStorage implements YggdrasilSessionStorage {

    /**
     * Default filename to use if no file was specified in the constructors.
     */
    private static final String DEFAULT_FILENAME = "session.json";

    private final ObjectMapper jsonMapper = new ObjectMapper();
    private final File file;

    /**
     * Default constructor uses a file named "session.json" in the current working directory.
     */
    public FileYggdrasilSessionStorage() {
        this("session.json");
    }

    /**
     * @param file specify the file we will use.
     */
    public FileYggdrasilSessionStorage(String file) {
        this(new File(StringUtil.isNullOrEmpty(file) ? DEFAULT_FILENAME : file));
    }

    /**
     * @param file the file to store and load from.
     */
    public FileYggdrasilSessionStorage(File file) {
        this.file = file;
    }

    /**
     * Stores the given session
     *
     * @param session the YggdrasilSession to store.
     * @throws IOException thrown when we somehow cannot store it.
     */
    @Override
    public void store(YggdrasilSession session) throws IOException {
        if (file.exists()) {
            if (!file.delete()) {
                throw new IOException("Could not delete previous session file.");
            }
        }

        if (!file.createNewFile()) {
            throw new IOException("Could not create session file.");
        }

        jsonMapper.writeValue(file, session);
    }

    /**
     * Loads the YggdrasilSession
     *
     * @return loaded YggdrasilSession that has not been verified yet.
     * @throws IOException thrown when we could not load it.
     */
    @Override
    public YggdrasilSession load() throws IOException {
        if (!file.exists()) {
            return null;
        }

        return jsonMapper.readValue(file, YggdrasilSession.class);
    }
}


text:
<?php

namespace Sqz\Slim\DI;

use DI\ContainerBuilder as DIContainerBuilder;

/**
 * ContainerBuilder class for sqz-slim-phpdi <http://github.com/zeroastro/sqz-slim-phpdi>
 *
 * @license MIT
 * @author Salvatore Quaranta (Zeroastro) <salvoquaranta@gmail.com>
 */
class ContainerBuilder
{
    /**
     * @var \DI\ContainerBuilder;
     */
    private $builder;

    /**
     * @var DefaultSettingsProvider
     */
    private $defaultSettingsProvider;

    /**
     * Creates a ContainerBuilder using \Sqz\Slim\DI\Container as Container
     */
    public function __construct()
    {
        $this->builder = new DIContainerBuilder(Container::class);
        $this->defaultSettingsProvider = new DefaultSettingsProvider();
    }

    /**
     * Statically creates the Container using given settings and services
     *
     * @param array $settings Array of custom settings
     * @param array $services Array of services
     *
     * @return \Sqz\Slim\DI\Container
     */
    public static function create(array $settings = [], array $services = [])
    {
        return (new static())->build($settings, $services);
    }

    /**
     * Build the Container using given settings and services
     *
     * @param array $settings Array of custom settings
     * @param array $services Array of services
     *
     * @return \Sqz\Slim\DI\Container
     */
    public function build(array $settings = [], array $services = [])
    {
        if (array_key_exists('phpdi-settings', $settings) && is_array($settings['phpdi-settings'])) {
            $this->configurePhpDi($settings['phpdi-settings']);
        }

        $realSettings = array_merge($this->defaultSettingsProvider->getDefaultSettings(), $settings);

        $allServices = array_merge($this->defaultSettingsProvider->getDefaultServices(), $services);

        $this->builder->addDefinitions(['settings' => $realSettings]);
        $this->builder->addDefinitions($allServices);

        return $this->builder->build();
    }

    /**
     * Reconfigures PHP-DI
     *
     * @param array $settings Array of custom settings
     */
    private function configurePhpDi(array $settings)
    {
        if (array_key_exists('use_autowiring', $settings)) {
            $this->builder->useAutowiring((bool) $settings['use_autowiring']);
        }

        if (array_key_exists('use_annotations', $settings)) {
            $this->builder->useAnnotations((bool) $settings['use_annotations']);
        }

        if (array_key_exists('ignore_php_doc_errors', $settings)) {
            $this->builder->ignorePhpDocErrors((bool) $settings['ignore_php_doc_errors']);
        }

        if (array_key_exists('proxies_to_file_path', $settings)) {
            $this->builder->writeProxiesToFile(true, $settings['proxies_to_file_path']);
        }

        if (array_key_exists('definitions_cache', $settings)) {
            $this->builder->setDefinitionCache($settings['definitions_cache']);
        }
    }
}


text:
/*---
description: Fails by throwing an error
---*/

function foo() {
    throw new Error('failure message');
}

foo();


text:
extern crate clap;
#[cfg(feature = "color")]
extern crate ansi_term;
extern crate tabwriter;
extern crate glob;
extern crate regex;

use std::io::Write;
#[cfg(feature = "debug")]
use std::env;

use clap::{App, AppSettings, Arg, SubCommand};

use config::Config;
use count::Counts;
use error::{CliError, CliResult};
use fmt::Format;

#[macro_use]
mod macros;
mod comment;
mod config;
mod count;
mod error;
mod fmt;
mod fsutil;
mod language;

static UTF8_RULES: [&'static str; 3] = ["strict", "lossy", "ignore"];

fn main() {
    debugln!("executing; cmd=cargo-count; args={:?}", env::args().collect::<Vec<_>>());
    let m = App::new("cargo-count")
        .version(&*format!("v{}", crate_version!()))
        // We have to lie about our binary name since this will be a third party
        // subcommand for cargo but we want usage strings to generated properly
        .bin_name("cargo")
        // Global version uses the version we supplied (Cargo.toml) for all subcommands as well
        .settings(&[AppSettings::GlobalVersion,
                    AppSettings::SubcommandRequired])
        // We use a subcommand because everything parsed after `cargo` is sent to the third party
        // plugin which will then be interpreted as a subcommand/positional arg by clap
        .subcommand(SubCommand::with_name("count")
            .author("Kevin K. <kbknapp@gmail.com>")
            .about("Displays line counts of code for cargo projects")
            .args_from_usage("-e, --exclude [paths]...    'Files or directories to exclude (automatically includes \'.git\')'
                              --unsafe-statistics         'Displays lines and percentages of \"unsafe\" code'
                              -l, --language [exts]...    'Only count these languges (by source code extension){n}\
                                                           (i.e. \'-l js py cpp\')'
                              -v, --verbose               'Print verbose output'
                              -S, --follow-symlinks       'Follows symlinks and counts source files it finds{n}(Defaults to false when omitted)'
                              [to_count]...               'The files or directories (including children) to count{n}\
                                                           (defaults to current working directory when omitted)'")
            .arg(Arg::from_usage("-s, --separator [sep]   'Set the thousands separator for pretty printing'")
                .validator(single_char))
            .arg(Arg::from_usage("--utf8-rule [rule]     'Sets the UTF-8 parsing rule (Defaults to \'strict\'){n}'")
                .possible_values(&UTF8_RULES))
            .after_help("When using '--exclude <path>' the path given can either be relative to the current \n\
                         directory, or absolute. When '<path>' is a file, it must be relative to the current \n\
                         directory or it will not be found. Example, if the current directory has a child \n\
                         directory named 'target' with a child fild 'test.rs' and you use `--exclude target/test.rs' \n\
                         \n\
                         Globs are also supported. For example, to eclude 'test.rs' files from all child directories \n\
                         of the current directory you could do '--exclude */test.rs'."))
        .get_matches();

    if let Some(m) = m.subcommand_matches("count") {
        let cfg = Config::from_matches(m).unwrap_or_else(|e| e.exit());
        println!("Gathering information...");
        if let Err(e) = execute(cfg) {
            e.exit();
        }
    }
}

fn execute(cfg: Config) -> CliResult<()> {
    debugln!("executing; cmd=execute;");
    verboseln!(cfg, "{}: {:?}", Format::Warning("Excluding"), cfg.exclude);
    verbose!(cfg, "{}",
        if cfg.exts.is_some() {
            format!("{} including files with extension: {}\n", Format::Warning("Only"), cfg.exts.as_ref().unwrap().connect(", "))
        } else {
            "".to_owned()
        }
    );

    debugln!("Checking for files or dirs to count from cli");

    let mut counts = Counts::new(&cfg);
    counts.fill_from();
    cli_try!(counts.count());
    cli_try!(counts.write_results());
    Ok(())
}

fn single_char(s: String) -> Result<(), String> {
    if s.len() != 1 {
        Err(format!("the --separator argument option only accepts a single character but found '{}'", Format::Warning(s)))
    } else {
        Ok(())
    }
}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20141002181008 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP INDEX UNIQ_1483A5E935C246D5 ON users');
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE UNIQUE INDEX UNIQ_1483A5E935C246D5 ON users (password)');
    }
}


text:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginService } from '../services/login.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  username: FormControl;
  password: FormControl;
  cookieStor = [];
  reportList = [];
  errorMessage = "Login Failed";
  location: Location;

  constructor(builder: FormBuilder, private loginService: LoginService, private router: Router) {
    this.username = new FormControl('', [Validators.required]);
    this.password = new FormControl('', [Validators.required, Validators.minLength(6)]);
    this.loginForm = builder.group({
      username: this.username,
      password: this.password
    });
  }

  login() {
    this.loginService.login(this.loginForm.value)
      .subscribe(cookieStor => {
        this.cookieStor = cookieStor;
        sessionStorage.setItem('rolejson', JSON.stringify(cookieStor));
        this.reportList = JSON.parse(cookieStor.roleJSON).categories;
        sessionStorage.setItem('reportList', JSON.stringify(this.reportList));
        console.log(this.reportList);
      },
      err => { this.errorMessage = err.message; },
      () => { console.log('Data Loading Completed'); });
    //console.log(this.cookieStor);

    //location.href("localhost:4200");
    //this.router.navigate(["/crisis-center"])
    this.router.navigate(["/dashboard"])
  }

  //  login(){
  //    console.log(this.loginForm.value);
  //  }
  ngOnInit() {
  }

}


text:
#region References

using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Migrations.History;
using Bloodhound.Data.Mappings;
using Bloodhound.Models;

#endregion

namespace Bloodhound.Data
{
	[DbConfigurationType(typeof (ModelConfiguration))]
	public class DataContext : DbContext, IDataContext
	{
		#region Constructors

		public DataContext()
			: this("DefaultConnection")
		{
		}

		public DataContext(string nameOrConnectionString)
			: base(nameOrConnectionString)
		{
		}

		#endregion

		#region Properties

		public IRepository<Event> Events => new Repository<Event>(Set<Event>());

		public IRepository<EventValue> EventValues => new Repository<EventValue>(Set<EventValue>());

		public IRepository<WidgetFilter> WidgetFilters => new Repository<WidgetFilter>(Set<WidgetFilter>());

		public IRepository<Widget> Widgets => new Repository<Widget>(Set<Widget>());

		#endregion

		#region Methods

		protected override void OnModelCreating(DbModelBuilder modelBuilder)
		{
			modelBuilder.Configurations.Add(new EventMap());
			modelBuilder.Configurations.Add(new EventValueMap());
			modelBuilder.Configurations.Add(new WidgetFilterMap());
			modelBuilder.Configurations.Add(new WidgetMap());
		}

		#endregion

		#region Classes

		private class DbHistoryContext : HistoryContext
		{
			#region Constructors

			public DbHistoryContext(DbConnection dbConnection, string defaultSchema)
				: base(dbConnection, defaultSchema)
			{
			}

			#endregion

			#region Methods

			protected override void OnModelCreating(DbModelBuilder modelBuilder)
			{
				base.OnModelCreating(modelBuilder);
				modelBuilder.Entity<HistoryRow>().ToTable("MigrationHistory", "system");
			}

			#endregion
		}

		private class ModelConfiguration : DbConfiguration
		{
			#region Constructors

			public ModelConfiguration()
			{
				SetHistoryContext("System.Data.SqlClient", (connection, defaultSchema) => new DbHistoryContext(connection, defaultSchema));
			}

			#endregion
		}

		#endregion
	}
}


text:
package org.apache.hadoop.ozone.container.common;

import com.google.common.base.Preconditions;
import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos;
import org.apache.hadoop.hdds.protocol.proto.
    StorageContainerDatanodeProtocolProtos.CommandStatus;
import org.apache.hadoop.hdds.scm.VersionInfo;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.DatanodeDetailsProto;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos.SCMHeartbeatRequestProto;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos.ContainerBlocksDeletionACKProto;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos
    .ContainerBlocksDeletionACKResponseProto;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos.ContainerInfo;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos.SCMCommandProto;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos.SCMHeartbeatResponseProto;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos.NodeReportProto;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos.StorageReportProto;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.protocol.StorageContainerDatanodeProtocol;
import org.apache.hadoop.ozone.protocol.VersionResponse;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * SCM RPC mock class.
 */
public class ScmTestMock implements StorageContainerDatanodeProtocol {
  private int rpcResponseDelay;
  private AtomicInteger heartbeatCount = new AtomicInteger(0);
  private AtomicInteger rpcCount = new AtomicInteger(0);
  private AtomicInteger containerReportsCount = new AtomicInteger(0);
  private String clusterId;
  private String scmId;

  public ScmTestMock() {
    clusterId = UUID.randomUUID().toString();
    scmId = UUID.randomUUID().toString();
  }

  // Map of datanode to containers
  private Map<DatanodeDetails, Map<String, ContainerInfo>> nodeContainers =
      new HashMap();
  private Map<DatanodeDetails, NodeReportProto> nodeReports = new HashMap<>();
  private AtomicInteger commandStatusReport = new AtomicInteger(0);
  private List<CommandStatus> cmdStatusList = new LinkedList<>();
  private List<SCMCommandProto> scmCommandRequests = new LinkedList<>();
  /**
   * Returns the number of heartbeats made to this class.
   *
   * @return int
   */
  public int getHeartbeatCount() {
    return heartbeatCount.get();
  }

  /**
   * Returns the number of RPC calls made to this mock class instance.
   *
   * @return - Number of RPC calls serviced by this class.
   */
  public int getRpcCount() {
    return rpcCount.get();
  }

  /**
   * Gets the RPC response delay.
   *
   * @return delay in milliseconds.
   */
  public int getRpcResponseDelay() {
    return rpcResponseDelay;
  }

  /**
   * Sets the RPC response delay.
   *
   * @param rpcResponseDelay - delay in milliseconds.
   */
  public void setRpcResponseDelay(int rpcResponseDelay) {
    this.rpcResponseDelay = rpcResponseDelay;
  }

  /**
   * Returns the number of container reports server has seen.
   * @return int
   */
  public int getContainerReportsCount() {
    return containerReportsCount.get();
  }

  /**
   * Returns the number of containers that have been reported so far.
   * @return - count of reported containers.
   */
  public long getContainerCount() {
    return nodeContainers.values().parallelStream().mapToLong((containerMap)->{
      return containerMap.size();
    }).sum();
  }

  /**
   * Get the number keys reported from container reports.
   * @return - number of keys reported.
   */
  public long getKeyCount() {
    return nodeContainers.values().parallelStream().mapToLong((containerMap)->{
      return containerMap.values().parallelStream().mapToLong((container) -> {
        return container.getKeyCount();
      }).sum();
    }).sum();
  }

  /**
   * Get the number of bytes used from container reports.
   * @return - number of bytes used.
   */
  public long getBytesUsed() {
    return nodeContainers.values().parallelStream().mapToLong((containerMap)->{
      return containerMap.values().parallelStream().mapToLong((container) -> {
        return container.getUsed();
      }).sum();
    }).sum();
  }

  /**
   * Returns SCM version.
   *
   * @return Version info.
   */
  @Override
  public StorageContainerDatanodeProtocolProtos.SCMVersionResponseProto
      getVersion(StorageContainerDatanodeProtocolProtos
      .SCMVersionRequestProto unused) throws IOException {
    rpcCount.incrementAndGet();
    sleepIfNeeded();
    VersionInfo versionInfo = VersionInfo.getLatestVersion();
    return VersionResponse.newBuilder()
        .setVersion(versionInfo.getVersion())
        .addValue(VersionInfo.DESCRIPTION_KEY, versionInfo.getDescription())
        .addValue(OzoneConsts.SCM_ID, scmId)
        .addValue(OzoneConsts.CLUSTER_ID, clusterId)
        .build().getProtobufMessage();

  }

  private void sleepIfNeeded() {
    if (getRpcResponseDelay() > 0) {
      try {
        Thread.sleep(getRpcResponseDelay());
      } catch (InterruptedException ex) {
        // Just ignore this exception.
      }
    }
  }

  /**
   * Used by data node to send a Heartbeat.
   *
   * @param heartbeat - node heartbeat.
   * @return - SCMHeartbeatResponseProto
   * @throws IOException
   */
  @Override
  public StorageContainerDatanodeProtocolProtos.SCMHeartbeatResponseProto
      sendHeartbeat(SCMHeartbeatRequestProto heartbeat) throws IOException {
    rpcCount.incrementAndGet();
    heartbeatCount.incrementAndGet();
    if(heartbeat.hasCommandStatusReport()){
      cmdStatusList.addAll(heartbeat.getCommandStatusReport()
          .getCmdStatusList());
      commandStatusReport.incrementAndGet();
    }
    sleepIfNeeded();
    return SCMHeartbeatResponseProto.newBuilder().addAllCommands(
        scmCommandRequests)
        .setDatanodeUUID(heartbeat.getDatanodeDetails().getUuid())
        .build();
  }

  /**
   * Register Datanode.
   *
   * @param datanodeDetailsProto DatanodDetailsProto.
   * @return SCM Command.
   */
  @Override
  public StorageContainerDatanodeProtocolProtos
      .SCMRegisteredResponseProto register(
          DatanodeDetailsProto datanodeDetailsProto, NodeReportProto nodeReport,
          StorageContainerDatanodeProtocolProtos.ContainerReportsProto
              containerReportsRequestProto)
      throws IOException {
    rpcCount.incrementAndGet();
    updateNodeReport(datanodeDetailsProto, nodeReport);
    updateContainerReport(containerReportsRequestProto, datanodeDetailsProto);
    sleepIfNeeded();
    return StorageContainerDatanodeProtocolProtos.SCMRegisteredResponseProto
        .newBuilder().setClusterID(UUID.randomUUID().toString())
        .setDatanodeUUID(datanodeDetailsProto.getUuid()).setErrorCode(
            StorageContainerDatanodeProtocolProtos
                .SCMRegisteredResponseProto.ErrorCode.success).build();
  }

  /**
   * Update nodeReport.
   * @param datanodeDetailsProto
   * @param nodeReport
   */
  public void updateNodeReport(DatanodeDetailsProto datanodeDetailsProto,
      NodeReportProto nodeReport) {
    DatanodeDetails datanode = DatanodeDetails.getFromProtoBuf(
        datanodeDetailsProto);
    NodeReportProto.Builder nodeReportProto = NodeReportProto.newBuilder();

    List<StorageReportProto> storageReports =
        nodeReport.getStorageReportList();

    for(StorageReportProto report : storageReports) {
      nodeReportProto.addStorageReport(report);
    }

    nodeReports.put(datanode, nodeReportProto.build());

  }

  /**
   * Update the cotainerReport.
   *
   * @param reports Container report
   * @param datanodeDetails DataNode Info
   * @throws IOException
   */
  public void updateContainerReport(
      StorageContainerDatanodeProtocolProtos.ContainerReportsProto reports,
      DatanodeDetailsProto datanodeDetails) throws IOException {
    Preconditions.checkNotNull(reports);
    containerReportsCount.incrementAndGet();
    DatanodeDetails datanode = DatanodeDetails.getFromProtoBuf(
        datanodeDetails);
    if (reports.getReportsCount() > 0) {
      Map containers = nodeContainers.get(datanode);
      if (containers == null) {
        containers = new LinkedHashMap();
        nodeContainers.put(datanode, containers);
      }

      for (StorageContainerDatanodeProtocolProtos.ContainerInfo report : reports
          .getReportsList()) {
        containers.put(report.getContainerID(), report);
      }
    }
  }

  /**
   * Return the number of StorageReports of a datanode.
   * @param datanodeDetails
   * @return count of containers of a datanode
   */
  public int getNodeReportsCount(DatanodeDetails datanodeDetails) {
    return nodeReports.get(datanodeDetails).getStorageReportCount();
  }

  /**
   * Returns the number of containers of a datanode.
   * @param datanodeDetails
   * @return count of storage reports of a datanode
   */
  public int getContainerCountsForDatanode(DatanodeDetails datanodeDetails) {
    Map<String, ContainerInfo> cr = nodeContainers.get(datanodeDetails);
    if(cr != null) {
      return cr.size();
    }
    return 0;
  }

  @Override
  public ContainerBlocksDeletionACKResponseProto sendContainerBlocksDeletionACK(
      ContainerBlocksDeletionACKProto request) throws IOException {
    return ContainerBlocksDeletionACKResponseProto
        .newBuilder().getDefaultInstanceForType();
  }

  /**
   * Reset the mock Scm for test to get a fresh start without rebuild MockScm.
   */
  public void reset() {
    heartbeatCount.set(0);
    rpcCount.set(0);
    containerReportsCount.set(0);
    nodeContainers.clear();

  }

  public int getCommandStatusReportCount() {
    return commandStatusReport.get();
  }

  public List<CommandStatus> getCmdStatusList() {
    return cmdStatusList;
  }

  public List<SCMCommandProto> getScmCommandRequests() {
    return scmCommandRequests;
  }

  public void clearScmCommandRequests() {
    scmCommandRequests.clear();
  }

  public void addScmCommandRequest(SCMCommandProto scmCmd) {
    scmCommandRequests.add(scmCmd);
  }

  /**
   * Set scmId.
   * @param id
   */
  public void setScmId(String id) {
    this.scmId = id;
  }

  /**
   * Set scmId.
   * @return scmId
   */
  public String getScmId() {
    return scmId;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.intel.hadoop.graphbuilder.partition.mapreduce.keyvalue
</TITLE>

<META NAME="date" CONTENT="2012-11-08">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.intel.hadoop.graphbuilder.partition.mapreduce.keyvalue

Class Summary

CombinedEdgeValueType<VidType extends WritableComparable<VidType>,VertexData extends Writable,EdgeData extends Writable>
Intermediate value type of edge records and supports commutative and
 associative add operation to merge with instances of the same type.

CombinedVrecordValueType<VidType extends WritableComparable<VidType>,VertexData extends Writable,EdgeData extends Writable>
Intermediate value type of vertex records and supports commutative and
 associative add operation through additvity of inEdges, outEdges and union of
 the mirror set.

GraphTypeFactory<VidType extends WritableComparable<VidType>,VertexData extends Writable,EdgeData extends Writable>

IngressJobKeyValueFactory

IngressKeyType<VidType extends WritableComparable<VidType>>
Abstract MapKey for edge ingress templated with VidType.

IngressValueType<VidType extends WritableComparable<VidType>,VertexData extends Writable,EdgeData extends Writable>
An abstract class for map value templated with VidType, VertexData, and
 EdgeData.

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
package cgroups

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	specs "github.com/opencontainers/runtime-spec/specs-go"
)

func NewHugetlb(root string) (*hugetlbController, error) {
	sizes, err := hugePageSizes()
	if err != nil {
		return nil, err
	}

	return &hugetlbController{
		root:  filepath.Join(root, string(Hugetlb)),
		sizes: sizes,
	}, nil
}

type hugetlbController struct {
	root  string
	sizes []string
}

func (h *hugetlbController) Name() Name {
	return Hugetlb
}

func (h *hugetlbController) Path(path string) string {
	return filepath.Join(h.root, path)
}

func (h *hugetlbController) Create(path string, resources *specs.LinuxResources) error {
	if err := os.MkdirAll(h.Path(path), defaultDirPerm); err != nil {
		return err
	}
	for _, limit := range resources.HugepageLimits {
		if err := ioutil.WriteFile(
			filepath.Join(h.Path(path), strings.Join([]string{"hugetlb", limit.Pagesize, "limit_in_bytes"}, ".")),
			[]byte(strconv.FormatUint(limit.Limit, 10)),
			defaultFilePerm,
		); err != nil {
			return err
		}
	}
	return nil
}

func (h *hugetlbController) Stat(path string, stats *Stats) error {
	stats.Hugetlb = make(map[string]HugetlbStat)
	for _, size := range h.sizes {
		s, err := h.readSizeStat(path, size)
		if err != nil {
			return err
		}
		stats.Hugetlb[size] = s
	}
	return nil
}

func (h *hugetlbController) readSizeStat(path, size string) (HugetlbStat, error) {
	var s HugetlbStat
	for _, t := range []struct {
		name  string
		value *uint64
	}{
		{
			name:  "usage_in_bytes",
			value: &s.Usage,
		},
		{
			name:  "max_usage_in_bytes",
			value: &s.Max,
		},
		{
			name:  "failcnt",
			value: &s.Failcnt,
		},
	} {
		v, err := readUint(filepath.Join(h.Path(path), strings.Join([]string{"hugetlb", size, t.name}, ".")))
		if err != nil {
			return s, err
		}
		*t.value = v
	}
	return s, nil
}


text:
class CreateCourseTickets < ActiveRecord::Migration
  def change
    create_table :course_tickets do |t|
      t.string :name
      t.float :price
      t.string :description
      t.boolean :require_invoice
      t.integer :course_id

      t.timestamps
    end
    add_index :course_tickets, :course_id
    add_column :courses, :tickets_quantity, :integer
  end
end


text:
export CFLAGS="-I$PREFIX/include"
export LDFLAGS="-L$PREFIX/lib"
export CPATH=${PREFIX}/include

cd "$SRC_DIR"
autoreconf -i
./configure CPPFLAGS="-I${PREFIX}/include" LDFLAGS="-L${PREFIX}/lib" --prefix=$PREFIX
make
make install -C src

for f in bamsort.sh moabs preprocess_novoalign.sh redepth.pl routines.pm template_for_cfg template_for_qsub
do
	cp "${SRC_DIR}/bin/$f" ${PREFIX}/bin
done
cp -R "${SRC_DIR}/bin/plib" ${PREFIX}/bin
cp "${SRC_DIR}/lib/samtools/samtools" ${PREFIX}/bin


text:
import datetime
import email.utils
import hashlib
import random
import time

import six
from six.moves.urllib import parse
from swiftclient import client as sc
from swiftclient import exceptions
from swiftclient import utils as swiftclient_utils

from heat.engine.clients import client_plugin

IN_PROGRESS = 'in progress'

MAX_EPOCH = 2147483647

CLIENT_NAME = 'swift'

class SwiftClientPlugin(client_plugin.ClientPlugin):

    exceptions_module = exceptions

    service_types = [OBJECT_STORE] = ['object-store']

    def _create(self):

        con = self.context
        endpoint_type = self._get_client_option(CLIENT_NAME, 'endpoint_type')
        args = {
            'auth_version': '2.0',
            'tenant_name': con.tenant,
            'user': con.username,
            'key': None,
            'authurl': None,
            'preauthtoken': self.auth_token,
            'preauthurl': self.url_for(service_type=self.OBJECT_STORE,
                                       endpoint_type=endpoint_type),
            'os_options': {'endpoint_type': endpoint_type},
            'cacert': self._get_client_option(CLIENT_NAME, 'ca_file'),
            'insecure': self._get_client_option(CLIENT_NAME, 'insecure')
        }
        return sc.Connection(**args)

    def is_client_exception(self, ex):
        return isinstance(ex, exceptions.ClientException)

    def is_not_found(self, ex):
        return (isinstance(ex, exceptions.ClientException) and
                ex.http_status == 404)

    def is_over_limit(self, ex):
        return (isinstance(ex, exceptions.ClientException) and
                ex.http_status == 413)

    def is_conflict(self, ex):
        return (isinstance(ex, exceptions.ClientException) and
                ex.http_status == 409)

    def is_valid_temp_url_path(self, path):
        """Return True if path is a valid Swift TempURL path, False otherwise.

        A Swift TempURL path must:
        - Be five parts, ['', 'v1', 'account', 'container', 'object']
        - Be a v1 request
        - Have account, container, and object values
        - Have an object value with more than just '/'s

        :param path: The TempURL path
        :type path: string
        """
        parts = path.split('/', 4)
        return bool(len(parts) == 5 and
                    not parts[0] and
                    parts[1] == 'v1' and
                    parts[2].endswith(self.context.tenant_id) and
                    parts[3] and
                    parts[4].strip('/'))

    def get_temp_url(self, container_name, obj_name, timeout=None,
                     method='PUT'):
        """Return a Swift TempURL."""
        key_header = 'x-account-meta-temp-url-key'
        if key_header not in self.client().head_account():
            self.client().post_account({
                key_header: hashlib.sha224(
                    six.b(six.text_type(
                        random.getrandbits(256)))).hexdigest()[:32]})

        key = self.client().head_account()[key_header]

        path = '/v1/AUTH_%s/%s/%s' % (self.context.tenant_id, container_name,
                                      obj_name)
        if timeout is None:
            timeout = MAX_EPOCH - 60 - time.time()
        tempurl = swiftclient_utils.generate_temp_url(path, timeout, key,
                                                      method)
        sw_url = parse.urlparse(self.client().url)
        return '%s://%s%s' % (sw_url.scheme, sw_url.netloc, tempurl)

    def get_signal_url(self, container_name, obj_name, timeout=None):
        """Turn on object versioning.

        We can use a single TempURL for multiple signals and return a Swift
        TempURL.
        """
        self.client().put_container(
            container_name, headers={'x-versions-location': container_name})
        self.client().put_object(container_name, obj_name, IN_PROGRESS)

        return self.get_temp_url(container_name, obj_name, timeout)

    def parse_last_modified(self, lm):
        """Parses the last-modified value.

        For example, last-modified values from a swift object header.
        Returns the datetime.datetime of that value.

        :param lm: The last-modified value (or None)
        :type lm: string
        :returns: An offset-naive UTC datetime of the value (or None)
        """
        if not lm:
            return None
        pd = email.utils.parsedate(lm)[:6]
        # according to RFC 2616, all HTTP time headers must be
        # in GMT time, so create an offset-naive UTC datetime
        return datetime.datetime(*pd)


text:
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

require('redux');
require('./turn-order-9099d084.js');
require('immer');
require('lodash.isplainobject');
require('./reducer-0e2d2957.js');
require('rfc6902');
require('./initialize-662b4f1a.js');
require('./transport-b1874dfa.js');
require('./util-9da6d45a.js');
var socketio = require('./socketio-310dbf65.js');
require('./master-6515378c.js');
require('./filter-player-view-ba976da7.js');
require('socket.io-client');

exports.Local = socketio.Local;
exports.SocketIO = socketio.SocketIO;


text:
Repository for examples of the data analysis workflow at CSX.

## General Notebooks

* [Loading and Viewing FastCCD Images] (https://github.com/NSLS-II-CSX/csx-examples/blob/master/examples/general/Correct_FastCCD_Images.ipynb)
* [Single Photon Counting (Fe55)] (https://github.com/NSLS-II-CSX/csx-examples/blob/master/examples/general/Fe55_Single_Photon_Counting.ipynb)
* [Performance Tests] (https://github.com/NSLS-II-CSX/csx-examples/blob/master/examples/general/Performance_Tests.ipynb)

## XPCS Data Analysis

* [1-time correlation] (https://github.com/NSLS-II-CSX/csx-examples/blob/master/examples/xpcs/FastCCD_MultiTau_Example.ipynb)

## Reciprocal Space Conversion

* [Reciprocal Space Conversion] (https://github.com/NSLS-II-CSX/csx-examples/blob/master/examples/recip/Recip_Convversion_Gridding.ipynb)

License
-------
BSD (3-clause) License
See LICENSE for full text


text:
<?php

namespace Hmaus\Spas\Tests\Event;

use Hmaus\Spas\Event\AfterEach;
use Hmaus\Spas\Parser\SpasRequest;

class AfterEachTest extends \PHPUnit_Framework_TestCase
{
    public function testCanSetAndGetRequest()
    {
        $request = new SpasRequest();
        $event = new AfterEach($request);

        $this->assertSame($request, $event->getRequest());

        $event->setRequest($request);
        $this->assertSame($request, $event->getRequest());
    }
}


text:
title: Bulunduğunuz ağ'daki erişebileceğiniz makineler ve IP adresleri
date: Oct 1st, 2015 3:21:25pm
tags: osx
external_url: http://osx.gelistiriciyiz.biz/2015/10/01/bulundugunuz-agdaki-erisebileceginiz-makineler-ve-ip-adresleri/
---


text:
/**
 * Migration

UPDATE `scenarios`
SET `game_id` = 1
WHERE `scenarios`.`game` = 'pfs';

UPDATE `scenarios`
SET `game_id` = 2
WHERE `scenarios`.`game` = 'pfs2';

UPDATE `scenarios`
SET `game_id` = 3
WHERE `scenarios`.`game` = 'sfs';

// No need to migrate acg, no acg in before migration
 */

module.exports = function(sequelize, DataTypes) {
	var Scenario = sequelize.define('Scenario', {
		id: {
		  type: DataTypes.INTEGER(11),
		  allowNull: false,
		  primaryKey: true,
		  autoIncrement: true
		},
		name: {
		  type: DataTypes.STRING,
		  allowNull: false
		},
		description: {
		  type: DataTypes.TEXT,
		  allowNull: true
		},
		type: {
		  type: DataTypes.STRING,
		  allowNull: false,
		  defaultValue: 'scenario'
		},
		season: {
		  type: DataTypes.STRING,
		  allowNull: false,
		  defaultValue: '99'
		},
		number: {
		  type: DataTypes.STRING,
		  allowNull: true
		},
		tier: {
		  type: DataTypes.STRING,
		  allowNull: true
		},
		levelrange: {
		  type: DataTypes.STRING,
		  allowNull: false,
		  defaultValue: '01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20'
		},
		link: {
		  type: DataTypes.STRING,
		  allowNull: true
		},
		evergreen: {
		  type: DataTypes.BOOLEAN,
		  allowNull: true,
		  defaultValue: '0'
		},
		quest: {
			  type: DataTypes.BOOLEAN,
			  allowNull: true,
			  defaultValue: '0'
			},
		multitable: {
			  type: DataTypes.BOOLEAN,
			  allowNull: true,
			  defaultValue: '0'
			},
		archived_on: {
			type: DataTypes.DATE,
			allowNull: true
		}
	}, {
		tableName: 'scenarios'
	});

	Scenario.associate = function(models) {
		Scenario.belongsTo(models.Game, {as: 'game', foreignKey: 'game_id'})
		Scenario.belongsToMany(models.Author, {as: 'authors', foreignKey: 'scenario_id', through: 'j_author_scenario'});
		Scenario.hasMany(models.Statistic, {as: 'statistics', foreignKey: 'scenario_id'});
		Scenario.hasMany(models.Report, {as: 'reports', foreignKey: 'scenario_id'});
		Scenario.belongsToMany(models.Person, {as: 'players', foreignKey: 'scenario_id', through: models.Report});
	}

	// http://stackoverflow.com/questions/27972271/sequelize-dont-return-password
	// prevent the API from ever returning the deleted values
	Scenario.prototype.toJSON = function() {
		var values = this.get();

		delete values.created_on;
		delete values.updated_on;
		delete values.deleted_on;

		return values;
	}

	return Scenario;
};


text:
void reboot();
void halt();
extern void hlt();

extern unsigned char _KERNEL_START_[];
extern unsigned char _KERNEL_END_[];
extern unsigned char _TEXT_START_[];
extern unsigned char _TEXT_END_[];
extern unsigned char _RODATA_START_[];
extern unsigned char _RODATA_END_[];
extern unsigned char _DATA_START_[];
extern unsigned char _DATA_END_[];
extern unsigned char _BSS_START_[];
extern unsigned char _BSS_END_[];

#define KERNEL_BASE_ADDR    0xC0000000

extern unsigned char initial_kernel_stack[4096];


text:
<?php

namespace PHPExiftool\Driver\Tag\SigmaRaw;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class WhiteBalance extends AbstractTag
{

    protected $Id = 'mixed';

    protected $Name = 'WhiteBalance';

    protected $FullName = 'mixed';

    protected $GroupName = 'SigmaRaw';

    protected $g0 = 'SigmaRaw';

    protected $g1 = 'SigmaRaw';

    protected $g2 = 'mixed';

    protected $Type = 'mixed';

    protected $Writable = false;

    protected $Description = 'White Balance';

    protected $MaxLength = 32;
}


text:
from flask import Blueprint

customer = Blueprint('customer', __name__)

from . import views


text:
package com.kleen.selector;

/**
 * Object contains regex results.

 * For multi group result extension.

 *
 * @author kleen888@gmail.com

 * @since 0.1.0
 */
class RegexResult {

    private String[] groups;

    public static final RegexResult EMPTY_RESULT = new RegexResult();

    public RegexResult() {

    }

    public RegexResult(String[] groups) {
        this.groups = groups;
    }

    public String get(int groupId) {
        if (groups == null) {
            return null;
        }
        return groups[groupId];
    }

}


text:
Additional header content

Specifies mini-chart empty values

**Namespace:** iTin.Export.Model
**Assembly:** iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0)

## Syntax

**C#**

``` C#
[SerializableAttribute]
public enum MiniChartEmptyValuesAs
```

**VB**

``` VB
<SerializableAttribute>
Public Enumeration MiniChartEmptyValuesAs
```

## Members

	Member name	Value	Description

**Gap**	0

**Zero**	1

**Connect**	2

## Remarks
\[Missing <remarks> documentation for "T:iTin.Export.Model.MiniChartEmptyValuesAs"\]

## See Also

#### Reference
iTin.Export.Model Namespace


text:
package register

import (
	// register the zfs driver
	_ "github.com/containers/storage/drivers/zfs"
)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Primo Capelo</logradouro><bairro>Centro</bairro><cidade>Itajubá</cidade><uf>MG</uf><cep>37500062</cep></feed>


text:
"use strict";

/**
 * Representation a of zip file in js
 * @constructor
 */
function JSZip() {
    // if this constructor is used without `new`, it adds `new` before itself:
    if(!(this instanceof JSZip)) {
        return new JSZip();
    }

    if(arguments.length) {
        throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
    }

    // object containing the files :
    // {
    //   "folder/" : {...},
    //   "folder/data.txt" : {...}
    // }
    // NOTE: we use a null prototype because we do not
    // want filenames like "toString" coming from a zip file
    // to overwrite methods and attributes in a normal Object.
    this.files = Object.create(null);

    this.comment = null;

    // Where we are in the hierarchy
    this.root = "";
    this.clone = function() {
        var newObj = new JSZip();
        for (var i in this) {
            if (typeof this[i] !== "function") {
                newObj[i] = this[i];
            }
        }
        return newObj;
    };
}
JSZip.prototype = require("./object");
JSZip.prototype.loadAsync = require("./load");
JSZip.support = require("./support");
JSZip.defaults = require("./defaults");

// TODO find a better way to handle this version,
// a require('package.json').version doesn't work with webpack, see #327
JSZip.version = "3.10.1";

JSZip.loadAsync = function (content, options) {
    return new JSZip().loadAsync(content, options);
};

JSZip.external = require("./external");
module.exports = JSZip;


text:
{{type}} in {{city}}

{{title}}

 {{type}}

 {{cost}}/month

 Available:

{{availability}}

      Go to listing
      Some Details

Bedrooms: {{bed}}

Bathrooms: {{bath}}


text:
from django.contrib import admin

from .models import Route, Waypoint

class WaypointInlines(admin.TabularInline):
    model = Waypoint
    extra = 1

class RouteAdmin(admin.ModelAdmin):
    field = ['description','title']
    search_fields = ['title','description']
    inlines = [WaypointInlines]

class WaypointAdmin(admin.ModelAdmin):
    search_fields = ['title','description']

admin.site.register(Route, RouteAdmin)
admin.site.register(Waypoint, WaypointAdmin)


text:
using Awful.Parser.Models.PostIcons;
using System;
using System.Collections.Generic;
using System.Text;

namespace Awful.Parser.Models.Messages
{
    public class NewPrivateMessage
    {
        public PostIcon Icon { get; set; }

        public string Title { get; set; }

        public string Receiver { get; set; }

        public string Body { get; set; }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.kit.dama.transfer.client.types;

/**
 *
 * @author jejkal
 */
public enum IngestStatusEnum {

    INGEST_RUNNING, INGEST_PAUSED, INGEST_ABORTED, INGEST_FINISHED;
}


text:
shared_context 'pages support' do
  let!(:page_owner) {
    user = FactoryGirl.create(:user)
    user.wildcard_permit! 'public', 'Page'
    user
  }
  let!(:page_follower) { FactoryGirl.create(:user) }
  let!(:page_stranger) { FactoryGirl.create(:user) }
  let!(:page_viewer) { FactoryGirl.create(:user) }
  let!(:private_page_owner) { FactoryGirl.create(:user) }

  let!(:root_parent_page) { FactoryGirl.create(:page, :title => 'Parent') }
  let!(:root_child_page) { FactoryGirl.create(:page, :title => 'Child', :parent => root_parent_page) }
  let!(:root_grandchild_page) { FactoryGirl.create(:page, :title => 'Grandchild', :parent => root_child_page) }

  let!(:owned_parent_page) { FactoryGirl.create(:page, :title => 'Parent', :pageable => page_owner) }
  let!(:owned_child_page) { FactoryGirl.create(:page, :title => 'Child', :pageable => page_owner, :parent => owned_parent_page) }
  let!(:owned_grandchild_page) { FactoryGirl.create(:page, :title => 'Grandchild', :pageable => page_owner, :parent => owned_child_page) }

  let!(:private_home_page) { FactoryGirl.create(:page, :title => 'Home', :pageable => private_page_owner) }
  let!(:private_inner_page) { FactoryGirl.create(:page, :title => 'Inner', :pageable => private_page_owner, :parent => private_home_page) }

  before do
    ChalkDust.subscribe(page_follower, :to => page_owner)
    ChalkDust.subscribe(private_page_owner, :to => page_viewer)
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Telopea 8:22. 1998

#### Original name
Leptocarpus similis Edgar

### Remarks
null


text:
===========================================
Mixpanel Settings: mixpanel - mixpanel.conf
===========================================

.. currentmodule:: mixpanel.conf

.. automodule:: mixpanel.conf
    :members:


text:
package org.onosproject.rest.resources;

import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import org.hamcrest.Description;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Test;
import org.onlab.osgi.ServiceDirectory;
import org.onlab.osgi.TestServiceDirectory;
import org.onosproject.codec.CodecService;
import org.onosproject.codec.impl.CodecManager;
import org.onosproject.net.key.DeviceKey;
import org.onosproject.net.key.DeviceKeyAdminService;
import org.onosproject.net.key.DeviceKeyId;
import org.onosproject.net.key.DeviceKeyService;

import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashSet;

import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/**
 * Unit tests for device key REST APIs.
 */
public class DeviceKeyWebResourceTest extends ResourceTest {

    final DeviceKeyService mockDeviceKeyService = createMock(DeviceKeyService.class);
    final DeviceKeyAdminService mockDeviceKeyAdminService = createMock(DeviceKeyAdminService.class);

    final HashSet<DeviceKey> deviceKeySet = new HashSet<>();

    private static final String ID = "id";
    private static final String TYPE = "type";
    private static final String LABEL = "label";
    private static final String COMMUNITY_NAME = "community_name";
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";

    private final String deviceKeyId1 = "DeviceKeyId1";
    private final String deviceKeyId2 = "DeviceKeyId2";
    private final String deviceKeyId3 = "DeviceKeyId3";
    private final String deviceKeyId4 = "DeviceKeyId4";
    private final String deviceKeyLabel = "DeviceKeyLabel";
    private final String deviceKeyCommunityName = "DeviceKeyCommunityName";
    private final String deviceKeyUsername = "DeviceKeyUsername";
    private final String deviceKeyPassword = "DeviceKeyPassword";

    private final DeviceKey deviceKey1 = DeviceKey.createDeviceKeyUsingCommunityName(
            DeviceKeyId.deviceKeyId(deviceKeyId1), deviceKeyLabel, deviceKeyCommunityName);
    private final DeviceKey deviceKey2 = DeviceKey.createDeviceKeyUsingUsernamePassword(
            DeviceKeyId.deviceKeyId(deviceKeyId2), null, deviceKeyUsername, deviceKeyPassword);
    private final DeviceKey deviceKey3 = DeviceKey.createDeviceKeyUsingUsernamePassword(
            DeviceKeyId.deviceKeyId(deviceKeyId3), null, null, null);
    private final DeviceKey deviceKey4 = DeviceKey.createDeviceKeyUsingCommunityName(
            DeviceKeyId.deviceKeyId(deviceKeyId4), null, null);

    /**
     * Initializes test mocks and environment.
     */
    @Before
    public void setUpMocks() {
        expect(mockDeviceKeyService.getDeviceKeys()).andReturn(deviceKeySet).anyTimes();

        // Register the services needed for the test
        CodecManager codecService = new CodecManager();
        codecService.activate();
        ServiceDirectory testDirectory =
                new TestServiceDirectory()
                        .add(DeviceKeyService.class, mockDeviceKeyService)
                        .add(DeviceKeyAdminService.class, mockDeviceKeyAdminService)
                        .add(CodecService.class, codecService);

        setServiceDirectory(testDirectory);
    }

    /**
     * Hamcrest matcher to check that a device key representation in JSON matches
     * the actual device key.
     */
    public static class DeviceKeyJsonMatcher extends TypeSafeMatcher<JsonObject> {
        private final DeviceKey deviceKey;
        private String reason = "";

        public DeviceKeyJsonMatcher(DeviceKey deviceKeyValue) {
            deviceKey = deviceKeyValue;
        }

        @Override
        public boolean matchesSafely(JsonObject jsonHost) {
            // Check the device key id
            final String jsonId = jsonHost.get(ID).asString();
            if (!jsonId.equals(deviceKey.deviceKeyId().id().toString())) {
                reason = ID + " " + deviceKey.deviceKeyId().id().toString();
                return false;
            }

            // Check the device key label
            final String jsonLabel = (jsonHost.get(LABEL).isNull()) ? null : jsonHost.get(LABEL).asString();
            if (deviceKey.label() != null) {
                if ((jsonLabel == null) || !jsonLabel.equals(deviceKey.label())) {
                    reason = LABEL + " " + deviceKey.label();
                    return false;
                }
            }

            // Check the device key type
            final String jsonType = jsonHost.get(TYPE).asString();
            if (!jsonType.equals(deviceKey.type().toString())) {
                reason = TYPE + " " + deviceKey.type().toString();
                return false;
            }

            if (jsonType.equals(DeviceKey.Type.COMMUNITY_NAME.toString())) {
                // Check the device key community name
                final String jsonCommunityName = jsonHost.get(COMMUNITY_NAME).isNull() ?
                        null : jsonHost.get(COMMUNITY_NAME).asString();
                if (deviceKey.asCommunityName().name() != null) {
                    if (!jsonCommunityName.equals(deviceKey.asCommunityName().name().toString())) {
                        reason = COMMUNITY_NAME + " " + deviceKey.asCommunityName().name().toString();
                        return false;
                    }
                }
            } else if (jsonType.equals(DeviceKey.Type.USERNAME_PASSWORD.toString())) {
                // Check the device key username
                final String jsonUsername = jsonHost.get(USERNAME).isNull() ?
                        null : jsonHost.get(USERNAME).asString();
                if (deviceKey.asUsernamePassword().username() != null) {
                    if (!jsonUsername.equals(deviceKey.asUsernamePassword().username().toString())) {
                        reason = USERNAME + " " + deviceKey.asUsernamePassword().username().toString();
                        return false;
                    }
                }

                // Check the device key password
                final String jsonPassword = jsonHost.get(PASSWORD).isNull() ?
                        null : jsonHost.get(PASSWORD).asString();
                if (deviceKey.asUsernamePassword().password() != null) {
                    if (!jsonPassword.equals(deviceKey.asUsernamePassword().password().toString())) {
                        reason = PASSWORD + " " + deviceKey.asUsernamePassword().password().toString();
                        return false;
                    }
                }
            } else {
                reason = "Unknown " + TYPE + " " + deviceKey.type().toString();
                return false;
            }

            return true;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(reason);
        }
    }

    /**
     * Factory to allocate a device key array matcher.
     *
     * @param deviceKey device key object we are looking for
     * @return matcher
     */
    private static DeviceKeyJsonMatcher matchesDeviceKey(DeviceKey deviceKey) {
        return new DeviceKeyJsonMatcher(deviceKey);
    }

    /**
     * Hamcrest matcher to check that a device key is represented properly in a JSON
     * array of device keys.
     */
    public static class DeviceKeyJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
        private final DeviceKey deviceKey;
        private String reason = "";

        public DeviceKeyJsonArrayMatcher(DeviceKey deviceKeyValue) {
            deviceKey = deviceKeyValue;
        }

        @Override
        public boolean matchesSafely(JsonArray json) {
            boolean deviceKeyFound = false;
            final int expectedAttributes = 5;
            for (int jsonDeviceKeyIndex = 0; jsonDeviceKeyIndex < json.size();
                 jsonDeviceKeyIndex++) {

                final JsonObject jsonHost = json.get(jsonDeviceKeyIndex).asObject();

                // Device keys can have a variable number of attribute so we check
                // that there is a minimum number.
                if (jsonHost.names().size() < expectedAttributes) {
                    reason = "Found a device key with the wrong number of attributes";
                    return false;
                }

                final String jsonDeviceKeyId = jsonHost.get(ID).asString();
                if (jsonDeviceKeyId.equals(deviceKey.deviceKeyId().id().toString())) {
                    deviceKeyFound = true;

                    //  We found the correct device key, check the device key attribute values
                    assertThat(jsonHost, matchesDeviceKey(deviceKey));
                }
            }
            if (!deviceKeyFound) {
                reason = "Device key with id " + deviceKey.deviceKeyId().id().toString() + " was not found";
                return false;
            } else {
                return true;
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(reason);
        }
    }

    /**
     * Factory to allocate a device key array matcher.
     *
     * @param deviceKey device key object we are looking for
     * @return matcher
     */
    private static DeviceKeyJsonArrayMatcher hasDeviceKey(DeviceKey deviceKey) {
        return new DeviceKeyJsonArrayMatcher(deviceKey);
    }

    /**
     * Tests the result of the REST API GET when there are no device keys.
     */
    @Test
    public void testGetDeviceKeysEmptyArray() {
        replay(mockDeviceKeyService);

        WebTarget wt = target();
        String response = wt.path("keys").request().get(String.class);
        assertThat(response, is("{\"keys\":[]}"));

        verify(mockDeviceKeyService);
    }

    /**
     * Tests the result of the REST API GET when device keys are defined.
     */
    @Test
    public void testGetDeviceKeysArray() {
        replay(mockDeviceKeyService);
        deviceKeySet.add(deviceKey1);
        deviceKeySet.add(deviceKey2);
        deviceKeySet.add(deviceKey3);
        deviceKeySet.add(deviceKey4);

        WebTarget wt = target();
        String response = wt.path("keys").request().get(String.class);
        assertThat(response, containsString("{\"keys\":["));

        final JsonObject result = Json.parse(response).asObject();
        assertThat(result, notNullValue());

        assertThat(result.names(), hasSize(1));
        assertThat(result.names().get(0), is("keys"));

        final JsonArray deviceKeys = result.get("keys").asArray();
        assertThat(deviceKeys, notNullValue());
        assertEquals("Device keys array is not the correct size.", 4, deviceKeys.size());

        assertThat(deviceKeys, hasDeviceKey(deviceKey1));
        assertThat(deviceKeys, hasDeviceKey(deviceKey2));
        assertThat(deviceKeys, hasDeviceKey(deviceKey3));
        assertThat(deviceKeys, hasDeviceKey(deviceKey4));

        verify(mockDeviceKeyService);
    }

    /**
     * Tests the result of the REST API GET using a device key identifier.
     */
    @Test
    public void testGetDeviceKeyById() {
        deviceKeySet.add(deviceKey1);

        expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId1)))
                .andReturn(deviceKey1)
                .anyTimes();
        replay(mockDeviceKeyService);

        WebTarget wt = target();
        String response = wt.path("keys/" + deviceKeyId1).request().get(String.class);
        final JsonObject result = Json.parse(response).asObject();
        assertThat(result, notNullValue());

        assertThat(result, matchesDeviceKey(deviceKey1));

        verify(mockDeviceKeyService);
    }

    /**
     * Tests that a GET of a non-existent object throws an exception.
     */
    @Test
    public void testGetNonExistentDeviceKey() {

        expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId1)))
                .andReturn(null)
                .anyTimes();
        replay(mockDeviceKeyService);

        WebTarget wt = target();
        try {
            wt.path("keys/" + deviceKeyId1).request().get(String.class);
            fail("GET of a non-existent device key did not throw an exception");
        } catch (NotFoundException ex) {
            assertThat(ex.getMessage(), containsString("HTTP 404 Not Found"));
        }

        verify(mockDeviceKeyService);
    }

    /**
     * Tests adding of new device key using POST via JSON stream.
     */
    @Test
    public void testPost() {

        mockDeviceKeyAdminService.addKey(anyObject());
        expectLastCall();

        replay(mockDeviceKeyAdminService);

        WebTarget wt = target();
        InputStream jsonStream = DeviceKeyWebResourceTest.class
                .getResourceAsStream("post-device-key.json");

        Response response = wt.path("keys").request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.json(jsonStream));
        assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));

        String location = response.getLocation().getPath();
        assertThat(location, Matchers.startsWith("/keys/" + deviceKeyId3));

        verify(mockDeviceKeyAdminService);
    }

    /**
     * Tests adding of a null device key using POST via JSON stream.
     */
    @Test
    public void testPostNullDeviceKey() {

        replay(mockDeviceKeyAdminService);

        WebTarget wt = target();
        try {
            wt.path("keys").request(MediaType.APPLICATION_JSON_TYPE)
                    .post(Entity.json(null), String.class);
            fail("POST of null device key did not throw an exception");
        } catch (BadRequestException ex) {
            assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request"));
        }

        verify(mockDeviceKeyAdminService);
    }

    /**
     * Tests removing a device key with DELETE request.
     */
    @Test
    public void testDelete() {
        expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId2)))
                .andReturn(deviceKey2)
                .anyTimes();
        mockDeviceKeyAdminService.removeKey(anyObject());
        expectLastCall();

        replay(mockDeviceKeyService);
        replay(mockDeviceKeyAdminService);

        WebTarget wt = target();

        Response response = wt.path("keys/" + deviceKeyId2)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .delete();
        assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK));

        verify(mockDeviceKeyService);
        verify(mockDeviceKeyAdminService);
    }

    /**
     * Tests that a DELETE of a non-existent device key throws an exception.
     */
    @Test
    public void testDeleteNonExistentDeviceKey() {
        expect(mockDeviceKeyService.getDeviceKey(anyObject()))
                .andReturn(null)
                .anyTimes();

        expectLastCall();

        replay(mockDeviceKeyService);
        replay(mockDeviceKeyAdminService);

        WebTarget wt = target();

        try {
            wt.path("keys/" + "NON_EXISTENT_DEVICE_KEY").request()
                    .delete(String.class);
            fail("Delete of a non-existent device key did not throw an exception");
        } catch (NotFoundException ex) {
            assertThat(ex.getMessage(), containsString("HTTP 404 Not Found"));
        }

        verify(mockDeviceKeyService);
        verify(mockDeviceKeyAdminService);
    }
}


text:
/*
  This is an example file shipped by 'Aleph - A Library for Exploring
  Persistent Homology'.

  This example demonstrates how to obtain a Vietoris--Rips complex
  from an unstructured point cloud (using Euclidean distances) and
  calculate its persistent homology.

  Demonstrated classes:

    - aleph::PersistenceDiagram
    - aleph::containers::PointCloud
    - aleph::geometry::FLANN
    - aleph::geometry::BruteForce

  Demonstrated functions:

    - aleph::geometry::buildVietorisRipsComplex
    - aleph::calculatePersistenceDiagrams
    - aleph::utilities::convert

  Original author: Bastian Rieck
*/

#include <aleph/config/FLANN.hh>

#include <aleph/containers/PointCloud.hh>

#include <aleph/geometry/BruteForce.hh>
#include <aleph/geometry/FLANN.hh>
#include <aleph/geometry/VietorisRipsComplex.hh>

#include <aleph/geometry/distances/Euclidean.hh>

#include <aleph/utilities/String.hh>

#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <iostream>
#include <string>
#include <vector>

#include <getopt.h>

void usage()
{
  std::cerr << "Usage: vietoris_rips FILE EPSILON [DIMENSION]\n"
            << "\n"
            << "Calculates the Vietoris--Rips complex of an unstructured point\n"
            << "cloud, stored in FILE. Euclidean distances are used during the\n"
            << "expansion process. The maximum distance threshold is specified\n"
            << "by EPSILON. If present, an optional parameter DIMENSION may be\n"
            << "used to truncate the simplicial complex.\n"
            << "\n";
}

int main( int argc, char** argv )
{
  if( argc <= 2 )
  {
    usage();
    return -1;
  }

  bool normalize = false;

  {
    static option commandLineOptions[] =
    {
      { "normalize", no_argument, nullptr, 'n' },
      { nullptr    , 0          , nullptr,  0  }
    };

    int option = 0;
    while( ( option = getopt_long( argc, argv, "n", commandLineOptions, nullptr ) ) != -1 )
    {
      switch( option )
      {
      case 'n':
        normalize = true;
        break;

      default:
        break;
      }
    }
  }

  // We first have to specify the data type to use for the subsequent
  // expansion of the Vietoris--Rips complex. This also results in
  // a different choice of point clouds.
  //
  // Moreover, we specify a distance functor to use for the subsequent
  // expansion process.
  //
  // For educational purposes, we use the full namespace here.
  using DataType   = double;
  using PointCloud = aleph::containers::PointCloud<DataType>;
  using Distance   = aleph::geometry::distances::Euclidean<DataType>;

  std::string input = argv[optind++];

  PointCloud pointCloud;

  if( input == "-" )
    pointCloud = aleph::containers::load<DataType>( std::cin );
  else
  {
    // This loads the point cloud from an unstructured file. The point
    // cloud loader is smart enough to handle things such as different
    // separators in a file.
    pointCloud = aleph::containers::load<DataType>( input );
  }

  auto dimension = pointCloud.dimension() + 1;

  // This converts the string supplied by the user to the corresponding
  // data type. Note that the `convert()` function only makes sense for
  // builtin types such as 'double' or 'float'. If you want to use this
  // for your own data types, you need to overload `operator>>` because
  // the converter internally uses `std::stringstream` for tokens.
  auto epsilon = aleph::utilities::convert<DataType>( argv[optind++] );

  if( (argc - optind) > 0 )
    dimension = std::stoul( argv[optind++] );

  std::cerr << "* Calculating Vietoris--Rips complex with eps=" << epsilon << " and d=" << dimension << "...";

  // Aleph gives you some options for detecting optional features such
  // as the wrapper for neighbourhood calculations. I would recommend
  // using the FLANN wrapper. It uses kd-trees, is reasonably fast in
  // higher dimensions and well tested.
  //
  // If this wrapper is not available, we fall back to the brute force
  // wrapper, which---you guessed it---enumerates all neighbours by,
  // well, brute force.
  //
  // If you want to write a wrapper for another library, take a look at
  // the interface of the FLANN wrapper.
  #ifdef ALEPH_WITH_FLANN
    aleph::geometry::FLANN<PointCloud, Distance> flannWrapper( pointCloud );

    // That's really all there is to is: the convenience function below
    // uses a neighbourhood wrapper and additional parameters and
    // creates an appropriate Vietoris--Rips complex.
    //
    // Since we did not specify anything else, the complex will contain
    // the high-dimensional distances as weights. The vertices of K are
    // assigned a value of 0, while the edges are assigned a value
    // according to the distance between their corresponding vertices.
    //
    // The simplicial complex is ordered according to this weight, from
    // low values to high values, resulting in a filtration of the
    // sublevel sets of the distance function.
    //
    // Other filtrations are possible but need to be applied manually
    // afterwards.
    auto K
      = aleph::geometry::buildVietorisRipsComplex( flannWrapper,
                                                   epsilon,
                                                   unsigned( dimension ) );
  #else
    aleph::geometry::BruteForce<PointCloud, Distance> bruteForceWrapper( pointCloud );

    auto K
      = aleph::geometry::buildVietorisRipsComplex( bruteForceWrapper,
                                                   epsilon,
                                                   unsigned( dimension ) );
  #endif

  std::cerr << "finished\n"
            << "* Obtained simplicial complex with " << K.size() << " simplices\n";

  std::cerr << "* Calculating persistence diagrams...";

  // Finally, this function will calculate all persistence diagrams of
  // the simplicial complex. Again, this is a convenience function which
  // assumes that the complex is already in filtration order.
  auto diagrams
    = aleph::calculatePersistenceDiagrams( K );

  std::cerr << "finished\n"
            << "* Obtained " << diagrams.size() << " persistence diagrams\n";

  DataType maxDistance = DataType();

  // Calculate maximum pairwise distance in the data set in order to
  // perform a proper normalisation.
  if( normalize )
  {
    for( std::size_t i = 0; i < pointCloud.size(); i++ )
    {
      auto&& p = pointCloud[i];

      for( std::size_t j = i + 1; j < pointCloud.size(); j++ )
      {
        auto&& q    = pointCloud[j];
        maxDistance = std::max( maxDistance, Distance()( p.begin(), q.begin(), pointCloud.dimension() ) );
      }
    }
  }

  using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;

  for( auto&& D : diagrams )
  {
    // Removes all features of zero persistence. They only clutter up
    // the diagonal.
    D.removeDiagonal();

    if( normalize )
    {
      std::transform( D.begin(), D.end(), D.begin(),
          [&maxDistance] ( const PersistenceDiagram::Point& p )
          {
            if( !std::isfinite( p.y() ) )
              return PersistenceDiagram::Point( p.x() / maxDistance, DataType(1) );
            else
              return PersistenceDiagram::Point( p.x() / maxDistance, p.y() / maxDistance );
          }
      );
    }

    // This output contains a sort of header (in gnuplot style) so that
    // it is possible to store multiple persistence diagrams in the same
    // file.
    //
    // Note that for the output, it would also be possible just to loop
    // over the individual points of the persistence diagram.
    std::cout << "# Persistence diagram <" << input << ">\n"
              << "#\n"
              << "# Dimension: " << D.dimension() << "\n"
              << "# Entries  : " << D.size() << "\n"
              << D << "\n\n";
  }
}


text:
package com.packt.sfjd.ch7;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;

import scala.Tuple2;

public class CustomPartitionerExample {
public static void main(String[] args) {
	System.setProperty("hadoop.home.dir", "C:\\softwares\\Winutils");
	SparkConf conf = new SparkConf().setMaster("local").setAppName("Partitioning");
	JavaSparkContext jsc = new JavaSparkContext(conf);

	 JavaPairRDD<String, String> pairRdd = jsc.parallelizePairs(
				Arrays.asList(new Tuple2<String, String>("India", "Asia"),new Tuple2<String, String>("Germany", "Europe"),
						new Tuple2<String, String>("Japan", "Asia"),new Tuple2<String, String>("France", "Europe"))
						,3);

	 JavaPairRDD<String, String> customPartitioned = pairRdd.partitionBy(new CustomPartitioner());

	 System.out.println(customPartitioned.getNumPartitions());

	 JavaRDD<String> mapPartitionsWithIndex = customPartitioned.mapPartitionsWithIndex((index, tupleIterator) -> {

			List<String> list=new ArrayList<>();

			while(tupleIterator.hasNext()){
				list.add("Partition number:"+index+",key:"+tupleIterator.next()._1());
			}

			return list.iterator();
		}, true);

		 System.out.println(mapPartitionsWithIndex.collect());
}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace vNextUIDemos.Models
{
    public enum ProductType
    {
        All,
        Gear,
        Food,
        Beer
    }

    public class Product
    {
        public int Id { get; set; }
        public ProductType Type { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }
}


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

/*=====================================================================
**
** Source:  SetCurrentDirectoryW.c (test 2)
**
** Purpose: Tests the PAL implementation of the SetCurrentDirectoryW function
**          by setting the current directory with ../
**
**
**===================================================================*/

#include <palsuite.h>

int __cdecl main(int argc, char *argv[])
{
    const char szDirName[MAX_PATH] = "testing";
    char szBuiltDir[MAX_PATH];
    WCHAR* szwBuiltDir = NULL;
    WCHAR szwHomeDirBefore[MAX_PATH];
    WCHAR szwHomeDirAfter[MAX_PATH];
    WCHAR* szwPtr = NULL;

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /* create a temp directory off the current directory */
    szwPtr = convert((LPSTR)szDirName);

    if (CreateDirectoryW(szwPtr, NULL) != TRUE)
    {
        free(szwPtr);
        Fail("Unexpected error: CreateDirectoryW failed "
             "with error code: %ld.\n",
             GetLastError());
    }

    /* find out what the current "home" directory is */
    memset(szwHomeDirBefore, 0, MAX_PATH * sizeof(WCHAR));

    if( 0 == GetCurrentDirectoryW(MAX_PATH, szwHomeDirBefore) )
    {
        Trace("Unexpected error: Unable to get current directory "
              "with GetCurrentDirectoryW that returned %ld\n",
              GetLastError());

        if (!RemoveDirectoryW(szwPtr))
        {
            Trace("Unexpected error: RemoveDirectoryW failed "
            "with error code: %ld.\n",
            GetLastError());
        }
        free(szwPtr);

        Fail("");
    }

     /* append the temp name to the "home" directory */
    memset(szBuiltDir, 0, MAX_PATH);
#if WIN32
    sprintf(szBuiltDir,"%s\\..\\", szDirName);
#else
    sprintf(szBuiltDir,"%s/../", szDirName);
#endif

    szwBuiltDir = convert(szBuiltDir);

    /* set the current directory to the temp directory */
    if (SetCurrentDirectoryW(szwBuiltDir) != TRUE)
    {
        Trace("ERROR: Unable to set current "
              "directory to %S. Failed with error code: %ld.\n",
              szwBuiltDir,
              GetLastError());

        if (!RemoveDirectoryW(szwPtr))
        {
            Trace("Unexpected error: RemoveDirectoryW failed "
            "with error code: %ld.\n",
            GetLastError());
        }
        free(szwPtr);
        free(szwBuiltDir);
        Fail("");
    }

    free(szwBuiltDir);

    /* find out what the current "home" directory is */
    memset(szwHomeDirAfter, 0, MAX_PATH * sizeof(WCHAR));

    if( 0 == GetCurrentDirectoryW(MAX_PATH, szwHomeDirAfter) )
    {
        Trace("Unexpected error: Unable to get current directory "
              "with GetCurrentDirectoryW that returned %ld\n",
              GetLastError());

        if (!RemoveDirectoryW(szwPtr))
        {
            Trace("ERROR: RemoveDirectoryW failed "
            "with error code: %ld.\n",
            GetLastError());
        }
        free(szwPtr);

        Fail("");
    }

    /*compare the new current dir to the compiled current dir */
    if (wcsncmp(szwHomeDirBefore, szwHomeDirAfter, wcslen(szwHomeDirBefore)) != 0)
    {
        Trace("ERROR:The set directory \"%S\" does not "
              "compare to the built directory \"%S\".\n",
              szwHomeDirAfter,
              szwHomeDirBefore);

        if (!RemoveDirectoryW(szwPtr))
        {
            Trace("Unexpected error: RemoveDirectoryW failed "
                  "with error code: %ld.\n",
                  GetLastError());
        }
        free(szwPtr);
        Fail("");
    }

    /* clean up */
    if (!RemoveDirectoryW(szwPtr))
    {
        free(szwPtr);
        Fail("Unexpected error: RemoveDirectoryW failed "
             "with error code: %ld.\n",
             GetLastError());
    }

    free(szwPtr);
    PAL_Terminate();

    return PASS;
}


text:
package com.pubnub.api;

import java.util.Enumeration;
import java.util.Hashtable;

import com.pubnub.api.PubnubUtil;

class HttpRequest {
    private volatile ResponseHandler responseHandler;
    private Hashtable headers;
    private String[] urlComponents;
    private Hashtable params;
    private String url;
    private boolean dar;
    private boolean subzero;
    private Worker _worker;

    public boolean isSubzero() {
        return subzero;
    }

    public void setWorker(Worker worker) {
        this._worker = worker;
    }

    public Worker getWorker() {
        return this._worker;
    }
    public void setSubzero(boolean subzero) {
        this.subzero = subzero;
    }

    public boolean isDar() {
        return dar;
    }

    public void setDar(boolean dar) {
        this.dar = dar;
    }

    public HttpRequest(String[] urlComponents, Hashtable params,
                       Hashtable headers, ResponseHandler rh) {
        this.setUrlComponents(urlComponents);
        this.setParams(params);
        this.setHeaders(headers);
        this.setResponseHandler(rh);
    }

    public HttpRequest(String[] urlComponents, Hashtable params,
                       ResponseHandler rh) {
        this.setUrlComponents(urlComponents);
        this.setParams(params);
        this.setResponseHandler(rh);
    }

    public HttpRequest(String[] urlComponents, ResponseHandler rh) {
        this.setUrlComponents(urlComponents);
        this.setResponseHandler(rh);
    }

    public String[] getUrlComponents() {
        return urlComponents;
    }

    public void setUrlComponents(String[] urlComponents) {
        this.urlComponents = urlComponents;
    }

    public Hashtable getParams() {
        return params;
    }

    public void setParams(Hashtable params) {
        this.params = params;
    }

    public ResponseHandler getResponseHandler() {
        return responseHandler;
    }

    public void setResponseHandler(ResponseHandler responseHandler) {
        this.responseHandler = responseHandler;
    }

    public Hashtable getHeaders() {
        return headers;
    }

    public void setHeaders(Hashtable headers) {
        this.headers = headers;
    }

    public String getUrl() {

        if (url != null) {
            return url;
        }

        String url = PubnubUtil.joinString(urlComponents, "/");

        if (this.params != null && this.params.size() > 0) {
            StringBuffer sb = new StringBuffer();
            sb.append(url).append("?");

            Enumeration paramsKeys = this.params.keys();
            boolean first = true;
            while (paramsKeys.hasMoreElements()) {
                if (!first) {
                    sb.append("&");
                } else
                    first = false;

                String key = (String) paramsKeys.nextElement();
                sb.append(PubnubUtil.urlEncode((String) key))
                .append("=")
                .append(PubnubUtil.urlEncode((String) this.params
                                             .get(key)));
            }

            url = sb.toString();
        }
        this.url = url;

        return this.url;
    }
}


text:
<?php
/** @see Gen_Form_Element */
require_once('Gen/Form/Element.php');
require_once('Gen/Date.php');

/**
 * @category   Gen
 * @package	Gen_Form
 */
class Gen_Form_Date extends Gen_Form_Textbox
{
	protected $_date;
	protected $_enable_time = false;
	protected $_firstYear;
	protected $_lastYear;

	protected $_format = 'Y/m/d H:i';

	public function setValue($date)
	{
		if(null != $date) {
			$date = Gen_Date::create($date);
			$date = $date->format($this->_format);
		} else {
			$date = null;
		}
		return parent::setValue($date);
	}

	public function __construct(array $attributes = array())
	{
		$this->_icon = 'calendar';
		parent::__construct($attributes);
		$this->addClass('date');
	}

	public function render()
	{
		$this->appendScript('$(function() {$( "#'. $this->getId() .'" ).datepicker({dateFormat : \'yy-mm-dd\'});});');
		return parent::render();
	}

	public function enableTime($enableTime)
	{
		$this->_enable_time = (bool) $enableTime;
		return $this;
	}
}


text:
package com.google.errorprone.refaster;

import static com.google.errorprone.refaster.Unifier.unifications;

import com.google.auto.value.AutoValue;
import com.google.errorprone.util.ASTHelpers;

import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.tree.JCTree.JCExpression;

/**
 * Identifier representing a static member (field, method, etc.) on a class.
 *
 * @author lowasser@google.com (Louis Wasserman)
 */
@AutoValue
public abstract class UStaticIdent extends UIdent {
  public static UStaticIdent create(
      UClassIdent classIdent, CharSequence member, UType memberType) {
    return new AutoValue_UStaticIdent(classIdent, StringName.of(member), memberType);
  }

  public static UStaticIdent create(String qualifiedClass, CharSequence member, UType memberType) {
    return create(UClassIdent.create(qualifiedClass), member, memberType);
  }

  public static UStaticIdent create(ClassSymbol classSym, CharSequence member, UType memberType) {
    return create(UClassIdent.create(classSym), member, memberType);
  }

  abstract UClassIdent classIdent();

  @Override
  public abstract StringName getName();

  abstract UType memberType();

  @Override
  public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
    return inliner.importPolicy().staticReference(
        inliner, classIdent().getTopLevelClass(),
        classIdent().getName(),
        getName());
  }

  @Override
  protected Choice<Unifier> defaultAction(Tree node, Unifier unifier) {
    Symbol symbol = ASTHelpers.getSymbol(node);
    if (symbol != null) {
      return classIdent().unify(symbol.getEnclosingElement(), unifier)
          .thenChoose(unifications(getName(), symbol.getSimpleName()))
          .thenChoose(unifications(memberType(), symbol.asType()));
    }
    return Choice.none();
  }
}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/system/sys_info.h"
#include "base/test/launcher/test_launcher.h"
#include "base/test/test_suite.h"
#include "build/build_config.h"
#include "chromecast/app/cast_main_delegate.h"
#include "content/public/common/network_service_util.h"
#include "content/public/test/test_launcher.h"
#include "ipc/ipc_channel.h"
#include "mojo/core/embedder/embedder.h"

#if BUILDFLAG(IS_WIN)
#include "base/win/win_util.h"
#endif  // BUILDFLAG(IS_WIN)

namespace chromecast {
namespace shell {

class CastTestLauncherDelegate : public content::TestLauncherDelegate {
 public:
  CastTestLauncherDelegate() {}

  CastTestLauncherDelegate(const CastTestLauncherDelegate&) = delete;
  CastTestLauncherDelegate& operator=(const CastTestLauncherDelegate&) = delete;

  ~CastTestLauncherDelegate() override {}

  int RunTestSuite(int argc, char** argv) override {
    base::TestSuite test_suite(argc, argv);
    // Browser tests are expected not to tear-down various globals .
    test_suite.DisableCheckForLeakedGlobals();
    return test_suite.Run();
  }

 protected:
#if !BUILDFLAG(IS_ANDROID)
  content::ContentMainDelegate* CreateContentMainDelegate() override {
    return new CastMainDelegate();
  }
#endif  // BUILDFLAG(IS_ANDROID)
};

}  // namespace shell
}  // namespace chromecast

int main(int argc, char** argv) {
  base::CommandLine::Init(argc, argv);
  size_t parallel_jobs = base::NumParallelJobs(/*cores_per_job=*/2);
  if (parallel_jobs == 0U)
    return 1;

#if BUILDFLAG(IS_WIN)
  // Load and pin user32.dll to avoid having to load it once tests start while
  // on the main thread loop where blocking calls are disallowed.
  base::win::PinUser32();
#endif  // BUILDFLAG(IS_WIN)

  chromecast::shell::CastTestLauncherDelegate launcher_delegate;
  mojo::core::Init();
  content::ForceInProcessNetworkService(true);
  return content::LaunchTests(&launcher_delegate, parallel_jobs, argc, argv);
}


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.notification;

import com.intellij.ide.ui.IdeUiService;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.util.NlsContexts.NotificationContent;
import org.jetbrains.annotations.NotNull;

/**
 * @author Alexander Lobas
 */
public class BrowseNotificationAction extends NotificationAction {
  private final String myUrl;

  public BrowseNotificationAction(@NotNull @NotificationContent String text, @NotNull String url) {
    super(text);
    myUrl = url;
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) {
    IdeUiService.getInstance().browse(myUrl);
  }
}


text:
"""
@brief      test log(time=8s)
@author     Xavier Dupre
"""

import sys
import os
import unittest

from pyquickhelper.loghelper.flog import fLOG
from pyquickhelper.helpgen import rst2html

class TestRst2HtmlBug(unittest.TestCase):

    def test_rst2html_bug_faq(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        content = """
                        .. faqref::
                            :title: How to add a FAQ?
                            :tag: faqexample2

                            Some description.

                        .. faqreflist::
                            :tag: faqexample2
                            :contents:
        """.replace("                        ", "")

        text = rst2html(content, writer="rst", layout="sphinx")
        if "(`original entry <#indexfaqref-faqexample20>`_ : <string>, line 2)" not in text:
            raise Exception(text)

if __name__ == "__main__":
    unittest.main()