text:
NS_ASSUME_NONNULL_BEGIN

/// Space API response
@interface MXSpaceChildrenResponse : MXJSONModel

/// Its presence indicates that there are more results to return.
@property (nonatomic, nullable) NSString* nextBatch;

/// Rooms information like name/avatar/type ...
@property (nonatomic, nullable) NSArray<MXSpaceChildSummaryResponse*>* rooms;

@end

NS_ASSUME_NONNULL_END


text:
import React from 'react';
import { Provider, connect } from 'react-redux';

let memoizedStore;

export default (
  createStore,
  mapStateToProps,
  mapDispatchToProps
) => Component => {
  function getStoreInstance(initialState) {
    if (typeof window === 'undefined') {
      return createStore(initialState);
    }
    if (!memoizedStore) {
      memoizedStore = createStore(initialState);
    }
    return memoizedStore;
  }

  function ResolveWrapper({ initialState, ...initialProps }) {
    const WrapComponent = connect(mapStateToProps, mapDispatchToProps)(
      Component
    );
    return (
      <Provider store={getStoreInstance(initialState)}>
        <WrapComponent {...initialProps} />
      </Provider>
    );
  }

  ResolveWrapper.getInitialProps = async context => {
    const initialState = context.req ? context.req.initialState : undefined;
    const initialProps = Component.getInitialProps
      ? await Component.getInitialProps(context)
      : {};

    return {
      initialState,
      ...initialProps
    };
  };

  return ResolveWrapper;
};

redpajama_set_name: RedPajamaGithub


text:
namespace csapex
{
class ScatterPlot : public Plot, public csapex::VariadicInputs
{
public:
    void setup(csapex::NodeModifier& node_modifier) override;
    void setupParameters(Parameterizable& parameters) override;
    void process() override;

    const double* getXData() const;
    const double* getYData() const;
    const double* getVarData(std::size_t idx) const;
    std::size_t getCount() const;
    //    std::size_t getNumberOfPlots() const;

    double getPointSize() const;

private:
    void reset() override;

private:
    Input* in_x_;
    Input* in_y_;
    std::vector<double> x;
    std::vector<double> y;
    std::vector<std::vector<double>> var_y_;

    double min_x_;
    double min_y_;
    double max_x_;
    double max_y_;
};

}  // namespace csapex

#endif  // SCATTER_PLOT_H


text:
<?php

class MageWorx_SeoMarkup_Model_Observer_Category
{
    public function createRichsnippetCategoryMarkup($observer)
    {
        if (!Mage::helper('mageworx_seomarkup')->isCategoryPage()) {
            return;
        }

        if (!Mage::helper('mageworx_seomarkup/config')->isCategoryRichsnippetEnabled()) {
            return false;
        }

        if (Mage::app()->getRequest()->isXmlHttpRequest()) {
            return false;
        }

        $block = $observer->getBlock();
        if ($block->getNameInLayout() != 'root') {
            return false;
        }

        if (Mage::helper('mageworx_seomarkup/config')->isUseCategoryRobotsRestriction() && $this->_isNoindexPage()) {
            return false;
        }

        $currentCategory = Mage::registry('current_category');
        if ($currentCategory->getDisplayMode() == 'PAGE') {
           return false;
        }

        $productCollection = $this->_getProductCollection();
        if (empty($productCollection)) {
            return false;
        }

        $jsonCategoryHelper = Mage::helper('mageworx_seomarkup/json_category');
        $categoryRichsnippetData = $jsonCategoryHelper->getJsonCategoryData($productCollection);

        if (!empty($categoryRichsnippetData)) {
            $transport    = $observer->getTransport();
            $normalOutput = $observer->getTransport()->getHtml();
            $catJson = '';
            $modifyOutput = str_replace('', "\n" . $catJson . '', $normalOutput);
            $transport->setHtml($modifyOutput);
        }

        return $this;
    }

    protected function _getProductCollection()
    {
        $productList = Mage::app()->getLayout()->getBlock('product_list');
        if (is_object($productList) && ($productList instanceof Mage_Catalog_Block_Product_List)) {
            return $productList->getLoadedProductCollection();
        }

        $pager = Mage::app()->getLayout()->getBlock('product_list_toolbar_pager');
        if (!is_object($pager)) {
            $pager = $this->_getPagerFromToolbar();
        } elseif (!$pager->getCollection()) {
            $pager = $this->_getPagerFromToolbar();
        }

        if(!is_object($pager)){
            return false;
        }

        return $pager->getCollection();
    }

    protected function _getPagerFromToolbar()
    {
        $toolbar = Mage::app()->getLayout()->getBlock('product_list_toolbar');
        if (is_object($toolbar)) {
            $pager = $toolbar->getChild('product_list_toolbar_pager');
        }
        return is_object($pager) ? $pager : false;
    }

    protected function _isNoindexPage()
    {
        $head = Mage::app()->getLayout()->getBlock('head');
        if (is_object($head) && ($head instanceof Mage_Page_Block_Html_Head)) {
            $robots = $head->getRobots();
            if ($robots && stripos($robots, 'noindex') !== false) {
                return true;
            }
        }

        return false;
    }
}


text:
package org.fishwife.jrugged.spring.config;

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

import org.fishwife.jrugged.spring.PerformanceMonitorBean;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionDecorator;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Node;

/**
 * This class is invoked when Spring encounters the jrugged:methods attribute
 * on a bean. It parses the attribute value with is a comma delimited list
 * of method names to wrap with the PerformanceMonitor. It tells Spring to
 * create a SingleServiceWrapperInterceptor named after the bean with
 * "PerformanceMonitorInterceptor" appended to the name. It also defines
 * a PerformanceMonitorBean named after the bean with "PerformanceMonitor"
 * appended to it. The interceptor has a reference to the PerformanceMonitor.
 */
public class MonitorMethodInterceptorDefinitionDecorator implements
                BeanDefinitionDecorator {

    /**
     * Method called by Spring when it encounters the custom jrugged:methods
     * attribute. Registers the performance monitor and interceptor.
     */
    public BeanDefinitionHolder decorate(Node source,
                                         BeanDefinitionHolder holder,
                                         ParserContext context) {

        String beanName = holder.getBeanName();
        BeanDefinitionRegistry registry = context.getRegistry();
        registerPerformanceMonitor(beanName, registry);
        registerInterceptor(source, beanName, registry);

        return holder;
    }

    /**
     * Register a new SingleServiceWrapperInterceptor for the bean being
     * wrapped, associate it with the PerformanceMonitor and tell it which methods
     * to intercept.
     *
     * @param source An Attribute node from the spring configuration
     * @param beanName The name of the bean that this performance monitor is wrapped around
     * @param registry The registry where all the spring beans are registered
     */
    private void registerInterceptor(Node source,
                                     String beanName,
                                     BeanDefinitionRegistry registry) {
        List<String> methodList = buildMethodList(source);

        BeanDefinitionBuilder initializer =
            BeanDefinitionBuilder.rootBeanDefinition(SingleServiceWrapperInterceptor.class);
        initializer.addPropertyValue("methods", methodList);

        String perfMonitorName = beanName + "PerformanceMonitor";
        initializer.addPropertyReference("serviceWrapper", perfMonitorName);

        String interceptorName = beanName + "PerformanceMonitorInterceptor";
        registry.registerBeanDefinition(interceptorName, initializer.getBeanDefinition());
    }

    /**
     * Parse the jrugged:methods attribute into a List of strings of method
     * names
     *
     * @param source An Attribute node from the spring configuration
     *
     * @return List<String>
     */
    private List<String> buildMethodList(Node source) {
        Attr attribute = (Attr)source;
        String methods = attribute.getValue();
        return parseMethodList(methods);
    }

    /**
     * Parse a comma-delimited list of method names into a List of strings.
     * Whitespace is ignored.
     *
     * @param methods the comma delimited list of methods from the spring configuration
     *
     * @return List<String>
     */
    public List<String> parseMethodList(String methods) {

        String[] methodArray = StringUtils.delimitedListToStringArray(methods, ",");

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

        for (String methodName : methodArray) {
            methodList.add(methodName.trim());
        }
        return methodList;
    }

    /**
     * Register a new PerformanceMonitor with Spring if it does not already exist.
     *
     * @param beanName The name of the bean that this performance monitor is wrapped around
     * @param registry The registry where all the spring beans are registered
     */
    private void registerPerformanceMonitor(String beanName,
                                            BeanDefinitionRegistry registry) {

        String perfMonitorName = beanName + "PerformanceMonitor";
        if (!registry.containsBeanDefinition(perfMonitorName))  {
            BeanDefinitionBuilder initializer =
                BeanDefinitionBuilder.rootBeanDefinition(PerformanceMonitorBean.class);
            registry.registerBeanDefinition(perfMonitorName, initializer.getBeanDefinition());
        }
    }
}


text:
<?php

namespace Propel\Generator\Behavior\I18n\Component;

use Propel\Generator\Builder\Om\Component\BuildComponent;

/**
 * Add I18n attributes to the entity.
 *
 * @author Cristiano Cinotti <cristianocinotti@gmail.com>
 */
class Attributes extends BuildComponent
{
    public function process()
    {
        $behavior = $this->getBehavior();

        $this->addProperty('currentLocale', $behavior->getDefaultLocale())
            ->setDescription('Current locale');

        $this->addProperty('currentTranslations', null)
            ->setDescription('Current translation objects')
            ->setTypeDescription('array[' . $behavior->getI18nEntity()->getFullName() . ']');
    }
}


text:
      General Setup
      Control panel

 Home

Dashboard

<?php $this->load->view("exam/success"); ?>

Exam Name Setting

Passing Mark Setup

Grading System

Room Setup

Other Exam name Setup

            <?php $this->load->view("exam/exm_name"); ?>
            <?php $this->load->view("exam/xmNameList"); ?>

            <?php $this->load->view("exam/passing_mark_set"); ?>
            <?php $this->load->view("exam/passMarkRepo"); ?>

            <?php $this->load->view("exam/grade_settings"); ?>
            <?php $this->load->view("exam/grade_report"); ?>

            <?php $this->load->view("exam/roomSet"); ?>
            <?php $this->load->view("exam/roomRepo"); ?>

            <?php $this->load->view("exam/other_xm"); ?>
            <?php $this->load->view("exam/othXmRepo"); ?>


text:
<!DOCTYPE html>

    <title></title>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'/>


text:
package org.jbox2d.dynamics.joints;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.joints.JointDef;
import org.jbox2d.dynamics.joints.JointType;

/**
 * Created at 3:38:52 AM Jan 15, 2011
 */

/**
 * @author Daniel Murphy
 */
public class WeldJointDef extends JointDef {
	/**
	 * The local anchor point relative to body1's origin.
	 */
	public final Vec2 localAnchorA;

	/**
	 * The local anchor point relative to body2's origin.
	 */
	public final Vec2  localAnchorB;

	/**
	 * The body2 angle minus body1 angle in the reference state (radians).
	 */
	public float referenceAngle;

	public WeldJointDef(){
		type = JointType.WELD;
		localAnchorA = new Vec2();
		localAnchorB = new Vec2();
		referenceAngle = 0.0f;
	}

	/**
	 * Initialize the bodies, anchors, and reference angle using a world
	 * anchor point.
	 * @param bA
	 * @param bB
	 * @param anchor
	 */
	public void initialize(Body bA, Body bB, Vec2 anchor){
		bodyA = bA;
		bodyB = bB;
		bodyA.getLocalPointToOut(anchor, localAnchorA);
		bodyB.getLocalPointToOut(anchor, localAnchorB);
		referenceAngle = bodyB.getAngle() - bodyA.getAngle();
	}
}


text:
package protokube

import (
	"encoding/json"
	"fmt"
	"github.com/golang/glog"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/pkg/api/v1"
)

type nodePatch struct {
	Metadata *nodePatchMetadata `json:"metadata,omitempty"`
	Spec     *nodePatchSpec     `json:"spec,omitempty"`
}

type nodePatchMetadata struct {
	Annotations map[string]string `json:"annotations,omitempty"`
}

type nodePatchSpec struct {
	Unschedulable *bool `json:"unschedulable,omitempty"`
}

// TaintsAnnotationKey represents the key of taints data (json serialized)
// in the Annotations of a Node.
// Note that this is for k8s <= 1.5 only
const TaintsAnnotationKey string = "scheduler.alpha.kubernetes.io/taints"

// ApplyMasterTaints finds masters that have not yet been tainted, and applies the master taint
// Once the kubelet support --taints (like --labels) this can probably go away entirely.
// It also sets the unschedulable flag to false, so pods (with a toleration) can target the node
func ApplyMasterTaints(kubeContext *KubernetesContext) error {
	client, err := kubeContext.KubernetesClient()
	if err != nil {
		return err
	}

	options := metav1.ListOptions{
		LabelSelector: labels.SelectorFromSet(labels.Set{"kubernetes.io/role": "master"}).String(),
	}
	glog.V(2).Infof("Querying k8s for nodes with selector %q", options.LabelSelector)
	nodes, err := client.CoreV1().Nodes().List(options)
	if err != nil {
		return fmt.Errorf("error querying nodes: %v", err)
	}

	taint := []v1.Taint{{Key: "dedicated", Value: "master", Effect: "NoSchedule"}}
	taintJSON, err := json.Marshal(taint)
	if err != nil {
		return fmt.Errorf("error serializing taint: %v", err)
	}

	for i := range nodes.Items {
		node := &nodes.Items[i]

		nodeTaintJSON := node.Annotations[TaintsAnnotationKey]
		if nodeTaintJSON != "" {
			if nodeTaintJSON != string(taintJSON) {
				glog.Infof("Node %q had unexpected taint: %v", node.Name, nodeTaintJSON)
			}
			continue
		}

		nodePatchMetadata := &nodePatchMetadata{
			Annotations: map[string]string{TaintsAnnotationKey: string(taintJSON)},
		}
		unschedulable := false
		nodePatchSpec := &nodePatchSpec{
			Unschedulable: &unschedulable,
		}
		nodePatch := &nodePatch{
			Metadata: nodePatchMetadata,
			Spec:     nodePatchSpec,
		}
		nodePatchJson, err := json.Marshal(nodePatch)
		if err != nil {
			return fmt.Errorf("error building node patch: %v", err)
		}

		glog.V(2).Infof("sending patch for node %q: %q", node.Name, string(nodePatchJson))

		_, err = client.CoreV1().Nodes().Patch(node.Name, types.StrategicMergePatchType, nodePatchJson)
		if err != nil {
			// TODO: Should we keep going?
			return fmt.Errorf("error applying patch to node: %v", err)
		}
	}

	return nil
}


text:
class TrivialFields {
public:
  TrivialFields &operator=(const TrivialFields &object) {
    // CHECK-MESSAGES: [[@LINE-1]]:18: warning: operator=() does not handle self-assignment properly [cert-oop54-cpp]
    return *this;
  }

private:
  int m;
  float f;
  double d;
  bool b;
};


text:
import {Component, Input, Output, EventEmitter} from 'angular2/core';
import {ControlGroup, FormBuilder, Validators, Control} from 'angular2/common';
import {LoginModel} from '../../../model/login.model';
import {CValidators} from '../../common/validation';

@Component({
  selector: 'registration-form',
  template: `

      <form
        [ngFormModel]="form"
        class="form"
        autocomplete="off"
        (ngSubmit)="submit()">

            <input
              ngControl="username"
              type="text"
              placeholder="USERNAME"
              class="input-block login-field"
              [ngClass]="{
                'has-success': username.valid && username.dirty,
                'has-error': !username.valid && username.dirty
              }">

              Username is required
              Username is too short
              Username is too long

            <input
              ngControl="email"
              type="email"
              placeholder="EMAIL"
              class="input-block email-field"
              [ngClass]="{
                'has-success': email.valid && email.dirty,
                'has-error': !email.valid && email.dirty
              }">

                Email is required

                Invalid Email

            <input
              ngControl="password"
              placeholder="PASSWORD"
              class="input-block password-field"
              [ngClass]="{
                'has-success': password.valid && password.dirty,
                'has-error': !password.valid && password.dirty
              }">

                Password is required

            <input
              ngControl="confirmPassword"
              placeholder="CONFIRM PASSWORD"
              class="input-block password-field"
              [ngClass]="{
                'has-success': confirmPassword.valid && confirmPassword.dirty,
                'has-error': !confirmPassword.valid && confirmPassword.dirty
              }">

                Password is required

                Passwords do not match

Register with:

          <button type="submit" ng-disabled="signupForm.$invalid" class="register-button">Sign up</button>

Have an account? - Sign in

      </form>

  `
})
export class RegistrationForm {
  @Output()
  public onSubmit = new EventEmitter<LoginModel>();

  public form:ControlGroup;

  public username: Control;
  public email: Control;
  public password: Control;
  public confirmPassword: Control;

  constructor(builder: FormBuilder) {
    this.username = new Control('', Validators.compose([
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(12)
    ]));

    this.email = new Control('', Validators.compose([
      Validators.required,
      CValidators.emailValidator
    ]));

    this.password = new Control('', Validators.compose([
      Validators.required
    ]));

    this.confirmPassword = new Control('', Validators.compose([
      Validators.required,
      CValidators.passwordRepeatValidator(this.password)
    ]));

    this.form = builder.group({
      username: this.username,
      email: this.email,
      password: this.password,
      confirmPassword: this.confirmPassword
    });
  }

  public submit() {
    console.log(this.form);
    if(this.form.valid) {
      this.onSubmit.emit(this.form.value);
    }
  }
}


text:
title: "多种方式实现在Java中用线程轮流打印ABC"
date: 2020-09-08T11:11:06+08:00
lastmod: 2020-09-08T11:11:06+08:00
draft: false
keywords: ["java","thread"]
description: "多种方式实现在Java中用线程轮流打印ABC"
tags: ["Java","Java Concurrency"]
categories: ["Java编程"]
author: "Rosen Lu"

# You can also close(false) or open(true) something for this content.
# P.S. comment can only be closed
comment: true
toc: true
autoCollapseToc: false
postMetaInFooter: false
hiddenFromHomePage: false
# You can also define another contentCopyright. e.g. contentCopyright: "This is another copyright."
contentCopyright: false
reward: false
mathjax: false
mathjaxEnableSingleDollar: false
mathjaxEnableAutoNumber: false

# You unlisted posts you might want not want the header or footer to show
hideHeaderAndFooter: false

# You can enable or disable out-of-date content warning for individual post.
# Comment this out to use the global config.
#enableOutdatedInfoWarning: false

flowchartDiagrams:
  enable: false
  options: ""

sequenceDiagrams:
  enable: false
  options: ""

---

在`Java`中采用3个线程不停的轮流打印ABC这3个字符,采用不同的方式实现。

<!--more-->

# 原理分析

实现思路如下:

* 要在一个`while`循环中,实现不停的打印
* 多个线程间需要依次唤醒下一个线程,实现依次打印,此时会形成死循环
* 为了打破死循环,还需要一个启动线程延后调用

![原理图](/blog_img/java-concurrency/print-a-b-c-in-turn-by-threads/threads-print-character-process.png "原理图")

# 代码实现

## 基于wait&notify

```java
public class ThreadPrint1Test {

    public static void main(String[] args) {
        new ThreadPrint1Test().testPrint();
    }

    public void testPrint() {
        Object lockA = new Object();
        Object lockB = new Object();
        Object lockC = new Object();

        new PrintThread("A", lockA, lockB).start();
        new PrintThread("B", lockB, lockC).start();
        new PrintThread("C", lockC, lockA).start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        new Thread(() -> {
            synchronized (lockA) {
                lockA.notify();
            }
        }).start();
    }

    class PrintThread extends Thread {

        private Object waitLock;
        private Object notifyLock;
        private String value;

        public PrintThread(String value, Object waitLock, Object notifyLock) {
            this.value = value;
            this.waitLock = waitLock;
            this.notifyLock = notifyLock;
        }

        public void run() {
            while (true) {
                synchronized (waitLock) {
                    try {
                        waitLock.wait();
                        Thread.sleep(500);
                        System.out.println(value);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    synchronized (notifyLock) {
                        notifyLock.notify();
                    }
                }
            }
        }
    }
}
```

## 基于ReentrantLock&Condition

```java
public class ThreadPrint2Test {

    public static void main(String[] args) {
        new ThreadPrint2Test().testPrint();
    }

    public void testPrint() {
        Lock lock = new ReentrantLock();
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();

        new Thread(new PrintThread("A", lock, conditionA, conditionB), "thread-a").start();
        new Thread(new PrintThread("B", lock, conditionB, conditionC), "thread-b").start();
        new Thread(new PrintThread("C", lock, conditionC, conditionA), "thread-c").start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        new Thread(() -> {
            lock.lock();
            conditionA.signal();
            lock.unlock();
        }, "init").start();
    }

    class PrintThread implements Runnable {

        private Lock lock;
        private Condition ca;
        private Condition cb;
        private String value;

        public PrintThread(String value, Lock lock, Condition ca, Condition cb) {
            this.value = value;
            this.lock = lock;
            this.ca = ca;
            this.cb = cb;
        }

        public void run() {
            while (true) {
                try {
                    lock.lock();
                    ca.await();
                    System.out.println(value);
                    Thread.sleep(500);
                    cb.signal();
                    lock.unlock();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
```

## 基于Semaphore

```java
public class ThreadPrint3Test {

    public static void main(String[] args) {
        new ThreadPrint3Test().testPrint();
    }

    public void testPrint() {
        Semaphore sa = new Semaphore(1);
        Semaphore sb = new Semaphore(1);
        Semaphore sc = new Semaphore(1);

        try {
            sb.acquire();
            sc.acquire();
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        new PrintThread("A", sa, sb).start();
        new PrintThread("B", sb, sc).start();
        new PrintThread("C", sc, sa).start();
    }

    class PrintThread extends Thread {

        private Semaphore sa;
        private Semaphore sb;
        private String value;

        public PrintThread(String value, Semaphore sa, Semaphore sb) {
            this.value = value;
            this.sa = sa;
            this.sb = sb;
        }

        public void run() {
            while (true) {
                try {
                    sa.acquire();
                    System.out.println(value);
                    Thread.sleep(500);
                    sb.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
```

## 单个锁&volatile变量

此种方式不需要唤醒线程,同时便于很方便的修改线程数目。

```java
public class ThreadPrint4Test {

    public static void main(String[] args) {
        new ThreadPrint4Test().testPrint();
    }

    private volatile int count = 0;

    public void testPrint() {
        Object lock = new Object();
        new Thread(new PrintThread("A", lock), "thread-A").start();
        new Thread(new PrintThread("B", lock), "thread-B").start();
        new Thread(new PrintThread("C", lock), "thread-C").start();
    }

    class PrintThread implements Runnable {

        private Object lock;
        private String value;

        public PrintThread(String value, Object lock) {
            this.value = value;
            this.lock = lock;
        }

        public void run() {
            while (true) {
                try {
                    synchronized (lock) {
                        boolean process = "A".equals(value) && count % 3 == 0;
                        if (process) {
                            count = 0;
                        }
                        process = process || ("B".equals(value) && count % 3 == 1);
                        process = process || ("C".equals(value) && count % 3 == 2);
                        if (process) {
                            lock.wait();
                            System.out.println(value);
                            count++;
                            Thread.sleep(500);
                        }
                        lock.notifyAll();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
```


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coprinus miniatoflexuosus Bres. & Pat.

### Remarks
null


text:
package org.creepbros.game.minimirobot;

import android.app.Activity;
import android.os.Bundle;

public class GameActivity extends Activity {
	/**
	 * The GLES3 JNI View
	 */
    private GLES3JNIView mView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mView = new GLES3JNIView(getApplication());
        setContentView(mView);
	}

    @Override protected void onPause() {
        super.onPause();
        mView.onPause();
    }

    @Override protected void onResume() {
        super.onResume();
        mView.onResume();
    }

}


text:
namespace views {

namespace {

// EmptyMenuMenuItem ---------------------------------------------------------

// EmptyMenuMenuItem is used when a menu has no menu items. EmptyMenuMenuItem
// is itself a MenuItemView, but it uses a different ID so that it isn't
// identified as a MenuItemView.

class EmptyMenuMenuItem : public MenuItemView {
 public:
  explicit EmptyMenuMenuItem(MenuItemView* parent) :
      MenuItemView(parent, 0, NORMAL) {
    SetTitle(l10n_util::GetString(IDS_APP_MENU_EMPTY_SUBMENU));
    // Set this so that we're not identified as a normal menu item.
    SetID(kEmptyMenuItemViewID);
    SetEnabled(false);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(EmptyMenuMenuItem);
};

}  // namespace

// MenuItemView ---------------------------------------------------------------

//  static
const int MenuItemView::kMenuItemViewID = 1001;

// static
const int MenuItemView::kEmptyMenuItemViewID =
    MenuItemView::kMenuItemViewID + 1;

// static
bool MenuItemView::allow_task_nesting_during_run_ = false;

// static
int MenuItemView::label_start_;

// static
int MenuItemView::item_right_margin_;

// static
int MenuItemView::pref_menu_height_;

MenuItemView::MenuItemView(MenuDelegate* delegate) {
  // NOTE: don't check the delegate for NULL, UpdateMenuPartSizes supplies a
  // NULL delegate.
  Init(NULL, 0, SUBMENU, delegate);
}

MenuItemView::~MenuItemView() {
  // TODO(sky): ownership is bit wrong now. In particular if a nested message
  // loop is running deletion can't be done, otherwise the stack gets
  // thoroughly screwed. The destructor should be made private, and
  // MenuController should be the only place handling deletion of the menu.
  delete submenu_;
}

void MenuItemView::RunMenuAt(gfx::NativeWindow parent,
                             MenuButton* button,
                             const gfx::Rect& bounds,
                             AnchorPosition anchor,
                             bool has_mnemonics) {
  PrepareForRun(has_mnemonics);

  int mouse_event_flags;

  MenuController* controller = MenuController::GetActiveInstance();
  if (controller && !controller->IsBlockingRun()) {
    // A menu is already showing, but it isn't a blocking menu. Cancel it.
    // We can get here during drag and drop if the user right clicks on the
    // menu quickly after the drop.
    controller->Cancel(true);
    controller = NULL;
  }
  bool owns_controller = false;
  if (!controller) {
    // No menus are showing, show one.
    controller = new MenuController(true);
    MenuController::SetActiveInstance(controller);
    owns_controller = true;
  } else {
    // A menu is already showing, use the same controller.

    // Don't support blocking from within non-blocking.
    DCHECK(controller->IsBlockingRun());
  }

  controller_ = controller;

  // Run the loop.
  MenuItemView* result =
      controller->Run(parent, button, this, bounds, anchor, &mouse_event_flags);

  RemoveEmptyMenus();

  controller_ = NULL;

  if (owns_controller) {
    // We created the controller and need to delete it.
    if (MenuController::GetActiveInstance() == controller)
      MenuController::SetActiveInstance(NULL);
    delete controller;
  }
  // Make sure all the windows we created to show the menus have been
  // destroyed.
  DestroyAllMenuHosts();
  if (result && delegate_)
    delegate_->ExecuteCommand(result->GetCommand(), mouse_event_flags);
}

void MenuItemView::RunMenuForDropAt(gfx::NativeWindow parent,
                                    const gfx::Rect& bounds,
                                    AnchorPosition anchor) {
  PrepareForRun(false);

  // If there is a menu, hide it so that only one menu is shown during dnd.
  MenuController* current_controller = MenuController::GetActiveInstance();
  if (current_controller) {
    current_controller->Cancel(true);
  }

  // Always create a new controller for non-blocking.
  controller_ = new MenuController(false);

  // Set the instance, that way it can be canceled by another menu.
  MenuController::SetActiveInstance(controller_);

  controller_->Run(parent, NULL, this, bounds, anchor, NULL);
}

void MenuItemView::Cancel() {
  if (controller_ && !canceled_) {
    canceled_ = true;
    controller_->Cancel(true);
  }
}

SubmenuView* MenuItemView::CreateSubmenu() {
  if (!submenu_)
    submenu_ = new SubmenuView(this);
  return submenu_;
}

void MenuItemView::SetSelected(bool selected) {
  selected_ = selected;
  SchedulePaint();
}

void MenuItemView::SetIcon(const SkBitmap& icon, int item_id) {
  MenuItemView* item = GetMenuItemByID(item_id);
  DCHECK(item);
  item->SetIcon(icon);
}

void MenuItemView::SetIcon(const SkBitmap& icon) {
  icon_ = icon;
  SchedulePaint();
}

void MenuItemView::Paint(gfx::Canvas* canvas) {
  Paint(canvas, false);
}

MenuController* MenuItemView::GetMenuController() {
  return GetRootMenuItem()->controller_;
}

MenuDelegate* MenuItemView::GetDelegate() {
  return GetRootMenuItem()->delegate_;
}

MenuItemView* MenuItemView::GetRootMenuItem() {
  MenuItemView* item = this;
  while (item) {
    MenuItemView* parent = item->GetParentMenuItem();
    if (!parent)
      return item;
    item = parent;
  }
  NOTREACHED();
  return NULL;
}

wchar_t MenuItemView::GetMnemonic() {
  if (!has_mnemonics_)
    return 0;

  const std::wstring& title = GetTitle();
  size_t index = 0;
  do {
    index = title.find('&', index);
    if (index != std::wstring::npos) {
      if (index + 1 != title.size() && title[index + 1] != '&')
        return title[index + 1];
      index++;
    }
  } while (index != std::wstring::npos);
  return 0;
}

MenuItemView* MenuItemView::GetMenuItemByID(int id) {
  if (GetCommand() == id)
    return this;
  if (!HasSubmenu())
    return NULL;
  for (int i = 0; i < GetSubmenu()->GetChildViewCount(); ++i) {
    View* child = GetSubmenu()->GetChildViewAt(i);
    if (child->GetID() == MenuItemView::kMenuItemViewID) {
      MenuItemView* result = static_cast<MenuItemView*>(child)->
          GetMenuItemByID(id);
      if (result)
        return result;
    }
  }
  return NULL;
}

MenuItemView::MenuItemView(MenuItemView* parent,
                           int command,
                           MenuItemView::Type type) {
  Init(parent, command, type, NULL);
}

// Calculates all sizes that we can from the OS.
//
// This is invoked prior to Running a menu.
void MenuItemView::UpdateMenuPartSizes(bool has_icons) {
  MenuConfig::Reset();
  const MenuConfig& config = MenuConfig::instance();

  item_right_margin_ = config.label_to_arrow_padding + config.arrow_width +
      config.arrow_to_edge_padding;

  if (has_icons) {
    label_start_ = config.item_left_margin + config.check_width +
                   config.icon_to_label_padding;
  } else {
    // If there are no icons don't pad by the icon to label padding. This
    // makes us look close to system menus.
    label_start_ = config.item_left_margin + config.check_width;
  }
  if (config.render_gutter)
    label_start_ += config.gutter_width + config.gutter_to_label;

  MenuItemView menu_item(NULL);
  menu_item.SetTitle(L"blah");  // Text doesn't matter here.
  pref_menu_height_ = menu_item.GetPreferredSize().height();
}

void MenuItemView::Init(MenuItemView* parent,
                        int command,
                        MenuItemView::Type type,
                        MenuDelegate* delegate) {
  delegate_ = delegate;
  controller_ = NULL;
  canceled_ = false;
  parent_menu_item_ = parent;
  type_ = type;
  selected_ = false;
  command_ = command;
  submenu_ = NULL;
  // Assign our ID, this allows SubmenuItemView to find MenuItemViews.
  SetID(kMenuItemViewID);
  has_icons_ = false;

  MenuDelegate* root_delegate = GetDelegate();
  if (root_delegate)
    SetEnabled(root_delegate->IsCommandEnabled(command));
}

MenuItemView* MenuItemView::AppendMenuItemInternal(int item_id,
                                                   const std::wstring& label,
                                                   const SkBitmap& icon,
                                                   Type type) {
  if (!submenu_)
    CreateSubmenu();
  if (type == SEPARATOR) {
    submenu_->AddChildView(new MenuSeparator());
    return NULL;
  }
  MenuItemView* item = new MenuItemView(this, item_id, type);
  if (label.empty() && GetDelegate())
    item->SetTitle(GetDelegate()->GetLabel(item_id));
  else
    item->SetTitle(label);
  item->SetIcon(icon);
  if (type == SUBMENU)
    item->CreateSubmenu();
  submenu_->AddChildView(item);
  return item;
}

void MenuItemView::DropMenuClosed(bool notify_delegate) {
  DCHECK(controller_);
  DCHECK(!controller_->IsBlockingRun());
  if (MenuController::GetActiveInstance() == controller_)
    MenuController::SetActiveInstance(NULL);
  delete controller_;
  controller_ = NULL;

  RemoveEmptyMenus();

  if (notify_delegate && delegate_) {
    // Our delegate is null when invoked from the destructor.
    delegate_->DropMenuClosed(this);
  }
  // WARNING: its possible the delegate deleted us at this point.
}

void MenuItemView::PrepareForRun(bool has_mnemonics) {
  // Currently we only support showing the root.
  DCHECK(!parent_menu_item_);

  // Force us to have a submenu.
  CreateSubmenu();

  canceled_ = false;

  has_mnemonics_ = has_mnemonics;

  AddEmptyMenus();

  if (!MenuController::GetActiveInstance()) {
    // Only update the menu size if there are no menus showing, otherwise
    // things may shift around.
    UpdateMenuPartSizes(has_icons_);
  }
}

int MenuItemView::GetDrawStringFlags() {
  int flags = 0;
  if (UILayoutIsRightToLeft())
    flags |= gfx::Canvas::TEXT_ALIGN_RIGHT;
  else
    flags |= gfx::Canvas::TEXT_ALIGN_LEFT;

  if (has_mnemonics_) {
    if (MenuConfig::instance().show_mnemonics)
      flags |= gfx::Canvas::SHOW_PREFIX;
    else
      flags |= gfx::Canvas::HIDE_PREFIX;
  }
  return flags;
}

void MenuItemView::AddEmptyMenus() {
  DCHECK(HasSubmenu());
  if (submenu_->GetChildViewCount() == 0) {
    submenu_->AddChildView(0, new EmptyMenuMenuItem(this));
  } else {
    for (int i = 0, item_count = submenu_->GetMenuItemCount(); i < item_count;
         ++i) {
      MenuItemView* child = submenu_->GetMenuItemAt(i);
      if (child->HasSubmenu())
        child->AddEmptyMenus();
    }
  }
}

void MenuItemView::RemoveEmptyMenus() {
  DCHECK(HasSubmenu());
  // Iterate backwards as we may end up removing views, which alters the child
  // view count.
  for (int i = submenu_->GetChildViewCount() - 1; i >= 0; --i) {
    View* child = submenu_->GetChildViewAt(i);
    if (child->GetID() == MenuItemView::kMenuItemViewID) {
      MenuItemView* menu_item = static_cast<MenuItemView*>(child);
      if (menu_item->HasSubmenu())
        menu_item->RemoveEmptyMenus();
    } else if (child->GetID() == EmptyMenuMenuItem::kEmptyMenuItemViewID) {
      submenu_->RemoveChildView(child);
    }
  }
}

void MenuItemView::AdjustBoundsForRTLUI(gfx::Rect* rect) const {
  rect->set_x(MirroredLeftPointForRect(*rect));
}

void MenuItemView::DestroyAllMenuHosts() {
  if (!HasSubmenu())
    return;

  submenu_->Close();
  for (int i = 0, item_count = submenu_->GetMenuItemCount(); i < item_count;
       ++i) {
    submenu_->GetMenuItemAt(i)->DestroyAllMenuHosts();
  }
}

int MenuItemView::GetTopMargin() {
  MenuItemView* root = GetRootMenuItem();
  return root && root->has_icons_
      ? MenuConfig::instance().item_top_margin :
        MenuConfig::instance().item_no_icon_top_margin;
}

int MenuItemView::GetBottomMargin() {
  MenuItemView* root = GetRootMenuItem();
  return root && root->has_icons_
      ? MenuConfig::instance().item_bottom_margin :
        MenuConfig::instance().item_no_icon_bottom_margin;
}

}  // namespace views


text:
package com.opengamma.financial.security.summary;

import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity;

/**
 * Summary factory for {@link EquityVarianceSwapSecurity}.
 */
public class EquityVarianceSwapSummaryFactory implements SummaryFactory<EquityVarianceSwapSecurity> {

  @Override
  public String getSecurityType() {
    return EquityVarianceSwapSecurity.SECURITY_TYPE;
  }

  @Override
  public Summary getSummary(EquityVarianceSwapSecurity security) {
    return SummaryBuilder.create(security)
        .with(SummaryField.NOTIONAL, security.getNotional())
        .with(SummaryField.STRIKE, security.getStrike())
        .with(SummaryField.UNDERLYING, security.getSpotUnderlyingId())
        .with(SummaryField.START, security.getFirstObservationDate())
        .with(SummaryField.MATURITY, security.getLastObservationDate())
        .with(SummaryField.FREQUENCY, security.getObservationFrequency().getName()).build();
  }

}


text:
"use strict";

const cheerio = require('cheerio'),
    async = require('async'),
    errors = require('../../errors'),
    _ = require('lodash'),
    url = require('url'),
    utils = require('../../utils');

class AccountValidator {

    constructor(options) {

        this.options = {
            content: '',
            requester: null,
            Task: null
        };

        _.extend(this.options, options);

        this.proxyRequester = this.options.requester;
        this.Task = this.options.Task;

        this.scope = [
            'notify',
            'friends',
            'photos',
            'audio',
            'video',
            'docs',
            'notes',
            'pages',
            'status',
            'offers',
            'questions',
            'wall',
            'groups',
            'messages',
            'notifications',
            'stats',
            'ads',
            'offline'
        ].join(',');
        this.redirect_uri = 'https://oauth.vk.com/blank.html';
    }

    static _setOptionsByLink(link, options, method) {
        if (link[0] == '/')
            link = (options.port == 443 ? 'https://' : 'http://') + options.host + link;
        const parsed = url.parse(link);
        options.host = parsed.host;
        options.path = parsed.path;
        options.port = parsed.protocol == 'https:' ? 443 : 80;
        options.method = method || 'GET';
    }

    validate(callback) {
        const that = this;

        const options = {
            host: 'm.vk.com',
            port: 443,
            path: '/',
            method: 'GET',
            formData: null
        };

        let userInfo = null;

        this.proxyRequester.response.cookies.push({
            key: 'remixmdevice',
            value: '360/640/3/!!!!!!!',
            path: '/',
            domain: '.vk.com'
        });

        const _split_ = this.options.content.split(':');

        if (_split_.length !== 2) {

            console.log('Неверный формат аккаунта')
            return callback(new errors.ValidationError('Неверный формат аккаунта', 3))
        }

        async.forever((next) => {
            this.proxyRequester.request(options, function (err, response) {

                //   console.log(err)
                //   console.log(response.body)

                if (err) return next(err);

                switch (response.statusCode) {
                    case 200:
                        const $ = cheerio.load(response.body, {
                            decodeEntities: false
                        });

                        const $service_msg_warning = $('.service_msg_warning');
                        const $ownerPanel = $('.mmi_logout');
                        const $profileDeletedText = $('.profile_deleted_text');
                        const $profileBlocked = $('.login_blocked_panel');
                        const $form = $('form[method="post"]');

                        if ($service_msg_warning.length) {
                            return next(new errors.ValidationError('Невалидный аккаунт', 3));
                        } else if ($ownerPanel.length) {
                            console.log('is logined');
                            // console.log(`https://oauth.vk.com/authorize?client_id=${that.vkClientId}&display=mobile&redirect_uri=${that.redirect_uri}&scope=${that.scope}&response_type=token&v=${that.vkApiVersion}`);
                            AccountValidator._setOptionsByLink(`https://oauth.vk.com/authorize?client_id=${VK_CLIENT_ID}&display=mobile&redirect_uri=${that.redirect_uri}&scope=${that.scope}&response_type=token&v=${VK_API_VERSION}`, options);
                            return next();
                        } else if ($profileDeletedText.length) {
                            return next(new errors.ValidationError('Аккаунт удален', 4));
                        } else if ($profileBlocked.length) {
                            return next(new errors.ValidationError('Аккаунт заблокирован', 5));
                        } else if ($form.length) {
                            console.log('is form');
                            const formData = {};
                            const link = $form.attr('action');
                            AccountValidator._setOptionsByLink(link, options, 'POST');
                            $('input[name]', $form).each(function (i, elem) {
                                const $elem = $(elem);
                                formData[$elem.attr('name')] = $elem.attr('value');
                            });
                            if (formData.hasOwnProperty('email') &&
                                formData.hasOwnProperty('pass')) {
                                formData['email'] = _split_[0];
                                formData['pass'] = _split_[1];
                            }
                            if (formData.hasOwnProperty('captcha_sid')) {
                                console.log(response.body);

                                that.task.pushMsg(utils.createMsg({
                                    msg: `Поймали каптчу`,
                                    status: 1
                                }));

                                const captcha = new Captcha({
                                    service: that.Task.settings.captchaService.value,
                                    key: that.Task.settings.captchaKey.value,
                                    manual: that.Task.settings.manualCaptcha.value,
                                    requester: that.proxyRequester
                                });

                                const params = captcha.extractCaptchaData($);
                                captcha.solve(params, (err, result) => {
                                    if (err) return next(err);
                                    formData['captcha_key'] = result;
                                    options.formData = formData;
                                    return next();
                                });
                            } else if (formData.hasOwnProperty('code')) {
                                return next(new errors.ValidationError('Требуется подтверждение номера'));
                            } else {
                                options.formData = formData;
                                return next();
                            }
                        } else {

                            console.log(response.body);

                            return next(new errors.ValidationError('Неизвестный ответ'));
                        }
                        break;
                    case 301:
                    case 302:
                        if (response.headers.location) {
                            console.log(response.headers.location);
                            if (response.headers.location.indexOf(that.redirect_uri) === 0) {
                                console.log('is token');
                                let split = response.headers.location.split('#');
                                split = split[1].split('&');
                                const obj = {};
                                split.forEach(function (part) {
                                    const sp = part.split('=');
                                    obj[sp[0]] = sp[1];
                                });
                                if (obj.hasOwnProperty('error'))
                                    return next(new errors.ValidationError(`${obj['error']}: ${obj['error_description']}`));
                                userInfo = _.extend(obj, {cookies: response.cookies});
                                return next(new errors.ValidationError('OK', 2));
                            }
                            AccountValidator._setOptionsByLink(response.headers.location, options);
                            return next();
                        } else {
                            return next(new errors.ValidationError(`Неверный редирект: ${response.statusCode}`));
                        }
                        break;
                    default:
                        return next(new errors.ValidationError(`Неверный код ответа: ${response.statusCode}`));
                }
            })
        }, (err) => {
            return callback(err, userInfo);
        });
    }
}

module.exports = AccountValidator;


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.10 at 01:22:30 오후 KST
//

package org.onem2m.xml.protocols;

import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.Duration;

/**
 *
Java class for rateLimit complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="rateLimit">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="maxNrOfNotify" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/>
 *         <element name="timeWindow" type="{http://www.w3.org/2001/XMLSchema}duration" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "rateLimit", propOrder = {
    "maxNrOfNotify",
    "timeWindow"
})
public class RateLimit {

    @XmlSchemaType(name = "nonNegativeInteger")
    protected BigInteger maxNrOfNotify;
    protected Duration timeWindow;

    /**
     * Gets the value of the maxNrOfNotify property.
     *
     * @return
     *     possible object is
     *     {@link BigInteger }
     *
     */
    public BigInteger getMaxNrOfNotify() {
        return maxNrOfNotify;
    }

    /**
     * Sets the value of the maxNrOfNotify property.
     *
     * @param value
     *     allowed object is
     *     {@link BigInteger }
     *
     */
    public void setMaxNrOfNotify(BigInteger value) {
        this.maxNrOfNotify = value;
    }

    /**
     * Gets the value of the timeWindow property.
     *
     * @return
     *     possible object is
     *     {@link Duration }
     *
     */
    public Duration getTimeWindow() {
        return timeWindow;
    }

    /**
     * Sets the value of the timeWindow property.
     *
     * @param value
     *     allowed object is
     *     {@link Duration }
     *
     */
    public void setTimeWindow(Duration value) {
        this.timeWindow = value;
    }

}


text:
This event serves as a notification that a device has been unplugged from a vehicle's OBD-II port.

## Properties

- body: (object)
  - footer: `128` (number) - Contains a checksum for the message contents.
  - message: (object) - Contains the contents of the event.
    - type: `ConnectDisconnectEvent` (string) - Indicates a type for this event.
    - eventType: `Disconnect` (string) - Further specifies the type of event.
    - eventTime: `22017-08-29T17:46:58-05:00` (string) - [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)-formatted time stamp showing when the event was produced on the device.
    - firmwareVersion: `07.2E` (string) - The name of the firmware file that the device is running.
    - cfgVersion: `JHGDL13` (string) - The name of the configuration file that the device is running.
    - keyOnOffDisconnect: `KeyOffDisconnect` (enum[string])
      - Members
        - `KeyOnDisconnect`
        - `KeyOffDisconnect`
    - odometer: `135857` (number) - Vehicle odometer or device-calculated odometer (see `odometerInfo` for differentiator).
    - odometerInfo: `VehicleOdometer` (enum[string]) - Indicates whether the `odometer` value is read from the vehicle or the device.
      - Members
        - `Calculated` - Indicates that the `odometer` value came from the device.
        - `VehicleOdometer` - Indicates that the `odometer` value was read from the vehicle.
  - header (object) - UDP-specifc object containing meta-data about the event.
    - timestamp: `2017-08-29T17:46:58-05:00` (string) - [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)-formatted time stamp showing when the event was produced on the device.
    - tripType: `Trip`(enum[string]) - Indicates a contextual type for this event.
      - Members
        - `IgnitionOff`
        - `Trip`
        - `Idling`
        - `Unknown`
    - tripNumber: `890`- A sequential number that increases after each trip. Resets after 65,536 trips.
    - messageType: `14` (number) -
    - messageLength: `32` (number) - Indicates the total bytes of the message, including the checksum.
    - latitude: `42.478084564208984` (number)
    - longitude: `-83.45092010498047` (number)
    - fixQuality: `FixOk` (enum[string]) - The validity and accuracy of the GPS data.
      - Members
        - `FixOk` - 2D or 3D fix. Latitude and longitude are valid.
        - `StoredFix` - Latitude and longitude are readings from (up to) 5 seconds ago, because the device has not been able to get a GPS fix for 5 seconds.
        - `FixInvalid` - Latitude and longitude are invalid.
        - `Unknown` - The platform cannot decode the value.
    - vehicleProtocolId: `ISO15765_11_BIT_CAN` (enum[string]) - The type of protocol the device detected on the vehicle bus.
      - Members
        - `NoProtocol` - Would only appear if a vehicle were being towed.
        - `J1850VPW`
        - `J1850PWM`
        - `ISO9141`
        - `ISO14230_FIVE_BAWD`
        - `ISO14230_FAST_INIT`
        - `ISO15765_11_BIT_CAN`
        - `ISO15765_29_BIT_CAN`
        - `J1939`
        - `J1708`
        - `Unknown`
    - odo: `5623` (number) - Vehicle odometer or device-calculated odometer.

## Example

```json
{
  "header": {...},
  "body": {
    "footer": 128,
    "message": {
      "type": "ConnectDisconnectEvent",
      "eventType": "Disconnect",
      "eventTime": "2017-08-29T17:46:58-05:00",
      "firmwareVersion": "07.2E",
      "cfgVersion": "JHGDL13",
      "keyOnOffDisconnect": "KeyOffDisconnect",
      "odometer": 135857,
      "odometerInfo": "VehicleOdometer"
    },
    "header": {
      "timestamp": "2017-08-29T17:46:58-05:00",
      "tripType": "Trip",
      "tripNumber": 890,
      "messageType": 14,
      "messageLength": 32,
      "latitude": 42.478084564208984,
      "longitude": -83.45092010498047,
      "fixQuality": "FixOk",
      "vehicleProtocolId": "ISO15765_11_BIT_CAN",
      "odo": 5623
    },
    "isError": false
  }
}
```


text:
import { DomPortal } from '@angular/cdk/portal';
import { ChangeDetectionStrategy, Component, ElementRef, OnInit } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { asyncScheduler, Observable } from 'rxjs';
import { delay, map, take } from 'rxjs/operators';
import * as fromRoot from 'src/app/reducers';
import * as fromConfig from '../../selectors/config.selectors';
import { MapService } from '../../services';
import { FormMapService } from '../../services/form-map.service';

@Component({
  selector: 'app-form-map',
  templateUrl: './form-map.component.html',
  styleUrls: ['./form-map.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{ provide: MapService, useExisting: FormMapService }],
})
export class FormMapComponent implements OnInit {
  readonly zoomToHomeDisabled$: Observable<boolean>;

  options$: Observable<google.maps.MapOptions>;

  constructor(
    private elementRef: ElementRef,
    private store: Store<fromRoot.State>,
    private formMapService: FormMapService
  ) {
    this.formMapService.domPortal = new DomPortal(this.elementRef);
    this.zoomToHomeDisabled$ = this.formMapService.bounds$.pipe(
      delay(0, asyncScheduler),
      map((bounds) => bounds == null || bounds.isEmpty())
    );
  }

  ngOnInit(): void {
    this.options$ = this.store.pipe(select(fromConfig.selectMapOptions), take(1));
  }

  onTypeChange(satellite: boolean): void {
    this.formMapService.map.setMapTypeId(satellite ? 'satellite' : 'roadmap');
  }

  onZoomToHome(): void {
    this.formMapService.zoomToHome();
  }
}


text:
var moment = require("../../moment");

exports.zones = {
    setUp : function (cb) {
        moment.lang('en');
        cb();
    },

    tearDown : function (cb) {
        moment.lang('en');
        cb();
    },

    "set zone" : function (test) {
        var zone = moment();

        zone.zone(0);
        test.equal(zone.zone(), 0, "should be able to set the zone to 0");

        zone.zone(60);
        test.equal(zone.zone(), 60, "should be able to set the zone to 60");

        zone.zone(-60);
        test.equal(zone.zone(), -60, "should be able to set the zone to -60");

        test.done();
    },

    "set zone shorthand" : function (test) {
        var zone = moment();

        zone.zone(1);
        test.equal(zone.zone(), 60, "setting the zone to 1 should imply hours and convert to 60");

        zone.zone(-1);
        test.equal(zone.zone(), -60, "setting the zone to -1 should imply hours and convert to -60");

        zone.zone(15);
        test.equal(zone.zone(), 900, "setting the zone to 15 should imply hours and convert to 900");

        zone.zone(-15);
        test.equal(zone.zone(), -900, "setting the zone to -15 should imply hours and convert to -900");

        zone.zone(16);
        test.equal(zone.zone(), 16, "setting the zone to 16 should imply minutes");

        zone.zone(-16);
        test.equal(zone.zone(), -16, "setting the zone to -16 should imply minutes");

        test.done();
    },

    "set zone with string" : function (test) {
        var zone = moment();

        zone.zone("+00:00");
        test.equal(zone.zone(), 0, "set the zone with a timezone string");

        zone.zone("2013-03-07T07:00:00-08:00");
        test.equal(zone.zone(), 480, "set the zone with a string that does not begin with the timezone");

        zone.zone("2013-03-07T07:00:00+0100");
        test.equal(zone.zone(), -60, "set the zone with a string that uses the +0000 syntax");

        test.done();
    },

    "change hours when changing the zone" : function (test) {
        var zone = moment.utc([2000, 0, 1, 6]);

        zone.zone(0);
        test.equal(zone.hour(), 6, "UTC 6AM should be 6AM at +0000");

        zone.zone(60);
        test.equal(zone.hour(), 5, "UTC 6AM should be 5AM at -0100");

        zone.zone(-60);
        test.equal(zone.hour(), 7, "UTC 6AM should be 7AM at +0100");

        test.done();
    },

    "change minutes when changing the zone" : function (test) {
        var zone = moment.utc([2000, 0, 1, 6, 31]);

        zone.zone(0);
        test.equal(zone.format("HH:mm"), "06:31", "UTC 6:31AM should be 6:31AM at +0000");

        zone.zone(30);
        test.equal(zone.format("HH:mm"), "06:01", "UTC 6:31AM should be 6:01AM at -0030");

        zone.zone(-30);
        test.equal(zone.format("HH:mm"), "07:01", "UTC 6:31AM should be 7:01AM at +0030");

        zone.zone(1380);
        test.equal(zone.format("HH:mm"), "07:31", "UTC 6:31AM should be 7:31AM at +1380");

        test.done();
    },

    "distance from the unix epoch" : function (test) {
        var zoneA = moment(),
            zoneB = moment(zoneA),
            zoneC = moment(zoneA),
            zoneD = moment(zoneA),
            zoneE = moment(zoneA);

        zoneB.utc();
        test.equal(+zoneA, +zoneB, "moment should equal moment.utc");

        zoneC.zone(-60);
        test.equal(+zoneA, +zoneC, "moment should equal moment.zone(-60)");

        zoneD.zone(480);
        test.equal(+zoneA, +zoneD, "moment should equal moment.zone(480)");

        zoneE.zone(1000);
        test.equal(+zoneA, +zoneE, "moment should equal moment.zone(1000)");

        test.done();
    },

    "update offset after changing any values" : function (test) {
        var oldOffset = moment.updateOffset,
            m = moment.utc([2000, 6, 1]);

        moment.updateOffset = function (mom) {
            if (mom.__doChange) {
                if (+mom > 962409600000) {
                    mom.zone(120);
                } else {
                    mom.zone(60);
                }
            }
        };

        test.equal(m.format("ZZ"), "+0000", "should be at +0000");
        test.equal(m.format("HH:mm"), "00:00", "should start 12AM at +0000 timezone");

        m.__doChange = true;
        m.add('h', 1);

        test.equal(m.format("ZZ"), "-0200", "should be at -0200");
        test.equal(m.format("HH:mm"), "23:00", "1AM at +0000 should be 11PM at -0200 timezone");

        m.subtract('h', 1);

        test.equal(m.format("ZZ"), "-0100", "should be at -0100");
        test.equal(m.format("HH:mm"), "23:00", "12AM at +0000 should be 11PM at -0100 timezone");

        moment.updateOffset = oldOffset;

        test.done();
    },

    "getters and setters" : function (test) {
        var a = moment([2011, 5, 20]);

        test.equal(a.clone().zone(120).year(2012).year(), 2012, "should get and set year correctly");
        test.equal(a.clone().zone(120).month(1).month(), 1, "should get and set month correctly");
        test.equal(a.clone().zone(120).date(2).date(), 2, "should get and set date correctly");
        test.equal(a.clone().zone(120).day(1).day(), 1, "should get and set day correctly");
        test.equal(a.clone().zone(120).hour(1).hour(), 1, "should get and set hour correctly");
        test.equal(a.clone().zone(120).minute(1).minute(), 1, "should get and set minute correctly");

        test.done();
    },

    "getters" : function (test) {
        var a = moment.utc([2012, 0, 1, 0, 0, 0]);

        test.equal(a.clone().zone(120).year(),  2011, "should get year correctly");
        test.equal(a.clone().zone(120).month(),   11, "should get month correctly");
        test.equal(a.clone().zone(120).date(),    31, "should get date correctly");
        test.equal(a.clone().zone(120).hour(),    22, "should get hour correctly");
        test.equal(a.clone().zone(120).minute(),   0, "should get minute correctly");

        test.equal(a.clone().zone(-120).year(),  2012, "should get year correctly");
        test.equal(a.clone().zone(-120).month(),    0, "should get month correctly");
        test.equal(a.clone().zone(-120).date(),     1, "should get date correctly");
        test.equal(a.clone().zone(-120).hour(),     2, "should get hour correctly");
        test.equal(a.clone().zone(-120).minute(),   0, "should get minute correctly");

        test.equal(a.clone().zone(-90).year(),  2012, "should get year correctly");
        test.equal(a.clone().zone(-90).month(),    0, "should get month correctly");
        test.equal(a.clone().zone(-90).date(),     1, "should get date correctly");
        test.equal(a.clone().zone(-90).hour(),     1, "should get hour correctly");
        test.equal(a.clone().zone(-90).minute(),  30, "should get minute correctly");

        test.done();
    },

    "from" : function (test) {
        var zoneA = moment(),
            zoneB = moment(zoneA).zone(720),
            zoneC = moment(zoneA).zone(360),
            zoneD = moment(zoneA).zone(-690),
            other = moment(zoneA).add('m', 35);

        test.equal(zoneA.from(other), zoneB.from(other), "moment#from should be the same in all zones");
        test.equal(zoneA.from(other), zoneC.from(other), "moment#from should be the same in all zones");
        test.equal(zoneA.from(other), zoneD.from(other), "moment#from should be the same in all zones");

        test.done();
    },

    "diff" : function (test) {
        var zoneA = moment(),
            zoneB = moment(zoneA).zone(720),
            zoneC = moment(zoneA).zone(360),
            zoneD = moment(zoneA).zone(-690),
            other = moment(zoneA).add('m', 35);

        test.equal(zoneA.diff(other), zoneB.diff(other), "moment#diff should be the same in all zones");
        test.equal(zoneA.diff(other), zoneC.diff(other), "moment#diff should be the same in all zones");
        test.equal(zoneA.diff(other), zoneD.diff(other), "moment#diff should be the same in all zones");

        test.equal(zoneA.diff(other, 'minute', true), zoneB.diff(other, 'minute', true), "moment#diff should be the same in all zones");
        test.equal(zoneA.diff(other, 'minute', true), zoneC.diff(other, 'minute', true), "moment#diff should be the same in all zones");
        test.equal(zoneA.diff(other, 'minute', true), zoneD.diff(other, 'minute', true), "moment#diff should be the same in all zones");

        test.equal(zoneA.diff(other, 'hour', true), zoneB.diff(other, 'hour', true), "moment#diff should be the same in all zones");
        test.equal(zoneA.diff(other, 'hour', true), zoneC.diff(other, 'hour', true), "moment#diff should be the same in all zones");
        test.equal(zoneA.diff(other, 'hour', true), zoneD.diff(other, 'hour', true), "moment#diff should be the same in all zones");

        test.done();
    },

    "unix offset and timestamp" : function (test) {
        var zoneA = moment(),
            zoneB = moment(zoneA).zone(720),
            zoneC = moment(zoneA).zone(360),
            zoneD = moment(zoneA).zone(-690);

        test.equal(zoneA.unix(), zoneB.unix(), "moment#unix should be the same in all zones");
        test.equal(zoneA.unix(), zoneC.unix(), "moment#unix should be the same in all zones");
        test.equal(zoneA.unix(), zoneD.unix(), "moment#unix should be the same in all zones");

        test.equal(+zoneA, +zoneB, "moment#valueOf should be the same in all zones");
        test.equal(+zoneA, +zoneC, "moment#valueOf should be the same in all zones");
        test.equal(+zoneA, +zoneD, "moment#valueOf should be the same in all zones");

        test.done();
    },

    "cloning" : function (test) {
        test.equal(moment().zone(120).clone().zone(),   120, "explicit cloning should retain the zone");
        test.equal(moment().zone(-120).clone().zone(), -120, "explicit cloning should retain the zone");
        test.equal(moment(moment().zone(120)).zone(),   120, "implicit cloning should retain the zone");
        test.equal(moment(moment().zone(-120)).zone(), -120, "implicit cloning should retain the zone");

        test.done();
    },

    "start of / end of" : function (test) {
        var a = moment.utc([2010, 1, 2, 0, 0, 0]).zone(450);

        test.equal(a.clone().startOf('day').hour(), 0, "start of day should work on moments with a zone");
        test.equal(a.clone().startOf('day').minute(), 0, "start of day should work on moments with a zone");
        test.equal(a.clone().startOf('hour').minute(), 0, "start of hour should work on moments with a zone");

        test.equal(a.clone().endOf('day').hour(), 23, "end of day should work on moments with a zone");
        test.equal(a.clone().endOf('day').minute(), 59, "end of day should work on moments with a zone");
        test.equal(a.clone().endOf('hour').minute(), 59, "end of hour should work on moments with a zone");

        test.done();
    },

    "reset zone with moment#utc" : function (test) {
        var a = moment.utc([2012]).zone(480);

        test.equal(a.clone().hour(),      16, "different zone should have different hour");
        test.equal(a.clone().utc().hour(), 0, "calling moment#utc should reset the offset");

        test.done();
    },

    "reset zone with moment#local" : function (test) {
        var a = moment([2012]).zone(480);

        test.equal(a.clone().local().hour(), 0, "calling moment#local should reset the offset");

        test.done();
    },

    "toDate" : function (test) {
        var zoneA = new Date(),
            zoneB = moment(zoneA).zone(720).toDate(),
            zoneC = moment(zoneA).zone(360).toDate(),
            zoneD = moment(zoneA).zone(-690).toDate();

        test.equal(+zoneA, +zoneB, "moment#toDate should output a date with the right unix timestamp");
        test.equal(+zoneA, +zoneC, "moment#toDate should output a date with the right unix timestamp");
        test.equal(+zoneA, +zoneD, "moment#toDate should output a date with the right unix timestamp");

        test.done();
    },

    "same / before / after" : function (test) {
        var zoneA = moment(),
            zoneB = moment(zoneA).zone(120),
            zoneC = moment(zoneA).zone(-120);

        test.ok(zoneA.isSame(zoneB), "two moments with different offsets should be the same");
        test.ok(zoneA.isSame(zoneC), "two moments with different offsets should be the same");

        test.ok(zoneA.isSame(zoneB, 'hour'), "two moments with different offsets should be the same hour");
        test.ok(zoneA.isSame(zoneC, 'hour'), "two moments with different offsets should be the same hour");

        zoneA.add('hour', 1);

        test.ok(zoneA.isAfter(zoneB), "isAfter should work with two moments with different offsets");
        test.ok(zoneA.isAfter(zoneC), "isAfter should work with two moments with different offsets");

        test.ok(zoneA.isAfter(zoneB, 'hour'), "isAfter:hour should work with two moments with different offsets");
        test.ok(zoneA.isAfter(zoneC, 'hour'), "isAfter:hour should work with two moments with different offsets");

        zoneA.subtract('hour', 2);

        test.ok(zoneA.isBefore(zoneB), "isBefore should work with two moments with different offsets");
        test.ok(zoneA.isBefore(zoneC), "isBefore should work with two moments with different offsets");

        test.ok(zoneA.isBefore(zoneB, 'hour'), "isBefore:hour should work with two moments with different offsets");
        test.ok(zoneA.isBefore(zoneC, 'hour'), "isBefore:hour should work with two moments with different offsets");

        test.done();
    },

    "add / subtract over dst" : function (test) {
        var oldOffset = moment.updateOffset,
            m = moment.utc([2000, 2, 31, 3]);

        moment.updateOffset = function (mom) {
            if (mom.clone().utc().month() > 2) {
                mom.zone(-60);
            } else {
                mom.zone(0);
            }
        };

        test.equal(m.hour(), 3, "should start at 00:00");

        m.add('hour', 24);

        test.equal(m.hour(), 4, "adding 24 hours should disregard dst");

        m.subtract('hour', 24);

        test.equal(m.hour(), 3, "subtracting 24 hours should disregard dst");

        m.add('day', 1);

        test.equal(m.hour(), 3, "adding 1 day should have the same hour");

        m.subtract('day', 1);

        test.equal(m.hour(), 3, "subtracting 1 day should have the same hour");

        m.add('month', 1);

        test.equal(m.hour(), 3, "adding 1 month should have the same hour");

        m.subtract('month', 1);

        test.equal(m.hour(), 3, "subtracting 1 month should have the same hour");

        moment.updateOffset = oldOffset;

        test.done();
    },

    "isDST" : function (test) {
        var oldOffset = moment.updateOffset;

        moment.updateOffset = function (mom) {
            if (mom.month() > 2 && mom.month() < 9) {
                mom.zone(-60);
            } else {
                mom.zone(0);
            }
        };

        test.ok(!moment().month(0).isDST(),  "Jan should not be summer dst");
        test.ok(moment().month(6).isDST(),   "Jul should be summer dst");
        test.ok(!moment().month(11).isDST(), "Dec should not be summer dst");

        moment.updateOffset = function (mom) {
            if (mom.month() > 2 && mom.month() < 9) {
                mom.zone(0);
            } else {
                mom.zone(-60);
            }
        };

        test.ok(moment().month(0).isDST(),  "Jan should be winter dst");
        test.ok(!moment().month(6).isDST(), "Jul should not be winter dst");
        test.ok(moment().month(11).isDST(), "Dec should be winter dst");

        moment.updateOffset = oldOffset;

        test.done();
    },

    "zone names" : function (test) {
        test.expect(8);

        test.equal(moment().zoneAbbr(),   "", "Local zone abbr should be empty");
        test.equal(moment().format('z'),  "", "Local zone formatted abbr should be empty");
        test.equal(moment().zoneName(),   "", "Local zone name should be empty");
        test.equal(moment().format('zz'), "", "Local zone formatted name should be empty");

        test.equal(moment.utc().zoneAbbr(),   "UTC", "UTC zone abbr should be UTC");
        test.equal(moment.utc().format('z'),  "UTC", "UTC zone formatted abbr should be UTC");
        test.equal(moment.utc().zoneName(),   "Coordinated Universal Time", "UTC zone abbr should be Coordinated Universal Time");
        test.equal(moment.utc().format('zz'), "Coordinated Universal Time", "UTC zone formatted abbr should be Coordinated Universal Time");

        test.done();
    }

};


text:
package org.omg.DynamicAny;

/**
* org/omg/DynamicAny/DynArrayOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON3/workspace/8-2-build-linux-amd64/jdk8u121/8372/corba/src/share/classes/org/omg/DynamicAny/DynamicAny.idl
* Monday, December 12, 2016 4:37:46 PM PST
*/

/**
    * DynArray objects support the manipulation of IDL arrays.
    * Note that the dimension of the array is contained in the TypeCode which is accessible
    * through the type attribute. It can also be obtained by calling the component_count operation.
    */
public interface DynArrayOperations  extends DynAnyOperations
{

  /**
          * Returns the elements of the DynArray.
          */
  org.omg.CORBA.Any[] get_elements();

  /**
          * Sets the DynArray to contain the passed elements.
          *
          * @exception TypeMismatch if one or more elements have a type that is inconsistent with the DynArrays TypeCode
          * @exception InvalidValue if the sequence does not contain the same number of elements as the array dimension
          */
  void set_elements(org.omg.CORBA.Any[] value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue;

  /**
          * Returns the elements of the DynArray as DynAnys.
          */
  DynAny[] get_elements_as_dyn_any();

  /**
          * Sets the DynArray to contain the passed elements.
          *
          * @exception TypeMismatch if one or more elements have a type that is inconsistent with the DynArrays TypeCode
          * @exception InvalidValue if the sequence does not contain the same number of elements as the array dimension
          */
  void set_elements_as_dyn_any(DynAny[] value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue;
} // interface DynArrayOperations


text:
package web.notifier;

import web.notifier.helpers.Browser;
import web.notifier.helpers.Registry;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.UIManager;
import net.sf.jcarrierpigeon.WindowPosition;
import net.sf.jtelegraph.*;
import web.notifier.frames.LogFrame;
import web.notifier.models.Site;

/**
 *
 * @author Maciej "Gilek" Kłak
 */
public class CheckerTask extends java.util.TimerTask {

    @Override
    public void run() {
        ArrayList<Site> sites = Site.model().checkAll();

        final Color panelBgColor = UIManager.getLookAndFeelDefaults().getColor("Panel.background");

        TelegraphQueue queue = new TelegraphQueue();
        TelegraphAppearance appearance = new TelegraphAppearance();
        appearance.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(panelBgColor.getRed() - 20, panelBgColor.getGreen() - 20, panelBgColor.getBlue() - 20), 1));
        appearance.setIcon(new javax.swing.ImageIcon(getClass().getResource("/web/notifier/resources/ico-32x32.png")));

        for (Site site : sites) {

            String message = null;

            if (site.hasState("availability") && (Boolean)site.getState("availability") == false) {
                message = "Strona \"" + site.getName() + "\" nie jest dostępna.";
            } else if (site.hasState("status") && (Integer)site.getState("status") != 200) {
                message = "Strona \"" + site.getName() + "\" zwraca nieprawidłowy status (" + (Integer)site.getState("status") + ").";
            } else if (site.hasState("content") && (Boolean)site.getState("content") == true) {
                message = "Zawartość strony \"" + site.getName() + "\" uległa zmianie.";
            }

            final String url = site.getUrl();

            if (message != null && message.length() > 0) {

                MouseListener mouseListener = new MouseListener() {

                    @Override
                    public void mouseClicked(MouseEvent e) {
                        Browser.open(url);
                    }

                    @Override
                    public void mousePressed(MouseEvent e) {
                    }

                    @Override
                    public void mouseReleased(MouseEvent e) {
                    }

                    @Override
                    public void mouseEntered(MouseEvent e) {
                        e.getComponent().setCursor(new Cursor(Cursor.HAND_CURSOR));
                        e.getComponent().setBackground(new Color(panelBgColor.getRed() - 15, panelBgColor.getGreen() - 15, panelBgColor.getBlue() - 15));
                    }

                    @Override
                    public void mouseExited(MouseEvent e) {
                        e.getComponent().setCursor(Cursor.getDefaultCursor());
                        e.getComponent().setBackground(panelBgColor);
                    }
                };

                // dodaniie do okna logow
                LogFrame logFrame = (LogFrame)Registry.get("logFrame");
                logFrame.appendSiteToList(site);
                logFrame.fillLogTable();

                // wyswietlenie komunikatu
                Telegraph telegraph = new Telegraph(message, appearance, mouseListener, WindowPosition.BOTTOMRIGHT, 4000);
                queue.add(telegraph);
            }
        }
    }
}


text:
(function () {
  'use strict';

  angular.module('exceptionless.search', ['restangular'])
    .factory('searchService', function ($cacheFactory, $timeout, $q, Restangular) {
      var _cache = $cacheFactory('http:search');

      var _cachedRestangular = Restangular.withConfig(function(RestangularConfigurer) {
        RestangularConfigurer.setDefaultHttpFields({ cache: _cache });
      });

      function validate(query) {
        if (!query || (query.trim && query.trim() === '*')) {
          var deferred = $q.defer();
          $timeout(function() {
            deferred.resolve({
              data: {
                is_valid: true,
                uses_premium_features: false
              }
            });
          }, 0);

          return deferred.promise;
        }

        return _cachedRestangular.one('search', 'validate').get({ query: query });
      }

      var service = {
        validate: validate
      };

      return service;
    });
}());


text:
"""Unit tests for net_metrics."""

# pylint: disable=protected-access

from __future__ import absolute_import
from __future__ import print_function

import socket
import sys

import mock
import psutil  # pylint: disable=import-error

from chromite.lib import cros_test_lib
from chromite.scripts.sysmon import net_metrics

assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'

snetio = psutil._common.snetio
snicstats = psutil._common.snicstats
snic = getattr(psutil._common, 'snic', None)

pytestmark = cros_test_lib.pytestmark_skipif(snic is None,
                                             reason='Wrong version of psutil')

class TestNetMetrics(cros_test_lib.TestCase):
  """Tests for net_metrics."""

  def setUp(self):
    patcher = mock.patch('infra_libs.ts_mon.common.interface.state.store',
                         autospec=True)
    self.store = patcher.start()
    self.addCleanup(patcher.stop)

  def test_collect(self):
    with mock.patch('psutil.net_io_counters', autospec=True) \
             as net_io_counters, \
         mock.patch('psutil.net_if_stats', autospec=True) as net_if_stats, \
         mock.patch('socket.getfqdn', autospec=True) as getfqdn, \
         mock.patch('psutil.net_if_addrs', autospec=True) as net_if_addrs:
      net_io_counters.return_value = {
          'lo': snetio(
              bytes_sent=17247495681, bytes_recv=172474956,
              packets_sent=109564455, packets_recv=1095644,
              errin=10, errout=1, dropin=20, dropout=2),
      }
      net_if_stats.return_value = {
          'lo': snicstats(isup=True, duplex=0, speed=0, mtu=65536),
      }
      getfqdn.return_value = 'foo.example.com'
      net_if_addrs.return_value = {
          'lo': [
              snic(family=psutil.AF_LINK, address='11:22:33:44:55:66',
                   netmask=None, broadcast=None, ptp=None),
              snic(family=socket.AF_INET, address='10.1.1.1', netmask=None,
                   broadcast=None, ptp=None),
              snic(family=socket.AF_INET6,
                   address='fc00:0000:0000:0000:0000:0000:0000:0001',
                   netmask=None, broadcast=None, ptp=None),
          ],
      }
      net_metrics.collect_net_info()

    setter = self.store.set
    calls = [
        mock.call('dev/net/bytes', ('up', 'lo'), None,
                  17247495681, enforce_ge=mock.ANY),
        mock.call('dev/net/bytes', ('down', 'lo'), None,
                  172474956, enforce_ge=mock.ANY),
        mock.call('dev/net/packets', ('up', 'lo'), None,
                  109564455, enforce_ge=mock.ANY),
        mock.call('dev/net/packets', ('down', 'lo'), None,
                  1095644, enforce_ge=mock.ANY),
        mock.call('dev/net/errors', ('up', 'lo'), None,
                  1, enforce_ge=mock.ANY),
        mock.call('dev/net/errors', ('down', 'lo'), None,
                  10, enforce_ge=mock.ANY),
        mock.call('dev/net/dropped', ('up', 'lo'), None,
                  2, enforce_ge=mock.ANY),
        mock.call('dev/net/dropped', ('down', 'lo'), None,
                  20, enforce_ge=mock.ANY),
        mock.call('dev/net/isup', ('lo',), None,
                  True, enforce_ge=mock.ANY),
        mock.call('dev/net/duplex', ('lo',), None,
                  0, enforce_ge=mock.ANY),
        mock.call('dev/net/speed', ('lo',), None,
                  0, enforce_ge=mock.ANY),
        mock.call('dev/net/mtu', ('lo',), None,
                  65536, enforce_ge=mock.ANY),
        mock.call('net/fqdn', (), None,
                  'foo.example.com', enforce_ge=mock.ANY),
        mock.call('dev/net/address', ('AF_LINK', 'lo'), None,
                  '11:22:33:44:55:66', enforce_ge=mock.ANY),
        mock.call('dev/net/address', ('AF_INET', 'lo',), None,
                  '10.1.1.1', enforce_ge=mock.ANY),
        mock.call('dev/net/address', ('AF_INET6', 'lo'), None,
                  'fc00:0000:0000:0000:0000:0000:0000:0001',
                  enforce_ge=mock.ANY),
    ]
    setter.assert_has_calls(calls)
    self.assertEqual(len(setter.mock_calls), len(calls))


text:
<?php

namespace Concrete\Core\Updater\ApplicationUpdate;

class Diagnostic
{

    protected $requestedVersion;
    protected $marketplaceItemStatuses = array();
    protected $notices = array();
    protected $status;

    /**
     * @return mixed
     */
    public function getRequestedVersion()
    {
        return $this->requestedVersion;
    }

    /**
     * @param mixed $requestedVersion
     */
    public function setRequestedVersion(Version $requestedVersion)
    {
        $this->requestedVersion = $requestedVersion;
    }

    public function addMarketplaceItemStatusObject(MarketplaceItemStatus $s)
    {
        $this->marketplaceItemStatuses[] = $s;
    }

    public function addNoticeStatusObject(Status $s)
    {
        $this->notices[] = $s;
    }

    public function setUpdateStatusObject(Status $status)
    {
        $this->status = $status;
    }

    public function getJSONObject()
    {
        $o = new \stdClass();
        if ($this->requestedVersion) {
            $o->requestedVersion = $this->requestedVersion->getVersion();
            $o->releaseNotes = $this->requestedVersion->getReleaseNotes();
            $o->releaseNotesUrl = $this->requestedVersion->getReleaseNotesURL();
        }
        $o->marketplaceItemStatuses = array();
        foreach($this->marketplaceItemStatuses as $s) {
            $o->marketplaceItemStatuses[] = $s->getJSONObject();
        }
        $o->notices = array();
        foreach($this->notices as $s) {
            $o->notices[] = $s->getJSONObject();
        }
        if ($this->status) {
            $o->status = $this->status->getJSONObject();
        }
        return $o;
    }

}


text:
// ReSharper disable once CheckNamespace
namespace Fluent;

using System.Windows;

/// <summary>
/// Represents menu item in ribbon status bar menu
/// </summary>
public class StatusBarMenuItem : MenuItem
{
    #region Properties

    /// <summary>
    /// Gets or sets Ribbon Status Bar menu item
    /// </summary>
    public StatusBarItem? StatusBarItem
    {
        get { return (StatusBarItem?)this.GetValue(StatusBarItemProperty); }
        set { this.SetValue(StatusBarItemProperty, value); }
    }

    /// <summary>Identifies the <see cref="StatusBarItem"/> dependency property.</summary>
    public static readonly DependencyProperty StatusBarItemProperty =
        DependencyProperty.Register(nameof(StatusBarItem), typeof(StatusBarItem), typeof(StatusBarMenuItem), new PropertyMetadata());

    #endregion

    #region Constructors

    /// <summary>
    /// Static constructor
    /// </summary>
    static StatusBarMenuItem()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusBarMenuItem), new FrameworkPropertyMetadata(typeof(StatusBarMenuItem)));
    }

    /// <summary>
    /// Default constructor
    /// </summary>
    /// <param name="item">Ribbon Status Bar menu item</param>
    public StatusBarMenuItem(StatusBarItem item)
    {
        this.StatusBarItem = item;
    }

    internal StatusBarMenuItem()
    {
    }

    #endregion
}