text:
package com.gs.fw.common.mithra.finder;

import com.gs.fw.common.mithra.attribute.Attribute;
import com.gs.fw.common.mithra.attribute.SingleColumnAttribute;
import com.gs.fw.common.mithra.extractor.*;
import com.gs.fw.common.mithra.util.HashUtil;
import com.gs.fw.common.mithra.util.StringPool;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.math.BigDecimal;

public class IsNullOperation  extends AtomicEqualityOperation
{
    private static final NullExtractor extractor = new NullExtractor();

    public IsNullOperation(Attribute attribute)
    {
        super(attribute);
    }

    @Override
    public int getParameterHashCode()
    {
        return HashUtil.NULL_HASH;
    }

    public Object getParameterAsObject()
    {
        return null;
    }

    @Override
    public boolean parameterValueEquals(Object other, Extractor extractor)
    {
        return extractor.isAttributeNull(other);
    }

    public Extractor getParameterExtractor()
    {
        return extractor;
    }

    protected List getByIndex()
    {
        return this.getCache().getNulls(this.getIndexRef());
    }

    @Override
    public List applyOperationToPartialCache()
    {
        // a nullable attribute is not likely to be uniquely indexable.
        return null;
    }

    protected Boolean matchesWithoutDeleteCheck(Object o)
    {
        return this.getAttribute().isAttributeNull(o);
    }

    public SingleColumnAttribute getSingleColumnAttribute()
    {
        return (SingleColumnAttribute) this.getAttribute();
    }

    @Override
    public void generateSql(SqlQuery query)
    {
        query.appendWhereClause(this.getAttribute().getFullyQualifiedLeftHandExpression(query)+" IS NULL");
    }

    public int setSqlParameters(PreparedStatement pstmt, int startIndex, SqlQuery query) throws SQLException
    {
        // nothing to set
        return 0;
    }

    @Override
    public void zToString(ToStringContext toStringContext)
    {
        this.getAttribute().zAppendToString(toStringContext);
        toStringContext.append("is null");
    }

    public int hashCode()
    {
        return this.getAttribute().hashCode();
    }

    public boolean equals(Object obj)
    {
        if (obj instanceof IsNullOperation)
        {
            IsNullOperation other = (IsNullOperation) obj;
            return other.getAttribute() == this.getAttribute();
        }
        return false;
    }

    /*
    returns the combined and operation. Many operations are more efficient when combined.
    This method is internal to Mithra's operation processing.
    */
    @Override
    public Operation zCombinedAnd(Operation op)
    {
        if (op instanceof IsNullOperation)
        {
            return zCombineWithNullOperation((IsNullOperation) op);
        }
        return op.zCombinedAnd(this);
    }

    private Operation zCombineWithNullOperation(IsNullOperation other)
    {
        if (other.getAttribute().equals(this.getAttribute()))
        {
            return this;
        }
        return null;
    }

    @Override
    public Operation zCombinedAndWithAtomicEquality(AtomicEqualityOperation op)
    {
        if (op.getAttribute().equals(this.getAttribute()))
        {
            if (op.zIsNullOperation())
            {
                return this;
            }
            return new None(this.getAttribute());
        }
        // == ok is fine in this case, as the strings are ultimately coming from a static reference in the finder
        else if (op.zGetResultClassName() == this.zGetResultClassName())
        {
            return new MultiEqualityOperation(this, op);
        }
        return null;
    }

    private static class NullExtractor extends OperationParameterExtractor implements ByteExtractor, ShortExtractor,
            IntExtractor, LongExtractor, FloatExtractor, DoubleExtractor, StringExtractor,
            TimestampExtractor, DateExtractor, BigDecimalExtractor
    {
        public boolean isAttributeNull(Object o)
        {
            return true;
        }

        public byte byteValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public int intValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public boolean valueEquals(Object first, Object second, Extractor secondExtractor)
        {
            return secondExtractor.isAttributeNull(second);
        }

        public int valueHashCode(Object o)
        {
            return HashUtil.NULL_HASH;
        }

        public boolean valueEquals(Object first, Object second)
        {
            return second instanceof IsNullOperation;
        }

        @Override
        public int offHeapValueOf(Object o)
        {
            return 0;
        }

        public Object valueOf(Object anObject)
        {
            return null;
        }

        @Override
        public long dateValueOfAsLong(Object valueHolder)
        {
            throw new RuntimeException("not implemented");
        }

        public short shortValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public long longValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public float floatValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public double doubleValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public String stringValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public void setStringValue(Object o, String newValue)
        {
            throw new RuntimeException("not implemented");
        }

        public Timestamp timestampValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        @Override
        public long timestampValueOfAsLong(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public Date dateValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }

        public void setDateValue(Object o, Date newValue)
        {
            throw new RuntimeException("not implemented");
        }

        public BigDecimal bigDecimalValueOf(Object o)
        {
            throw new RuntimeException("not implemented");
        }
    }

}


text:
@implementation VBAlertView{
    UIActivityIndicatorView *_activityView; // 新添加系统自带活动指示器
}

+ (instancetype)shareAlertView
{
    static id managerInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        managerInstance = [[[self class] alloc] init];
    });
    return managerInstance;
}

- (id)init
{
    self = [super init];
    if (self) {

    }
    return self;
}
#pragma mark - 弹窗
//普通提示弹窗
- (void)showTipAlert:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

- (void)showTipAlert:(NSString *)message completion:(choiceCompletionBlock)completion
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    objc_setAssociatedObject(alert, VBChoiceAlertViewKey, completion, OBJC_ASSOCIATION_COPY);
    [alert show];
}

//可以选择的弹窗
- (void)showChoiceAlert:(NSString *)message completion:(choiceCompletionBlock)completion
{
    [self showChoiceAlert:message doneTitle:@"确定" completion:completion];
}
- (void)showChoiceAlert:(NSString *)message doneTitle:(NSString *)doneTitile completion:(choiceCompletionBlock)completion
{
    [self showChoiceAlert:message title:@"提示" doneTitle:doneTitile completion:completion];
}
- (void)showChoiceAlert:(NSString *)message title:(NSString *)title doneTitle:(NSString *)doneTitle completion:(choiceCompletionBlock)completion {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:doneTitle, nil];
    objc_setAssociatedObject(alert, VBChoiceAlertViewKey, completion, OBJC_ASSOCIATION_COPY);
    [alert show];
}

// 可自定义Title
- (void)showChoiceAlert:(NSString *)message button1Title:(NSString *)title1 button2Title:(NSString *)title2 completion:(choiceCompletionBlock)completion
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:title1, title2, nil];
    objc_setAssociatedObject(alert, VBChoiceAlertViewKey, completion, OBJC_ASSOCIATION_COPY);
    [alert show];
}

- (void)showChoiceAlert:(NSString *)message title:(NSString *)title button1Title:(NSString *)button1Title button2Title:(NSString *)button2Title completion:(choiceCompletionBlock)completion {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:nil otherButtonTitles:button1Title, button2Title, nil];
    objc_setAssociatedObject(alert, VBChoiceAlertViewKey, completion, OBJC_ASSOCIATION_COPY);
    [alert show];
}

//三选择弹窗
- (void)showChoiceAlert:(NSString *)message button1Title:(NSString *)title1 button2Title:(NSString *)title2 button3Title:(NSString *)title3 completion:(choiceCompletionBlock)completion
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:title1, title2, title3, nil];
    objc_setAssociatedObject(alert, VBChoiceAlertViewKey, completion, OBJC_ASSOCIATION_COPY);
    [alert show];
}

//带输入框的弹窗
- (void)showTextFiledAlert:(NSString *)message defaultText:(NSString *)defaultText completion:(textCompletionBlock)completion
{
    [self showTextFiledAlert:message doneTitle:@"确定" defaultText:defaultText completion:completion];
}

- (void)showTextFiledAlert:(NSString *)message doneTitle:(NSString *)doneTitle defaultText:(NSString *)defaultText completion:(textCompletionBlock)completion
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:doneTitle, nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *textField = [alert textFieldAtIndex:0];
    [textField setText:defaultText];

    objc_setAssociatedObject(alert, VBTextAlertViewKey, completion, OBJC_ASSOCIATION_COPY);

    [alert show];
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    textCompletionBlock textBlock = objc_getAssociatedObject(alertView, VBTextAlertViewKey);
    if (textBlock) {
        if (buttonIndex == 1) {
            UITextField *textField = [alertView textFieldAtIndex:0];
            textBlock(textField.text);
        }
    }

    choiceCompletionBlock choiceBlock = objc_getAssociatedObject(alertView, VBChoiceAlertViewKey);
    if (choiceBlock) {
        choiceBlock(buttonIndex);
    }
}

#pragma mark - 提示窗
//
////加载中提示
+ (void)showHUD
{
    [WSProgressHUD show];
}

+ (void)showHUDWithMask
{
    [WSProgressHUD showWithMaskType:WSProgressHUDMaskTypeBlack];
}

+ (void)showLoadingHUD:(NSString *)status
{
    [WSProgressHUD showWithStatus:status];
}

+ (void)showLoadingHUDWithMask:(NSString *)status maskWithout:(VBProgressHUDMaskWithoutType)type
{
    [WSProgressHUD showWithStatus:status maskType:WSProgressHUDMaskTypeBlack maskWithout:(NSInteger)type];
}

+ (void)showLoadingHUD:(NSString *)status inView:(UIView *)view
{
    if (view) {
        WSProgressHUD* hud = [[WSProgressHUD alloc] initWithView:view];
        [view addSubview:hud];
        [hud showWithString:status maskType:WSProgressHUDMaskTypeDefault];
        objc_setAssociatedObject(view, VBProgressHUDKey, hud, OBJC_ASSOCIATION_RETAIN);
    }
}

+ (void)showLoadingHUDMask:(NSString *)status inView:(UIView *)view
{
    if (view) {
        WSProgressHUD* hud = [[WSProgressHUD alloc] initWithView:view];
        [view addSubview:hud];
        [hud showWithString:status maskType:WSProgressHUDMaskTypeBlack];
        objc_setAssociatedObject(view, VBProgressHUDKey, hud, OBJC_ASSOCIATION_RETAIN);
    }
}

+ (void)showShimmering:(NSString *)string
{
    [WSProgressHUD showShimmeringString:string];
}

+ (void)showProgress:(CGFloat)progress
{
    [WSProgressHUD showProgress:progress];
}

+ (void)showProgress:(CGFloat)progress status:(NSString *)status
{
    [WSProgressHUD showProgress:progress status:status];
}
////成功提示
+ (void)showSuccessHUD:(NSString *)status
{
    UIImage *successImage = [UIImage imageNamed:@"VBsuccess.png"];
    [WSProgressHUD showImage:successImage status:status];
}
////失败提示
+ (void)showErrorHUD:(NSString *)status
{
    UIImage *errorImage = [UIImage imageNamed:@"VBerror.png"];
    [WSProgressHUD showImage:errorImage status:status];
}
////普通文本提示
+ (void)showTextHUD:(NSString *)status
{
    [WSProgressHUD showImage:nil status:status];
}
+ (void)showImage:(UIImage *)image status:(NSString *)status{
    [WSProgressHUD showImage:image status:status];
}
//消除提示提示
+ (void)dismiss{
    [WSProgressHUD dismiss];

}
+ (void)dismissWithView:(UIView *)view{
   WSProgressHUD* hud = objc_getAssociatedObject(view, VBProgressHUDKey);
    [hud dismiss];
}
//+ (void)dismissWithAnimated:(BOOL)animated;
//// 数据获取失败
//+ (void)showFetchError;

#pragma mark -
#pragma mark 活动指示器相关
- (void)showActivityIndicatorViewInView:(UIView *)view{
    if (_activityView == nil) {
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [_activityView setFrame:CGRectMake(0, 0, 50, 50)
         ];
    }

    _activityView.center = view.center;
    [view addSubview:_activityView];
    [_activityView startAnimating];
}

- (void)showActivityIndicatorViewInView:(UIView *)view center:(CGPoint)center {
    [self showActivityIndicatorViewInView:view];
    _activityView.center = center;
}

- (void)removeActivityIndicatorView {
    [_activityView stopAnimating];
    _activityView = nil;
}

@end

redpajama_set_name: RedPajamaGithub


text:
import requests, zipfile, os
import json, sqlite3
import pickle #Optional

#Reading the Destiny API Manifest in Python. [How I Did It, Anyway]

weapon_types = ['Rocket Launcher', 'Scout Rifle', 'Fusion Rifle', 'Sniper Rifle',
                'Shotgun', 'Machine Gun', 'Pulse Rifle', 'Auto Rifle', 'Hand Cannon', 'Sidearm']

#dictionary that tells where to get the hashes for each table
#FULL DICTIONARY
hash_dict = {'DestinyActivityDefinition': 'activityHash',
             'DestinyActivityTypeDefinition': 'activityTypeHash',
             'DestinyClassDefinition': 'classHash',
             'DestinyGenderDefinition': 'genderHash',
             'DestinyInventoryBucketDefinition': 'bucketHash',
             'DestinyInventoryItemDefinition': 'itemHash',
             'DestinyProgressionDefinition': 'progressionHash',
             'DestinyRaceDefinition': 'raceHash',
             'DestinyTalentGridDefinition': 'gridHash',
             'DestinyUnlockFlagDefinition': 'flagHash',
             'DestinyHistoricalStatsDefinition': 'statId',
             'DestinyDirectorBookDefinition': 'bookHash',
             'DestinyStatDefinition': 'statHash',
             'DestinySandboxPerkDefinition': 'perkHash',
             'DestinyDestinationDefinition': 'destinationHash',
             'DestinyPlaceDefinition': 'placeHash',
             'DestinyActivityBundleDefinition': 'bundleHash',
             'DestinyStatGroupDefinition': 'statGroupHash',
             'DestinySpecialEventDefinition': 'eventHash',
             'DestinyFactionDefinition': 'factionHash',
             'DestinyVendorCategoryDefinition': 'categoryHash',
             'DestinyEnemyRaceDefinition': 'raceHash',
             'DestinyScriptedSkullDefinition': 'skullHash',
             'DestinyGrimoireCardDefinition': 'cardId'}

def get_manifest():
    manifest_url = 'http://www.bungie.net/Platform/Destiny/Manifest/'
    #get the manifest location from the json
    r = requests.get(manifest_url)
    manifest = r.json()
    mani_url = 'http://www.bungie.net'+manifest['Response']['mobileWorldContentPaths']['en']
    #Download the file, write it to MANZIP
    r = requests.get(mani_url)
    with open("MANZIP", "wb") as zip:
        zip.write(r.content)
    print "Download Complete!"

    #Extract the file contents, and rename the extracted file
    # to 'Manifest.content'
    with zipfile.ZipFile('MANZIP') as zip:
        name = zip.namelist()
        zip.extractall()
    os.rename(name[0], 'Manifest.content')
    print 'Unzipped!'

def build_dict(hash_dict):
    #connect to the manifest
    con = sqlite3.connect('Manifest.content')
    print 'Connected'
    #create a cursor object
    cur = con.cursor()

    all_data = {}
    #for every table name in the dictionary
    for table_name in hash_dict.keys():
        #get a list of all the jsons from the table
        cur.execute('SELECT json from '+table_name)
        print 'Generating '+table_name+' dictionary....'

        #this returns a list of tuples: the first item in each tuple is our json
        items = cur.fetchall()

        #create a list of jsons
        item_jsons = [json.loads(item[0]) for item in items]

        #create a dictionary with the hashes as keys
        #and the jsons as values
        item_dict = {}
        hash = hash_dict[table_name]
        for item in item_jsons:
            item_dict[item[hash]] = item

        #add that dictionary to our all_data using the name of the table
        #as a key.
        all_data[table_name] = item_dict
    print 'Dictionary Generated!'
    return all_data

#check if pickle exists, if not create one.
if os.path.isfile('manifest.pickle') == False:
    get_manifest()
    all_data = build_dict(hash_dict)
    with open('manifest.pickle', 'wb') as data:
        pickle.dump(all_data, data)
    print "'manifest.pickle' created!\nDONE!"
else:
    print 'Pickle Exists'


text:
================================================================================
PhysicalNicConfig
================================================================================

.. describe:: Property of

    :py:class:`~pyvisdk.do.host_network_config.HostNetworkConfig`

.. describe:: See also

    :py:class:`~pyvisdk.do.physical_nic_spec.PhysicalNicSpec`

.. describe:: Extends

    :py:class:`~pyvisdk.mo.dynamic_data.DynamicData`

.. class:: pyvisdk.do.physical_nic_config.PhysicalNicConfig

    .. py:attribute:: device

        PhysicalNic device to which configuration applies.

    .. py:attribute:: spec

        The specification of the physical network adapter.


text:
<?php

namespace ZF2rapid\Filter;

use Zend\Filter\Word\DashToCamelCase;
use Zend\Filter\Word\UnderscoreToCamelCase;
use ZF\Console\Filter\Explode;

/**
 * Class NormalizeList
 *
 * @package ZF2rapid\Filter
 */
class NormalizeList extends Explode
{
    /**
     * @param mixed $value
     *
     * @return array|mixed
     */
    public function filter($value)
    {
        $list = parent::filter($value);

        $dashToCamelCaseFilter       = new DashToCamelCase();
        $underscoreToCamelCaseFilter = new UnderscoreToCamelCase();

        foreach ($list as $listKey => $listOption) {
            $listOption = $dashToCamelCaseFilter->filter($listOption);
            $listOption = $underscoreToCamelCaseFilter->filter($listOption);

            $list[$listKey] = $listOption;
        }

        return $list;
    }

}


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods

Data Object - ComplianceFailure

Property of

ComplianceResult

Extends

DynamicData

See also

LocalizableMessage

Since

vSphere API 4.0

Data Object
                  Description

Properties

	          Name

	          Type

	          Description

expressionName*	xsd:string

         Name of the Expression which generated the ComplianceFailure

failureType	xsd:string

         String uniquely identifying the failure.

message	LocalizableMessage

         Message which describes the compliance failures

 message.key serves as a key to the localized
 message catalog.

						Properties inherited from DynamicData

dynamicProperty, dynamicType

*Need not be set

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="ComplianceFailure">
            <complexContent>
               <extension base="vim25:DynamicData">
                  <sequence>
                     <element name="failureType" type="xsd:string"/>
                     <element name="message" type="vim25:LocalizableMessage"/>
                     <element name="expressionName" type="xsd:string" minOccurs="0"/>
                  </sequence>
               </extension>
            </complexContent>
         </complexType></textarea>

Top of page		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods


text:
fn CamelCase() {} //~ ERROR function `CamelCase` should have a snake case name

#[allow(bad_style)]
mod test {
    fn CamelCase() {}

    #[forbid(bad_style)]
    //~^ NOTE lint level defined here
    //~^^ NOTE lint level defined here
    mod bad {
        fn CamelCase() {} //~ ERROR function `CamelCase` should have a snake case name

        static bad: int = 1; //~ ERROR static constant `bad` should have an uppercase name
    }

    mod warn {
        #![warn(bad_style)]
        //~^ NOTE lint level defined here

        fn CamelCase() {} //~ WARN function `CamelCase` should have a snake case name

        struct snake_case; //~ WARN type `snake_case` should have a camel case name
    }
}

fn main() {}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package com.cloud.network;

public class NetworkManagerTestComponentLibrary {

    /* (non-Javadoc)
     * @see com.cloud.configuration.DefaultComponentLibrary#populateManagers()
     */
    protected void populateManagers() {
//        addManager("configuration manager", MockConfigurationManagerImpl.class);
//        addManager("account manager", MockAccountManagerImpl.class);
//        addManager("domain manager", MockDomainManagerImpl.class);
//        addManager("resource limit manager", MockResourceLimitManagerImpl.class);
//        addManager("network service", NetworkServiceImpl.class);
//        addManager("network manager", NetworkManagerImpl.class);
//        addManager("network model", NetworkModelImpl.class);
//        addManager("LoadBalancingRulesManager", LoadBalancingRulesManagerImpl.class);
//        //addManager("AutoScaleManager", AutoScaleManagerImpl.class);
//        addManager("RulesManager", RulesManagerImpl.class);
//        addManager("RemoteAccessVpnManager", RemoteAccessVpnManagerImpl.class);
//        addManager("FirewallManager", FirewallManagerImpl.class);
//        addManager("StorageNetworkManager", StorageNetworkManagerImpl.class);
//        addManager("VPC Manager", MockVpcManagerImpl.class);
//        addManager("VpcVirtualRouterManager", MockVpcVirtualNetworkApplianceManager.class);
//        addManager("NetworkACLManager", NetworkACLManagerImpl.class);
//        addManager("Site2SiteVpnManager", Site2SiteVpnManagerImpl.class);
//        addManager("Alert Manager", MockAlertManagerImpl.class);
//        addManager("ProjectManager", MockProjectManagerImpl.class);
//        //addManager("SwiftManager", SwiftManagerImpl.class);
//        //addManager("S3Manager", S3ManagerImpl.class);
//        //addManager("SecondaryStorageManager", SecondaryStorageManagerImpl.class);
//        //addManager("SecurityGroupManager", SecurityGroupManagerImpl2.class);
//        addManager("AgentManager", MockAgentManagerImpl.class);
//        addManager("ExternalLoadBalancerUsageManager", ExternalLoadBalancerUsageManagerImpl.class);
//        //addManager("TemplateManager", TemplateManagerImpl.class);
//        //addManager("VirtualMachineManager", MockVirtualMachineManagerImpl.class);
//        addManager("ResourceManager", MockResourceManagerImpl.class);
//        addManager("ExternalDhcpManager", ExternalDhcpManagerImpl.class);

    }

}


text:
pushd `dirname $0` > /dev/null
SCRIPT_DIR=`pwd`
popd > /dev/null

ROOT=`dirname $SCRIPT_DIR`
source "$SCRIPT_DIR/env.sh"

if (( "$#" == 1 )); then
  java -cp "$CLASSPATH:${ROOT}/build/classes/integration" \
    -javaagent:${ROOT}/lib/catg-dev.jar janala.utils.ClassRunner $@
elif (( "$#" == 2 )); then
  java -cp "$CLASSPATH:${ROOT}/build/classes/integration" \
    -javaagent:${ROOT}/lib/catg-dev.jar janala.utils.Runner $@
else
  echo "Wrong number of inputs"
  exit 1
fi


text:
PPP Options

Because the PPTP protocol uses PPP internally to actually transport data,
the PPP daemon's configuration effects how it behaves. The options on this page
determine if authentication is required or not, and if so what forms of
authentication are accepted. CHAP is recommended, as it is the defacto
standard for PPTP. However, once authentication is activated you must set
up logins for clients on the PPP Accounts page.

The options at the bottom of the page can be used to enable the MPPE encryption
and MS-CHAP authentication protocols used by default by Windows clients. MPPE
adds security to PPTP connections, but requires that both the PPP daemon and
the operating system kernel support it. PPPd versions 2.4.2 and above have
native MPPE support, while a patch exists for older versions. However, the
actual configuration file options differ between these two PPPd versions. This
module will always use the correct options though.


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

namespace RhinoMocksInternalMembers
{
    /// <summary>
    /// Minimum implementation to pass the test
    /// </summary>
    internal class Class1
    {
        internal virtual string TestMethod()
        {
            return "TestMethod";
        }

        internal virtual string TestProperty
        {
            get { return "TestProperty"; }
        }
    }
}


text:
numpy.ma.MaskedArray.__rlshift__
================================

.. currentmodule:: numpy.ma

.. automethod:: MaskedArray.__rlshift__


text:
/**
 */
package org.liquibase.xml.ns.dbchangelog.impl;

import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.ecore.EClass;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import org.liquibase.xml.ns.dbchangelog.DbchangelogPackage;
import org.liquibase.xml.ns.dbchangelog.SqlFileType;

/**
 *
 * An implementation of the model object 'Sql File Type'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.liquibase.xml.ns.dbchangelog.impl.SqlFileTypeImpl#getDbms Dbms}

 *
{@link org.liquibase.xml.ns.dbchangelog.impl.SqlFileTypeImpl#getEncoding Encoding}

 *
{@link org.liquibase.xml.ns.dbchangelog.impl.SqlFileTypeImpl#getEndDelimiter End Delimiter}

 *
{@link org.liquibase.xml.ns.dbchangelog.impl.SqlFileTypeImpl#getPath Path}

 *
{@link org.liquibase.xml.ns.dbchangelog.impl.SqlFileTypeImpl#getRelativeToChangelogFile Relative To Changelog File}

 *
{@link org.liquibase.xml.ns.dbchangelog.impl.SqlFileTypeImpl#getSplitStatements Split Statements}

 *
{@link org.liquibase.xml.ns.dbchangelog.impl.SqlFileTypeImpl#getStripComments Strip Comments}

 *

 *

 *
 * @generated
 */
public class SqlFileTypeImpl extends MinimalEObjectImpl.Container implements SqlFileType {
	/**
	 * The default value of the '{@link #getDbms() Dbms}' attribute.
	 *
	 *
	 * @see #getDbms()
	 * @generated
	 * @ordered
	 */
	protected static final String DBMS_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getDbms() Dbms}' attribute.
	 *
	 *
	 * @see #getDbms()
	 * @generated
	 * @ordered
	 */
	protected String dbms = DBMS_EDEFAULT;

	/**
	 * The default value of the '{@link #getEncoding() Encoding}' attribute.
	 *
	 *
	 * @see #getEncoding()
	 * @generated
	 * @ordered
	 */
	protected static final String ENCODING_EDEFAULT = "UTF-8";

	/**
	 * The cached value of the '{@link #getEncoding() Encoding}' attribute.
	 *
	 *
	 * @see #getEncoding()
	 * @generated
	 * @ordered
	 */
	protected String encoding = ENCODING_EDEFAULT;

	/**
	 * This is true if the Encoding attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean encodingESet;

	/**
	 * The default value of the '{@link #getEndDelimiter() End Delimiter}' attribute.
	 *
	 *
	 * @see #getEndDelimiter()
	 * @generated
	 * @ordered
	 */
	protected static final String END_DELIMITER_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getEndDelimiter() End Delimiter}' attribute.
	 *
	 *
	 * @see #getEndDelimiter()
	 * @generated
	 * @ordered
	 */
	protected String endDelimiter = END_DELIMITER_EDEFAULT;

	/**
	 * The default value of the '{@link #getPath() Path}' attribute.
	 *
	 *
	 * @see #getPath()
	 * @generated
	 * @ordered
	 */
	protected static final String PATH_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getPath() Path}' attribute.
	 *
	 *
	 * @see #getPath()
	 * @generated
	 * @ordered
	 */
	protected String path = PATH_EDEFAULT;

	/**
	 * The default value of the '{@link #getRelativeToChangelogFile() Relative To Changelog File}' attribute.
	 *
	 *
	 * @see #getRelativeToChangelogFile()
	 * @generated
	 * @ordered
	 */
	protected static final Object RELATIVE_TO_CHANGELOG_FILE_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getRelativeToChangelogFile() Relative To Changelog File}' attribute.
	 *
	 *
	 * @see #getRelativeToChangelogFile()
	 * @generated
	 * @ordered
	 */
	protected Object relativeToChangelogFile = RELATIVE_TO_CHANGELOG_FILE_EDEFAULT;

	/**
	 * The default value of the '{@link #getSplitStatements() Split Statements}' attribute.
	 *
	 *
	 * @see #getSplitStatements()
	 * @generated
	 * @ordered
	 */
	protected static final Object SPLIT_STATEMENTS_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getSplitStatements() Split Statements}' attribute.
	 *
	 *
	 * @see #getSplitStatements()
	 * @generated
	 * @ordered
	 */
	protected Object splitStatements = SPLIT_STATEMENTS_EDEFAULT;

	/**
	 * The default value of the '{@link #getStripComments() Strip Comments}' attribute.
	 *
	 *
	 * @see #getStripComments()
	 * @generated
	 * @ordered
	 */
	protected static final Object STRIP_COMMENTS_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getStripComments() Strip Comments}' attribute.
	 *
	 *
	 * @see #getStripComments()
	 * @generated
	 * @ordered
	 */
	protected Object stripComments = STRIP_COMMENTS_EDEFAULT;

	/**
	 *
	 *
	 * @generated
	 */
	protected SqlFileTypeImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return DbchangelogPackage.eINSTANCE.getSqlFileType();
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getDbms() {
		return dbms;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setDbms(String newDbms) {
		String oldDbms = dbms;
		dbms = newDbms;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DbchangelogPackage.SQL_FILE_TYPE__DBMS, oldDbms, dbms));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getEncoding() {
		return encoding;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setEncoding(String newEncoding) {
		String oldEncoding = encoding;
		encoding = newEncoding;
		boolean oldEncodingESet = encodingESet;
		encodingESet = true;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DbchangelogPackage.SQL_FILE_TYPE__ENCODING, oldEncoding, encoding, !oldEncodingESet));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void unsetEncoding() {
		String oldEncoding = encoding;
		boolean oldEncodingESet = encodingESet;
		encoding = ENCODING_EDEFAULT;
		encodingESet = false;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.UNSET, DbchangelogPackage.SQL_FILE_TYPE__ENCODING, oldEncoding, ENCODING_EDEFAULT, oldEncodingESet));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public boolean isSetEncoding() {
		return encodingESet;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getEndDelimiter() {
		return endDelimiter;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setEndDelimiter(String newEndDelimiter) {
		String oldEndDelimiter = endDelimiter;
		endDelimiter = newEndDelimiter;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DbchangelogPackage.SQL_FILE_TYPE__END_DELIMITER, oldEndDelimiter, endDelimiter));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getPath() {
		return path;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setPath(String newPath) {
		String oldPath = path;
		path = newPath;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DbchangelogPackage.SQL_FILE_TYPE__PATH, oldPath, path));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Object getRelativeToChangelogFile() {
		return relativeToChangelogFile;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setRelativeToChangelogFile(Object newRelativeToChangelogFile) {
		Object oldRelativeToChangelogFile = relativeToChangelogFile;
		relativeToChangelogFile = newRelativeToChangelogFile;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DbchangelogPackage.SQL_FILE_TYPE__RELATIVE_TO_CHANGELOG_FILE, oldRelativeToChangelogFile, relativeToChangelogFile));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Object getSplitStatements() {
		return splitStatements;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setSplitStatements(Object newSplitStatements) {
		Object oldSplitStatements = splitStatements;
		splitStatements = newSplitStatements;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DbchangelogPackage.SQL_FILE_TYPE__SPLIT_STATEMENTS, oldSplitStatements, splitStatements));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Object getStripComments() {
		return stripComments;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setStripComments(Object newStripComments) {
		Object oldStripComments = stripComments;
		stripComments = newStripComments;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DbchangelogPackage.SQL_FILE_TYPE__STRIP_COMMENTS, oldStripComments, stripComments));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case DbchangelogPackage.SQL_FILE_TYPE__DBMS:
				return getDbms();
			case DbchangelogPackage.SQL_FILE_TYPE__ENCODING:
				return getEncoding();
			case DbchangelogPackage.SQL_FILE_TYPE__END_DELIMITER:
				return getEndDelimiter();
			case DbchangelogPackage.SQL_FILE_TYPE__PATH:
				return getPath();
			case DbchangelogPackage.SQL_FILE_TYPE__RELATIVE_TO_CHANGELOG_FILE:
				return getRelativeToChangelogFile();
			case DbchangelogPackage.SQL_FILE_TYPE__SPLIT_STATEMENTS:
				return getSplitStatements();
			case DbchangelogPackage.SQL_FILE_TYPE__STRIP_COMMENTS:
				return getStripComments();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case DbchangelogPackage.SQL_FILE_TYPE__DBMS:
				setDbms((String)newValue);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__ENCODING:
				setEncoding((String)newValue);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__END_DELIMITER:
				setEndDelimiter((String)newValue);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__PATH:
				setPath((String)newValue);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__RELATIVE_TO_CHANGELOG_FILE:
				setRelativeToChangelogFile(newValue);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__SPLIT_STATEMENTS:
				setSplitStatements(newValue);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__STRIP_COMMENTS:
				setStripComments(newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case DbchangelogPackage.SQL_FILE_TYPE__DBMS:
				setDbms(DBMS_EDEFAULT);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__ENCODING:
				unsetEncoding();
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__END_DELIMITER:
				setEndDelimiter(END_DELIMITER_EDEFAULT);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__PATH:
				setPath(PATH_EDEFAULT);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__RELATIVE_TO_CHANGELOG_FILE:
				setRelativeToChangelogFile(RELATIVE_TO_CHANGELOG_FILE_EDEFAULT);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__SPLIT_STATEMENTS:
				setSplitStatements(SPLIT_STATEMENTS_EDEFAULT);
				return;
			case DbchangelogPackage.SQL_FILE_TYPE__STRIP_COMMENTS:
				setStripComments(STRIP_COMMENTS_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case DbchangelogPackage.SQL_FILE_TYPE__DBMS:
				return DBMS_EDEFAULT == null ? dbms != null : !DBMS_EDEFAULT.equals(dbms);
			case DbchangelogPackage.SQL_FILE_TYPE__ENCODING:
				return isSetEncoding();
			case DbchangelogPackage.SQL_FILE_TYPE__END_DELIMITER:
				return END_DELIMITER_EDEFAULT == null ? endDelimiter != null : !END_DELIMITER_EDEFAULT.equals(endDelimiter);
			case DbchangelogPackage.SQL_FILE_TYPE__PATH:
				return PATH_EDEFAULT == null ? path != null : !PATH_EDEFAULT.equals(path);
			case DbchangelogPackage.SQL_FILE_TYPE__RELATIVE_TO_CHANGELOG_FILE:
				return RELATIVE_TO_CHANGELOG_FILE_EDEFAULT == null ? relativeToChangelogFile != null : !RELATIVE_TO_CHANGELOG_FILE_EDEFAULT.equals(relativeToChangelogFile);
			case DbchangelogPackage.SQL_FILE_TYPE__SPLIT_STATEMENTS:
				return SPLIT_STATEMENTS_EDEFAULT == null ? splitStatements != null : !SPLIT_STATEMENTS_EDEFAULT.equals(splitStatements);
			case DbchangelogPackage.SQL_FILE_TYPE__STRIP_COMMENTS:
				return STRIP_COMMENTS_EDEFAULT == null ? stripComments != null : !STRIP_COMMENTS_EDEFAULT.equals(stripComments);
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (dbms: ");
		result.append(dbms);
		result.append(", encoding: ");
		if (encodingESet) result.append(encoding); else result.append("<unset>");
		result.append(", endDelimiter: ");
		result.append(endDelimiter);
		result.append(", path: ");
		result.append(path);
		result.append(", relativeToChangelogFile: ");
		result.append(relativeToChangelogFile);
		result.append(", splitStatements: ");
		result.append(splitStatements);
		result.append(", stripComments: ");
		result.append(stripComments);
		result.append(')');
		return result.toString();
	}

} //SqlFileTypeImpl


text:
package monix.execution.schedulers

import java.util.concurrent.TimeUnit

import cats.effect.IO
import minitest.SimpleTestSuite
import monix.execution.Cancelable
import monix.execution.ExecutionModel.{AlwaysAsyncExecution, SynchronousExecution}
import scala.concurrent.duration._
import scala.util.Success

object ReferenceSchedulerSuite extends SimpleTestSuite {
  class DummyScheduler(
    val underlying: TestScheduler = TestScheduler())
    extends ReferenceScheduler {

    def executionModel = monix.execution.ExecutionModel.Default
    def tick(time: FiniteDuration = Duration.Zero) = underlying.tick(time)
    def execute(runnable: Runnable): Unit = underlying.execute(runnable)
    def reportFailure(t: Throwable): Unit = underlying.reportFailure(t)
    def scheduleOnce(initialDelay: Long, unit: TimeUnit, r: Runnable): Cancelable =
      underlying.scheduleOnce(initialDelay, unit, r)
  }

  test("clockRealTime") {
    val s = new DummyScheduler
    val ws = s.withExecutionModel(SynchronousExecution)
    assert(ws.clockRealTime(MILLISECONDS) > 0)
  }

  test("clockMonotonic") {
    val s = new DummyScheduler
    val ws = s.withExecutionModel(SynchronousExecution)
    assert(ws.clockMonotonic(MILLISECONDS) > 0)
  }

  test("schedule with fixed delay") {
    val s = new DummyScheduler
    val ws = s.withExecutionModel(SynchronousExecution)
    var effect = 0

    val task = ws.scheduleWithFixedDelay(1.second, 2.seconds) { effect += 1 }

    s.tick(1.second)
    assertEquals(effect, 1)
    s.tick(2.seconds)
    assertEquals(effect, 2)
    s.tick(1.seconds)
    assertEquals(effect, 2)
    s.tick(1.seconds)
    assertEquals(effect, 3)
    s.tick(1.second)
    task.cancel()
    s.tick(1.second)
    assertEquals(effect, 3)
  }

  test("schedule at fixed rate") {
    val s = new DummyScheduler
    val ws = s.withExecutionModel(SynchronousExecution)

    var effect = 0
    val task = ws.scheduleAtFixedRate(1.second, 2.seconds) { effect += 1 }

    s.tick(1.second)
    assertEquals(effect, 1)
    s.tick(2.seconds)
    assertEquals(effect, 2)
    s.tick(1.seconds)
    assertEquals(effect, 2)
    s.tick(1.seconds)
    assertEquals(effect, 3)
    s.tick(1.second)
    task.cancel()
    s.tick(1.second)
    assertEquals(effect, 3)
  }

  test("change ExecutionModel") {
    val s = (new DummyScheduler).withExecutionModel(AlwaysAsyncExecution)
    assertEquals(s.executionModel, AlwaysAsyncExecution)
  }

  test("changed em triggers execution") {
    val s = new DummyScheduler
    val ws = s.withExecutionModel(AlwaysAsyncExecution)

    var effect = 0
    ws.executeAsync { () => effect += 1 }

    assertEquals(effect, 0)
    s.tick()
    assertEquals(effect, 1)
  }

  test("can change em multiple times") {
    val s = new DummyScheduler
    var ws = s.withExecutionModel(AlwaysAsyncExecution)
    for (_ <- 0 until 10000) ws = ws.withExecutionModel(AlwaysAsyncExecution)
    assertEquals(ws.executionModel, AlwaysAsyncExecution)
  }

  test("changed em triggers execution with delay") {
    val s = new DummyScheduler
    val ws = s.withExecutionModel(AlwaysAsyncExecution)

    var effect = 0
    ws.scheduleOnce(1.second) { effect += 1 }

    assertEquals(effect, 0)
    s.tick(1.second)
    assertEquals(effect, 1)
  }

  test("changed em error reporting") {
    val s = new DummyScheduler
    val ws = s.withExecutionModel(AlwaysAsyncExecution)

    val dummy = new RuntimeException("dummy")
    ws.executeAsync { () => throw dummy }

    s.tick()
    assertEquals(s.underlying.state.lastReportedError, dummy)
  }

  test("clock.monotonic") {
    val s = new DummyScheduler
    val clock = s.clock[IO]

    val clockMonotonic = clock.monotonic(MILLISECONDS).unsafeRunSync()
    assert(clockMonotonic > 0)
  }

  test("clock.realTime") {
    val s = new DummyScheduler
    val clock = s.clock[IO]

    val clockRealTime = clock.realTime(MILLISECONDS).unsafeRunSync()
    assert(clockRealTime > 0)
  }

  test("timer.sleep") {
    val s = new DummyScheduler
    val timer = s.timerLiftIO[IO]

    val f = timer.sleep(10.seconds).unsafeToFuture()
    assertEquals(f.value, None)

    s.tick(5.seconds)
    assertEquals(f.value, None)

    s.tick(5.seconds)
    assertEquals(f.value, Some(Success(())))
  }

  test("contextShift.shift") {
    val s = new DummyScheduler
    val contextShift = s.contextShift[IO]

    val f = contextShift.shift.unsafeToFuture()
    assertEquals(f.value, None)

    s.tick()
    assertEquals(f.value, Some(Success(())))
  }

  test("contextShift.evalOn") {
    val s = new DummyScheduler
    val contextShift = s.contextShift[IO]
    val s2 = new DummyScheduler()

    val f = contextShift.evalOn(s2)(IO(1)).unsafeToFuture()
    assertEquals(f.value, None)

    s.tick()
    assertEquals(f.value, None)

    s2.tick()
    assertEquals(f.value, None)
    s.tick()
    assertEquals(f.value, Some(Success(1)))
  }
}


text:
layout: post
title:  "C# Simple Http Server"
date:   2012-09-09 20:02:05 +0300
tags: c-sharp http
redirect_from: /networking/c-simple-http-server
image: /imgs/thumbnails/httpserver.webp
---

In this short tutorial I'll explain how to make a simple **Http Server** using only C#. The server will be able to serve any page that contains **client-side** code (html and javascript).

## Basic stuff

When a client requests a page of a website (let's say index.html), the **Http Server** will start looking for that file. If the file is found, the server will read all the content and send it back to the client as a **byte array**. After this, the connection is closed.

## The coding part

Before starting, you need to change your project's profile to **.NET Framework 4** (not .NET Framework 4 client profile). This can be done by going to _Project->Project properties->Application_.

Now, go to _Solution Explorer->References->Add Reference->.NET_ and import **System.Web** .
Also make sure you have the following lines included in your project's header:

```csharp
using System;
using System.Net;
using System.IO;
using System.Text;
```

Creating the server is quite simple - we'll use .NET's **HttpListener**:

```csharp
HttpListener server = new HttpListener();  // this is the http server
server.Prefixes.Add("http://127.0.0.1/");  //we set a listening address here (localhost)
server.Prefixes.Add("http://localhost/");

server.Start();   // and start the server
```

The server is made, now we need to identify incoming connections and serve the requested files. For each connection, we send only one file and because we might have multiple connections, we'll need an endless loop to handle them one by one.

```csharp
while (true)
{
          HttpListenerContext context = server.GetContext();
          //context: provides access to httplistener's response

          HttpListenerResponse response = context.Response;
         //the response tells the server where to send the datas

          string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath;
          //this will get the page requested by the browser

          if (page == string.Empty)  //if there's no page, we'll say it's index.html
              page = "index.html";

          TextReader tr = new StreamReader(page);
          string msg = tr.ReadToEnd();  //getting the page's content

          byte[] buffer = Encoding.UTF8.GetBytes(msg);
          //then we transform it into a byte array

          response.ContentLength64 = buffer.Length;  // set up the messasge's length
          Stream st = response.OutputStream;  // here we create a stream to send the message
          st.Write(buffer, 0, buffer.Length); // and this will send all the content to the browser

          context.Response.Close();  // here we close the connection
}
```

Well, this is all, now all you need to do is to create some html pages and place them into your executable's directory.
Then run the application and access
**http://127.0.0.1/anyfile.html**.

You should be able to see your file in the browser's window.

## The complete code

```csharp
using System;
using System.Net;
using System.IO;
using System.Text;

namespace test
{

    class Program
    {
        static void Main(string[] args)
        {
            HttpListener server = new HttpListener();
            server.Prefixes.Add("http://127.0.0.1/");
            server.Prefixes.Add("http://localhost/");

            server.Start();

            Console.WriteLine("Listening...");

            while (true)
            {
                HttpListenerContext context = server.GetContext();
                HttpListenerResponse response = context.Response;

                string page = Directory.GetCurrentDirectory() + context.Request.Url.LocalPath;

                if (page == string.Empty)
                    page = "index.html";

                TextReader tr = new StreamReader(page);
                string msg = tr.ReadToEnd();

                byte[] buffer = Encoding.UTF8.GetBytes(msg);

                response.ContentLength64 = buffer.Length;
                Stream st = response.OutputStream;
                st.Write(buffer, 0, buffer.Length);

                context.Response.Close();
            }

        }
    }

}
```

Remember that this server isn't able to parse server-side languages like PHP or ASP.NET, it just sends the file's content to the browser. If you're interested in embedding ASP.NET into a http server [see this tutorial](http://www.codingvision.net/networking/c-http-server-with-aspnet).


text:
package main

import (
	"fmt"

	"github.com/opsgenie/opsgenie-go-sdk/_samples/constants"
	ogcli "github.com/opsgenie/opsgenie-go-sdk/client"
	"github.com/opsgenie/opsgenie-go-sdk/userv2"
)

func main() {
	cli := new(ogcli.OpsGenieClient)
	cli.SetAPIKey(constants.APIKey)

	userCli, _ := cli.UserV2()

	request := userv2.ListUserSchedulesRequest{
		Identifier: &userv2.Identifier{Username: "user@company.com"},
	}

	response, err := userCli.ListSchedules(request)
	if err != nil {
		fmt.Println(err)
	} else {
		for _, schedule := range response.Schedules {
			fmt.Println(schedule.Name)
		}
	}
}


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

namespace BookInfo.WebUI.Models
{
    public class StatisticsViewModel
    {
        public int Authors { get; set; }
        public int Titles { get; set; }
    }
}


text:
#pragma once

#if ENABLE(GAMEPAD)

#include <wtf/Forward.h>

namespace WebCore {

class PlatformGamepad;

class GamepadProviderClient {
public:
    virtual ~GamepadProviderClient() = default;

    virtual void setInitialConnectedGamepads(const Vector<PlatformGamepad*>&) { }
    virtual void platformGamepadConnected(PlatformGamepad&) = 0;
    virtual void platformGamepadDisconnected(PlatformGamepad&) = 0;
    virtual void platformGamepadInputActivity(bool shouldMakeGamepadVisible) = 0;
};

} // namespace WebCore

#endif // ENABLE(GAMEPAD)


text:
layout: page
title: "Reading List"
description: "A series of papers, books or other resources that I should get round to reading at some point"
---
{% include JB/setup %}

## Posts to be done

* Basically available soft state eventual consistency
* Bloom Filters, caching your way to performance
* CAP theorem
* Components of a database management system
* Designing a graph file system
* Gossip protocols
* Haskell all you need to know - Turned into [haskell.zcourts.com](http://haskell.zcourts.com)
* Haskell FFI, working with C libraries (see above)
* Imutability, a beautiful future
* Introduction to the fundamentals of graph theory
* Log structured merge trees for the rest of us (and why it doesn't work for graphs)
* Voltage Cluster (Finding communities in linear time: a physics approach)
* Markov cluster (http://micans.org/mcl/) Thesis => http://micans.org/mcl/index.html?sec_thesisetc
* Network modularity - http://en.wikipedia.org/wiki/Modularity_(networks)
* Clique - http://en.wikipedia.org/wiki/Clique_(graph_theory)
* Fuzy clustering - http://en.wikipedia.org/wiki/Fuzzy_clustering
* BIRCH - http://en.wikipedia.org/wiki/Birch_(data_clustering)

## TODO

Update with list of papers in the repo.

## Problems that can be solved with graphs

Having data represented as graphs is one thing but once you have that graph, what do you want to know about it? What can it tell you?
This is a collection of resources with ideas of how to use graphs or graph algorithms.

[Graphs from real life problems __question__](http://cstheory.stackexchange.com/questions/3409/graphs-from-real-life-problems)
[Data for testing graphs __question__](http://cstheory.stackexchange.com/questions/739/data-for-testing-graph-algorithms)
[Generating interesting combinatorial optimization problems](http://cstheory.stackexchange.com/questions/16751/generating-interesting-combinatorial-optimization-problems)

[Stanford network analysis project - SNAP](http://snap.stanford.edu/index.html)
[Data collection from SNAP](http://snap.stanford.edu/data/)

[DIMACS challenge data](http://www.dis.uniroma1.it/challenge9/download.shtml#benchmark)

[Stanford's GraphBase __Knuth__](http://www-cs-staff.stanford.edu/~knuth/sgb.html)

[Nauty and traces - new site](http://pallini.di.uniroma1.it/)
[Nauty and Traces - generate graphs, old site](http://cs.anu.edu.au/~bdm/nauty/)

[Clique Benchmark Instances](http://cs.hbg.psu.edu/benchmarks/clique.html)

[Graph colouring instances](http://mat.gsia.cmu.edu/COLOR/instances.html)

[The Open Graph Archive: A Community-Driven Effort](http://arxiv.org/abs/1109.1465)
[Graph archive](http://www.graph-archive.org/doku.php)

[UCI Network Data Repository](http://networkdata.ics.uci.edu/index.html)
[UCI Public dataset](http://networkdata.ics.uci.edu/resources.php)

[Washington state graph dataset](http://www.eecs.wsu.edu/mgd/gdb.html)

[GraphChi technique](http://graphlab.org/graphchi/)
[GraphLab's DataSet](http://graphlab.org/downloads/datasets/)

[Networks, Crowds and Markets, reasoning about a highly connected world](http://www.cs.cornell.edu/home/kleinber/networks-book/)

[Introduction to graph theory- Wikibooks](http://en.wikibooks.org/wiki/Graph_Theory/Introduction)

[Problem solving using graph traversals](http://www.slideshare.net/slidarko/problemsolving-using-graph-traversals-searching-scoring-ranking-and-recommendation)

[An Introduction to Graph Theory and Complex Networks](http://www.di.unipi.it/~ricci/book-watermarked.pdf)


text:
set -e

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

PARENT_DIR=$(dirname "$DIR")
source $PARENT_DIR/dist/inquirer.sh

text_input "What's your first name" name

hawker_centres=( 'Old Airport Road Hawker Centre' 'Golden Mile Food Complex' 'Maxwell Food Centre' 'Newton Food Centre' )
checkbox_input "Which hawker centres do you prefer?" hawker_centres selected_hawkers

drinks=( 'Teh' 'Teh Ping Gao Siu Dai' 'Kopi O' 'Yuan Yang' )
list_input "What would you like to drink today?" drinks selected_drink

food=( 'Chicken Rice' 'Lor Mee' 'Nasi Lemak' 'Bak Kut Teh' )
list_input "What would you like to eat today?" food selected_food

echo "              Your selections                   "
echo "------------------------------------------------"
echo "Name: $name"
echo "Drink: $selected_drink"
echo "Food: $selected_food"
echo "Hawker Centres: $(join selected_hawkers)"
echo "------------------------------------------------"


text:
.mc-item,
.mc-item > * {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.mc-item {
  position: relative;
}

.mc-item > .mc-item__image,
.mc-item > .mc-item__caption {
  display: block;
  -webkit-transition: all 0.3s ease-in;
  transition: all 0.3s ease-in;
}

.mc-item > .mc-item__image {
  width: 100%;
}

.mc-item .mc-item__caption {
  background-color: #7f8c8d;
}

/* -------------------------
   Effect 1
---------------------------- */
.mc-item.mc-item--fadeIn > .mc-item__caption {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  -webkit-transform: translate(0, 0);
  transform: translate(0, 0);
  width: 100%;
  height: 100%;
}

.mc-item.mc-item--fadeIn:hover > .mc-item__caption, .mc-item.mc-item--fadeIn.touch > .mc-item__caption {
  opacity: 1;
  -webkit-transform: translate(1em, 1em);
  transform: translate(1em, 1em);
}

/* -------------------------
   Effect 2
---------------------------- */
.mc-item.mc-item--slideInUp, .mc-item.mc-item--slideInUpBig, .mc-item.mc-item--slideInDown, .mc-item.mc-item--slideInDownBig {
  overflow: hidden;
}

.mc-item.mc-item--slideInUp > .mc-item__image, .mc-item.mc-item--slideInUpBig > .mc-item__image, .mc-item.mc-item--slideInDown > .mc-item__image, .mc-item.mc-item--slideInDownBig > .mc-item__image {
  -webkit-transform: translateY(0);
  transform: translateY(0);
}

.mc-item.mc-item--slideInUp > .mc-item__caption, .mc-item.mc-item--slideInUpBig > .mc-item__caption, .mc-item.mc-item--slideInDown > .mc-item__caption, .mc-item.mc-item--slideInDownBig > .mc-item__caption {
  position: absolute;
  left: 0;
  width: 100%;
}

.mc-item.mc-item--slideInUp:hover > .mc-item__caption, .mc-item.mc-item--slideInUp.touch > .mc-item__caption, .mc-item.mc-item--slideInUpBig:hover > .mc-item__caption, .mc-item.mc-item--slideInUpBig.touch > .mc-item__caption, .mc-item.mc-item--slideInDown:hover > .mc-item__caption, .mc-item.mc-item--slideInDown.touch > .mc-item__caption, .mc-item.mc-item--slideInDownBig:hover > .mc-item__caption, .mc-item.mc-item--slideInDownBig.touch > .mc-item__caption {
  -webkit-transform: translateY(0);
  transform: translateY(0);
}

.mc-item.mc-item--slideInUpBig > .mc-item__caption, .mc-item.mc-item--slideInDownBig > .mc-item__caption {
  height: 100%;
}

.mc-item.mc-item--slideInUp > .mc-item__caption, .mc-item.mc-item--slideInUpBig > .mc-item__caption {
  bottom: 0;
  -webkit-transform: translateY(100%);
  transform: translateY(100%);
}

.mc-item.mc-item--slideInUp:hover > .mc-item__image, .mc-item.mc-item--slideInUp.touch > .mc-item__image, .mc-item.mc-item--slideInUpBig:hover > .mc-item__image, .mc-item.mc-item--slideInUpBig.touch > .mc-item__image {
  -webkit-transform: translateY(-2em);
  transform: translateY(-2em);
}

.mc-item.mc-item--slideInDown > .mc-item__caption, .mc-item.mc-item--slideInDownBig > .mc-item__caption {
  top: 0;
  -webkit-transform: translateY(-100%);
  transform: translateY(-100%);
}

.mc-item.mc-item--slideInDown:hover > .mc-item__image, .mc-item.mc-item--slideInDown.touch > .mc-item__image, .mc-item.mc-item--slideInDownBig:hover > .mc-item__image, .mc-item.mc-item--slideInDownBig.touch > .mc-item__image {
  -webkit-transform: translateY(2em);
  transform: translateY(2em);
}

/* -------------------------
   Effect 3
---------------------------- */
.mc-item.mc-item--slideInUp-zoomIn, .mc-item.mc-item--slideInUpBig-zoomIn, .mc-item.mc-item--slideInDown-zoomIn, .mc-item.mc-item--slideInDownBig-zoomIn {
  overflow: hidden;
}

.mc-item.mc-item--slideInUp-zoomIn > .mc-item__image, .mc-item.mc-item--slideInUpBig-zoomIn > .mc-item__image, .mc-item.mc-item--slideInDown-zoomIn > .mc-item__image, .mc-item.mc-item--slideInDownBig-zoomIn > .mc-item__image {
  -webkit-transform: scale(1);
  transform: scale(1);
}

.mc-item.mc-item--slideInUp-zoomIn > .mc-item__caption, .mc-item.mc-item--slideInUpBig-zoomIn > .mc-item__caption, .mc-item.mc-item--slideInDown-zoomIn > .mc-item__caption, .mc-item.mc-item--slideInDownBig-zoomIn > .mc-item__caption {
  position: absolute;
  left: 0;
  width: 100%;
}

.mc-item.mc-item--slideInUp-zoomIn:hover > .mc-item__image, .mc-item.mc-item--slideInUp-zoomIn.touch > .mc-item__image, .mc-item.mc-item--slideInUpBig-zoomIn:hover > .mc-item__image, .mc-item.mc-item--slideInUpBig-zoomIn.touch > .mc-item__image, .mc-item.mc-item--slideInDown-zoomIn:hover > .mc-item__image, .mc-item.mc-item--slideInDown-zoomIn.touch > .mc-item__image, .mc-item.mc-item--slideInDownBig-zoomIn:hover > .mc-item__image, .mc-item.mc-item--slideInDownBig-zoomIn.touch > .mc-item__image {
  -webkit-transform: scale(1.5);
  transform: scale(1.5);
}

.mc-item.mc-item--slideInUp-zoomIn:hover > .mc-item__caption, .mc-item.mc-item--slideInUp-zoomIn.touch > .mc-item__caption, .mc-item.mc-item--slideInUpBig-zoomIn:hover > .mc-item__caption, .mc-item.mc-item--slideInUpBig-zoomIn.touch > .mc-item__caption, .mc-item.mc-item--slideInDown-zoomIn:hover > .mc-item__caption, .mc-item.mc-item--slideInDown-zoomIn.touch > .mc-item__caption, .mc-item.mc-item--slideInDownBig-zoomIn:hover > .mc-item__caption, .mc-item.mc-item--slideInDownBig-zoomIn.touch > .mc-item__caption {
  -webkit-transform: translateY(0);
  transform: translateY(0);
}

.mc-item.mc-item--slideInUpBig-zoomIn > .mc-item__caption, .mc-item.mc-item--slideInDownBig-zoomIn > .mc-item__caption {
  height: 100%;
}

.mc-item.mc-item--slideInUp-zoomIn > .mc-item__caption, .mc-item.mc-item--slideInUpBig-zoomIn > .mc-item__caption {
  bottom: 0;
  -webkit-transform: translateY(100%);
  transform: translateY(100%);
}

.mc-item.mc-item--slideInDown-zoomIn > .mc-item__caption, .mc-item.mc-item--slideInDownBig-zoomIn > .mc-item__caption {
  top: 0;
  -webkit-transform: translateY(-100%);
  transform: translateY(-100%);
}

/* -------------------------
   Effect 4
---------------------------- */
.mc-item.mc-item--zoomOut > .mc-item__image, .mc-item.mc-item--zoomOutUp > .mc-item__image, .mc-item.mc-item--zoomOutDown > .mc-item__image {
  z-index: 2;
  position: relative;
  -webkit-transform: translate(0, 0) scale(1);
  transform: translate(0, 0) scale(1);
}

.mc-item.mc-item--zoomOut > .mc-item__caption, .mc-item.mc-item--zoomOutUp > .mc-item__caption, .mc-item.mc-item--zoomOutDown > .mc-item__caption {
  z-index: 0;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.mc-item.mc-item--zoomOut:hover > .mc-item__image, .mc-item.mc-item--zoomOut.touch > .mc-item__image, .mc-item.mc-item--zoomOutUp:hover > .mc-item__image, .mc-item.mc-item--zoomOutUp.touch > .mc-item__image, .mc-item.mc-item--zoomOutDown:hover > .mc-item__image, .mc-item.mc-item--zoomOutDown.touch > .mc-item__image {
  -webkit-transform: translate(0, 0) scale(0.4);
  transform: translate(0, 0) scale(0.4);
}

.mc-item.mc-item--zoomOutUp:hover > .mc-item__image, .mc-item.mc-item--zoomOutUp.touch > .mc-item__image {
  -webkit-transform: translate(0, -20%) scale(0.4);
  transform: translate(0, -20%) scale(0.4);
}

.mc-item.mc-item--zoomOutDown:hover > .mc-item__image, .mc-item.mc-item--zoomOutDown.touch > .mc-item__image {
  -webkit-transform: translate(0, 20%) scale(0.4);
  transform: translate(0, 20%) scale(0.4);
}

/* -------------------------
   Effect 5
---------------------------- */
.mc-item.mc-item--slideInUpBig-zoomOut, .mc-item.mc-item--slideInDownBig-zoomOut, .mc-item.mc-item--slideInLeftBig-zoomOut, .mc-item.mc-item--slideInRightBig-zoomOut {
  overflow: hidden;
}

.mc-item.mc-item--slideInUpBig-zoomOut > .mc-item__image, .mc-item.mc-item--slideInDownBig-zoomOut > .mc-item__image, .mc-item.mc-item--slideInLeftBig-zoomOut > .mc-item__image, .mc-item.mc-item--slideInRightBig-zoomOut > .mc-item__image {
  -webkit-transform: scale(1);
  transform: scale(1);
}

.mc-item.mc-item--slideInUpBig-zoomOut > .mc-item__caption, .mc-item.mc-item--slideInDownBig-zoomOut > .mc-item__caption, .mc-item.mc-item--slideInLeftBig-zoomOut > .mc-item__caption, .mc-item.mc-item--slideInRightBig-zoomOut > .mc-item__caption {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.mc-item.mc-item--slideInUpBig-zoomOut:hover > .mc-item__image, .mc-item.mc-item--slideInUpBig-zoomOut.touch > .mc-item__image, .mc-item.mc-item--slideInDownBig-zoomOut:hover > .mc-item__image, .mc-item.mc-item--slideInDownBig-zoomOut.touch > .mc-item__image, .mc-item.mc-item--slideInLeftBig-zoomOut:hover > .mc-item__image, .mc-item.mc-item--slideInLeftBig-zoomOut.touch > .mc-item__image, .mc-item.mc-item--slideInRightBig-zoomOut:hover > .mc-item__image, .mc-item.mc-item--slideInRightBig-zoomOut.touch > .mc-item__image {
  -webkit-transform: scale(0.5);
  transform: scale(0.5);
}

.mc-item.mc-item--slideInUpBig-zoomOut:hover > .mc-item__caption, .mc-item.mc-item--slideInUpBig-zoomOut.touch > .mc-item__caption, .mc-item.mc-item--slideInDownBig-zoomOut:hover > .mc-item__caption, .mc-item.mc-item--slideInDownBig-zoomOut.touch > .mc-item__caption, .mc-item.mc-item--slideInLeftBig-zoomOut:hover > .mc-item__caption, .mc-item.mc-item--slideInLeftBig-zoomOut.touch > .mc-item__caption, .mc-item.mc-item--slideInRightBig-zoomOut:hover > .mc-item__caption, .mc-item.mc-item--slideInRightBig-zoomOut.touch > .mc-item__caption {
  -webkit-transition-delay: 0.2s;
  transition-delay: 0.2s;
  -webkit-transform: translate(0, 0);
  transform: translate(0, 0);
}

.mc-item.mc-item--slideInUpBig-zoomOut > .mc-item__caption {
  -webkit-transform: translate(0, 100%);
  transform: translate(0, 100%);
}

.mc-item.mc-item--slideInDownBig-zoomOut > .mc-item__caption {
  -webkit-transform: translate(0, -100%);
  transform: translate(0, -100%);
}

.mc-item.mc-item--slideInLeftBig-zoomOut > .mc-item__caption {
  -webkit-transform: translate(-100%, 0);
  transform: translate(-100%, 0);
}

.mc-item.mc-item--slideInRightBig-zoomOut > .mc-item__caption {
  -webkit-transform: translate(100%, 0);
  transform: translate(100%, 0);
}

/* -------------------------
   Effect 6
---------------------------- */
.mc-item.mc-item--slideInLeftHalf, .mc-item.mc-item--slideInRightHalf {
  overflow: hidden;
}

.mc-item.mc-item--slideInLeftHalf > .mc-item__image, .mc-item.mc-item--slideInRightHalf > .mc-item__image {
  -webkit-transform: translateX(0);
  transform: translateX(0);
}

.mc-item.mc-item--slideInLeftHalf > .mc-item__caption, .mc-item.mc-item--slideInRightHalf > .mc-item__caption {
  position: absolute;
  top: 0;
  width: 50%;
  height: 100%;
}

.mc-item.mc-item--slideInLeftHalf:hover > .mc-item__caption, .mc-item.mc-item--slideInLeftHalf.touch > .mc-item__caption, .mc-item.mc-item--slideInRightHalf:hover > .mc-item__caption, .mc-item.mc-item--slideInRightHalf.touch > .mc-item__caption {
  -webkit-transform: translateX(0);
  transform: translateX(0);
}

.mc-item.mc-item--slideInLeftHalf > .mc-item__caption {
  left: 0;
  -webkit-transform: translateX(-100%);
  transform: translateX(-100%);
}

.mc-item.mc-item--slideInLeftHalf:hover .mc-item__image, .mc-item.mc-item--slideInLeftHalf.touch .mc-item__image {
  -webkit-transform: translateX(50%);
  transform: translateX(50%);
}

.mc-item.mc-item--slideInRightHalf > .mc-item__caption {
  right: 0;
  -webkit-transform: translateX(100%);
  transform: translateX(100%);
}

.mc-item.mc-item--slideInRightHalf:hover .mc-item__image, .mc-item.mc-item--slideInRightHalf.touch .mc-item__image {
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
}

/* -------------------------
   Effect 7
---------------------------- */
.mc-item.mc-item--flipOutUp, .mc-item.mc-item--flipOutDown, .mc-item.mc-item--flipOutLeft, .mc-item.mc-item--flipOutRight {
  -webkit-perspective: 82em;
  perspective: 82em;
}

.mc-item.mc-item--flipOutUp .mc-item__image, .mc-item.mc-item--flipOutDown .mc-item__image, .mc-item.mc-item--flipOutLeft .mc-item__image, .mc-item.mc-item--flipOutRight .mc-item__image {
  opacity: 1;
}

.mc-item.mc-item--flipOutUp > .mc-item__caption, .mc-item.mc-item--flipOutDown > .mc-item__caption, .mc-item.mc-item--flipOutLeft > .mc-item__caption, .mc-item.mc-item--flipOutRight > .mc-item__caption {
  position: absolute;
  opacity: 0;
  visibility: hidden;
  width: 100%;
  height: 100%;
}

.mc-item.mc-item--flipOutUp:hover .mc-item__image, .mc-item.mc-item--flipOutUp.touch .mc-item__image, .mc-item.mc-item--flipOutDown:hover .mc-item__image, .mc-item.mc-item--flipOutDown.touch .mc-item__image, .mc-item.mc-item--flipOutLeft:hover .mc-item__image, .mc-item.mc-item--flipOutLeft.touch .mc-item__image, .mc-item.mc-item--flipOutRight:hover .mc-item__image, .mc-item.mc-item--flipOutRight.touch .mc-item__image {
  opacity: 0;
}

.mc-item.mc-item--flipOutUp:hover > .mc-item__caption, .mc-item.mc-item--flipOutUp.touch > .mc-item__caption, .mc-item.mc-item--flipOutDown:hover > .mc-item__caption, .mc-item.mc-item--flipOutDown.touch > .mc-item__caption, .mc-item.mc-item--flipOutLeft:hover > .mc-item__caption, .mc-item.mc-item--flipOutLeft.touch > .mc-item__caption, .mc-item.mc-item--flipOutRight:hover > .mc-item__caption, .mc-item.mc-item--flipOutRight.touch > .mc-item__caption {
  opacity: 1;
  visibility: visible;
  -webkit-transform: rotate3d(0, 0, 0, 0);
  transform: rotate3d(0, 0, 0, 0);
}

.mc-item.mc-item--flipOutUp > .mc-item__image,
.mc-item.mc-item--flipOutUp > .mc-item__caption {
  -webkit-transform-origin: 0% 100%;
  transform-origin: 0% 100%;
}

.mc-item.mc-item--flipOutUp > .mc-item__caption {
  left: 0;
  bottom: 0;
  -webkit-transform: rotate3d(1, 0, 0, -90deg);
  transform: rotate3d(1, 0, 0, -90deg);
}

.mc-item.mc-item--flipOutUp:hover > .mc-item__image, .mc-item.mc-item--flipOutUp.touch > .mc-item__image {
  -webkit-transform: rotate3d(1, 0, 0, 90deg);
  transform: rotate3d(1, 0, 0, 90deg);
}

.mc-item.mc-item--flipOutDown > .mc-item__image,
.mc-item.mc-item--flipOutDown > .mc-item__caption {
  -webkit-transform-origin: 0% 0%;
  transform-origin: 0% 0%;
}

.mc-item.mc-item--flipOutDown > .mc-item__caption {
  top: 0;
  left: 0;
  -webkit-transform: rotate3d(1, 0, 0, 90deg);
  transform: rotate3d(1, 0, 0, 90deg);
}

.mc-item.mc-item--flipOutDown:hover > .mc-item__image, .mc-item.mc-item--flipOutDown.touch > .mc-item__image {
  -webkit-transform: rotate3d(1, 0, 0, -90deg);
  transform: rotate3d(1, 0, 0, -90deg);
}

.mc-item.mc-item--flipOutLeft > .mc-item__image,
.mc-item.mc-item--flipOutLeft > .mc-item__caption {
  -webkit-transform-origin: 0% 0%;
  transform-origin: 0% 0%;
}

.mc-item.mc-item--flipOutLeft > .mc-item__caption {
  top: 0;
  left: 0;
  -webkit-transform: rotate3d(0, 1, 0, -90deg);
  transform: rotate3d(0, 1, 0, -90deg);
}

.mc-item.mc-item--flipOutLeft:hover > .mc-item__image, .mc-item.mc-item--flipOutLeft.touch > .mc-item__image {
  -webkit-transform: rotate3d(0, 1, 0, 90deg);
  transform: rotate3d(0, 1, 0, 90deg);
}

.mc-item.mc-item--flipOutRight > .mc-item__image,
.mc-item.mc-item--flipOutRight > .mc-item__caption {
  -webkit-transform-origin: 100% 0%;
  transform-origin: 100% 0%;
}

.mc-item.mc-item--flipOutRight > .mc-item__caption {
  top: 0;
  right: 0;
  -webkit-transform: rotate3d(0, 1, 0, 90deg);
  transform: rotate3d(0, 1, 0, 90deg);
}

.mc-item.mc-item--flipOutRight:hover > .mc-item__image, .mc-item.mc-item--flipOutRight.touch > .mc-item__image {
  -webkit-transform: rotate3d(0, 1, 0, -90deg);
  transform: rotate3d(0, 1, 0, -90deg);
}


text:
namespace em = enterprise_management;

using testing::_;

namespace policy {

class CloudPolicyServiceTest : public testing::Test {
 public:
  CloudPolicyServiceTest()
      : policy_type_(dm_protocol::kChromeUserPolicyType),
        service_(policy_type_, std::string(), &client_, &store_) {}

  MOCK_METHOD1(OnPolicyRefresh, void(bool));
  MOCK_METHOD1(OnUnregister, void(bool));

 protected:
  std::string policy_type_;
  MockCloudPolicyClient client_;
  MockCloudPolicyStore store_;
  CloudPolicyService service_;
};

MATCHER_P(ProtoMatches, proto, std::string()) {
  return arg.SerializePartialAsString() == proto.SerializePartialAsString();
}

TEST_F(CloudPolicyServiceTest, PolicyUpdateSuccess) {
  em::PolicyFetchResponse policy;
  policy.set_policy_data("fake policy");
  client_.SetPolicy(policy_type_, std::string(), policy);
  EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1);
  client_.NotifyPolicyFetched();

  // After |store_| initializes, credentials and other meta data should be
  // transferred to |client_|.
  auto policy_data = std::make_unique<em::PolicyData>();
  policy_data->set_request_token("fake token");
  policy_data->set_device_id("fake client id");
  policy_data->set_timestamp(32);
  policy_data->set_public_key_version(17);
  policy_data->add_user_affiliation_ids("id1");
  store_.set_policy_data_for_testing(std::move(policy_data));
  std::vector<std::string> user_affiliation_ids = {
      store_.policy()->user_affiliation_ids(0)};
  EXPECT_CALL(client_, SetupRegistration(store_.policy()->request_token(),
                                         store_.policy()->device_id(),
                                         user_affiliation_ids))
      .Times(1);
  EXPECT_CALL(client_, UploadPolicyValidationReport(_, _, _, _)).Times(0);
  store_.NotifyStoreLoaded();
  EXPECT_EQ(base::Time::FromJavaTime(32), client_.last_policy_timestamp_);
  EXPECT_TRUE(client_.public_key_version_valid_);
  EXPECT_EQ(17, client_.public_key_version_);
}

TEST_F(CloudPolicyServiceTest, PolicyUpdateClientFailure) {
  client_.SetStatus(DM_STATUS_REQUEST_FAILED);
  EXPECT_CALL(store_, Store(_)).Times(0);
  client_.NotifyPolicyFetched();
}

TEST_F(CloudPolicyServiceTest, RefreshPolicySuccess) {
  testing::InSequence seq;

  EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0);
  client_.SetDMToken("fake token");

  // Trigger a fetch on the client.
  EXPECT_CALL(client_, FetchPolicy()).Times(1);
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));

  // Client responds, push policy to store.
  em::PolicyFetchResponse policy;
  policy.set_policy_data("fake policy");
  client_.SetPolicy(policy_type_, std::string(), policy);
  client_.fetched_invalidation_version_ = 12345;
  EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1);
  EXPECT_EQ(0, store_.invalidation_version());
  client_.NotifyPolicyFetched();
  EXPECT_EQ(12345, store_.invalidation_version());

  // Store reloads policy, callback gets triggered.
  auto policy_data = std::make_unique<em::PolicyData>();
  policy_data->set_request_token("token");
  policy_data->set_device_id("device-id");
  store_.set_policy_data_for_testing(std::move(policy_data));
  EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(1);
  store_.NotifyStoreLoaded();
}

TEST_F(CloudPolicyServiceTest, RefreshPolicyNotRegistered) {
  // Clear the token so the client is not registered.
  client_.SetDMToken(std::string());

  EXPECT_CALL(client_, FetchPolicy()).Times(0);
  EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));
}

TEST_F(CloudPolicyServiceTest, RefreshPolicyClientError) {
  testing::InSequence seq;

  EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0);
  client_.SetDMToken("fake token");

  // Trigger a fetch on the client.
  EXPECT_CALL(client_, FetchPolicy()).Times(1);
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));

  // Client responds with an error, which should trigger the callback.
  client_.SetStatus(DM_STATUS_REQUEST_FAILED);
  EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
  client_.NotifyClientError();
}

TEST_F(CloudPolicyServiceTest, RefreshPolicyStoreError) {
  testing::InSequence seq;

  EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0);
  client_.SetDMToken("fake token");

  // Trigger a fetch on the client.
  EXPECT_CALL(client_, FetchPolicy()).Times(1);
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));

  // Client responds, push policy to store.
  em::PolicyFetchResponse policy;
  policy.set_policy_data("fake policy");
  client_.SetPolicy(policy_type_, std::string(), policy);
  EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1);
  client_.NotifyPolicyFetched();

  // Store fails, which should trigger the callback.
  EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(1);
  store_.NotifyStoreError();
}

TEST_F(CloudPolicyServiceTest, RefreshPolicyConcurrent) {
  testing::InSequence seq;

  EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0);
  client_.SetDMToken("fake token");

  // Trigger a fetch on the client.
  EXPECT_CALL(client_, FetchPolicy()).Times(1);
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));

  // Triggering another policy refresh should generate a new fetch request.
  EXPECT_CALL(client_, FetchPolicy()).Times(1);
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));

  // Client responds, push policy to store.
  em::PolicyFetchResponse policy;
  policy.set_policy_data("fake policy");
  client_.SetPolicy(policy_type_, std::string(), policy);
  EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1);
  client_.NotifyPolicyFetched();

  // Trigger another policy fetch.
  EXPECT_CALL(client_, FetchPolicy()).Times(1);
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));

  // The store finishing the first load should not generate callbacks.
  EXPECT_CALL(*this, OnPolicyRefresh(_)).Times(0);
  store_.NotifyStoreLoaded();

  // Second policy fetch finishes.
  EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1);
  client_.NotifyPolicyFetched();

  // Corresponding store operation finishes, all _three_ callbacks fire.
  EXPECT_CALL(*this, OnPolicyRefresh(true)).Times(3);
  store_.NotifyStoreLoaded();
}

TEST_F(CloudPolicyServiceTest, UnregisterSucceeds) {
  EXPECT_CALL(client_, Unregister());
  EXPECT_CALL(*this, OnUnregister(true));

  service_.Unregister(base::BindOnce(&CloudPolicyServiceTest::OnUnregister,
                                     base::Unretained(this)));
  client_.NotifyRegistrationStateChanged();
}

TEST_F(CloudPolicyServiceTest, UnregisterFailsOnClientError) {
  EXPECT_CALL(client_, Unregister());
  EXPECT_CALL(*this, OnUnregister(false));

  service_.Unregister(base::BindOnce(&CloudPolicyServiceTest::OnUnregister,
                                     base::Unretained(this)));
  client_.NotifyClientError();
}

TEST_F(CloudPolicyServiceTest, UnregisterRevokesAllOnGoingPolicyRefreshes) {
  EXPECT_CALL(client_, Unregister());
  EXPECT_CALL(*this, OnPolicyRefresh(false)).Times(2);

  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));
  service_.Unregister(base::BindOnce(&CloudPolicyServiceTest::OnUnregister,
                                     base::Unretained(this)));
}

TEST_F(CloudPolicyServiceTest, RefreshPolicyFailsWhenUnregistering) {
  EXPECT_CALL(client_, Unregister());
  EXPECT_CALL(*this, OnPolicyRefresh(false));

  service_.Unregister(base::BindOnce(&CloudPolicyServiceTest::OnUnregister,
                                     base::Unretained(this)));
  service_.RefreshPolicy(base::BindOnce(
      &CloudPolicyServiceTest::OnPolicyRefresh, base::Unretained(this)));
}

TEST_F(CloudPolicyServiceTest, StoreAlreadyInitialized) {
  // Service should start off initialized if the store has already loaded
  // policy.
  store_.NotifyStoreLoaded();
  CloudPolicyService service(policy_type_, std::string(), &client_, &store_);
  EXPECT_TRUE(service.IsInitializationComplete());
}

TEST_F(CloudPolicyServiceTest, StoreLoadAfterCreation) {
  // Service should start off un-initialized if the store has not yet loaded
  // policy.
  EXPECT_FALSE(service_.IsInitializationComplete());
  MockCloudPolicyServiceObserver observer;
  service_.AddObserver(&observer);
  // Service should be marked as initialized and observer should be called back.
  EXPECT_CALL(observer, OnCloudPolicyServiceInitializationCompleted()).Times(1);
  store_.NotifyStoreLoaded();
  EXPECT_TRUE(service_.IsInitializationComplete());
  testing::Mock::VerifyAndClearExpectations(&observer);

  // Now, the next time the store is loaded, the observer should not be called
  // again.
  EXPECT_CALL(observer, OnCloudPolicyServiceInitializationCompleted()).Times(0);
  store_.NotifyStoreLoaded();
  service_.RemoveObserver(&observer);
}

TEST_F(CloudPolicyServiceTest, ReportValidationResult) {
  // Sync |policy_data_signature| between store and service by fetching a
  // policy.
  em::PolicyFetchResponse policy;
  policy.set_policy_data_signature("fake-policy-data-signature");
  client_.SetPolicy(policy_type_, std::string(), policy);
  EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1);
  EXPECT_CALL(client_, UploadPolicyValidationReport(_, _, _, _)).Times(0);
  client_.NotifyPolicyFetched();

  // Simulate a value validation error from the store and expect a validation
  // report to be uploaded.
  store_.validation_result_ =
      std::make_unique<CloudPolicyValidatorBase::ValidationResult>();
  store_.validation_result_->status =
      CloudPolicyValidatorBase::VALIDATION_VALUE_ERROR;
  store_.validation_result_->value_validation_issues.push_back(
      {"fake-policy-name", ValueValidationIssue::kError, "message"});
  store_.validation_result_->policy_token = "fake-policy-token";
  store_.validation_result_->policy_data_signature =
      "fake-policy-data-signature";
  EXPECT_CALL(client_,
              UploadPolicyValidationReport(
                  store_.validation_result_->status,
                  store_.validation_result_->value_validation_issues,
                  policy_type_, store_.validation_result_->policy_token))
      .Times(1);
  store_.NotifyStoreError();

  // A second validation of the same policy should not trigger another upload.
  EXPECT_CALL(client_, UploadPolicyValidationReport(_, _, _, _)).Times(0);
  store_.NotifyStoreError();

  testing::Mock::VerifyAndClearExpectations(&client_);
}

TEST_F(CloudPolicyServiceTest, ReportValidationResultWrongSignature) {
  // Sync |policy_data_signature| between store and service by fetching a
  // policy.
  em::PolicyFetchResponse policy;
  policy.set_policy_data_signature("fake-policy-data-signature-1");
  client_.SetPolicy(policy_type_, std::string(), policy);
  EXPECT_CALL(store_, Store(ProtoMatches(policy))).Times(1);
  EXPECT_CALL(client_, UploadPolicyValidationReport(_, _, _, _)).Times(0);
  client_.NotifyPolicyFetched();

  // Simulate a value validation error from the store with a different policy
  // data signature. No Validation report should be uploaded in that case.
  store_.validation_result_ =
      std::make_unique<CloudPolicyValidatorBase::ValidationResult>();
  store_.validation_result_->status =
      CloudPolicyValidatorBase::VALIDATION_VALUE_ERROR;
  store_.validation_result_->value_validation_issues.push_back(
      {"fake-policy-name", ValueValidationIssue::kError, "message"});
  store_.validation_result_->policy_token = "fake-policy-token";
  store_.validation_result_->policy_data_signature =
      "fake-policy-data-signature-2";
  EXPECT_CALL(client_, UploadPolicyValidationReport(_, _, _, _)).Times(0);
  store_.NotifyStoreError();

  testing::Mock::VerifyAndClearExpectations(&client_);
}

}  // namespace policy


text:
layout: page
title: Custom metrics
description: Information on how to push custom metrics to the CoScale platform.
---

The CoScale custom metrics options allow you to monitor aspects of your application that are not monitored by default with CoScale. They provide an easy way to extend the CoScale monitoring platform with metrics that are specific to your environment. CoScale provides a couple of methods of integrating these metrics into the platform.

With the [CoScale Generic script plugin]({{ site.baseurl }}/custom-metrics/generic-script/index), [CoScale Log plugin]({{ site.baserurl }}/agent/plugins/log/) and [CoScale CLI]({{ site.baseurl }}/custom-metrics/cli/) it's possible to write small custom integrations for your environment. CoScale also supports pulling metrics from within your code using [StatsD]({{ site.baseurl }}/custom-metrics/statsd/index), [JMX]({{ site.baserurl }}/agent/plugins/jmx/) or [Prometheus]({{ site.baserurl }}/agent/plugins/prometheus/).

## Methods

### [CoScale Generic script plugin]({{ site.baseurl }}/custom-metrics/generic-script/index)

The CoScale agent can execute scripts or binaries to gathers metrics from your application and push them to the platform. We provide examples and guide your in configuring it for your application.

### [CoScale CLI]({{ site.baseurl }}/custom-metrics/cli/)

The CoScale CLI allows you to push multiple metrics at the same time from the command line. You can use it together with Bash scripts to get your custom data inside CoScale. The CoScale CLI is available as an executable or Docker image. When using our CoScale agent package installion it is installed by default.

### [CoScale Log plugin]({{ site.baserurl }}/agent/plugins/log/)

The CoScale agent supports retrieving data from existing log files using a regular expression. The plugin can be used to count the number of lines that match a certain regex, as well as get information from within the log lines.

### [JMX Plugin]({{ site.baserurl }}/agent/plugins/jmx/)

The CoScale agent can retrieve metrics from JMX endpoints. By default the agent will retrieve JVM related information, but other metrics can be added using the `MBEANS` or `METRICS` format.

### [Prometheus Plugin]({{ site.baserurl }}/agent/plugins/prometheus/)

The CoScale agent can retrieve metrics and events from Prometheus endpoints. The plugin will parse all available information coming from the endpoint, including dimensions.

### [StatsD]({{ site.baseurl }}/custom-metrics/statsd/index)

CoScale provides a StatsD plugin to push data gathered in the StatsD or CollectD daemons immediatly to CoScale.

### [CoScale API]({{ site.baseurl }}/api/)

As a last resort the CoScale API is available for advanced configuration and integration. An SDK is available for Java and PHP.


text:
package com.google.idea.blaze.base.project;

import com.google.idea.blaze.base.model.primitives.WorkspacePath;
import com.google.idea.blaze.base.model.primitives.WorkspaceRoot;
import com.google.idea.blaze.base.projectview.ProjectView;
import com.google.idea.blaze.base.projectview.ProjectView.Builder;
import com.google.idea.blaze.base.projectview.ProjectViewSet;
import com.google.idea.blaze.base.projectview.parser.ProjectViewParser;
import com.google.idea.blaze.base.projectview.section.ListSection;
import com.google.idea.blaze.base.projectview.section.ScalarSection;
import com.google.idea.blaze.base.projectview.section.sections.AutomaticallyDeriveTargetsSection;
import com.google.idea.blaze.base.projectview.section.sections.DirectoryEntry;
import com.google.idea.blaze.base.projectview.section.sections.DirectorySection;
import com.google.idea.blaze.base.projectview.section.sections.TextBlock;
import com.google.idea.blaze.base.projectview.section.sections.TextBlockSection;
import com.google.idea.blaze.base.settings.Blaze;
import com.google.idea.blaze.base.settings.BuildSystemName;
import com.google.idea.blaze.base.sync.data.BlazeDataStorage;
import com.google.idea.blaze.base.sync.workspace.WorkspacePathResolver;
import com.google.idea.blaze.base.sync.workspace.WorkspacePathResolverImpl;
import com.google.idea.blaze.base.wizard2.BlazeProjectCommitException;
import com.google.idea.blaze.base.wizard2.BlazeProjectImportBuilder;
import com.google.idea.blaze.base.wizard2.CreateFromScratchProjectViewOption;
import com.google.idea.blaze.base.wizard2.WorkspaceTypeData;
import com.google.idea.sdkcompat.general.BaseSdkCompat;
import com.intellij.ide.SaveAndSyncHandler;
import com.intellij.ide.impl.OpenProjectTask;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.projectImport.ProjectOpenProcessor;
import icons.BlazeIcons;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import javax.swing.Icon;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Adds {@link ProjectOpenProcessor} to import project by opening it directly from a directory
 *

 * Project view can be created from (in order of existence):
 *

 *
ENV var: INTELLIJ_BAZEL_PROJECT_VIEW_TEMPLATE=/home/user/some.bazelproject

 *
workspace - tools/intellij/.managed.bazelproject

 *
if above do not exist, creates minimal project view file

 *

 *

 * Must be loaded after {@link BlazeProjectOpenProcessor} to only import new projects.
 */
public class AutoImportProjectOpenProcessor extends ProjectOpenProcessor {

  private static final Logger LOG = Logger.getInstance(AutoImportProjectOpenProcessor.class);

  @Override
  public @NotNull
  @Nls
  String getName() {
    return Blaze.defaultBuildSystemName() + " Project";
  }

  @javax.annotation.Nullable
  @Override
  public Icon getIcon() {
    return BlazeIcons.Logo;
  }

  @Override
  public boolean isStrongProjectInfoHolder() {
    return true;
  }

  @Override
  public boolean lookForProjectsInDirectory() {
    return false;
  }

  @Override
  public boolean canOpenProject(@NotNull VirtualFile virtualFile) {
    return !Registry.is("bazel.auto.import.disabled")
            && isBazelWorkspace(virtualFile);
  }

  private boolean isBazelWorkspace(VirtualFile virtualFile) {
    return virtualFile.findChild("WORKSPACE") != null
        || virtualFile.findChild("WORKSPACE.bazel") != null;
  }

  @Override
  public @Nullable
  Project doOpenProject(
      @NotNull VirtualFile virtualFile,
      @Nullable Project projectToClose,
      boolean forceOpenInNewFrame
  ) {

    ProjectManager pm = ProjectManager.getInstance();
    if (projectToClose != null) {
      pm.closeAndDispose(projectToClose);
    }

    Project newProject = createProject(virtualFile);
    Objects.requireNonNull(newProject);

    Path projectFilePath = Paths.get(Objects.requireNonNull(newProject.getProjectFilePath()));
    ProjectUtil.updateLastProjectLocation(projectFilePath);

    ProjectManagerEx.getInstanceEx()
            .openProject(
                    projectFilePath,
                    BaseSdkCompat.createOpenProjectTask(newProject)
            );
    SaveAndSyncHandler.getInstance().scheduleProjectSave(newProject);
    return newProject;
  }

  @Nullable
  private Project createProject(@NotNull VirtualFile virtualFile) {
    String projectFilePath =
        virtualFile.getPath() + "/" + BlazeDataStorage.PROJECT_DATA_SUBDIRECTORY;

    createDirs(projectFilePath);

    String name = virtualFile.getName();

    File projectViewFile = new File(projectFilePath + "/.bazelproject");

    BlazeProjectImportBuilder builder = new BlazeProjectImportBuilder();
    File workspaceRootFile = new File(virtualFile.getPath());
    WorkspaceRoot root = new WorkspaceRoot(workspaceRootFile);

    WorkspacePathResolver pathResolver = new WorkspacePathResolverImpl(root);
    builder.builder().setWorkspaceData(
        WorkspaceTypeData.builder()
            .setWorkspaceName(workspaceRootFile.getName())
            .setWorkspaceRoot(root)
            .setCanonicalProjectDataLocation(workspaceRootFile)
            .setFileBrowserRoot(workspaceRootFile)
            .setWorkspacePathResolver(pathResolver)
            .setBuildSystem(BuildSystemName.Bazel)
            .build()
    );
    ProjectView projectView = createProjectView(virtualFile, pathResolver);

    builder.builder().setProjectView(projectView);
    builder.builder().setProjectViewFile(projectViewFile);
    builder.builder().setProjectViewSet(ProjectViewSet.builder().add(projectView).build());
    builder.builder().setProjectViewOption(new CreateFromScratchProjectViewOption());
    builder.builder().setProjectName(name);
    builder.builder().setProjectDataDirectory(projectFilePath);

    try {
      builder.builder().commit(); // set pending project settings
    } catch (BlazeProjectCommitException e) {
      LOG.error("Failed to commit project import builder", e);
    }

    Project newProject = builder.createProject(name, projectFilePath);
    if (newProject == null) {
      LOG.error("Failed to Bazel create project");
      return null;
    }

    newProject.save();

    if (!builder.validate(null, newProject)) {
      LOG.error("New Bazel project validation failed");
      return null;
    }

    builder.builder().commitToProject(newProject); // required to trigger sync
    return newProject;
  }

  private void createDirs(String projectFilePath) {
    try {
      FileUtil.ensureExists(new File(projectFilePath, Project.DIRECTORY_STORE_FOLDER));
    } catch (IOException e) {
      LOG.error("Failed creating project dirs", e);
    }
  }

  private ProjectView defaultEmptyProjectView() {
    Builder projectViewBuilder = ProjectView.builder();

    projectViewBuilder.add(
        ListSection
            .builder(DirectorySection.KEY)
            .add(DirectoryEntry.include(new WorkspacePath(".")))
            .build()
    );

    projectViewBuilder.add(TextBlockSection.of(TextBlock.newLine()));

    projectViewBuilder.add(
        ScalarSection
            .builder(AutomaticallyDeriveTargetsSection.KEY)
            .set(false)
            .build()
    );

    return projectViewBuilder.build();
  }

  private ProjectView createProjectView(VirtualFile workspaceRoot,
      WorkspacePathResolver pathResolver) {

    // first check env for project view template
    String projectViewFileFromEnv = System.getenv(
        "INTELLIJ_BAZEL_PROJECT_VIEW_TEMPLATE");

    if (projectViewFileFromEnv != null) {
      return fromFileProjectView(Paths.get(projectViewFileFromEnv), pathResolver);
    }

    // second check managed project view template
    Path managedProjectViewFilePath = workspaceRoot.toNioPath()
        .resolve("tools/intellij/.managed.bazelproject");
    if (managedProjectViewFilePath.toFile().exists()) {
      return fromFileProjectView(managedProjectViewFilePath, pathResolver);
    }

    // create minimal project view file manually
    return defaultEmptyProjectView();
  }

  private ProjectView fromFileProjectView(
      Path projectViewFilePath,
      WorkspacePathResolver pathResolver
  ) {
    ProjectViewParser projectViewParser = new ProjectViewParser(null, pathResolver);
    projectViewParser.parseProjectView(projectViewFilePath.toFile());
    ProjectViewSet result = projectViewParser.getResult();
    return Objects.requireNonNull(result.getTopLevelProjectViewFile()).projectView;
  }
}


text:
<!DOCTYPE html>

    <title>Test</title>

Firecrow - simple Js Test

Method invocation on a logical expression result


text:
Articles

				Posted on

				by

		No articles yet, why don't you create one?


text:
using Ugoria.URBD.RemoteService.Strategy.Exchange;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using Ugoria.URBD.Contracts.Services;

namespace UnitTests
{

    ///
    ///This is a test class for VerifierTest and is intended
    ///to contain all VerifierTest Unit Tests
    ///
    [TestClass()]
    public class VerifierTest
    {

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        ///
        ///A test for Verification
        ///
        [TestMethod]
        [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\MlgFiles.xml", "TestFile", DataAccessMethod.Sequential)]
        [DeploymentItem("UnitTests\\MlgFiles.xml")]
        [DeploymentItem("TestMLG")]
        public void VerificationTest()
        {
            string logFilename = Convert.ToString(testContextInstance.DataRow["FileName"]); // TODO: Initialize to an appropriate value
            FileInfo fi = new FileInfo(logFilename);
            fi = fi.CopyTo(logFilename + "0", true);

            Verifier target = new Verifier(logFilename);
            fi.CopyTo(logFilename, true);

            target.Verification();

        IEnumerable<DataRow> rowsList = testContextInstance.DataRow.GetChildRows("TestFile_Packet");

            Assert.AreEqual(rowsList.Count(), target.MlgReport.Count);
            foreach (DataRow childRow in rowsList)
            {
                PacketInfo pi = target.MlgReport.FirstOrDefault(p => p.Key.Equals(Convert.ToString(childRow["Name"]))).Value;
                Assert.IsNotNull(pi);
                Assert.AreEqual(pi.type, Enum.Parse(typeof(PacketType), Convert.ToString(childRow["Type"])));
                Assert.AreEqual(pi.isSuccess, Convert.ToBoolean(childRow["Success"]));
            }
            //Assert.AreNotEqual(testContextInstance.DataRow.GetChildRows(["FileName"]), target.MlgReport.Count);
        }

        ///
        ///A test for Verifier Constructor
        ///
        [TestMethod]
        public void VerifierConstructorTest()
        {
            string logFilename = string.Empty; // TODO: Initialize to an appropriate value

            string filename = "test.txt";
            FileInfo f = new FileInfo(filename);
            using (FileStream fs = f.Create())
            {
                fs.Write(new byte[] { 0, 1, 2, 3 }, 0, 4); // заполянем файл данными
            }
            Verifier target = new Verifier(filename);

            bool expected = true;
            bool actual = f.Exists;
            Assert.AreEqual(expected, actual);
            Assert.AreEqual(0, f.Length); // файл должен быть пустым
        }
    }
}