text:
using UnityEngine;
using UnityEditor;

namespace Com.LuisPedroFonseca.ProCamera2D
{
    [CanEditMultipleObjects]
    [CustomEditor(typeof(ProCamera2DPixelPerfectSprite))]
    public class ProCamera2DPixelPerfectSpriteEditor : Editor
    {
        MonoScript _script;
        GUIContent _tooltip;

        void OnEnable()
        {
            var proCamera2DPixelPerfectSprite = (ProCamera2DPixelPerfectSprite)target;

            if (proCamera2DPixelPerfectSprite.ProCamera2D == null && Camera.main != null)
                proCamera2DPixelPerfectSprite.ProCamera2D = Camera.main.GetComponent<ProCamera2D>();

            _script = MonoScript.FromMonoBehaviour(proCamera2DPixelPerfectSprite);
        }

        public override void OnInspectorGUI()
        {
            var proCamera2DPixelPerfectSprite = (ProCamera2DPixelPerfectSprite)target;

            if (proCamera2DPixelPerfectSprite.ProCamera2D == null)
            {
                EditorGUILayout.HelpBox("ProCamera2D is not set.", MessageType.Error, true);
                return;
            }

            // No sprite found
            var hasSprite = false;
            #if PC2D_TK2D_SUPPORT
            if (proCamera2DPixelPerfectSprite.GetComponent<tk2dBaseSprite>() != null)
            {
                hasSprite = true;
            }
            else
            {
                #endif
                if (proCamera2DPixelPerfectSprite.GetComponent<SpriteRenderer>() != null)
                    hasSprite = true;
                #if PC2D_TK2D_SUPPORT
            }
            #endif

            if (!hasSprite)
                EditorGUILayout.HelpBox("This component needs a Sprite renderer on the same GameObject!", MessageType.Error, true);

            // Rigidbody, collider, character controller warning
            if (proCamera2DPixelPerfectSprite.IsAMovingObject &&
                (proCamera2DPixelPerfectSprite.GetComponent<Rigidbody>() != null ||
                proCamera2DPixelPerfectSprite.GetComponent<Rigidbody2D>() != null ||
                proCamera2DPixelPerfectSprite.GetComponent<Collider>() != null ||
                proCamera2DPixelPerfectSprite.GetComponent<Collider2D>() != null ||
                proCamera2DPixelPerfectSprite.GetComponent<CharacterController>() != null))
            {
                EditorGUILayout.HelpBox("You should not add this component to GameObjects that have physics components, because rounding the sprite to a pixel-perfect position might interfere with the physics calculations. Please add the sprite as a child of this GameObject and add this component to it instead.", MessageType.Warning, true);
            }

            serializedObject.Update();

            // Show script link
            _script = EditorGUILayout.ObjectField("Script", _script, typeof(MonoScript), false) as MonoScript;

            // ProCamera2D
            _tooltip = new GUIContent("Pro Camera 2D", "");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("ProCamera2D"), _tooltip);

            // Moving object
            _tooltip = new GUIContent("Is A Moving Object", "If checked, the object position will be aligned to pixel perfect every frame. To improve performance, enable only if the object (or its parent) move.");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("IsAMovingObject"), _tooltip);

            // Child sprite
            if (proCamera2DPixelPerfectSprite.IsAMovingObject && proCamera2DPixelPerfectSprite.transform.parent != null)
            {
                _tooltip = new GUIContent("Use Parent Movement", "Enable if you're moving the parent of this sprite instead of the sprite itself.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("IsAChildSprite"), _tooltip);
            }
            else
            {
                proCamera2DPixelPerfectSprite.IsAChildSprite = false;
            }

            // Local Position
            if (proCamera2DPixelPerfectSprite.IsAChildSprite)
            {
                EditorGUILayout.BeginHorizontal();

                _tooltip = new GUIContent("Local Position", "If you're using the parent movement, you have to set this sprite local position using this value.");
                EditorGUILayout.PropertyField(serializedObject.FindProperty("LocalPosition"), _tooltip);

                if (GUILayout.Button("R", GUILayout.Width(20)))
                    serializedObject.FindProperty("LocalPosition").vector2Value = Vector2.zero;

                EditorGUILayout.EndHorizontal();
            }

            // Pixel Scale
            _tooltip = new GUIContent("Sprite Scale", "The scale of this sprite");
            EditorGUILayout.PropertyField(serializedObject.FindProperty("SpriteScale"), _tooltip);

            // Scale 0 warning
            if (proCamera2DPixelPerfectSprite.SpriteScale == 0)
            {
                EditorGUILayout.HelpBox("A scale of 0 allows you to manually scale the sprite, however, it doesn't guarantee that it will be pixel-perfect. Use a scale different than 0 to guarantee your sprite size is pixel-perfect.", MessageType.Warning, true);
            }

            // Save properties
            serializedObject.ApplyModifiedProperties();
        }
    }
}


text:
/* Generated code */
import ShippingMethod from './ShippingMethod';

interface DictionaryShippingOptions {

	/**
	 * Quantity of devices to ship
	 */
	quantity?: number;

	/**
	 * Price for shipping with the specified method (depending on the quantity value)
	 */
	price?: number;

	/**
	 * Shipping method description
	 */
	method?: ShippingMethod;
}

export default DictionaryShippingOptions;

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class net.sourceforge.pmd.lang.swift.antlr4.SwiftParser.IdentifierContext (PMD Swift 5.5.1 API)</title>
<meta name="date" content="2016-07-27">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.sourceforge.pmd.lang.swift.antlr4.SwiftParser.IdentifierContext

Packages that use SwiftParser.IdentifierContext

Package
Description

net.sourceforge.pmd.lang.swift.antlr4

Uses of SwiftParser.IdentifierContext in net.sourceforge.pmd.lang.swift.antlr4

Methods in net.sourceforge.pmd.lang.swift.antlr4 that return SwiftParser.IdentifierContext

Modifier and Type
Method and Description

SwiftParser.IdentifierContext
SwiftParser.identifier()

SwiftParser.IdentifierContext
SwiftParser.LabelNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.ImportPathIdentifierContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.VariableNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.SetterNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.TypealiasNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.FunctionNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.ExternalParameterNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.LocalParameterNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.EnumNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.EnumCaseNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.StructNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.ClassNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.ProtocolNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.IdentifierPatternContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.AttributeNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.BalancedTokenContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.InOutExpressionContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.PrimaryExpressionContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.SelfExpressionContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.SuperclassMethodExpressionContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.ImplicitMemberExpressionContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.ExpressionElementContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.ExplicitMemberExpression2Context.identifier()

SwiftParser.IdentifierContext
SwiftParser.TypeNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.ElementNameContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.BuildConfigurationContext.identifier()

SwiftParser.IdentifierContext
SwiftParser.IdentifierListContext.identifier(int i)

Methods in net.sourceforge.pmd.lang.swift.antlr4 that return types with arguments of type SwiftParser.IdentifierContext

Modifier and Type
Method and Description

List<SwiftParser.IdentifierContext>
SwiftParser.IdentifierListContext.identifier()

Methods in net.sourceforge.pmd.lang.swift.antlr4 with parameters of type SwiftParser.IdentifierContext

Modifier and Type
Method and Description

void
SwiftBaseListener.enterIdentifier(SwiftParser.IdentifierContext ctx)

Enter a parse tree produced by SwiftParser.identifier().

void
SwiftListener.enterIdentifier(SwiftParser.IdentifierContext ctx)

Enter a parse tree produced by SwiftParser.identifier().

void
SwiftBaseListener.exitIdentifier(SwiftParser.IdentifierContext ctx)

Exit a parse tree produced by SwiftParser.identifier().

void
SwiftListener.exitIdentifier(SwiftParser.IdentifierContext ctx)

Exit a parse tree produced by SwiftParser.identifier().

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2002–2016 InfoEther. All rights reserved.


text: <button class="btn btn-primary btn-comment show-comments">Write or Read Comments</button>


text:
// Problem 6. Most frequent number
//
// Write a script that finds the most frequent number in an array.  [4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3] -> 4 (5 times)

/* global jsConsole */

function mostFrequentNumber() {

    if (jsConsole.read('#arr') !== '') {

        var arr = (jsConsole.read('#arr')).split(','),
            len = arr.length,
            i, j,
            counter = 1,
            mostFrequentElement,
            indexOfNextOccurrence,
            maxOccurrences = 1;

        for (i = 0; i < len; i += 1) {

            arr[i] = parseInt(arr[i]);
        }

        jsConsole.writeLine('array = [' + arr + ']');
        jsConsole.writeLine('');

        for (i = 0; i < len; i += 1) {

            for (j = i + 1, counter = 1; j < len;) {

                indexOfNextOccurrence = arr.indexOf(arr[i], j);

                if (indexOfNextOccurrence !== -1) {

                    counter += 1;
                    j = indexOfNextOccurrence + 1;

                    if (counter > maxOccurrences) {

                        maxOccurrences = counter;
                        mostFrequentElement = arr[i];
                    }
                } else {

                    break;
                }
            }
        }

        jsConsole.writeLine('The most frequent number in an array is : ' + mostFrequentElement + ' (' + maxOccurrences + ' times)');
        jsConsole.writeLine('');

    } else {

        jsConsole.writeLine('ERROR : Array is empty');
    }
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Export_ad_model extends CI_Model {

	public function exportData($search, $start_id, $end_id) {
		$this->db->select('*');
		$this->db->from('forms');
		$this->db->where('status','აქტიური');
		$this->db->where('a_index >=',$start_id);
		$this->db->where('a_index <=',$end_id);
		$this->db->where('hide','0');
		$this->db->order_by('a_index', 'desc');
		$query = $this->db->get();
		return $query->result_array();
	}

	public function listFields() {
		return $this->db->list_fields('forms');
	}

	public function exportCount($start_id, $end_id){

		$this->db->select('*');
		$this->db->from('forms');
		$this->db->where('status','აქტიური');
		$this->db->where('a_index >=',$start_id);
		$this->db->where('a_index <=',$end_id);
		$this->db->where('hide','0');
		$this->db->order_by('a_index', 'desc');
		$query = $this->db->get();
		return $query->result_array();
	}

}


text:
var express = require('express'),
    Message = require('../models/Message');

// Create basic auth middleware used to authenticate all admin requests
exports.auth = express.basicAuth(process.env.BASIC_UN, process.env.BASIC_PW);

// Middleware to redirect all non-secure traffic to an SSL endpoint - use
// Heroku's header to determine if the original request was over SSL or not
exports.secure = function(request, response, next) {
    // Check current environment and Heroku protocol header
    var prod = process.env.NODE_ENV === 'production',
        notSecure = request.header('x-forwarded-proto') !== 'https';

    // Redirect to SSL if necessary
    if (prod && notSecure) {
        var host = request.header('host'), url = request.url;
        response.redirect('https://'+ host + url);
    }

    // Otherwise continue to process the request
    next();
};

// Render admin home page
exports.index = function(request, response) {
    response.render('admin', {
        title: 'Moderate Messages',
        staticfile: 'admin'
    });
};

// Get a list of messages
exports.messages = function(request, response) {
    // Get query params
    var favorites = request.param('favorites') ? true : false,
        unapproved = request.param('unapproved') ? true : false;

    // Query for public accessible messages
    Message.listMessages({
        unapproved: unapproved,
        favorites: favorites
    }, function(err, models) {
        if (err) {
            response.send(500, err);
        } else {
            response.send(models);
        }
    });
};

// Update a given message
exports.update = function(request, response) {
    console.log(request.param('props'));
    // Args for find and update
    var id = request.param('id'),
        props = JSON.parse(request.param('props'));

    // Update message based on input from client
    Message.findByIdAndUpdate(id, props, function(err, doc) {
        if (err) {
            response.send(500, err);
        } else {
            response.send(doc);
        }
    });
};

// Delete a given message
exports.delete = function(request, response) {
    // Args for find and remove
    var id = request.param('id');

    // Update message based on input from client
    Message.findByIdAndRemove(id, function(err, doc) {
        if (err) {
            response.send(500, err);
        } else {
            response.send(doc);
        }
    });
};


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType MaximumCopiesNumericType
 * @xmlName MaximumCopiesNumeric
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\MaximumCopiesNumeric
 */
class MaximumCopiesNumeric
	extends MaximumCopiesNumericType
	{

} // end class MaximumCopiesNumeric


text:
class UsersController < ApplicationController
  def index
    @user = User.new
    @users = User.all
  end

  def create
    User.create user_params
    redirect_to :back
  end

  def new
    @user = User.new
  end

  def edit
    @user = User.find id_params
  end

  def update
    user = User.find id_params
    if user.update_attributes user_params
      redirect_to users_path, :notice => 'Your task has successfully been updated'
    else
      redirect_to :back, :notice => 'There was an error updating your post.'
    end
  end

  def destroy
    User.destroy id_params
    redirect_to :back, :notice => 'Post has been deleted.'
  end

  def user_params
    params.require(:user).permit(:name, :password, :password_confirmation)
  end

  def id_params
    params.require(:id)
  end

end


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>KfaccountUploadheadimg</title>
<meta name="date" content="2019-06-04">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

org.jeewx.api.core.req.model.kfaccount

类 KfaccountUploadheadimg

java.lang.Object

org.jeewx.api.core.req.model.WeixinReqParam

org.jeewx.api.core.req.model.kfaccount.KfaccountUploadheadimg

public class KfaccountUploadheadimg
extends WeixinReqParam

公众号可调用本接口来上传图片、语音、视频等文件到微信服务器,
 上传后服务器会返回对应的media_id,公众号此后可根据该media_id来获取多媒体

作者:

sfli.sir

构造器概要

构造器

构造器和说明

KfaccountUploadheadimg()

方法概要

方法

限定符和类型
方法和说明

java.lang.String
getFilePathName()

java.lang.String
getKf_account()

java.lang.String
getType()

void
setFilePathName(java.lang.String filePathName)

void
setKf_account(java.lang.String kf_account)

void
setType(java.lang.String type)

从类继承的方法 org.jeewx.api.core.req.model.WeixinReqParam

getAccess_token, setAccess_token

从类继承的方法 java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

构造器详细资料

KfaccountUploadheadimg

public KfaccountUploadheadimg()

方法详细资料

getKf_account

public java.lang.String getKf_account()

setKf_account

public void setKf_account(java.lang.String kf_account)

getType

public java.lang.String getType()

setType

public void setType(java.lang.String type)

getFilePathName

public java.lang.String getFilePathName()

setFilePathName

public void setFilePathName(java.lang.String filePathName)

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法


text:
;(function($, window, document, undefined) {
})(jQuery, window, document);


text:
'use strict';

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var Q = require('q');
var rewire = require('rewire');

Q.longStackSupport = true;

chai.should();
chai.use(chaiAsPromised);

global.chaiAsPromised = chaiAsPromised;
global.expect = chai.expect;
global.AssertionError = chai.AssertionError;
global.Assertion = chai.Assertion;
global.assert = chai.assert;

global.rewire = rewire;

global.fulfilledPromise = Q.resolve;
global.rejectedPromise = Q.reject;
global.defer = Q.defer;
global.waitAll = Q.all;


text:
<?php

namespace PROCERGS\LoginCidadao\APIBundle\Controller;

use FOS\RestBundle\Controller\Annotations as REST;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use PROCERGS\LoginCidadao\APIBundle\Security\Audit\Annotation as Audit;

class BadgeController extends BaseController
{
    /**
     * Retrieves all badges available
     *
     * @ApiDoc(
     *   resource = true,
     *   description = "Gets the available badges.",
     *   output = "ArrayCollection",
     *   statusCodes = {
     *     200 = "Returned when successful"
     *   }
     * )
     * @REST\View(templateVar="badges")
     * @Audit\Loggable(type="SELECT")
     * @throws NotFoundHttpException
     */
    public function getBadgesAction()
    {
        $badges = $this->get('badges.handler')->getAvailableBadges();

        return $badges;
    }
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests\ContactsRequest;
use App\Http\Controllers\Controller;

use App\Contact;

class ContactsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Contact $contact)
    {
        $contacts = $contact
            ->whereUserId(auth()->user()->id)
            ->orWhere('public', 1)
            ->paginate(15);

        return view('contacts.index', compact('contacts'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Contact $contact)
    {
        return view('contacts.create', compact('contact'));
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\ContactsRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Contact $contact, ContactsRequest $request)
    {
        $contact = auth()->user()->contacts()->create($request->all());

        return redirect()->route('admin.contacts.index')
            ->withSuccess("El contacto $contact->name ha sido creado de manera correcta!");
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Contact $contact)
    {
        $this->checkAuthorization($contact);

        return view('contacts.show', compact('contact'));
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Contact $contact)
    {

        $this->checkAuthorization($contact);
        // return  $contact;
        return view('contacts.edit', compact('contact'));
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\ContactsRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Contact $contact, ContactsRequest $request)
    {
        $this->checkAuthorization($contact);
        // return $contact;
        $contact->update($request->all());

        return redirect()->route('admin.contacts.index')
            ->withSuccess("El contacto $contact->name ha sido actualizado de manera correcta!");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Contact $contact)
    {
        $this->checkAuthorization($contact);
        $contact->delete();

        return redirect()->route('admin.contacts.index')
            ->withWarning("Se ha eliminado el contacto $contact->name. ");
    }

    /**
     * Allows to search contacts by db indexes
     * @param  Request $request [description]
     * @param  User    $users   [description]
     * @return [type]           [description]
     */
    public function search(Request $request, Contact $contacts)
    {
        $searchs = explode(' ', $request->get('search'));

        foreach ($searchs as $key => $value) {
            $contacts = $contacts
                ->orWhere('name', 'like', "%$value%")
                ->orWhere('mobile', 'like', "%$value%")
                ->orWhere('secondary', 'like', "%$value%")
                ->orWhere('email', 'like', "%$value%")
                ->orWhere('address', 'like', "%$value%")
                ;
        }

        $contacts = $contacts->paginate(10)->appends(['search' => $request->get('search')]);

        $request->flash();
        return view('contacts.index', compact('contacts'));
    }

    /**
     * Save a main image for this contact
     * @param  Request $request user inputs and request
     * @param  Contact $contact current contact
     * @return [type]           [description]
     */
    public function postImage(Request $request, Contact $contact, $id)
    {
        $this->validate($request, [
            'photo' => 'required|image|max:8000',
        ]);

        $contact = $contact->find($id);

        $file = $request->file('photo');
        $localPath = 'images/contacts/'; // local folder where the image will be loaded to
        $fileName = sha1($contact->id . $contact->name); // $fileName = str_random(40); //username sha1ed, so it is unique
        $extension = "." . $file->getClientOriginalExtension(); // $fileName = str_random(40); //username sha1ed, so it is unique
        $extendedName = $localPath . $fileName . $extension;

        $img = \File::get($file);

        $save = \File::put($extendedName, $img);

        if ($save) {

            $contact->photo = $extendedName;
            $contact->update();

        } else {
            return dd($save);
        }

        if ($request->ajax()) {
            return response()->json([
                'success' => 1,
                'data' => $contact
            ]);
        }

        return redirect()->route('admin.contacts.edit', $contact->id)
            ->withSuccess("Main image updated...");
    }

    public function checkAuthorization($contact)
    {
        if (!$contact->ownedOrPublic()) {
              return redirect()->route('contacts.index')
                  ->withDanger("asfa asdfasdf");
        }

        return true;

    }
}


text:
/**
 * layout 布局渲染
 */
import BaseSection from "./baseSection"

import footerStyle from "../theme/default/footer"
import headerStyle from "../theme/default/header"

import { IadItemModel } from "../interfaces"

class LayoutSections extends BaseSection {
  /**
   * 页头
   * @param  {number}    winWidth 页面宽度
   * @param  {string}    title 标题文字
   * @return {HTMLElement}
   */
  createHeader(winWidth: number, title: string = "猜你喜欢") {
    const headerEle = this.buildDom("div", {}, () =>
      headerStyle.configWrapCreate(winWidth)
    )
    const titleEle = this.buildDom("div", {}, () =>
      headerStyle.configTitleCreate(winWidth)
    )
    titleEle.innerText = title

    headerEle.appendChild(titleEle)
    return headerEle
  }
  /**
   * 底部 Dom
   * @param  {number} winWidth 页面宽度
   * @return {HTMLElement}
   */
  createFooter(winWidth: number) {
    return this.buildDom("div", {}, () =>
      footerStyle.configWrapCreate(winWidth)
    )
  }
  /**
   * 容器 Dom
   * @return {HTMLElement}
   */
  createrContainer() {
    return this.buildDom("div", {})
  }
}

export default LayoutSections


text:
Directories order will be changed after running `python setup.py develop`. This may break your python installation because default system package directory gets more priority than local ones with newer versions of packages.

The most typical symptom looks like:
```console
vagrant@vagrant-ubuntu-trusty-64:~$ # We want to update pip but it doesn't work realy
vagrant@vagrant-ubuntu-trusty-64:~$ sudo pip install -U pip==8.1.2
Downloading/unpacking pip==8.1.2
  Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB): 1.2MB downloaded
Installing collected packages: pip
  Found existing installation: pip 1.5.4
    Not uninstalling pip at /usr/lib/python2.7/dist-packages, owned by OS
Successfully installed pip
Cleaning up...
vagrant@vagrant-ubuntu-trusty-64:~$ hash -r
vagrant@vagrant-ubuntu-trusty-64:~$ pip --version
pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7)
vagrant@vagrant-ubuntu-trusty-64:~$ pip install -U pip --user
Downloading/unpacking pip from https://pypi.python.org/packages/9c/32/004ce0852e0a127f07f358b715015763273799bd798956fa930814b60f39/pip-8.1.2-py2.py3-none-any.whl#md5=0570520434c5b600d89ec95393b2650b
  Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB): 1.2MB downloaded
Installing collected packages: pip
Successfully installed pip
Cleaning up...
vagrant@vagrant-ubuntu-trusty-64:~$ hash -r
vagrant@vagrant-ubuntu-trusty-64:~$ pip --version
pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7)
vagrant@vagrant-ubuntu-trusty-64:~$ ~/.local/bin/pip --version
pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7)
```

### Checking for bug (by default on ubuntu trusty)
```bash
./check.sh
```

### Or check with specific version of ubuntu
```bash
TAG='xenial' ./check.sh
```

```bash
TAG='latest' ./check.sh
```

### Or even with specific version of setuptools
```bash
SETUPTOOLS='setuptools<20' ./check.sh
```

```bash
SETUPTOOLS='git+https://github.com/last-g/setuptools@bug/shadowbug' ./check.sh
```

## More in [bug.sh](bug.sh)


text:
package serverless

import (
	"reflect"

	serverlessv1alpha2 "github.com/kyma-project/kyma/components/function-controller/pkg/apis/serverless/v1alpha2"
	"go.uber.org/zap"
	"sigs.k8s.io/controller-runtime/pkg/event"
)

func IsNotFunctionStatusUpdate(log *zap.SugaredLogger) func(event.UpdateEvent) bool {
	return func(event event.UpdateEvent) bool {
		if event.ObjectOld == nil || event.ObjectNew == nil {
			return true
		}

		log.Debug("old: ", event.ObjectOld.GetName())
		log.Debug("new: ", event.ObjectNew.GetName())

		oldFn, ok := event.ObjectOld.(*serverlessv1alpha2.Function)
		if !ok {
			v := reflect.ValueOf(event.ObjectOld)
			log.Debug("Can't cast to function from type: ", v.Type())
			return true
		}

		newFn, ok := event.ObjectNew.(*serverlessv1alpha2.Function)
		if !ok {
			v := reflect.ValueOf(event.ObjectNew)
			log.Debug("Can't cast to function from type: ", v.Type())
			return true
		}

		equalStatus := equalFunctionStatus(oldFn.Status, newFn.Status)
		log.Debug("Statuses are equal: ", equalStatus)

		return equalStatus
	}
}


text:
package com.appsfs.sfs.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import com.appsfs.sfs.Objects.Shop;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by longdv on 4/18/16.
 */
public class DatabaseHelperShop extends SQLiteOpenHelper{
    private static final String DATABASE_NAME = "shop.db";
    private static final String TABLE_NAME = "shop_info";
    private static final int DATABASE_VERSION = 1;

    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_PHONE = "phone";
    private static final String COLUMN_ADDRESS = "address";
    private static final String COLUMN_PRODUCT = "product";
    private static final String COLUMN_MONEY = "money";
    private static final String COLUMN_LAT = "latitude";
    private static final String COLUMN_LONG = "longitude";

    public static final String[] COLS = {COLUMN_ID, COLUMN_NAME,COLUMN_PHONE,COLUMN_ADDRESS,
            COLUMN_PRODUCT,COLUMN_MONEY,COLUMN_LAT,COLUMN_LONG};

    private static DatabaseHelperShop helper;
    private static SQLiteDatabase mDb;

    private static String FILE_DIR = "SFS";

    public static synchronized DatabaseHelperShop getInstance(Context context)
    {
        if(helper == null)
        {
            helper = new DatabaseHelperShop(context);
        }
        return helper;
    }

    private DatabaseHelperShop(Context context)
    {
//        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        super(context, Environment.getExternalStorageDirectory()
                + File.separator + FILE_DIR
                + File.separator + DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String createSessionTable = "create table if not exists shop_info" +
                "( id integer primary key autoincrement,name text,phone text,address text UNIQUE,product text,money int,latitude double,longitude double)";
        sqLiteDatabase.execSQL(createSessionTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
        onCreate(sqLiteDatabase);
    }

    @Override
    protected void finalize() throws Throwable {
        if(helper != null) helper.close();
        super.finalize();
    }

    private static boolean openDatabase()
    {
        try
        {
            if ((mDb == null) || ((mDb != null) && (!mDb.isOpen())))
            {
                mDb = helper.getWritableDatabase();
            }
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    /***********************************************************************************************
     * Insert shop infomation when register
     ************************************************************************************************/
    public long insertShopInfo(Shop shopInfo)
    {
        boolean isOpenDb = openDatabase();
        if (!isOpenDb) {
            return -1;
        } else {
            ContentValues contentValues = new ContentValues();
            contentValues.put(COLS[1], shopInfo.getName());
            contentValues.put(COLS[2], shopInfo.getPhoneNumber());
            contentValues.put(COLS[3], shopInfo.getAddress());
            contentValues.put(COLS[4], shopInfo.getProduct());
            contentValues.put(COLS[5], shopInfo.getMoney());
            contentValues.put(COLS[6], shopInfo.getLatitude());
            contentValues.put(COLS[7], shopInfo.getLongitude());
            return mDb.insert(TABLE_NAME, null, contentValues);
        }

    }

    /***********************************************************************************************
     * Delete shop infomation based on phone number
     ************************************************************************************************/
    public int deleteShopInfo(String phone)
    {
        openDatabase();
        return mDb.delete(TABLE_NAME, "phone=?", new String[]{phone});
    }

    /***********************************************************************************************
     * Update all shop
     ************************************************************************************************/
    public boolean updateItems(Shop shopInfo){
        openDatabase();
        try {
            final ContentValues contentValues = new ContentValues();
            contentValues.put(COLS[1], shopInfo.getName());
            contentValues.put(COLS[2], shopInfo.getPhoneNumber());
            contentValues.put(COLS[3], shopInfo.getAddress());
            contentValues.put(COLS[4], shopInfo.getProduct());
            contentValues.put(COLS[5], shopInfo.getMoney());
            contentValues.put(COLS[6], shopInfo.getLatitude());
            contentValues.put(COLS[7], shopInfo.getLongitude());

            mDb.update(TABLE_NAME, contentValues, COLS[1] + "= ?", new String[]{shopInfo.getName()});
            return true;
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
    }

    /***********************************************************************************************
     * Get shop item
     ************************************************************************************************/
    public Shop getShopItem(String phone){
        Cursor cursor = null;
        openDatabase();
        try{
            String SQL = "SELECT * FROM " + TABLE_NAME + " WHERE " + COLS[2] + " = '" + phone +"'";
            cursor = mDb.rawQuery(SQL, null);
            if(cursor.moveToFirst()){
                Shop ret = new Shop();
                ret.setName(cursor.getString(1));
                ret.setPhoneNumber(cursor.getString(2));
                ret.setAddress(cursor.getString(3));
                ret.setProduct(cursor.getString(4));
                ret.setMoney(cursor.getInt(5));
                ret.setLatitude(cursor.getDouble(6));
                ret.setLongitude(cursor.getDouble(7));
                return ret;
            }
        }
        catch (Exception e)
        {
            return null;
        }
        finally
        {
            if(cursor != null) cursor.close();
        }
        return null;
    }

    /***********************************************************************************************
     * Get All Shop
     ************************************************************************************************/
    public ArrayList<Shop> getAllShops() {
        ArrayList<Shop> shopList = new ArrayList<Shop>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

        openDatabase();
        Cursor cursor = mDb.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Shop ret = new Shop();
                ret.setName(cursor.getString(1));
                ret.setPhoneNumber(cursor.getString(2));
                ret.setAddress(cursor.getString(3));
                ret.setProduct(cursor.getString(4));
                ret.setMoney(cursor.getInt(5));
                ret.setLatitude(cursor.getDouble(6));
                ret.setLongitude(cursor.getDouble(7));
                // Adding contact to list
                shopList.add(ret);
            } while (cursor.moveToNext());
        }

        // return shop list
        return shopList;
    }

    /***********************************************************************************************
     * Insert phone number when edit
     ************************************************************************************************/

    public boolean updatePhoneNumber(String oldPhone,String newPhone) {
        openDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_PHONE, newPhone);
        long ret = mDb.update(TABLE_NAME, contentValues,COLS[2] + "=?",new String[]{oldPhone});
        if (ret == -1) {
            return false;
        } else {
            return true;
        }

    }

    /***********************************************************************************************
     * Insert shop information when edit infomation
     ************************************************************************************************/

    public boolean updatePhoneInformation(String phone,Shop shop) {
        openDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_NAME, shop.getName());
        contentValues.put(COLUMN_ADDRESS, shop.getAddress());
        contentValues.put(COLUMN_PRODUCT, shop.getProduct());
        contentValues.put(COLUMN_MONEY, shop.getMoney());
        contentValues.put(COLUMN_LAT, shop.getLatitude());
        contentValues.put(COLUMN_LONG, shop.getLongitude());
        long ret = mDb.update(TABLE_NAME, contentValues,COLS[2] + "=?",new String[]{phone});
        if (ret == -1) {
            return false;
        } else {
            return true;
        }

    }

}


text:
package v1

import (
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// SetStatusCondition sets the corresponding condition in conditions to newCondition.
// The return value indicates if this resulted in any changes *other than* LastHeartbeatTime.
func SetStatusCondition(conditions *[]Condition, newCondition Condition) bool {
	if conditions == nil {
		conditions = &[]Condition{}
	}
	existingCondition := FindStatusCondition(*conditions, newCondition.Type)
	if existingCondition == nil {
		newCondition.LastTransitionTime = metav1.NewTime(time.Now())
		newCondition.LastHeartbeatTime = metav1.NewTime(time.Now())
		*conditions = append(*conditions, newCondition)
		return true
	}

	changed := updateCondition(existingCondition, newCondition)
	existingCondition.LastHeartbeatTime = metav1.NewTime(time.Now())
	return changed
}

// SetStatusConditionNoHearbeat sets the corresponding condition in conditions to newCondition
// without setting lastHeartbeatTime.
// The return value indicates if this resulted in any changes.
func SetStatusConditionNoHeartbeat(conditions *[]Condition, newCondition Condition) bool {
	if conditions == nil {
		conditions = &[]Condition{}
	}
	existingCondition := FindStatusCondition(*conditions, newCondition.Type)
	if existingCondition == nil {
		newCondition.LastTransitionTime = metav1.NewTime(time.Now())
		*conditions = append(*conditions, newCondition)
		return true
	}

	return updateCondition(existingCondition, newCondition)
}

// RemoveStatusCondition removes the corresponding conditionType from conditions.
func RemoveStatusCondition(conditions *[]Condition, conditionType ConditionType) {
	if conditions == nil {
		return
	}
	newConditions := []Condition{}
	for _, condition := range *conditions {
		if condition.Type != conditionType {
			newConditions = append(newConditions, condition)
		}
	}

	*conditions = newConditions
}

func updateCondition(existingCondition *Condition, newCondition Condition) bool {
	changed := false
	if existingCondition.Status != newCondition.Status {
		changed = true
		existingCondition.Status = newCondition.Status
		existingCondition.LastTransitionTime = metav1.NewTime(time.Now())
	}

	if existingCondition.Reason != newCondition.Reason {
		changed = true
		existingCondition.Reason = newCondition.Reason
	}
	if existingCondition.Message != newCondition.Message {
		changed = true
		existingCondition.Message = newCondition.Message
	}
	return changed
}

// FindStatusCondition finds the conditionType in conditions.
func FindStatusCondition(conditions []Condition, conditionType ConditionType) *Condition {
	for i := range conditions {
		if conditions[i].Type == conditionType {
			return &conditions[i]
		}
	}

	return nil
}

// IsStatusConditionTrue returns true when the conditionType is present and set to `corev1.ConditionTrue`
func IsStatusConditionTrue(conditions []Condition, conditionType ConditionType) bool {
	return IsStatusConditionPresentAndEqual(conditions, conditionType, corev1.ConditionTrue)
}

// IsStatusConditionFalse returns true when the conditionType is present and set to `corev1.ConditionFalse`
func IsStatusConditionFalse(conditions []Condition, conditionType ConditionType) bool {
	return IsStatusConditionPresentAndEqual(conditions, conditionType, corev1.ConditionFalse)
}

// IsStatusConditionUnknown returns true when the conditionType is present and set to `corev1.ConditionUnknown`
func IsStatusConditionUnknown(conditions []Condition, conditionType ConditionType) bool {
	return IsStatusConditionPresentAndEqual(conditions, conditionType, corev1.ConditionUnknown)
}

// IsStatusConditionPresentAndEqual returns true when conditionType is present and equal to status.
func IsStatusConditionPresentAndEqual(conditions []Condition, conditionType ConditionType, status corev1.ConditionStatus) bool {
	for _, condition := range conditions {
		if condition.Type == conditionType {
			return condition.Status == status
		}
	}
	return false
}


text:
from django.core.files.storage import default_storage as storage

import basket

import olympia.core.logger

from olympia.amo.celery import task
from olympia.amo.decorators import set_modified_on
from olympia.amo.templatetags.jinja_helpers import user_media_path
from olympia.amo.utils import resize_image

from .models import UserProfile

task_log = olympia.core.logger.getLogger('z.task')

@task
def delete_photo(dst, **kw):
    task_log.debug('[1@None] Deleting photo: %s.' % dst)

    if not dst.startswith(user_media_path('userpics')):
        task_log.error("Someone tried deleting something they shouldn't: %s"
                       % dst)
        return

    try:
        storage.delete(dst)
    except Exception, e:
        task_log.error("Error deleting userpic: %s" % e)

@task
@set_modified_on
def resize_photo(src, dst, locally=False, **kw):
    """Resizes userpics to 200x200"""
    task_log.debug('[1@None] Resizing photo: %s' % dst)

    try:
        resize_image(src, dst, (200, 200))
        return True
    except Exception, e:
        task_log.error("Error saving userpic: %s" % e)

@task(rate_limit='15/m')
def update_user_ratings_task(data, **kw):
    task_log.info("[%s@%s] Updating add-on author's ratings." %
                  (len(data), update_user_ratings_task.rate_limit))
    for pk, rating in data:
        UserProfile.objects.filter(pk=pk).update(
            averagerating=round(rating, 2))

@task(rate_limit='250/m')
def sync_user_with_basket(user_profile_id):
    user = UserProfile.objects.get(pk=user_profile_id)
    if user.basket_token:
        return

    try:
        data = basket.lookup_user(user.email)
        user.update(basket_token=data['token'])
        return True
    except Exception as exc:
        acceptable_errors = (
            basket.errors.BASKET_INVALID_EMAIL,
            basket.errors.BASKET_UNKNOWN_EMAIL)

        if getattr(exc, 'code', None) not in acceptable_errors:
            task_log.exception(
                'sync_user_with_basket() failed with error: {}, retrying'
                .format(exc))
            return sync_user_with_basket.retry(exc=exc, max_retries=3)


text:
export * from './BottomToolbar';
export * from './AutoformControls';

export * from './I18nTools';
export * from './DuplicateButton';
export * from './Trash';
export * from './ImageUpload';
export * from './SelectParentButton';
export * from './PluginDrawer';
export * from './ThemeProvider';
export * from './ColorPicker';
export * from './Sidebar';


text:
import { RouterModule } from '@angular/router'

import { HomeComponent } from "./home/home.component"
import { AboutComponent } from "./about/about.component"
import { ExperimentsComponent } from "./experiments/experiments.component"

const routes  =  [
  {path: '',            component: HomeComponent },
  {path: 'home',        component: HomeComponent },
  {path: 'about',      component: AboutComponent },
  {path: 'experiments', component: ExperimentsComponent },
  {path: '*',           component: HomeComponent }
]

export const APP_ROUTES = [
  RouterModule.forRoot(routes)
]


text:
<md-card layout-padding style="padding-left: 6%; padding-right: 6%; padding-bottom: 4%; padding-top: 3%">
    <form layout="column" ng-submit="cadastrarRefeicao.cadastrar(cadastrarRefeicao.refeicao)">

        <md-input-container class="md-icon-float md-block">
            Nome
            <input ng-model="cadastrarRefeicao.refeicao.tipo" type="text" required>
        </md-input-container>

        <md-input-container flex-gt-md="30">
            Horário de Início
            <input mdc-datetime-picker date="false" time="true" type="text" id="time" short-time="true" placeholder="hh:mm:ss" min-date="minDate" format="hh:mm:ss" ng-model="cadastrarRefeicao.refeicao.horaInicio" required>
        </md-input-container>

        <md-input-container flex-gt-md="30">
            Horário de Fim
            <input mdc-datetime-picker date="false" time="true" type="text" id="time" short-time="true" placeholder="hh:mm:ss" min-date="minDate" format="hh:mm:ss" ng-model="cadastrarRefeicao.refeicao.horaFinal" required>
        </md-input-container>

        <md-input-container class="md-icon-float md-block">
            Custo
            <input currency-mask ng-model="cadastrarRefeicao.refeicao.custo"/>
        </md-input-container>

        <md-input-container flex-gt-md="30">
            Previsão da Pretensão
            <input mdc-datetime-picker date="false" time="true" type="text" id="time" short-time="true" placeholder="hh:mm:ss" min-date="minDate" format="hh:mm:ss" ng-model="cadastrarRefeicao.refeicao.horaPrevisaoPretensao" required>

Tempo em horas, minutos e segundos que antecede a Refeição e permite ao beneficiário solicitar a Pretensão.

        </md-input-container>

        <md-button type="submit" layout-fill type="submit" class="md-raised md-primary md-hue-1 flex" style="margin-top: 40px">Cadastrar Refeição</md-button>
    </form>
</md-card>


text:
Portfolio

Ce portfolio est un projet personnel développé principalement avec AngularJS. On peut noter aussi l'utilisation de Material Design de Google.
    L'objectif est de se familiariser avec le développement AngularJS en mettant en avant mon parcours professionnel ainsi que mes projets personnels.


text:
using System;
using System.Linq;
using System.Management.Automation;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell.Commands.Internal.Format;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// Gets formatting information from the loading
    /// format information database
    /// </summary>
    /// <remarks>Currently supports only table controls
    /// </remarks>
    [Cmdlet(VerbsCommon.Get, "FormatData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=144303")]
    [OutputType(typeof(System.Management.Automation.ExtendedTypeDefinition))]
    public class GetFormatDataCommand : PSCmdlet
    {
        private string[] _typename;
        private WildcardPattern[] _filter = new WildcardPattern[1];

        /// <summary>
        /// Get Formatting information only for the specified
        /// typename
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        [ValidateNotNullOrEmpty]
        [Parameter(Position = 0)]
        public String[] TypeName
        {
            get
            {
                return _typename;
            }
            set
            {
                _typename = value;

                if (_typename == null)
                {
                    _filter = Utils.EmptyArray<WildcardPattern>();
                }
                else
                {
                    _filter = new WildcardPattern[_typename.Length];
                    for (int i = 0; i < _filter.Length; i++)
                    {
                        _filter[i] = WildcardPattern.Get(_typename[i],
                            WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
                    }
                }
            }
        }

        /// <summary>
        /// When specified, helps control whether or not to send richer formatting data
        /// that was not supported by earlier versions of PowerShell.
        /// </summary>
        [Parameter]
        public Version PowerShellVersion { get; set; }

        /// <summary>
        /// set the default filter
        /// </summary>
        protected override void BeginProcessing()
        {
            if (_filter[0] == null)
            {
                _filter[0] = WildcardPattern.Get("*", WildcardOptions.None);
            }
        }

        private static Dictionary<string, List<string>> GetTypeGroupMap(IEnumerable<TypeGroupDefinition> groupDefinitions)
        {
            var typeGroupMap = new Dictionary<string, List<string>>();
            foreach (TypeGroupDefinition typeGroup in groupDefinitions)
            {
                // The format system actually allows you to define multiple SelectionSets with the same name, but only the
                // first type group will take effect. So we skip the rest groups that have the same name.
                if (!typeGroupMap.ContainsKey(typeGroup.name))
                {
                    var typesInGroup = typeGroup.typeReferenceList.Select(typeReference => typeReference.name).ToList();
                    typeGroupMap.Add(typeGroup.name, typesInGroup);
                }
            }

            return typeGroupMap;
        }

        /// <summary>
        /// Takes out the content from the database and writes them
        /// out
        /// </summary>
        protected override void ProcessRecord()
        {
            bool writeOldWay = PowerShellVersion == null ||
                               PowerShellVersion.Major < 5 ||
                               PowerShellVersion.Build < 11086;

            TypeInfoDataBase db = this.Context.FormatDBManager.Database;

            List<ViewDefinition> viewdefinitions = db.viewDefinitionsSection.viewDefinitionList;
            Dictionary<string, List<string>> typeGroupMap = GetTypeGroupMap(db.typeGroupSection.typeGroupDefinitionList);

            var typedefs = new Dictionary<ConsolidatedString, List<FormatViewDefinition>>(ConsolidatedString.EqualityComparer);

            foreach (ViewDefinition definition in viewdefinitions)
            {
                if (definition.isHelpFormatter)
                    continue;

                var consolidatedTypeName = CreateConsolidatedTypeName(definition, typeGroupMap);

                if (!ShouldGenerateView(consolidatedTypeName))
                    continue;

                PSControl control;

                var tableControlBody = definition.mainControl as TableControlBody;
                if (tableControlBody != null)
                {
                    control = new TableControl(tableControlBody, definition);
                }
                else
                {
                    var listControlBody = definition.mainControl as ListControlBody;
                    if (listControlBody != null)
                    {
                        control = new ListControl(listControlBody, definition);
                    }
                    else
                    {
                        var wideControlBody = definition.mainControl as WideControlBody;
                        if (wideControlBody != null)
                        {
                            control = new WideControl(wideControlBody, definition);
                            if (writeOldWay)
                            {
                                // Alignment was added to WideControl in V2, but wasn't
                                // used.  It was removed in V5, but old PowerShell clients
                                // expect this property or fail to rehydrate the remote object.
                                var psobj = new PSObject(control);
                                psobj.Properties.Add(new PSNoteProperty("Alignment", 0));
                            }
                        }
                        else
                        {
                            var complexControlBody = (ComplexControlBody)definition.mainControl;
                            control = new CustomControl(complexControlBody, definition);
                        }
                    }
                }

                // Older version of PowerShell do not know about something in the control, so
                // don't return it.
                if (writeOldWay && !control.CompatibleWithOldPowerShell())
                    continue;

                var formatdef = new FormatViewDefinition(definition.name, control, definition.InstanceId);

                List<FormatViewDefinition> viewList;
                if (!typedefs.TryGetValue(consolidatedTypeName, out viewList))
                {
                    viewList = new List<FormatViewDefinition>();
                    typedefs.Add(consolidatedTypeName, viewList);
                }
                viewList.Add(formatdef);
            }// foreach(ViewDefinition...

            // write out all the available type definitions
            foreach (var pair in typedefs)
            {
                var typeNames = pair.Key;

                if (writeOldWay)
                {
                    foreach (var typeName in typeNames)
                    {
                        var etd = new ExtendedTypeDefinition(typeName, pair.Value);
                        WriteObject(etd);
                    }
                }
                else
                {
                    var etd = new ExtendedTypeDefinition(typeNames[0], pair.Value);
                    for (int i = 1; i < typeNames.Count; i++)
                    {
                        etd.TypeNames.Add(typeNames[i]);
                    }
                    WriteObject(etd);
                }
            }
        }

        private static ConsolidatedString CreateConsolidatedTypeName(ViewDefinition definition, Dictionary<string, List<string>> typeGroupMap)
        {
            // Create our "consolidated string" typename which is used as a dictionary key
            var reflist = definition.appliesTo.referenceList;
            var consolidatedTypeName = new ConsolidatedString(ConsolidatedString.Empty);

            foreach (TypeOrGroupReference item in reflist)
            {
                // If it's a TypeGroup, we need to look that up and add it's members
                if (item is TypeGroupReference)
                {
                    List<string> typesInGroup;
                    if (typeGroupMap.TryGetValue(item.name, out typesInGroup))
                    {
                        foreach (string typeName in typesInGroup)
                        {
                            consolidatedTypeName.Add(typeName);
                        }
                    }
                }
                else
                {
                    consolidatedTypeName.Add(item.name);
                }
            }
            return consolidatedTypeName;
        }

        private bool ShouldGenerateView(ConsolidatedString consolidatedTypeName)
        {
            foreach (WildcardPattern pattern in _filter)
            {
                foreach (var typeName in consolidatedTypeName)
                {
                    if (pattern.IsMatch(typeName))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}


text:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.

#ifndef PX_VEHICLE_NWDRIVE_H
#define PX_VEHICLE_NWDRIVE_H
/** \addtogroup vehicle
  @{
*/

#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleComponents.h"

#if !PX_DOXYGEN
namespace physx
{
#endif

struct PxFilterData;
class PxGeometry;
class PxPhysics;
class PxVehicleDrivableSurfaceToTireFrictionPairs;
class PxShape;
class PxMaterial;
class PxRigidDynamic;

/**
\brief Data structure describing configuration data of a vehicle with up to PX_MAX_NB_WHEELS driven equally through the differential. The vehicle has an
engine, clutch, gears, autobox, differential.
@see PxVehicleDriveSimData
*/
class PxVehicleDriveSimDataNW : public PxVehicleDriveSimData
{
//= ATTENTION! =====================================================================================
// Changing the data layout of this class breaks the binary serialization format.  See comments for
// PX_BINARY_SERIAL_VERSION.  If a modification is required, please adjust the getBinaryMetaData
// function.  If the modification is made on a custom branch, please change PX_BINARY_SERIAL_VERSION
// accordingly.
//==================================================================================================
public:

	friend class PxVehicleDriveNW;

	PxVehicleDriveSimDataNW()
		: PxVehicleDriveSimData()
	{
	}

	/**
	\brief Return the data describing the differential of a vehicle with up to PX_MAX_NB_WHEELS driven wheels.
	*/
	const PxVehicleDifferentialNWData& getDiffData()  const
	{
		return mDiff;
	}

	/**
	\brief Set the data describing the differential of a vehicle with up to PX_MAX_NB_WHEELS driven wheels.
	The differential data describes the set of wheels that are driven by the differential.
	*/
	void setDiffData(const PxVehicleDifferentialNWData& diff);

private:

	/**
	\brief Differential simulation data
	@see setDiffData, getDiffData
	*/
	PxVehicleDifferentialNWData mDiff;

	/**
	\brief Test if the NW-drive simulation data has been setup with legal data.
	Call only after setting all components.
	@see setEngineData, setClutchData, setGearsData, setAutoboxData, setDiffData, setAckermannGeometryData
	*/
	bool isValid() const;

//serialization
public:
	PxVehicleDriveSimDataNW(const PxEMPTY) : PxVehicleDriveSimData(PxEmpty), mDiff(PxEmpty) {}
	static void getBinaryMetaData(PxOutputStream& stream);
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveSimDataNW) & 15));

/**
\brief The control inputs for a PxVehicleDriveNW.

@see PxVehicleDriveDynData::setAnalogInput, PxVehicleDriveDynData::getAnalogInput
*/
struct PxVehicleDriveNWControl
{
	enum Enum
	{
		eANALOG_INPUT_ACCEL=0,
		eANALOG_INPUT_BRAKE,
		eANALOG_INPUT_HANDBRAKE,
		eANALOG_INPUT_STEER_LEFT,
		eANALOG_INPUT_STEER_RIGHT,
		eMAX_NB_DRIVENW_ANALOG_INPUTS
	};
};

/**
\brief Data structure with instanced dynamics data and configuration data of a vehicle with up to PX_MAX_NB_WHEELS driven wheels.
*/
class PxVehicleDriveNW : public PxVehicleDrive
{
//= ATTENTION! =====================================================================================
// Changing the data layout of this class breaks the binary serialization format.  See comments for
// PX_BINARY_SERIAL_VERSION.  If a modification is required, please adjust the getBinaryMetaData
// function.  If the modification is made on a custom branch, please change PX_BINARY_SERIAL_VERSION
// accordingly.
//==================================================================================================
public:

	friend class PxVehicleUpdate;

	/**
	\brief Allocate a PxVehicleDriveNW instance for a NWDrive vehicle with nbWheels

	\param[in] nbWheels is the number of wheels on the vehicle.

	\return The instantiated vehicle.

	@see free, setup
	*/
	static PxVehicleDriveNW* allocate(const PxU32 nbWheels);

	/**
	\brief Deallocate a PxVehicleDriveNW instance.
	@see allocate
	*/
	void free();

	/**
	\brief Set up a vehicle using simulation data for the wheels and drive model.
	\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
	\param[in] vehActor is a PxRigidDynamic instance that is used to represent the vehicle in the PhysX SDK.
	\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the vehicle. The vehicle instance takes a copy of this data.
	\param[in] driveData describes the properties of the vehicle's drive model (gears/engine/clutch/differential/autobox).  The vehicle instance takes a copy of this data.
	\param[in] nbWheels is the number of wheels on the vehicle.
	\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes.  To break this assumption use PxVehicleWheelsSimData::setWheelShapeMapping.
	@see allocate, free, setToRestState, PxVehicleWheelsSimData::setWheelShapeMapping
	*/
	void setup
		(PxPhysics* physics, PxRigidDynamic* vehActor,
		 const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimDataNW& driveData,
		 const PxU32 nbWheels);

	/**
	\brief Allocate and set up a vehicle using simulation data for the wheels and drive model.
	\param[in] physics is a PxPhysics instance that is needed to create special vehicle constraints that are maintained by the vehicle.
	\param[in] vehActor is a PxRigidDynamic instance that is used to represent the vehicle in the PhysX SDK.
	\param[in] wheelsData describes the configuration of all suspension/tires/wheels of the vehicle. The vehicle instance takes a copy of this data.
	\param[in] driveData describes the properties of the vehicle's drive model (gears/engine/clutch/differential/autobox).  The vehicle instance takes a copy of this data.
	\param[in] nbWheels is the number of wheels on the vehicle.
	\note It is assumed that the first shapes of the actor are the wheel shapes, followed by the chassis shapes.  To break this assumption use PxVehicleWheelsSimData::setWheelShapeMapping.
	\return The instantiated vehicle.
	@see allocate, free, setToRestState, PxVehicleWheelsSimData::setWheelShapeMapping
	*/
	static PxVehicleDriveNW* create
		(PxPhysics* physics, PxRigidDynamic* vehActor,
		 const PxVehicleWheelsSimData& wheelsData, const PxVehicleDriveSimDataNW& driveData,
		 const PxU32 nbWheels);

	/**
	\brief Set a vehicle to its rest state.  Aside from the rigid body transform, this will set the vehicle and rigid body
	to the state they were in immediately after setup or create.
	\note Calling setToRestState invalidates the cached raycast hit planes under each wheel meaning that suspension line
	raycasts need to be performed at least once with PxVehicleSuspensionRaycasts before calling PxVehicleUpdates.
	@see setup, create, PxVehicleSuspensionRaycasts, PxVehicleUpdates
	*/
	void setToRestState();

	/**
	\brief Simulation data that describes the configuration of the vehicle's drive model.
	@see setup, create
	*/
	PxVehicleDriveSimDataNW mDriveSimData;

private:

	/**
	\brief Test if the instanced dynamics and configuration data has legal values.
	*/
	bool isValid() const;

//serialization
public:
								PxVehicleDriveNW(PxBaseFlags baseFlags) : PxVehicleDrive(baseFlags), mDriveSimData(PxEmpty) {}
								PxVehicleDriveNW();
								~PxVehicleDriveNW(){}
	static	PxVehicleDriveNW*	createObject(PxU8*& address, PxDeserializationContext& context);
	static	void				getBinaryMetaData(PxOutputStream& stream);
	virtual	const char*			getConcreteTypeName() const			{ return "PxVehicleDriveNW";	}
	virtual	bool				isKindOf(const char* name)	const	{ return !::strcmp("PxVehicleDriveNW", name) || PxBase::isKindOf(name); }
//~serialization
};
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxVehicleDriveNW) & 15));

#if !PX_DOXYGEN
} // namespace physx
#endif

/** @} */
#endif //PX_VEHICLE_NWDRIVE_H


text:
//
//  GDataEntryContact.h
//

#import "GDataEntryBase.h"
#import "GDataOrganization.h"
#import "GDataEmail.h"
#import "GDataIM.h"
#import "GDataPhoneNumber.h"
#import "GDataPostalAddress.h"
#import "GDataCategory.h"
#import "GDataExtendedProperty.h"
#import "GDataGroupMembershipInfo.h"

#undef _EXTERN
#undef _INITIALIZE_AS
#ifdef GDATAENTRYCONTACT_DEFINE_GLOBALS
#define _EXTERN
#define _INITIALIZE_AS(x) =x
#else
#define _EXTERN extern
#define _INITIALIZE_AS(x)
#endif

_EXTERN NSString* kGDataNamespaceContact _INITIALIZE_AS(@"http://schemas.google.com/contact/2008");
_EXTERN NSString* kGDataNamespaceContactPrefix _INITIALIZE_AS(@"gContact");

_EXTERN NSString* kGDataCategoryContact      _INITIALIZE_AS(@"http://schemas.google.com/contact/2008#contact");
_EXTERN NSString* kGDataCategoryContactGroup _INITIALIZE_AS(@"http://schemas.google.com/contact/2008#group");

// rel values
_EXTERN NSString* kGDataContactHome    _INITIALIZE_AS(@"http://schemas.google.com/g/2005#home");
_EXTERN NSString* kGDataContactWork    _INITIALIZE_AS(@"http://schemas.google.com/g/2005#work");
_EXTERN NSString* kGDataContactOther   _INITIALIZE_AS(@"http://schemas.google.com/g/2005#other");

// link rel values
_EXTERN NSString* kGDataContactPhotoRel     _INITIALIZE_AS(@"http://schemas.google.com/contacts/2008/rel#photo");
_EXTERN NSString* kGDataContactEditPhotoRel _INITIALIZE_AS(@"http://schemas.google.com/contacts/2008/rel#edit-photo");

@interface GDataEntryContact : GDataEntryBase {
}

+ (NSDictionary *)contactNamespaces;

+ (GDataEntryContact *)contactEntryWithTitle:(NSString *)title;

// each type of contact data includes convenience methods for getting or
// setting a primary element.

- (NSArray *)organizations;
- (void)setOrganizations:(NSArray *)array;
- (void)addOrganization:(GDataOrganization *)obj;
- (void)removeOrganization:(GDataOrganization *)obj;

- (GDataOrganization *)primaryOrganization;
- (void)setPrimaryOrganization:(GDataOrganization *)obj;

- (NSArray *)emailAddresses;
- (void)setEmailAddresses:(NSArray *)array;
- (void)addEmailAddress:(GDataEmail *)obj;
- (void)removeEmailAddress:(GDataEmail *)obj;

- (GDataEmail *)primaryEmailAddress;
- (void)setPrimaryEmailAddress:(GDataEmail *)obj;

- (NSArray *)IMAddresses;
- (void)setIMAddresses:(NSArray *)array;
- (void)addIMAddress:(GDataIM *)obj;
- (void)removeIMAddress:(GDataIM *)obj;

- (GDataIM *)primaryIMAddress;
- (void)setPrimaryIMAddress:(GDataIM *)obj;

- (NSArray *)phoneNumbers;
- (void)setPhoneNumbers:(NSArray *)array;
- (void)addPhoneNumber:(GDataPhoneNumber *)obj;
- (void)removePhoneNumber:(GDataPhoneNumber *)obj;

- (GDataPhoneNumber *)primaryPhoneNumber;
- (void)setPrimaryPhoneNumber:(GDataPhoneNumber *)obj;

- (NSArray *)postalAddresses;
- (void)setPostalAddresses:(NSArray *)array;
- (void)addPostalAddress:(GDataPostalAddress *)obj;
- (void)removePostalAddress:(GDataPostalAddress *)obj;

- (GDataPostalAddress *)primaryPostalAddress;
- (void)setPrimaryPostalAddress:(GDataPostalAddress *)obj;

- (NSArray *)groupMembershipInfos;
- (void)setGroupMembershipInfos:(NSArray *)arr;
- (void)addGroupMembershipInfo:(GDataGroupMembershipInfo *)obj;
- (void)removeGroupMembershipInfo:(GDataGroupMembershipInfo *)obj;

- (NSArray *)extendedProperties;
- (void)setExtendedProperties:(NSArray *)arr;
- (void)addExtendedProperty:(GDataExtendedProperty *)obj;
- (void)removeExtendedProperty:(GDataExtendedProperty *)obj;

// convenience accessors
- (GDataExtendedProperty *)extendedPropertyForName:(NSString *)name;

- (GDataLink *)photoLink;
- (GDataLink *)editPhotoLink;
@end


text:
package logbook.gui.listener;

import logbook.gui.CreateShipReportTable;

import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Shell;

/**
 * 建造報告書ボタンのリスナー
 *
 */
public final class CreateShipReportAdapter extends AbstractReportAdapter {

    /**
     * @param shell シェル
     */
    public CreateShipReportAdapter(Shell shell) {
        super(shell);
    }

    @Override
    public void widgetSelected(SelectionEvent paramSelectionEvent) {
        new CreateShipReportTable(this.shell).open();
    }
}


text:
angular.module('factories').factory('Pagination', function () {

  return function(apiResponse) {

    this.page       = apiResponse.config.params.page || 1;
    this.perPage    = apiResponse.config.params.per_page || 25;
    this.totalItems = apiResponse.headers()['total-items'];
    this.totalPages = apiResponse.headers()['total-pages'];

  };

});


text:
import * as React from 'react';
import * as Utils from '../lib/Utils';
import { ExperimentList, ExperimentListProps } from './ExperimentList';
import TestUtils from '../TestUtils';
import { ApiFilter, PredicateOp } from '../apis/filter';
import { RunStorageState } from '../apis/run';
import { ExperimentStorageState } from '../apis/experiment';
import { ExpandState } from './CustomTable';

import { Apis, ExperimentSortKeys, ListRequest } from '../lib/Apis';
import { ReactWrapper, ShallowWrapper, shallow } from 'enzyme';
import { range } from 'lodash';

class ExperimentListTest extends ExperimentList {
  public _loadExperiments(request: ListRequest): Promise<string> {
    return super._loadExperiments(request);
  }
}

describe('ExperimentList', () => {
  let tree: ShallowWrapper | ReactWrapper;

  const onErrorSpy = jest.fn();
  const listExperimentsSpy = jest.spyOn(Apis.experimentServiceApi, 'listExperiment');
  const getExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'getExperiment');
  // We mock this because it uses toLocaleDateString, which causes mismatches between local and CI
  // test enviroments
  const formatDateStringSpy = jest.spyOn(Utils, 'formatDateString');
  const listRunsSpy = jest.spyOn(Apis.runServiceApi, 'listRuns');

  function generateProps(): ExperimentListProps {
    return {
      history: {} as any,
      location: { search: '' } as any,
      match: '' as any,
      onError: onErrorSpy,
    };
  }

  function mockNExperiments(n: number): void {
    getExperimentSpy.mockImplementation(id =>
      Promise.resolve({
        id: 'testexperiment' + id,
        name: 'experiment with id: testexperiment' + id,
      }),
    );
    listExperimentsSpy.mockImplementation(() =>
      Promise.resolve({
        experiments: range(1, n + 1).map(i => {
          return {
            id: 'testexperiment' + i,
            name: 'experiment with id: testexperiment' + i,
          };
        }),
      }),
    );
  }

  beforeEach(() => {
    formatDateStringSpy.mockImplementation((date?: Date) => {
      return date ? '1/2/2019, 12:34:56 PM' : '-';
    });
    onErrorSpy.mockClear();
    listExperimentsSpy.mockClear();
    getExperimentSpy.mockClear();
  });

  afterEach(async () => {
    // unmount() should be called before resetAllMocks() in case any part of the unmount life cycle
    // depends on mocks/spies
    if (tree) {
      await tree.unmount();
    }
    jest.resetAllMocks();
  });

  it('renders the empty experience', () => {
    expect(shallow(<ExperimentList {...generateProps()} />)).toMatchSnapshot();
  });

  it('renders the empty experience in ARCHIVED state', () => {
    const props = generateProps();
    props.storageState = ExperimentStorageState.ARCHIVED;
    expect(shallow(<ExperimentList {...props} />)).toMatchSnapshot();
  });

  it('loads experiments whose storage state is not ARCHIVED when storage state equals AVAILABLE', async () => {
    mockNExperiments(1);
    const props = generateProps();
    props.storageState = ExperimentStorageState.AVAILABLE;
    tree = shallow(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentListTest)._loadExperiments({});
    expect(Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(
      undefined,
      undefined,
      undefined,
      encodeURIComponent(
        JSON.stringify({
          predicates: [
            {
              key: 'storage_state',
              op: PredicateOp.NOTEQUALS,
              string_value: ExperimentStorageState.ARCHIVED.toString(),
            },
          ],
        } as ApiFilter),
      ),
      undefined,
      undefined,
    );
  });

  it('loads experiments whose storage state is ARCHIVED when storage state equals ARCHIVED', async () => {
    mockNExperiments(1);
    const props = generateProps();
    props.storageState = ExperimentStorageState.ARCHIVED;
    tree = shallow(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentListTest)._loadExperiments({});
    expect(Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(
      undefined,
      undefined,
      undefined,
      encodeURIComponent(
        JSON.stringify({
          predicates: [
            {
              key: 'storage_state',
              op: PredicateOp.EQUALS,
              string_value: ExperimentStorageState.ARCHIVED.toString(),
            },
          ],
        } as ApiFilter),
      ),
      undefined,
      undefined,
    );
  });

  it('augments request filter with storage state predicates', async () => {
    mockNExperiments(1);
    const props = generateProps();
    props.storageState = ExperimentStorageState.ARCHIVED;
    tree = shallow(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentListTest)._loadExperiments({
      filter: encodeURIComponent(
        JSON.stringify({
          predicates: [{ key: 'k', op: 'op', string_value: 'val' }],
        }),
      ),
    });
    expect(Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(
      undefined,
      undefined,
      undefined,
      encodeURIComponent(
        JSON.stringify({
          predicates: [
            {
              key: 'k',
              op: 'op',
              string_value: 'val',
            },
            {
              key: 'storage_state',
              op: PredicateOp.EQUALS,
              string_value: ExperimentStorageState.ARCHIVED.toString(),
            },
          ],
        } as ApiFilter),
      ),
      undefined,
      undefined,
    );
  });

  it('loads one experiment', async () => {
    mockNExperiments(1);
    const props = generateProps();
    tree = shallow(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentListTest)._loadExperiments({});
    expect(Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
    );
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('reloads the experiment when refresh is called', async () => {
    mockNExperiments(0);
    const props = generateProps();
    tree = TestUtils.mountWithRouter(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentList).refresh();
    tree.update();
    expect(Apis.experimentServiceApi.listExperiment).toHaveBeenCalledTimes(2);
    expect(Apis.experimentServiceApi.listExperiment).toHaveBeenLastCalledWith(
      '',
      10,
      ExperimentSortKeys.CREATED_AT + ' desc',
      '',
      undefined,
      undefined,
    );
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('loads multiple experiments', async () => {
    mockNExperiments(5);
    const props = generateProps();
    tree = shallow(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentListTest)._loadExperiments({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('calls error callback when loading experiment fails', async () => {
    TestUtils.makeErrorResponseOnce(
      jest.spyOn(Apis.experimentServiceApi, 'listExperiment'),
      'bad stuff happened',
    );
    const props = generateProps();
    tree = shallow(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentListTest)._loadExperiments({});
    expect(props.onError).toHaveBeenLastCalledWith(
      'Error: failed to list experiments: ',
      new Error('bad stuff happened'),
    );
  });

  it('loads runs for a given experiment id when it is expanded', async () => {
    listRunsSpy.mockImplementation(() => {});
    mockNExperiments(1);
    const props = generateProps();
    tree = TestUtils.mountWithRouter(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentListTest)._loadExperiments({});
    tree.update();
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree.state()).toHaveProperty('displayExperiments', [
      {
        expandState: ExpandState.COLLAPSED,
        id: 'testexperiment1',
        name: 'experiment with id: testexperiment1',
      },
    ]);
    // Expand the first experiment
    tree
      .find('button[aria-label="Expand"]')
      .at(0)
      .simulate('click');
    await listRunsSpy;
    tree.update();
    expect(tree.state()).toHaveProperty('displayExperiments', [
      {
        expandState: ExpandState.EXPANDED,
        id: 'testexperiment1',
        name: 'experiment with id: testexperiment1',
      },
    ]);
    expect(Apis.runServiceApi.listRuns).toHaveBeenCalledTimes(1);
    expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
      '',
      10,
      'created_at desc',
      'EXPERIMENT',
      'testexperiment1',
      encodeURIComponent(
        JSON.stringify({
          predicates: [
            {
              key: 'storage_state',
              op: PredicateOp.NOTEQUALS,
              string_value: RunStorageState.ARCHIVED.toString(),
            },
          ],
        } as ApiFilter),
      ),
    );
  });

  it('loads runs for a given experiment id with augumented storage state when it is expanded', async () => {
    listRunsSpy.mockImplementation(() => {});
    mockNExperiments(1);
    const props = generateProps();
    props.storageState = ExperimentStorageState.ARCHIVED;
    tree = TestUtils.mountWithRouter(<ExperimentList {...props} />);
    await (tree.instance() as ExperimentListTest)._loadExperiments({});
    tree.update();
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree.state()).toHaveProperty('displayExperiments', [
      {
        expandState: ExpandState.COLLAPSED,
        id: 'testexperiment1',
        name: 'experiment with id: testexperiment1',
      },
    ]);
    // Expand the first experiment
    tree
      .find('button[aria-label="Expand"]')
      .at(0)
      .simulate('click');
    await listRunsSpy;
    tree.update();
    expect(tree.state()).toHaveProperty('displayExperiments', [
      {
        expandState: ExpandState.EXPANDED,
        id: 'testexperiment1',
        name: 'experiment with id: testexperiment1',
      },
    ]);
    expect(Apis.runServiceApi.listRuns).toHaveBeenCalledTimes(1);
    expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
      '',
      10,
      'created_at desc',
      'EXPERIMENT',
      'testexperiment1',
      encodeURIComponent(
        JSON.stringify({
          predicates: [
            {
              key: 'storage_state',
              op: PredicateOp.EQUALS,
              string_value: RunStorageState.ARCHIVED.toString(),
            },
          ],
        } as ApiFilter),
      ),
    );
  });
});


text:
namespace settings {

ResetSettingsHandler::ResetSettingsHandler(
    Profile* profile, bool allow_powerwash)
    : profile_(profile), weak_ptr_factory_(this) {
#if defined(OS_CHROMEOS)
  allow_powerwash_ = allow_powerwash;
#endif  // defined(OS_CHROMEOS)
  google_brand::GetBrand(&brandcode_);
}

ResetSettingsHandler::~ResetSettingsHandler() {}

ResetSettingsHandler* ResetSettingsHandler::Create(
    content::WebUIDataSource* html_source, Profile* profile) {
  bool allow_powerwash = false;
#if defined(OS_CHROMEOS)
  policy::BrowserPolicyConnectorChromeOS* connector =
      g_browser_process->platform_part()->browser_policy_connector_chromeos();
  allow_powerwash = !connector->IsEnterpriseManaged() &&
      !user_manager::UserManager::Get()->IsLoggedInAsGuest() &&
      !user_manager::UserManager::Get()->IsLoggedInAsSupervisedUser();
  html_source->AddBoolean("allowPowerwash", allow_powerwash);
#endif  // defined(OS_CHROMEOS)

  bool show_reset_profile_banner = false;
  static const int kBannerShowTimeInDays = 5;
  const base::Time then = chrome_prefs::GetResetTime(profile);
  if (!then.is_null()) {
    show_reset_profile_banner =
        (base::Time::Now() - then).InDays() < kBannerShowTimeInDays;
  }
  html_source->AddBoolean("showResetProfileBanner", show_reset_profile_banner);

  // Inject |allow_powerwash| for testing.
  return new ResetSettingsHandler(profile, allow_powerwash);
}

void ResetSettingsHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback("performResetProfileSettings",
      base::Bind(&ResetSettingsHandler::HandleResetProfileSettings,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("onShowResetProfileDialog",
      base::Bind(&ResetSettingsHandler::OnShowResetProfileDialog,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("onHideResetProfileDialog",
      base::Bind(&ResetSettingsHandler::OnHideResetProfileDialog,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("onHideResetProfileBanner",
      base::Bind(&ResetSettingsHandler::OnHideResetProfileBanner,
                 base::Unretained(this)));
#if defined(OS_CHROMEOS)
  web_ui()->RegisterMessageCallback(
       "onPowerwashDialogShow",
       base::Bind(&ResetSettingsHandler::OnShowPowerwashDialog,
                  base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "requestFactoryResetRestart",
      base::Bind(&ResetSettingsHandler::HandleFactoryResetRestart,
                 base::Unretained(this)));
#endif  // defined(OS_CHROMEOS)
}

void ResetSettingsHandler::HandleResetProfileSettings(
    const base::ListValue* value) {
  bool send_settings = false;
  bool success = value->GetBoolean(0, &send_settings);
  DCHECK(success);

  DCHECK(brandcode_.empty() || config_fetcher_);
  if (config_fetcher_ && config_fetcher_->IsActive()) {
    // Reset once the prefs are fetched.
    config_fetcher_->SetCallback(
        base::Bind(&ResetSettingsHandler::ResetProfile,
                   base::Unretained(this),
                   send_settings));
  } else {
    ResetProfile(send_settings);
  }
}

void ResetSettingsHandler::OnResetProfileSettingsDone(
    bool send_feedback) {
  web_ui()->CallJavascriptFunction("SettingsResetPage.doneResetting");
  if (send_feedback && setting_snapshot_) {
    ResettableSettingsSnapshot current_snapshot(profile_);
    int difference = setting_snapshot_->FindDifferentFields(current_snapshot);
    if (difference) {
      setting_snapshot_->Subtract(current_snapshot);
      std::string report = SerializeSettingsReport(*setting_snapshot_,
                                                   difference);
      SendSettingsFeedback(report, profile_);

      // Send the same report as a protobuf to a different endpoint.
      scoped_ptr<reset_report::ChromeResetReport> report_proto =
          SerializeSettingsReportToProto(*setting_snapshot_, difference);
      if (report_proto)
        SendSettingsFeedbackProto(*report_proto, profile_);
    }
  }
  setting_snapshot_.reset();
}

void ResetSettingsHandler::OnShowResetProfileDialog(
    const base::ListValue* value) {
  if (!GetResetter()->IsActive()) {
    setting_snapshot_.reset(new ResettableSettingsSnapshot(profile_));
    setting_snapshot_->RequestShortcuts(base::Bind(
        &ResetSettingsHandler::UpdateFeedbackUI,
        weak_ptr_factory_.GetWeakPtr()));
    UpdateFeedbackUI();
  }

  if (brandcode_.empty())
    return;
  config_fetcher_.reset(new BrandcodeConfigFetcher(
      base::Bind(&ResetSettingsHandler::OnSettingsFetched,
                 base::Unretained(this)),
      GURL("https://tools.google.com/service/update2"),
      brandcode_));
}

void ResetSettingsHandler::OnHideResetProfileDialog(
    const base::ListValue* value) {
  if (!GetResetter()->IsActive())
    setting_snapshot_.reset();
}

void ResetSettingsHandler::OnHideResetProfileBanner(
    const base::ListValue* value) {
  chrome_prefs::ClearResetTime(profile_);
}

void ResetSettingsHandler::OnSettingsFetched() {
  DCHECK(config_fetcher_);
  DCHECK(!config_fetcher_->IsActive());
  // The master prefs is fetched. We are waiting for user pressing 'Reset'.
}

void ResetSettingsHandler::ResetProfile(bool send_settings) {
  DCHECK(!GetResetter()->IsActive());

  scoped_ptr<BrandcodedDefaultSettings> default_settings;
  if (config_fetcher_) {
    DCHECK(!config_fetcher_->IsActive());
    default_settings = config_fetcher_->GetSettings();
    config_fetcher_.reset();
  } else {
    DCHECK(brandcode_.empty());
  }

  // If failed to fetch BrandcodedDefaultSettings or this is an organic
  // installation, use default settings.
  if (!default_settings)
    default_settings.reset(new BrandcodedDefaultSettings);

  GetResetter()->Reset(
      ProfileResetter::ALL, std::move(default_settings),
      base::Bind(&ResetSettingsHandler::OnResetProfileSettingsDone,
                 weak_ptr_factory_.GetWeakPtr(),
                 send_settings));
  content::RecordAction(base::UserMetricsAction("ResetProfile"));
  UMA_HISTOGRAM_BOOLEAN("ProfileReset.SendFeedback", send_settings);
}

void ResetSettingsHandler::UpdateFeedbackUI() {
  if (!setting_snapshot_)
    return;
  scoped_ptr<base::ListValue> list = GetReadableFeedbackForSnapshot(
      profile_, *setting_snapshot_);
  base::DictionaryValue feedback_info;
  feedback_info.Set("feedbackInfo", list.release());
  web_ui()->CallJavascriptFunction(
      "SettingsResetPage.setFeedbackInfo", feedback_info);
}

ProfileResetter* ResetSettingsHandler::GetResetter() {
  if (!resetter_)
    resetter_.reset(new ProfileResetter(profile_));
  return resetter_.get();
}

#if defined(OS_CHROMEOS)
void ResetSettingsHandler::OnShowPowerwashDialog(
     const base::ListValue* args) {
  UMA_HISTOGRAM_ENUMERATION(
      "Reset.ChromeOS.PowerwashDialogShown",
      chromeos::reset::DIALOG_FROM_OPTIONS,
      chromeos::reset::DIALOG_VIEW_TYPE_SIZE);
}

void ResetSettingsHandler::HandleFactoryResetRestart(
    const base::ListValue* args) {
  if (!allow_powerwash_)
    return;

  PrefService* prefs = g_browser_process->local_state();
  prefs->SetBoolean(prefs::kFactoryResetRequested, true);
  prefs->CommitPendingWrite();

  // Perform sign out. Current chrome process will then terminate, new one will
  // be launched (as if it was a restart).
  chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
}
#endif  // defined(OS_CHROMEOS)

}  // namespace settings


text:
package com.intellij.openapi.vfs.impl.http;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ex.http.HttpVirtualFileListener;
import com.intellij.util.EventDispatcher;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;

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

/**
 * @author nik
 */
public class RemoteFileManagerImpl extends RemoteFileManager implements Disposable {
  private final LocalFileStorage myStorage;
  private final Map<Pair<Boolean, String>, VirtualFileImpl> myRemoteFiles;
  private final EventDispatcher<HttpVirtualFileListener> myDispatcher = EventDispatcher.create(HttpVirtualFileListener.class);
  private final List<RemoteContentProvider> myProviders = new ArrayList<RemoteContentProvider>();
  private final DefaultRemoteContentProvider myDefaultRemoteContentProvider;

  public RemoteFileManagerImpl() {
    myStorage = new LocalFileStorage();
    myRemoteFiles = new THashMap<Pair<Boolean, String>, VirtualFileImpl>();
    myDefaultRemoteContentProvider = new DefaultRemoteContentProvider();
  }

  @NotNull
  public RemoteContentProvider findContentProvider(final @NotNull String url) {
    for (RemoteContentProvider provider : myProviders) {
      if (provider.canProvideContent(url)) {
        return provider;
      }
    }
    return myDefaultRemoteContentProvider;
  }

  public synchronized VirtualFileImpl getOrCreateFile(final @NotNull String url, final @NotNull String path, final boolean directory) throws IOException {
    Pair<Boolean, String> key = Pair.create(directory, url);
    VirtualFileImpl file = myRemoteFiles.get(key);

    if (file == null) {
      if (!directory) {
        RemoteFileInfo fileInfo = new RemoteFileInfo(url, this);
        file = new VirtualFileImpl(getHttpFileSystem(url), path, fileInfo);
        fileInfo.addDownloadingListener(new MyDownloadingListener(file));
      }
      else {
        file = new VirtualFileImpl(getHttpFileSystem(url), path, null);
      }
      myRemoteFiles.put(key, file);
    }
    return file;
  }

  private static HttpFileSystemBase getHttpFileSystem(@NotNull String url) {
    return url.startsWith(HttpsFileSystem.HTTPS_PROTOCOL) ? HttpsFileSystem.getHttpsInstance() : HttpFileSystemImpl.getInstanceImpl();
  }

  @Override
  public void addRemoteContentProvider(@NotNull final RemoteContentProvider provider, @NotNull Disposable parentDisposable) {
    addRemoteContentProvider(provider);
    Disposer.register(parentDisposable, new Disposable() {
      @Override
      public void dispose() {
        removeRemoteContentProvider(provider);
      }
    });
  }

  @Override
  public void addRemoteContentProvider(@NotNull RemoteContentProvider provider) {
    myProviders.add(provider);
  }

  @Override
  public void removeRemoteContentProvider(@NotNull RemoteContentProvider provider) {
    myProviders.remove(provider);
  }

  @Override
  public void addFileListener(@NotNull final HttpVirtualFileListener listener) {
    myDispatcher.addListener(listener);
  }

  @Override
  public void addFileListener(@NotNull final HttpVirtualFileListener listener, @NotNull final Disposable parentDisposable) {
    addFileListener(listener);
    Disposer.register(parentDisposable, new Disposable() {
      @Override
      public void dispose() {
        removeFileListener(listener);
      }
    });
  }

  @Override
  public void removeFileListener(@NotNull final HttpVirtualFileListener listener) {
    myDispatcher.removeListener(listener);
  }

  public void fireFileDownloaded(@NotNull VirtualFile file) {
    myDispatcher.getMulticaster().fileDownloaded(file);
  }

  public LocalFileStorage getStorage() {
    return myStorage;
  }

  @Override
  public void dispose() {
    myStorage.deleteDownloadedFiles();
  }

  private class MyDownloadingListener extends FileDownloadingAdapter {
    private final VirtualFileImpl myFile;

    public MyDownloadingListener(final VirtualFileImpl file) {
      myFile = file;
    }

    @Override
    public void fileDownloaded(final VirtualFile localFile) {
      fireFileDownloaded(myFile);
    }
  }
}


text:
#ifndef GEOMETRYFEATURE_H_6014714286
#define GEOMETRYFEATURE_H_6014714286

/** \file   GeometryFeature.h
  * \brief  Defines \ref Carna::base::GeometryFeature.
  */

#include <Carna/base/noncopyable.h>
#include <set>

namespace Carna
{

namespace base
{

// ----------------------------------------------------------------------------------
// GeometryFeature
// ----------------------------------------------------------------------------------

/** \brief
  * Represents \em "components" that are aggregated by \ref Geometry objects.
  * Closer description is given \ref GeometryFeatures "here".
  *
  * \author Leonid Kostrykin
  * \date   1.3.15 - 13.3.15
  */
class CARNA_LIB GeometryFeature
{

    NON_COPYABLE

    struct Details;
    const std::unique_ptr< Details > pimpl;

protected:

    /** \brief
      * Instantiates.
      */
    GeometryFeature();

    /** \brief
      * Deletes and \ref Log "logs" an error if video resources are leaked.
      */
    virtual ~GeometryFeature();

public:

    /** \brief
      * Tells current number of \ref ManagedInterface "video resource acquisitions".
      */
    unsigned int videoResourceAcquisitionsCount() const;

    /** \brief
      * Tells whether this instance maintains the same video resources like \a other.
      */
    virtual bool controlsSameVideoResource( const GeometryFeature& other ) const = 0;

    /** \brief
      * Denotes that this object is no longer required and may be deleted as soon as
      * it is valid to delete it.
      *
      * It will be deleted as soon as the following conditions become true, which may
      * also be immediately:
      *
      * - The video resources are not loaded, i.e. the last acquisition was released.
      * - This feature is no longer referenced by a scene graph.
      */
    void release();

    /** \brief
      * Puts this geometry feature on the \a sceneGraphNode.
      *
      * This is equivalent to \ref Geometry::putFeature.
      */
    void addTo( Geometry& sceneGraphNode, unsigned int role );

    /** \brief
    * Removes this geometry feature from the \a sceneGraphNode.
    *
    * This is equivalent to \ref Geometry::removeFeature.
      */
    void removeFrom( Geometry& sceneGraphNode );

    // ------------------------------------------------------------------------------
    // GeometryFeature :: ManagedInterface
    // ------------------------------------------------------------------------------

    /** \brief
      * Represents an acquisition of the video resources from a particular
      * \ref GeometryFeature. This *acquisition* realizes the RAII idiom.
      *
      * \author Leonid Kostrykin
      * \date   22.2.15 - 18.3.15
      */
    class CARNA_LIB ManagedInterface
    {

        NON_COPYABLE

    protected:

        /** \brief
          * Acquires the video resources from \a gf.
          *
          * The instantiated `%ManagedInterface` object is only valid within the
          * \ref GLContext "current OpenGL context". Delete the object in order to
          * release the acquired resources. Usually the resources are uploaded to
          * video memory when they are first acquired, and deleted from video memory
          * when the last acquisition is released. This depends on whether the
          * resources are \ref GLContext "sharable" across OpenGL contexts.
          */
        explicit ManagedInterface( GeometryFeature& gf );

    public:

        /** \brief
          * Releases the video resources previously acquired from the managing
          * \ref geometryFeature.
          */
        virtual ~ManagedInterface();

        /** \brief
          * References the `%GeometryFeature` that manages the video resources that
          * this object interfaces.
          */
        GeometryFeature& geometryFeature;

    }; // GeometryFeature :: ManagedInterface

    /** \brief
      * Acquires the video resources from this `%GeometryFeature` by returning new
      * instance of a class derived from \ref ManagedInterface, that realizes the
      * RAII idiom. Refer to its documentation for details. May return `nullptr` if
      * this `%GeometryFeature` does not provide any video resources.
      */
    virtual ManagedInterface* acquireVideoResource() = 0;

}; // GeometryFeature

}  // namespace Carna :: base

}  // namespace Carna

#endif // GEOMETRYFEATURE_H_6014714286