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

package com.android.settings.applications.assist;

import static androidx.lifecycle.Lifecycle.Event.ON_RESUME;

import static com.google.common.truth.Truth.assertThat;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.provider.Settings;

import androidx.lifecycle.LifecycleOwner;
import androidx.preference.PreferenceScreen;
import androidx.preference.TwoStatePreference;

import com.android.settings.testutils.shadow.ShadowSecureSettings;
import com.android.settingslib.core.lifecycle.Lifecycle;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;

@RunWith(RobolectricTestRunner.class)
public class AssistFlashScreenPreferenceControllerTest {

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    private Context mMockContext;
    @Mock
    private PreferenceScreen mScreen;
    @Mock
    private TwoStatePreference mPreference;
    @Mock
    private AssistFlashScreenPreferenceController.SettingObserver mObserver;
    private Context mContext;
    private AssistFlashScreenPreferenceController mController;
    private LifecycleOwner mLifecycleOwner;
    private Lifecycle mLifecycle;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(mScreen.findPreference(anyString())).thenReturn(mPreference);
        mLifecycleOwner = () -> mLifecycle;
        mLifecycle = new Lifecycle(mLifecycleOwner);
        mContext = RuntimeEnvironment.application;
        mController = spy(new AssistFlashScreenPreferenceController(mContext, mLifecycle));
        mLifecycle.addObserver(mController);
        ReflectionHelpers.setField(mController, "mSettingObserver", mObserver);
    }

    @Test
    @Config(shadows = {ShadowSecureSettings.class})
    public void isAvailable_hasAssistantAndAllowDisclosure_shouldReturnTrue() {
        ReflectionHelpers.setField(mController, "mContext", mMockContext);
        final ContentResolver cr = mContext.getContentResolver();
        Settings.Secure.putString(cr, Settings.Secure.ASSISTANT, "com.android.settings/assist");
        doReturn(true).when(mController).allowDisablingAssistDisclosure();

        assertThat(mController.isAvailable()).isTrue();
    }

    @Test
    @Config(shadows = {ShadowSecureSettings.class})
    public void isAvailable_hasAssistantAndDisallowDisclosure_shouldReturnTrue() {
        ReflectionHelpers.setField(mController, "mContext", mMockContext);
        final ContentResolver cr = mContext.getContentResolver();
        Settings.Secure.putString(cr, Settings.Secure.ASSISTANT, "com.android.settings/assist");
        doReturn(false).when(mController).allowDisablingAssistDisclosure();

        assertThat(mController.isAvailable()).isFalse();
    }

    @Test
    public void isAvailable_hasNoAssistant_shouldReturnFalse() {
        Settings.Secure.putString(mContext.getContentResolver(), Settings.Secure.ASSISTANT, "");

        assertThat(mController.isAvailable()).isFalse();
    }

    @Test
    @Config(shadows = {ShadowSecureSettings.class})
    public void onResume_shouldUpdatePreference() {
        Settings.Secure.putString(mContext.getContentResolver(),
                Settings.Secure.ASSISTANT, "com.android.settings/assist");
        doReturn(true).when(mController).isAvailable();
        doReturn(true).when(mController).isPreInstalledAssistant(any(ComponentName.class));
        doReturn(true).when(mController).willShowFlash(any(ComponentName.class));

        mController.displayPreference(mScreen);
        Settings.Secure.putInt(mContext.getContentResolver(),
                Settings.Secure.ASSIST_DISCLOSURE_ENABLED, 1);

        mLifecycle.handleLifecycleEvent(ON_RESUME);

        verify(mObserver).register(any(ContentResolver.class), eq(true));
        verify(mPreference).setChecked(true);
    }
}

{'repo_name': 'ResurrectionRemix/Resurrection_packages_apps_Settings', 'stars': '125', 'repo_language': 'Java', 'file_name': 'account_preferences.xml', 'mime_type': 'text/xml', 'hash': -4878303041467423536, 'source_dataset': 'data'}


---
title: 'All by Type: Horizontal'
layout: default
targetsuffix: '-horizontal'
---
{% include all-paged.html %}

{'repo_name': 'VectorLogoZone/vectorlogozone', 'stars': '209', 'repo_language': 'HTML', 'file_name': 'none.html', 'mime_type': 'text/plain', 'hash': -827199663138751329, 'source_dataset': 'data'}


# Notification (الإشعارات)

> Create OS desktop notifications

العملية: [Main](../glossary.md#main-process)

## Using in the renderer process

If you want to show Notifications from a renderer process you should use the [HTML5 Notification API](../tutorial/notifications.md)

## Class: Notification

> Create OS desktop notifications

العملية: [Main](../glossary.md#main-process)

`Notification` is an [EventEmitter][event-emitter].

It creates a new `Notification` with native properties as set by the `options`.

### Static Methods

The `Notification` class has the following static methods:

#### `Notification.isSupported()`

Returns `Boolean` - Whether or not desktop notifications are supported on the current system

### `new Notification([options])`

* `options` Object (optional)
  * `title` String - A title for the notification, which will be shown at the top of the notification window when it is shown.
  * `subtitle` String (optional) _macOS_ - A subtitle for the notification, which will be displayed below the title.
  * `body` String - The body text of the notification, which will be displayed below the title or subtitle.
  * `silent` Boolean (optional) - Whether or not to emit an OS notification noise when showing the notification.
  * `icon` (String | [NativeImage](native-image.md)) (optional) - An icon to use in the notification.
  * `hasReply` Boolean (optional) _macOS_ - Whether or not to add an inline reply option to the notification.
  * `timeoutType` String (optional) _Linux_ _Windows_ - The timeout duration of the notification. Can be 'default' or 'never'.
  * `replyPlaceholder` String (optional) _macOS_ - The placeholder to write in the inline reply input field.
  * `sound` String (optional) _macOS_ - The name of the sound file to play when the notification is shown.
  * `urgency` String (optional) _Linux_ - The urgency level of the notification. Can be 'normal', 'critical', or 'low'.
  * `actions` [NotificationAction[]](structures/notification-action.md) (optional) _macOS_ - Actions to add to the notification. Please read the available actions and limitations in the `NotificationAction` documentation.
  * `closeButtonText` String (optional) _macOS_ - A custom title for the close button of an alert. An empty string will cause the default localized text to be used.

### Instance Events

Objects created with `new Notification` emit the following events:

**Note:** Some events are only available on specific operating systems and are labeled as such.

#### Event: 'show'

تراجع:

* `event` Event

Emitted when the notification is shown to the user, note this could be fired multiple times as a notification can be shown multiple times through the `show()` method.

#### Event: 'click'

تراجع:

* `event` Event

Emitted when the notification is clicked by the user.

#### Event: 'close'

تراجع:

* `event` Event

Emitted when the notification is closed by manual intervention from the user.

This event is not guaranteed to be emitted in all cases where the notification is closed.

#### Event: 'reply' _macOS_

تراجع:

* `event` Event
* `reply` String - The string the user entered into the inline reply field.

Emitted when the user clicks the "Reply" button on a notification with `hasReply: true`.

#### Event: 'action' _macOS_

تراجع:

* `event` Event
* `index` Number - The index of the action that was activated.

### Instance Methods

Objects created with `new Notification` have the following instance methods:

#### `notification.show()`

Immediately shows the notification to the user, please note this means unlike the HTML5 Notification implementation, instantiating a `new Notification` does not immediately show it to the user, you need to call this method before the OS will display it.

If the notification has been shown before, this method will dismiss the previously shown notification and create a new one with identical properties.

#### `notification.close()`

Dismisses the notification.

### Instance Properties

#### `notification.title`

A `String` property representing the title of the notification.

#### `notification.subtitle`

A `String` property representing the subtitle of the notification.

#### `notification.body`

A `String` property representing the body of the notification.

#### `notification.replyPlaceholder`

A `String` property representing the reply placeholder of the notification.

#### `notification.sound`

A `String` property representing the sound of the notification.

#### `notification.closeButtonText`

A `String` property representing the close button text of the notification.

#### `notification.silent`

A `Boolean` property representing whether the notification is silent.

#### `notification.hasReply`

A `Boolean` property representing whether the notification has a reply action.

#### `notification.urgency` _Linux_

A `String` property representing the urgency level of the notification. Can be 'normal', 'critical', or 'low'.

Default is 'low' - see [NotifyUrgency](https://developer.gnome.org/notification-spec/#urgency-levels) for more information.

#### `notification.timeoutType` _Linux_ _Windows_

A `String` property representing the type of timeout duration for the notification. Can be 'default' or 'never'.

If `timeoutType` is set to 'never', the notification never expires. It stays open until closed by the calling API or the user.

#### `notification.actions`

A [`NotificationAction[]`](structures/notification-action.md) property representing the actions of the notification.

### Playing Sounds

On macOS, you can specify the name of the sound you'd like to play when the notification is shown. Any of the default sounds (under System Preferences > Sound) can be used, in addition to custom sound files. Be sure that the sound file is copied under the app bundle (e.g., `YourApp.app/Contents/Resources`), or one of the following locations:

* `~/Library/Sounds`
* `/Library/Sounds`
* `/Network/Library/Sounds`
* `/System/Library/Sounds`

See the [`NSSound`](https://developer.apple.com/documentation/appkit/nssound) docs for more information.

[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter

{'repo_name': 'electron/i18n', 'stars': '435', 'repo_language': 'TypeScript', 'file_name': 'repl.md', 'mime_type': 'text/plain', 'hash': -2448442912296459080, 'source_dataset': 'data'}


.animated {
  animation-duration: 1s;
  animation-fill-mode: both;
}

.animated.infinite {
  animation-iteration-count: infinite;
}

.animated.hinge {
  animation-duration: 2s;
}

{'repo_name': 'liuyunzhuge/blog', 'stars': '269', 'repo_language': 'JavaScript', 'file_name': 'demo.js', 'mime_type': 'text/plain', 'hash': 7729663432731143908, 'source_dataset': 'data'}


mkdirp

Recursively mkdir, like `mkdir -p`

{'repo_name': 'luckykun/About-React', 'stars': '301', 'repo_language': 'CSS', 'file_name': 'test.json', 'mime_type': 'text/plain', 'hash': -1124042260700033329, 'source_dataset': 'data'}


%{
#include <stdlib.h>

typedef enum {cGLOBAL, cLOCAL} class;
typedef enum {tREAL, tINTEGER} type;
typedef char * name;

struct symbol { class c; type t; name id; };
typedef struct symbol symbol;

struct namelist { symbol *s; struct namelist *next; };
typedef struct namelist namelist;

extern symbol *mksymbol(type t, class c, name id);

#ifdef YYBISON
#define YYLEX_DECL() yylex(void)
#define YYERROR_DECL() yyerror(const char *s)
#endif
%}

%token <cval> GLOBAL LOCAL
%token <tval> REAL INTEGER
%token <id>   NAME

%type <nlist> declaration namelist(<cval>, <tval>) locnamelist(<tval>)
%type <cval>  class
%type <tval>  type

%destructor	{
		  namelist *p = $$;
		  while (p != NULL)
		  { namelist *pp = p;
		    p = p->next;
		    free(pp->s); free(pp);
		  }
		} <nlist>

%union
{
    class	cval;
    type	tval;
    namelist *	nlist;
    name	id;
}

%start declaration

%%
declaration: class type namelist($1, $2)
	{ $$ = $3; }
	| type locnamelist($1)
	{ $$ = $2; }
	;

class	: GLOBAL { $$ = cGLOBAL; }
	| LOCAL  { $$ = cLOCAL; }
	;

type	: REAL    { $$ = tREAL; }
	| INTEGER { $$ = tINTEGER; }
	;

namelist($c, $t): namelist NAME
	    { $$->s = mksymbol($<tval>t, $<cval>c, $2);
	      $$->next = $1;
	    }
	| NAME
	    { $$->s = mksymbol($t, $c, $1);
	      $$->next = NULL;
	    }
	;

locnamelist($t): namelist(cLOCAL, $t)
	{ $$ = $1; }
	;
%%

extern int YYLEX_DECL();
extern void YYERROR_DECL();

{'repo_name': 'sergev/LiteBSD', 'stars': '236', 'repo_language': 'C', 'file_name': 'README.txt', 'mime_type': 'text/plain', 'hash': 6057100146323358850, 'source_dataset': 'data'}


/*

  u8g_ll_api.c

  low level api

  Universal 8bit Graphics Library

  Copyright (c) 2011, olikraus@gmail.com
  All rights reserved.

  Redistribution and use in source and binary forms, with or without modification,
  are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this list
    of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright notice, this
    list of conditions and the following disclaimer in the documentation and/or other
    materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include <stddef.h>
#include "u8g.h"

uint8_t u8g_call_dev_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg)
{
  return dev->dev_fn(u8g, dev, msg, arg);
}

/*====================================================================*/

uint8_t u8g_InitLL(u8g_t *u8g, u8g_dev_t *dev)
{
  uint8_t r;
  u8g->state_cb(U8G_STATE_MSG_BACKUP_ENV);
  r =  u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_INIT, NULL);
  u8g->state_cb(U8G_STATE_MSG_BACKUP_U8G);
  u8g->state_cb(U8G_STATE_MSG_RESTORE_ENV);
  return r;
}

void u8g_FirstPageLL(u8g_t *u8g, u8g_dev_t *dev)
{
  u8g->state_cb(U8G_STATE_MSG_BACKUP_ENV);
  u8g->state_cb(U8G_STATE_MSG_RESTORE_U8G);
  u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_PAGE_FIRST, NULL);
  u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_GET_PAGE_BOX, &(u8g->current_page));
  u8g->state_cb(U8G_STATE_MSG_RESTORE_ENV);
}

uint8_t u8g_NextPageLL(u8g_t *u8g, u8g_dev_t *dev)
{
  uint8_t r;
  u8g->state_cb(U8G_STATE_MSG_BACKUP_ENV);
  u8g->state_cb(U8G_STATE_MSG_RESTORE_U8G);
  r = u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_PAGE_NEXT, NULL);
  if ( r != 0 )
  {
    u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_GET_PAGE_BOX, &(u8g->current_page));
  }
  u8g->state_cb(U8G_STATE_MSG_RESTORE_ENV);
  return r;
}

uint8_t u8g_SetContrastLL(u8g_t *u8g, u8g_dev_t *dev, uint8_t contrast)
{
  return u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_CONTRAST, &contrast);
}

void u8g_DrawPixelLL(u8g_t *u8g, u8g_dev_t *dev, u8g_uint_t x, u8g_uint_t y)
{
  u8g_dev_arg_pixel_t *arg = &(u8g->arg_pixel);
  arg->x = x;
  arg->y = y;
  u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_SET_PIXEL, arg);
}

void u8g_Draw8PixelLL(u8g_t *u8g, u8g_dev_t *dev, u8g_uint_t x, u8g_uint_t y, uint8_t dir, uint8_t pixel)
{
  u8g_dev_arg_pixel_t *arg = &(u8g->arg_pixel);
  arg->x = x;
  arg->y = y;
  arg->dir = dir;
  arg->pixel = pixel;
  u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_SET_8PIXEL, arg);
}

#ifdef U8G_DEV_MSG_IS_BBX_INTERSECTION
uint8_t u8g_IsBBXIntersectionLL(u8g_t *u8g, u8g_dev_t *dev, u8g_uint_t x, u8g_uint_t y, u8g_uint_t w, u8g_uint_t h)
{
  return u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_IS_BBX_INTERSECTION, &arg);
}
#endif

u8g_uint_t u8g_GetWidthLL(u8g_t *u8g, u8g_dev_t *dev)
{
  u8g_uint_t r;
  u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_GET_WIDTH, &r);
  return r;
}

u8g_uint_t u8g_GetHeightLL(u8g_t *u8g, u8g_dev_t *dev)
{
  u8g_uint_t r;
  u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_GET_HEIGHT, &r);
  return r;
}

u8g_uint_t u8g_GetModeLL(u8g_t *u8g, u8g_dev_t *dev)
{
  return u8g_call_dev_fn(u8g, dev, U8G_DEV_MSG_GET_MODE, NULL);
}

/*====================================================================*/

void u8g_UpdateDimension(u8g_t *u8g)
{
  u8g->width = u8g_GetWidthLL(u8g, u8g->dev);
  u8g->height = u8g_GetHeightLL(u8g, u8g->dev);
  u8g->mode = u8g_GetModeLL(u8g, u8g->dev);
  /* 9 Dec 2012: u8g_scale.c requires update of current page */
  u8g_call_dev_fn(u8g, u8g->dev, U8G_DEV_MSG_GET_PAGE_BOX, &(u8g->current_page));
}

static void u8g_init_data(u8g_t *u8g)
{
  uint8_t i;
  u8g->font = NULL;
  u8g->cursor_font = NULL;
  u8g->cursor_bg_color = 0;
  u8g->cursor_fg_color = 1;
  u8g->cursor_encoding = 34;
  u8g->cursor_fn = (u8g_draw_cursor_fn)0;

  for( i = 0; i < U8G_PIN_LIST_LEN; i++ )
    u8g->pin_list[i] = U8G_PIN_NONE;

  u8g_SetColorIndex(u8g, 1);

  u8g_SetFontPosBaseline(u8g);

  u8g->font_height_mode = U8G_FONT_HEIGHT_MODE_XTEXT;
  u8g->font_ref_ascent = 0;
  u8g->font_ref_descent = 0;
  u8g->font_line_spacing_factor = 64;           /* 64 = 1.0, 77 = 1.2 line spacing factor */
  u8g->line_spacing = 0;

  u8g->state_cb = u8g_state_dummy_cb;

}

uint8_t u8g_Begin(u8g_t *u8g)
{
  /* call and init low level driver and com device */
  if ( u8g_InitLL(u8g, u8g->dev) == 0 )
    return 0;
  /* fetch width and height from the low level */
  u8g_UpdateDimension(u8g);
  return 1;
}

uint8_t u8g_Init(u8g_t *u8g, u8g_dev_t *dev)
{
  u8g_init_data(u8g);
  u8g->dev = dev;

  /* On the Arduino Environment this will lead to two calls to u8g_Begin(), the following line will be called first (by U8glib constructors) */
  /* if - in future releases - this is removed, then still call u8g_UpdateDimension() */
  /* if Arduino call u8g_UpdateDimension else u8g_Begin */
  /* issue 146 */
  return u8g_Begin(u8g);
}

uint8_t u8g_InitSPI(u8g_t *u8g, u8g_dev_t *dev, uint8_t sck, uint8_t mosi, uint8_t cs, uint8_t a0, uint8_t reset)
{

  /* fill data structure with some suitable values */
  u8g_init_data(u8g);
  u8g->dev = dev;

  /* assign user pins */
  u8g->pin_list[U8G_PI_SCK] = sck;
  u8g->pin_list[U8G_PI_MOSI] = mosi;
  u8g->pin_list[U8G_PI_CS] = cs;
  u8g->pin_list[U8G_PI_A0] = a0;
  u8g->pin_list[U8G_PI_RESET] = reset;

  /* On the Arduino Environment this will lead to two calls to u8g_Begin(), the following line will be called first (by U8glib constructors) */
  /* if - in future releases - this is removed, then still call u8g_UpdateDimension() */
  /* if Arduino call u8g_UpdateDimension else u8g_Begin */
  /* issue 146 */
  return u8g_Begin(u8g);
}

uint8_t u8g_InitHWSPI(u8g_t *u8g, u8g_dev_t *dev, uint8_t cs, uint8_t a0, uint8_t reset)
{
  /* fill data structure with some suitable values */
  u8g_init_data(u8g);
  u8g->dev = dev;

  /* assign user pins */
  u8g->pin_list[U8G_PI_CS] = cs;
  u8g->pin_list[U8G_PI_A0] = a0;
  u8g->pin_list[U8G_PI_RESET] = reset;

  return u8g_Begin(u8g);
}

uint8_t u8g_InitI2C(u8g_t *u8g, u8g_dev_t *dev, uint8_t options)
{
  /* fill data structure with some suitable values */
  u8g_init_data(u8g);
  u8g->dev = dev;

  u8g->pin_list[U8G_PI_I2C_OPTION] = options;

  return u8g_Begin(u8g);
}

uint8_t u8g_Init8BitFixedPort(u8g_t *u8g, u8g_dev_t *dev, uint8_t en, uint8_t cs, uint8_t di, uint8_t rw, uint8_t reset)
{

  /* fill data structure with some suitable values */
  u8g_init_data(u8g);
  u8g->dev = dev;

  /* assign user pins */

  u8g->pin_list[U8G_PI_EN] = en;
  u8g->pin_list[U8G_PI_CS] = cs;
  u8g->pin_list[U8G_PI_DI] = di;
  u8g->pin_list[U8G_PI_RW] = rw;
  u8g->pin_list[U8G_PI_RESET] = reset;

  return u8g_Begin(u8g);
}

uint8_t u8g_Init8Bit(u8g_t *u8g, u8g_dev_t *dev, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
  uint8_t en, uint8_t cs1, uint8_t cs2, uint8_t di, uint8_t rw, uint8_t reset)
{

  /* fill data structure with some suitable values */
  u8g_init_data(u8g);
  u8g->dev = dev;

  /* assign user pins */

  u8g->pin_list[U8G_PI_D0] = d0;
  u8g->pin_list[U8G_PI_D1] = d1;
  u8g->pin_list[U8G_PI_D2] = d2;
  u8g->pin_list[U8G_PI_D3] = d3;
  u8g->pin_list[U8G_PI_D4] = d4;
  u8g->pin_list[U8G_PI_D5] = d5;
  u8g->pin_list[U8G_PI_D6] = d6;
  u8g->pin_list[U8G_PI_D7] = d7;

  u8g->pin_list[U8G_PI_EN] = en;
  u8g->pin_list[U8G_PI_CS1] = cs1;
  u8g->pin_list[U8G_PI_CS2] = cs2;
  u8g->pin_list[U8G_PI_DI] = di;
  u8g->pin_list[U8G_PI_RW] = rw;
  u8g->pin_list[U8G_PI_RESET] = reset;

  return u8g_Begin(u8g);
}

/*

  PIN_D0 8
  PIN_D1 9
  PIN_D2 10
  PIN_D3 11
  PIN_D4 4
  PIN_D5 5
  PIN_D6 6
  PIN_D7 7

  PIN_CS 14
  PIN_A0 15
  PIN_RESET 16
  PIN_WR 17
  PIN_RD 18

  u8g_InitRW8Bit(u8g, dev, d0, d1, d2, d3, d4, d5, d6, d7, cs, a0, wr, rd, reset)
  u8g_InitRW8Bit(u8g, dev,  8,  9, 10, 11,  4,  5,  6,  7, 14, 15, 17, 18, 16)

*/

uint8_t u8g_InitRW8Bit(u8g_t *u8g, u8g_dev_t *dev, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
  uint8_t cs, uint8_t a0, uint8_t wr, uint8_t rd, uint8_t reset)
{

  /* fill data structure with some suitable values */
  u8g_init_data(u8g);
  u8g->dev = dev;

  /* assign user pins */

  u8g->pin_list[U8G_PI_D0] = d0;
  u8g->pin_list[U8G_PI_D1] = d1;
  u8g->pin_list[U8G_PI_D2] = d2;
  u8g->pin_list[U8G_PI_D3] = d3;
  u8g->pin_list[U8G_PI_D4] = d4;
  u8g->pin_list[U8G_PI_D5] = d5;
  u8g->pin_list[U8G_PI_D6] = d6;
  u8g->pin_list[U8G_PI_D7] = d7;

  u8g->pin_list[U8G_PI_CS] = cs;
  u8g->pin_list[U8G_PI_A0] = a0;
  u8g->pin_list[U8G_PI_WR] = wr;
  u8g->pin_list[U8G_PI_RD] = rd;
  u8g->pin_list[U8G_PI_RESET] = reset;

  return u8g_Begin(u8g);
}

void u8g_FirstPage(u8g_t *u8g)
{
  u8g_FirstPageLL(u8g, u8g->dev);
}

uint8_t u8g_NextPage(u8g_t *u8g)
{
  if  ( u8g->cursor_fn != (u8g_draw_cursor_fn)0 )
  {
    u8g->cursor_fn(u8g);
  }
  return u8g_NextPageLL(u8g, u8g->dev);
}

uint8_t u8g_SetContrast(u8g_t *u8g, uint8_t contrast)
{
  return u8g_SetContrastLL(u8g, u8g->dev, contrast);
}

void u8g_SleepOn(u8g_t *u8g)
{
  u8g_call_dev_fn(u8g, u8g->dev, U8G_DEV_MSG_SLEEP_ON, NULL);
}

void u8g_SleepOff(u8g_t *u8g)
{
  u8g_call_dev_fn(u8g, u8g->dev, U8G_DEV_MSG_SLEEP_OFF, NULL);
}

void u8g_DrawPixel(u8g_t *u8g, u8g_uint_t x, u8g_uint_t y)
{
  u8g_DrawPixelLL(u8g, u8g->dev, x, y);
}

void u8g_Draw8Pixel(u8g_t *u8g, u8g_uint_t x, u8g_uint_t y, uint8_t dir, uint8_t pixel)
{
  u8g_Draw8PixelLL(u8g, u8g->dev, x, y, dir, pixel);
}

/* u8g_IsBBXIntersection() has been moved to u8g_clip.c */
#ifdef OBSOLETE_CODE
uint8_t u8g_IsBBXIntersection(u8g_t *u8g, u8g_uint_t x, u8g_uint_t y, u8g_uint_t w, u8g_uint_t h)
{
  /* new code */
  u8g_dev_arg_bbx_t arg;
  arg.x = x;
  arg.y = y;
  arg.w = w;
  arg.h = h;
  return u8g_is_box_bbx_intersection(&(u8g->current_page), &arg);

  /* old code */
  //return u8g_IsBBXIntersectionLL(u8g, u8g->dev, x, y, w, h);
}
#endif

void u8g_SetColorIndex(u8g_t *u8g, uint8_t idx)
{
  u8g->arg_pixel.color = idx;
  /*u8g->color_index = idx; */ /* must be removed */
}

uint8_t u8g_GetColorIndex(u8g_t *u8g)
{
  return u8g->arg_pixel.color;
}

uint8_t u8g_GetDefaultForegroundColor(u8g_t *u8g)
{
  uint8_t mode;
  mode = u8g_GetMode(u8g);
  if ( mode == U8G_MODE_R3G3B2 )
    return 255;     /* white */
  else if ( u8g_GetMode(u8g) == U8G_MODE_GRAY2BIT )
    return 3;         /* max intensity */
  else /* if ( u8g.getMode() == U8G_MODE_BW ) */
    return 1;         /* pixel on */
  return 1;
}

void u8g_SetDefaultForegroundColor(u8g_t *u8g)
{
  u8g_SetColorIndex(u8g, u8g_GetDefaultForegroundColor(u8g));
}

uint8_t u8g_GetDefaultBackgroundColor(u8g_t *u8g)
{
  return 0;
}

void u8g_SetDefaultBackgroundColor(u8g_t *u8g)
{
  u8g_SetColorIndex(u8g, u8g_GetDefaultBackgroundColor(u8g));         /* pixel on / black */
}

uint8_t u8g_GetDefaultMidColor(u8g_t *u8g)
{
  uint8_t mode;
  mode = u8g_GetMode(u8g);
  if ( mode == U8G_MODE_R3G3B2 )
    return 0x06d;     /* gray: 01101101 */
  else if ( u8g_GetMode(u8g) == U8G_MODE_GRAY2BIT )
    return 1;         /* low mid intensity */
  else /* if ( u8g.getMode() == U8G_MODE_BW ) */
    return 1;         /* pixel on */
  return 1;   /* default */
}

void u8g_SetDefaultMidColor(u8g_t *u8g)
{
  u8g_SetColorIndex(u8g, u8g_GetDefaultMidColor(u8g));
}

{'repo_name': 'MillerLabFTW/OpenSLS', 'stars': '159', 'repo_language': 'C', 'file_name': 'body r1.DXF', 'mime_type': 'text/plain', 'hash': 2548542239065047238, 'source_dataset': 'data'}


{'repo_name': 'wolfSSL/wolfssl', 'stars': '905', 'repo_language': 'C', 'file_name': 'include.am', 'mime_type': 'text/plain', 'hash': -6806549413309202859, 'source_dataset': 'data'}


package design.design_patterns.proxy.gumball;

public class SoldOutState implements State {

	private static final long serialVersionUID = 2L;
    transient GumballMachine gumballMachine;

    public SoldOutState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

	public void insertQuarter() {
		System.out.println("You can't insert a quarter, the machine is sold out");
	}

	public void ejectQuarter() {
		System.out.println("You can't eject, you haven't inserted a quarter yet");
	}

	public void turnCrank() {
		System.out.println("You turned, but there are no gumballs");
	}

	public void dispense() {
		System.out.println("No gumball dispensed");
	}

	public String toString() {
		return "sold out";
	}
}

{'repo_name': 'Chaklader/Object-Oriented-Design', 'stars': '150', 'repo_language': 'Java', 'file_name': 'CharacterTest.java', 'mime_type': 'text/x-java', 'hash': -8017060977721311312, 'source_dataset': 'data'}


/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

'use strict';

let registerModule;
if (global.RN$Bridgeless && global.RN$registerCallableModule) {
  registerModule = global.RN$registerCallableModule;
} else {
  const BatchedBridge = require('../BatchedBridge/BatchedBridge');
  registerModule = (moduleName, factory) =>
    BatchedBridge.registerLazyCallableModule(moduleName, factory);
}

registerModule('Systrace', () => require('../Performance/Systrace'));
registerModule('JSTimers', () => require('./Timers/JSTimers'));
registerModule('HeapCapture', () => require('../HeapCapture/HeapCapture'));
registerModule('SamplingProfiler', () =>
  require('../Performance/SamplingProfiler'),
);
registerModule('RCTLog', () => require('../Utilities/RCTLog'));
registerModule(
  'RCTDeviceEventEmitter',
  () => require('../EventEmitter/RCTDeviceEventEmitter').default,
);
registerModule('RCTNativeAppEventEmitter', () =>
  require('../EventEmitter/RCTNativeAppEventEmitter'),
);
registerModule('GlobalPerformanceLogger', () =>
  require('../Utilities/GlobalPerformanceLogger'),
);
registerModule('JSDevSupportModule', () =>
  require('../Utilities/JSDevSupportModule'),
);

if (__DEV__ && !global.__RCTProfileIsProfiling) {
  registerModule('HMRClient', () => require('../Utilities/HMRClient'));
} else {
  registerModule('HMRClient', () => require('../Utilities/HMRClientProdShim'));
}

{'repo_name': 'facebook/react-native', 'stars': '88741', 'repo_language': 'JavaScript', 'file_name': 'libevent.podspec', 'mime_type': 'text/x-c', 'hash': 2198106902127639141, 'source_dataset': 'data'}


/*
 *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/pacing/round_robin_packet_queue.h"

#include <algorithm>
#include <cstdint>
#include <utility>

#include "rtc_base/checks.h"

namespace webrtc {
namespace {
static constexpr DataSize kMaxLeadingSize = DataSize::Bytes(1400);
}

RoundRobinPacketQueue::QueuedPacket::QueuedPacket(const QueuedPacket& rhs) =
    default;
RoundRobinPacketQueue::QueuedPacket::~QueuedPacket() = default;

RoundRobinPacketQueue::QueuedPacket::QueuedPacket(
    int priority,
    Timestamp enqueue_time,
    uint64_t enqueue_order,
    std::multiset<Timestamp>::iterator enqueue_time_it,
    std::unique_ptr<RtpPacketToSend> packet)
    : priority_(priority),
      enqueue_time_(enqueue_time),
      enqueue_order_(enqueue_order),
      is_retransmission_(packet->packet_type() ==
                         RtpPacketMediaType::kRetransmission),
      enqueue_time_it_(enqueue_time_it),
      owned_packet_(packet.release()) {}

bool RoundRobinPacketQueue::QueuedPacket::operator<(
    const RoundRobinPacketQueue::QueuedPacket& other) const {
  if (priority_ != other.priority_)
    return priority_ > other.priority_;
  if (is_retransmission_ != other.is_retransmission_)
    return other.is_retransmission_;

  return enqueue_order_ > other.enqueue_order_;
}

int RoundRobinPacketQueue::QueuedPacket::Priority() const {
  return priority_;
}

RtpPacketMediaType RoundRobinPacketQueue::QueuedPacket::Type() const {
  return *owned_packet_->packet_type();
}

uint32_t RoundRobinPacketQueue::QueuedPacket::Ssrc() const {
  return owned_packet_->Ssrc();
}

Timestamp RoundRobinPacketQueue::QueuedPacket::EnqueueTime() const {
  return enqueue_time_;
}

bool RoundRobinPacketQueue::QueuedPacket::IsRetransmission() const {
  return Type() == RtpPacketMediaType::kRetransmission;
}

uint64_t RoundRobinPacketQueue::QueuedPacket::EnqueueOrder() const {
  return enqueue_order_;
}

RtpPacketToSend* RoundRobinPacketQueue::QueuedPacket::RtpPacket() const {
  return owned_packet_;
}

std::multiset<Timestamp>::iterator
RoundRobinPacketQueue::QueuedPacket::EnqueueTimeIterator() const {
  return enqueue_time_it_;
}

void RoundRobinPacketQueue::QueuedPacket::SubtractPauseTime(
    TimeDelta pause_time_sum) {
  enqueue_time_ -= pause_time_sum;
}

RoundRobinPacketQueue::PriorityPacketQueue::const_iterator
RoundRobinPacketQueue::PriorityPacketQueue::begin() const {
  return c.begin();
}

RoundRobinPacketQueue::PriorityPacketQueue::const_iterator
RoundRobinPacketQueue::PriorityPacketQueue::end() const {
  return c.end();
}

RoundRobinPacketQueue::Stream::Stream() : size(DataSize::Zero()), ssrc(0) {}
RoundRobinPacketQueue::Stream::Stream(const Stream& stream) = default;
RoundRobinPacketQueue::Stream::~Stream() = default;

bool IsEnabled(const WebRtcKeyValueConfig* field_trials, const char* name) {
  if (!field_trials) {
    return false;
  }
  return field_trials->Lookup(name).find("Enabled") == 0;
}

RoundRobinPacketQueue::RoundRobinPacketQueue(
    Timestamp start_time,
    const WebRtcKeyValueConfig* field_trials)
    : transport_overhead_per_packet_(DataSize::Zero()),
      time_last_updated_(start_time),
      paused_(false),
      size_packets_(0),
      size_(DataSize::Zero()),
      max_size_(kMaxLeadingSize),
      queue_time_sum_(TimeDelta::Zero()),
      pause_time_sum_(TimeDelta::Zero()),
      include_overhead_(false) {}

RoundRobinPacketQueue::~RoundRobinPacketQueue() {
  // Make sure to release any packets owned by raw pointer in QueuedPacket.
  while (!Empty()) {
    Pop();
  }
}

void RoundRobinPacketQueue::Push(int priority,
                                 Timestamp enqueue_time,
                                 uint64_t enqueue_order,
                                 std::unique_ptr<RtpPacketToSend> packet) {
  RTC_DCHECK(packet->packet_type().has_value());
  Push(QueuedPacket(priority, enqueue_time, enqueue_order,
                    enqueue_times_.insert(enqueue_time), std::move(packet)));
}

std::unique_ptr<RtpPacketToSend> RoundRobinPacketQueue::Pop() {
  RTC_DCHECK(!Empty());
  Stream* stream = GetHighestPriorityStream();
  const QueuedPacket& queued_packet = stream->packet_queue.top();

  stream_priorities_.erase(stream->priority_it);

  // Calculate the total amount of time spent by this packet in the queue
  // while in a non-paused state. Note that the |pause_time_sum_ms_| was
  // subtracted from |packet.enqueue_time_ms| when the packet was pushed, and
  // by subtracting it now we effectively remove the time spent in in the
  // queue while in a paused state.
  TimeDelta time_in_non_paused_state =
      time_last_updated_ - queued_packet.EnqueueTime() - pause_time_sum_;
  queue_time_sum_ -= time_in_non_paused_state;

  RTC_CHECK(queued_packet.EnqueueTimeIterator() != enqueue_times_.end());
  enqueue_times_.erase(queued_packet.EnqueueTimeIterator());

  // Update |bytes| of this stream. The general idea is that the stream that
  // has sent the least amount of bytes should have the highest priority.
  // The problem with that is if streams send with different rates, in which
  // case a "budget" will be built up for the stream sending at the lower
  // rate. To avoid building a too large budget we limit |bytes| to be within
  // kMaxLeading bytes of the stream that has sent the most amount of bytes.
  DataSize packet_size =
      DataSize::Bytes(queued_packet.RtpPacket()->payload_size() +
                      queued_packet.RtpPacket()->padding_size());
  if (include_overhead_) {
    packet_size += DataSize::Bytes(queued_packet.RtpPacket()->headers_size()) +
                   transport_overhead_per_packet_;
  }
  stream->size =
      std::max(stream->size + packet_size, max_size_ - kMaxLeadingSize);
  max_size_ = std::max(max_size_, stream->size);

  size_ -= packet_size;
  size_packets_ -= 1;
  RTC_CHECK(size_packets_ > 0 || queue_time_sum_ == TimeDelta::Zero());

  std::unique_ptr<RtpPacketToSend> rtp_packet(queued_packet.RtpPacket());
  stream->packet_queue.pop();

  // If there are packets left to be sent, schedule the stream again.
  RTC_CHECK(!IsSsrcScheduled(stream->ssrc));
  if (stream->packet_queue.empty()) {
    stream->priority_it = stream_priorities_.end();
  } else {
    int priority = stream->packet_queue.top().Priority();
    stream->priority_it = stream_priorities_.emplace(
        StreamPrioKey(priority, stream->size), stream->ssrc);
  }

  return rtp_packet;
}

bool RoundRobinPacketQueue::Empty() const {
  RTC_CHECK((!stream_priorities_.empty() && size_packets_ > 0) ||
            (stream_priorities_.empty() && size_packets_ == 0));
  return stream_priorities_.empty();
}

size_t RoundRobinPacketQueue::SizeInPackets() const {
  return size_packets_;
}

DataSize RoundRobinPacketQueue::Size() const {
  return size_;
}

bool RoundRobinPacketQueue::NextPacketIsAudio() const {
  if (stream_priorities_.empty()) {
    return false;
  }
  uint32_t ssrc = stream_priorities_.begin()->second;

  auto stream_info_it = streams_.find(ssrc);
  return stream_info_it->second.packet_queue.top().Type() ==
         RtpPacketMediaType::kAudio;
}

Timestamp RoundRobinPacketQueue::OldestEnqueueTime() const {
  if (Empty())
    return Timestamp::MinusInfinity();
  RTC_CHECK(!enqueue_times_.empty());
  return *enqueue_times_.begin();
}

void RoundRobinPacketQueue::UpdateQueueTime(Timestamp now) {
  RTC_CHECK_GE(now, time_last_updated_);
  if (now == time_last_updated_)
    return;

  TimeDelta delta = now - time_last_updated_;

  if (paused_) {
    pause_time_sum_ += delta;
  } else {
    queue_time_sum_ += TimeDelta::Micros(delta.us() * size_packets_);
  }

  time_last_updated_ = now;
}

void RoundRobinPacketQueue::SetPauseState(bool paused, Timestamp now) {
  if (paused_ == paused)
    return;
  UpdateQueueTime(now);
  paused_ = paused;
}

void RoundRobinPacketQueue::SetIncludeOverhead() {
  include_overhead_ = true;
  // We need to update the size to reflect overhead for existing packets.
  for (const auto& stream : streams_) {
    for (const QueuedPacket& packet : stream.second.packet_queue) {
      size_ += DataSize::Bytes(packet.RtpPacket()->headers_size()) +
               transport_overhead_per_packet_;
    }
  }
}

void RoundRobinPacketQueue::SetTransportOverhead(DataSize overhead_per_packet) {
  if (include_overhead_) {
    DataSize previous_overhead = transport_overhead_per_packet_;
    // We need to update the size to reflect overhead for existing packets.
    for (const auto& stream : streams_) {
      int packets = stream.second.packet_queue.size();
      size_ -= packets * previous_overhead;
      size_ += packets * overhead_per_packet;
    }
  }
  transport_overhead_per_packet_ = overhead_per_packet;
}

TimeDelta RoundRobinPacketQueue::AverageQueueTime() const {
  if (Empty())
    return TimeDelta::Zero();
  return queue_time_sum_ / size_packets_;
}

void RoundRobinPacketQueue::Push(QueuedPacket packet) {
  auto stream_info_it = streams_.find(packet.Ssrc());
  if (stream_info_it == streams_.end()) {
    stream_info_it = streams_.emplace(packet.Ssrc(), Stream()).first;
    stream_info_it->second.priority_it = stream_priorities_.end();
    stream_info_it->second.ssrc = packet.Ssrc();
  }

  Stream* stream = &stream_info_it->second;

  if (stream->priority_it == stream_priorities_.end()) {
    // If the SSRC is not currently scheduled, add it to |stream_priorities_|.
    RTC_CHECK(!IsSsrcScheduled(stream->ssrc));
    stream->priority_it = stream_priorities_.emplace(
        StreamPrioKey(packet.Priority(), stream->size), packet.Ssrc());
  } else if (packet.Priority() < stream->priority_it->first.priority) {
    // If the priority of this SSRC increased, remove the outdated StreamPrioKey
    // and insert a new one with the new priority. Note that |priority_| uses
    // lower ordinal for higher priority.
    stream_priorities_.erase(stream->priority_it);
    stream->priority_it = stream_priorities_.emplace(
        StreamPrioKey(packet.Priority(), stream->size), packet.Ssrc());
  }
  RTC_CHECK(stream->priority_it != stream_priorities_.end());

  // In order to figure out how much time a packet has spent in the queue while
  // not in a paused state, we subtract the total amount of time the queue has
  // been paused so far, and when the packet is popped we subtract the total
  // amount of time the queue has been paused at that moment. This way we
  // subtract the total amount of time the packet has spent in the queue while
  // in a paused state.
  UpdateQueueTime(packet.EnqueueTime());
  packet.SubtractPauseTime(pause_time_sum_);

  size_packets_ += 1;
  size_ += DataSize::Bytes(packet.RtpPacket()->payload_size() +
                           packet.RtpPacket()->padding_size());
  if (include_overhead_) {
    size_ += DataSize::Bytes(packet.RtpPacket()->headers_size()) +
             transport_overhead_per_packet_;
  }

  stream->packet_queue.push(packet);
}

RoundRobinPacketQueue::Stream*
RoundRobinPacketQueue::GetHighestPriorityStream() {
  RTC_CHECK(!stream_priorities_.empty());
  uint32_t ssrc = stream_priorities_.begin()->second;

  auto stream_info_it = streams_.find(ssrc);
  RTC_CHECK(stream_info_it != streams_.end());
  RTC_CHECK(stream_info_it->second.priority_it == stream_priorities_.begin());
  RTC_CHECK(!stream_info_it->second.packet_queue.empty());
  return &stream_info_it->second;
}

bool RoundRobinPacketQueue::IsSsrcScheduled(uint32_t ssrc) const {
  for (const auto& scheduled_stream : stream_priorities_) {
    if (scheduled_stream.second == ssrc)
      return true;
  }
  return false;
}

}  // namespace webrtc

{'repo_name': 'WebKit/webkit', 'stars': '4806', 'repo_language': 'None', 'file_name': 'audio_encoder_isac.h', 'mime_type': 'text/x-c++', 'hash': 4791741797700686395, 'source_dataset': 'data'}


# Generated by Django 2.1 on 2018-10-20 18:45

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("motions", "0013_motion_sorting_and_statute")]

    operations = [
        migrations.AddField(
            model_name="motionchangerecommendation",
            name="internal",
            field=models.BooleanField(default=False),
        )
    ]

{'repo_name': 'OpenSlides/OpenSlides', 'stars': '268', 'repo_language': 'TypeScript', 'file_name': '0007_list_of_speakers_3.py', 'mime_type': 'text/x-python', 'hash': 4033477735041852516, 'source_dataset': 'data'}


---
http_client_port: 6004
http_server_port: 2082
udp_server_port: 6005
database: jdbc:postgresql://localhost:5432/universa_node_t3
node_number: 3
public_host: localhost
node_name: node2_3
ip:
- 127.0.0.1

{'repo_name': 'UniversaBlockchain/universa', 'stars': '323', 'repo_language': 'Java', 'file_name': 'SecureRandomTest.java', 'mime_type': 'text/x-c', 'hash': -1172025722973400131, 'source_dataset': 'data'}


package algs.model.tests.chapter7;

import org.junit.Test;

import algs.model.gametree.IGameState;
import algs.model.gametree.IGameMove;
import algs.model.problems.tictactoe.debug.TicTacToeDebugger;
import algs.model.problems.tictactoe.model.BoardEvaluation;
import algs.model.problems.tictactoe.model.PlaceMark;
import algs.model.problems.tictactoe.model.Player;
import algs.model.problems.tictactoe.model.PlayerFactory;
import algs.model.problems.tictactoe.model.StraightLogic;
import algs.model.problems.tictactoe.model.TicTacToeBoard;
import algs.model.problems.tictactoe.model.TicTacToeState;

import junit.framework.TestCase;

public class AlphaBetaExampleTest extends TestCase {

	@Test
	public void testAlphaBeta() {
		// create the TicTacToe game. Only instantiate the proper class
	    // that you want to play.
		StraightLogic logic = new StraightLogic();

		// 2-move lookahead, using the BoardEvaluation function as described in Nilsson.
	    Player xPlayer = PlayerFactory.createPlayerWithPly(PlayerFactory.AlphaBeta, Player.XMARK, 2);
	    xPlayer.logic(logic);
		xPlayer.score(new BoardEvaluation());

	    // 2-move lookahead, for O.
	    Player oPlayer = PlayerFactory.createPlayerWithPly(PlayerFactory.AlphaBeta, Player.OMARK, 2);
	    oPlayer.logic(logic);
		oPlayer.score(new BoardEvaluation());

	    TicTacToeBoard board = new TicTacToeBoard();
	    IGameState state = new TicTacToeState(board, logic);

	     // pre-initialize board to 1.5 moves
	    new PlaceMark(1,1, (Player) xPlayer).execute(state);
	    new PlaceMark(2,0, (Player) oPlayer).execute(state);
	    new PlaceMark(2,2, (Player) xPlayer).execute(state);

	    algs.model.gametree.debug.AlphaBetaEvaluation ae =
	    	new algs.model.gametree.debug.AlphaBetaEvaluation(2);
	    TicTacToeDebugger std = new TicTacToeDebugger();
		ae.debug(std);

		IGameMove move = ae.bestMove (state, oPlayer, xPlayer);
		System.out.println ("best move:" + move);
		System.out.println (std.getInputString());

		// Only looking ahead, this is the best it can come up with.
		assertEquals (0, ((PlaceMark)move).getColumn());
		assertEquals (0, ((PlaceMark)move).getRow());
	}

}

{'repo_name': 'heineman/algorithms-nutshell-2ed', 'stars': '407', 'repo_language': 'Java', 'file_name': 'org.eclipse.jdt.core.prefs', 'mime_type': 'text/plain', 'hash': -6358181145556605521, 'source_dataset': 'data'}


//
//  ImageLoader.swift
//  ModernMVVM
//
//  Created by Vadym Bulavin on 2/13/20.
//  Copyright © 2020 Vadym Bulavin. All rights reserved.
//

import Combine
import UIKit

class ImageLoader: ObservableObject {
    @Published var image: UIImage?

    private(set) var isLoading = false

    private let url: URL
    private var cache: ImageCache?
    private var cancellable: AnyCancellable?

    private static let imageProcessingQueue = DispatchQueue(label: "image-processing")

    init(url: URL, cache: ImageCache? = nil) {
        self.url = url
        self.cache = cache
    }

    deinit {
        cancellable?.cancel()
    }

    func load() {
        guard !isLoading else { return }

        if let image = cache?[url] {
            self.image = image
            return
        }

        cancellable = URLSession.shared.dataTaskPublisher(for: url)
            .map { UIImage(data: $0.data) }
            .replaceError(with: nil)
            .handleEvents(receiveSubscription: { [weak self] _ in self?.onStart() },
                          receiveOutput: { [weak self] in self?.cache($0) },
                          receiveCompletion: { [weak self] _ in self?.onFinish() },
                          receiveCancel: { [weak self] in self?.onFinish() })
            .subscribe(on: Self.imageProcessingQueue)
            .receive(on: DispatchQueue.main)
            .assign(to: \.image, on: self)
    }

    func cancel() {
        cancellable?.cancel()
    }

    private func onStart() {
        isLoading = true
    }

    private func onFinish() {
        isLoading = false
    }

    private func cache(_ image: UIImage?) {
        image.map { cache?[url] = $0 }
    }
}

{'repo_name': 'V8tr/ModernMVVM', 'stars': '125', 'repo_language': 'Swift', 'file_name': 'IDEWorkspaceChecks.plist', 'mime_type': 'text/xml', 'hash': -3965432051289956192, 'source_dataset': 'data'}


/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsDocShellEnumerator_h___
#define nsDocShellEnumerator_h___

#include "nsISimpleEnumerator.h"
#include "nsTArray.h"
#include "nsIWeakReferenceUtils.h"

class nsIDocShellTreeItem;

/*
// {13cbc281-35ae-11d5-be5b-bde0edece43c}
#define NS_DOCSHELL_FORWARDS_ENUMERATOR_CID  \
{ 0x13cbc281, 0x35ae, 0x11d5, { 0xbe, 0x5b, 0xbd, 0xe0, 0xed, 0xec, 0xe4, 0x3c } }

#define NS_DOCSHELL_FORWARDS_ENUMERATOR_CONTRACTID \
"@mozilla.org/docshell/enumerator-forwards;1"

// {13cbc282-35ae-11d5-be5b-bde0edece43c}
#define NS_DOCSHELL_BACKWARDS_ENUMERATOR_CID  \
{ 0x13cbc282, 0x35ae, 0x11d5, { 0xbe, 0x5b, 0xbd, 0xe0, 0xed, 0xec, 0xe4, 0x3c } }

#define NS_DOCSHELL_BACKWARDS_ENUMERATOR_CONTRACTID \
"@mozilla.org/docshell/enumerator-backwards;1"
*/

class nsDocShellEnumerator : public nsISimpleEnumerator
{
protected:

  enum {
    enumerateForwards,
    enumerateBackwards
  };

  virtual                     ~nsDocShellEnumerator();

public:

                              explicit nsDocShellEnumerator(int32_t inEnumerationDirection);

  // nsISupports
  NS_DECL_ISUPPORTS

  // nsISimpleEnumerator
  NS_DECL_NSISIMPLEENUMERATOR

public:

  nsresult                    GetEnumerationRootItem(nsIDocShellTreeItem * *aEnumerationRootItem);
  nsresult                    SetEnumerationRootItem(nsIDocShellTreeItem * aEnumerationRootItem);

  nsresult                    GetEnumDocShellType(int32_t *aEnumerationItemType);
  nsresult                    SetEnumDocShellType(int32_t aEnumerationItemType);

  nsresult                    First();

protected:

  nsresult                    EnsureDocShellArray();
  nsresult                    ClearState();

  nsresult                    BuildDocShellArray(nsTArray<nsWeakPtr>& inItemArray);
  virtual nsresult            BuildArrayRecursive(nsIDocShellTreeItem* inItem, nsTArray<nsWeakPtr>& inItemArray) = 0;

protected:

  nsWeakPtr                   mRootItem;      // weak ref!

  nsTArray<nsWeakPtr>         mItemArray;     // flattened list of items with matching type
  uint32_t                    mCurIndex;

  int32_t                     mDocShellType;  // only want shells of this type
  bool                        mArrayValid;    // is mItemArray up to date?

  const int8_t                mEnumerationDirection;
};

class nsDocShellForwardsEnumerator : public nsDocShellEnumerator
{
public:

                              nsDocShellForwardsEnumerator()
                              : nsDocShellEnumerator(enumerateForwards)
                              {
                              }

protected:

  virtual nsresult            BuildArrayRecursive(nsIDocShellTreeItem* inItem, nsTArray<nsWeakPtr>& inItemArray);

};

class nsDocShellBackwardsEnumerator : public nsDocShellEnumerator
{
public:

                              nsDocShellBackwardsEnumerator()
                              : nsDocShellEnumerator(enumerateBackwards)
                              {
                              }
protected:

  virtual nsresult            BuildArrayRecursive(nsIDocShellTreeItem* inItem, nsTArray<nsWeakPtr>& inItemArray);
};

#endif // nsDocShellEnumerator_h___

{'repo_name': 'ricardoquesada/Spidermonkey', 'stars': '201', 'repo_language': 'C++', 'file_name': 'panelUI.css', 'mime_type': 'text/plain', 'hash': -6524017369359645627, 'source_dataset': 'data'}


/*
 * Copyright (c) 2003 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

/* HISTORY
 * 8 Aug. 2003 - Created (Derek Kumar)
 */

/* Various protocol definitions
 * for the core transfer protocol, which is a variant of TFTP
 */
#ifndef __KDP_CORE_H
#define __KDP_CORE_H

#include <kern/thread.h>
#include <kdp/kdp_protocol.h>
#include <string.h>

/*
 * Packet types.
 */
#define	KDP_RRQ	  1			/* read request */
#define	KDP_WRQ	  2			/* write request */
#define	KDP_DATA  3			/* data packet */
#define	KDP_ACK	  4			/* acknowledgement */
#define	KDP_ERROR 5			/* error code */
#define KDP_SEEK  6                     /* Seek to specified offset */
#define KDP_EOF   7                     /* signal end of file */
#define KDP_FLUSH 8                     /* flush outstanding data */
#define KDP_FEATURE_MASK_STRING		"features"

enum	{KDP_FEATURE_LARGE_CRASHDUMPS = 1, KDP_FEATURE_LARGE_PKT_SIZE = 2};
extern	uint32_t	kdp_feature_large_crashdumps, kdp_feature_large_pkt_size;

struct	corehdr {
	short	th_opcode;		/* packet type */
	union {
		unsigned int	tu_block;	/* block # */
		unsigned int	tu_code;	/* error code */
		char	tu_rpl[1];	/* request packet payload */
	} th_u;
	char	th_data[0];		/* data or error string */
}__attribute__((packed));

#define	th_block	th_u.tu_block
#define	th_code		th_u.tu_code
#define	th_stuff	th_u.tu_rpl
#define	th_msg		th_data

/*
 * Error codes.
 */
#define	EUNDEF		0		/* not defined */
#define	ENOTFOUND	1		/* file not found */
#define	EACCESS		2		/* access violation */
#define	ENOSPACE	3		/* disk full or allocation exceeded */
#define	EBADOP		4		/* illegal TFTP operation */
#define	EBADID		5		/* unknown transfer ID */
#define	EEXISTS		6		/* file already exists */
#define	ENOUSER		7		/* no such user */

#define CORE_REMOTE_PORT 1069 /* hardwired, we can't really query the services file */

#if CONFIG_EMBEDDED
/*
 * xnu shared memory hardware debugger support
 *
 * A hardware debugger can connect, read the consistent debug
 * header to determine the physical location of the handshake
 * structure and communicate using commands in the structure as
 * defined below.
 *
 * Currently used for sending compressed coredumps to
 * astris.
 */
struct xnu_hw_shmem_dbg_command_info {
	volatile uint32_t xhsdci_status;
	uint32_t xhsdci_seq_no;
	volatile uint64_t xhsdci_buf_phys_addr;
	volatile uint32_t xhsdci_buf_data_length;
	/* end of version 0 structure */
	uint64_t xhsdci_coredump_total_size_uncomp;
	uint64_t xhsdci_coredump_total_size_sent_uncomp;
	uint32_t xhsdci_page_size;
} __attribute__((packed));

#define CUR_XNU_HWSDCI_STRUCT_VERS 1

#define XHSDCI_STATUS_NONE              0 /* default status */
#define XHSDCI_STATUS_KERNEL_BUSY       1 /* kernel is busy with other procedure */
#define XHSDCI_STATUS_KERNEL_READY      2 /* kernel ready to begin command */
#define XHSDCI_COREDUMP_BEGIN           3 /* indicates hardware debugger is ready to begin consuming coredump info */
#define XHSDCI_COREDUMP_BUF_READY       4 /* indicates the kernel has populated the buffer */
#define XHSDCI_COREDUMP_BUF_EMPTY       5 /* indicates hardware debugger is done consuming the current data */
#define XHSDCI_COREDUMP_STATUS_DONE     6 /* indicates last compressed data is in buffer */
#define XHSDCI_COREDUMP_ERROR           7 /* indicates an error was encountered */
#define XHSDCI_COREDUMP_REMOTE_DONE     8 /* indicates that hardware debugger is done */

void panic_spin_shmcon(void);

#endif /* CONFIG_EMBEDDED */

void kdp_panic_dump (void);
void begin_panic_transfer(void);
void abort_panic_transfer (void);
void kdp_set_dump_info(const uint32_t flags, const char *file, const char *destip,
                       const char *routerip, const uint32_t port);
void kdp_get_dump_info(kdp_dumpinfo_reply_t *rp);

enum kern_dump_type {
	KERN_DUMP_DISK, /* local, on device core dump */
	KERN_DUMP_NET, /* kdp network core dump */
#if CONFIG_EMBEDDED
	KERN_DUMP_HW_SHMEM_DBG, /* coordinated hardware shared memory debugger core dump */
#endif
};

int kern_dump(enum kern_dump_type kd_variant);

boolean_t dumped_kernel_core(void);

struct corehdr *create_panic_header(unsigned int request, const char *corename, unsigned length, unsigned block);

int 	kdp_send_crashdump_pkt(unsigned int request, char *corename,
				uint64_t length, void *panic_data);

int	kdp_send_crashdump_data(unsigned int request, char *corename,
    			    uint64_t length, void * txstart);

void kern_collectth_state_size(uint64_t * tstate_count, uint64_t * tstate_size);

void kern_collectth_state(thread_t thread, void *buffer, uint64_t size, void **iter);

boolean_t kdp_has_polled_corefile(void);
kern_return_t kdp_polled_corefile_error(void);

void kdp_core_init(void);

extern boolean_t kdp_corezip_disabled;

#define KDP_CRASHDUMP_POLL_COUNT (2500)

#if PRIVATE
kern_return_t kdp_core_output(void *kdp_core_out_vars, uint64_t length, void * data);

kern_return_t kdp_reset_output_vars(void *kdp_core_out_vars, uint64_t totalbytes);

int kern_dump_record_file(void *kdp_core_out_vars, const char *filename, uint64_t file_offset, uint64_t *out_file_length);

int kern_dump_seek_to_next_file(void *kdp_core_out_varss, uint64_t next_file_offset);

extern boolean_t efi_valid_page(ppnum_t ppn);
#if defined(__x86_64__)
#define EFI_VALID_PAGE(x)	efi_valid_page(x)
#elif defined(__arm__) || defined(__arm64__)
#define EFI_VALID_PAGE(x)	(FALSE)
#endif /* defined (__x86_64__) */

#endif /* PRIVATE */

#endif /* __KDP_CORE_H */

{'repo_name': 'LGCooci/objc4_debug', 'stars': '223', 'repo_language': 'C', 'file_name': 'objcrt.vcproj', 'mime_type': 'text/xml', 'hash': 373124500656896348, 'source_dataset': 'data'}


package io.quarkus.liquibase.runtime;

import static io.quarkus.liquibase.runtime.LiquibaseDataSourceBuildTimeConfig.DEFAULT_CHANGE_LOG;
import static io.quarkus.liquibase.runtime.LiquibaseDataSourceRuntimeConfig.DEFAULT_LOCK_TABLE;
import static io.quarkus.liquibase.runtime.LiquibaseDataSourceRuntimeConfig.DEFAULT_LOG_TABLE;

import java.util.List;
import java.util.Optional;

/**
 * The liquibase configuration
 */
public class LiquibaseConfig {

    /**
     * The change log file
     */
    public String changeLog = DEFAULT_CHANGE_LOG;

    /**
     * The migrate at start flag
     */
    public boolean migrateAtStart = false;

    /**
     * The validate on update flag
     */
    public boolean validateOnMigrate = true;

    /**
     * The clean at start flag
     */
    public boolean cleanAtStart = false;

    /**
     * The list of contexts
     */
    public List<String> contexts = null;

    /**
     * The list of labels
     */
    public List<String> labels = null;

    /**
     * The database change log lock table name
     */
    public String databaseChangeLogLockTableName = DEFAULT_LOCK_TABLE;

    /**
     * The database change log table name
     */
    public String databaseChangeLogTableName = DEFAULT_LOG_TABLE;

    /**
     * The default catalog name
     */
    public Optional<String> defaultCatalogName = Optional.empty();

    /**
     * The default schema name
     */
    public Optional<String> defaultSchemaName = Optional.empty();

    /**
     * The liquibase tables catalog name
     */
    public Optional<String> liquibaseCatalogName = Optional.empty();

    /**
     * The liquibase tables schema name
     */
    public Optional<String> liquibaseSchemaName = Optional.empty();

    /**
     * The liquibase tables tablespace name
     */
    public Optional<String> liquibaseTablespaceName = Optional.empty();

}

{'repo_name': 'quarkusio/quarkus', 'stars': '5298', 'repo_language': 'Java', 'file_name': 'ProdModeTestResults.java', 'mime_type': 'text/x-java', 'hash': -9193976169807712349, 'source_dataset': 'data'}


# Copyright (c) 2018, Intel Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

set(TMP_SOURCES_
    ${TMP_SOURCES_}
    ${CMAKE_CURRENT_LIST_DIR}/decode_basic_feature.cpp
    ${CMAKE_CURRENT_LIST_DIR}/decode_predication.cpp
    ${CMAKE_CURRENT_LIST_DIR}/decode_feature_manager.cpp
    ${CMAKE_CURRENT_LIST_DIR}/decode_marker.cpp
)

set(TMP_HEADERS_
    ${TMP_HEADERS_}
    ${CMAKE_CURRENT_LIST_DIR}/decode_basic_feature.h
    ${CMAKE_CURRENT_LIST_DIR}/decode_predication.h
    ${CMAKE_CURRENT_LIST_DIR}/decode_feature_manager.h
    ${CMAKE_CURRENT_LIST_DIR}/decode_marker.h
)

media_add_curr_to_include_path()

{'repo_name': 'intel/media-driver', 'stars': '405', 'repo_language': 'C', 'file_name': 'Readme.txt', 'mime_type': 'text/plain', 'hash': 8671137054773638334, 'source_dataset': 'data'}


namespace CachingWithAspectCore.Controllers
{
    using AspectCore.Injector;
    using CachingWithAspectCore.BLL;
    using CachingWithAspectCore.Services;
    using Microsoft.AspNetCore.Mvc;

    public class HomeController : Controller
    {
        private IDateTimeService _dateTimeService;

        public HomeController(IDateTimeService dateTimeService)
        {
            _dateTimeService = dateTimeService;
        }

        public IActionResult Index()
        {
            return Content(_dateTimeService.GetCurrentUtcTime());
        }
    }

    public class BllController : Controller
    {
        private IServiceResolver _scope;
        private DateTimeBLL _dateTimeBLL;

        public BllController(IServiceResolver scope)
        {
            this._scope = scope;
            _dateTimeBLL = _scope.Resolve<DateTimeBLL>();
        }

        public IActionResult Index()
        {
            return Content(_dateTimeBLL.GetCurrentUtcTime());
        }
    }
}

{'repo_name': 'catcherwong/Demos', 'stars': '223', 'repo_language': 'C#', 'file_name': 'launchSettings.json', 'mime_type': 'text/plain', 'hash': -21491139743163439, 'source_dataset': 'data'}


// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * When Date is called as a function rather than as a constructor,
 * it should be "string" representing the current time (UTC)
 *
 * @path ch15/15.9/15.9.2/S15.9.2.1_A1.js
 * @description Checking type of returned value
 */

//CHECK#1
if( typeof Date() !== "string" ) {
  $ERROR('#1: typeof Date() should be "string", actual is '+(typeof Date()));
}

//CHECK#2
if( typeof Date(1) !== "string"  ) {
  $ERROR('#2: typeof Date(1) should be "string", actual is '+(typeof Date(1)));
}

//CHECK#3
if( typeof Date(1970, 1) !== "string"  ) {
  $ERROR('#3: typeof Date(1970, 1) should be "string", actual is '+(typeof Date(1970, 1)));
}

//CHECK#4
if( typeof Date(1970, 1, 1) !== "string"  ) {
  $ERROR('#4: typeof Date(1970, 1, 1) should be "string", actual is '+(typeof Date(1970, 1, 1)));
}

//CHECK#5
if( typeof Date(1970, 1, 1, 1) !== "string"  ) {
  $ERROR('#5: typeof Date(1970, 1, 1, 1) should be "string", actual is '+(typeof Date(1970, 1, 1, 1)));
}

//CHECK#6
if( typeof Date(1970, 1, 1, 1) !== "string"  ) {
  $ERROR('#7: typeof Date(1970, 1, 1, 1) should be "string", actual is '+(typeof Date(1970, 1, 1, 1)));
}

//CHECK#8
if( typeof Date(1970, 1, 1, 1, 0) !== "string"  ) {
  $ERROR('#8: typeof Date(1970, 1, 1, 1, 0) should be "string", actual is '+(typeof Date(1970, 1, 1, 1, 0)));
}

//CHECK#9
if( typeof Date(1970, 1, 1, 1, 0, 0) !== "string"  ) {
  $ERROR('#9: typeof Date(1970, 1, 1, 1, 0, 0) should be "string", actual is '+(typeof Date(1970, 1, 1, 1, 0, 0)));
}

//CHECK#10
if( typeof Date(1970, 1, 1, 1, 0, 0, 0) !== "string"  ) {
  $ERROR('#10: typeof Date(1970, 1, 1, 1, 0, 0, 0) should be "string", actual is '+(typeof Date(1970, 1, 1, 1, 0, 0, 0)));
}

//CHECK#11
if( typeof Date(Number.NaN) !== "string"  ) {
  $ERROR('#11: typeof Date(Number.NaN) should be "string", actual is '+(typeof Date(Number.NaN)));
}

//CHECK#12
if( typeof Date(Number.POSITIVE_INFINITY) !== "string"  ) {
  $ERROR('#12: typeof Date(Number.POSITIVE_INFINITY) should be "string", actual is '+(typeof Date(Number.POSITIVE_INFINITY)));
}

//CHECK#13
if( typeof Date(Number.NEGATIVE_INFINITY) !== "string"  ) {
  $ERROR('#13: typeof Date(Number.NEGATIVE_INFINITY) should be "string", actual is '+(typeof Date(Number.NEGATIVE_INFINITY)));
}

//CHECK#14
if( typeof Date(undefined) !== "string"  ) {
  $ERROR('#14: typeof Date(undefined) should be "string", actual is '+(typeof Date(undefined)));
}

//CHECK#15
if( typeof Date(null) !== "string"  ) {
  $ERROR('#15: typeof Date(null) should be "string", actual is '+(typeof Date(null)));
}

{'repo_name': 'wizzard0/js2lua', 'stars': '181', 'repo_language': 'JavaScript', 'file_name': 'shortcuts.js', 'mime_type': 'text/plain', 'hash': -5922366984871008255, 'source_dataset': 'data'}


{0 Abstract Interpretation Framework}

{!module-Absint} is Infer's abstract interpretation framework, the recommended way to write analyses in Infer.

Important modules:
- {!module-Absint.AbstractInterpreter}
- {!module-Absint.AbstractDomain}

{'repo_name': 'facebook/infer', 'stars': '11071', 'repo_language': 'OCaml', 'file_name': 'version-0.17.0-sidebars.json', 'mime_type': 'text/plain', 'hash': -3563048872381622152, 'source_dataset': 'data'}


'use strict';

var xtend = require('xtend');
var escapes = require('markdown-escapes');
var defaults = require('./defaults');

module.exports = setOptions;

function setOptions(options) {
  var self = this;
  var current = self.options;
  var key;
  var value;

  if (options == null) {
    options = {};
  } else if (typeof options === 'object') {
    options = xtend(options);
  } else {
    throw new Error(
      'Invalid value `' + options + '` ' +
      'for setting `options`'
    );
  }

  for (key in defaults) {
    value = options[key];

    if (value == null) {
      value = current[key];
    }

    if (
      (key !== 'blocks' && typeof value !== 'boolean') ||
      (key === 'blocks' && typeof value !== 'object')
    ) {
      throw new Error('Invalid value `' + value + '` for setting `options.' + key + '`');
    }

    options[key] = value;
  }

  self.options = options;
  self.escape = escapes(options);

  return self;
}

{'repo_name': 'nodejs/quic', 'stars': '266', 'repo_language': 'JavaScript', 'file_name': 'd8-worker-shutdown-gc.js', 'mime_type': 'text/plain', 'hash': -6201414657961924681, 'source_dataset': 'data'}


/*******************************************************************************
 * This file is part of OpenNMS(R).
 *
 * Copyright (C) 2013-2014 The OpenNMS Group, Inc.
 * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * OpenNMS(R) is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with OpenNMS(R).  If not, see:
 *      http://www.gnu.org/licenses/
 *
 * Additional permission under GNU AGPL version 3 section 7
 *
 * If you modify this Program, or any covered work, by linking or
 * combining it with SBLIM (or a modified version of that library),
 * containing parts covered by the terms of the Eclipse Public License,
 * the licensors of this Program grant you additional permission to
 * convey the resulting work. {Corresponding Source for a non-source
 * form of such a combination shall include the source code for the
 * parts of SBLIM used as well as that of the covered work.}
 *
 * For more information contact:
 *     OpenNMS(R) Licensing <license@opennms.org>
 *     http://www.opennms.org/
 *     http://www.opennms.com/
 *******************************************************************************/

package org.opennms.netmgt.collectd.vmware;

import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.createPartialMock;
import static org.powermock.api.easymock.PowerMock.expectNew;
import static org.powermock.api.easymock.PowerMock.method;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.suppress;
import static org.powermock.api.easymock.PowerMock.verify;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.SSLSocketFactory;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.netmgt.collectd.vmware.vijava.VmwarePerformanceValues;
import org.opennms.protocols.vmware.ServiceInstancePool;
import org.opennms.protocols.vmware.VmwareViJavaAccess;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import org.sblim.wbem.cim.CIMDataType;
import org.sblim.wbem.cim.CIMInstance;
import org.sblim.wbem.cim.CIMNameSpace;
import org.sblim.wbem.cim.CIMObject;
import org.sblim.wbem.cim.CIMObjectPath;
import org.sblim.wbem.cim.CIMProperty;
import org.sblim.wbem.cim.CIMValue;
import org.sblim.wbem.client.CIMClient;
import org.sblim.wbem.util.SessionProperties;

import com.vmware.vim25.AboutInfo;
import com.vmware.vim25.ElementDescription;
import com.vmware.vim25.HostIpConfig;
import com.vmware.vim25.HostNetworkInfo;
import com.vmware.vim25.HostServiceTicket;
import com.vmware.vim25.HostVirtualNic;
import com.vmware.vim25.HostVirtualNicSpec;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.PerfCounterInfo;
import com.vmware.vim25.PerfEntityMetric;
import com.vmware.vim25.PerfEntityMetricBase;
import com.vmware.vim25.PerfMetricId;
import com.vmware.vim25.PerfMetricIntSeries;
import com.vmware.vim25.PerfProviderSummary;
import com.vmware.vim25.PerfQuerySpec;
import com.vmware.vim25.PerfSummaryType;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.mo.HostNetworkSystem;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.PerformanceManager;
import com.vmware.vim25.mo.ServerConnection;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.mo.util.MorUtil;
import com.vmware.vim25.ws.WSClient;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceInstance.class, PerformanceManager.class, VmwareViJavaAccess.class, MorUtil.class, PerfProviderSummary.class, HostSystem.class, HostNetworkSystem.class, CIMClient.class})
public class VmwareViJavaAccessTest {

    private VmwareViJavaAccess vmwareViJavaAccess;
    private PerformanceManager mockPerformanceManager;
    private ServiceInstance mockServiceInstance;
    private ServerConnection mockServerConnection;
    private AboutInfo mockAboutInfo;
    private PerfProviderSummary mockPerfProviderSummary;
    private HostNetworkSystem mockHostNetworkSystem;
    private HostSystem mockHostSystem;
    private CIMClient mockCIMClient;

    private ManagedObjectReference managedObjectReferenceVirtualMachine;
    private ManagedObjectReference managedObjectReferenceHostSystem;
    private ManagedObjectReference managedObjectReferenceManagedEntity;

    private VirtualMachine virtualMachine;
    private HostSystem hostSystem;
    private ManagedEntity managedEntity;

    private PerfEntityMetricBase[] perfEntityMetricBases;
    private PerfCounterInfo[] perfCounterInfos;
    private PerfQuerySpec perfQuerySpec;
    private List<CIMObject> cimObjects;

    @Before
    public void setUp() throws Exception {
        // setup required objects

        managedObjectReferenceManagedEntity = new ManagedObjectReference();
        managedObjectReferenceManagedEntity.setType("ManagedEntity");
        managedObjectReferenceManagedEntity.setVal("moIdMe");

        managedObjectReferenceVirtualMachine = new ManagedObjectReference();
        managedObjectReferenceVirtualMachine.setType("VirtualMachine");
        managedObjectReferenceVirtualMachine.setVal("moIdVm");

        managedObjectReferenceHostSystem = new ManagedObjectReference();
        managedObjectReferenceHostSystem.setType("HostSystem");
        managedObjectReferenceHostSystem.setVal("moIdHs");

        // setup VmwareViJavaAccess
        vmwareViJavaAccess = new VmwareViJavaAccess("hostname", "username", "password") {
            @Override
            protected void relax() {
            }
        };

        // setup PerformanceManager
        mockPerformanceManager = createMock(PerformanceManager.class);

        // setup ServiceInstance mock
        mockServiceInstance = createMock(ServiceInstance.class);

        // setup ServerConnection
        mockServerConnection = new ServerConnection(new URL("https://hostname/sdk"), new VimPortType(new WSClient("https://hostname/sdk") {
            @Override
            protected SSLSocketFactory getTrustAllSocketFactory(boolean ignoreCert) throws RemoteException {
                return null;
            }
        }), mockServiceInstance);

        // setup AboutInfo
        mockAboutInfo = createMock(AboutInfo.class);

        expectNew(ServiceInstance.class, new Class<?>[]{URL.class, String.class, String.class}, new URL("https://hostname/sdk"), "username", "password").andReturn(mockServiceInstance).anyTimes();
        expect(mockServiceInstance.getServerConnection()).andReturn(mockServerConnection).anyTimes();
        expect(mockServiceInstance.getPerformanceManager()).andReturn(mockPerformanceManager).anyTimes();
        expect(mockServiceInstance.getAboutInfo()).andReturn(mockAboutInfo).anyTimes();

        managedEntity = new ManagedEntity(null, managedObjectReferenceManagedEntity);
        virtualMachine = new VirtualMachine(null, managedObjectReferenceVirtualMachine);
        hostSystem = new HostSystem(null, managedObjectReferenceHostSystem);

        Whitebox.setInternalState(VmwareViJavaAccess.class, "m_serviceInstancePool", new ServiceInstancePool(){
            @Override
            public synchronized ServiceInstance retain(String host, String username, String password) throws MalformedURLException, RemoteException {
                return mockServiceInstance;
            }
        });

        // setup MorUtil

        mockStatic(MorUtil.class);
        expect(MorUtil.createExactManagedEntity(mockServerConnection, managedObjectReferenceManagedEntity)).andReturn(managedEntity).anyTimes();
        expect(MorUtil.createExactManagedEntity(mockServerConnection, managedObjectReferenceVirtualMachine)).andReturn(virtualMachine).anyTimes();
        expect(MorUtil.createExactManagedEntity(mockServerConnection, managedObjectReferenceHostSystem)).andReturn(hostSystem).anyTimes();

        // setup about info

        expect(mockAboutInfo.getApiVersion()).andReturn("2.x");
        expect(mockAboutInfo.getApiVersion()).andReturn("3.x");
        expect(mockAboutInfo.getApiVersion()).andReturn("4.x");
        expect(mockAboutInfo.getApiVersion()).andReturn("5.x");
        expect(mockAboutInfo.getApiVersion()).andReturn("6.x");
        expect(mockAboutInfo.getApiVersion()).andReturn("x");

        // setup performance data

        int refreshRate = 100;
        int metricCount = 15;
        int instanceModifier = 5;

        perfQuerySpec = new PerfQuerySpec();
        perfQuerySpec.setEntity(managedEntity.getMOR());
        perfQuerySpec.setMaxSample(new
                Integer(1)
        );
        perfQuerySpec.setIntervalId(refreshRate);

        perfEntityMetricBases = new PerfEntityMetricBase[metricCount];
        perfCounterInfos = new PerfCounterInfo[metricCount];

        for (int i = 0; i < metricCount; i++) {
            ElementDescription groupInfo = new ElementDescription();
            groupInfo.setKey("key" + i);

            ElementDescription nameInfo = new ElementDescription();
            nameInfo.setKey("name" + i);

            perfCounterInfos[i] = new PerfCounterInfo();
            perfCounterInfos[i].setKey(i);
            perfCounterInfos[i].setGroupInfo(groupInfo);
            perfCounterInfos[i].setNameInfo(nameInfo);
            perfCounterInfos[i].setRollupType(PerfSummaryType.average);

            perfEntityMetricBases[i] = new PerfEntityMetric();

            PerfMetricIntSeries[] perfMetricIntSeries;

            int instanceCount = (i % instanceModifier) + 1;

            perfMetricIntSeries = new PerfMetricIntSeries[instanceCount];

            for (int b = 0; b < instanceCount; b++) {
                PerfMetricId perfMetricId = new PerfMetricId();
                perfMetricId.setCounterId(i);

                if (instanceCount == 1) {
                    perfMetricId.setInstance(null);
                } else {
                    perfMetricId.setInstance("instance" + b);
                }

                perfMetricIntSeries[b] = new PerfMetricIntSeries();
                perfMetricIntSeries[b].setValue(new long[]{(long) 42});
                perfMetricIntSeries[b].setId(perfMetricId);
            }

            ((PerfEntityMetric) perfEntityMetricBases[i]).setValue(perfMetricIntSeries);
        }

        // setup PerfProviderSummary
        mockPerfProviderSummary = createMock(PerfProviderSummary.class);

        expect(mockPerformanceManager.queryPerfProviderSummary(managedEntity)).andReturn(mockPerfProviderSummary).anyTimes();
        expect(mockPerfProviderSummary.getRefreshRate()).andReturn(refreshRate).anyTimes();
        expect(mockPerformanceManager.getPerfCounter()).andReturn(perfCounterInfos).anyTimes();
        expect(mockPerformanceManager.queryPerf(anyObject(PerfQuerySpec[].class))).andReturn(perfEntityMetricBases).anyTimes();

        // setup network info

        HostNetworkInfo hostNetworkInfo = new HostNetworkInfo();

        int numberOfVnics = 3;

        HostVirtualNic[] hostVirtualNics = new HostVirtualNic[numberOfVnics];

        for (int i = 0; i < numberOfVnics; i++) {
            HostVirtualNicSpec hostVirtualNicSpec = new HostVirtualNicSpec();
            HostIpConfig hostIpConfig = new HostIpConfig();
            hostIpConfig.setIpAddress("192.168.1." + (i + 1));
            hostVirtualNicSpec.setIp(hostIpConfig);
            hostVirtualNics[i] = new HostVirtualNic();
            hostVirtualNics[i].setSpec(hostVirtualNicSpec);
        }

        hostNetworkInfo.setVnic(hostVirtualNics);

        HostVirtualNic[] hostVirtualConsoleNics = new HostVirtualNic[numberOfVnics];

        for (int i = 0; i < numberOfVnics; i++) {
            HostVirtualNicSpec hostVirtualNicSpec = new HostVirtualNicSpec();
            HostIpConfig hostIpConfig = new HostIpConfig();
            hostIpConfig.setIpAddress("192.168.2." + (i + 1));
            hostVirtualNicSpec.setIp(hostIpConfig);
            hostVirtualConsoleNics[i] = new HostVirtualNic();
            hostVirtualConsoleNics[i].setSpec(hostVirtualNicSpec);
        }

        hostNetworkInfo.setConsoleVnic(hostVirtualConsoleNics);

        HostServiceTicket hostServiceTicket = new HostServiceTicket();
        hostServiceTicket.setSessionId("sessionId");

        // setup HostSystem
        mockHostSystem = createMock(HostSystem.class);

        // setup HostNetworkSystem
        mockHostNetworkSystem = createMock(HostNetworkSystem.class);

        // setup CIMClient
        mockCIMClient = createPartialMock(CIMClient.class, "enumerateInstances", "getSessionProperties");

        // setup the cim objects

        cimObjects = new ArrayList<>();

        int cimObjectCount = 5;

        for (int i = 0; i < cimObjectCount; i++) {
            CIMInstance cimInstance = new CIMInstance();
            cimInstance.setName("cimInstance" + i);
            cimObjects.add(cimInstance);
        }

        expect(mockHostSystem.getName()).andReturn("mockesxi01.local").anyTimes();
        expect(mockHostSystem.getHostNetworkSystem()).andReturn(mockHostNetworkSystem).anyTimes();
        expect(mockHostSystem.acquireCimServicesTicket()).andReturn(hostServiceTicket).anyTimes();
        expect(mockHostNetworkSystem.getNetworkInfo()).andReturn(hostNetworkInfo).anyTimes();
        expectNew(CIMClient.class, new Class<?>[]{CIMNameSpace.class, Principal.class, Object.class}, anyObject(), anyObject(), anyObject()).andReturn(mockCIMClient).anyTimes();

        suppress(method(CIMClient.class, "useMPost"));

        expect(mockCIMClient.enumerateInstances(new CIMObjectPath("cimClass"))).andReturn(Collections.enumeration(cimObjects)).anyTimes();

        SessionProperties sessionProperties = new SessionProperties();
        expect(mockCIMClient.getSessionProperties()).andReturn(sessionProperties).anyTimes();
    }

    @Test
    public void testGetPerfCounterInfoMap() {

        replay(mockPerformanceManager, mockServiceInstance, ServiceInstance.class);

        try {
            vmwareViJavaAccess.connect();
        } catch (MalformedURLException e) {
            Assert.fail(e.getMessage());
        } catch (RemoteException e) {
            Assert.fail(e.getMessage());
        }

        Map<Integer, PerfCounterInfo> returnedPerfCounterInfoMap = vmwareViJavaAccess.getPerfCounterInfoMap();

        Assert.assertEquals(returnedPerfCounterInfoMap.size(), perfCounterInfos.length);

        for (int i : returnedPerfCounterInfoMap.keySet()) {
            Assert.assertEquals(returnedPerfCounterInfoMap.get(i), perfCounterInfos[i]);
        }

        verify(mockPerformanceManager, mockServiceInstance, ServiceInstance.class);
    }

    @Test
    public void testGetManagedEntityByManagedObjectId() {
        replay(mockServiceInstance, MorUtil.class, ServiceInstance.class);

        try {
            vmwareViJavaAccess.connect();
        } catch (MalformedURLException e) {
            Assert.fail(e.getMessage());
        } catch (RemoteException e) {
            Assert.fail(e.getMessage());
        }

        ManagedEntity returnedManagedEntity = vmwareViJavaAccess.getManagedEntityByManagedObjectId("moIdMe");

        Assert.assertNotNull(returnedManagedEntity);
        Assert.assertEquals(managedEntity.getMOR().getVal(), returnedManagedEntity.getMOR().getVal());

        verify(mockServiceInstance, MorUtil.class, ServiceInstance.class);
    }

    @Test
    public void testGetVirtualMachineByManagedObjectId() throws Exception {
        replay(mockServiceInstance, MorUtil.class, ServiceInstance.class);

        try {
            vmwareViJavaAccess.connect();
        } catch (MalformedURLException e) {
            Assert.fail(e.getMessage());
        } catch (RemoteException e) {
            Assert.fail(e.getMessage());
        }

        VirtualMachine returnedVirtualMachine = vmwareViJavaAccess.getVirtualMachineByManagedObjectId("moIdVm");

        Assert.assertNotNull(returnedVirtualMachine);
        Assert.assertEquals(virtualMachine.getMOR().getVal(), returnedVirtualMachine.getMOR().getVal());

        verify(mockServiceInstance, MorUtil.class, ServiceInstance.class);
    }

    @Test
    public void testGetHostSystemByManagedObjectId() throws Exception {
        replay(mockServiceInstance, MorUtil.class, ServiceInstance.class);

        try {
            vmwareViJavaAccess.connect();
        } catch (MalformedURLException e) {
            Assert.fail(e.getMessage());
        } catch (RemoteException e) {
            Assert.fail(e.getMessage());
        }

        HostSystem returnedHostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId("moIdHs");

        Assert.assertNotNull(returnedHostSystem);
        Assert.assertEquals(hostSystem.getMOR().getVal(), returnedHostSystem.getMOR().getVal());

        verify(mockServiceInstance, MorUtil.class, ServiceInstance.class);
    }

    @Test
    public void testQueryPerformanceValues() {
        replay(mockPerformanceManager, mockPerfProviderSummary, mockServiceInstance, ServiceInstance.class);

        VmwarePerformanceValues vmwarePerformanceValues = null;

        try {
            vmwareViJavaAccess.connect();

            vmwarePerformanceValues = vmwareViJavaAccess.queryPerformanceValues(managedEntity);
        } catch (MalformedURLException e) {
            Assert.fail(e.getMessage());
        } catch (RemoteException e) {
            Assert.fail(e.getMessage());
        }

        Assert.assertNotNull(vmwarePerformanceValues);

        for (int i = 0; i < perfCounterInfos.length; i++) {
            PerfCounterInfo perfCounterInfo = perfCounterInfos[i];

            String expectedName = perfCounterInfo.getGroupInfo().getKey() + "." + perfCounterInfo.getNameInfo().getKey() + "." + perfCounterInfo.getRollupType().toString();

            if (vmwarePerformanceValues.hasInstances(expectedName)) {
                Set<String> instances = vmwarePerformanceValues.getInstances(expectedName);

                Assert.assertEquals(instances.size(), ((PerfEntityMetric) perfEntityMetricBases[i]).getValue().length);

                PerfMetricIntSeries[] perfMetricIntSeries = (PerfMetricIntSeries[]) ((PerfEntityMetric) perfEntityMetricBases[i]).getValue();

                for (int b = 0; b < perfMetricIntSeries.length; b++) {
                    Assert.assertTrue(instances.contains(perfMetricIntSeries[b].getId().getInstance()));
                }
            } else {
                Assert.assertEquals(1, ((PerfEntityMetric) perfEntityMetricBases[i]).getValue().length);
            }
        }

        verify(mockPerformanceManager, mockPerfProviderSummary, mockServiceInstance, ServiceInstance.class);
    }

    @Test
    public void testQueryCimObjects() {
        replay(mockPerformanceManager, mockHostSystem, mockHostNetworkSystem, mockCIMClient, CIMClient.class, mockServiceInstance, ServiceInstance.class);

        try {
            vmwareViJavaAccess.connect();
        } catch (MalformedURLException e) {
            Assert.fail(e.getMessage());
        } catch (RemoteException e) {
            Assert.fail(e.getMessage());
        }

        List<CIMObject> returnedCimObjects = null;

        try {
            returnedCimObjects = vmwareViJavaAccess.queryCimObjects(mockHostSystem, "cimClass");
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }

        Assert.assertNotNull(returnedCimObjects);
        Assert.assertEquals(returnedCimObjects.size(), cimObjects.size());

        for (CIMObject cimObject : cimObjects) {
            Assert.assertTrue(returnedCimObjects.contains(cimObject));

        }

        verify(mockPerformanceManager, mockHostSystem, mockHostNetworkSystem, mockCIMClient, CIMClient.class, mockServiceInstance, ServiceInstance.class);
    }

    @Test
    public void testSearchManagedEntities() throws Exception {
        // noop
    }

    @Test
    public void testGetPropertyOfCimObject() throws Exception {

        CIMObject obj1 = new CIMInstance();

        CIMProperty cimProperty1 = new CIMProperty();
        cimProperty1.setName("theKey");
        cimProperty1.setValue(new CIMValue("theValue", CIMDataType.getPredefinedType(CIMDataType.STRING)));
        obj1.addProperty(cimProperty1);

        CIMObject obj2 = new CIMInstance();

        CIMProperty cimProperty2 = new CIMProperty();
        cimProperty2.setName("theKey");
        cimProperty2.setValue(new CIMValue(null, CIMDataType.getPredefinedType(CIMDataType.STRING)));
        obj2.addProperty(cimProperty2);

        CIMObject obj3 = new CIMInstance();

        CIMProperty cimProperty3 = new CIMProperty();
        obj3.addProperty(cimProperty3);

        Assert.assertEquals(vmwareViJavaAccess.getPropertyOfCimObject(obj1, "theKey"), "theValue");
        Assert.assertNull(vmwareViJavaAccess.getPropertyOfCimObject(obj2, "theKey"));
        Assert.assertNull(vmwareViJavaAccess.getPropertyOfCimObject(obj3, "theKey"));
    }

    @Test
    public void testGetMajorApiVersion() throws Exception {
        replay(mockAboutInfo, mockServiceInstance, ServiceInstance.class);

        try {
            vmwareViJavaAccess.connect();

            int majorApiVersion;

            majorApiVersion = vmwareViJavaAccess.getMajorApiVersion();
            Assert.assertEquals(majorApiVersion, 3);
            majorApiVersion = vmwareViJavaAccess.getMajorApiVersion();
            Assert.assertEquals(majorApiVersion, 3);
            majorApiVersion = vmwareViJavaAccess.getMajorApiVersion();
            Assert.assertEquals(majorApiVersion, 4);
            majorApiVersion = vmwareViJavaAccess.getMajorApiVersion();
            Assert.assertEquals(majorApiVersion, 5);
            majorApiVersion = vmwareViJavaAccess.getMajorApiVersion();
            Assert.assertEquals(majorApiVersion, 6);
        } catch (MalformedURLException e) {
            Assert.fail(e.getMessage());
        } catch (RemoteException e) {
            Assert.fail(e.getMessage());
        }
    }
}

{'repo_name': 'OpenNMS/opennms', 'stars': '506', 'repo_language': 'Java', 'file_name': 'ReportParameterBuilder.java', 'mime_type': 'text/x-java', 'hash': -8102911592769718988, 'source_dataset': 'data'}