code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
using java.lang;
using loon.utils;
namespace loon.geom
{
public class AABB : XY, BoxSize {
public static AABB At(string v)
{
if (StringUtils.IsEmpty(v))
{
return new AABB();
}
string[] result = StringUtils.Split(v, ',');
int len = result.Length;
if (len > 3)
{
try
{
float x = Float.ParseFloat(result[0].Trim());
float y = Float.ParseFloat(result[1].Trim());
float width = Float.ParseFloat(result[2].Trim());
float height = Float.ParseFloat(result[3].Trim());
return new AABB(x, y, width, height);
}
catch (Exception)
{
}
}
return new AABB();
}
public static AABB At(int x, int y, int w, int h)
{
return new AABB(x, y, w, h);
}
public static AABB At(float x, float y, float w, float h)
{
return new AABB(x, y, w, h);
}
/*
public static AABB fromActor(ActionBind bind)
{
return new AABB(bind.GetX(), bind.GetY(), bind.GetWidth(), bind.GetHeight());
}*/
public float minX, minY;
public float maxX, maxY;
public AABB(): this(0.0F, 0.0F, 0.0F, 0.0F)
{
}
public AABB(float minX, float minY, float maxX, float maxY)
{
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
}
public AABB SetCentered(float x, float y, float size)
{
return Set(x - size / 2f, y - size / 2f, size, size);
}
public AABB SetCentered(float x, float y, float width, float height)
{
return Set(x - width / 2f, y - height / 2f, width, height);
}
public int Width()
{
return (int)this.maxX;
}
public int Height()
{
return (int)this.maxY;
}
public float GetWidth()
{
return this.maxX;
}
public float GetHeight()
{
return this.maxY;
}
public AABB Cpy()
{
return new AABB(this.minX, this.minY, this.maxX, this.maxY);
}
public bool IsHit(AABB b)
{
return this.minX < b.maxX && b.minX < this.maxX && this.minY < b.maxY && b.minY < this.maxY;
}
public AABB Set(float minX, float minY, float maxX, float maxY)
{
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
return this;
}
public AABB Move(float cx, float cy)
{
this.minX += cx;
this.minY += cy;
return this;
}
public float Distance(Vector2f other)
{
float dx = GetX() - other.x;
float dy = GetY() - other.y;
return MathUtils.Sqrt(dx * dx + dy * dy);
}
public AABB Merge(AABB other)
{
float minX = MathUtils.Min(this.GetX(), other.GetX());
float minY = MathUtils.Min(this.GetY(), other.GetY());
float maxW = MathUtils.Max(this.GetWidth(), other.GetWidth());
float maxH = MathUtils.Max(this.GetHeight(), other.GetHeight());
return new AABB(minX, minY, maxW, maxH);
}
public Vector2f GetPosition(Vector2f pos)
{
return pos.Set(GetX(), GetY());
}
public AABB SetPosition(XY pos)
{
if (pos == null)
{
return this;
}
SetPosition(pos.GetX(), pos.GetY());
return this;
}
public AABB SetPosition(float x, float y)
{
SetX(x);
SetY(y);
return this;
}
public AABB SetSize(float width, float height)
{
SetWidth(width);
SetHeight(height);
return this;
}
public float GetAspectRatio()
{
return (GetHeight() == 0) ? MathUtils.NaN : GetWidth() / GetHeight();
}
public Vector2f GetCenter(Vector2f pos)
{
pos.x = GetX() + GetWidth() / 2f;
pos.y = GetY() + GetHeight() / 2;
return pos;
}
public AABB SetCenter(float x, float y)
{
SetPosition(x - GetWidth() / 2, y - GetHeight() / 2);
return this;
}
public AABB SetCenter(XY pos)
{
SetPosition(pos.GetX() - GetWidth() / 2, pos.GetY() - GetHeight() / 2);
return this;
}
public AABB FitOutside(AABB rect)
{
float ratio = GetAspectRatio();
if (ratio > rect.GetAspectRatio())
{
SetSize(rect.GetHeight() * ratio, rect.GetHeight());
}
else
{
SetSize(rect.GetWidth(), rect.GetWidth() / ratio);
}
SetPosition((rect.GetX() + rect.GetWidth() / 2) - GetWidth() / 2,
(rect.GetY() + rect.GetHeight() / 2) - GetHeight() / 2);
return this;
}
public AABB FitInside(AABB rect)
{
float ratio = GetAspectRatio();
if (ratio < rect.GetAspectRatio())
{
SetSize(rect.GetHeight() * ratio, rect.GetHeight());
}
else
{
SetSize(rect.GetWidth(), rect.GetWidth() / ratio);
}
SetPosition((rect.GetX() + rect.GetWidth() / 2) - GetWidth() / 2,
(rect.GetY() + rect.GetHeight() / 2) - GetHeight() / 2);
return this;
}
public void SetX(float x)
{
this.minX = x;
}
public void SetY(float y)
{
this.minY = y;
}
public void SetWidth(float w)
{
this.maxX = w;
}
public void SetHeight(float h)
{
this.maxY = h;
}
public float GetX()
{
return minX;
}
public float GetY()
{
return minY;
}
/*
public bool contains(Circle circle)
{
float xmin = circle.x - circle.GetRadius();
float xmax = xmin + 2f * circle.GetRadius();
float ymin = circle.y - circle.GetRadius();
float ymax = ymin + 2f * circle.GetRadius();
return ((xmin > minX && xmin < minX + maxX) && (xmax > minX && xmax < minX + maxX))
&& ((ymin > minY && ymin < minY + maxY) && (ymax > minY && ymax < minY + maxY));
}
*/
public bool IsEmpty()
{
return this.maxX <= 0 && this.maxY <= 0;
}
public AABB Random()
{
this.minX = MathUtils.Random(0f, LSystem.viewSize.GetWidth());
this.minY = MathUtils.Random(0f, LSystem.viewSize.GetHeight());
this.maxX = MathUtils.Random(0f, LSystem.viewSize.GetWidth());
this.maxY = MathUtils.Random(0f, LSystem.viewSize.GetHeight());
return this;
}
public float GetCenterX()
{
return this.minX + this.maxX / 2f;
}
public float GetCenterY()
{
return this.minY + this.maxY / 2f;
}
public RectBox ToRectBox()
{
return new RectBox(this.minX, this.minY, this.maxX, this.maxY);
}
public override int GetHashCode()
{
uint prime = 31;
uint result = 1;
result = prime * result + NumberUtils.FloatToIntBits(minX);
result = prime * result + NumberUtils.FloatToIntBits(minY);
result = prime * result + NumberUtils.FloatToIntBits(maxX);
result = prime * result + NumberUtils.FloatToIntBits(maxY);
return (int)result;
}
public override string ToString()
{
StringKeyValue builder = new StringKeyValue("AABB");
builder.Kv("minX", minX).Comma().Kv("minY", minY).Comma().Kv("maxX", maxX).Comma().Kv("maxY", maxY);
return builder.ToString();
}
}
}
| cping/LGame | C#/Loon2MonoGame/LoonMonoGame-Lib/loon/geom/AABB.cs | C# | apache-2.0 | 6,235 |
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
namespace FineUI.Examples.grid
{
public partial class grid_rownumber_align : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
#region BindGrid
private void BindGrid()
{
int recordCount = 999;
// 1.设置总项数(特别注意:数据库分页一定要设置总记录数RecordCount)
Grid1.RecordCount = recordCount;
// 2.获取当前分页数据
DataTable table = GetPagedDataTable(Grid1.PageIndex, Grid1.PageSize, recordCount);
// 3.绑定到Grid
Grid1.DataSource = table;
Grid1.DataBind();
}
/// <summary>
/// 模拟数据库分页
/// </summary>
/// <returns></returns>
private DataTable GetPagedDataTable(int pageIndex, int pageSize, int recordCount)
{
DataTable table = new DataTable();
table.Columns.Add(new DataColumn("Id", typeof(int)));
table.Columns.Add(new DataColumn("EntranceTime", typeof(DateTime)));
DataRow row = null;
for (int i = pageIndex * pageSize, count = Math.Min(recordCount, pageIndex * pageSize + pageSize); i < count; i++)
{
row = table.NewRow();
row[0] = 1000 + i;
row[1] = DateTime.Now.AddSeconds(i);
table.Rows.Add(row);
}
return table;
}
#endregion
#region Events
protected void Button1_Click(object sender, EventArgs e)
{
labResult.Text = HowManyRowsAreSelected(Grid1, true);
}
protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
{
//Grid1.PageIndex = e.NewPageIndex;
BindGrid();
}
#endregion
}
}
| u0hz/FineUI | src/FineUI.Examples/grid/grid_rownumber_align.aspx.cs | C# | apache-2.0 | 2,206 |
# Korovinia ferganensis Korovin SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Galagania/Galagania ferganensis/ Syn. Korovinia ferganensis/README.md | Markdown | apache-2.0 | 186 |
package com.joypupil.study.tools.验证码生成;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 生成验证码图片
*/
public class MakeCertPic {
// 验证码图片中可以出现的字符集,可根据需要修改
private char mapTable[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
/**
* 功能:生成彩色验证码图片 参数width为生成图片的宽度,参数height为生成图片的高度,参数os为页面的输出流
*/
public String getCertPic(int width, int height, OutputStream os) {
if (width <= 0)
width = 60;
if (height <= 0)
height = 20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 设定背景色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
// 画边框
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// 取随机产生的认证码
String strEnsure = "";
// 4代表4位验证码,如果要生成更多位的认证码,则加大数值
for (int i = 0; i < 4; ++i) {
strEnsure += mapTable[(int) (mapTable.length * Math.random())];
}
// 将认证码显示到图像中,如果要生成更多位的认证码,增加drawString语句
g.setColor(Color.black);
g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18));
String str = strEnsure.substring(0, 1);
g.drawString(str, 8, 17);
str = strEnsure.substring(1, 2);
g.drawString(str, 20, 15);
str = strEnsure.substring(2, 3);
g.drawString(str, 35, 18);
str = strEnsure.substring(3, 4);
g.drawString(str, 45, 15);
// 随机产生10个干扰点
Random rand = new Random();
for (int i = 0; i < 20; i++) {
int x = rand.nextInt(width);
int y = rand.nextInt(height);
g.drawOval(x, y, 1, 1);
}
// 释放图形上下文
g.dispose();
try {
// File file = new File("D://a.JPEG");
// ImageIO.write(image, "JPEG", file);
// 输出图像到页面
ImageIO.write(image, "JPEG", os);
} catch (IOException e) {
return "";
}
return strEnsure;
}
} | joypupil/study | study/src/main/java/com/joypupil/study/tools/验证码生成/MakeCertPic.java | Java | apache-2.0 | 2,430 |
player_manager.AddValidModel( "PMC5_13", "models/player/PMC_5/PMC__13.mdl" ) list.Set( "PlayerOptionsModel", "PMC5_13", "models/player/PMC_5/PMC__13.mdl" ) | FluffyGods/IBG-Afghan-War-TDM-Content | IBG Afghan War TDM Content/lua/autorun/pmc5_pmc__13.lua | Lua | apache-2.0 | 197 |
/**
* Copyright 2016 Milinda Pathirage
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 org.pathirage.freshet.api.data;
import java.util.List;
public interface Type {
enum TypeName {
INTEGER,
LONG,
FLOAT,
DOUBLE,
BOOL,
STRING,
BYTE,
BYTES,
STRUCT,
ARRAY,
MAP
}
boolean isStruct();
Type getKeyType();
Type getValueType();
Type getElementType();
TypeName getType();
List<String> getFieldNames();
int getFieldCount();
List<Field> getFields();
Field getField(String fieldName, boolean caseSensitive);
Value build(Object o);
}
| milinda/Freshet | freshet-core/src/main/java/org/pathirage/freshet/api/data/Type.java | Java | apache-2.0 | 1,123 |
from .test_antivirus import AbstractTests
import modules.antivirus.avg.avg as module
import modules.antivirus.base as base
from mock import patch
from pathlib import Path
class TestAvg(AbstractTests.TestAntivirus):
name = "AVG AntiVirus Free (Linux)"
scan_path = Path("/usr/bin/avgscan")
scan_args = ('--heur', '--paranoid', '--arc', '--macrow', '--pwdw',
'--pup')
module = module.AVGAntiVirusFree
scan_clean_stdout = """AVG command line Anti-Virus scanner
Copyright (c) 2013 AVG Technologies CZ
Virus database version: 4793/15678
Virus database release date: Mon, 21 May 2018 13:00:00 +0000
Files scanned : 1(1)
Infections found : 0(0)
PUPs found : 0
Files healed : 0
Warnings reported : 0
Errors reported : 0
"""
scan_virus_retcode = 4
virusname = "EICAR_Test"
scan_virus_stdout = """AVG command line Anti-Virus scanner
Copyright (c) 2013 AVG Technologies CZ
Virus database version: 4793/15678
Virus database release date: Mon, 21 May 2018 13:00:00 +0000
eicar.com.txt Virus identified EICAR_Test
Files scanned : 1(1)
Infections found : 1(1)
PUPs found : 0
Files healed : 0
Warnings reported : 0
Errors reported : 0
"""
version = "13.0.3118"
virus_database_version = "4793/15678 (21 May 2018)"
version_stdout = """AVG command line controller
Copyright (c) 2013 AVG Technologies CZ
------ AVG status ------
AVG version : 13.0.3118
Components version : Aspam:3111, Cfg:3109, Cli:3115, Common:3110, Core:4793, Doc:3115, Ems:3111, Initd:3113, Lng:3112, Oad:3118, Other:3109, Scan:3115, Sched:3110, Update:3109
Last update : Tue, 22 May 2018 07:52:31 +0000
------ License status ------
License number : LUOTY-674PL-VRWOV-APYEG-ZXHMA-E
License version : 10
License type : FREE
License expires on :
Registered user :
Registered company :
------ WD status ------
Component State Restarts UpTime
Avid running 0 13 minute(s)
Oad running 0 13 minute(s)
Sched running 0 13 minute(s)
Tcpd running 0 13 minute(s)
Update stopped 0 -
------ Sched status ------
Task name Next runtime Last runtime
Virus update Tue, 22 May 2018 18:04:00 +0000 Tue, 22 May 2018 07:46:29 +0000
Program update - -
User counting Wed, 23 May 2018 07:46:29 +0000 Tue, 22 May 2018 07:46:29 +0000
------ Tcpd status ------
E-mails checked : 0
SPAM messages : 0
Phishing messages : 0
E-mails infected : 0
E-mails dropped : 0
------ Avid status ------
Virus database reload times : 0
Virus database version : 4793/15678
Virus database release date : Mon, 21 May 2018 13:00:00 +0000
Virus database shared in memory : yes
------ Oad status ------
Files scanned : 0(0)
Infections found : 0(0)
PUPs found : 0
Files healed : 0
Warnings reported : 0
Errors reported : 0
Operation successful.
""" # nopep8
@patch.object(base.AntivirusUnix, "locate")
@patch.object(base.AntivirusUnix, "locate_one")
@patch.object(base.AntivirusUnix, "run_cmd")
def setUp(self, m_run_cmd, m_locate_one, m_locate):
m_run_cmd.return_value = 0, self.version_stdout, ""
m_locate_one.return_value = self.scan_path
m_locate.return_value = self.database
super().setUp()
@patch.object(module, "locate_one")
@patch.object(base.AntivirusUnix, "run_cmd")
def test_get_virus_db_error(self, m_run_cmd, m_locate_one):
m_locate_one.return_value = self.scan_path
m_run_cmd.return_value = -1, self.version_stdout, ""
with self.assertRaises(RuntimeError):
self.plugin.get_virus_database_version()
@patch.object(module, "locate_one")
@patch.object(base.AntivirusUnix, "run_cmd")
def test_get_virus_db_no_version(self, m_run_cmd, m_locate_one):
m_locate_one.return_value = self.scan_path
wrong_stdout = "LOREM IPSUM"
m_run_cmd.return_value = 0, wrong_stdout, ""
with self.assertRaises(RuntimeError):
self.plugin.get_virus_database_version()
@patch.object(module, "locate_one")
@patch.object(base.AntivirusUnix, "run_cmd")
def test_get_virus_db_no_release(self, m_run_cmd, m_locate_one):
m_locate_one.return_value = self.scan_path
wrong_stdout = "Virus database version : 4793/15678"
m_run_cmd.return_value = 0, wrong_stdout, ""
version = self.plugin.get_virus_database_version()
self.assertEquals(version, "4793/15678")
| quarkslab/irma | probe/tests/modules/antivirus/test_avg.py | Python | apache-2.0 | 4,618 |
'use strict';
describe('Service: solvice', function () {
// load the service's module
beforeEach(module('vcPlannerApp'));
// instantiate service
var solvice;
beforeEach(inject(function (_solvice_) {
solvice = _solvice_;
}));
it('should do something', function () {
expect(!!solvice).toBe(true);
});
});
| truemath/vc-planner | test/spec/services/solvice.js | JavaScript | apache-2.0 | 332 |
import {action} from "mobx";
import MainStore from "../common/MainStore";
import ToastStore from "../toast/ToastStore";
import commonActions from "../common/commonActions";
import "whatwg-fetch";
// TODO: ES2015
module.exports = {
saveDownloadList: action(saveDownloadList),
hideDownloadCard: action(hideDownloadCard)
};
function saveDownloadList(title, id) {
if (commonActions.isInvalidTitle(title) ||
commonActions.isDuplicateTitle(title) ||
commonActions.isInvalidId(id)) {
return;
}
fetch("https://spoilerblocker.herokuapp.com/downloadList?id=" + id, {
method: "get",
credentials: "include"
}).then(function(response) {
return response.json();
}).then(function(data) {
if (data.Status !== "Success") {
ToastStore.isMissingList = true;
return;
}
const tagArr = commonActions.tagStringToArray(data.list.tags);
if (commonActions.isInvalidTags(tagArr)) {
// Ideally should never happen, as tags on website should be valid
return;
}
commonActions.addNewList(title, tagArr);
hideDownloadCard();
});
}
function hideDownloadCard() {
MainStore.isDownloadCardVisible = false;
}
| kabir-plod/spoiler-blocker | src/panel/download_card/downloadActions.js | JavaScript | apache-2.0 | 1,173 |
//--------------------------------------------------------------------------
// <copyright file="IRasHelper.cs" company="Jeff Winn">
// Copyright (c) Jeff Winn. All rights reserved.
//
// The use and distribution terms for this software is covered by the
// GNU Library General Public License (LGPL) v2.1 which can be found
// in the License.rtf at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by
// the terms of this license.
//
// You must not remove this notice, or any other, from this software.
// </copyright>
//--------------------------------------------------------------------------
namespace DotRas.Internal
{
using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows.Forms;
/// <summary>
/// Defines the members for the remote access service (RAS) helper.
/// </summary>
internal interface IRasHelper
{
#region Methods
/// <summary>
/// Generates a new locally unique identifier.
/// </summary>
/// <returns>A new <see cref="DotRas.Luid"/> structure.</returns>
Luid AllocateLocallyUniqueId();
/// <summary>
/// Establishes a remote access connection between a client and a server.
/// </summary>
/// <param name="phoneBookPath">The full path (including filename) of a phone book. If this parameter is a null reference (<b>Nothing</b> in Visual Basic), the default phone book is used.</param>
/// <param name="parameters">A <see cref="NativeMethods.RASDIALPARAMS"/> structure containing calling parameters for the connection.</param>
/// <param name="extensions">A <see cref="NativeMethods.RASDIALEXTENSIONS"/> structure containing extended feature information.</param>
/// <param name="callback">A <see cref="NativeMethods.RasDialFunc2"/> delegate to notify during the connection process.</param>
/// <param name="eapOptions">Specifies options to use during authentication.</param>
/// <returns>The handle of the connection.</returns>
RasHandle Dial(string phoneBookPath, NativeMethods.RASDIALPARAMS parameters, NativeMethods.RASDIALEXTENSIONS extensions, NativeMethods.RasDialFunc2 callback, NativeMethods.RASEAPF eapOptions);
/// <summary>
/// Indicates the current AutoDial status for a specific TAPI dialing location.
/// </summary>
/// <param name="dialingLocation">The dialing location whose status to check.</param>
/// <returns><b>true</b> if the AutoDial feature is currently enabled for the dialing location, otherwise <b>false</b>.</returns>
bool GetAutoDialEnable(int dialingLocation);
/// <summary>
/// Retrieves the value of an AutoDial parameter.
/// </summary>
/// <param name="parameter">The parameter whose value to retrieve.</param>
/// <returns>The value of the parameter.</returns>
int GetAutoDialParameter(NativeMethods.RASADP parameter);
/// <summary>
/// Clears any accumulated statistics for the specified remote access connection.
/// </summary>
/// <param name="handle">The handle to the connection.</param>
/// <returns><b>true</b> if the function succeeds, otherwise <b>false</b>.</returns>
bool ClearConnectionStatistics(RasHandle handle);
/// <summary>
/// Clears any accumulated statistics for the specified link in a remote access multilink connection.
/// </summary>
/// <param name="handle">The handle to the connection.</param>
/// <param name="subEntryId">The subentry index that corresponds to the link for which to clear statistics.</param>
/// <returns><b>true</b> if the function succeeds, otherwise <b>false</b>.</returns>
bool ClearLinkStatistics(RasHandle handle, int subEntryId);
/// <summary>
/// Deletes an entry from a phone book.
/// </summary>
/// <param name="phoneBookPath">Required. The full path (including file name) of the phone book.</param>
/// <param name="entryName">Required. The name of the entry to delete.</param>
/// <returns><b>true</b> if the entry was deleted, otherwise <b>false</b>.</returns>
bool DeleteEntry(string phoneBookPath, string entryName);
#if (WINXP || WIN2K8 || WIN7 || WIN8)
/// <summary>
/// Deletes a subentry from the specified phone book entry.
/// </summary>
/// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> containing the entry.</param>
/// <param name="entry">Required. The <see cref="DotRas.RasEntry"/> containing the subentry to be deleted.</param>
/// <param name="subEntryId">The one-based index of the subentry to delete.</param>
/// <returns><b>true</b> if the function succeeds, otherwise <b>false</b>.</returns>
bool DeleteSubEntry(RasPhoneBook phoneBook, RasEntry entry, int subEntryId);
#endif
/// <summary>
/// Retrieves a read-only list of active connections.
/// </summary>
/// <returns>A new read-only collection of <see cref="DotRas.RasConnection"/> objects, or an empty collection if no active connections were found.</returns>
ReadOnlyCollection<RasConnection> GetActiveConnections();
/// <summary>
/// Retrieves information about the entries associated with a network address in the AutoDial mapping database.
/// </summary>
/// <param name="address">The address to retrieve.</param>
/// <returns>A new <see cref="DotRas.RasAutoDialAddress"/> object.</returns>
RasAutoDialAddress GetAutoDialAddress(string address);
/// <summary>
/// Retrieves a collection of addresses in the AutoDial mapping database.
/// </summary>
/// <returns>A new collection of <see cref="DotRas.RasAutoDialAddress"/> objects, or an empty collection if no addresses were found.</returns>
Collection<string> GetAutoDialAddresses();
/// <summary>
/// Retrieves the connection status for the handle specified.
/// </summary>
/// <param name="handle">The remote access connection handle to retrieve.</param>
/// <returns>A <see cref="DotRas.RasConnectionStatus"/> object containing connection status information.</returns>
RasConnectionStatus GetConnectionStatus(RasHandle handle);
/// <summary>
/// Retrieves user credentials associated with a specified remote access phone book entry.
/// </summary>
/// <param name="phoneBookPath">Required. The full path (including filename) of the phone book containing the entry.</param>
/// <param name="entryName">Required. The name of the entry whose credentials to retrieve.</param>
/// <param name="options">The options to request.</param>
/// <returns>The credentials stored in the entry, otherwise a null reference (<b>Nothing</b> in Visual Basic) if the credentials did not exist.</returns>
NetworkCredential GetCredentials(string phoneBookPath, string entryName, NativeMethods.RASCM options);
/// <summary>
/// Retrieves connection specific authentication information.
/// </summary>
/// <param name="phoneBookPath">Required. The full path (including filename) of the phone book containing the entry.</param>
/// <param name="entryName">Required. The name of the entry whose credentials to retrieve.</param>
/// <returns>A byte array containing the authentication information, otherwise a null reference (<b>Nothing</b> in Visual Basic).</returns>
byte[] GetCustomAuthData(string phoneBookPath, string entryName);
/// <summary>
/// Lists all available remote access capable devices.
/// </summary>
/// <returns>A new collection of <see cref="DotRas.RasDevice"/> objects.</returns>
ReadOnlyCollection<RasDevice> GetDevices();
/// <summary>
/// Retrieves user-specific Extensible Authentication Protocol (EAP) information for the specified phone book entry.
/// </summary>
/// <param name="userToken">The handle of a Windows account token. This token is usually retrieved through a call to unmanaged code, such as a call to the Win32 API LogonUser function.</param>
/// <param name="phoneBookPath">The full path and filename of a phone book file. If this parameter is a null reference (<b>Nothing</b> in Visual Basic), the default phone book is used.</param>
/// <param name="entryName">The entry name to validate.</param>
/// <returns>A byte array containing the EAP data, otherwise a null reference (<b>Nothing</b> in Visual Basic).</returns>
byte[] GetEapUserData(IntPtr userToken, string phoneBookPath, string entryName);
/// <summary>
/// Retrieves the entry properties for an entry within a phone book.
/// </summary>
/// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> containing the entry.</param>
/// <param name="entryName">Required. The name of an entry to retrieve.</param>
/// <returns>A <see cref="DotRas.RasEntry"/> object.</returns>
RasEntry GetEntryProperties(RasPhoneBook phoneBook, string entryName);
/// <summary>
/// Retrieves a connection handle for a subentry of a multilink connection.
/// </summary>
/// <param name="handle">The handle of the connection.</param>
/// <param name="subEntryId">The one-based index of the subentry to whose handle to retrieve.</param>
/// <returns>The handle of the subentry if available, otherwise a null reference (<b>Nothing</b> in Visual Basic).</returns>
RasHandle GetSubEntryHandle(RasHandle handle, int subEntryId);
/// <summary>
/// Retrieves the subentry properties for an entry within a phone book.
/// </summary>
/// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> containing the entry.</param>
/// <param name="entry">Required. The <see cref="DotRas.RasEntry"/> containing the subentry.</param>
/// <param name="subEntryId">The zero-based index of the subentry to retrieve.</param>
/// <returns>A new <see cref="DotRas.RasSubEntry"/> object.</returns>
RasSubEntry GetSubEntryProperties(RasPhoneBook phoneBook, RasEntry entry, int subEntryId);
/// <summary>
/// Retrieves a list of entry names within a phone book.
/// </summary>
/// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> whose entry names to retrieve.</param>
/// <returns>An array of <see cref="NativeMethods.RASENTRYNAME"/> structures, or a null reference if the phone-book was not found.</returns>
NativeMethods.RASENTRYNAME[] GetEntryNames(RasPhoneBook phoneBook);
/// <summary>
/// Retrieves accumulated statistics for the specified connection.
/// </summary>
/// <param name="handle">The handle to the connection.</param>
/// <returns>A <see cref="DotRas.RasLinkStatistics"/> structure containing connection statistics.</returns>
RasLinkStatistics GetConnectionStatistics(RasHandle handle);
/// <summary>
/// Retrieves country/region specific dialing information from the Windows Telephony list of countries/regions for a specific country id.
/// </summary>
/// <param name="countryId">The country id to retrieve.</param>
/// <param name="nextCountryId">Upon output, contains the next country id from the list; otherwise zero for the last country/region in the list.</param>
/// <returns>A new <see cref="DotRas.RasCountry"/> object.</returns>
RasCountry GetCountry(int countryId, out int nextCountryId);
/// <summary>
/// Retrieves accumulated statistics for the specified link in a RAS multilink connection.
/// </summary>
/// <param name="handle">The handle to the connection.</param>
/// <param name="subEntryId">The one-based index that corresponds to the link for which to retrieve statistics.</param>
/// <returns>A <see cref="DotRas.RasLinkStatistics"/> structure containing connection statistics.</returns>
RasLinkStatistics GetLinkStatistics(RasHandle handle, int subEntryId);
/// <summary>
/// Terminates a remote access connection.
/// </summary>
/// <param name="handle">The remote access connection handle to terminate.</param>
/// <param name="pollingInterval">The length of time, in milliseconds, the thread must be paused while polling whether the connection has terminated.</param>
/// <param name="closeAllReferences"><b>true</b> to disconnect all connection references, otherwise <b>false</b>.</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="pollingInterval"/> must be greater than or equal to zero.</exception>
/// <exception cref="DotRas.InvalidHandleException"><paramref name="handle"/> is not a valid handle.</exception>
void HangUp(RasHandle handle, int pollingInterval, bool closeAllReferences);
/// <summary>
/// Indicates whether a connection is currently active.
/// </summary>
/// <param name="handle">The handle to check.</param>
/// <returns><b>true</b> if the connection is active, otherwise <b>false</b>.</returns>
bool IsConnectionActive(RasHandle handle);
/// <summary>
/// Frees the memory buffer of an EAP user identity.
/// </summary>
/// <param name="rasEapUserIdentity">The <see cref="NativeMethods.RASEAPUSERIDENTITY"/> structure to free.</param>
void FreeEapUserIdentity(NativeMethods.RASEAPUSERIDENTITY rasEapUserIdentity);
/// <summary>
/// Retrieves any Extensible Authentication Protocol (EAP) user identity information if available.
/// </summary>
/// <param name="phoneBookPath">The full path (including filename) of a phone book. If this parameter is a null reference (<b>Nothing</b> in Visual Basic), the default phone book is used.</param>
/// <param name="entryName">Required. The name of the entry in the phone book being connected.</param>
/// <param name="eapOptions">Specifies options to use during authentication.</param>
/// <param name="owner">The parent window for the UI dialog (if needed).</param>
/// <param name="identity">Upon return, contains the Extensible Authentication Protocol (EAP) user identity information.</param>
/// <returns><b>true</b> if the user identity information was returned, otherwise <b>false</b>.</returns>
bool TryGetEapUserIdentity(string phoneBookPath, string entryName, NativeMethods.RASEAPF eapOptions, IWin32Window owner, out NativeMethods.RASEAPUSERIDENTITY identity);
#if (WIN2K8 || WIN7 || WIN8)
/// <summary>
/// Retrieves the network access protection (NAP) status for a remote access connection.
/// </summary>
/// <param name="handle">The handle of the connection.</param>
/// <returns>A <see cref="DotRas.RasNapStatus"/> object containing the NAP status.</returns>
RasNapStatus GetNapStatus(RasHandle handle);
#endif
/// <summary>
/// Retrieves information about a remote access projection operation for a connection.
/// </summary>
/// <param name="handle">The handle of the connection.</param>
/// <param name="projection">The protocol of interest.</param>
/// <returns>The resulting projection information, otherwise null reference (<b>Nothing</b> in Visual Basic) if the protocol was not found.</returns>
object GetProjectionInfo(RasHandle handle, NativeMethods.RASPROJECTION projection);
#if (WIN7 || WIN8)
/// <summary>
/// Retrieves extended information about a remote access projection operation for a connection.
/// </summary>
/// <param name="handle">The handle of the connection.</param>
/// <returns>The resulting projection information, otherwise null reference (<b>Nothing</b> in Visual Basic) if the protocol was not found.</returns>
object GetProjectionInfoEx(RasHandle handle);
#endif
/// <summary>
/// Retrieves an error message for a specified RAS error code.
/// </summary>
/// <param name="errorCode">The error code to retrieve.</param>
/// <returns>An <see cref="System.String"/> with the error message, otherwise a null reference (<b>Nothing</b> in Visual Basic) if the error code was not found.</returns>
string GetRasErrorString(int errorCode);
/// <summary>
/// Indicates whether the entry name is valid for the phone book specified.
/// </summary>
/// <param name="phoneBook">Required. An <see cref="DotRas.RasPhoneBook"/> to validate the name against.</param>
/// <param name="entryName">Required. The name of an entry to check.</param>
/// <returns><b>true</b> if the entry name is valid, otherwise <b>false</b>.</returns>
bool IsValidEntryName(RasPhoneBook phoneBook, string entryName);
/// <summary>
/// Indicates whether the entry name is valid for the phone book specified.
/// </summary>
/// <param name="phoneBook">Required. An <see cref="DotRas.RasPhoneBook"/> to validate the name against.</param>
/// <param name="entryName">Required. The name of an entry to check.</param>
/// <param name="acceptableResults">Any additional results that are considered acceptable results from the call.</param>
/// <returns><b>true</b> if the entry name is valid, otherwise <b>false</b>.</returns>
bool IsValidEntryName(RasPhoneBook phoneBook, string entryName, params int[] acceptableResults);
/// <summary>
/// Renames an existing entry in a phone book.
/// </summary>
/// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> containing the entry to be renamed.</param>
/// <param name="entryName">Required. The name of an entry to rename.</param>
/// <param name="newEntryName">Required. The new name of the entry.</param>
/// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns>
bool RenameEntry(RasPhoneBook phoneBook, string entryName, string newEntryName);
/// <summary>
/// Updates an address in the AutoDial mapping database.
/// </summary>
/// <param name="address">The address to update.</param>
/// <param name="entries">A collection of <see cref="DotRas.RasAutoDialEntry"/> objects containing the entries for the <paramref name="address"/> specified.</param>
/// <returns><b>true</b> if the update was successful, otherwise <b>false</b>.</returns>
bool SetAutoDialAddress(string address, Collection<RasAutoDialEntry> entries);
/// <summary>
/// Enables or disables the AutoDial feature for a specific TAPI dialing location.
/// </summary>
/// <param name="dialingLocation">The TAPI dialing location to update.</param>
/// <param name="enabled"><b>true</b> to enable the AutoDial feature, otherwise <b>false</b> to disable it.</param>
/// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns>
bool SetAutoDialEnable(int dialingLocation, bool enabled);
/// <summary>
/// Sets the value of an AutoDial parameter.
/// </summary>
/// <param name="parameter">The parameter whose value to set.</param>
/// <param name="value">The new value of the parameter.</param>
void SetAutoDialParameter(NativeMethods.RASADP parameter, int value);
/// <summary>
/// Sets the custom authentication data.
/// </summary>
/// <param name="phoneBookPath">The full path and filename of a phone book file. If this parameter is a null reference (<b>Nothing</b> in Visual Basic), the default phone book is used.</param>
/// <param name="entryName">The entry name to validate.</param>
/// <param name="data">A byte array containing the custom authentication data.</param>
/// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns>
bool SetCustomAuthData(string phoneBookPath, string entryName, byte[] data);
/// <summary>
/// Store user-specific Extensible Authentication Protocol (EAP) information for the specified phone book entry in the registry.
/// </summary>
/// <param name="handle">The handle to a primary or impersonation access token.</param>
/// <param name="phoneBookPath">The full path and filename of a phone book file. If this parameter is a null reference (<b>Nothing</b> in Visual Basic), the default phone book is used.</param>
/// <param name="entryName">The entry name to validate.</param>
/// <param name="data">A byte array containing the EAP data.</param>
/// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns>
bool SetEapUserData(IntPtr handle, string phoneBookPath, string entryName, byte[] data);
/// <summary>
/// Sets the entry properties for an existing phone book entry, or creates a new entry.
/// </summary>
/// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> that will contain the entry.</param>
/// <param name="value">An <see cref="DotRas.RasEntry"/> object whose properties to set.</param>
/// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns>
bool SetEntryProperties(RasPhoneBook phoneBook, RasEntry value);
/// <summary>
/// Sets the subentry properties for an existing subentry, or creates a new subentry.
/// </summary>
/// <param name="phoneBook">Required. The <see cref="DotRas.RasPhoneBook"/> that will contain the entry.</param>
/// <param name="entry">Required. The <see cref="DotRas.RasEntry"/> whose subentry to set.</param>
/// <param name="subEntryId">The zero-based index of the subentry to set.</param>
/// <param name="value">An <see cref="DotRas.RasSubEntry"/> object whose properties to set.</param>
/// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns>
bool SetSubEntryProperties(RasPhoneBook phoneBook, RasEntry entry, int subEntryId, RasSubEntry value);
/// <summary>
/// Sets the user credentials for a phone book entry.
/// </summary>
/// <param name="phoneBookPath">The full path (including filename) of a phone book. If this parameter is a null reference (<b>Nothing</b> in Visual Basic), the default phone book is used.</param>
/// <param name="entryName">The name of the entry whose credentials to set.</param>
/// <param name="credentials">An <see cref="NativeMethods.RASCREDENTIALS"/> object containing user credentials.</param>
/// <param name="clearCredentials"><b>true</b> clears existing credentials by setting them to an empty string, otherwise <b>false</b>.</param>
/// <returns><b>true</b> if the operation was successful, otherwise <b>false</b>.</returns>
bool SetCredentials(string phoneBookPath, string entryName, NativeMethods.RASCREDENTIALS credentials, bool clearCredentials);
#if (WIN7 || WIN8)
/// <summary>
/// Updates the tunnel endpoints of an Internet Key Exchange (IKEv2) connection.
/// </summary>
/// <param name="handle">The handle of the connection.</param>
/// <param name="interfaceIndex">The new interface index of the endpoint.</param>
/// <param name="localEndPoint">The new local client endpoint of the connection.</param>
/// <param name="remoteEndPoint">The new remote server endpoint of the connection.</param>
void UpdateConnection(RasHandle handle, int interfaceIndex, IPAddress localEndPoint, IPAddress remoteEndPoint);
#endif
#endregion
}
} | kangwl/xk | DotRas/Internal/IRasHelper.cs | C# | apache-2.0 | 24,454 |
/*
* Copyright (C) 2011 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.inputmethod.latin.spellcheck;
import android.content.Intent;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Log;
import com.android.inputmethod.compat.ArraysCompatUtils;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.BinaryDictionary;
import com.android.inputmethod.latin.Dictionary;
import com.android.inputmethod.latin.Dictionary.DataType;
import com.android.inputmethod.latin.Dictionary.WordCallback;
import com.android.inputmethod.latin.DictionaryCollection;
import com.android.inputmethod.latin.DictionaryFactory;
import com.android.inputmethod.latin.Flag;
import com.android.inputmethod.latin.LocaleUtils;
import com.android.inputmethod.latin.SynchronouslyLoadedContactsDictionary;
import com.android.inputmethod.latin.SynchronouslyLoadedUserDictionary;
import com.android.inputmethod.latin.Utils;
import com.android.inputmethod.latin.WhitelistDictionary;
import com.android.inputmethod.latin.WordComposer;
import com.android.s16.inputmethod.R;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
/**
* Service for spell checking, using LatinIME's dictionaries and mechanisms.
*/
public class AndroidSpellCheckerService extends SpellCheckerService {
private static final String TAG = AndroidSpellCheckerService.class.getSimpleName();
private static final boolean DBG = false;
private static final int POOL_SIZE = 2;
private static final int CAPITALIZE_NONE = 0; // No caps, or mixed case
private static final int CAPITALIZE_FIRST = 1; // First only
private static final int CAPITALIZE_ALL = 2; // All caps
private final static String[] EMPTY_STRING_ARRAY = new String[0];
private final static Flag[] USE_FULL_EDIT_DISTANCE_FLAG_ARRAY;
static {
// See BinaryDictionary.java for an explanation of these flags
// Specifially, ALL_CONFIG_FLAGS means that we want to consider all flags with the
// current dictionary configuration - for example, consider the UMLAUT flag
// so that it will be turned on for German dictionaries and off for others.
USE_FULL_EDIT_DISTANCE_FLAG_ARRAY = Arrays.copyOf(BinaryDictionary.ALL_CONFIG_FLAGS,
BinaryDictionary.ALL_CONFIG_FLAGS.length + 1);
USE_FULL_EDIT_DISTANCE_FLAG_ARRAY[BinaryDictionary.ALL_CONFIG_FLAGS.length] =
BinaryDictionary.FLAG_USE_FULL_EDIT_DISTANCE;
}
private Map<String, DictionaryPool> mDictionaryPools =
Collections.synchronizedMap(new TreeMap<String, DictionaryPool>());
private Map<String, Dictionary> mUserDictionaries =
Collections.synchronizedMap(new TreeMap<String, Dictionary>());
private Map<String, Dictionary> mWhitelistDictionaries =
Collections.synchronizedMap(new TreeMap<String, Dictionary>());
private SynchronouslyLoadedContactsDictionary mContactsDictionary;
// The threshold for a candidate to be offered as a suggestion.
private double mSuggestionThreshold;
// The threshold for a suggestion to be considered "likely".
private double mLikelyThreshold;
@Override public void onCreate() {
super.onCreate();
mSuggestionThreshold =
Double.parseDouble(getString(R.string.spellchecker_suggestion_threshold_value));
mLikelyThreshold =
Double.parseDouble(getString(R.string.spellchecker_likely_threshold_value));
}
@Override
public Session createSession() {
return new AndroidSpellCheckerSession(this);
}
private static SuggestionsInfo getNotInDictEmptySuggestions() {
return new SuggestionsInfo(0, EMPTY_STRING_ARRAY);
}
private static SuggestionsInfo getInDictEmptySuggestions() {
return new SuggestionsInfo(SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY,
EMPTY_STRING_ARRAY);
}
private static class SuggestionsGatherer implements WordCallback {
public static class Result {
public final String[] mSuggestions;
public final boolean mHasLikelySuggestions;
public Result(final String[] gatheredSuggestions, final boolean hasLikelySuggestions) {
mSuggestions = gatheredSuggestions;
mHasLikelySuggestions = hasLikelySuggestions;
}
}
private final ArrayList<CharSequence> mSuggestions;
private final int[] mScores;
private final String mOriginalText;
private final double mSuggestionThreshold;
private final double mLikelyThreshold;
private final int mMaxLength;
private int mLength = 0;
// The two following attributes are only ever filled if the requested max length
// is 0 (or less, which is treated the same).
private String mBestSuggestion = null;
private int mBestScore = Integer.MIN_VALUE; // As small as possible
SuggestionsGatherer(final String originalText, final double suggestionThreshold,
final double likelyThreshold, final int maxLength) {
mOriginalText = originalText;
mSuggestionThreshold = suggestionThreshold;
mLikelyThreshold = likelyThreshold;
mMaxLength = maxLength;
mSuggestions = new ArrayList<CharSequence>(maxLength + 1);
mScores = new int[mMaxLength];
}
@Override
synchronized public boolean addWord(char[] word, int wordOffset, int wordLength, int score,
int dicTypeId, DataType dataType) {
final int positionIndex = ArraysCompatUtils.binarySearch(mScores, 0, mLength, score);
// binarySearch returns the index if the element exists, and -<insertion index> - 1
// if it doesn't. See documentation for binarySearch.
final int insertIndex = positionIndex >= 0 ? positionIndex : -positionIndex - 1;
if (insertIndex == 0 && mLength >= mMaxLength) {
// In the future, we may want to keep track of the best suggestion score even if
// we are asked for 0 suggestions. In this case, we can use the following
// (tested) code to keep it:
// If the maxLength is 0 (should never be less, but if it is, it's treated as 0)
// then we need to keep track of the best suggestion in mBestScore and
// mBestSuggestion. This is so that we know whether the best suggestion makes
// the score cutoff, since we need to know that to return a meaningful
// looksLikeTypo.
// if (0 >= mMaxLength) {
// if (score > mBestScore) {
// mBestScore = score;
// mBestSuggestion = new String(word, wordOffset, wordLength);
// }
// }
return true;
}
if (insertIndex >= mMaxLength) {
// We found a suggestion, but its score is too weak to be kept considering
// the suggestion limit.
return true;
}
// Compute the normalized score and skip this word if it's normalized score does not
// make the threshold.
final String wordString = new String(word, wordOffset, wordLength);
final double normalizedScore =
Utils.calcNormalizedScore(mOriginalText, wordString, score);
if (normalizedScore < mSuggestionThreshold) {
if (DBG) Log.i(TAG, wordString + " does not make the score threshold");
return true;
}
if (mLength < mMaxLength) {
final int copyLen = mLength - insertIndex;
++mLength;
System.arraycopy(mScores, insertIndex, mScores, insertIndex + 1, copyLen);
mSuggestions.add(insertIndex, wordString);
} else {
System.arraycopy(mScores, 1, mScores, 0, insertIndex);
mSuggestions.add(insertIndex, wordString);
mSuggestions.remove(0);
}
mScores[insertIndex] = score;
return true;
}
public Result getResults(final int capitalizeType, final Locale locale) {
final String[] gatheredSuggestions;
final boolean hasLikelySuggestions;
if (0 == mLength) {
// Either we found no suggestions, or we found some BUT the max length was 0.
// If we found some mBestSuggestion will not be null. If it is null, then
// we found none, regardless of the max length.
if (null == mBestSuggestion) {
gatheredSuggestions = null;
hasLikelySuggestions = false;
} else {
gatheredSuggestions = EMPTY_STRING_ARRAY;
final double normalizedScore =
Utils.calcNormalizedScore(mOriginalText, mBestSuggestion, mBestScore);
hasLikelySuggestions = (normalizedScore > mLikelyThreshold);
}
} else {
if (DBG) {
if (mLength != mSuggestions.size()) {
Log.e(TAG, "Suggestion size is not the same as stored mLength");
}
for (int i = mLength - 1; i >= 0; --i) {
Log.i(TAG, "" + mScores[i] + " " + mSuggestions.get(i));
}
}
Collections.reverse(mSuggestions);
Utils.removeDupes(mSuggestions);
if (CAPITALIZE_ALL == capitalizeType) {
for (int i = 0; i < mSuggestions.size(); ++i) {
// get(i) returns a CharSequence which is actually a String so .toString()
// should return the same object.
mSuggestions.set(i, mSuggestions.get(i).toString().toUpperCase(locale));
}
} else if (CAPITALIZE_FIRST == capitalizeType) {
for (int i = 0; i < mSuggestions.size(); ++i) {
// Likewise
mSuggestions.set(i, Utils.toTitleCase(mSuggestions.get(i).toString(),
locale));
}
}
// This returns a String[], while toArray() returns an Object[] which cannot be cast
// into a String[].
gatheredSuggestions = mSuggestions.toArray(EMPTY_STRING_ARRAY);
final int bestScore = mScores[mLength - 1];
final CharSequence bestSuggestion = mSuggestions.get(0);
final double normalizedScore =
Utils.calcNormalizedScore(mOriginalText, bestSuggestion, bestScore);
hasLikelySuggestions = (normalizedScore > mLikelyThreshold);
if (DBG) {
Log.i(TAG, "Best suggestion : " + bestSuggestion + ", score " + bestScore);
Log.i(TAG, "Normalized score = " + normalizedScore
+ " (threshold " + mLikelyThreshold
+ ") => hasLikelySuggestions = " + hasLikelySuggestions);
}
}
return new Result(gatheredSuggestions, hasLikelySuggestions);
}
}
@Override
public boolean onUnbind(final Intent intent) {
final Map<String, DictionaryPool> oldPools = mDictionaryPools;
mDictionaryPools = Collections.synchronizedMap(new TreeMap<String, DictionaryPool>());
final Map<String, Dictionary> oldUserDictionaries = mUserDictionaries;
mUserDictionaries = Collections.synchronizedMap(new TreeMap<String, Dictionary>());
final Map<String, Dictionary> oldWhitelistDictionaries = mWhitelistDictionaries;
mWhitelistDictionaries = Collections.synchronizedMap(new TreeMap<String, Dictionary>());
for (DictionaryPool pool : oldPools.values()) {
pool.close();
}
for (Dictionary dict : oldUserDictionaries.values()) {
dict.close();
}
for (Dictionary dict : oldWhitelistDictionaries.values()) {
dict.close();
}
if (null != mContactsDictionary) {
// The synchronously loaded contacts dictionary should have been in one
// or several pools, but it is shielded against multiple closing and it's
// safe to call it several times.
final SynchronouslyLoadedContactsDictionary dictToClose = mContactsDictionary;
mContactsDictionary = null;
dictToClose.close();
}
return false;
}
private DictionaryPool getDictionaryPool(final String locale) {
DictionaryPool pool = mDictionaryPools.get(locale);
if (null == pool) {
final Locale localeObject = LocaleUtils.constructLocaleFromString(locale);
pool = new DictionaryPool(POOL_SIZE, this, localeObject);
mDictionaryPools.put(locale, pool);
}
return pool;
}
public DictAndProximity createDictAndProximity(final Locale locale) {
final ProximityInfo proximityInfo = ProximityInfo.createSpellCheckerProximityInfo();
final Resources resources = getResources();
final int fallbackResourceId = Utils.getMainDictionaryResourceId(resources);
final DictionaryCollection dictionaryCollection =
DictionaryFactory.createDictionaryFromManager(this, locale, fallbackResourceId,
USE_FULL_EDIT_DISTANCE_FLAG_ARRAY);
final String localeStr = locale.toString();
Dictionary userDictionary = mUserDictionaries.get(localeStr);
if (null == userDictionary) {
userDictionary = new SynchronouslyLoadedUserDictionary(this, localeStr, true);
mUserDictionaries.put(localeStr, userDictionary);
}
dictionaryCollection.addDictionary(userDictionary);
Dictionary whitelistDictionary = mWhitelistDictionaries.get(localeStr);
if (null == whitelistDictionary) {
whitelistDictionary = new WhitelistDictionary(this, locale);
mWhitelistDictionaries.put(localeStr, whitelistDictionary);
}
dictionaryCollection.addDictionary(whitelistDictionary);
if (null == mContactsDictionary) {
mContactsDictionary = new SynchronouslyLoadedContactsDictionary(this);
}
// TODO: add a setting to use or not contacts when checking spelling
dictionaryCollection.addDictionary(mContactsDictionary);
return new DictAndProximity(dictionaryCollection, proximityInfo);
}
// This method assumes the text is not empty or null.
private static int getCapitalizationType(String text) {
// If the first char is not uppercase, then the word is either all lower case,
// and in either case we return CAPITALIZE_NONE.
if (!Character.isUpperCase(text.codePointAt(0))) return CAPITALIZE_NONE;
final int len = text.codePointCount(0, text.length());
int capsCount = 1;
for (int i = 1; i < len; ++i) {
if (1 != capsCount && i != capsCount) break;
if (Character.isUpperCase(text.codePointAt(i))) ++capsCount;
}
// We know the first char is upper case. So we want to test if either everything
// else is lower case, or if everything else is upper case. If the string is
// exactly one char long, then we will arrive here with capsCount 1, and this is
// correct, too.
if (1 == capsCount) return CAPITALIZE_FIRST;
return (len == capsCount ? CAPITALIZE_ALL : CAPITALIZE_NONE);
}
private static class AndroidSpellCheckerSession extends Session {
// Immutable, but need the locale which is not available in the constructor yet
private DictionaryPool mDictionaryPool;
// Likewise
private Locale mLocale;
private final AndroidSpellCheckerService mService;
AndroidSpellCheckerSession(final AndroidSpellCheckerService service) {
mService = service;
}
@Override
public void onCreate() {
final String localeString = getLocale();
mDictionaryPool = mService.getDictionaryPool(localeString);
mLocale = LocaleUtils.constructLocaleFromString(localeString);
}
/**
* Finds out whether a particular string should be filtered out of spell checking.
*
* This will loosely match URLs, numbers, symbols.
*
* @param text the string to evaluate.
* @return true if we should filter this text out, false otherwise
*/
private boolean shouldFilterOut(final String text) {
if (TextUtils.isEmpty(text) || text.length() <= 1) return true;
// TODO: check if an equivalent processing can't be done more quickly with a
// compiled regexp.
// Filter by first letter
final int firstCodePoint = text.codePointAt(0);
// Filter out words that don't start with a letter or an apostrophe
if (!Character.isLetter(firstCodePoint)
&& '\'' != firstCodePoint) return true;
// Filter contents
final int length = text.length();
int letterCount = 0;
for (int i = 0; i < length; ++i) {
final int codePoint = text.codePointAt(i);
// Any word containing a '@' is probably an e-mail address
// Any word containing a '/' is probably either an ad-hoc combination of two
// words or a URI - in either case we don't want to spell check that
if ('@' == codePoint
|| '/' == codePoint) return true;
if (Character.isLetter(codePoint)) ++letterCount;
}
// Guestimate heuristic: perform spell checking if at least 3/4 of the characters
// in this word are letters
return (letterCount * 4 < length * 3);
}
// Note : this must be reentrant
/**
* Gets a list of suggestions for a specific string. This returns a list of possible
* corrections for the text passed as an argument. It may split or group words, and
* even perform grammatical analysis.
*/
@Override
public SuggestionsInfo onGetSuggestions(final TextInfo textInfo,
final int suggestionsLimit) {
try {
final String text = textInfo.getText();
if (shouldFilterOut(text)) {
DictAndProximity dictInfo = null;
try {
dictInfo = mDictionaryPool.takeOrGetNull();
if (null == dictInfo) return getNotInDictEmptySuggestions();
return dictInfo.mDictionary.isValidWord(text) ? getInDictEmptySuggestions()
: getNotInDictEmptySuggestions();
} finally {
if (null != dictInfo) {
if (!mDictionaryPool.offer(dictInfo)) {
Log.e(TAG, "Can't re-insert a dictionary into its pool");
}
}
}
}
// TODO: Don't gather suggestions if the limit is <= 0 unless necessary
final SuggestionsGatherer suggestionsGatherer = new SuggestionsGatherer(text,
mService.mSuggestionThreshold, mService.mLikelyThreshold, suggestionsLimit);
final WordComposer composer = new WordComposer();
final int length = text.length();
for (int i = 0; i < length; ++i) {
final int character = text.codePointAt(i);
final int proximityIndex = SpellCheckerProximityInfo.getIndexOf(character);
final int[] proximities;
if (-1 == proximityIndex) {
proximities = new int[] { character };
} else {
proximities = Arrays.copyOfRange(SpellCheckerProximityInfo.PROXIMITY,
proximityIndex,
proximityIndex + SpellCheckerProximityInfo.ROW_SIZE);
}
composer.add(character, proximities,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
}
final int capitalizeType = getCapitalizationType(text);
boolean isInDict = true;
DictAndProximity dictInfo = null;
try {
dictInfo = mDictionaryPool.takeOrGetNull();
if (null == dictInfo) return getNotInDictEmptySuggestions();
dictInfo.mDictionary.getWords(composer, suggestionsGatherer,
dictInfo.mProximityInfo);
isInDict = dictInfo.mDictionary.isValidWord(text);
if (!isInDict && CAPITALIZE_NONE != capitalizeType) {
// We want to test the word again if it's all caps or first caps only.
// If it's fully down, we already tested it, if it's mixed case, we don't
// want to test a lowercase version of it.
isInDict = dictInfo.mDictionary.isValidWord(text.toLowerCase(mLocale));
}
} finally {
if (null != dictInfo) {
if (!mDictionaryPool.offer(dictInfo)) {
Log.e(TAG, "Can't re-insert a dictionary into its pool");
}
}
}
final SuggestionsGatherer.Result result = suggestionsGatherer.getResults(
capitalizeType, mLocale);
if (DBG) {
Log.i(TAG, "Spell checking results for " + text + " with suggestion limit "
+ suggestionsLimit);
Log.i(TAG, "IsInDict = " + isInDict);
Log.i(TAG, "LooksLikeTypo = " + (!isInDict));
Log.i(TAG, "HasLikelySuggestions = " + result.mHasLikelySuggestions);
if (null != result.mSuggestions) {
for (String suggestion : result.mSuggestions) {
Log.i(TAG, suggestion);
}
}
}
// TODO: actually use result.mHasLikelySuggestions
final int flags =
(isInDict ? SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY
: SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO);
return new SuggestionsInfo(flags, result.mSuggestions);
} catch (RuntimeException e) {
// Don't kill the keyboard if there is a bug in the spell checker
if (DBG) {
throw e;
} else {
Log.e(TAG, "Exception while spellcheking: " + e);
return getNotInDictEmptySuggestions();
}
}
}
}
}
| soeminnminn/LatinIME_ICS_ported | src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java | Java | apache-2.0 | 24,716 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.typesystem.types;
import com.google.common.collect.ImmutableList;
import org.apache.atlas.classification.InterfaceAudience;
public class HierarchicalTypeDefinition<T extends HierarchicalType> extends StructTypeDefinition {
public final ImmutableList<String> superTypes;
public final String hierarchicalMetaTypeName;
/**
* Used for json deserialization only.
* not intended public consumption
* @param hierarchicalMetaTypeName
* @param typeName
* @param superTypes
* @param attributeDefinitions
* @throws ClassNotFoundException
*/
@InterfaceAudience.Private
public HierarchicalTypeDefinition(String hierarchicalMetaTypeName, String typeName, String[] superTypes,
AttributeDefinition[] attributeDefinitions) throws ClassNotFoundException {
this((Class<T>) Class.forName(hierarchicalMetaTypeName), typeName, ImmutableList.copyOf(superTypes),
attributeDefinitions);
}
public HierarchicalTypeDefinition(Class<T> hierarchicalMetaType, String typeName, ImmutableList<String> superTypes,
AttributeDefinition[] attributeDefinitions) {
super(typeName, false, attributeDefinitions);
hierarchicalMetaTypeName = hierarchicalMetaType.getName();
this.superTypes = superTypes == null ? ImmutableList.<String>of() : superTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
HierarchicalTypeDefinition that = (HierarchicalTypeDefinition) o;
if (!hierarchicalMetaTypeName.equals(that.hierarchicalMetaTypeName)) {
return false;
}
if (!superTypes.equals(that.superTypes)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + superTypes.hashCode();
result = 31 * result + hierarchicalMetaTypeName.hashCode();
return result;
}
}
| SarahMehddi/HelloWorld | typesystem/src/main/java/org/apache/atlas/typesystem/types/HierarchicalTypeDefinition.java | Java | apache-2.0 | 3,008 |
package com.lingganhezi.myapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBManager extends SQLiteOpenHelper {
private static final String DBName = "data.db";
private final static int version = 1;
public DBManager(Context context) {
super(context, DBName, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ArticleProvider.getCreateSql());
db.execSQL(MessageSessionProvider.getCreateSql());
db.execSQL(UserInfoProvider.getCreateSql());
db.execSQL(MessageProvider.getCreateSql());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| lingganhezi/dedecmsapp | android/myapp/src/com/lingganhezi/myapp/DBManager.java | Java | apache-2.0 | 727 |
package es.boart.rest;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.annotation.Resource;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import es.boart.services.PublicationService;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class PublicationTest {
private final String API_PUBLICATION = "/api/publication/";
private final int ALL_PUBLICATIONS = 9;
private final String MOST_LIKED_PUBLICATION = "NORWAY";
private final int ID_PUBLICATION = 41;
@Autowired
private PublicationService ps;
@Autowired
private MockMvc mockMvc;
@Resource
private FilterChainProxy springSecurityFilterChain;
@Resource
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.addFilter(springSecurityFilterChain)
.build();
}
@Test
public void findAllPublication() throws Exception{
this.mockMvc.perform(get(API_PUBLICATION+"list")).andExpect(status().isBadRequest());
}
@Test
public void findLikesPublication() throws Exception{
this.mockMvc.perform(post(API_PUBLICATION+"list")
.param("filter", "likes"))
.andDo(print()).andExpect(status().isBadRequest());
}
@Test
public void findPublication() throws Exception{
this.mockMvc.perform(get(API_PUBLICATION+ID_PUBLICATION))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString(MOST_LIKED_PUBLICATION)));
}
@Test
public void publicationDoesntExists() throws Exception{
this.mockMvc.perform(get(API_PUBLICATION+999999))
.andDo(print()).andExpect(status().isNotFound());
}
}
| priverop/boart | boart-back/src/test/java/es/boart/rest/PublicationTest.java | Java | apache-2.0 | 2,813 |
# Omphalocarpum brieyi De Wild. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Sapotaceae/Omphalocarpum/Omphalocarpum brieyi/README.md | Markdown | apache-2.0 | 187 |
# Dryopteris taiwanensis C.Chr. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Dryopteris/Dryopteris taiwanensis/README.md | Markdown | apache-2.0 | 179 |
# Parmelia soredica var. neghelliensis Sambo VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Parmelia soredica var. neghelliensis Sambo
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Parmeliaceae/Flavopunctelia/Flavopunctelia soredica/Parmelia soredica neghelliensis/README.md | Markdown | apache-2.0 | 213 |
# Erica viminalis Salisb. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Erica/Erica viminalis/README.md | Markdown | apache-2.0 | 173 |
# Microporus confertus (Lév.) Kuntze, 1898 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Revis. gen. pl. (Leipzig) 3(2): 495 (1898)
#### Original name
Polyporus confertus Lév., 1844
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Polyporaceae/Coriolopsis/Coriolopsis aspera/ Syn. Microporus confertus/README.md | Markdown | apache-2.0 | 263 |
# Hosta tsushimensis var. tibae VARIETY
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Asparagaceae/Hosta/Hosta tsushimensis/Hosta tsushimensis tibae/README.md | Markdown | apache-2.0 | 187 |
# Diplotaxis viminea var. integrifolia Guss. VARIETY
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Diplotaxis/Diplotaxis viminea/Diplotaxis viminea integrifolia/README.md | Markdown | apache-2.0 | 200 |
# Protoperidinium obtusum (Karsten) Parke & Dodge SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Protozoa/Dinophyta/Dinophyceae/Peridiniales/Protoperidiniaceae/Protoperidinium/Protoperidinium obtusum/README.md | Markdown | apache-2.0 | 205 |
# Azospirillum melinis Peng et al., 2006 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Bacteria/Proteobacteria/Alphaproteobacteria/Rhodospirillales/Rhodospirillaceae/Azospirillum/Azospirillum melinis/README.md | Markdown | apache-2.0 | 196 |
# Gibellula globosa Kobayasi & Shimizu SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Bull. natn. Sci. Mus. , Tokyo, B 8(2): 45 (1982)
#### Original name
Gibellula globosa Kobayasi & Shimizu
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Hypocreales/Cordycipitaceae/Gibellula/Gibellula globosa/README.md | Markdown | apache-2.0 | 245 |
# Pteridium revolutum (Blume) Nakai SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dennstaedtiaceae/Pteridium/Pteridium revolutum/README.md | Markdown | apache-2.0 | 183 |
# Chylocladia schneideri D.L.Ballantine, 2004 SPECIES
#### Status
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Rhodophyta/Florideophyceae/Rhodymeniales/Champiaceae/Chylocladia/Chylocladia schneideri/README.md | Markdown | apache-2.0 | 194 |
{% extends "base.html" %}
{% block body %}
<h2>Playlists</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Owner</th>
</tr>
</thead>
<tbody>
{% for playlist in playlists %}
<tr>
<td>{{ name }}</td>
<td>{{ owner }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %} | disqus/playa | playa/templates/playlists/index.html | HTML | apache-2.0 | 461 |
#!/bin/bash
echo 'Sharing PDF books...'
mkdir -p /cygdrive/d/Todd/pdf
mkdir -p /tmp/Todd/pdf
rm -rf /tmp/ronbo/pdf
mkdir -p /tmp/ronbo/pdf
rsync --verbose --recursive --times --checksum --delete --prune-empty-dirs --human-readable --progress --include='*/' --include='*.pdf' --exclude='*' '/cygdrive/g/Users/TLougee/Books/Packet Publishing/' '/tmp/Todd/pdf'
find /tmp/Todd/pdf -type f -name \*.pdf -exec cp --verbose $(basename {}) /tmp/ronbo/pdf \;
rsync --verbose --checksum --recursive --times --delete --prune-empty-dirs --human-readable --progress --include='*/' --include='*.pdf' --exclude='*' '/tmp/ronbo/pdf/' '/cygdrive/d/Todd/pdf'
echo 'Sharing epub books...'
mkdir -p /cygdrive/i/BitTorrenSync/Todd/epub
mkdir -p /tmp/Todd/epub
rm -rf /tmp/ronbo/epub
mkdir -p /tmp/ronbo/epub
rsync --verbose --recursive --times --delete --checksum --prune-empty-dirs --human-readable --progress --include='*/' --include='*.epub' --exclude='*' '/cygdrive/g/Users/TLougee/Books/Packet Publishing/' '/tmp/Todd/epub'
find /tmp/Todd/epub -type f -name \*.epub -exec cp --verbose $(basename {}) /tmp/ronbo/epub \;
rsync --verbose --checksum --recursive --times --delete --prune-empty-dirs --human-readable --progress --include='*/' --include='*.epub' --exclude='*' '/tmp/ronbo/epub/' '/cygdrive/i/BitTorrenSync/Todd/epub'
echo 'Sharing mobi books...'
mkdir -p /cygdrive/i/BitTorrenSync/Todd/mobi
mkdir -p /tmp/Todd/mobi
rm -rf /tmp/ronbo/mobi
mkdir -p /tmp/ronbo/mobi
rsync --verbose --recursive --times --delete --prune-empty-dirs --human-readable --progress --include='*/' --include='*.mobi' --exclude='*' '/cygdrive/g/Users/TLougee/Books/Packet Publishing/' '/tmp/Todd/mobi'
find /tmp/Todd/mobi -type f -name \*.mobi -exec cp --verbose $(basename {}) /tmp/ronbo/mobi \;
rsync --verbose --checksum --recursive --times --delete --prune-empty-dirs --human-readable --progress --include='*/' --include='*.mobi' --exclude='*' '/tmp/ronbo/mobi/' '/cygdrive/i/BitTorrenSync/Todd/mobi'
echo 'Sharing archive files...'
#mkdir -p /cygdrive/i/BitTorrenSync/Todd/zip
#rsync --verbose --recursive --times --checksum --delete --prune-empty-dirs --human-readable --progress --include='*/' --include='*.zip' --include='*.rar' --exclude='*' '/cygdrive/g/Users/TLougee/Books/' '/cygdrive/i/BitTorrenSync/Todd/zip'
echo 'Sharing video files...'
mkdir -p /cygdrive/i/BitTorrenSync/Todd/video
rsync --verbose --checksum --recursive --times --delete --prune-empty-dirs --human-readable --progress --include='*/' --include='*.mp4' --exclude='*' '/cygdrive/g/Users/TLougee/Books/' '/cygdrive/i/BitTorrenSync/Todd/video'
| kurron/scripts | share-todd-books.sh | Shell | apache-2.0 | 2,601 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.datastructures;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteAtomicLong;
import org.apache.ignite.IgniteAtomicSequence;
import org.apache.ignite.IgniteCountDownLatch;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLock;
import org.apache.ignite.IgniteQueue;
import org.apache.ignite.IgniteSemaphore;
import org.apache.ignite.IgniteSet;
import org.apache.ignite.configuration.CollectionConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
/**
*
*/
public abstract class IgniteClientDataStructuresAbstractTest extends GridCommonAbstractTest {
/** */
protected static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
/** */
private static final int NODE_CNT = 4;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
if (igniteInstanceName.equals(getTestIgniteInstanceName(NODE_CNT - 1))) {
cfg.setClientMode(true);
if (!clientDiscovery())
((TcpDiscoverySpi)cfg.getDiscoverySpi()).setForceServerMode(true);
}
((TcpDiscoverySpi)cfg.getDiscoverySpi()).setIpFinder(ipFinder);
((TcpCommunicationSpi)cfg.getCommunicationSpi()).setSharedMemoryPort(-1);
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
startGrids(NODE_CNT);
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
}
/**
* @return {@code True} if use client discovery.
*/
protected abstract boolean clientDiscovery();
/**
* @throws Exception If failed.
*/
public void testSequence() throws Exception {
Ignite clientNode = clientIgnite();
Ignite srvNode = serverNode();
testSequence(clientNode, srvNode);
testSequence(srvNode, clientNode);
}
/**
* @param creator Creator node.
* @param other Other node.
* @throws Exception If failed.
*/
private void testSequence(Ignite creator, Ignite other) throws Exception {
assertNull(creator.atomicSequence("seq1", 1L, false));
assertNull(other.atomicSequence("seq1", 1L, false));
try (IgniteAtomicSequence seq = creator.atomicSequence("seq1", 1L, true)) {
assertNotNull(seq);
assertEquals(1L, seq.get());
assertEquals(1L, seq.getAndAdd(1));
assertEquals(2L, seq.get());
IgniteAtomicSequence seq0 = other.atomicSequence("seq1", 1L, false);
assertNotNull(seq0);
}
assertNull(creator.atomicSequence("seq1", 1L, false));
assertNull(other.atomicSequence("seq1", 1L, false));
}
/**
* @throws Exception If failed.
*/
public void testAtomicLong() throws Exception {
Ignite clientNode = clientIgnite();
Ignite srvNode = serverNode();
testAtomicLong(clientNode, srvNode);
testAtomicLong(srvNode, clientNode);
}
/**
* @param creator Creator node.
* @param other Other node.
* @throws Exception If failed.
*/
private void testAtomicLong(Ignite creator, Ignite other) throws Exception {
assertNull(creator.atomicLong("long1", 1L, false));
assertNull(other.atomicLong("long1", 1L, false));
try (IgniteAtomicLong cntr = creator.atomicLong("long1", 1L, true)) {
assertNotNull(cntr);
assertEquals(1L, cntr.get());
assertEquals(1L, cntr.getAndAdd(1));
assertEquals(2L, cntr.get());
IgniteAtomicLong cntr0 = other.atomicLong("long1", 1L, false);
assertNotNull(cntr0);
assertEquals(2L, cntr0.get());
assertEquals(3L, cntr0.incrementAndGet());
assertEquals(3L, cntr.get());
}
assertAtomicLongClosedCorrect(creator.atomicLong("long1", 1L, false));
assertAtomicLongClosedCorrect(other.atomicLong("long1", 1L, false));
}
/**
* It is possible 3 variants:
* * input value is null, because it already delete.
* * input value is not null, but call 'get' method causes IllegalStateException because IgniteAtomicLong marked as delete.
* * input value is not null, but call 'get' method causes IgniteException
* because IgniteAtomicLong have not marked as delete yet but already removed from cache.
*/
private void assertAtomicLongClosedCorrect(IgniteAtomicLong atomicLong) {
if (atomicLong == null)
assertNull(atomicLong);
else {
try {
atomicLong.get();
fail("Always should be exception because atomicLong was closed");
}
catch (IllegalStateException e) {
String expectedMessage = "Sequence was removed from cache";
assertTrue(
String.format("Exception should start with '%s' but was '%s'", expectedMessage, e.getMessage()),
e.getMessage().startsWith(expectedMessage)
);
}
catch (IgniteException e){
String expectedMessage = "Failed to find atomic long:";
assertTrue(
String.format("Exception should start with '%s' but was '%s'", expectedMessage, e.getMessage()),
e.getMessage().startsWith(expectedMessage)
);
}
}
}
/**
* @throws Exception If failed.
*/
public void testSet() throws Exception {
Ignite clientNode = clientIgnite();
Ignite srvNode = serverNode();
testSet(clientNode, srvNode);
testSet(srvNode, clientNode);
}
/**
* @param creator Creator node.
* @param other Other node.
* @throws Exception If failed.
*/
private void testSet(Ignite creator, Ignite other) throws Exception {
assertNull(creator.set("set1", null));
assertNull(other.set("set1", null));
CollectionConfiguration colCfg = new CollectionConfiguration();
try (IgniteSet<Integer> set = creator.set("set1", colCfg)) {
assertNotNull(set);
assertEquals(0, set.size());
assertFalse(set.contains(1));
assertTrue(set.add(1));
assertTrue(set.contains(1));
IgniteSet<Integer> set0 = other.set("set1", null);
assertTrue(set0.contains(1));
assertEquals(1, set0.size());
assertTrue(set0.remove(1));
assertFalse(set.contains(1));
}
assertNull(creator.set("set1", null));
assertNull(other.set("set1", null));
}
/**
* @throws Exception If failed.
*/
public void testLatch() throws Exception {
Ignite clientNode = clientIgnite();
Ignite srvNode = serverNode();
testLatch(clientNode, srvNode);
testLatch(srvNode, clientNode);
}
/**
* @param creator Creator node.
* @param other Other node.
* @throws Exception If failed.
*/
private void testLatch(Ignite creator, final Ignite other) throws Exception {
assertNull(creator.countDownLatch("latch1", 1, true, false));
assertNull(other.countDownLatch("latch1", 1, true, false));
try (IgniteCountDownLatch latch = creator.countDownLatch("latch1", 1, true, true)) {
assertNotNull(latch);
assertEquals(1, latch.count());
IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
U.sleep(1000);
IgniteCountDownLatch latch0 = other.countDownLatch("latch1", 1, true, false);
assertEquals(1, latch0.count());
log.info("Count down latch.");
latch0.countDown();
assertEquals(0, latch0.count());
return null;
}
});
log.info("Await latch.");
assertTrue(latch.await(5000, TimeUnit.MILLISECONDS));
log.info("Finished wait.");
fut.get();
}
assertNull(creator.countDownLatch("latch1", 1, true, false));
assertNull(other.countDownLatch("latch1", 1, true, false));
}
/**
* @throws Exception If failed.
*/
public void testSemaphore() throws Exception {
Ignite clientNode = clientIgnite();
Ignite srvNode = serverNode();
testSemaphore(clientNode, srvNode);
testSemaphore(srvNode, clientNode);
}
/**
* @param creator Creator node.
* @param other Other node.
* @throws Exception If failed.
*/
private void testSemaphore(Ignite creator, final Ignite other) throws Exception {
assertNull(creator.semaphore("semaphore1", 1, true, false));
assertNull(other.semaphore("semaphore1", 1, true, false));
try (IgniteSemaphore semaphore = creator.semaphore("semaphore1", -1, true, true)) {
assertNotNull(semaphore);
assertEquals(-1, semaphore.availablePermits());
IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
U.sleep(1000);
IgniteSemaphore semaphore0 = other.semaphore("semaphore1", -1, true, false);
assertEquals(-1, semaphore0.availablePermits());
log.info("Release semaphore.");
semaphore0.release(2);
return null;
}
});
log.info("Acquire semaphore.");
assertTrue(semaphore.tryAcquire(1, 5000, TimeUnit.MILLISECONDS));
log.info("Finished wait.");
fut.get();
assertEquals(0, semaphore.availablePermits());
}
assertNull(creator.semaphore("semaphore1", 1, true, false));
assertNull(other.semaphore("semaphore1", 1, true, false));
}
/**
* @throws Exception If failed.
*/
public void testReentrantLock() throws Exception {
Ignite clientNode = clientIgnite();
Ignite srvNode = serverNode();
testReentrantLock(clientNode, srvNode);
testReentrantLock(srvNode, clientNode);
}
/**
* @param creator Creator node.
* @param other Other node.
* @throws Exception If failed.
*/
private void testReentrantLock(Ignite creator, final Ignite other) throws Exception {
assertNull(creator.reentrantLock("lock1", true, false, false));
assertNull(other.reentrantLock("lock1", true, false, false));
try (IgniteLock lock = creator.reentrantLock("lock1", true, false, true)) {
assertNotNull(lock);
assertFalse(lock.isLocked());
final Semaphore semaphore = new Semaphore(0);
IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
IgniteLock lock0 = other.reentrantLock("lock1", true, false, false);
lock0.lock();
assertTrue(lock0.isLocked());
semaphore.release();
U.sleep(1000);
log.info("Release reentrant lock.");
lock0.unlock();
return null;
}
});
semaphore.acquire();
log.info("Try acquire lock.");
assertTrue(lock.tryLock(5000, TimeUnit.MILLISECONDS));
log.info("Finished wait.");
fut.get();
assertTrue(lock.isLocked());
lock.unlock();
assertFalse(lock.isLocked());
}
assertNull(creator.reentrantLock("lock1", true, false, false));
assertNull(other.reentrantLock("lock1", true, false, false));
}
/**
* @throws Exception If failed.
*/
public void testQueue() throws Exception {
Ignite clientNode = clientIgnite();
Ignite srvNode = serverNode();
testQueue(clientNode, srvNode);
testQueue(srvNode, clientNode);
}
/**
* @param creator Creator node.
* @param other Other node.
* @throws Exception If failed.
*/
private void testQueue(Ignite creator, final Ignite other) throws Exception {
assertNull(creator.queue("q1", 0, null));
assertNull(other.queue("q1", 0, null));
try (IgniteQueue<Integer> queue = creator.queue("q1", 0, new CollectionConfiguration())) {
assertNotNull(queue);
queue.add(1);
assertEquals(1, queue.poll().intValue());
IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Object>() {
@Override public Object call() throws Exception {
U.sleep(1000);
IgniteQueue<Integer> queue0 = other.queue("q1", 0, null);
assertEquals(0, queue0.size());
log.info("Add in queue.");
queue0.add(2);
return null;
}
});
log.info("Try take.");
assertEquals(2, queue.take().intValue());
log.info("Finished take.");
fut.get();
}
assertNull(creator.queue("q1", 0, null));
assertNull(other.queue("q1", 0, null));
}
/**
* @return Client node.
*/
private Ignite clientIgnite() {
Ignite ignite = ignite(NODE_CNT - 1);
assertTrue(ignite.configuration().isClientMode());
assertEquals(clientDiscovery(), ignite.configuration().getDiscoverySpi().isClientMode());
return ignite;
}
/**
* @return Server node.
*/
private Ignite serverNode() {
Ignite ignite = ignite(0);
assertFalse(ignite.configuration().isClientMode());
return ignite;
}
}
| vladisav/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/datastructures/IgniteClientDataStructuresAbstractTest.java | Java | apache-2.0 | 15,788 |
# Dalbergia pervillei Vatke SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Dalbergia/Dalbergia pervillei/README.md | Markdown | apache-2.0 | 183 |
# twilight-poj-solution
POJ (http://poj.org/) solution by twilight
想当年要找一题的分析, 解答实在太难了
现在都是开源的时代了, 干脆把Archive放到GitHub上, 供后来人参考.
POJ ID: http://poj.org/userstatus?user_id=twilight
部分题解: http://blog.csdn.net/twilightgod
转载请注明出处~
| twilightgod/twilight-poj-solution | README.md | Markdown | apache-2.0 | 332 |
package net.swiftos.common.presenter;
import rx.subscriptions.CompositeSubscription;
import rx.Subscription;
/**
* Created by ganyao on 2017/3/9.
*/
public class RxAsyncSubjectsQueue implements IAsyncSubjectsQueue<Subscription> {
private CompositeSubscription compositeSubscription;
@Override
public void addSubject(IAsyncSubject<Subscription> observer) {
if (compositeSubscription == null) {
compositeSubscription = new CompositeSubscription();
}
compositeSubscription.add(observer.getEntity());
}
@Override
public void removeSubject(IAsyncSubject<Subscription> observer) {
if (compositeSubscription != null) {
compositeSubscription.remove(observer.getEntity());
}
}
@Override
public void destroyQueue() {
if (compositeSubscription != null && compositeSubscription.hasSubscriptions()) {
compositeSubscription.unsubscribe();
}
}
}
| ganyao114/SwiftAndroid | common/src/main/java/net/swiftos/common/presenter/RxAsyncSubjectsQueue.java | Java | apache-2.0 | 973 |
/*
* Copyright 2016-2020 the original author or authors.
*
* 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
*
* https://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 org.springframework.cloud.vault.config.databases;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import com.datastax.oss.driver.api.core.CqlSession;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.vault.util.CanConnect;
import org.springframework.cloud.vault.util.VaultRule;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.vault.core.VaultOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
/**
* Integration tests using the cassandra secret backend. In case this test should fail
* because of SSL make sure you run the test within the
* spring-cloud-vault-config/spring-cloud-vault-config directory as the keystore is
* referenced with {@code ../work/keystore.jks}.
*
* @author Mark Paluch
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = VaultConfigCassandraTests.TestApplication.class,
properties = { "spring.cloud.vault.cassandra.enabled=true", "spring.cloud.vault.cassandra.role=readonly",
"spring.data.cassandra.jmx-enabled=false", "spring.cloud.bootstrap.enabled=true" })
public class VaultConfigCassandraTests {
private static final String CASSANDRA_HOST = "localhost";
private static final int CASSANDRA_PORT = 9042;
private static final String CASSANDRA_USERNAME = "springvault";
private static final String CASSANDRA_PASSWORD = "springvault";
private static final String CREATE_USER_AND_GRANT_CQL = "CREATE USER '{{username}}' WITH PASSWORD '{{password}}' NOSUPERUSER;"
+ "GRANT SELECT ON ALL KEYSPACES TO {{username}};";
@Value("${spring.data.cassandra.username}")
String username;
@Value("${spring.data.cassandra.password}")
String password;
@Autowired
CqlSession cqlSession;
/**
* Initialize the cassandra secret backend.
*/
@BeforeClass
public static void beforeClass() {
assumeTrue(CanConnect.to(new InetSocketAddress(CASSANDRA_HOST, CASSANDRA_PORT)));
VaultRule vaultRule = new VaultRule();
vaultRule.before();
if (!vaultRule.prepare().hasSecretBackend("cassandra")) {
vaultRule.prepare().mountSecret("cassandra");
}
VaultOperations vaultOperations = vaultRule.prepare().getVaultOperations();
Map<String, Object> connection = new HashMap<>();
connection.put("hosts", CASSANDRA_HOST);
connection.put("username", CASSANDRA_USERNAME);
connection.put("password", CASSANDRA_PASSWORD);
connection.put("protocol_version", 3);
vaultOperations.write(String.format("%s/config/connection", "cassandra"), connection);
Map<String, String> role = new HashMap<>();
role.put("creation_cql", CREATE_USER_AND_GRANT_CQL);
role.put("consistency", "All");
vaultOperations.write("cassandra/roles/readonly", role);
}
@Test
public void shouldUseAuthenticatedSession() {
assertThat(this.cqlSession.getMetadata().getKeyspace("system")).isNotEmpty();
}
@Test
public void shouldConnectUsingCassandraClient() {
try (CqlSession session = CqlSession.builder().withLocalDatacenter("dc1")
.addContactPoint(new InetSocketAddress(CASSANDRA_HOST, CASSANDRA_PORT))
.withAuthCredentials(this.username, this.password).build()) {
assertThat(session.getMetadata().getKeyspace("system")).isNotEmpty();
}
}
@SpringBootApplication
public static class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
}
| spencergibb/spring-cloud-vault-config | spring-cloud-vault-config-databases/src/test/java/org/springframework/cloud/vault/config/databases/VaultConfigCassandraTests.java | Java | apache-2.0 | 4,425 |
---
title: Work with GitHub
description: Shows you how to use GitHub to contribute to the Istio documentation.
weight: 2
aliases:
- /docs/welcome/contribute/creating-a-pull-request.html
- /docs/welcome/contribute/staging-your-changes.html
- /docs/welcome/contribute/editing.html
- /about/contribute/creating-a-pull-request
- /about/contribute/editing
- /about/contribute/staging-your-changes
- /about/contribute/github
- /latest/about/contribute/github
keywords: [contribute,community,github,pr]
owner: istio/wg-docs-maintainers
test: n/a
---
The Istio documentation follows the standard [GitHub collaboration flow](https://guides.github.com/introduction/flow/)
for Pull Requests (PRs). This well-established collaboration model helps open
source projects manage the following types of contributions:
- [Add](/docs/releases/contribute/add-content) new files to the repository.
- [Edit](#quick-edit) existing files.
- [Review](/docs/releases/contribute/review) the added or modified files.
- Manage multiple release or development [branches](#branching-strategy).
The contribution guides assume you can complete the following tasks:
- Fork the [Istio documentation repository](https://github.com/istio/istio.io).
- Create a branch for your changes.
- Add commits to that branch.
- Open a PR to share your contribution.
## Before you begin
To contribute to the Istio documentation, you need to:
1. Create a [GitHub account](https://github.com).
1. Sign the [Contributor License Agreement](https://github.com/istio/community/blob/master/CONTRIBUTING.md#contributor-license-agreements).
1. Install [Docker](https://www.docker.com/get-started) on your authoring system
to preview and test your changes.
The Istio documentation is published under the
[Apache 2.0](https://github.com/istio/community/blob/master/LICENSE) license.
## Perform quick edits {#quick-edit}
Anyone with a GitHub account who signs the CLA can contribute a quick
edit to any page on the Istio website. The process is very simple:
1. Visit the page you wish to edit.
1. Add `preliminary` to the beginning of the URL. For example, to edit
`https://istio.io/about`, the new URL should be
`https://preliminary.istio.io/about`
1. Click the pencil icon in the lower right corner.
1. Perform your edits on the GitHub UI.
1. Submit a Pull Request with your changes.
Please see our guides on how to [contribute new content](/docs/releases/contribute/add-content)
or [review content](/docs/releases/contribute/review) to learn more about submitting more
substantial changes.
## Branching strategy {#branching-strategy}
Active content development takes place using the master branch of the
`istio/istio.io` repository. On the day of an Istio release, we create a release
branch of master for that release. The following button takes you to the
repository on GitHub:
<a class="btn"
href="https://github.com/istio/istio.io/">Browse this site's source
code</a>
The Istio documentation repository uses multiple branches to publish
documentation for all Istio releases. Each Istio release has a corresponding
documentation branch. For example, there are branches called `release-1.0`,
`release-1.1`, `release-1.2` and so forth. These branches were created on the
day of the corresponding release. To view the documentation for a specific
release, see the [archive page](https://archive.istio.io/).
This branching strategy allows us to provide the following Istio online resources:
- The [public site](/docs/) shows the content from the current
release branch.
- The preliminary site at `https://preliminary.istio.io` shows the content from
the master branch.
- The [archive site](https://archive.istio.io) shows the content from all prior
release branches.
Given how branching works, if you submit a change into the master branch,
that change won't appear on `istio.io` until the next major Istio release
happens. If your documentation change is relevant to the current Istio release,
then it's probably worth also applying your change to the current release branch.
You can do this easily and automatically by using the special cherry-pick labels
on your documentation PR. For example, if you introduce a correction in a PR to
the master branch, you can apply the `cherrypick/release-1.4` label in order to
merge this change to the `release-1.4` branch.
When your initial PR is merged, automation creates a new PR in the release
branch which includes your changes. You may need to add a comment to the PR
that reads `@googlebot I consent` in order to satisfy the `CLA` bot that we
use.
On rare occasions, automatic cherry picks don't work. When that happens, the
automation leaves a note in the original PR indicating it failed. When
that happens, you must manually create the cherry pick and deal
with the merge issues that prevented the process from working automatically.
Note that we only ever cherry pick changes into the current release branch,
and never to older branches. Older branches are considered to be archived and
generally no longer receive any changes.
## Istio community roles
Depending on your contributions and responsibilities, there are several roles
you can assume.
Visit our [role summary page](https://github.com/istio/community/blob/master/ROLES.md#role-summary)
to learn about the roles, the related requirements and responsibilities, and
the privileges associated with the roles.
Visit our [community page](https://github.com/istio/community) to learn more
about the Istio community in general.
| istio/istio.io | content/en/docs/releases/contribute/github/index.md | Markdown | apache-2.0 | 5,552 |
/**
* Copyright (C) 2009-2012 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 org.fusesource.restygwt.client.codec;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY)
@JsonSubTypes(value = { @Type(SubCredentialsWithProperty.class), @Type(CredentialsWithProperty.class) })
class CredentialsWithProperty {
String password;
String email;
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
} | resty-gwt/resty-gwt | restygwt/src/test/java/org/fusesource/restygwt/client/codec/CredentialsWithProperty.java | Java | apache-2.0 | 1,603 |
#ifndef GraphicsJNI_DEFINED
#define GraphicsJNI_DEFINED
#include "SkBitmap.h"
#include "SkDevice.h"
#include "SkPixelRef.h"
#include "SkMallocPixelRef.h"
#include "SkPoint.h"
#include "SkRect.h"
#include "SkImageDecoder.h"
#include <jni.h>
class SkBitmapRegionDecoder;
class SkCanvas;
class SkPaint;
class SkPicture;
class GraphicsJNI {
public:
enum BitmapCreateFlags {
kBitmapCreateFlag_None = 0x0,
kBitmapCreateFlag_Mutable = 0x1,
kBitmapCreateFlag_Premultiplied = 0x2,
};
// returns true if an exception is set (and dumps it out to the Log)
static bool hasException(JNIEnv*);
static void get_jrect(JNIEnv*, jobject jrect, int* L, int* T, int* R, int* B);
static void set_jrect(JNIEnv*, jobject jrect, int L, int T, int R, int B);
static SkIRect* jrect_to_irect(JNIEnv*, jobject jrect, SkIRect*);
static void irect_to_jrect(const SkIRect&, JNIEnv*, jobject jrect);
static SkRect* jrectf_to_rect(JNIEnv*, jobject jrectf, SkRect*);
static SkRect* jrect_to_rect(JNIEnv*, jobject jrect, SkRect*);
static void rect_to_jrectf(const SkRect&, JNIEnv*, jobject jrectf);
static void set_jpoint(JNIEnv*, jobject jrect, int x, int y);
static SkIPoint* jpoint_to_ipoint(JNIEnv*, jobject jpoint, SkIPoint* point);
static void ipoint_to_jpoint(const SkIPoint& point, JNIEnv*, jobject jpoint);
static SkPoint* jpointf_to_point(JNIEnv*, jobject jpointf, SkPoint* point);
static void point_to_jpointf(const SkPoint& point, JNIEnv*, jobject jpointf);
static SkCanvas* getNativeCanvas(JNIEnv*, jobject canvas);
static SkPaint* getNativePaint(JNIEnv*, jobject paint);
static SkBitmap* getNativeBitmap(JNIEnv*, jobject bitmap);
static SkPicture* getNativePicture(JNIEnv*, jobject picture);
static SkRegion* getNativeRegion(JNIEnv*, jobject region);
/** Return the corresponding native config from the java Config enum,
or kNo_Config if the java object is null.
*/
static SkBitmap::Config getNativeBitmapConfig(JNIEnv*, jobject jconfig);
/** Create a java Bitmap object given the native bitmap (required) and optional
storage array (may be null).
*/
static jobject createBitmap(JNIEnv* env, SkBitmap* bitmap, jbyteArray buffer,
int bitmapCreateFlags, jbyteArray ninepatch, jintArray layoutbounds, int density = -1);
static jobject createBitmap(JNIEnv* env, SkBitmap* bitmap, int bitmapCreateFlags,
jbyteArray ninepatch, int density = -1);
static void reinitBitmap(JNIEnv* env, jobject javaBitmap, SkBitmap* bitmap,
bool isPremultiplied);
static int getBitmapAllocationByteCount(JNIEnv* env, jobject javaBitmap);
static jobject createRegion(JNIEnv* env, SkRegion* region);
static jobject createBitmapRegionDecoder(JNIEnv* env, SkBitmapRegionDecoder* bitmap);
static jbyteArray allocateJavaPixelRef(JNIEnv* env, SkBitmap* bitmap,
SkColorTable* ctable);
/** Copy the colors in colors[] to the bitmap, convert to the correct
format along the way.
*/
static bool SetPixels(JNIEnv* env, jintArray colors, int srcOffset,
int srcStride, int x, int y, int width, int height,
const SkBitmap& dstBitmap, bool isPremultiplied);
static jbyteArray getBitmapStorageObj(SkPixelRef *pixref);
};
class AndroidPixelRef : public SkMallocPixelRef {
public:
AndroidPixelRef(JNIEnv* env, void* storage, size_t size, jbyteArray storageObj,
SkColorTable* ctable);
/**
* Creates an AndroidPixelRef that wraps (and refs) another to reuse/share
* the same storage and java byte array refcounting, yet have a different
* color table.
*/
AndroidPixelRef(AndroidPixelRef& wrappedPixelRef, SkColorTable* ctable);
virtual ~AndroidPixelRef();
jbyteArray getStorageObj();
void setLocalJNIRef(jbyteArray arr);
/** Used to hold a ref to the pixels when the Java bitmap may be collected.
* If specified, 'localref' is a valid JNI local reference to the byte array
* containing the pixel data.
*
* 'localref' may only be NULL if setLocalJNIRef() was already called with
* a JNI local ref that is still valid.
*/
virtual void globalRef(void* localref=NULL);
/** Release a ref that was acquired using globalRef(). */
virtual void globalUnref();
private:
AndroidPixelRef* const fWrappedPixelRef; // if set, delegate memory management calls to this
JavaVM* fVM;
bool fOnJavaHeap; // If true, the memory was allocated on the Java heap
jbyteArray fStorageObj; // The Java byte[] object used as the bitmap backing store
bool fHasGlobalRef; // If true, fStorageObj holds a JNI global ref
mutable int32_t fGlobalRefCnt;
};
/** A helper class for accessing Java-heap-allocated bitmaps.
* This should be used when calling into a JNI method that retains a
* reference to the bitmap longer than the lifetime of the Java Bitmap.
*
* After creating an instance of this class, a call to
* AndroidPixelRef::globalRef() will allocate a JNI global reference
* to the backing buffer object.
*/
class JavaHeapBitmapRef {
public:
JavaHeapBitmapRef(JNIEnv *env, SkBitmap* nativeBitmap, jbyteArray buffer);
~JavaHeapBitmapRef();
private:
JNIEnv* fEnv;
SkBitmap* fNativeBitmap;
jbyteArray fBuffer;
};
/** Allocator which allocates the backing buffer in the Java heap.
* Instances can only be used to perform a single allocation, which helps
* ensure that the allocated buffer is properly accounted for with a
* reference in the heap (or a JNI global reference).
*/
class JavaPixelAllocator : public SkBitmap::Allocator {
public:
JavaPixelAllocator(JNIEnv* env);
// overrides
virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable);
/** Return the Java array object created for the last allocation.
* This returns a local JNI reference which the caller is responsible
* for storing appropriately (usually by passing it to the Bitmap
* constructor).
*/
jbyteArray getStorageObj() { return fStorageObj; }
/** Same as getStorageObj(), but also resets the allocator so that it
* can allocate again.
*/
jbyteArray getStorageObjAndReset() {
jbyteArray result = fStorageObj;
fStorageObj = NULL;
fAllocCount = 0;
return result;
};
private:
JavaVM* fVM;
bool fAllocateInJavaHeap;
jbyteArray fStorageObj;
int fAllocCount;
};
enum JNIAccess {
kRO_JNIAccess,
kRW_JNIAccess
};
class AutoJavaFloatArray {
public:
AutoJavaFloatArray(JNIEnv* env, jfloatArray array,
int minLength = 0, JNIAccess = kRW_JNIAccess);
~AutoJavaFloatArray();
float* ptr() const { return fPtr; }
int length() const { return fLen; }
private:
JNIEnv* fEnv;
jfloatArray fArray;
float* fPtr;
int fLen;
int fReleaseMode;
};
class AutoJavaIntArray {
public:
AutoJavaIntArray(JNIEnv* env, jintArray array, int minLength = 0);
~AutoJavaIntArray();
jint* ptr() const { return fPtr; }
int length() const { return fLen; }
private:
JNIEnv* fEnv;
jintArray fArray;
jint* fPtr;
int fLen;
};
class AutoJavaShortArray {
public:
AutoJavaShortArray(JNIEnv* env, jshortArray array,
int minLength = 0, JNIAccess = kRW_JNIAccess);
~AutoJavaShortArray();
jshort* ptr() const { return fPtr; }
int length() const { return fLen; }
private:
JNIEnv* fEnv;
jshortArray fArray;
jshort* fPtr;
int fLen;
int fReleaseMode;
};
class AutoJavaByteArray {
public:
AutoJavaByteArray(JNIEnv* env, jbyteArray array, int minLength = 0);
~AutoJavaByteArray();
jbyte* ptr() const { return fPtr; }
int length() const { return fLen; }
private:
JNIEnv* fEnv;
jbyteArray fArray;
jbyte* fPtr;
int fLen;
};
void doThrowNPE(JNIEnv* env);
void doThrowAIOOBE(JNIEnv* env); // Array Index Out Of Bounds Exception
void doThrowIAE(JNIEnv* env, const char* msg = NULL); // Illegal Argument
void doThrowRE(JNIEnv* env, const char* msg = NULL); // Runtime
void doThrowISE(JNIEnv* env, const char* msg = NULL); // Illegal State
void doThrowOOME(JNIEnv* env, const char* msg = NULL); // Out of memory
void doThrowIOE(JNIEnv* env, const char* msg = NULL); // IO Exception
#define NPE_CHECK_RETURN_ZERO(env, object) \
do { if (NULL == (object)) { doThrowNPE(env); return 0; } } while (0)
#define NPE_CHECK_RETURN_VOID(env, object) \
do { if (NULL == (object)) { doThrowNPE(env); return; } } while (0)
#endif
| indashnet/InDashNet.Open.UN2000 | android/frameworks/base/core/jni/android/graphics/GraphicsJNI.h | C | apache-2.0 | 8,758 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class GenerationPickUp : MonoBehaviour {
public GameObject panneauPickUp;
public Material[] typePanneau;
private bool canCreate = true;
public static int cptPlateforme = 0;
private int[] panneauPosition = {7,10,14,18};
void OnCollisionEnter(Collision col){
if (canCreate) {
canCreate = false;
int posSup = Random.Range (2, 15);
int positionZ = cptPlateforme * 40;
int indexMaterial = Random.Range(0,5);
if (col.gameObject.name == "unitychan") {
int indexPosition = Random.Range(0,4);
Instantiate (panneauPickUp, new Vector3 (panneauPosition[indexPosition], 3, positionZ + posSup), panneauPickUp.transform.rotation);
panneauPickUp.GetComponent<Renderer> ().material = typePanneau [indexMaterial];
}
}
}
}
| Reiaka/permispieton | Assets/Runner3DNew/Scripts/GenerationPickUp.cs | C# | apache-2.0 | 858 |
---
title: Integrating Virtual Machines
description: This sample deploys the Bookinfo services across Kubernetes and a set of virtual machines, and illustrates how to use the Istio service mesh to control this infrastructure as a single mesh.
weight: 60
---
This sample deploys the Bookinfo services across Kubernetes and a set of
Virtual Machines, and illustrates how to use Istio service mesh to control
this infrastructure as a single mesh.
> This guide is still under development and only tested on Google Cloud Platform.
On IBM Cloud or other platforms where overlay network of Pods is isolated from VM network,
VMs cannot initiate any direct communication to Kubernetes Pods even when using Istio.
## Overview
{{< image width="80%" ratio="56.78%"
link="../img/mesh-expansion.svg"
caption="Bookinfo Application with Istio Mesh Expansion"
>}}
<!-- source of the drawing https://docs.google.com/drawings/d/1gQp1OTusiccd-JUOHktQ9RFZaqREoQbwl2Vb-P3XlRQ/edit -->
## Before you begin
* Setup Istio by following the instructions in the
[Installation guide](/docs/setup/kubernetes/quick-start/).
* Deploy the [Bookinfo](/docs/guides/bookinfo/) sample application (in the `bookinfo` namespace).
* Create a VM named 'vm-1' in the same project as Istio cluster, and [Join the Mesh](/docs/setup/kubernetes/mesh-expansion/).
## Running MySQL on the VM
We will first install MySQL on the VM, and configure it as a backend for the ratings service.
On the VM:
```command
$ sudo apt-get update && sudo apt-get install -y mariadb-server
$ sudo mysql
# Grant access to root
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
quit;
```
```command
$ sudo systemctl restart mysql
```
You can find details of configuring MySQL at [Mysql](https://mariadb.com/kb/en/library/download/).
On the VM add ratings database to mysql.
```command
$ curl -q https://raw.githubusercontent.com/istio/istio/{{<branch_name>}}/samples/bookinfo/src/mysql/mysqldb-init.sql | mysql -u root -ppassword
```
To make it easy to visually inspect the difference in the output of the Bookinfo application, you can change the ratings that are generated by using the
following commands to inspect the ratings:
```command
$ mysql -u root -ppassword test -e "select * from ratings;"
+----------+--------+
| ReviewID | Rating |
+----------+--------+
| 1 | 5 |
| 2 | 4 |
+----------+--------+
```
and to change the ratings
```command
$ mysql -u root -ppassword test -e "update ratings set rating=1 where reviewid=1;select * from ratings;"
+----------+--------+
| ReviewID | Rating |
+----------+--------+
| 1 | 1 |
| 2 | 4 |
+----------+--------+
```
## Find out the IP address of the VM that will be used to add it to the mesh
On the VM:
```command
$ hostname -I
```
## Registering the mysql service with the mesh
On a host with access to `istioctl` commands, register the VM and mysql db service
```command
$ istioctl register -n vm mysqldb <ip-address-of-vm> 3306
I1108 20:17:54.256699 40419 register.go:43] Registering for service 'mysqldb' ip '10.150.0.5', ports list [{3306 mysql}]
I1108 20:17:54.256815 40419 register.go:48] 0 labels ([]) and 1 annotations ([alpha.istio.io/kubernetes-serviceaccounts=default])
W1108 20:17:54.573068 40419 register.go:123] Got 'services "mysqldb" not found' looking up svc 'mysqldb' in namespace 'vm', attempting to create it
W1108 20:17:54.816122 40419 register.go:138] Got 'endpoints "mysqldb" not found' looking up endpoints for 'mysqldb' in namespace 'vm', attempting to create them
I1108 20:17:54.886657 40419 register.go:180] No pre existing exact matching ports list found, created new subset {[{10.150.0.5 <nil> nil}] [] [{mysql 3306 }]}
I1108 20:17:54.959744 40419 register.go:191] Successfully updated mysqldb, now with 1 endpoints
```
Note that the 'mysqldb' virtual machine does not need and should not have special Kubernetes privileges.
## Using the mysql service
The ratings service in bookinfo will use the DB on the machine. To verify that it works, create version 2 of the ratings service that uses the mysql db on the VM. Then specify route rules that force the review service to use the ratings version 2.
```command
$ istioctl kube-inject -n bookinfo -f @samples/bookinfo/kube/bookinfo-ratings-v2-mysql-vm.yaml@ | kubectl apply -n bookinfo -f -
```
Create route rules that will force bookinfo to use the ratings back end:
```command
$ istioctl create -n bookinfo -f @samples/bookinfo/kube/route-rule-ratings-mysql-vm.yaml@
```
You can verify the output of the Bookinfo application is showing 1 star from Reviewer1 and 4 stars from Reviewer2 or change the ratings on your VM and see the
results.
You can also find some troubleshooting and other information in the [RawVM MySQL](https://github.com/istio/istio/blob/{{<branch_name>}}/samples/rawvm/README.md) document in the meantime.
| ZackButcher/istio.github.io | content/docs/guides/integrating-vms.md | Markdown | apache-2.0 | 4,945 |
/*!
* STAN Loader 1.1.0
* Copyright 2015 Andrew Womersley
*/
!function(a,b){function c(c,d,e,j){g=c,h=d,i=e,b.addEventListener?b.addEventListener("DOMContentLoaded",f):a.attachEvent("onload",f),"undefined"!=typeof j&&f()}function d(){j++,g[j]?f():"function"==typeof h&&h()}function e(){"function"==typeof i&&i()}function f(){var a=b.createElement("script");a.type="text/javascript",a.src=g[j],a.async=!0,"onload"in a?(a.onload=d,a.onerror=e):a.onreadystatechange=function(){("complete"===this.readyState||"loaded"===this.readyState)&&d()},b.getElementsByTagName("head")[0].appendChild(a)}var g,h,i,j=0;a.$STAN_Load=c}(window,document); | awomersley/stan-loader | stan-loader.min.js | JavaScript | apache-2.0 | 638 |
<?php
require_once('../../includes/config.inc.php');
$link = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD) or die("could not connect to host.");
mysqli_select_db($link, DB_DATABASE) or die("could not find db.");
$sellno = $_POST['sellerno'];
$product = $_POST['product'];
$price = $_POST['price'];
$transno = $_POST['transno'];
$sql = "UPDATE cardstatement SET sellerno = '$sellno' , product= '$product', price = '$price' WHERE transno=$transno";
if (mysqli_query($link, $sql)) {
echo "Save record successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
mysqli_close($link);
| ripzery/WebDatabase | custom/menus/php_database/savecard.php | PHP | apache-2.0 | 671 |
import React, { Component } from "react";
import { ReactiveBase, MultiList, ReactiveElement } from "../../app.js";
import { combineStreamData } from "../../middleware/helper.js";
import ResponsiveStory from "./ResponsiveStory";
import { GetTopTopics } from "./helper";
import { Img } from "../Img.js";
require("../list.css");
export default class WithTheme extends Component {
constructor(props) {
super(props);
this.cityQuery = this.cityQuery.bind(this);
this.onAllData = this.onAllData.bind(this);
this.DEFAULT_IMAGE = "http://www.avidog.com/wp-content/uploads/2015/01/BellaHead082712_11-50x65.jpg";
}
cityQuery(value) {
if (value) {
const field = "group.group_city.group_city_simple";
const query = JSON.parse(`{"${field}":${JSON.stringify(value)}}`);
return { terms: query };
} return null;
}
componentDidMount() {
ResponsiveStory();
}
onAllData(res, err) {
let result = null;
if (res && res.appliedQuery) {
let combineData = res.currentData;
if (res.mode === "historic") {
combineData = res.currentData.concat(res.newData);
} else if (res.mode === "streaming") {
combineData = combineStreamData(res.currentData, res.newData);
}
if (combineData) {
combineData = GetTopTopics(combineData);
const resultMarkup = combineData.map((data, index) => {
if (index < 5) {
return this.itemMarkup(data, index);
}
});
result = (
<div className="trendingTopics col s12 col-xs-12" style={{ padding: "10px", paddingBottom: "60px", color: "#eee" }}>
<table className="table">
<tbody>
{resultMarkup}
</tbody>
</table>
</div>
);
}
}
return result;
}
itemMarkup(data, index) {
return (
<tr key={index}>
<th>{data.name}</th>
<td>{data.value}</td>
</tr>
);
}
render() {
return (
<ReactiveBase
app="meetup2"
credentials="qz4ZD8xq1:a0edfc7f-5611-46f6-8fe1-d4db234631f3"
type="meetup"
theme="rbc-dark"
>
<div className="row reverse-labels">
<div className="col s6 col-xs-6">
<ReactiveElement
componentId="SearchResult"
from={0}
size={1000}
onAllData={this.onAllData}
placeholder="Select a city from the input filter..."
title="Reactive Element: Dark Theme"
{...this.props}
react={{
and: "CitySensor"
}}
/>
</div>
<div className="col s6 col-xs-6">
<MultiList
componentId="CitySensor"
dataField="group.group_city.group_city_simple"
showCount={true}
size={10}
title="Input Filter"
initialLoader="Loading city list.."
selectAllLabel="All cities"
customQuery={this.cityQuery}
searchPlaceholder="Search City"
includeSelectAll={true}
/>
</div>
</div>
</ReactiveBase>
);
}
}
| appbaseio/reactivebase | app/stories/ReactiveElement/WithTheme.js | JavaScript | apache-2.0 | 2,846 |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="modulin.css">
<title>Modul.in</title>
</head>
<body>
<div class="button" data-module=linkButton>
<a href="#" class="link link__button">
Click me
</a>
</div>
<div class="menu" data-module=menu>
<div class="button button__menu" data-module=linkButton data-instance=rotate>
<a href="#" class="link link__button">
Click me
</a>
</div>
<div class="button button__menu" data-module=closeButton data-instance=red>
X
</div>
<div class="button button__menu" data-module=backButton>
B
</div>
<div class="button button__menu" data-module=closeButton>
X
</div>
</div>
<div class="menu" data-module=menu data-instance=wide>
<div class="button button__menu" data-module=linkButton data-instance=rotate>
<a href="#" class="link link__button">
Click me
</a>
</div>
<div class="button button__menu" data-module=closeButton data-instance=invisible>
X
</div>
<div class="button button__menu" data-module=backButton>
B
</div>
<div class="button button__menu" data-module=closeButton>
X
</div>
</div>
<div class="menu" data-module=menu data-instance=wide>
<div class="button button__menu" data-module=linkButton data-instance=rotate>
<a href="#" class="link link__button">
Click me
</a>
</div>
<div class="button button__menu" data-module=backButton data-instance=rotate>
<a href="#" class="link link__button">
B
</a>
</div>
<div class="button button__menu" data-module=closeButton>
X
</div>
</div>
</body>
</html> | Modulin/Modulin | src/index.html | HTML | apache-2.0 | 1,597 |
package wzp.project.android.elvtmtn.biz.listener;
import java.util.Date;
import wzp.project.android.elvtmtn.biz.listener.base.IBaseListener;
public interface IWorkOrderReceiveListener extends IBaseListener {
void onReceiveSuccess(Date receivingTime);
void onReceiveFailure(String tipInfo);
}
| zippenwang/ElevatorMaintenance | src/wzp/project/android/elvtmtn/biz/listener/IWorkOrderReceiveListener.java | Java | apache-2.0 | 300 |
/*
* Copyright 2015-2019 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v20.html
*/
package org.junit.jupiter.api.condition;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.DayOfWeek;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* @see EnabledOnDayOfWeek
* @see org.junit.jupiter.api.Disabled
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ExtendWith(DisabledOnDayOfWeekCondition.class)
public @interface DisabledOnDayOfWeek {
DayOfWeek[] value();
}
| sbrannen/junit5-demo | src/main/java/org/junit/jupiter/api/condition/DisabledOnDayOfWeek.java | Java | apache-2.0 | 924 |
using System.Windows.Automation;
namespace aQuery
{
public interface ICustomCondition
{
bool IsMatch(AutomationElement element);
}
} | Soul-Master/aQuery | aQuery/ICustomCondition.cs | C# | apache-2.0 | 156 |
/*global defineSuite*/
defineSuite([
'Widgets/Geocoder/GeocoderViewModel',
'Core/Cartesian3',
'Specs/createScene',
'Specs/pollToPromise',
'ThirdParty/when'
], function(
GeocoderViewModel,
Cartesian3,
createScene,
pollToPromise,
when) {
'use strict';
var scene;
var mockDestination = new Cartesian3(1.0, 2.0, 3.0);
var geocoderResults1 = [{
displayName: 'a',
destination: mockDestination
}, {
displayName: 'b',
destination: mockDestination
}];
var customGeocoderOptions = {
autoComplete: true,
geocode: function (input) {
return when.resolve(geocoderResults1);
}
};
var geocoderResults2 = [{
displayName: '1',
destination: mockDestination
}, {
displayName: '2',
destination: mockDestination
}];
var customGeocoderOptions2 = {
autoComplete: true,
geocode: function (input) {
return when.resolve(geocoderResults2);
}
};
var noResultsGeocoder = {
autoComplete: true,
geocode: function (input) {
return when.resolve([]);
}
};
beforeAll(function() {
scene = createScene();
});
afterAll(function() {
scene.destroyForSpecs();
});
it('constructor sets expected properties', function() {
var flightDuration = 1234;
var viewModel = new GeocoderViewModel({
scene : scene,
flightDuration : flightDuration
});
expect(viewModel.scene).toBe(scene);
expect(viewModel.flightDuration).toBe(flightDuration);
expect(viewModel.keepExpanded).toBe(false);
});
it('can get and set flight duration', function() {
var viewModel = new GeocoderViewModel({
scene : scene
});
viewModel.flightDuration = 324;
expect(viewModel.flightDuration).toEqual(324);
expect(function() {
viewModel.flightDuration = -123;
}).toThrowDeveloperError();
});
it('throws is searchText is not a string', function() {
var viewModel = new GeocoderViewModel({
scene : scene,
geocoderServices : [customGeocoderOptions]
});
expect(function() {
viewModel.searchText = undefined;
}).toThrowDeveloperError();
});
it('moves camera when search command invoked', function() {
var viewModel = new GeocoderViewModel({
scene : scene,
geocoderServices : [customGeocoderOptions]
});
var cameraPosition = Cartesian3.clone(scene.camera.position);
viewModel.searchText = '220 Valley Creek Blvd, Exton, PA';
viewModel.search();
return pollToPromise(function() {
scene.tweens.update();
return !Cartesian3.equals(cameraPosition, scene.camera.position);
});
});
it('constructor throws without scene', function() {
expect(function() {
return new GeocoderViewModel();
}).toThrowDeveloperError();
});
it('raises the complete event camera finished', function() {
var viewModel = new GeocoderViewModel({
scene : scene,
flightDuration : 0,
geocoderServices : [customGeocoderOptions]
});
var spyListener = jasmine.createSpy('listener');
viewModel.complete.addEventListener(spyListener);
viewModel.searchText = '-1.0, -2.0';
viewModel.search();
expect(spyListener.calls.count()).toBe(1);
viewModel.flightDuration = 1.5;
viewModel.searchText = '2.0, 2.0';
viewModel.search();
return pollToPromise(function() {
scene.tweens.update();
return spyListener.calls.count() === 2;
});
});
it('can be created with a custom geocoder', function() {
expect(function() {
return new GeocoderViewModel({
scene : scene,
geocoderServices : [customGeocoderOptions]
});
}).not.toThrowDeveloperError();
});
it('automatic suggestions can be retrieved', function() {
var geocoder = new GeocoderViewModel({
scene : scene,
geocoderServices : [customGeocoderOptions]
});
geocoder._searchText = 'some_text';
geocoder._updateSearchSuggestions(geocoder);
expect(geocoder._suggestions.length).toEqual(2);
});
it('update search suggestions results in empty list if the query is empty', function() {
var geocoder = new GeocoderViewModel({
scene : scene,
geocoderServices : [customGeocoderOptions]
});
geocoder._searchText = '';
spyOn(geocoder, '_adjustSuggestionsScroll');
geocoder._updateSearchSuggestions(geocoder);
expect(geocoder._suggestions.length).toEqual(0);
});
it('can activate selected search suggestion', function () {
var geocoder = new GeocoderViewModel({
scene : scene,
geocoderServices : [customGeocoderOptions]
});
spyOn(geocoder, '_updateCamera');
spyOn(geocoder, '_adjustSuggestionsScroll');
var suggestion = {displayName: 'a', destination: {west: 0.0, east: 0.1, north: 0.1, south: -0.1}};
geocoder._selectedSuggestion = suggestion;
geocoder.activateSuggestion(suggestion);
expect(geocoder._searchText).toEqual('a');
});
it('if more than one geocoder service is provided, use first result from first geocode in array order', function () {
var geocoder = new GeocoderViewModel({
scene : scene,
geocoderServices : [noResultsGeocoder, customGeocoderOptions2]
});
geocoder._searchText = 'sthsnth'; // an empty query will prevent geocoding
spyOn(geocoder, '_updateCamera');
spyOn(geocoder, '_adjustSuggestionsScroll');
geocoder.search();
expect(geocoder._searchText).toEqual(geocoderResults2[0].displayName);
});
it('can update autoComplete suggestions list using multiple geocoders', function () {
var geocoder = new GeocoderViewModel({
scene : scene,
geocoderServices : [customGeocoderOptions, customGeocoderOptions2]
});
geocoder._searchText = 'sthsnth'; // an empty query will prevent geocoding
spyOn(geocoder, '_updateCamera');
spyOn(geocoder, '_adjustSuggestionsScroll');
geocoder._updateSearchSuggestions(geocoder);
expect(geocoder._suggestions.length).toEqual(geocoderResults1.length + geocoderResults2.length);
});
}, 'WebGL');
| atrawog/360-flight-explorer | Specs/Widgets/Geocoder/GeocoderViewModelSpec.js | JavaScript | apache-2.0 | 6,981 |
/*
* Licensed to the University of California, Berkeley under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package tachyon.worker;
import java.io.File;
import java.io.IOException;
import org.apache.thrift.TException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import tachyon.Constants;
import tachyon.TachyonURI;
import tachyon.TestUtils;
import tachyon.UnderFileSystem;
import tachyon.client.TachyonFS;
import tachyon.client.WriteType;
import tachyon.conf.TachyonConf;
import tachyon.master.LocalTachyonCluster;
import tachyon.master.MasterInfo;
import tachyon.thrift.ClientFileInfo;
import tachyon.thrift.FileAlreadyExistException;
import tachyon.thrift.FileDoesNotExistException;
import tachyon.thrift.InvalidPathException;
import tachyon.thrift.OutOfSpaceException;
import tachyon.util.CommonUtils;
/**
* Unit tests for tachyon.WorkerServiceHandler
*/
public class WorkerServiceHandlerTest {
private static final long WORKER_CAPACITY_BYTES = 10000;
private static final int USER_QUOTA_UNIT_BYTES = 100;
private LocalTachyonCluster mLocalTachyonCluster = null;
private MasterInfo mMasterInfo = null;
private WorkerServiceHandler mWorkerServiceHandler = null;
private TachyonFS mTfs = null;
private TachyonConf mMasterTachyonConf;
private TachyonConf mWorkerTachyonConf;
@After
public final void after() throws Exception {
mLocalTachyonCluster.stop();
}
@Before
public final void before() throws IOException {
mLocalTachyonCluster = new LocalTachyonCluster(WORKER_CAPACITY_BYTES, USER_QUOTA_UNIT_BYTES,
Constants.GB);
mLocalTachyonCluster.start();
mWorkerServiceHandler = mLocalTachyonCluster.getWorker().getWorkerServiceHandler();
mMasterInfo = mLocalTachyonCluster.getMasterInfo();
mTfs = mLocalTachyonCluster.getClient();
mMasterTachyonConf = mLocalTachyonCluster.getMasterTachyonConf();
mWorkerTachyonConf = mLocalTachyonCluster.getWorkerTachyonConf();
}
@Test
public void cancelBlockTest() throws TException, IOException {
final long userId = 1L;
final long blockId = 12345L;
String filename = mWorkerServiceHandler.requestBlockLocation(userId, blockId,
WORKER_CAPACITY_BYTES / 10L);
Assert.assertTrue(filename != null);
createBlockFile(filename, (int)(WORKER_CAPACITY_BYTES / 10L - 10L));
mWorkerServiceHandler.cancelBlock(userId, blockId);
Assert.assertFalse(new File(filename).exists());
CommonUtils.sleepMs(null,
TestUtils.getToMasterHeartBeatIntervalMs(mWorkerTachyonConf) * 2 + 10);
Assert.assertEquals(0, mMasterInfo.getUsedBytes());
}
@Test
public void cacheBlockTest() throws TException, IOException {
final long userId = 1L;
final int fileId = mTfs.createFile(new TachyonURI("/testFile1"));
final long blockId0 = mTfs.getBlockId(fileId, 0);
final long blockId1 = mTfs.getBlockId(fileId, 1);
String filename = mWorkerServiceHandler.requestBlockLocation(userId, blockId0,
WORKER_CAPACITY_BYTES / 10L);
Assert.assertTrue(filename != null);
createBlockFile(filename, (int)(WORKER_CAPACITY_BYTES / 10L - 10L));
mWorkerServiceHandler.cacheBlock(userId, blockId0);
Assert.assertEquals(WORKER_CAPACITY_BYTES / 10L - 10, mMasterInfo.getUsedBytes());
Exception exception = null;
try {
mWorkerServiceHandler.cacheBlock(userId, blockId1);
} catch (FileDoesNotExistException e) {
exception = e;
}
Assert.assertEquals(
new FileDoesNotExistException("Block doesn't exist! blockId:" + blockId1), exception);
}
private void createBlockFile(String filename, int fileLen)
throws IOException, InvalidPathException {
UnderFileSystem.get(filename, mMasterTachyonConf).mkdirs(CommonUtils.getParent(filename), true);
BlockHandler handler = BlockHandler.get(filename);
handler.append(0, TestUtils.getIncreasingByteArray(fileLen), 0, fileLen);
handler.close();
}
@Test
public void evictionTest() throws IOException, TException {
int fileId1 =
TestUtils.createByteFile(mTfs, "/file1", WriteType.MUST_CACHE,
(int) WORKER_CAPACITY_BYTES / 3);
Assert.assertTrue(fileId1 >= 0);
ClientFileInfo fileInfo1 = mMasterInfo.getClientFileInfo(new TachyonURI("/file1"));
Assert.assertEquals(100, fileInfo1.inMemoryPercentage);
int fileId2 =
TestUtils.createByteFile(mTfs, "/file2", WriteType.MUST_CACHE,
(int) WORKER_CAPACITY_BYTES / 3);
Assert.assertTrue(fileId2 >= 0);
fileInfo1 = mMasterInfo.getClientFileInfo(new TachyonURI("/file1"));
ClientFileInfo fileInfo2 = mMasterInfo.getClientFileInfo(new TachyonURI("/file2"));
Assert.assertEquals(100, fileInfo1.inMemoryPercentage);
Assert.assertEquals(100, fileInfo2.inMemoryPercentage);
int fileId3 =
TestUtils.createByteFile(mTfs, "/file3", WriteType.MUST_CACHE,
(int) WORKER_CAPACITY_BYTES / 2);
CommonUtils.sleepMs(null,
TestUtils.getToMasterHeartBeatIntervalMs(mWorkerTachyonConf) * 2 + 10);
fileInfo1 = mMasterInfo.getClientFileInfo(new TachyonURI("/file1"));
fileInfo2 = mMasterInfo.getClientFileInfo(new TachyonURI("/file2"));
ClientFileInfo fileInfo3 = mMasterInfo.getClientFileInfo(new TachyonURI("/file3"));
Assert.assertTrue(fileId3 >= 0);
Assert.assertEquals(0, fileInfo1.inMemoryPercentage);
Assert.assertEquals(100, fileInfo2.inMemoryPercentage);
Assert.assertEquals(100, fileInfo3.inMemoryPercentage);
}
@Test
public void requestSpaceTest() throws TException, IOException {
final long userId = 1L;
final long blockId1 = 12345L;
final long blockId2 = 12346L;
String filename = mWorkerServiceHandler.requestBlockLocation(userId, blockId1,
WORKER_CAPACITY_BYTES / 10L);
Assert.assertTrue(filename != null);
boolean result =
mWorkerServiceHandler.requestSpace(userId, blockId1, WORKER_CAPACITY_BYTES / 10L);
Assert.assertEquals(true, result);
result = mWorkerServiceHandler.requestSpace(userId, blockId1, WORKER_CAPACITY_BYTES);
Assert.assertEquals(false, result);
Exception exception = null;
try {
mWorkerServiceHandler.requestSpace(userId, blockId2, WORKER_CAPACITY_BYTES / 10L);
} catch (FileDoesNotExistException e) {
exception = e;
}
Assert.assertEquals(new FileDoesNotExistException(
"Temporary block file doesn't exist! blockId:" + blockId2), exception);
try {
mWorkerServiceHandler.requestBlockLocation(userId, blockId2, WORKER_CAPACITY_BYTES + 1);
} catch (OutOfSpaceException e) {
exception = e;
}
Assert.assertEquals(new OutOfSpaceException(String.format("Failed to allocate space for block!"
+ " blockId(%d) sizeBytes(%d)", blockId2, WORKER_CAPACITY_BYTES + 1)), exception);
}
@Test
public void totalOverCapacityRequestSpaceTest() throws TException {
final long userId1 = 1L;
final long blockId1 = 12345L;
final long userId2 = 2L;
final long blockId2 = 23456L;
String filePath1 = mWorkerServiceHandler.requestBlockLocation(userId1, blockId1,
WORKER_CAPACITY_BYTES / 2);
Assert.assertTrue(filePath1 != null);
String filePath2 = mWorkerServiceHandler.requestBlockLocation(userId2, blockId2,
WORKER_CAPACITY_BYTES / 2);
Assert.assertTrue(filePath2 != null);
Assert.assertFalse(mWorkerServiceHandler.requestSpace(userId1, blockId1,
WORKER_CAPACITY_BYTES / 2));
Assert.assertFalse(mWorkerServiceHandler.requestSpace(userId2, blockId2,
WORKER_CAPACITY_BYTES / 2));
}
}
| ooq/memory | core/src/test/java/tachyon/worker/WorkerServiceHandlerTest.java | Java | apache-2.0 | 8,284 |
#!/bin/sh
cd $(dirname $0)
../tools/minify.sh package.js -no-alias -output ../../build/enyo
| rwadkins/EnyoJS-NYC-Subway-Status | framework/js/enyo/minify/minify.sh | Shell | apache-2.0 | 95 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TobascoTest.GeneratedEntity
{
public class DifferentBase : EntityBase
{
}
}
| VictordeBaare/Tobasco | TobascoTest/GeneratedEntity/DifferentBase.cs | C# | apache-2.0 | 218 |
/*!
@file
Defines `boost::hana::none`.
@copyright Louis Dionne 2013-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_NONE_HPP
#define BOOST_HANA_NONE_HPP
#include <boost/hana/fwd/none.hpp>
#include <boost/hana/concept/searchable.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/functional/id.hpp>
#include <boost/hana/none_of.hpp>
BOOST_HANA_NAMESPACE_BEGIN
//! @cond
template <typename Xs>
constexpr auto none_t::operator()(Xs&& xs) const {
using S = typename hana::tag_of<Xs>::type;
using None = BOOST_HANA_DISPATCH_IF(none_impl<S>,
hana::Searchable<S>::value
);
#ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
static_assert(hana::Searchable<S>::value,
"hana::none(xs) requires 'xs' to be a Searchable");
#endif
return None::apply(static_cast<Xs&&>(xs));
}
//! @endcond
template <typename S, bool condition>
struct none_impl<S, when<condition>> : default_ {
template <typename Xs>
static constexpr auto apply(Xs&& xs)
{ return hana::none_of(static_cast<Xs&&>(xs), hana::id); }
};
BOOST_HANA_NAMESPACE_END
#endif // !BOOST_HANA_NONE_HPP
| Owldream/Ginseng | include/ginseng/3rd-party/boost/hana/none.hpp | C++ | apache-2.0 | 1,388 |
---
title: "Instalación del servidor Standalone"
weight: 3
---
Si planeas usar [Grid]({{< ref "/grid/_index.md" >}}) debes descargar el fichero
[selenium-server-standalone JAR](//www.seleniumhq.org/download/).
El jar _selenium-server-standalone_ nunca se carga, pero todos los componentes están disponibles a través de
[selenium-server](//repo1.maven.org/maven2/org/seleniumhq/selenium/selenium-server/).
El _standalone_ JAR contiene todo, incluso el servidor remoto de Selenium
y los enlaces del lado del cliente.
Ésto quiere decir que si usas el selenium-server-standalone jar
en tu proyecto, no tienes que añadir selenium-java
o un jar de navegador específico.
```xml
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.X</version>
</dependency>
```
| SeleniumHQ/docs | docs_source_files/content/selenium_installation/installing_standalone_server.es.md | Markdown | apache-2.0 | 828 |
# Copyright 2014 Google Inc.
#
# 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.
import unittest
import mock
class TestQuery(unittest.TestCase):
_PROJECT = 'PROJECT'
@staticmethod
def _get_target_class():
from google.cloud.datastore.query import Query
return Query
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def _make_client(self):
return _Client(self._PROJECT)
def test_ctor_defaults(self):
client = self._make_client()
query = self._make_one(client)
self.assertIs(query._client, client)
self.assertEqual(query.project, client.project)
self.assertIsNone(query.kind)
self.assertEqual(query.namespace, client.namespace)
self.assertIsNone(query.ancestor)
self.assertEqual(query.filters, [])
self.assertEqual(query.projection, [])
self.assertEqual(query.order, [])
self.assertEqual(query.distinct_on, [])
def test_ctor_explicit(self):
from google.cloud.datastore.key import Key
_PROJECT = 'OTHER_PROJECT'
_KIND = 'KIND'
_NAMESPACE = 'OTHER_NAMESPACE'
client = self._make_client()
ancestor = Key('ANCESTOR', 123, project=_PROJECT)
FILTERS = [('foo', '=', 'Qux'), ('bar', '<', 17)]
PROJECTION = ['foo', 'bar', 'baz']
ORDER = ['foo', 'bar']
DISTINCT_ON = ['foo']
query = self._make_one(
client,
kind=_KIND,
project=_PROJECT,
namespace=_NAMESPACE,
ancestor=ancestor,
filters=FILTERS,
projection=PROJECTION,
order=ORDER,
distinct_on=DISTINCT_ON,
)
self.assertIs(query._client, client)
self.assertEqual(query.project, _PROJECT)
self.assertEqual(query.kind, _KIND)
self.assertEqual(query.namespace, _NAMESPACE)
self.assertEqual(query.ancestor.path, ancestor.path)
self.assertEqual(query.filters, FILTERS)
self.assertEqual(query.projection, PROJECTION)
self.assertEqual(query.order, ORDER)
self.assertEqual(query.distinct_on, DISTINCT_ON)
def test_ctor_bad_projection(self):
BAD_PROJECTION = object()
self.assertRaises(TypeError, self._make_one, self._make_client(),
projection=BAD_PROJECTION)
def test_ctor_bad_order(self):
BAD_ORDER = object()
self.assertRaises(TypeError, self._make_one, self._make_client(),
order=BAD_ORDER)
def test_ctor_bad_distinct_on(self):
BAD_DISTINCT_ON = object()
self.assertRaises(TypeError, self._make_one, self._make_client(),
distinct_on=BAD_DISTINCT_ON)
def test_ctor_bad_filters(self):
FILTERS_CANT_UNPACK = [('one', 'two')]
self.assertRaises(ValueError, self._make_one, self._make_client(),
filters=FILTERS_CANT_UNPACK)
def test_namespace_setter_w_non_string(self):
query = self._make_one(self._make_client())
def _assign(val):
query.namespace = val
self.assertRaises(ValueError, _assign, object())
def test_namespace_setter(self):
_NAMESPACE = 'OTHER_NAMESPACE'
query = self._make_one(self._make_client())
query.namespace = _NAMESPACE
self.assertEqual(query.namespace, _NAMESPACE)
def test_kind_setter_w_non_string(self):
query = self._make_one(self._make_client())
def _assign(val):
query.kind = val
self.assertRaises(TypeError, _assign, object())
def test_kind_setter_wo_existing(self):
_KIND = 'KIND'
query = self._make_one(self._make_client())
query.kind = _KIND
self.assertEqual(query.kind, _KIND)
def test_kind_setter_w_existing(self):
_KIND_BEFORE = 'KIND_BEFORE'
_KIND_AFTER = 'KIND_AFTER'
query = self._make_one(self._make_client(), kind=_KIND_BEFORE)
self.assertEqual(query.kind, _KIND_BEFORE)
query.kind = _KIND_AFTER
self.assertEqual(query.project, self._PROJECT)
self.assertEqual(query.kind, _KIND_AFTER)
def test_ancestor_setter_w_non_key(self):
query = self._make_one(self._make_client())
def _assign(val):
query.ancestor = val
self.assertRaises(TypeError, _assign, object())
self.assertRaises(TypeError, _assign, ['KIND', 'NAME'])
def test_ancestor_setter_w_key(self):
from google.cloud.datastore.key import Key
_NAME = u'NAME'
key = Key('KIND', 123, project=self._PROJECT)
query = self._make_one(self._make_client())
query.add_filter('name', '=', _NAME)
query.ancestor = key
self.assertEqual(query.ancestor.path, key.path)
def test_ancestor_deleter_w_key(self):
from google.cloud.datastore.key import Key
key = Key('KIND', 123, project=self._PROJECT)
query = self._make_one(client=self._make_client(), ancestor=key)
del query.ancestor
self.assertIsNone(query.ancestor)
def test_add_filter_setter_w_unknown_operator(self):
query = self._make_one(self._make_client())
self.assertRaises(ValueError, query.add_filter,
'firstname', '~~', 'John')
def test_add_filter_w_known_operator(self):
query = self._make_one(self._make_client())
query.add_filter('firstname', '=', u'John')
self.assertEqual(query.filters, [('firstname', '=', u'John')])
def test_add_filter_w_all_operators(self):
query = self._make_one(self._make_client())
query.add_filter('leq_prop', '<=', u'val1')
query.add_filter('geq_prop', '>=', u'val2')
query.add_filter('lt_prop', '<', u'val3')
query.add_filter('gt_prop', '>', u'val4')
query.add_filter('eq_prop', '=', u'val5')
self.assertEqual(len(query.filters), 5)
self.assertEqual(query.filters[0], ('leq_prop', '<=', u'val1'))
self.assertEqual(query.filters[1], ('geq_prop', '>=', u'val2'))
self.assertEqual(query.filters[2], ('lt_prop', '<', u'val3'))
self.assertEqual(query.filters[3], ('gt_prop', '>', u'val4'))
self.assertEqual(query.filters[4], ('eq_prop', '=', u'val5'))
def test_add_filter_w_known_operator_and_entity(self):
from google.cloud.datastore.entity import Entity
query = self._make_one(self._make_client())
other = Entity()
other['firstname'] = u'John'
other['lastname'] = u'Smith'
query.add_filter('other', '=', other)
self.assertEqual(query.filters, [('other', '=', other)])
def test_add_filter_w_whitespace_property_name(self):
query = self._make_one(self._make_client())
PROPERTY_NAME = ' property with lots of space '
query.add_filter(PROPERTY_NAME, '=', u'John')
self.assertEqual(query.filters, [(PROPERTY_NAME, '=', u'John')])
def test_add_filter___key__valid_key(self):
from google.cloud.datastore.key import Key
query = self._make_one(self._make_client())
key = Key('Foo', project=self._PROJECT)
query.add_filter('__key__', '=', key)
self.assertEqual(query.filters, [('__key__', '=', key)])
def test_filter___key__not_equal_operator(self):
from google.cloud.datastore.key import Key
key = Key('Foo', project=self._PROJECT)
query = self._make_one(self._make_client())
query.add_filter('__key__', '<', key)
self.assertEqual(query.filters, [('__key__', '<', key)])
def test_filter___key__invalid_value(self):
query = self._make_one(self._make_client())
self.assertRaises(ValueError, query.add_filter, '__key__', '=', None)
def test_projection_setter_empty(self):
query = self._make_one(self._make_client())
query.projection = []
self.assertEqual(query.projection, [])
def test_projection_setter_string(self):
query = self._make_one(self._make_client())
query.projection = 'field1'
self.assertEqual(query.projection, ['field1'])
def test_projection_setter_non_empty(self):
query = self._make_one(self._make_client())
query.projection = ['field1', 'field2']
self.assertEqual(query.projection, ['field1', 'field2'])
def test_projection_setter_multiple_calls(self):
_PROJECTION1 = ['field1', 'field2']
_PROJECTION2 = ['field3']
query = self._make_one(self._make_client())
query.projection = _PROJECTION1
self.assertEqual(query.projection, _PROJECTION1)
query.projection = _PROJECTION2
self.assertEqual(query.projection, _PROJECTION2)
def test_keys_only(self):
query = self._make_one(self._make_client())
query.keys_only()
self.assertEqual(query.projection, ['__key__'])
def test_key_filter_defaults(self):
from google.cloud.datastore.key import Key
client = self._make_client()
query = self._make_one(client)
self.assertEqual(query.filters, [])
key = Key('Kind', 1234, project='project')
query.key_filter(key)
self.assertEqual(query.filters, [('__key__', '=', key)])
def test_key_filter_explicit(self):
from google.cloud.datastore.key import Key
client = self._make_client()
query = self._make_one(client)
self.assertEqual(query.filters, [])
key = Key('Kind', 1234, project='project')
query.key_filter(key, operator='>')
self.assertEqual(query.filters, [('__key__', '>', key)])
def test_order_setter_empty(self):
query = self._make_one(self._make_client(), order=['foo', '-bar'])
query.order = []
self.assertEqual(query.order, [])
def test_order_setter_string(self):
query = self._make_one(self._make_client())
query.order = 'field'
self.assertEqual(query.order, ['field'])
def test_order_setter_single_item_list_desc(self):
query = self._make_one(self._make_client())
query.order = ['-field']
self.assertEqual(query.order, ['-field'])
def test_order_setter_multiple(self):
query = self._make_one(self._make_client())
query.order = ['foo', '-bar']
self.assertEqual(query.order, ['foo', '-bar'])
def test_distinct_on_setter_empty(self):
query = self._make_one(self._make_client(), distinct_on=['foo', 'bar'])
query.distinct_on = []
self.assertEqual(query.distinct_on, [])
def test_distinct_on_setter_string(self):
query = self._make_one(self._make_client())
query.distinct_on = 'field1'
self.assertEqual(query.distinct_on, ['field1'])
def test_distinct_on_setter_non_empty(self):
query = self._make_one(self._make_client())
query.distinct_on = ['field1', 'field2']
self.assertEqual(query.distinct_on, ['field1', 'field2'])
def test_distinct_on_multiple_calls(self):
_DISTINCT_ON1 = ['field1', 'field2']
_DISTINCT_ON2 = ['field3']
query = self._make_one(self._make_client())
query.distinct_on = _DISTINCT_ON1
self.assertEqual(query.distinct_on, _DISTINCT_ON1)
query.distinct_on = _DISTINCT_ON2
self.assertEqual(query.distinct_on, _DISTINCT_ON2)
def test_fetch_defaults_w_client_attr(self):
from google.cloud.datastore.query import Iterator
client = self._make_client()
query = self._make_one(client)
iterator = query.fetch()
self.assertIsInstance(iterator, Iterator)
self.assertIs(iterator._query, query)
self.assertIs(iterator.client, client)
self.assertIsNone(iterator.max_results)
self.assertEqual(iterator._offset, 0)
def test_fetch_w_explicit_client(self):
from google.cloud.datastore.query import Iterator
client = self._make_client()
other_client = self._make_client()
query = self._make_one(client)
iterator = query.fetch(limit=7, offset=8, client=other_client)
self.assertIsInstance(iterator, Iterator)
self.assertIs(iterator._query, query)
self.assertIs(iterator.client, other_client)
self.assertEqual(iterator.max_results, 7)
self.assertEqual(iterator._offset, 8)
class TestIterator(unittest.TestCase):
@staticmethod
def _get_target_class():
from google.cloud.datastore.query import Iterator
return Iterator
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_constructor_defaults(self):
query = object()
client = object()
iterator = self._make_one(query, client)
self.assertFalse(iterator._started)
self.assertIs(iterator.client, client)
self.assertIsNotNone(iterator._item_to_value)
self.assertIsNone(iterator.max_results)
self.assertEqual(iterator.page_number, 0)
self.assertIsNone(iterator.next_page_token,)
self.assertEqual(iterator.num_results, 0)
self.assertIs(iterator._query, query)
self.assertIsNone(iterator._offset)
self.assertIsNone(iterator._end_cursor)
self.assertTrue(iterator._more_results)
def test_constructor_explicit(self):
query = object()
client = object()
limit = 43
offset = 9
start_cursor = b'8290\xff'
end_cursor = b'so20rc\ta'
iterator = self._make_one(
query, client, limit=limit, offset=offset,
start_cursor=start_cursor, end_cursor=end_cursor)
self.assertFalse(iterator._started)
self.assertIs(iterator.client, client)
self.assertIsNotNone(iterator._item_to_value)
self.assertEqual(iterator.max_results, limit)
self.assertEqual(iterator.page_number, 0)
self.assertEqual(iterator.next_page_token, start_cursor)
self.assertEqual(iterator.num_results, 0)
self.assertIs(iterator._query, query)
self.assertEqual(iterator._offset, offset)
self.assertEqual(iterator._end_cursor, end_cursor)
self.assertTrue(iterator._more_results)
def test__build_protobuf_empty(self):
from google.cloud.proto.datastore.v1 import query_pb2
from google.cloud.datastore.query import Query
client = _Client(None)
query = Query(client)
iterator = self._make_one(query, client)
pb = iterator._build_protobuf()
expected_pb = query_pb2.Query()
self.assertEqual(pb, expected_pb)
def test__build_protobuf_all_values(self):
from google.cloud.proto.datastore.v1 import query_pb2
from google.cloud.datastore.query import Query
client = _Client(None)
query = Query(client)
limit = 15
offset = 9
start_bytes = b'i\xb7\x1d'
start_cursor = 'abcd'
end_bytes = b'\xc3\x1c\xb3'
end_cursor = 'wxyz'
iterator = self._make_one(
query, client, limit=limit, offset=offset,
start_cursor=start_cursor, end_cursor=end_cursor)
self.assertEqual(iterator.max_results, limit)
iterator.num_results = 4
iterator._skipped_results = 1
pb = iterator._build_protobuf()
expected_pb = query_pb2.Query(
start_cursor=start_bytes,
end_cursor=end_bytes,
offset=offset - iterator._skipped_results,
)
expected_pb.limit.value = limit - iterator.num_results
self.assertEqual(pb, expected_pb)
def test__process_query_results(self):
from google.cloud.proto.datastore.v1 import query_pb2
iterator = self._make_one(None, None,
end_cursor='abcd')
self.assertIsNotNone(iterator._end_cursor)
entity_pbs = [
_make_entity('Hello', 9998, 'PRAHJEKT'),
]
cursor_as_bytes = b'\x9ai\xe7'
cursor = b'mmnn'
skipped_results = 4
more_results_enum = query_pb2.QueryResultBatch.NOT_FINISHED
response_pb = _make_query_response(
entity_pbs, cursor_as_bytes, more_results_enum, skipped_results)
result = iterator._process_query_results(response_pb)
self.assertEqual(result, entity_pbs)
self.assertEqual(iterator._skipped_results, skipped_results)
self.assertEqual(iterator.next_page_token, cursor)
self.assertTrue(iterator._more_results)
def test__process_query_results_done(self):
from google.cloud.proto.datastore.v1 import query_pb2
iterator = self._make_one(None, None,
end_cursor='abcd')
self.assertIsNotNone(iterator._end_cursor)
entity_pbs = [
_make_entity('World', 1234, 'PROJECT'),
]
cursor_as_bytes = b''
skipped_results = 44
more_results_enum = query_pb2.QueryResultBatch.NO_MORE_RESULTS
response_pb = _make_query_response(
entity_pbs, cursor_as_bytes, more_results_enum, skipped_results)
result = iterator._process_query_results(response_pb)
self.assertEqual(result, entity_pbs)
self.assertEqual(iterator._skipped_results, skipped_results)
self.assertIsNone(iterator.next_page_token)
self.assertFalse(iterator._more_results)
def test__process_query_results_bad_enum(self):
iterator = self._make_one(None, None)
more_results_enum = 999
response_pb = _make_query_response(
[], b'', more_results_enum, 0)
with self.assertRaises(ValueError):
iterator._process_query_results(response_pb)
def _next_page_helper(self, txn_id=None):
from google.cloud.iterator import Page
from google.cloud.proto.datastore.v1 import datastore_pb2
from google.cloud.proto.datastore.v1 import entity_pb2
from google.cloud.proto.datastore.v1 import query_pb2
from google.cloud.datastore.query import Query
more_enum = query_pb2.QueryResultBatch.NOT_FINISHED
result = _make_query_response([], b'', more_enum, 0)
project = 'prujekt'
ds_api = _make_datastore_api(result)
if txn_id is None:
client = _Client(project, datastore_api=ds_api)
else:
transaction = mock.Mock(id=txn_id, spec=['id'])
client = _Client(
project, datastore_api=ds_api, transaction=transaction)
query = Query(client)
iterator = self._make_one(query, client)
page = iterator._next_page()
self.assertIsInstance(page, Page)
self.assertIs(page._parent, iterator)
partition_id = entity_pb2.PartitionId(project_id=project)
if txn_id is None:
read_options = datastore_pb2.ReadOptions()
else:
read_options = datastore_pb2.ReadOptions(transaction=txn_id)
empty_query = query_pb2.Query()
ds_api.run_query.assert_called_once_with(
project, partition_id, read_options, query=empty_query)
def test__next_page(self):
self._next_page_helper()
def test__next_page_in_transaction(self):
txn_id = b'1xo1md\xe2\x98\x83'
self._next_page_helper(txn_id)
def test__next_page_no_more(self):
from google.cloud.datastore.query import Query
ds_api = _make_datastore_api()
client = _Client(None, datastore_api=ds_api)
query = Query(client)
iterator = self._make_one(query, client)
iterator._more_results = False
page = iterator._next_page()
self.assertIsNone(page)
ds_api.run_query.assert_not_called()
class Test__item_to_entity(unittest.TestCase):
def _call_fut(self, iterator, entity_pb):
from google.cloud.datastore.query import _item_to_entity
return _item_to_entity(iterator, entity_pb)
def test_it(self):
entity_pb = mock.sentinel.entity_pb
patch = mock.patch(
'google.cloud.datastore.helpers.entity_from_protobuf')
with patch as entity_from_protobuf:
result = self._call_fut(None, entity_pb)
self.assertIs(result, entity_from_protobuf.return_value)
entity_from_protobuf.assert_called_once_with(entity_pb)
class Test__pb_from_query(unittest.TestCase):
def _call_fut(self, query):
from google.cloud.datastore.query import _pb_from_query
return _pb_from_query(query)
def test_empty(self):
from google.cloud.proto.datastore.v1 import query_pb2
pb = self._call_fut(_Query())
self.assertEqual(list(pb.projection), [])
self.assertEqual(list(pb.kind), [])
self.assertEqual(list(pb.order), [])
self.assertEqual(list(pb.distinct_on), [])
self.assertEqual(pb.filter.property_filter.property.name, '')
cfilter = pb.filter.composite_filter
self.assertEqual(cfilter.op,
query_pb2.CompositeFilter.OPERATOR_UNSPECIFIED)
self.assertEqual(list(cfilter.filters), [])
self.assertEqual(pb.start_cursor, b'')
self.assertEqual(pb.end_cursor, b'')
self.assertEqual(pb.limit.value, 0)
self.assertEqual(pb.offset, 0)
def test_projection(self):
pb = self._call_fut(_Query(projection=['a', 'b', 'c']))
self.assertEqual([item.property.name for item in pb.projection],
['a', 'b', 'c'])
def test_kind(self):
pb = self._call_fut(_Query(kind='KIND'))
self.assertEqual([item.name for item in pb.kind], ['KIND'])
def test_ancestor(self):
from google.cloud.datastore.key import Key
from google.cloud.proto.datastore.v1 import query_pb2
ancestor = Key('Ancestor', 123, project='PROJECT')
pb = self._call_fut(_Query(ancestor=ancestor))
cfilter = pb.filter.composite_filter
self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND)
self.assertEqual(len(cfilter.filters), 1)
pfilter = cfilter.filters[0].property_filter
self.assertEqual(pfilter.property.name, '__key__')
ancestor_pb = ancestor.to_protobuf()
self.assertEqual(pfilter.value.key_value, ancestor_pb)
def test_filter(self):
from google.cloud.proto.datastore.v1 import query_pb2
query = _Query(filters=[('name', '=', u'John')])
query.OPERATORS = {
'=': query_pb2.PropertyFilter.EQUAL,
}
pb = self._call_fut(query)
cfilter = pb.filter.composite_filter
self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND)
self.assertEqual(len(cfilter.filters), 1)
pfilter = cfilter.filters[0].property_filter
self.assertEqual(pfilter.property.name, 'name')
self.assertEqual(pfilter.value.string_value, u'John')
def test_filter_key(self):
from google.cloud.datastore.key import Key
from google.cloud.proto.datastore.v1 import query_pb2
key = Key('Kind', 123, project='PROJECT')
query = _Query(filters=[('__key__', '=', key)])
query.OPERATORS = {
'=': query_pb2.PropertyFilter.EQUAL,
}
pb = self._call_fut(query)
cfilter = pb.filter.composite_filter
self.assertEqual(cfilter.op, query_pb2.CompositeFilter.AND)
self.assertEqual(len(cfilter.filters), 1)
pfilter = cfilter.filters[0].property_filter
self.assertEqual(pfilter.property.name, '__key__')
key_pb = key.to_protobuf()
self.assertEqual(pfilter.value.key_value, key_pb)
def test_order(self):
from google.cloud.proto.datastore.v1 import query_pb2
pb = self._call_fut(_Query(order=['a', '-b', 'c']))
self.assertEqual([item.property.name for item in pb.order],
['a', 'b', 'c'])
self.assertEqual([item.direction for item in pb.order],
[query_pb2.PropertyOrder.ASCENDING,
query_pb2.PropertyOrder.DESCENDING,
query_pb2.PropertyOrder.ASCENDING])
def test_distinct_on(self):
pb = self._call_fut(_Query(distinct_on=['a', 'b', 'c']))
self.assertEqual([item.name for item in pb.distinct_on],
['a', 'b', 'c'])
class _Query(object):
def __init__(self,
client=object(),
kind=None,
project=None,
namespace=None,
ancestor=None,
filters=(),
projection=(),
order=(),
distinct_on=()):
self._client = client
self.kind = kind
self.project = project
self.namespace = namespace
self.ancestor = ancestor
self.filters = filters
self.projection = projection
self.order = order
self.distinct_on = distinct_on
class _Client(object):
def __init__(self, project, datastore_api=None, namespace=None,
transaction=None):
self.project = project
self._datastore_api = datastore_api
self.namespace = namespace
self._transaction = transaction
@property
def current_transaction(self):
return self._transaction
def _make_entity(kind, id_, project):
from google.cloud.proto.datastore.v1 import entity_pb2
key = entity_pb2.Key()
key.partition_id.project_id = project
elem = key.path.add()
elem.kind = kind
elem.id = id_
return entity_pb2.Entity(key=key)
def _make_query_response(
entity_pbs, cursor_as_bytes, more_results_enum, skipped_results):
from google.cloud.proto.datastore.v1 import datastore_pb2
from google.cloud.proto.datastore.v1 import query_pb2
return datastore_pb2.RunQueryResponse(
batch=query_pb2.QueryResultBatch(
skipped_results=skipped_results,
end_cursor=cursor_as_bytes,
more_results=more_results_enum,
entity_results=[
query_pb2.EntityResult(entity=entity)
for entity in entity_pbs
],
),
)
def _make_datastore_api(result=None):
run_query = mock.Mock(return_value=result, spec=[])
return mock.Mock(run_query=run_query, spec=['run_query'])
| tartavull/google-cloud-python | datastore/tests/unit/test_query.py | Python | apache-2.0 | 26,883 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.management.internal.cli.commands;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyStore;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.ExitShellRequest;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.internal.ClassPathLoader;
import com.gemstone.gemfire.internal.DSFIDFactory;
import com.gemstone.gemfire.internal.lang.Initializer;
import com.gemstone.gemfire.internal.lang.StringUtils;
import com.gemstone.gemfire.internal.lang.SystemUtils;
import com.gemstone.gemfire.internal.util.IOUtils;
import com.gemstone.gemfire.internal.util.PasswordUtil;
import com.gemstone.gemfire.management.cli.CliMetaData;
import com.gemstone.gemfire.management.cli.ConverterHint;
import com.gemstone.gemfire.management.cli.Result;
import com.gemstone.gemfire.management.internal.JmxManagerLocatorRequest;
import com.gemstone.gemfire.management.internal.JmxManagerLocatorResponse;
import com.gemstone.gemfire.management.internal.SSLUtil;
import com.gemstone.gemfire.management.internal.cli.CliUtil;
import com.gemstone.gemfire.management.internal.cli.GfshParser;
import com.gemstone.gemfire.management.internal.cli.LogWrapper;
import com.gemstone.gemfire.management.internal.cli.annotation.CliArgument;
import com.gemstone.gemfire.management.internal.cli.converters.ConnectionEndpointConverter;
import com.gemstone.gemfire.management.internal.cli.domain.ConnectToLocatorResult;
import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
import com.gemstone.gemfire.management.internal.cli.result.ErrorResultData;
import com.gemstone.gemfire.management.internal.cli.result.InfoResultData;
import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder;
import com.gemstone.gemfire.management.internal.cli.result.TabularResultData;
import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
import com.gemstone.gemfire.management.internal.cli.shell.JMXConnectionException;
import com.gemstone.gemfire.management.internal.cli.shell.JmxOperationInvoker;
import com.gemstone.gemfire.management.internal.cli.shell.OperationInvoker;
import com.gemstone.gemfire.management.internal.cli.shell.jline.GfshHistory;
import com.gemstone.gemfire.management.internal.cli.util.CauseFinder;
import com.gemstone.gemfire.management.internal.cli.util.ConnectionEndpoint;
import com.gemstone.gemfire.management.internal.web.domain.LinkIndex;
import com.gemstone.gemfire.management.internal.web.http.support.SimpleHttpRequester;
import com.gemstone.gemfire.management.internal.web.shell.HttpOperationInvoker;
import com.gemstone.gemfire.management.internal.web.shell.RestHttpOperationInvoker;
/**
* @author Abhishek Chaudhari
*
* @since 7.0
*/
public class ShellCommands implements CommandMarker {
private Gfsh getGfsh() {
return Gfsh.getCurrentInstance();
}
@CliCommand(value = { CliStrings.EXIT, "quit" }, help = CliStrings.EXIT__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
public ExitShellRequest exit() throws IOException {
Gfsh gfshInstance = getGfsh();
gfshInstance.stop();
ExitShellRequest exitShellRequest = gfshInstance.getExitShellRequest();
if (exitShellRequest == null) {
// shouldn't really happen, but we'll fallback to this anyway
exitShellRequest = ExitShellRequest.NORMAL_EXIT;
}
return exitShellRequest;
}
// millis that connect --locator will wait for a response from the locator.
private final static int CONNECT_LOCATOR_TIMEOUT_MS = 60000; // see bug 45971
public static int getConnectLocatorTimeoutInMS() {
return ShellCommands.CONNECT_LOCATOR_TIMEOUT_MS;
}
@CliCommand(value = { CliStrings.CONNECT }, help = CliStrings.CONNECT__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_MANAGER})
public Result connect(
@CliOption(key = { CliStrings.CONNECT__LOCATOR },
unspecifiedDefaultValue = ConnectionEndpointConverter.DEFAULT_LOCATOR_ENDPOINTS,
optionContext = ConnectionEndpoint.LOCATOR_OPTION_CONTEXT,
help = CliStrings.CONNECT__LOCATOR__HELP) ConnectionEndpoint locatorTcpHostPort,
@CliOption(key = { CliStrings.CONNECT__JMX_MANAGER },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
optionContext = ConnectionEndpoint.JMXMANAGER_OPTION_CONTEXT,
help = CliStrings.CONNECT__JMX_MANAGER__HELP) ConnectionEndpoint memberRmiHostPort,
@CliOption(key = { CliStrings.CONNECT__USE_HTTP },
mandatory = false,
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.CONNECT__USE_HTTP__HELP) boolean useHttp,
@CliOption(key = { CliStrings.CONNECT__URL },
mandatory = false,
unspecifiedDefaultValue = CliStrings.CONNECT__DEFAULT_BASE_URL,
help = CliStrings.CONNECT__URL__HELP) String url,
@CliOption(key = { CliStrings.CONNECT__USERNAME },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__USERNAME__HELP) String userName,
@CliOption(key = { CliStrings.CONNECT__PASSWORD },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__PASSWORD__HELP) String password,
@CliOption(key = { CliStrings.CONNECT__KEY_STORE },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__KEY_STORE__HELP) String keystore,
@CliOption(key = { CliStrings.CONNECT__KEY_STORE_PASSWORD },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__KEY_STORE_PASSWORD__HELP) String keystorePassword,
@CliOption(key = { CliStrings.CONNECT__TRUST_STORE },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__TRUST_STORE__HELP) String truststore,
@CliOption(key = { CliStrings.CONNECT__TRUST_STORE_PASSWORD },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__TRUST_STORE_PASSWORD__HELP) String truststorePassword,
@CliOption(key = { CliStrings.CONNECT__SSL_CIPHERS },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__SSL_CIPHERS__HELP) String sslCiphers,
@CliOption(key = { CliStrings.CONNECT__SSL_PROTOCOLS },
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__SSL_PROTOCOLS__HELP) String sslProtocols,
@CliOption(key = CliStrings.CONNECT__SECURITY_PROPERTIES,
optionContext = ConverterHint.FILE_PATHSTRING,
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.CONNECT__SECURITY_PROPERTIES__HELP) final String gfSecurityPropertiesPath,
@CliOption(key = { CliStrings.CONNECT__USE_SSL },
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.CONNECT__USE_SSL__HELP) final boolean useSsl)
{
Result result;
String passwordToUse = decrypt(password);
String keystoreToUse = keystore;
String keystorePasswordToUse = keystorePassword;
String truststoreToUse = truststore;
String truststorePasswordToUse = truststorePassword;
String sslCiphersToUse = sslCiphers;
String sslProtocolsToUse = sslProtocols;
// TODO shouldn't the condition be (getGfsh() != null && getGfsh().isConnectedAndReady())?
// otherwise, we have potential NullPointerException on the line with getGfsh().getOperationInvoker()
//if (getGfsh() == null || getGfsh().isConnectedAndReady()) {
if (getGfsh() != null && getGfsh().isConnectedAndReady()) {
try {
result = ResultBuilder.createInfoResult("Already connected to: " + getGfsh().getOperationInvoker().toString());
} catch (Exception e) {
result = ResultBuilder.buildResult(ResultBuilder.createErrorResultData().setErrorCode(
ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage()));
}
} else if (useHttp) {
try{
final Map<String, String> sslConfigProps = this.readSSLConfiguration(useSsl, keystoreToUse,keystorePasswordToUse,
truststoreToUse, truststorePasswordToUse, sslCiphersToUse, sslProtocolsToUse, gfSecurityPropertiesPath);
if (useSsl) {
configureHttpsURLConnection(sslConfigProps);
if (url.startsWith("http:")) {
url = url.replace("http:", "https:");
}
}
LogWrapper.getInstance().warning(String.format("Sending HTTP request for Link Index at (%1$s)...", url.concat("/index")));
LinkIndex linkIndex = new SimpleHttpRequester(CONNECT_LOCATOR_TIMEOUT_MS).get(url.concat("/index"), LinkIndex.class);
LogWrapper.getInstance().warning(String.format("Received Link Index (%1$s)", linkIndex.toString()));
Gfsh gemfireShell = getGfsh();
HttpOperationInvoker operationInvoker = new RestHttpOperationInvoker(linkIndex, gemfireShell, url);
Initializer.init(operationInvoker);
gemfireShell.setOperationInvoker(operationInvoker);
LogWrapper.getInstance().info(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, operationInvoker.toString()));
Gfsh.redirectInternalJavaLoggers();
result = ResultBuilder.createInfoResult(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, operationInvoker.toString()));
} catch (IOException ioe) {
String errorMessage = ioe.getMessage();
result = ResultBuilder.createConnectionErrorResult(errorMessage);
ioe.printStackTrace();
} catch (Exception e) {
String errorMessage = e.getMessage();
result = ResultBuilder.createConnectionErrorResult(errorMessage);
e.printStackTrace();
}
} else {
boolean isConnectingViaLocator = false;
InfoResultData infoResultData = ResultBuilder.createInfoResultData();
ConnectionEndpoint hostPortToConnect = null;
try {
Gfsh gfshInstance = getGfsh();
// JMX Authentication Config
if (userName != null && userName.length() > 0) {
if (passwordToUse == null || passwordToUse.length() == 0) {
passwordToUse = gfshInstance.readWithMask("jmx password: ", '*');
}
if (passwordToUse == null || passwordToUse.length() == 0) {
throw new IllegalArgumentException(CliStrings.CONNECT__MSG__JMX_PASSWORD_MUST_BE_SPECIFIED);
}
}
final Map<String, String> sslConfigProps = this.readSSLConfiguration(useSsl, keystoreToUse,keystorePasswordToUse,
truststoreToUse, truststorePasswordToUse, sslCiphersToUse, sslProtocolsToUse, gfSecurityPropertiesPath);
if (memberRmiHostPort != null) {
hostPortToConnect = memberRmiHostPort;
Gfsh.println(CliStrings.format(CliStrings.CONNECT__MSG__CONNECTING_TO_MANAGER_AT_0, new Object[] {memberRmiHostPort.toString(false)}));
} else {
isConnectingViaLocator = true;
hostPortToConnect = locatorTcpHostPort;
Gfsh.println(CliStrings.format(CliStrings.CONNECT__MSG__CONNECTING_TO_LOCATOR_AT_0, new Object[] {locatorTcpHostPort.toString(false)}));
// Props required to configure a SocketCreator with SSL.
// Used for gfsh->locator connection & not needed for gfsh->manager connection
if (useSsl || !sslConfigProps.isEmpty()) {
//Fix for 51266 : Added an check for cluster-ssl-enabled proeprty
if(!sslConfigProps.containsKey(DistributionConfig.CLUSTER_SSL_ENABLED_NAME))
sslConfigProps.put(DistributionConfig.SSL_ENABLED_NAME, String.valueOf(true));
sslConfigProps.put(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
sslConfigProps.put(DistributionConfig.LOCATORS_NAME, "");
String sslInfoLogMsg = "Connecting to Locator via SSL.";
if (useSsl) {
sslInfoLogMsg = CliStrings.CONNECT__USE_SSL + " is set to true. " + sslInfoLogMsg;
}
gfshInstance.logToFile(sslInfoLogMsg, null);
}
ConnectToLocatorResult connectToLocatorResult = connectToLocator(locatorTcpHostPort.getHost(), locatorTcpHostPort.getPort(), CONNECT_LOCATOR_TIMEOUT_MS, sslConfigProps);
memberRmiHostPort = connectToLocatorResult.getMemberEndpoint();
hostPortToConnect = memberRmiHostPort;
Gfsh.printlnErr(connectToLocatorResult.getResultMessage());
// when locator is configured to use SSL (ssl-enabled=true) but manager is not (jmx-manager-ssl=false)
if ((useSsl || !sslConfigProps.isEmpty()) && !connectToLocatorResult.isJmxManagerSslEnabled()) {
gfshInstance.logInfo(CliStrings.CONNECT__USE_SSL + " is set to true. But JMX Manager doesn't support SSL, connecting without SSL.", null);
sslConfigProps.clear();
}
}
if (!sslConfigProps.isEmpty()) {
gfshInstance.logToFile("Connecting to manager via SSL.", null);
}
JmxOperationInvoker operationInvoker = new JmxOperationInvoker(memberRmiHostPort.getHost(), memberRmiHostPort.getPort(), userName, passwordToUse, sslConfigProps);
gfshInstance.setOperationInvoker(operationInvoker);
infoResultData.addLine(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, memberRmiHostPort.toString(false)));
LogWrapper.getInstance().info(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, memberRmiHostPort.toString(false)));
result = ResultBuilder.buildResult(infoResultData);
} catch (Exception e) {
// TODO - Abhishek: Refactor to use catch blocks for instanceof checks
Gfsh gfshInstance = Gfsh.getCurrentInstance();
String errorMessage = e.getMessage();
boolean logAsFine = false;
if (CauseFinder.indexOfCause(e, javax.naming.ServiceUnavailableException.class, false) != -1) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__SERVICE_UNAVAILABLE_ERROR, hostPortToConnect.toString(false));
} else if (e instanceof JMXConnectionException) {
JMXConnectionException jce = (JMXConnectionException)e;
if (jce.getExceptionType() == JMXConnectionException.MANAGER_NOT_FOUND_EXCEPTION) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__SERVICE_UNAVAILABLE_ERROR, hostPortToConnect.toString(false));
}
} else if ((e instanceof ConnectException) && isConnectingViaLocator) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__COULD_NOT_CONNECT_TO_LOCATOR_0, hostPortToConnect.toString(false));
} else if ( (e instanceof IllegalStateException) && isConnectingViaLocator) {
Throwable causeByType = CauseFinder.causeByType(e, ClassCastException.class, false);
if (causeByType != null) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__COULD_NOT_CONNECT_TO_LOCATOR_0_POSSIBLY_SSL_CONFIG_ERROR,
new Object[] { hostPortToConnect.toString(false)});
if (gfshInstance.isLoggingEnabled()) {
errorMessage += " "+ getGfshLogsCheckMessage(gfshInstance.getLogFilePath());
}
} else if (errorMessage == null) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__COULD_NOT_CONNECT_TO_LOCATOR_0, locatorTcpHostPort.toString(false));
if (gfshInstance.isLoggingEnabled()) {
errorMessage += " "+ getGfshLogsCheckMessage(gfshInstance.getLogFilePath());
}
}
} else if (e instanceof IOException) {
Throwable causeByType = CauseFinder.causeByType(e, java.rmi.ConnectIOException.class, false);
if (causeByType != null) {
// TODO - Abhishek : Is there a better way to know about a specific cause?
if (String.valueOf(causeByType.getMessage()).contains("non-JRMP server")) {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__COULD_NOT_CONNECT_TO_MANAGER_0_POSSIBLY_SSL_CONFIG_ERROR,
new Object[] { memberRmiHostPort.toString(false)});
logAsFine = true;
} else {
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__ERROR, new Object[] {memberRmiHostPort.toString(false), ""});
}
if (gfshInstance.isLoggingEnabled()) {
errorMessage += " "+ getGfshLogsCheckMessage(gfshInstance.getLogFilePath());
}
}
} else if (e instanceof SecurityException) {
// the default exception message is clear enough
String msgPart = StringUtils.isBlank(userName) && StringUtils.isBlank(passwordToUse) ? "" : "appropriate ";
errorMessage += ". Please specify "+msgPart+"values for --"+CliStrings.CONNECT__USERNAME+" and --"+CliStrings.CONNECT__PASSWORD;
} else{
errorMessage = CliStrings.format(CliStrings.CONNECT__MSG__ERROR, hostPortToConnect.toString(false), errorMessage);
}
result = ResultBuilder.createConnectionErrorResult(errorMessage);
if (logAsFine) {
LogWrapper.getInstance().fine(e.getMessage(), e);
} else {
LogWrapper.getInstance().severe(e.getMessage(), e);
}
}
Gfsh.redirectInternalJavaLoggers();
}
return result;
}
private String decrypt(String password) {
if (password != null) {
return PasswordUtil.decrypt(password);
}
return null;
}
private void configureHttpsURLConnection(Map<String, String> sslConfigProps) throws Exception {
String keystoreToUse = sslConfigProps.get(Gfsh.SSL_KEYSTORE);
String keystorePasswordToUse = sslConfigProps.get(Gfsh.SSL_KEYSTORE_PASSWORD);
String truststoreToUse = sslConfigProps.get(Gfsh.SSL_TRUSTSTORE);
String truststorePasswordToUse = sslConfigProps.get(Gfsh.SSL_TRUSTSTORE_PASSWORD);
// Ciphers are not passed to HttpsURLConnection. Could not find a clean way
// to pass this attribute to socket layer (see #51645)
String sslCiphersToUse = sslConfigProps.get(DistributionConfig.CLUSTER_SSL_CIPHERS_NAME);
String sslProtocolsToUse = sslConfigProps.get(DistributionConfig.CLUSTER_SSL_PROTOCOLS_NAME);
//Commenting the code to set cipher suites in GFSH rest connect (see #51645)
/*
if(sslCiphersToUse != null){
System.setProperty("https.cipherSuites", sslCiphersToUse);
}
*/
FileInputStream keyStoreStream = null;
FileInputStream trustStoreStream = null;
try{
KeyManagerFactory keyManagerFactory = null;
if (!StringUtils.isBlank(keystoreToUse)) {
KeyStore clientKeys = KeyStore.getInstance("JKS");
keyStoreStream = new FileInputStream(keystoreToUse);
clientKeys.load(keyStoreStream, keystorePasswordToUse.toCharArray());
keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeys, keystorePasswordToUse.toCharArray());
}
// load server public key
TrustManagerFactory trustManagerFactory = null;
if (!StringUtils.isBlank(truststoreToUse)) {
KeyStore serverPub = KeyStore.getInstance("JKS");
trustStoreStream = new FileInputStream(truststoreToUse);
serverPub.load(trustStoreStream, truststorePasswordToUse.toCharArray());
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(serverPub);
}
SSLContext ssl = SSLContext.getInstance(SSLUtil.getSSLAlgo(SSLUtil.readArray(sslProtocolsToUse)));
ssl.init(keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null,
trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
}finally{
if(keyStoreStream != null){
keyStoreStream.close();
}
if(trustStoreStream != null ){
trustStoreStream.close();
}
}
}
/**
* Common code to read SSL information. Used by JMX, Locator & HTTP mode connect
*/
private Map<String, String> readSSLConfiguration(boolean useSsl, String keystoreToUse, String keystorePasswordToUse,
String truststoreToUse, String truststorePasswordToUse, String sslCiphersToUse, String sslProtocolsToUse,
String gfSecurityPropertiesPath) throws IOException {
Gfsh gfshInstance = getGfsh();
final Map<String, String> sslConfigProps = new LinkedHashMap<String, String>();
// JMX SSL Config 1:
// First from gfsecurity properties file if it's specified OR
// if the default gfsecurity.properties exists useSsl==true
if (useSsl || gfSecurityPropertiesPath != null) {
// reference to hold resolved gfSecurityPropertiesPath
String gfSecurityPropertiesPathToUse = CliUtil.resolvePathname(gfSecurityPropertiesPath);
URL gfSecurityPropertiesUrl = null;
// Case 1: User has specified gfSecurity properties file
if (!StringUtils.isBlank(gfSecurityPropertiesPathToUse)) {
// User specified gfSecurity properties doesn't exist
if (!IOUtils.isExistingPathname(gfSecurityPropertiesPathToUse)) {
gfshInstance.printAsSevere(CliStrings.format(CliStrings.GEMFIRE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ", gfSecurityPropertiesPathToUse));
} else {
gfSecurityPropertiesUrl = new File(gfSecurityPropertiesPathToUse).toURI().toURL();
}
} else if (useSsl && gfSecurityPropertiesPath == null) {
// Case 2: User has specified to useSsl but hasn't specified
// gfSecurity properties file. Use default "gfsecurity.properties"
// in current dir, user's home or classpath
gfSecurityPropertiesUrl = getFileUrl("gfsecurity.properties");
}
// if 'gfSecurityPropertiesPath' OR gfsecurity.properties has resolvable path
if (gfSecurityPropertiesUrl != null) {
gfshInstance.logToFile("Using security properties file : "
+ CliUtil.decodeWithDefaultCharSet(gfSecurityPropertiesUrl.getPath()), null);
Map<String, String> gfsecurityProps = loadPropertiesFromURL(gfSecurityPropertiesUrl);
// command line options (if any) would override props in gfsecurity.properties
sslConfigProps.putAll(gfsecurityProps);
}
}
int numTimesPrompted = 0;
/*
* Using do-while here for a case when --use-ssl=true is specified but
* no SSL options were specified & there was no gfsecurity properties
* specified or readable in default gfsh directory.
*
* NOTE: 2nd round of prompting is done only when sslConfigProps map is
* empty & useSsl is true - so we won't over-write any previous values.
*/
do {
// JMX SSL Config 2: Now read the options
if (numTimesPrompted > 0) {
Gfsh.println("Please specify these SSL Configuration properties: ");
}
if (numTimesPrompted > 0) {
//NOTE: sslConfigProps map was empty
keystoreToUse = readText(gfshInstance, CliStrings.CONNECT__KEY_STORE + ": ");
}
if (keystoreToUse != null && keystoreToUse.length() > 0) {
if (keystorePasswordToUse == null || keystorePasswordToUse.length() == 0) {
// Check whether specified in gfsecurity props earlier
keystorePasswordToUse = sslConfigProps.get(Gfsh.SSL_KEYSTORE_PASSWORD);
if (keystorePasswordToUse == null || keystorePasswordToUse.length() == 0) {
// not even in properties file, prompt user for it
keystorePasswordToUse = readPassword(gfshInstance, CliStrings.CONNECT__KEY_STORE_PASSWORD + ": ");
sslConfigProps.put(Gfsh.SSL_KEYSTORE_PASSWORD, keystorePasswordToUse);
}
}else{//For cases where password is already part of command option
sslConfigProps.put(Gfsh.SSL_KEYSTORE_PASSWORD, keystorePasswordToUse);
}
sslConfigProps.put(Gfsh.SSL_KEYSTORE, keystoreToUse);
}
if (numTimesPrompted > 0) {
truststoreToUse = readText(gfshInstance, CliStrings.CONNECT__TRUST_STORE + ": ");
}
if (truststoreToUse != null && truststoreToUse.length() > 0) {
if (truststorePasswordToUse == null || truststorePasswordToUse.length() == 0) {
// Check whether specified in gfsecurity props earlier?
truststorePasswordToUse = sslConfigProps.get(Gfsh.SSL_TRUSTSTORE_PASSWORD);
if (truststorePasswordToUse == null || truststorePasswordToUse.length() == 0) {
// not even in properties file, prompt user for it
truststorePasswordToUse = readPassword(gfshInstance, CliStrings.CONNECT__TRUST_STORE_PASSWORD + ": ");
sslConfigProps.put(Gfsh.SSL_TRUSTSTORE_PASSWORD, truststorePasswordToUse);
}
}else{//For cases where password is already part of command option
sslConfigProps.put(Gfsh.SSL_TRUSTSTORE_PASSWORD, truststorePasswordToUse);
}
sslConfigProps.put(Gfsh.SSL_TRUSTSTORE, truststoreToUse);
}
if (numTimesPrompted > 0) {
sslCiphersToUse = readText(gfshInstance, CliStrings.CONNECT__SSL_CIPHERS + ": ");
}
if (sslCiphersToUse != null && sslCiphersToUse.length() > 0) {
//sslConfigProps.put(DistributionConfig.CLUSTER_SSL_CIPHERS_NAME, sslCiphersToUse);
sslConfigProps.put(Gfsh.SSL_ENABLED_CIPHERS, sslCiphersToUse);
}
if (numTimesPrompted > 0) {
sslProtocolsToUse = readText(gfshInstance, CliStrings.CONNECT__SSL_PROTOCOLS + ": ");
}
if (sslProtocolsToUse != null && sslProtocolsToUse.length() > 0) {
//sslConfigProps.put(DistributionConfig.CLUSTER_SSL_PROTOCOLS_NAME, sslProtocolsToUse);
sslConfigProps.put(Gfsh.SSL_ENABLED_PROTOCOLS, sslProtocolsToUse);
}
// SSL is required to be used but no SSL config found
} while(useSsl && sslConfigProps.isEmpty() && (0 == numTimesPrompted++) && !gfshInstance.isQuietMode());
return sslConfigProps;
}
private static String getGfshLogsCheckMessage(String logFilePath) {
return CliStrings.format(CliStrings.GFSH__PLEASE_CHECK_LOGS_AT_0, logFilePath);
}
private String readText(Gfsh gfsh, String textToPrompt) throws IOException {
if (!gfsh.isHeadlessMode() || !gfsh.isQuietMode()) {
return gfsh.interact(textToPrompt);
} else {
return null;
}
}
private String readPassword(Gfsh gfsh, String textToPrompt) throws IOException {
if (!gfsh.isHeadlessMode() || !gfsh.isQuietMode()) {
return gfsh.readWithMask(textToPrompt, '*');
} else {
return null;
}
}
/* package-private */ static Map<String, String> loadPropertiesFromURL(URL gfSecurityPropertiesUrl) {
Map<String, String> propsMap = Collections.emptyMap();
if (gfSecurityPropertiesUrl != null) {
InputStream inputStream = null;
try {
Properties props = new Properties();
inputStream = gfSecurityPropertiesUrl.openStream();
props.load(inputStream);
if (!props.isEmpty()) {
Set<String> jmxSpecificProps = new HashSet<String>();
propsMap = new LinkedHashMap<String, String>();
Set<Entry<Object, Object>> entrySet = props.entrySet();
for (Entry<Object, Object> entry : entrySet) {
String key = (String)entry.getKey();
if (key.endsWith(DistributionConfig.JMX_SSL_PROPS_SUFFIX)) {
key = key.substring(0, key.length() - DistributionConfig.JMX_SSL_PROPS_SUFFIX.length());
jmxSpecificProps.add(key);
propsMap.put(key, (String)entry.getValue());
} else if (!jmxSpecificProps.contains(key)) {// Prefer properties ending with "-jmx" over default SSL props.
propsMap.put(key, (String)entry.getValue());
}
}
props.clear();
jmxSpecificProps.clear();
}
} catch (IOException io) {
throw new RuntimeException(CliStrings.format(
CliStrings.CONNECT__MSG__COULD_NOT_READ_CONFIG_FROM_0,
CliUtil.decodeWithDefaultCharSet(gfSecurityPropertiesUrl.getPath())), io);
} finally {
IOUtils.close(inputStream);
}
}
return propsMap;
}
// Copied from DistributedSystem.java
private static URL getFileUrl(String fileName) {
File file = new File(fileName);
if (file.exists()) {
try {
return IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(file).toURI().toURL();
} catch (MalformedURLException ignore) {
}
}
file = new File(System.getProperty("user.home"), fileName);
if (file.exists()) {
try {
return IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(file).toURI().toURL();
} catch (MalformedURLException ignore) {
}
}
return ClassPathLoader.getLatest().getResource(ShellCommands.class, fileName);
}
public static ConnectToLocatorResult connectToLocator(String host, int port, int timeout, Map<String, String> props)
throws IOException
{
// register DSFID types first; invoked explicitly so that all message type
// initializations do not happen in first deserialization on a possibly
// "precious" thread
DSFIDFactory.registerTypes();
JmxManagerLocatorResponse locatorResponse = JmxManagerLocatorRequest.send(host, port, timeout, props);
if (StringUtils.isBlank(locatorResponse.getHost()) || locatorResponse.getPort() == 0) {
Throwable locatorResponseException = locatorResponse.getException();
String exceptionMessage = CliStrings.CONNECT__MSG__LOCATOR_COULD_NOT_FIND_MANAGER;
if (locatorResponseException != null) {
String locatorResponseExceptionMessage = locatorResponseException.getMessage();
locatorResponseExceptionMessage = (!StringUtils.isBlank(locatorResponseExceptionMessage)
? locatorResponseExceptionMessage : locatorResponseException.toString());
exceptionMessage = "Exception caused JMX Manager startup to fail because: '"
.concat(locatorResponseExceptionMessage).concat("'");
}
throw new IllegalStateException(exceptionMessage, locatorResponseException);
}
ConnectionEndpoint memberEndpoint = new ConnectionEndpoint(locatorResponse.getHost(), locatorResponse.getPort());
String resultMessage = CliStrings.format(CliStrings.CONNECT__MSG__CONNECTING_TO_MANAGER_AT_0,
memberEndpoint.toString(false));
return new ConnectToLocatorResult(memberEndpoint, resultMessage, locatorResponse.isJmxManagerSslEnabled());
}
@CliCommand(value = { CliStrings.DISCONNECT }, help = CliStrings.DISCONNECT__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX, CliStrings.TOPIC_GEMFIRE_MANAGER})
public Result disconnect() {
Result result = null;
if (getGfsh() != null && !getGfsh().isConnectedAndReady()) {
result = ResultBuilder.createInfoResult("Not connected.");
} else {
InfoResultData infoResultData = ResultBuilder.createInfoResultData();
try {
Gfsh gfshInstance = getGfsh();
if (gfshInstance.isConnectedAndReady()) {
OperationInvoker operationInvoker = gfshInstance.getOperationInvoker();
Gfsh.println("Disconnecting from: " + operationInvoker);
operationInvoker.stop();
infoResultData.addLine(CliStrings
.format(CliStrings.DISCONNECT__MSG__DISCONNECTED, operationInvoker.toString()));
LogWrapper.getInstance().info(CliStrings.format(CliStrings.DISCONNECT__MSG__DISCONNECTED, operationInvoker.toString()));
gfshInstance.setPromptPath(com.gemstone.gemfire.management.internal.cli.converters.RegionPathConverter.DEFAULT_APP_CONTEXT_PATH);
} else {
infoResultData.addLine(CliStrings.DISCONNECT__MSG__NOTCONNECTED);
}
result = ResultBuilder.buildResult(infoResultData);
} catch (Exception e) {
result = ResultBuilder.createConnectionErrorResult(CliStrings.format(CliStrings.DISCONNECT__MSG__ERROR, e.getMessage()));
}
}
return result;
}
@CliCommand(value = {CliStrings.DESCRIBE_CONNECTION}, help = CliStrings.DESCRIBE_CONNECTION__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_JMX})
public Result describeConnection() {
Result result = null;
try {
TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
Gfsh gfshInstance = getGfsh();
if (gfshInstance.isConnectedAndReady()) {
OperationInvoker operationInvoker = gfshInstance.getOperationInvoker();
// tabularResultData.accumulate("Monitored GemFire DS", operationInvoker.toString());
tabularResultData.accumulate("Connection Endpoints", operationInvoker.toString());
} else {
tabularResultData.accumulate("Connection Endpoints", "Not connected");
}
result = ResultBuilder.buildResult(tabularResultData);
} catch (Exception e) {
ErrorResultData errorResultData =
ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(e.getMessage());
result = ResultBuilder.buildResult(errorResultData);
}
return result;
}
@CliCommand(value = { CliStrings.ECHO }, help = CliStrings.ECHO__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result echo(
@CliOption(key = {CliStrings.ECHO__STR, ""},
unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
specifiedDefaultValue = "",
mandatory = true,
help = CliStrings.ECHO__STR__HELP) String stringToEcho) {
Result result = null;
if(stringToEcho.equals("$*")){
Gfsh gfshInstance = getGfsh();
Map<String, String> envMap = gfshInstance.getEnv();
Set< Entry<String, String> > setEnvMap = envMap.entrySet();
TabularResultData resultData = buildResultForEcho(setEnvMap);
result = ResultBuilder.buildResult(resultData);
} else {
result = ResultBuilder.createInfoResult(stringToEcho);
}
return result;
}
TabularResultData buildResultForEcho(Set< Entry<String, String> > propertyMap){
TabularResultData resultData = ResultBuilder.createTabularResultData();
Iterator <Entry<String, String>> it = propertyMap.iterator();
while(it.hasNext()){
Entry<String, String> setEntry = it.next();
resultData.accumulate("Property", setEntry.getKey());
resultData.accumulate("Value", String.valueOf(setEntry.getValue()));
}
return resultData;
}
@CliCommand(value = { CliStrings.SET_VARIABLE }, help = CliStrings.SET_VARIABLE__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result setVariable(
@CliOption(key = CliStrings.SET_VARIABLE__VAR,
mandatory=true,
help = CliStrings.SET_VARIABLE__VAR__HELP)
String var,
@CliOption(key = CliStrings.SET_VARIABLE__VALUE,
mandatory=true,
help = CliStrings.SET_VARIABLE__VALUE__HELP)
String value) {
Result result = null;
try {
getGfsh().setEnvProperty(var, String.valueOf(value));
result = ResultBuilder.createInfoResult("Value for variable "+var+" is now: "+value+".");
} catch (IllegalArgumentException e) {
ErrorResultData errorResultData = ResultBuilder.createErrorResultData();
errorResultData.addLine(e.getMessage());
result = ResultBuilder.buildResult(errorResultData);
}
return result;
}
//Enable when "use region" command is required. See #46110
// @CliCommand(value = { CliStrings.USE_REGION }, help = CliStrings.USE_REGION__HELP)
// @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_REGION})
// public Result useRegion(
// @CliArgument(name = CliStrings.USE_REGION__REGION,
// unspecifiedDefaultValue = "/",
// argumentContext = CliStrings.PARAM_CONTEXT_REGIONPATH,
// help = CliStrings.USE_REGION__REGION__HELP)
// String toRegion) {
// Gfsh gfsh = Gfsh.getCurrentInstance();
//
// gfsh.setPromptPath(toRegion);
// return ResultBuilder.createInfoResult("");
// }
@CliCommand(value = { CliStrings.DEBUG }, help = CliStrings.DEBUG__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL })
public Result debug(
@CliOption(key = CliStrings.DEBUG__STATE,
unspecifiedDefaultValue = "OFF",
mandatory = true,
optionContext = "debug",
help = CliStrings.DEBUG__STATE__HELP)
String state) {
Gfsh gfshInstance = Gfsh.getCurrentInstance();
if (gfshInstance != null) {
// Handle state
if (state.equalsIgnoreCase("ON")) {
gfshInstance.setDebug(true);
} else if(state.equalsIgnoreCase("OFF")){
gfshInstance.setDebug(false);
}else{
return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.DEBUG__MSG_0_INVALID_STATE_VALUE,state)) ;
}
} else {
ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(
CliStrings.ECHO__MSG__NO_GFSH_INSTANCE);
return ResultBuilder.buildResult(errorResultData);
}
return ResultBuilder.createInfoResult(CliStrings.DEBUG__MSG_DEBUG_STATE_IS + state );
}
@CliCommand(value = CliStrings.HISTORY, help = CliStrings.HISTORY__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GFSH })
public Result history(
@CliOption(key = { CliStrings.HISTORY__FILE }, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.HISTORY__FILE__HELP)
String saveHistoryTo,
@CliOption(key = { CliStrings.HISTORY__CLEAR }, specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false", help = CliStrings.HISTORY__CLEAR__HELP) Boolean clearHistory) {
//process clear history
if (clearHistory ) {
return executeClearHistory();
}else {
//Process file option
Gfsh gfsh = Gfsh.getCurrentInstance();
ErrorResultData errorResultData = null;
StringBuilder contents = new StringBuilder();
Writer output = null;
int historySize = gfsh.getHistorySize();
String historySizeString = String.valueOf(historySize);
int historySizeWordLength = historySizeString.length();
GfshHistory gfshHistory = gfsh.getGfshHistory();
List<?> gfshHistoryList = gfshHistory.getHistoryList();
Iterator<?> it = gfshHistoryList.iterator();
boolean flagForLineNumbers = (saveHistoryTo != null && saveHistoryTo
.length() > 0) ? false : true;
long lineNumber = 0;
while (it.hasNext()) {
String line = (String) it.next();
if (line.isEmpty() == false) {
if (flagForLineNumbers) {
lineNumber++;
contents.append(String.format("%" + historySizeWordLength + "s ",
lineNumber));
}
contents.append(line);
contents.append(GfshParser.LINE_SEPARATOR);
}
}
try {
// write to a user file
if (saveHistoryTo != null && saveHistoryTo.length() > 0) {
File saveHistoryToFile = new File(saveHistoryTo);
output = new BufferedWriter(new FileWriter(saveHistoryToFile));
if (!saveHistoryToFile.exists()) {
errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(CliStrings.HISTORY__MSG__FILE_DOES_NOT_EXISTS);
return ResultBuilder.buildResult(errorResultData);
}
if (!saveHistoryToFile.isFile()) {
errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(CliStrings.HISTORY__MSG__FILE_SHOULD_NOT_BE_DIRECTORY);
return ResultBuilder.buildResult(errorResultData);
}
if (!saveHistoryToFile.canWrite()) {
errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine(CliStrings.HISTORY__MSG__FILE_CANNOT_BE_WRITTEN);
return ResultBuilder.buildResult(errorResultData);
}
output.write(contents.toString());
}
} catch (IOException ex) {
return ResultBuilder.createInfoResult("File error " + ex.getMessage()
+ " for file " + saveHistoryTo);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
errorResultData = ResultBuilder.createErrorResultData()
.setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
.addLine("exception in closing file");
return ResultBuilder.buildResult(errorResultData);
}
}
if (saveHistoryTo != null && saveHistoryTo.length() > 0) {
// since written to file no need to display the content
return ResultBuilder.createInfoResult("Wrote successfully to file "
+ saveHistoryTo);
} else {
return ResultBuilder.createInfoResult(contents.toString());
}
}
}
Result executeClearHistory(){
try{
Gfsh gfsh = Gfsh.getCurrentInstance();
GfshHistory gfshHistory = gfsh.getGfshHistory();
gfshHistory.clear();
}catch(Exception e){
LogWrapper.getInstance().info(CliUtil.stackTraceAsString(e) );
return ResultBuilder.createGemFireErrorResult("Exception occured while clearing history " + e.getMessage());
}
return ResultBuilder.createInfoResult(CliStrings.HISTORY__MSG__CLEARED_HISTORY);
}
@CliCommand(value = { CliStrings.RUN }, help = CliStrings.RUN__HELP)
@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result executeScript(
@CliOption(key = CliStrings.RUN__FILE,
optionContext = ConverterHint.FILE,
mandatory = true,
help = CliStrings.RUN__FILE__HELP)
File file,
@CliOption(key = { CliStrings.RUN__QUIET },
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.RUN__QUIET__HELP)
boolean quiet,
@CliOption(key = { CliStrings.RUN__CONTINUEONERROR },
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.RUN__CONTINUEONERROR__HELP)
boolean continueOnError) {
Result result = null;
Gfsh gfsh = Gfsh.getCurrentInstance();
try {
result = gfsh.executeScript(file, quiet, continueOnError);
} catch (IllegalArgumentException e) {
result = ResultBuilder.createShellClientErrorResult(e.getMessage());
} // let CommandProcessingException go to the caller
return result;
}
@CliCommand(value = CliStrings.ENCRYPT, help = CliStrings.ENCRYPT__HELP)
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEMFIRE_DEBUG_UTIL})
public Result encryptPassword(
@CliOption(key = CliStrings.ENCRYPT_STRING,
help = CliStrings.ENCRYPT_STRING__HELP,
mandatory = true)
String stringToEncrypt) {
return ResultBuilder.createInfoResult(PasswordUtil.encrypt(stringToEncrypt, false/*echo*/));
}
@CliCommand(value = { CliStrings.VERSION }, help = CliStrings.VERSION__HELP)
@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result version(
@CliOption(key = { CliStrings.VERSION__FULL },
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.VERSION__FULL__HELP)
boolean full) {
Gfsh gfsh = Gfsh.getCurrentInstance();
return ResultBuilder.createInfoResult(gfsh.getVersion(full));
}
@CliCommand(value = { CliStrings.SLEEP }, help = CliStrings.SLEEP__HELP)
@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result sleep(
@CliOption(key = { CliStrings.SLEEP__TIME },
unspecifiedDefaultValue = "3",
help = CliStrings.SLEEP__TIME__HELP)
double time) {
try {
LogWrapper.getInstance().fine("Sleeping for " + time + "seconds.");
Thread.sleep( Math.round(time * 1000) );
} catch (InterruptedException ignorable) {}
return ResultBuilder.createInfoResult("");
}
@CliCommand(value = { CliStrings.SH }, help = CliStrings.SH__HELP)
@CliMetaData(shellOnly=true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result sh(
@CliArgument(name = CliStrings.SH__COMMAND,
mandatory = true,
help = CliStrings.SH__COMMAND__HELP)
String command,
@CliOption(key = CliStrings.SH__USE_CONSOLE,
specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
help = CliStrings.SH__USE_CONSOLE__HELP)
boolean useConsole) {
Result result = null;
try {
result = ResultBuilder.buildResult(executeCommand(Gfsh.getCurrentInstance(), command, useConsole));
} catch (IllegalStateException e) {
result = ResultBuilder.createUserErrorResult(e.getMessage());
LogWrapper.getInstance().warning("Unable to execute command \"" + command + "\". Reason:" + e.getMessage() + ".");
} catch (IOException e) {
result = ResultBuilder.createUserErrorResult(e.getMessage());
LogWrapper.getInstance().warning("Unable to execute command \"" + command + "\". Reason:" + e.getMessage() + ".");
}
return result;
}
private static InfoResultData executeCommand(Gfsh gfsh, String userCommand, boolean useConsole) throws IOException {
InfoResultData infoResultData = ResultBuilder.createInfoResultData();
String cmdToExecute = userCommand;
String cmdExecutor = "/bin/sh";
String cmdExecutorOpt = "-c";
if (SystemUtils.isWindows()) {
cmdExecutor = "cmd";
cmdExecutorOpt = "/c";
} else if (useConsole) {
cmdToExecute = cmdToExecute + " </dev/tty >/dev/tty";
}
String[] commandArray = { cmdExecutor, cmdExecutorOpt, cmdToExecute };
ProcessBuilder builder = new ProcessBuilder();
builder.command(commandArray);
builder.directory();
builder.redirectErrorStream();
Process proc = builder.start();
BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String lineRead = "";
while ((lineRead = input.readLine()) != null) {
infoResultData.addLine(lineRead);
}
proc.getOutputStream().close();
try {
if (proc.waitFor() != 0) {
gfsh.logWarning("The command '" + userCommand + "' did not complete successfully", null);
}
} catch (final InterruptedException e) {
throw new IllegalStateException(e);
}
return infoResultData;
}
@CliAvailabilityIndicator({CliStrings.CONNECT, CliStrings.DISCONNECT, CliStrings.DESCRIBE_CONNECTION})
public boolean isAvailable() {
return true;
}
}
| robertgeiger/incubator-geode | gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommands.java | Java | apache-2.0 | 49,854 |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2008-2022 the original author or authors.
*
* 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 org.codehaus.griffon.converter;
import griffon.converter.ConversionException;
import org.codehaus.griffon.ConversionSupport;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Collections;
import java.util.Locale;
import java.util.stream.Stream;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Andres Almiray
*/
public class LocaleConverterTest extends ConversionSupport {
private static final Locale DE_CH_BASEL = new Locale("de", "CH", "Basel");
@ParameterizedTest
@MethodSource("where_bidirectional")
public void bidirectionalConversion(Object value, Locale locale, String literal) {
// given:
LocaleConverter formatter = new LocaleConverter();
// when:
Locale lcl = formatter.fromObject(value);
String str = formatter.toString(locale);
// then:
assertThat(str, equalTo(literal));
assertThat(lcl, equalTo(locale));
}
@ParameterizedTest
@MethodSource("where_invalid")
public void checkInvalidConversion(Object value) {
// given:
LocaleConverter converter = new LocaleConverter();
// when:
assertThrows(ConversionException.class, () -> converter.fromObject(value));
}
public static Stream<Arguments> where_bidirectional() {
return Stream.of(
Arguments.of(null, null, null),
Arguments.of("", null, null),
Arguments.of(" ", null, null),
Arguments.of(Locale.ENGLISH, Locale.ENGLISH, "en"),
Arguments.of("en", Locale.ENGLISH, "en")
);
}
public static Stream<Arguments> where_invalid() {
return Stream.of(
Arguments.of(1),
Arguments.of(new Object()),
Arguments.of(Collections.emptyList()),
Arguments.of(Collections.emptyMap())
);
}
}
| griffon/griffon | subprojects/griffon-converter-impl/src/test/java/org/codehaus/griffon/converter/LocaleConverterTest.java | Java | apache-2.0 | 2,754 |
#ifndef PYIU_PACKED_H
#define PYIU_PACKED_H
#ifdef __cplusplus
extern "C" {
#endif
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "helpercompat.h"
typedef struct {
PyObject_HEAD
PyObject *func;
#if PyIU_USE_VECTORCALL
vectorcallfunc vectorcall;
#endif
} PyIUObject_Packed;
extern PyTypeObject PyIUType_Packed;
#ifdef __cplusplus
}
#endif
#endif
| MSeifert04/iteration_utilities | src/iteration_utilities/_iteration_utilities/packed.h | C | apache-2.0 | 370 |
/*
ChibiOS/RT - Copyright (C) 2006-2014 Giovanni Di Sirio
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.
*/
/**
* @file templates/halconf.h
* @brief HAL configuration header.
* @details HAL configuration file, this file allows to enable or disable the
* various device drivers from your application. You may also use
* this file in order to override the device drivers default settings.
*
* @addtogroup HAL_CONF
* @{
*/
#ifndef _HALCONF_H_
#define _HALCONF_H_
#include "mcuconf.h"
/**
* @brief Enables the PAL subsystem.
*/
#if !defined(HAL_USE_PAL) || defined(__DOXYGEN__)
#define HAL_USE_PAL TRUE
#endif
/**
* @brief Enables the ADC subsystem.
*/
#if !defined(HAL_USE_ADC) || defined(__DOXYGEN__)
#define HAL_USE_ADC FALSE
#endif
/**
* @brief Enables the CAN subsystem.
*/
#if !defined(HAL_USE_CAN) || defined(__DOXYGEN__)
#define HAL_USE_CAN FALSE
#endif
/**
* @brief Enables the EXT subsystem.
*/
#if !defined(HAL_USE_EXT) || defined(__DOXYGEN__)
#define HAL_USE_EXT FALSE
#endif
/**
* @brief Enables the GPT subsystem.
*/
#if !defined(HAL_USE_GPT) || defined(__DOXYGEN__)
#define HAL_USE_GPT FALSE
#endif
/**
* @brief Enables the I2C subsystem.
*/
#if !defined(HAL_USE_I2C) || defined(__DOXYGEN__)
#define HAL_USE_I2C TRUE
#endif
/**
* @brief Enables the I2S subsystem.
*/
#if !defined(HAL_USE_I2S) || defined(__DOXYGEN__)
#define HAL_USE_I2S FALSE
#endif
/**
* @brief Enables the ICU subsystem.
*/
#if !defined(HAL_USE_ICU) || defined(__DOXYGEN__)
#define HAL_USE_ICU FALSE
#endif
/**
* @brief Enables the MAC subsystem.
*/
#if !defined(HAL_USE_MAC) || defined(__DOXYGEN__)
#define HAL_USE_MAC FALSE
#endif
/**
* @brief Enables the MMC_SPI subsystem.
*/
#if !defined(HAL_USE_MMC_SPI) || defined(__DOXYGEN__)
#define HAL_USE_MMC_SPI FALSE
#endif
/**
* @brief Enables the PWM subsystem.
*/
#if !defined(HAL_USE_PWM) || defined(__DOXYGEN__)
#define HAL_USE_PWM FALSE
#endif
/**
* @brief Enables the RTC subsystem.
*/
#if !defined(HAL_USE_RTC) || defined(__DOXYGEN__)
#define HAL_USE_RTC FALSE
#endif
/**
* @brief Enables the SDC subsystem.
*/
#if !defined(HAL_USE_SDC) || defined(__DOXYGEN__)
#define HAL_USE_SDC FALSE
#endif
/**
* @brief Enables the SERIAL subsystem.
*/
#if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__)
#define HAL_USE_SERIAL FALSE
#endif
/**
* @brief Enables the SERIAL over USB subsystem.
*/
#if !defined(HAL_USE_SERIAL_USB) || defined(__DOXYGEN__)
#define HAL_USE_SERIAL_USB FALSE
#endif
/**
* @brief Enables the SPI subsystem.
*/
#if !defined(HAL_USE_SPI) || defined(__DOXYGEN__)
#define HAL_USE_SPI FALSE
#endif
/**
* @brief Enables the UART subsystem.
*/
#if !defined(HAL_USE_UART) || defined(__DOXYGEN__)
#define HAL_USE_UART FALSE
#endif
/**
* @brief Enables the USB subsystem.
*/
#if !defined(HAL_USE_USB) || defined(__DOXYGEN__)
#define HAL_USE_USB FALSE
#endif
/*===========================================================================*/
/* ADC driver related settings. */
/*===========================================================================*/
/**
* @brief Enables synchronous APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(ADC_USE_WAIT) || defined(__DOXYGEN__)
#define ADC_USE_WAIT TRUE
#endif
/**
* @brief Enables the @p adcAcquireBus() and @p adcReleaseBus() APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(ADC_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define ADC_USE_MUTUAL_EXCLUSION TRUE
#endif
/*===========================================================================*/
/* CAN driver related settings. */
/*===========================================================================*/
/**
* @brief Sleep mode related APIs inclusion switch.
*/
#if !defined(CAN_USE_SLEEP_MODE) || defined(__DOXYGEN__)
#define CAN_USE_SLEEP_MODE TRUE
#endif
/*===========================================================================*/
/* I2C driver related settings. */
/*===========================================================================*/
/**
* @brief Enables the mutual exclusion APIs on the I2C bus.
*/
#if !defined(I2C_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define I2C_USE_MUTUAL_EXCLUSION TRUE
#endif
/*===========================================================================*/
/* MAC driver related settings. */
/*===========================================================================*/
/**
* @brief Enables an event sources for incoming packets.
*/
#if !defined(MAC_USE_ZERO_COPY) || defined(__DOXYGEN__)
#define MAC_USE_ZERO_COPY FALSE
#endif
/**
* @brief Enables an event sources for incoming packets.
*/
#if !defined(MAC_USE_EVENTS) || defined(__DOXYGEN__)
#define MAC_USE_EVENTS TRUE
#endif
/*===========================================================================*/
/* MMC_SPI driver related settings. */
/*===========================================================================*/
/**
* @brief Delays insertions.
* @details If enabled this options inserts delays into the MMC waiting
* routines releasing some extra CPU time for the threads with
* lower priority, this may slow down the driver a bit however.
* This option is recommended also if the SPI driver does not
* use a DMA channel and heavily loads the CPU.
*/
#if !defined(MMC_NICE_WAITING) || defined(__DOXYGEN__)
#define MMC_NICE_WAITING TRUE
#endif
/*===========================================================================*/
/* SDC driver related settings. */
/*===========================================================================*/
/**
* @brief Number of initialization attempts before rejecting the card.
* @note Attempts are performed at 10mS intervals.
*/
#if !defined(SDC_INIT_RETRY) || defined(__DOXYGEN__)
#define SDC_INIT_RETRY 100
#endif
/**
* @brief Include support for MMC cards.
* @note MMC support is not yet implemented so this option must be kept
* at @p FALSE.
*/
#if !defined(SDC_MMC_SUPPORT) || defined(__DOXYGEN__)
#define SDC_MMC_SUPPORT FALSE
#endif
/**
* @brief Delays insertions.
* @details If enabled this options inserts delays into the MMC waiting
* routines releasing some extra CPU time for the threads with
* lower priority, this may slow down the driver a bit however.
*/
#if !defined(SDC_NICE_WAITING) || defined(__DOXYGEN__)
#define SDC_NICE_WAITING TRUE
#endif
/*===========================================================================*/
/* SERIAL driver related settings. */
/*===========================================================================*/
/**
* @brief Default bit rate.
* @details Configuration parameter, this is the baud rate selected for the
* default configuration.
*/
#if !defined(SERIAL_DEFAULT_BITRATE) || defined(__DOXYGEN__)
#define SERIAL_DEFAULT_BITRATE 38400
#endif
/**
* @brief Serial buffers size.
* @details Configuration parameter, you can change the depth of the queue
* buffers depending on the requirements of your application.
* @note The default is 64 bytes for both the transmission and receive
* buffers.
*/
#if !defined(SERIAL_BUFFERS_SIZE) || defined(__DOXYGEN__)
#define SERIAL_BUFFERS_SIZE 16
#endif
/*===========================================================================*/
/* SPI driver related settings. */
/*===========================================================================*/
/**
* @brief Enables synchronous APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(SPI_USE_WAIT) || defined(__DOXYGEN__)
#define SPI_USE_WAIT TRUE
#endif
/**
* @brief Enables the @p spiAcquireBus() and @p spiReleaseBus() APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(SPI_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define SPI_USE_MUTUAL_EXCLUSION TRUE
#endif
#endif /* _HALCONF_H_ */
/** @} */
| marcoveeneman/ChibiOS-Tiva | testhal/KINETIS/I2C/halconf.h | C | apache-2.0 | 9,296 |
<!---
Copyright 2015 Karl Bennett
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.
-->
smt-waiting-spring
===========
[](https://travis-ci.org/shiver-me-timbers/smt-waiting-parent) [](https://coveralls.io/github/shiver-me-timbers/smt-waiting-parent?branch=master) [](https://maven-badges.herokuapp.com/maven-central/com.github.shiver-me-timbers/smt-waiting-spring/)
This library contains the [`SpringOptions`](src/main/java/shiver/me/timbers/waiting/SpringOptions.java) that can be
used to configure a [`Waiter`](../smt-waiting/src/main/java/shiver/me/timbers/waiting/Waiter.java) instance. If used,
any options that haven't been set will check within the
[Spring context](src/main/java/shiver/me/timbers/waiting/SpringPropertyGetter.java) for any related property values. The
Spring properties that can be set are exactly the same as the [JVM](../smt-waiting#properties) properties.
## Usage
```java
import shiver.me.timbers.waiting.Waiter;
import shiver.me.timbers.waiting.SpringOptions;
import shiver.me.timbers.waiting.Until;
class Examples {
public void all() {
new Waiter( new SpringOptions()).wait(new Until<Void>() {
public Void success() throws Throwable {
System.out.println("This wait will use any waiter options set within the Spring context.");
return null;
}
});
}
}
```
#### WaiterAspect
The [`WaiterAspect`](../smt-waiting-aspect/src/main/java/shiver/me/timbers/waiting/WaiterAspect.java) will also start
using global Spring properties just by having this library in the class path. This is because it uses the
[Java service API](https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html) to auto load any custom
implementation of the `Waiter` and [`Options`](../smt-waiting/src/main/java/shiver/me/timbers/waiting/Options.java).
```java
import shiver.me.timbers.waiting.Wait;
class Examples {
@Wait
public void UseSpringProperties() {
System.out.println("Use any global Spring properties if smt-waiting-spring is in the class path.");
}
}
``` | shiver-me-timbers/smt-waiting-parent | smt-waiting-spring/README.md | Markdown | apache-2.0 | 2,883 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>DAP_JTAG_Configure</title>
<title>CMSIS-DAP: DAP_JTAG_Configure</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="cmsis.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<script type="text/javascript" src="printComponentTabs.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 46px;">
<td id="projectlogo"><img alt="Logo" src="CMSIS_Logo_Final.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">CMSIS-DAP
 <span id="projectnumber">Version 2.0.0</span>
</div>
<div id="projectbrief">Interface Firmware for CoreSight Debug Access Port</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<div id="CMSISnav" class="tabs1">
<ul class="tablist">
<script type="text/javascript">
<!--
writeComponentTabs.call(this);
//-->
</script>
</ul>
</div>
<!-- Generated by Doxygen 1.8.6 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Usage and Description</span></a></li>
<li><a href="modules.html"><span>Reference</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('group__DAP__JTAG__Configure.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Groups</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Pages</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">DAP_JTAG_Configure<div class="ingroups"><a class="el" href="group__DAP__jtag__gr.html">JTAG Commands</a></div></div> </div>
</div><!--header-->
<div class="contents">
<p>Configure JTAG Chain.
<a href="#details">More...</a></p>
<p>Configure JTAG Chain. </p>
<p>The <b>DAP_JTAG_Configure Command</b> sets the JTAG device chain information for communication with <a class="el" href="group__DAP__transfer__gr.html">Transfer Commands</a>. The JTAG device chain needs to be iterated with <a class="el" href="group__DAP__JTAG__Sequence.html">DAP_JTAG_Sequence</a> or manually configured by the debugger on the host computer.</p>
<p><b>DAP_JTAG_Configure Command</b>: </p>
<div class="fragment"><div class="line">| BYTE | BYTE *| BYTE *****|</div>
<div class="line">> 0x15 | Count | IR Length | </div>
<div class="line">|******|*******|+++++++++++|</div>
</div><!-- fragment --><ul>
<li><b>Count:</b> Number of devices in chain</li>
<li><b>IR Length</b>: JTAG IR register length (in bits) for each device.</li>
</ul>
<p><b>DAP_JTAG_Configure Response</b>: </p>
<div class="fragment"><div class="line">| BYTE | BYTE **|</div>
<div class="line">< 0x15 | Status |</div>
<div class="line">|******|********|</div>
</div><!-- fragment --><ul>
<li><b>Status:</b> <a class="el" href="group__DAP__Response__Status.html">Response Status</a> </li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated on Wed Jul 10 2019 15:20:28 for CMSIS-DAP Version 2.0.0 by Arm Ltd. All rights reserved.
<!--
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.6
-->
</li>
</ul>
</div>
</body>
</html>
| STMicroelectronics/cmsis_core | docs/DAP/html/group__DAP__JTAG__Configure.html | HTML | apache-2.0 | 6,500 |
package com.example.android.miwok;
import android.os.NetworkOnMainThreadException;
import static android.os.Build.VERSION_CODES.N;
public class Word {
// providing default translation
private String mDefaultTranslation = null;
// providing miwok word
private String mMiwokTranslation = null;
// providing image resource id
private int mImageResourceId = Word.NO_IMAGE_PROVIDED;
private static final int NO_IMAGE_PROVIDED = -1;
private int mSoundResourceId = Word.NO_SOUND_PROVIDED;
private static final int NO_SOUND_PROVIDED = -1;
/**
* constructor for all the parameter
* @param defaultTranslation default Translation value
* @param miwokTranslation miwok translation word/phrase
* @param imageResourceId image resource id which is and integer URI
* @param soundResourceId sound Resource id which is URI for sound an integer
*/
public Word(String defaultTranslation, String miwokTranslation, int imageResourceId, int soundResourceId ){
mMiwokTranslation = miwokTranslation;
mDefaultTranslation = defaultTranslation;
mImageResourceId = imageResourceId ;
mSoundResourceId = soundResourceId;
}
/**
* overloaded constructor for providing miwok, default and sound only careful of the syntax
* @param defaultTranslation default translation
* @param miwokTranslation miwok word
* @param soundResourceId sound resource id
*/
public Word(String defaultTranslation, String miwokTranslation, int soundResourceId)
{
mMiwokTranslation = miwokTranslation;
mDefaultTranslation = defaultTranslation;
mSoundResourceId = soundResourceId;
}
// getter function for getting default Translation '
public String getDefaultTranslation() {
return mDefaultTranslation;
}
// getter function for getting miwok Translation
public String getMiwokTranslation() {
return mMiwokTranslation;
}
// getter method for getting image resource id
public int getmImageResourceId() {
return mImageResourceId;
}
// getter method for getting sound resource id
public int getSoundResourceId(){
return mSoundResourceId;
}
/**
* returns if the Words object has an image associated with it or not
* @return a boolean true if has an image else false
*/
public boolean hasImage() {
return mImageResourceId != NO_IMAGE_PROVIDED;
}
/**
* returns true if there is a sound resource id
* @return true if sound present else false
*/
public boolean hasSound(){ return mSoundResourceId != NO_SOUND_PROVIDED; }
@Override
public String toString() {
return "Word{" +
"mDefaultTranslation='" + mDefaultTranslation + '\'' +
", mMiwokTranslation='" + mMiwokTranslation + '\'' +
", mImageResourceId=" + mImageResourceId +
", mSoundResourceId=" + mSoundResourceId +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Word word = (Word) o;
if (mImageResourceId != word.mImageResourceId) return false;
if (mSoundResourceId != word.mSoundResourceId) return false;
if (!mDefaultTranslation.equals(word.mDefaultTranslation)) return false;
return mMiwokTranslation.equals(word.mMiwokTranslation);
}
@Override
public int hashCode() {
int result = mDefaultTranslation.hashCode();
result = 31 * result + mMiwokTranslation.hashCode();
result = 31 * result + mImageResourceId;
result = 31 * result + mSoundResourceId;
return result;
}
}
| vishwaprakashmishra/Miwok | app/src/main/java/com/example/android/miwok/Word.java | Java | apache-2.0 | 3,799 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Fri Mar 06 22:14:52 CST 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.yarn.util.SystemClock (hadoop-yarn-common 2.3.0 API)
</TITLE>
<META NAME="date" CONTENT="2015-03-06">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.yarn.util.SystemClock (hadoop-yarn-common 2.3.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/yarn/util/SystemClock.html" title="class in org.apache.hadoop.yarn.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/yarn/util//class-useSystemClock.html" target="_top"><B>FRAMES</B></A>
<A HREF="SystemClock.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.yarn.util.SystemClock</B></H2>
</CENTER>
No usage of org.apache.hadoop.yarn.util.SystemClock
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/yarn/util/SystemClock.html" title="class in org.apache.hadoop.yarn.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/yarn/util//class-useSystemClock.html" target="_top"><B>FRAMES</B></A>
<A HREF="SystemClock.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2015 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| jsrudani/HadoopHDFSProject | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/target/org/apache/hadoop/yarn/util/class-use/SystemClock.html | HTML | apache-2.0 | 6,201 |
# Copyright 2018 Google LLC
#
# 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.
from ._query import query | kubeflow/kfp-tekton-backend | components/gcp/container/component_sdk/python/kfp_component/google/bigquery/__init__.py | Python | apache-2.0 | 601 |
//
// ParseHelper.h
// NinjaRunner
//
// Created by Nikola Bozhkov on 11/8/14.
// Copyright (c) 2014 TeamOnaga. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Parse/Parse.h>
#import "Util.h"
#import "PlayerScore.h"
@interface ParseHelper : NSObject
+ (PlayerScore *) getPlayerScore;
+ (void) savePlayerScore:(PlayerScore *)playerScore;
+ (void) savePlayerScoreName:(NSString *)name;
+ (void) getTopTenPlayerScoresWithBlock:(void(^)(NSArray *playerScoreArray))block;
@end
| NikolaBozhkov/NinjaRunner | NinjaRunner/NinjaRunner/ParseHelper.h | C | apache-2.0 | 499 |
## mako
<%! from django.core.urlresolvers import reverse %>
<%namespace name='static' file='/static_content.html'/>
<%inherit file="/navigation.html"/>
## TODO: this will eventually be moved to the Sass
<%block name="navigation_logo">
<img src="${static.url('themes/gatherworkshops/images/gw_icon.svg')}" height="30" alt="Home Page" />
<span>Gather Workshops</span>
</%block>
| gileslauw/edx-theme-1 | templates/theme-header.html | HTML | apache-2.0 | 382 |
'use strict';
const React = require('react');
const rB = require('react-bootstrap');
const AppActions = require('../actions/AppActions');
const ListNotif = require('./ListNotif');
const AppStatus = require('./AppStatus');
const Counter = require('./Counter');
const Follow = require('./Follow');
const DisplayError = require('./DisplayError');
const cE = React.createElement;
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = this.props.ctx.store.getState();
}
componentDidMount() {
if (!this.unsubscribe) {
this.unsubscribe = this.props.ctx.store
.subscribe(this._onChange.bind(this));
this._onChange();
}
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
}
}
_onChange() {
if (this.unsubscribe) {
this.setState(this.props.ctx.store.getState());
}
}
render() {
const following = this.state.linkedTo ?
this.state.linkedTo.slice(0, -8) :
'NOBODY';
return cE('div', {className: 'container-fluid'},
cE(DisplayError, {
ctx: this.props.ctx,
error: this.state.error
}),
cE(rB.Panel, null,
cE(rB.Panel.Heading, null,
cE(rB.Panel.Title, null,
cE(rB.Grid, {fluid: true},
cE(rB.Row, null,
cE(rB.Col, {sm:1, xs:1},
cE(AppStatus, {
isClosed: this.state.isClosed
})
),
cE(rB.Col, {
sm: 5,
xs:10,
className: 'text-right'
}, 'Counter Example'),
cE(rB.Col, {
sm: 5,
xs:11,
className: 'text-right'
}, this.state.fullName)
)
)
)
),
cE(rB.Panel.Body, null,
cE(rB.Panel, null,
cE(rB.Panel.Heading, null,
cE(rB.Panel.Title, null, 'Counter')
),
cE(rB.Panel.Body, null,
cE(Counter, {
ctx: this.props.ctx,
counter: this.state.counter,
increment: this.state.increment
})
)
),
cE(rB.Panel, null,
cE(rB.Panel.Heading, null,
cE(rB.Panel.Title, null, 'Last Notifications')
),
cE(rB.Panel.Body, null,
cE(ListNotif, {
notif: this.state.notif
})
)
),
cE(rB.Panel, null,
cE(rB.Panel.Heading, null,
cE(rB.Panel.Title, null, `Following ${following}`)
),
cE(rB.Panel.Body, null,
cE(Follow, {
ctx: this.props.ctx
})
)
)
)
)
);
}
};
module.exports = MyApp;
| cafjs/caf_helloworld | public/js/components/MyApp.js | JavaScript | apache-2.0 | 4,081 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_14.html">Class Test_AbaRouteValidator_14</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_31982_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_14.html?line=47632#src-47632" >testAbaNumberCheck_31982_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:44:10
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_31982_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=16811#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=16811#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=16811#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | dcarda/aba.route.validator | target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_14_testAbaNumberCheck_31982_bad_cyz.html | HTML | apache-2.0 | 10,987 |
/**
* Copyright 2017 The GreyCat Authors. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
.Snapshot {
color:white;
text-align: left;
}
.list4 {
width:95%;
font-family:Georgia, Times, serif;
font-size:15px;
}
.list4 ul {
list-style: none;
}
.list4 ul li { }
.list4 ul li a {
display:block;
text-decoration:none;
color:#000000;
background-color:#eaf6ff;
line-height:30px;
border-style:solid;
border-width:1px;
border-color:#CCCCCC;
padding-left:10px;
cursor:pointer;
}
.list4 ul li a:hover {
color:#FFFFFF;
border-color:#000000;
background-color:#1b2b87;
}
.list4 ul li a strong {
margin-right:10px;
} | Neoskai/greycat | plugins/backup/src/main/web/src/Snapshot.css | CSS | apache-2.0 | 1,226 |
/*
* This code is subject to the HIEOS License, Version 1.0
*
* Copyright(c) 2008-2009 Vangent, Inc. All rights reserved.
*
* 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.vangent.hieos.xutil.response;
import com.vangent.hieos.xutil.metadata.structure.MetadataSupport;
import org.apache.axiom.om.OMElement;
import com.vangent.hieos.xutil.exception.XdsInternalException;
/**
*
* @author Bernie Thuman
*/
public class XCAAdhocQueryResponse extends Response {
OMElement queryResult = null;
/**
*
* @throws com.vangent.hieos.xutil.exception.XdsInternalException
*/
public XCAAdhocQueryResponse() throws XdsInternalException {
super();
response = MetadataSupport.om_factory.createOMElement("AdhocQueryResponse", ebQns);
queryResult = MetadataSupport.om_factory.createOMElement("RegistryObjectList", ebRIMns);
}
/**
*
* @return
*/
public OMElement getRoot() {
return response;
}
/**
*
* @return
*/
public OMElement getQueryResult() {
return this.queryResult;
}
/**
*
* @param metadata
* @throws XdsInternalException
*/
public void addQueryResults(OMElement metadata) throws XdsInternalException {
//if (queryResult == null) {
// queryResult = MetadataSupport.om_factory.createOMElement("RegistryObjectList", ebRIMns);
// response.addChild(queryResult);
//}
//if (queryResult == null) {
// queryResult = MetadataSupport.om_factory.createOMElement("RegistryObjectList", ebRIMns);
//}
if (metadata != null) {
queryResult.addChild(metadata);
}
}
}
| kef/hieos | src/xutil/src/com/vangent/hieos/xutil/response/XCAAdhocQueryResponse.java | Java | apache-2.0 | 2,171 |
/*
* =====================================================================================
*
* Filename: weixin.c
*
* Description: Function of weixin
*
* Version: 0.0.1
* Created: 2015/2/4 10:57:58
* Revision: none
*
* Author: Lin Hui (Link), linhui.568@163.com
* Organization: Nufront
*
*--------------------------------------------------------------------------------------
* ChangLog:
* version Author Date Purpose
* 0.0.1 Lin Hui 2015/2/4 Create and intialize
* 0.0.2 zhaoweixian 2015/3/2 fix light on or off fail bug
*
* =====================================================================================
*/
#include "../include/common.h"
#include "AES.h"
#define malloc OSMMalloc
#define calloc OSMCalloc
#define free OSMFree
unsigned char key[16] = {0x0};
unsigned char IV[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // ³õʼ»¯ÏòÁ¿
int print_hex_data(unsigned char * buf, int data_len)
{
int ret = 0;
int i;
printf("\n");
for (i = 0; i < data_len; i++) {
if ((i != 0) && (i % 8 == 0)) printf("\n");
printf("0x%x\t", buf[i]);
}
printf("\n\n");
return ret;
}
int report_device_data(char *sendbuf, int data_len)
{
int ret = 0;
return ret;
}
#define AES_ENCRYPT_MAX_BUFFER (1024)
int NL6621_AES_Encrypt(const unsigned char *plaintext,
unsigned char *ciphertext,
unsigned int data_len)
{
unsigned char *tempbuf = NULL;
unsigned int templen = data_len;
if (templen == 0) {
return -1;
} else if ((templen % 16) != 0) {
tempbuf = malloc(AES_ENCRYPT_MAX_BUFFER);
memset(tempbuf, 0x0, AES_ENCRYPT_MAX_BUFFER);
memcpy(tempbuf, plaintext, data_len);
templen = (((templen / 16) + 1) * 16);
AES_Encrypt(tempbuf, ciphertext, templen, IV);
if (tempbuf != NULL) free(tempbuf);
} else {
AES_Encrypt(plaintext, ciphertext, templen, IV);
}
return templen;
}
int NL6621_AES_Decrypt(unsigned char *plaintext,
const unsigned char *ciphertext,
unsigned int data_len)
{
AES_Decrypt(plaintext, ciphertext, data_len, IV);
return 0;
}
void AESThread(void *arg)
{
unsigned char *sendbuf = "I am linhui, who are you?";
unsigned char recevbuf[64] = {'\0'};
unsigned char CipherText[64] = {0x0};
unsigned int data_len = strlen(sendbuf);
unsigned int templen = data_len;
unsigned char *mykey = "nufront123456";
log_notice("Create AES test demo process task thread.\n");
OSTimeDly(100);
while (1) {
OSTimeDly(300);
memcpy(key, '\0', sizeof(key));
memcpy(key, mykey, strlen(mykey));
printf("key:%s\n", key);
AES_Init(key);
/* AES Encrypt plain data */
templen = NL6621_AES_Encrypt(sendbuf, CipherText, data_len);
printf("plain data(len:%d):%s.\n", data_len, sendbuf);
print_hex_data(CipherText, templen);
/* AES Decrypt cipher data */
NL6621_AES_Decrypt(recevbuf, CipherText, templen);
print_hex_data(recevbuf, templen);
log_notice("Decrypt Data(len:%d):%s\n", templen, recevbuf);
}
}
| NufrontIOT/NL6621-Yeelink | NL6621-Dev/Source/App/NuAgent/Sample/aesdemo.c | C | apache-2.0 | 3,272 |
#!/usr/bin/python
#
# Script to determine the performance statistics and other information
# related to libvirt guests
# https://github.com/odyssey4me/monitoring-scripts
#
#
# 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.
#
import re
import sys
import socket
import libvirt
import argparse
import traceback
import jsonpickle
import subprocess
from xml.etree import ElementTree
# Version required for nagios
VERSION = 'check_virsh_domains v1.0'
# Convert the Domain State integer into the description
# http://libvirt.org/html/libvirt-libvirt.html#virDomainState
DOMAIN_STATES = {
0: 'None',
1: 'Running',
2: 'Blocked on resource',
3: 'Paused by user',
4: 'Being shut down',
5: 'Shut off',
6: 'Crashed',
7: 'Suspended by guest power management'
}
# Location of Zabbix Agent Configuration file
# TODO: This really should either be found, or be an optional argument
ZABBIX_CONF = '/opt/zabbix/etc/zabbix_agentd.conf'
# Location of the zabbix_sender binary
# TODO: This really should either be found, or be an optional argument
ZABBIX_SENDER = '/opt/zabbix/bin/zabbix_sender'
class Domain(object):
def __init__(self, vir_dom):
try:
# Get the domain's network interface device list
if_devices = self.get_if_devices(vir_dom)
# Get the domain's block device list
blk_devices = self.get_blk_devices(vir_dom)
# Get the domain's information
dom_info = vir_dom.info()
# Get the domain's memory stats
mem_stats = vir_dom.memoryStats()
# Get the domain's UUID
self.uuid = vir_dom.UUIDString()
# Compile the network interface stats for each network interface device
for if_num, if_dev in enumerate(if_devices):
# Get the interface stats
if_stats = vir_dom.interfaceStats(if_dev)
# Set class attributes using the interface index number (not the name)
setattr(self, 'if_%s_rx_bytes' % if_num, int(if_stats[0]))
setattr(self, 'if_%s_rx_packets' % if_num, int(if_stats[1]))
setattr(self, 'if_%s_rx_errors' % if_num, int(if_stats[2]))
setattr(self, 'if_%s_rx_drop' % if_num, int(if_stats[3]))
setattr(self, 'if_%s_tx_bytes' % if_num, int(if_stats[4]))
setattr(self, 'if_%s_tx_packets' % if_num, int(if_stats[5]))
setattr(self, 'if_%s_tx_errors' % if_num, int(if_stats[6]))
setattr(self, 'if_%s_tx_drop' % if_num, int(if_stats[7]))
# Compile the block device stats for each block device
for blk_dev in blk_devices:
#Get the block device stats
blk_stats = vir_dom.blockStats(blk_dev)
# Set class attributes using the device name
setattr(self, 'blk_%s_rd_req' % blk_dev, int(blk_stats[0]))
setattr(self, 'blk_%s_rd_bytes' % blk_dev, int(blk_stats[1]))
setattr(self, 'blk_%s_wr_req' % blk_dev, int(blk_stats[2]))
setattr(self, 'blk_%s_wr_bytes' % blk_dev, int(blk_stats[3]))
# Get the memory stats in kB and covert to B for consistency
self.mem_max_bytes = int(dom_info[1]) * 1024
self.mem_used_bytes = int(dom_info[2]) * 1024
# Get the number of vCPU's and the usage time in nanoseconds
self.cpu_count = int(dom_info[3])
self.cpu_time = int(dom_info[4])
# Get the state of the domain
self.state = DOMAIN_STATES[dom_info[0]]
# Note:
# To calculate %CPU utilization you need to have a time period. We're expecting that the
# %CPU calculation is done externally by a system that knows the time period between measurements.
#
# For reference:
# http://people.redhat.com/~rjones/virt-top/faq.html#calccpu
# cpu_time_diff = cpuTime_now - cpuTime_t_seconds_ago
# %CPU = 100 * cpu_time_diff / (t * host_cpus * 10^9)
# There may not be anything in mem_stats (support is limited), but let's add any values there may be
for key, value in mem_stats.iteritems():
value_bytes = int(value) * 1024
setattr(self, 'mem_%s' % key, value_bytes)
except OSError:
print 'Failed to get domain information'
def get_if_devices(self, vir_dom):
#Function to return a list of network devices used
#Create a XML tree from the domain XML description
dom_tree = ElementTree.fromstring(vir_dom.XMLDesc(0))
#The list of device names
devices = []
#Iterate through all network interface target elements of the domain
for target in dom_tree.findall("devices/interface/target"):
#Get the device name
dev = target.get("dev")
#If this device is already in the list, don't add it again
if not dev in devices:
devices.append(dev)
#Completed device name list
return devices
def get_blk_devices(self, vir_dom):
#Function to return a list of block devices used
#Create a XML tree from the domain XML description
dom_tree = ElementTree.fromstring(vir_dom.XMLDesc(0))
#The list of device names
devices = []
#Iterate through all network interface target elements of the domain
for target in dom_tree.findall("devices/disk/target"):
#Get the device name
dev = target.get("dev")
#If this device is already in the list, don't add it again
if not dev in devices:
devices.append(dev)
#Completed device name list
return devices
def health(self):
output = {'errorlevel': 0, 'errors': []}
# Check whether there are network interface errors or drops
for key in vars(self):
if re.match('if_.*_errors', key):
if vars(self)[key] > 0:
output['errors'].append('Domain has network interface errors.')
output['errorlevel'] = set_errorlevel(output['errorlevel'], 1)
if re.match('if_.*_drop', key):
if vars(self)[key] > 0:
output['errors'].append('Domain has network interface drops.')
output['errorlevel'] = set_errorlevel(output['errorlevel'], 1)
# Check whether the domain is in a 'blocked' or 'crashed' state
if self.state == 'Blocked on resource' or self.state == 'Crashed':
output['errors'].append('Domain is %s!' % self.state)
output['errorlevel'] = set_errorlevel(output['errorlevel'], 2)
return output
def inventory(self):
output = {}
output['mem_max_bytes'] = '%i' % self.mem_max_bytes
output['cpu_count'] = '%i' % self.cpu_count
output['state'] = '%s' % self.state
output['uuid'] = '%s' % self.uuid
return output
def perfdata(self):
output = {}
# Loop through all attributes and add the if and blk data
for key in vars(self):
if re.match('if_.*', key) or re.match('blk_.*', key):
output[key] = vars(self)[key]
output['mem_used_bytes'] = self.mem_used_bytes
output['cpu_time'] = self.cpu_time
return output
def parse_args():
ap = argparse.ArgumentParser()
ap.add_argument('-d', '--discovery', action='store_true', help='Only output discovery data')
ap.add_argument('-i', '--inventory', action='store_true', help='Include inventory data in output')
ap.add_argument('-o', '--output', default='stdout', choices=['stdout', 'nagios', 'zabbix'], help='Output format')
ap.add_argument('-p', '--perfdata', action='store_true', help='Include performance data in output')
ap.add_argument('-v', '--verbose', default=0, action='count', help='Verbose output')
ap.add_argument('-V', '--version', action='store_true', help='Show script version')
return ap.parse_args()
def set_errorlevel(current, target):
if current < target != 3:
return target
elif target == 3:
return 3
else:
return current
def output_status(item_name, check_type, errorlevel):
if errorlevel == 0:
return '%s %s OK' % (item_name, check_type)
elif errorlevel == 1:
return '%s %s WARNING' % (item_name, check_type)
elif errorlevel == 2:
return '%s %s CRITICAL' % (item_name, check_type)
else:
return '%s %s UNKNOWN' % (item_name, check_type)
def output_stdout(args):
domains = domain_list()
errorlevels = []
for domain in domains:
print output_status('Domain %s' % domain.uuid, 'Health', domain.health()['errorlevel'])
errorlevels.append(domain.health()['errorlevel'])
if args.verbose > 0:
for error in domain.health()['errors']:
print ' - %s' % error
if args.perfdata:
for key, value in domain.perfdata().iteritems():
print ' - %s = %s' % (key, value)
if args.inventory:
for key, value in domain.inventory().iteritems():
print ' - %s = %s' % (key, value)
# filter out 'unknown' errorlevels if there are any 'warning' or 'critical' errorlevels
if (1 in errorlevels or 2 in errorlevels) and max(errorlevels) == 3:
errorlevels = filter(lambda item: item != 3, errorlevels)
sys.exit(max(errorlevels))
def output_nagios(args):
domains = domain_list()
output_line = ''
output_perfdata = ' |'
errorlevels = []
for domain in domains:
if output_line != '':
output_line += '; '
output_line += output_status('Dom %s' % domain.uuid, 'Health',
domain.health()['errorlevel'])
errorlevels.append(domain.health()['errorlevel'])
if args.verbose > 0:
for error in domain.health()['errors']:
output_line += ' %s' % error
if args.perfdata:
for key, value in domain.perfdata().iteritems():
output_perfdata += " %s='%s'" % (key, value)
if args.perfdata:
output_line += output_perfdata
print output_line
# filter out 'unknown' errorlevels if there are any 'warning' or 'critical' errorlevels
if (1 in errorlevels or 2 in errorlevels) and max(errorlevels) == 3:
errorlevels = filter(lambda item: item != 3, errorlevels)
sys.exit(max(errorlevels))
def output_zabbix(args):
domains = domain_list()
output_line = ''
errorlevels = []
for domain in domains:
output_line += '%s virsh.domain[%s,health] %s\n' % (socket.gethostname(), domain.uuid, output_status(domain.uuid,'Health', domain.health()['errorlevel']))
errorlevels.append(domain.health()['errorlevel'])
if args.verbose > 0 and len(domain.health()['errors']) > 0:
output_line += '%s virsh.domain[%s,errors] %s\n' % (socket.gethostname(), domain.uuid, ";".join(domain.health()['errors']))
elif args.verbose > 0 and len(domain.health()['errors']) == 0:
output_line += '%s virsh.domain[%s,errors] None\n' % (socket.gethostname(), domain.uuid)
if args.perfdata:
for key, value in domain.perfdata().iteritems():
output_line += '%s virsh.domain[%s,%s] %s\n' % (socket.gethostname(), domain.uuid, key, value)
if args.inventory:
for key, value in domain.inventory().iteritems():
output_line += '%s virsh.domain[%s,%s] %s\n' % (socket.gethostname(), domain.uuid, key, value)
# filter out 'unknown' errorlevels if there are any 'warning' or 'critical' errorlevels
if (1 in errorlevels or 2 in errorlevels) and max(errorlevels) == 3:
errorlevels = filter(lambda item: item != 3, errorlevels)
#TODO: This should really have exception handling
cmd = '%s -c %s -v -i -' % (ZABBIX_SENDER, ZABBIX_CONF)
cmd = cmd.split(' ')
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.write(output_line)
status = p.poll()
stdout, stderr = p.communicate()
if not status:
print 'zabbix_sender output: %s' % stdout
else:
print 'zabbix_sender error: %s' % stdout
print output_status('Overall','Health', max(errorlevels))
sys.exit(max(errorlevels))
def output_zabbix_discovery(args):
#TODO: Sort this mess out.
#Using the objects was too slow - the discovery would keep failing when requested by the Zabbix Server
try:
# Connect to the local hypervisor (read only)
conn = libvirt.openReadOnly(None)
# Prepare the lists and dict objects
dom_list = []
return_dict = {}
# Loop through the running domains and retrieve the appropriate discovery information
for dom_id in conn.listDomainsID():
dom_dict = {}
vir_dom = conn.lookupByID(dom_id)
dom_dict['{#VIRSH_DOMAIN_UUID}'] = vir_dom.UUIDString()
if args.perfdata:
dom_tree = ElementTree.fromstring(vir_dom.XMLDesc(0))
#The list of device names
if_devices = []
#Iterate through all network interface target elements of the domain
for target in dom_tree.findall("devices/interface/target"):
#Get the device name
dev = target.get("dev")
#If this device is already in the list, don't add it again
if not dev in if_devices:
if_devices.append(dev)
#Put the final device list into the domain's return dict
for if_num, if_dev in enumerate(if_devices):
dom_dict['{#VIRSH_DOMAIN_NIC}'] = str(if_num)
#The list of device names
blk_devices = []
#Iterate through all network interface target elements of the domain
for target in dom_tree.findall("devices/disk/target"):
#Get the device name
dev = target.get("dev")
#If this device is already in the list, don't add it again
if not dev in blk_devices:
blk_devices.append(dev)
#Put the final device list into the domain's return dict
for blk_dev in blk_devices:
dom_dict['{#VIRSH_DOMAIN_DISK}'] = blk_dev
dom_list.append(dom_dict)
# Loop through the offline domains and retrieve the appropriate discovery information
for name in conn.listDefinedDomains():
dom_dict = {}
vir_dom = conn.lookupByID(dom_id)
dom_dict['{#VIRSH_DOMAIN_UUID}'] = vir_dom.UUIDString()
if args.perfdata:
dom_tree = ElementTree.fromstring(vir_dom.XMLDesc(0))
#The list of device names
if_devices = []
#Iterate through all network interface target elements of the domain
for target in dom_tree.findall("devices/interface/target"):
#Get the device name
dev = target.get("dev")
#If this device is already in the list, don't add it again
if not dev in if_devices:
if_devices.append(dev)
#Put the final device list into the domain's return dict
for if_num, if_dev in enumerate(if_devices):
dom_dict['{#VIRSH_DOMAIN_NIC}'] = str(if_num)
#The list of device names
blk_devices = []
#Iterate through all network interface target elements of the domain
for target in dom_tree.findall("devices/disk/target"):
#Get the device name
dev = target.get("dev")
#If this device is already in the list, don't add it again
if not dev in blk_devices:
blk_devices.append(dev)
#Put the final device list into the domain's return dict
for blk_dev in blk_devices:
dom_dict['{#VIRSH_DOMAIN_DISK}'] = blk_dev
dom_list.append(dom_dict)
return_dict['data'] = dom_list
# return the data encoded as json
print jsonpickle.encode(return_dict)
except OSError:
print 'Failed to get domain list'
def domain_list():
try:
# Connect to the local hypervisor (read only)
conn = libvirt.openReadOnly(None)
# Prepare the list of domains to return
dom_list = []
# Loop through the running domains, create and store the objects
for id in conn.listDomainsID():
vir_dom = conn.lookupByID(id)
dom_obj = Domain(vir_dom)
dom_list.append(dom_obj)
# Loop through the offline domains, create and store the objects
for name in conn.listDefinedDomains():
vir_dom = conn.lookupByName(name)
dom_obj = Domain(vir_dom)
dom_list.append(dom_obj)
return dom_list
except OSError:
print 'Failed to get domain list'
return []
if __name__ == '__main__':
args = parse_args()
try:
if args.version:
print VERSION
elif args.output == 'stdout':
output_stdout(args)
elif args.output == 'nagios':
output_nagios(args)
elif args.output == 'zabbix' and not args.discovery:
output_zabbix(args)
elif args.output == 'zabbix' and args.discovery:
output_zabbix_discovery(args)
sys.exit(0)
except Exception, err:
#print("ERROR: %s" % err)
ex, val, tb = sys.exc_info()
traceback.print_exception(ex, val, tb)
sys.exit(1)
except KeyboardInterrupt:
sys.exit(1) | odyssey4me/monitoring-scripts | check_virsh_domains.py | Python | apache-2.0 | 18,638 |
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<h1>*** PLEASE NOTE: This document applies to the HEAD of the source
tree only. If you are using a released version of Kubernetes, you almost
certainly want the docs that go with that version.</h1>
<strong>Documentation for specific releases can be found at
[releases.k8s.io](http://releases.k8s.io).</strong>
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
# Sharing Cluster Access
Client access to a running kubernetes cluster can be shared by copying
the `kubectl` client config bundle ([.kubeconfig](kubeconfig-file.md)).
This config bundle lives in `$HOME/.kube/config`, and is generated
by `cluster/kube-up.sh`. Sample steps for sharing `kubeconfig` below.
**1. Create a cluster**
```bash
cluster/kube-up.sh
```
**2. Copy `kubeconfig` to new host**
```bash
scp $HOME/.kube/config user@remotehost:/path/to/.kube/config
```
**3. On new host, make copied `config` available to `kubectl`**
* Option A: copy to default location
```bash
mv /path/to/.kube/config $HOME/.kube/config
```
* Option B: copy to working directory (from which kubectl is run)
```bash
mv /path/to/.kube/config $PWD
```
* Option C: manually pass `kubeconfig` location to `.kubectl`
```bash
# via environment variable
export KUBECONFIG=/path/to/.kube/config
# via commandline flag
kubectl ... --kubeconfig=/path/to/.kube/config
```
## Manually Generating `kubeconfig`
`kubeconfig` is generated by `kube-up` but you can generate your own
using (any desired subset of) the following commands.
```bash
# create kubeconfig entry
kubectl config set-cluster $CLUSTER_NICK
--server=https://1.1.1.1 \
--certificate-authority=/path/to/apiserver/ca_file \
--embed-certs=true \
# Or if tls not needed, replace --certificate-authority and --embed-certs with
--insecure-skip-tls-verify=true
--kubeconfig=/path/to/standalone/.kube/config
# create user entry
kubectl config set-credentials $USER_NICK
# bearer token credentials, generated on kube master
--token=$token \
# use either username|password or token, not both
--username=$username \
--password=$password \
--client-certificate=/path/to/crt_file \
--client-key=/path/to/key_file \
--embed-certs=true
--kubeconfig=/path/to/standalone/.kubeconfig
# create context entry
kubectl config set-context $CONTEXT_NAME --cluster=$CLUSTER_NICKNAME --user=$USER_NICK
```
Notes:
* The `--embed-certs` flag is needed to generate a standalone
`kubeconfig`, that will work as-is on another host.
* `--kubeconfig` is both the preferred file to load config from and the file to
save config too. In the above commands the `--kubeconfig` file could be
omitted if you first run
```bash
export KUBECONFIG=/path/to/standalone/.kube/config
```
* The ca_file, key_file, and cert_file referenced above are generated on the
kube master at cluster turnup. They can be found on the master under
`/srv/kubernetes`. Bearer token/basic auth are also generated on the kube master.
For more details on `kubeconfig` see [kubeconfig-file.md](kubeconfig-file.md),
and/or run `kubectl config -h`.
## Merging `kubeconfig` Example
`kubectl` loads and merges config from the following locations (in order)
1. `--kubeconfig=path/to/.kube/config` commandline flag
2. `KUBECONFIG=path/to/.kube/config` env variable
3. `$PWD/.kubeconfig`
4. `$HOME/.kube/config`
If you create clusters A, B on host1, and clusters C, D on host2, you can
make all four clusters available on both hosts by running
```bash
# on host2, copy host1's default kubeconfig, and merge it from env
scp host1:/path/to/home1/.kube/config path/to/other/.kube/config
export $KUBECONFIG=path/to/other/.kube/config
# on host1, copy host2's default kubeconfig and merge it from env
scp host2:/path/to/home2/.kube/config path/to/other/.kube/config
export $KUBECONFIG=path/to/other/.kube/config
```
Detailed examples and explanation of `kubeconfig` loading/merging rules can be found in [kubeconfig-file.md](kubeconfig-file.md).
[]()
| zvbuhl/kubernetes | docs/sharing-clusters.md | Markdown | apache-2.0 | 4,155 |
'use strict';
/**
* @ngdoc overview
* @name tryingAngularJsApp
* @description
* # tryingAngularJsApp
*
* Main module of the application.
*/
angular
.module('tryingAngularJsApp', [
'ngAnimate',
'ngAria',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl',
controllerAs: 'about'
})
.otherwise({
redirectTo: '/'
});
});
| JArandaIzquierdo/TryingAngularJS | YO/app/scripts/app.js | JavaScript | apache-2.0 | 708 |
/*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* 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.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package javax.time.calendrical;
import static java.time.Month.AUGUST;
import static java.time.Month.FEBRUARY;
import static java.time.Month.JULY;
import static java.time.Month.JUNE;
import static java.time.Month.MARCH;
import static java.time.Month.OCTOBER;
import static java.time.Month.SEPTEMBER;
import static java.time.calendrical.ChronoUnit.DAYS;
import static java.time.calendrical.ChronoUnit.MONTHS;
import static java.time.calendrical.ChronoUnit.WEEKS;
import static java.time.calendrical.ChronoUnit.YEARS;
import static org.testng.Assert.assertEquals;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneOffset;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Test.
*/
@Test
public class TestChronoUnit {
// -----------------------------------------------------------------------
@DataProvider(name = "yearsBetween")
Object[][] data_yearsBetween() {
return new Object[][] { { date(1939, SEPTEMBER, 2), date(1939, SEPTEMBER, 1), 0 },
{ date(1939, SEPTEMBER, 2), date(1939, SEPTEMBER, 2), 0 },
{ date(1939, SEPTEMBER, 2), date(1939, SEPTEMBER, 3), 0 },
{ date(1939, SEPTEMBER, 2), date(1940, SEPTEMBER, 1), 0 },
{ date(1939, SEPTEMBER, 2), date(1940, SEPTEMBER, 2), 1 },
{ date(1939, SEPTEMBER, 2), date(1940, SEPTEMBER, 3), 1 },
{ date(1939, SEPTEMBER, 2), date(1938, SEPTEMBER, 1), -1 },
{ date(1939, SEPTEMBER, 2), date(1938, SEPTEMBER, 2), -1 },
{ date(1939, SEPTEMBER, 2), date(1938, SEPTEMBER, 3), 0 },
{ date(1939, SEPTEMBER, 2), date(1945, SEPTEMBER, 3), 6 },
{ date(1939, SEPTEMBER, 2), date(1945, OCTOBER, 3), 6 },
{ date(1939, SEPTEMBER, 2), date(1945, AUGUST, 3), 5 }, };
}
@Test(dataProvider = "yearsBetween")
public void test_yearsBetween(LocalDate start, LocalDate end, long expected) {
assertEquals(YEARS.between(start, end).getAmount(), expected);
assertEquals(YEARS.between(start, end).getUnit(), YEARS);
}
@Test(dataProvider = "yearsBetween")
public void test_yearsBetweenReversed(LocalDate start, LocalDate end, long expected) {
assertEquals(YEARS.between(end, start).getAmount(), -expected);
assertEquals(YEARS.between(end, start).getUnit(), YEARS);
}
@Test(dataProvider = "yearsBetween")
public void test_yearsBetween_LocalDateTimeSameTime(LocalDate start, LocalDate end, long expected) {
assertEquals(YEARS.between(start.atTime(12, 30), end.atTime(12, 30)).getAmount(), expected);
}
@Test(dataProvider = "yearsBetween")
public void test_yearsBetween_LocalDateTimeLaterTime(LocalDate start, LocalDate end, long expected) {
assertEquals(YEARS.between(start.atTime(12, 30), end.atTime(12, 31)).getAmount(), expected);
}
@Test(dataProvider = "yearsBetween")
public void test_yearsBetween_ZonedDateSameOffset(LocalDate start, LocalDate end, long expected) {
assertEquals(YEARS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2)))
.getAmount(), expected);
}
@Test(dataProvider = "yearsBetween")
public void test_yearsBetween_ZonedDateLaterOffset(LocalDate start, LocalDate end, long expected) {
// +01:00 is later than +02:00
assertEquals(YEARS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1)))
.getAmount(), expected);
}
// -----------------------------------------------------------------------
@DataProvider(name = "monthsBetween")
Object[][] data_monthsBetween() {
return new Object[][] { { date(2012, JULY, 2), date(2012, JULY, 1), 0 },
{ date(2012, JULY, 2), date(2012, JULY, 2), 0 }, { date(2012, JULY, 2), date(2012, JULY, 3), 0 },
{ date(2012, JULY, 2), date(2012, AUGUST, 1), 0 }, { date(2012, JULY, 2), date(2012, AUGUST, 2), 1 },
{ date(2012, JULY, 2), date(2012, AUGUST, 3), 1 },
{ date(2012, JULY, 2), date(2012, SEPTEMBER, 1), 1 }, { date(2012, JULY, 2), date(2012, SEPTEMBER, 2), 2 },
{ date(2012, JULY, 2), date(2012, SEPTEMBER, 3), 2 },
{ date(2012, JULY, 2), date(2012, JUNE, 1), -1 }, { date(2012, JULY, 2), date(2012, JUNE, 2), -1 },
{ date(2012, JULY, 2), date(2012, JUNE, 3), 0 },
{ date(2012, FEBRUARY, 27), date(2012, MARCH, 26), 0 }, { date(2012, FEBRUARY, 27), date(2012, MARCH, 27), 1 },
{ date(2012, FEBRUARY, 27), date(2012, MARCH, 28), 1 },
{ date(2012, FEBRUARY, 28), date(2012, MARCH, 27), 0 }, { date(2012, FEBRUARY, 28), date(2012, MARCH, 28), 1 },
{ date(2012, FEBRUARY, 28), date(2012, MARCH, 29), 1 },
{ date(2012, FEBRUARY, 29), date(2012, MARCH, 28), 0 }, { date(2012, FEBRUARY, 29), date(2012, MARCH, 29), 1 },
{ date(2012, FEBRUARY, 29), date(2012, MARCH, 30), 1 }, };
}
@Test(dataProvider = "monthsBetween")
public void test_monthsBetween(LocalDate start, LocalDate end, long expected) {
assertEquals(MONTHS.between(start, end).getAmount(), expected);
assertEquals(MONTHS.between(start, end).getUnit(), MONTHS);
}
@Test(dataProvider = "monthsBetween")
public void test_monthsBetweenReversed(LocalDate start, LocalDate end, long expected) {
assertEquals(MONTHS.between(end, start).getAmount(), -expected);
assertEquals(MONTHS.between(end, start).getUnit(), MONTHS);
}
@Test(dataProvider = "monthsBetween")
public void test_monthsBetween_LocalDateTimeSameTime(LocalDate start, LocalDate end, long expected) {
assertEquals(MONTHS.between(start.atTime(12, 30), end.atTime(12, 30)).getAmount(), expected);
}
@Test(dataProvider = "monthsBetween")
public void test_monthsBetween_LocalDateTimeLaterTime(LocalDate start, LocalDate end, long expected) {
assertEquals(MONTHS.between(start.atTime(12, 30), end.atTime(12, 31)).getAmount(), expected);
}
@Test(dataProvider = "monthsBetween")
public void test_monthsBetween_ZonedDateSameOffset(LocalDate start, LocalDate end, long expected) {
assertEquals(MONTHS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2)))
.getAmount(), expected);
}
@Test(dataProvider = "monthsBetween")
public void test_monthsBetween_ZonedDateLaterOffset(LocalDate start, LocalDate end, long expected) {
// +01:00 is later than +02:00
assertEquals(MONTHS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1)))
.getAmount(), expected);
}
// -----------------------------------------------------------------------
@DataProvider(name = "weeksBetween")
Object[][] data_weeksBetween() {
return new Object[][] { { date(2012, JULY, 2), date(2012, JUNE, 25), -1 },
{ date(2012, JULY, 2), date(2012, JUNE, 26), 0 }, { date(2012, JULY, 2), date(2012, JULY, 2), 0 },
{ date(2012, JULY, 2), date(2012, JULY, 8), 0 }, { date(2012, JULY, 2), date(2012, JULY, 9), 1 },
{ date(2012, FEBRUARY, 28), date(2012, FEBRUARY, 21), -1 },
{ date(2012, FEBRUARY, 28), date(2012, FEBRUARY, 22), 0 },
{ date(2012, FEBRUARY, 28), date(2012, FEBRUARY, 28), 0 },
{ date(2012, FEBRUARY, 28), date(2012, FEBRUARY, 29), 0 },
{ date(2012, FEBRUARY, 28), date(2012, MARCH, 1), 0 }, { date(2012, FEBRUARY, 28), date(2012, MARCH, 5), 0 },
{ date(2012, FEBRUARY, 28), date(2012, MARCH, 6), 1 },
{ date(2012, FEBRUARY, 29), date(2012, FEBRUARY, 22), -1 },
{ date(2012, FEBRUARY, 29), date(2012, FEBRUARY, 23), 0 },
{ date(2012, FEBRUARY, 29), date(2012, FEBRUARY, 28), 0 },
{ date(2012, FEBRUARY, 29), date(2012, FEBRUARY, 29), 0 },
{ date(2012, FEBRUARY, 29), date(2012, MARCH, 1), 0 }, { date(2012, FEBRUARY, 29), date(2012, MARCH, 6), 0 },
{ date(2012, FEBRUARY, 29), date(2012, MARCH, 7), 1 }, };
}
@Test(dataProvider = "weeksBetween")
public void test_weeksBetween(LocalDate start, LocalDate end, long expected) {
assertEquals(WEEKS.between(start, end).getAmount(), expected);
assertEquals(WEEKS.between(start, end).getUnit(), WEEKS);
}
@Test(dataProvider = "weeksBetween")
public void test_weeksBetweenReversed(LocalDate start, LocalDate end, long expected) {
assertEquals(WEEKS.between(end, start).getAmount(), -expected);
assertEquals(WEEKS.between(end, start).getUnit(), WEEKS);
}
// -----------------------------------------------------------------------
@DataProvider(name = "daysBetween")
Object[][] data_daysBetween() {
return new Object[][] { { date(2012, JULY, 2), date(2012, JULY, 1), -1 },
{ date(2012, JULY, 2), date(2012, JULY, 2), 0 }, { date(2012, JULY, 2), date(2012, JULY, 3), 1 },
{ date(2012, FEBRUARY, 28), date(2012, FEBRUARY, 27), -1 },
{ date(2012, FEBRUARY, 28), date(2012, FEBRUARY, 28), 0 },
{ date(2012, FEBRUARY, 28), date(2012, FEBRUARY, 29), 1 },
{ date(2012, FEBRUARY, 28), date(2012, MARCH, 1), 2 },
{ date(2012, FEBRUARY, 29), date(2012, FEBRUARY, 27), -2 },
{ date(2012, FEBRUARY, 29), date(2012, FEBRUARY, 28), -1 },
{ date(2012, FEBRUARY, 29), date(2012, FEBRUARY, 29), 0 },
{ date(2012, FEBRUARY, 29), date(2012, MARCH, 1), 1 },
{ date(2012, MARCH, 1), date(2012, FEBRUARY, 27), -3 }, { date(2012, MARCH, 1), date(2012, FEBRUARY, 28), -2 },
{ date(2012, MARCH, 1), date(2012, FEBRUARY, 29), -1 }, { date(2012, MARCH, 1), date(2012, MARCH, 1), 0 },
{ date(2012, MARCH, 1), date(2012, MARCH, 2), 1 },
{ date(2012, MARCH, 1), date(2013, FEBRUARY, 28), 364 }, { date(2012, MARCH, 1), date(2013, MARCH, 1), 365 },
{ date(2011, MARCH, 1), date(2012, FEBRUARY, 28), 364 },
{ date(2011, MARCH, 1), date(2012, FEBRUARY, 29), 365 }, { date(2011, MARCH, 1), date(2012, MARCH, 1), 366 }, };
}
@Test(dataProvider = "daysBetween")
public void test_daysBetween(LocalDate start, LocalDate end, long expected) {
assertEquals(DAYS.between(start, end).getAmount(), expected);
assertEquals(DAYS.between(start, end).getUnit(), DAYS);
}
@Test(dataProvider = "daysBetween")
public void test_daysBetweenReversed(LocalDate start, LocalDate end, long expected) {
assertEquals(DAYS.between(end, start).getAmount(), -expected);
assertEquals(DAYS.between(end, start).getUnit(), DAYS);
}
@Test(dataProvider = "daysBetween")
public void test_daysBetween_LocalDateTimeSameTime(LocalDate start, LocalDate end, long expected) {
assertEquals(DAYS.between(start.atTime(12, 30), end.atTime(12, 30)).getAmount(), expected);
}
@Test(dataProvider = "daysBetween")
public void test_daysBetween_LocalDateTimeLaterTime(LocalDate start, LocalDate end, long expected) {
assertEquals(DAYS.between(start.atTime(12, 30), end.atTime(12, 31)).getAmount(), expected);
}
@Test(dataProvider = "daysBetween")
public void test_daysBetween_ZonedDateSameOffset(LocalDate start, LocalDate end, long expected) {
assertEquals(DAYS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(2)))
.getAmount(), expected);
}
@Test(dataProvider = "daysBetween")
public void test_daysBetween_ZonedDateLaterOffset(LocalDate start, LocalDate end, long expected) {
// +01:00 is later than +02:00
assertEquals(DAYS.between(start.atStartOfDay(ZoneOffset.ofHours(2)), end.atStartOfDay(ZoneOffset.ofHours(1)))
.getAmount(), expected);
}
// -----------------------------------------------------------------------
private static LocalDate date(int year, Month month, int dom) {
return LocalDate.of(year, month, dom);
}
}
| m-m-m/java8-backports | mmm-util-backport-java.time/src/test/java/javax/time/calendrical/TestChronoUnit.java | Java | apache-2.0 | 13,228 |
package example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer497 {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private long id;
private String firstName;
private String lastName;
protected Customer497() {}
public Customer497(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer497[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
}
}
| spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/model/Customer497.java | Java | apache-2.0 | 624 |
/****************¡¶51µ¥Æ¬»úÇáËÉÈëÃÅ-»ùÓÚSTC15W4KϵÁС·ÅäÌ×Àý³Ì *************
¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï
¡¶51µ¥Æ¬»úÇáËÉÈëÃÅ-»ùÓÚSTC15W4KϵÁС· Ò»ÊéÒѾÓɱ±º½³ö°æÉçÕýʽ³ö°æ·¢ÐС£
×÷ÕßÇ×ÊÖ´´×÷µÄÓë½Ì²ÄÅäÌ×µÄ51Ë«ºËʵÑé°å(2¸öMCU)¶Ô³ÌÐòÏÂÔØ¡¢µ÷ÊÔ¡¢·ÂÕæ·½±ã£¬²»ÐèÒªÍⲿ
·ÂÕæÆ÷Óë±à³ÌÆ÷£¬ÕâÖÖÉè¼Æ·½Ê½³¹µ×½â¾öÁËϵͳÖжà¸ö×î¸ßÓÅÏȼ¶ËÒ²²»ÄÜÈÃ˵ÄÖжϾºÕùÎÊÌâ¡£
ÌÔ±¦µêµØÖ·£ºhttps://shop117387413.taobao.com
QQȺ£ºSTC51-STM32(3) £º515624099 »ò STC51-STM32(2)£º99794374¡£
ÑéÖ¤ÐÅÏ¢£ºSTC15µ¥Æ¬»ú
ÓÊÏ䣺xgliyouquan@126.com
¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï¡ï*/
#include "intrins.h" // _nop_()º¯ÊýÐèÒª
/******************************************************************
- ¹¦ÄÜÃèÊö£º½«Ò»¸ö32볤ÕûÐͱäÁ¿datתΪ×Ö·û´®£¬±ÈÈç°Ñ1234תΪ"1234"
- ²ÎÊý˵Ã÷£ºdat:´ýתµÄlongÐ͵ıäÁ¿
str:Ö¸Ïò×Ö·ûÊý×éµÄÖ¸Õ룬ת»»ºóµÄ×Ö½Ú´®·ÅÔÚÆäÖÐ
******************************************************************/
void Long_Str(unsigned long dat,char *str)
{
unsigned char temp[11]; // ³¤ÕûÊý×î´óÖµ4294967295£¬×ªASCIIÂëºóÕ¼ÓÃ10×Ö½Ú
unsigned char i=0,j=0;
while(dat) // ÊýֵתASCIIÂ룬×Ö½ÚÔÚÊý×éÖз´ÏòÅÅÁÐ
{
temp[i]=dat%10+0x30;
i++;
dat/=10;
}
j=i;
for(i=0;i<j;i++) // Êý×é½»»»ÏȺó˳Ðò£¬ÕýÏòÅÅÁÐ
{
str[i]=temp[j-i-1]; // CÓïÑÔÖÐÊý×éϱê¹Ì¶¨´Ó0¿ªÊ¼
}
if(!i) {str[i++]='0';} // º¯Êý²ÎÊýdat=0´¦Àí
str[i]=0; // ÓÉÓÚҪʹÓÃKEIL×Ô´øµÄ×Ö·û´®´¦Àíº¯Êý´¦Àí£¬±ØÐëÓнáÊø±ê¼Ç¡£
}
//void delay100ms(void) // 22.1184MHz
//{
// unsigned char i,j,k;
// for(i=19;i>0;i--) for(j=223;j>0;j--) for(k=129;k>0;k--);
//}
void Delay100ms(void) //@11.0592MHz
{
unsigned char i, j, k;
_nop_();
_nop_();
i = 5;
j = 52;
k = 195;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
| blacksea3/STC_mainkab | STC15W4K32LCD1602/myfun.c | C | apache-2.0 | 1,772 |
/**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - contact@hoteia.com
*
*/
package org.hoteia.qalingo.core.web.mvc.viewbean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class CustomerViewBean extends AbstractViewBean {
/**
* Generated UID
*/
private static final long serialVersionUID = 6264101125517957897L;
public static String SCREEN_NAME = "screenName";
private int version;
private String code;
private String login;
private String title;
private String firstname;
private String lastname;
private String email;
private String password;
private String defaultLocale;
private String birthday;
private boolean validated;
private boolean active;
private String avatarImg;
private Map<String, ValueBean> customerAttributes = new HashMap<String, ValueBean>();
private Map<String, String> groups = new HashMap<String, String>();
private Map<String, String> roles = new HashMap<String, String>();
private Map<String, String> permissions = new HashMap<String, String>();
private String lastConnectionDate;
private List<CustomerConnectionLogValueBean> customerConnectionLogs = new ArrayList<CustomerConnectionLogValueBean>();
private List<CustomerAddressViewBean> addresses = new ArrayList<CustomerAddressViewBean>();
private String detailsUrl;
private String editUrl;
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDefaultLocale() {
return defaultLocale;
}
public void setDefaultLocale(String defaultLocale) {
this.defaultLocale = defaultLocale;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public boolean isValidated() {
return validated;
}
public void setValidated(boolean validated) {
this.validated = validated;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getAvatarImg() {
return avatarImg;
}
public void setAvatarImg(String avatarImg) {
this.avatarImg = avatarImg;
}
public Map<String, ValueBean> getCustomerAttributes() {
return customerAttributes;
}
public void setCustomerAttributes(Map<String, ValueBean> customerAttributes) {
this.customerAttributes = customerAttributes;
}
public String getScreenName() {
String screenNameValue = null;
if (customerAttributes != null && customerAttributes.size() > 0) {
ValueBean screenName = customerAttributes.get(SCREEN_NAME);
if (screenName != null) {
screenNameValue = screenName.getValue();
}
}
if (screenNameValue == null) {
screenNameValue = getLastname() + " " + getFirstname();
}
return screenNameValue;
}
public Map<String, String> getGroups() {
return groups;
}
public boolean hasGroup(String groupCode) {
if (groups != null
&& !groups.isEmpty()
&& groups.get(groupCode) != null) {
return true;
}
return false;
}
public void setGroups(Map<String, String> groups) {
this.groups = groups;
}
public Map<String, String> getRoles() {
return roles;
}
public boolean hasRole(String roleCode) {
if (roles != null
&& !roles.isEmpty()
&& roles.get(roleCode) != null) {
return true;
}
return false;
}
public void setRoles(Map<String, String> roles) {
this.roles = roles;
}
public Map<String, String> getPermissions() {
return permissions;
}
public boolean hasPermission(String permissionCode) {
if (permissions != null
&& !permissions.isEmpty()
&& permissions.get(permissionCode) != null) {
return true;
}
return false;
}
public void setPermissions(Map<String, String> permissions) {
this.permissions = permissions;
}
public String getLastConnectionDate() {
return lastConnectionDate;
}
public void setLastConnectionDate(String lastConnectionDate) {
this.lastConnectionDate = lastConnectionDate;
}
public List<CustomerConnectionLogValueBean> getCustomerConnectionLogs() {
return customerConnectionLogs;
}
public void setCustomerConnectionLogs(List<CustomerConnectionLogValueBean> customerConnectionLogs) {
this.customerConnectionLogs = customerConnectionLogs;
}
public List<CustomerAddressViewBean> getAddresses() {
return addresses;
}
public CustomerAddressViewBean getDefaultAddress() {
if (addresses != null) {
for (Iterator<CustomerAddressViewBean> iterator = addresses.iterator(); iterator.hasNext();) {
CustomerAddressViewBean address = (CustomerAddressViewBean) iterator.next();
if(address.isDefaultBilling()){
return address;
}
}
if(addresses.size() > 0){
return addresses.iterator().next();
}
}
return null;
}
public void setAddresses(List<CustomerAddressViewBean> addresses) {
this.addresses = addresses;
}
public String getDetailsUrl() {
return detailsUrl;
}
public void setDetailsUrl(String detailsUrl) {
this.detailsUrl = detailsUrl;
}
public String getEditUrl() {
return editUrl;
}
public void setEditUrl(String editUrl) {
this.editUrl = editUrl;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
result = prime * result + ((login == null) ? 0 : login.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CustomerViewBean other = (CustomerViewBean) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
if (login == null) {
if (other.login != null)
return false;
} else if (!login.equals(other.login))
return false;
return true;
}
@Override
public String toString() {
return "CustomerViewBean [version=" + version + ", code=" + code + ", login=" + login + ", title=" + title + ", firstname=" + firstname + ", lastname=" + lastname + ", email=" + email
+ ", password=" + password + ", validated=" + validated + ", active=" + active + "]";
}
} | qalingo/qalingo-engine | apis/api-core/api-core-common/src/main/java/org/hoteia/qalingo/core/web/mvc/viewbean/CustomerViewBean.java | Java | apache-2.0 | 8,590 |
package com.akjava.gwt.modelweight.client;
import com.akjava.gwt.three.client.gwt.GWTParamUtils;
import com.akjava.gwt.three.client.gwt.core.Intersect;
import com.akjava.gwt.three.client.java.ThreeLog;
import com.akjava.gwt.three.client.js.THREE;
import com.akjava.gwt.three.client.js.cameras.Camera;
import com.akjava.gwt.three.client.js.core.Face3;
import com.akjava.gwt.three.client.js.core.Geometry;
import com.akjava.gwt.three.client.js.core.Object3D;
import com.akjava.gwt.three.client.js.math.Matrix3;
import com.akjava.gwt.three.client.js.math.Vector3;
import com.akjava.gwt.three.client.js.objects.Line;
import com.akjava.gwt.three.client.js.objects.Mesh;
import com.akjava.gwt.three.client.js.renderers.WebGLRenderer;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.ClickEvent;
public class MeshVertexSelector extends Object3DMouseSelecter{
public MeshVertexSelector(Mesh mesh,WebGLRenderer renderer, Camera camera,Object3D lineContainer) {
super(renderer, camera);
this.mesh=mesh;
this.lineContainer=lineContainer;
}
private Mesh mesh;
private Object3D lineContainer;
public int pickVertex(ClickEvent event){
return pickVertex(event.getX(),event.getY());
}
public void dispose(){
if(selectedLine!=null){
lineContainer.remove(selectedLine);
}
}
public int pickVertex(int mx,int my){
JsArray<Intersect> intersects=pickIntersects(mx, my, mesh);
if(intersects==null || intersects.length()==0){
selected=false;
if(selectedLine!=null){
selectedLine.setVisible(false);
}
return -1;
}
selected=true;
Face3 face=intersects.get(0).getFace();
Vector3 point=intersects.get(0).getPoint();
int faceIndex=intersects.get(0).getFaceIndex();
//ThreeLog.log("point:",point);
int vertexOfFaceIndex=0;
Vector3 selection=mesh.getGeometry().getVertices().get(face.getA());
//ThreeLog.log("vertex1:",mesh.getGeometry().getVertices().get(face.getA()));
double distance=point.distanceTo(matrixedPoint(mesh.getGeometry().getVertices().get(face.getA())));
//ThreeLog.log("vertex2:",mesh.getGeometry().getVertices().get(face.getB()));
double distance2=point.distanceTo(matrixedPoint(mesh.getGeometry().getVertices().get(face.getB())));
if(distance2<distance){
vertexOfFaceIndex=1;
distance=distance2;
selection=mesh.getGeometry().getVertices().get(face.getB());
}
//ThreeLog.log("vertex3:",mesh.getGeometry().getVertices().get(face.getC()));
double distance3=point.distanceTo(matrixedPoint(mesh.getGeometry().getVertices().get(face.getC())));
if(distance3<distance){
vertexOfFaceIndex=2;
distance=distance3;
selection=mesh.getGeometry().getVertices().get(face.getC());
}
Face3 face2=mesh.getGeometry().getFaces().get(faceIndex);
int vertex = face2.gwtGet(vertexOfFaceIndex);
setSelectionVertex(vertex);
return selectecVertexIndex;
}
protected Vector3 matrixedPoint(Vector3 vec){
return vec.clone().applyMatrix4(mesh.getMatrixWorld());
}
private boolean visible=true;
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
if(selected){
if(selectedLine!=null){
selectedLine.setVisible(visible);
}
}
}
private boolean selected;
public boolean isSelected() {
return selected;
}
private double lineLength=0.1;
private Line selectedLine;
private int selectecVertexIndex=-1;//-1 means no selection
public void setSelectionVertex(int vertexIndex){
selectecVertexIndex=vertexIndex;
if(selectecVertexIndex==-1){
selected=false;
if(selectedLine!=null){
selectedLine.setVisible(false);
}
return;
}
Vector3 normal=THREE.Vector3();
for(int i=0;i<mesh.getGeometry().getFaces().length();i++){
Face3 face3=mesh.getGeometry().getFaces().get(i);
for(int j=0;j<3;j++){
int vindex=face3.gwtGet(j);
if(vindex==vertexIndex){
normal.add(face3.getVertexNormals().get(j));
}
}
}
normal.normalize();
Vector3 selection=mesh.getGeometry().getVertices().get(vertexIndex);
//TODO log switch
//LogUtils.log(vertexIndex+","+ThreeLog.get(selection));
//make lines
Matrix3 normalMatrix=THREE.Matrix3();
Vector3 v1 = THREE.Vector3();
Vector3 v2 = THREE.Vector3();
normalMatrix.getNormalMatrix( mesh.getMatrixWorld());
//Vector3 normal = face.getVertexNormals().get(vertexOfFaceIndex);
v1.copy( selection ).applyMatrix4( mesh.getMatrixWorld() );
v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( lineLength ).add( v1 );
updateLine(v1,v2);
}
public int getSelectecVertex() {
return selectecVertexIndex;
}
public void updateLine(Vector3 v1,Vector3 v2){
if(selectedLine==null){
Geometry geo = THREE.Geometry();//var geo = new THREE.Geometry();
geo.getVertices().push( THREE.Vector3( ));//geo.vertices.push( new THREE.Vector3( pos1[0], pos1[1], pos1[2] ) );
geo.getVertices().push( THREE.Vector3( ));//geo.vertices.push( new THREE.Vector3( pos2[0], pos2[1], pos2[2] ) );
//TODO support color
selectedLine = THREE.Line(geo, THREE.LineBasicMaterial(GWTParamUtils.LineBasicMaterial().color(0xff00ff).linewidth(1)));
lineContainer.add(selectedLine);
}
selectedLine.setVisible(visible);
selectedLine.getGeometry().getVertices().get(0).copy(v1);
selectedLine.getGeometry().getVertices().get(1).copy(v2);
selectedLine.getGeometry().setVerticesNeedUpdate(true);
selectedLine.getGeometry().computeBoundingSphere();
}
public void update() {
setSelectionVertex(selectecVertexIndex);
}
}
| akjava/GWTModelWeight | src/com/akjava/gwt/modelweight/client/MeshVertexSelector.java | Java | apache-2.0 | 5,810 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Wed Sep 03 20:03:06 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>MasterProtos.EnableTableRequestOrBuilder (HBase 0.98.6-hadoop2 API)</title>
<meta name="date" content="2014-09-03">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="MasterProtos.EnableTableRequestOrBuilder (HBase 0.98.6-hadoop2 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/MasterProtos.EnableTableRequestOrBuilder.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequestOrBuilder.html" target="_top">Frames</a></li>
<li><a href="MasterProtos.EnableTableRequestOrBuilder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.hadoop.hbase.protobuf.generated</div>
<h2 title="Interface MasterProtos.EnableTableRequestOrBuilder" class="title">Interface MasterProtos.EnableTableRequestOrBuilder</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd>com.google.protobuf.MessageLiteOrBuilder, com.google.protobuf.MessageOrBuilder</dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">MasterProtos.EnableTableRequest</a>, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">MasterProtos.EnableTableRequest.Builder</a></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.html" title="class in org.apache.hadoop.hbase.protobuf.generated">MasterProtos</a></dd>
</dl>
<hr>
<br>
<pre>public static interface <span class="strong">MasterProtos.EnableTableRequestOrBuilder</span>
extends com.google.protobuf.MessageOrBuilder</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/HBaseProtos.TableName.html" title="class in org.apache.hadoop.hbase.protobuf.generated">HBaseProtos.TableName</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequestOrBuilder.html#getTableName()">getTableName</a></strong>()</code>
<div class="block"><code>required .TableName table_name = 1;</code></div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/HBaseProtos.TableNameOrBuilder.html" title="interface in org.apache.hadoop.hbase.protobuf.generated">HBaseProtos.TableNameOrBuilder</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequestOrBuilder.html#getTableNameOrBuilder()">getTableNameOrBuilder</a></strong>()</code>
<div class="block"><code>required .TableName table_name = 1;</code></div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequestOrBuilder.html#hasTableName()">hasTableName</a></strong>()</code>
<div class="block"><code>required .TableName table_name = 1;</code></div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.google.protobuf.MessageOrBuilder">
<!-- -->
</a>
<h3>Methods inherited from interface com.google.protobuf.MessageOrBuilder</h3>
<code>findInitializationErrors, getAllFields, getDefaultInstanceForType, getDescriptorForType, getField, getInitializationErrorString, getRepeatedField, getRepeatedFieldCount, getUnknownFields, hasField</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.google.protobuf.MessageLiteOrBuilder">
<!-- -->
</a>
<h3>Methods inherited from interface com.google.protobuf.MessageLiteOrBuilder</h3>
<code>isInitialized</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="hasTableName()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hasTableName</h4>
<pre>boolean hasTableName()</pre>
<div class="block"><code>required .TableName table_name = 1;</code></div>
</li>
</ul>
<a name="getTableName()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTableName</h4>
<pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/HBaseProtos.TableName.html" title="class in org.apache.hadoop.hbase.protobuf.generated">HBaseProtos.TableName</a> getTableName()</pre>
<div class="block"><code>required .TableName table_name = 1;</code></div>
</li>
</ul>
<a name="getTableNameOrBuilder()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getTableNameOrBuilder</h4>
<pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/HBaseProtos.TableNameOrBuilder.html" title="interface in org.apache.hadoop.hbase.protobuf.generated">HBaseProtos.TableNameOrBuilder</a> getTableNameOrBuilder()</pre>
<div class="block"><code>required .TableName table_name = 1;</code></div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/MasterProtos.EnableTableRequestOrBuilder.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequestOrBuilder.html" target="_top">Frames</a></li>
<li><a href="MasterProtos.EnableTableRequestOrBuilder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| lshain/hbase-0.98.6-hadoop2 | docs/devapidocs/org/apache/hadoop/hbase/protobuf/generated/MasterProtos.EnableTableRequestOrBuilder.html | HTML | apache-2.0 | 11,336 |
package org.cam.geo.sink
import java.net.URL
import org.apache.commons.codec.binary.Base64
import org.apache.http.{HttpHeaders, HttpStatus}
import org.apache.http.client.methods.{HttpGet, _}
import org.apache.http.entity.{ContentType, StringEntity}
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import org.json4s._
import org.json4s.jackson.JsonMethods._
object ElasticsearchUtils {
/**
*
* @param dataSourceName the name of the data source
* @param esHostName the es host name
* @param esPort the es port
* @return
*/
//TODO: Change DataSource references to Index
def doesDataSourceExists(dataSourceName:String, esHostName:String, esPort:Int = 9200, userName:String, password:String):Boolean = {
val client = HttpClients.createDefault()
try {
val dataSourceNameToLowercase = dataSourceName.toLowerCase()
val existsURLStr = s"http://$esHostName:$esPort/$dataSourceNameToLowercase"
val existsURL:URL = new URL(existsURLStr)
val httpGet:HttpGet = new HttpGet(existsURL.toURI)
addAuthorizationHeader(httpGet, userName, password)
val existsResponse = client.execute(httpGet)
val existsResponseAsString = getHttpResponseAsString(existsResponse, httpGet)
try {
val existsOpt = existsResponseAsString.map(str => {
implicit val formats = DefaultFormats
(parse(str) \ "error").extractOpt.isEmpty
})
existsOpt match {
case Some(exists) =>
exists
case _ =>
println(s"Failed to determine if DataSource $dataSourceName exist!")
false
}
} catch {
case parseError: Throwable =>
println(s"Failed to determine if DataSource $dataSourceName exist!")
parseError.printStackTrace()
false
}
} finally {
client.close()
}
}
/**
* Helper method used to create basic datasource metadata
*
* @param dataSourceName the name of the data source
* @param fields the fields
* @param esHostName the es host name
* @param esPort the es port name
*/
def createDataSource(dataSourceName:String, fields:Array[EsField], esHostName:String, esPort:Int = 9200, userName:String, password:String, shards:Int=3, replicas:Int=1):Boolean = {
val client = HttpClients.createDefault()
try {
val dataSourceNameToLowercase = dataSourceName.toLowerCase()
val createMappingURLStr = s"http://$esHostName:$esPort/$dataSourceNameToLowercase"
val createMappingURL:URL = new URL(createMappingURLStr)
val httpPut:HttpPut = new HttpPut(createMappingURL.toURI)
addAuthorizationHeader(httpPut, userName, password)
httpPut.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
httpPut.setHeader("charset", "utf-8")
val createMappingRequest = createMappingJsonAsStr(dataSourceNameToLowercase, fields, shards, replicas)
println(createMappingRequest) //TODO: remove
httpPut.setEntity(new StringEntity(createMappingRequest, ContentType.APPLICATION_JSON))
// execute
val createResponse = client.execute(httpPut)
val createResponseAsString = getHttpResponseAsString(createResponse, httpPut)
try {
val createSuccessOpt = createResponseAsString.map(str => {
implicit val formats = DefaultFormats
(parse(str) \ "acknowledged").extract[Boolean]
})
createSuccessOpt match {
case Some(success) =>
if (!success) {
println(s"Failed to create the mapping for DataSource $dataSourceName! Response: ${createResponseAsString.orNull}")
throw new Exception(s"Failed to create the mapping for DataSource $dataSourceName! Response: ${createResponseAsString.orNull}")
}
case _ =>
println(s"Failed to create the mapping for DataSource $dataSourceName! Response: ${createResponseAsString.orNull}")
throw new Exception(s"Failed to create the mapping for DataSource $dataSourceName! Response: ${createResponseAsString.orNull}")
}
} catch {
case parseError: Throwable =>
println(s"Failed to create the mapping for DataSource $dataSourceName!")
parseError.printStackTrace()
throw new Exception(s"Failed to create the mapping for DataSource $dataSourceName!", parseError)
}
true
} finally {
client.close()
}
}
/**
* Helper method used to parse the HTTP Response into a String
*
* @param response the Htto Response Object
* @param request the Http Request (either GET or POST)
* @return a String
*/
private def getHttpResponseAsString(response:CloseableHttpResponse, request:HttpUriRequest):Option[String] = {
try {
val entity = response.getEntity
val responseString = {
if (entity != null) {
EntityUtils.toString(entity, "UTF-8")
} else {
""
}
}
val statusLine = response.getStatusLine
if (statusLine.getStatusCode != HttpStatus.SC_OK) {
println(s"The HTTP Request failed with code ${statusLine.getStatusCode} for URL: ${request.getURI}")
return None
}
Option(responseString)
} finally {
response.close()
}
}
/**
* Get the Mapping JSON as a Str
*
* @param datSourceName the name of the datasource
* @param fields the es fields to create
* @return a json str
*/
private def createMappingJsonAsStr(datSourceName:String, fields:Array[EsField], shards:Int=3, replicas:Int=1):String = {
s"""
|{
| "settings": {
| "number_of_shards" : $shards,
| "auto_expand_replicas" : 0,
| "number_of_replicas" : $replicas
| },
| "mappings": {
| "$datSourceName": {
| "properties": {
| ${createFieldMappingJsonAsStr(fields)}
| }
| }
| }
|}
""".stripMargin
}
private def createFieldMappingJsonAsStr(fields:Array[EsField]):String = {
fields.foldRight("")( (field, str) => {
val fieldJson = field.fieldType match {
case EsFieldType.Unknown => ""
case EsFieldType.GeoPoint =>
s"""
"${field.name}": {
"type": "geo_point"
}
""".stripMargin
case EsFieldType.GeoShape =>
s"""
"${field.name}": {
"type": "geo_shape",
"tree": "quadtree"
}
""".stripMargin
case EsFieldType.Keyword =>
s"""
"${field.name}": {
"type": "keyword"
}
""".stripMargin
case _ =>
s"""
"${field.name}": {
"type": "${field.fieldType.name}"
}
""".stripMargin
}
if (str != "")
str + "," + fieldJson
else
str + fieldJson
})
}
private def addAuthorizationHeader(httpRequest:HttpRequestBase, userName:String, password:String):Unit = {
// credentials
val authString = userName + ":" + password
val credentialString: String = Base64.encodeBase64String(authString.getBytes)
httpRequest.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + credentialString)
}
}
/**
* EsFieldType
*/
sealed trait EsFieldType {
def name: String
override def toString = name
}
object EsFieldType {
case object Keyword extends EsFieldType {
val name: String = "keyword"
}
case object Date extends EsFieldType {
val name: String = "date"
}
case object Double extends EsFieldType {
val name: String = "double"
}
case object Float extends EsFieldType {
val name: String = "float"
}
case object GeoPoint extends EsFieldType {
val name: String = "geo_point"
}
case object GeoShape extends EsFieldType {
val name: String = "geo_shape"
}
case object Integer extends EsFieldType {
val name: String = "integer"
}
case object Long extends EsFieldType {
val name: String = "long"
}
case object Short extends EsFieldType {
val name: String = "short"
}
case object Boolean extends EsFieldType {
val name: String = "boolean"
}
case object Binary extends EsFieldType {
val name: String = "binary"
}
case object Unknown extends EsFieldType {
val name: String = "unknown"
}
def fromString(str:String):EsFieldType = {
str.toLowerCase match {
case Keyword.name => Keyword
case Date.name => Date
case Double.name => Double
case Float.name => Float
case GeoPoint.name => GeoPoint
case GeoShape.name => GeoShape
case Integer.name => Integer
case Long.name => Long
case Short.name => Short
case Boolean.name => Boolean
case Binary.name => Binary
case _ => Unknown
}
}
}
/**
* EsField
*
* @param name name of the field
* @param fieldType the field type
*/
case class EsField(name:String, fieldType:EsFieldType)
| amollenkopf/dcos-iot-demo | spatiotemporal-esri-analytics/src/main/scala/org/cam/geo/sink/ElasticsearchUtils.scala | Scala | apache-2.0 | 9,036 |
# Colletotrichum peckii (Sacc.) Davis SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Trans. Wis. Acad. Sci. Arts Lett. 24: 296 (1929)
#### Original name
Vermicularia peckii Sacc.
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Glomerellaceae/Colletotrichum/Colletotrichum peckii/README.md | Markdown | apache-2.0 | 233 |
testDenormedIndexFungorumSmall | Sp2000/colplus-backend | colplus-ws/src/test/resources/dwca/20/README.md | Markdown | apache-2.0 | 30 |
package com.nowcoder.interview;
import java.util.Arrays;
/*
* 现在有一个数组,请找出数组中每个元素的后面比它大的最小的元素,若不存在则为-1。
给定一个int数组A及数组的大小n,请返回每个元素所求的值组成的数组。保证A中元素为正整数,且n小于等于1000。
测试样例:
[11,13,10,5,12,21,3],7
[12,21,12,12,21,-1,-1]
*/
public class NextBiggerElementII {
public int[] findNext(int[] A, int n) {
if(A==null||n<=0)
throw new IllegalArgumentException();
int[] result=new int[n];
for(int i=0;i<n;i++){
int j=i+1;
int min=Integer.MAX_VALUE;
for(;j<n;j++){
if(A[j]>A[i]&&A[j]<min){
min=A[j];
result[i]=min;
}
}
if(min==Integer.MAX_VALUE)
result[i]=-1;
}
return result;
}
public static void main(String[] args) {
NextBiggerElementII nextBiggerElementII=new NextBiggerElementII();
int[] a={11,13,10,5,12,21,3};
System.out.println(Arrays.toString(nextBiggerElementII.findNext(a, a.length)));
}
}
| pengood/CodeInterview | src/com/nowcoder/interview/NextBiggerElementII.java | Java | apache-2.0 | 1,030 |
# Wahlenbergia larraini Skottsb. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Campanulaceae/Wahlenbergia/Wahlenbergia larraini/README.md | Markdown | apache-2.0 | 180 |
---
layout: post
title: "Figure Checklist"
date: 2018-09-08 14:27:57 -0400
tags: [writing, checklist]
author: Joshua Vogelstein
---
The following is the checklist I use when making *explanatory figures* (including tables), which is a special class of figures. Other kinds of figures include "exploratory" and "schematic", which have somewhat different guidelines, and will be discussed elsewhere.
1. **Main Point** The main point of the figure "pops-out" to your audience (note: addressing this successfully requires knowing precisely what the main point is, and who your audience is). *This is by far the most important property of any figure, until you figure this out, there is no reason to do anything else.*
2. **Data to Ink Ratio** All data presented are critical to the main point (meaning none can be removed or summarized elsewhere). See Tufte's "data to ink ratio" principle, for example, [here](https://medium.com/@plotlygraphs/maximizing-the-data-ink-ratio-in-dashboards-and-slide-deck-7887f7c1fab). In other words, is there any way to reduce cognitive load for the audience, and still make the same point, for example, by removing unnecessary:
- borders,
- gridlines,
- data markers,
- legends (by labeling data directly),
- if the data are 2D, are you displaying it in 2D? (If not, remove that additional 3rd dimension. It is just confusing and obfuscatory.)
3. **Color** Use a clear consistent color palette.
- I recommend one of the following:
- [qualitative color scheme](http://colorbrewer2.org/#type=qualitative&scheme=Set1&n=9) (for multiple lines, RED is the line you want to draw attention to, e.g., your new algorithm):
- [diverging color scheme](http://colorbrewer2.org/#type=diverging&scheme=PRGn&n=11) (for heatmaps),
- [blue](http://colorbrewer2.org/#type=sequential&scheme=Blues&n=9) or [orange](http://colorbrewer2.org/#type=sequential&scheme=Oranges&n=9) sequential color scheme (for multiple lines changing a single variable, like n_train)
- Color use is consistent (within and across figures), meaning if a given algorithm uses blue as its color in one figure, it should use blue for that algorithm in all other figures, and blue should not be used for anything else.
- Is the default color probably gray, so that black can be used for emphasis?
- Make red the color of the line that you want the audience to attend to most. For example, upon introducing a new algorithm, and comparing to others, color the new algorithm red.
4. **Title** The title provides context (e.g., sample size, dimensionality, dataset/simulation name, etc.), and possibly conclusion.
5. **Axes**
- All axes are labeled (with units).
- Show the minimal possible number of numbers on the x- and y-axis. For example, if the units are not interesting/relevant, do not display numbers at all. If they are, try only two or three numbers.
- If it's a log scale, the axis label says so.
- Are the number of significant digits reasonable (eg, the number of significant digits cannot reasonably be larger than the sample size)?
- Axis labels should be words, not symbols, not abbreviations, so one need not read the caption to understand the figure.
- Are your axes 'tight’ (that is, are the bounds of the axes just larger than the max and min of what you want to show)? If not, do you have good reason for the excess?
- Is the aspect ratio correct? (Hint: if you rescaled both the width and height separately, almost definitely not.)
6. **Text**
- All font sizes are legible for the typical reader. Specifically, all fonts sizes (including axis labels, numbers, titles, etc.), should be the *same* size as the caption in the text. Note that there is basically no advantage to smaller fonts, but there is a huge advantage to clarity, especially for readers with poor eyesight (which is a larger fraction of the readers).
- All the letters/numbers are fully visible (i.e., not obscured by part of the figure).
- All lines are labeled (e.g., in legend) with clearly different colors/styles.
- Is your method named something other than ‘proposed method’ or 'our method’? If not, name it and use it throughout.
7. **Caption**
- Begin with a sentence (fragment) stating what the figure is demonstrating (i.e., why it is there). If the figure consists of multiple panels, one sentence explains the collective take home message of all the panels.
- Define all acronyms used in the figure.
- When relevant, state the sample size, dimensionality, and statistical test / procedure.
- End by pointing out particularly interesting aspects of the figure that one should note. - Is below the figure.
8. **Lines & Markers**
- If there are multiple lines/dots, is each a different line style and color?
- Are all lines sufficiently thick? (If you used matlab, and they are the default thickness, the answer is no.)
- Are all markers clearly different?
- If errorbars make sense, are they there? If there, does the caption explain whether they are standard error? If they are not there, is there a good justification provided for that?
8. **Aesthetics**
- Are all graphics that can be vector graphics actually vector graphics?
- Is anything not aligned that could be aligned?
- If it's a bar chart, does the y-axis start at zero (if it is a log axis, the answer is no)?
- If it's a pie chart, can you replace it with a stacked barchart (or something else)?
- If you are comparing multiple approaches across multiple settings, are you grouping by the key comparison (eg, usually group by setting to make comparisons easier)?
- Is there sufficient whitespace?
9. **Multipanel figures**
- Can certain axes/labels be removed because they are redundant?
- Does the caption specifically mention each?
- Are the captions for each collected together in the overall figure caption?
10. **Table**
- Can it be converted to a figure? If so, do it (put table in appendix if you are scared of losing the information)!
- Are the rows sorted in a reasonable fashion (ie, according to the most important column)?
| neurodata/blog.neurodata.io | _posts/2018-09-08-figures.md | Markdown | apache-2.0 | 6,170 |
<!DOCTYPE html>
<html>
<head>
<title>Auction Monitor</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
<link rel="icon" type="image/png" href="favicon.png"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<link rel="stylesheet" href="http://bridgeit.github.io/demo-jqm/css/mobile.css" type="text/css" />
<!-- bridgeit.js UNSTABLE VERSION -->
<script type="text/javascript" src="http://bridgeit.github.io/bridgeit.js/src/bridgeit.js"></script>
<!-- bridgeit.js STABLE VERSION
<script type="text/javascript" src="http://api.bridgeit.mobi/bridgeit/bridgeit.js"></script -->
<script type="text/javascript" src="md5.min.js"></script>
<script type="text/javascript" src="phonetic.js"></script>
<!-- APP ICONS -->
<link rel="apple-touch-icon" href="images/touch-icon-iphone.png"/>
<link rel="apple-touch-icon" sizes="76x76" href="images/touch-icon-ipad.png"/>
<link rel="apple-touch-icon" sizes="120x120" href="images/touch-icon-iphone-retina.png"/>
<link rel="apple-touch-icon" sizes="152x152" href="images/touch-icon-ipad-retina.png"/>
<link rel="apple-touch-startup-image" href="images/touch-startup-image.png"/>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-45568600-1', 'bridgeit.mobi');
ga('send', 'pageview');
</script>
</head>
<body style="font-family:sans-serif">
<h2>Auction Monitor</h2>
<fieldset class="desc">
<div class="row"><p class="normalText">Auction bidding demonstrated with Doc Service, Code Service, and Push Service.</p></div>
</fieldset>
<label for="auctionNameField" style='display:inline-block;min-width:80px'>Auction: </label>
<span><input type="text" style="width:80px" onchange="updateAuctionName(this.value)" id="auctionNameField" placeholder="auction name"></span><br>
<label for="usernameField" style='display:inline-block;min-width:80px'>User: </label>
<span><input type="text" style="width:80px" onchange="updateUserName(this.value)" id="usernameField"
autocorrect="off" autocapitalize="off"></span><br>
<label for="passwordField" style='display:inline-block;min-width:80px'>Password: </label>
<span><input type="password" style="width:80px" id="passwordField"></span><br>
<button id="loginButton" onclick="login();">Login</button>
<button id="regBtn"
onclick="bridgeit.register('_reg', 'handlePushRegistration');">Enable Cloud Push</button>
<br>
<fieldset style='width:auto;display:inline-block;' id="auctionTable">
</fieldset>
<script type="text/javascript">
var SERVICE = "http://dev.bridgeit.io";
var access_token = "cafebabe-cafe-4c92-beef-cafebabebeef";
var auth = null;
var PUSH_STORE_KEY = 'bridgeit.pushes';
var date = new Date();
var hourStamp = date.getHours() + date.getDate() * 100 + date.getMonth() * 100 * 100
var auctionName = phonetic.generate({capFirst:0, seed: hourStamp});
var userName = "auctioneer";
if (!document.getElementById("auctionNameField").value) {
document.getElementById("auctionNameField").value = auctionName;
}
if (!document.getElementById("usernameField").value) {
document.getElementById("usernameField").value = userName;
}
var cloudPushReady;
restoreAuction();
if (bridgeit.isRegistered()) {
document.getElementById('regBtn').style.display = 'none';
}
function updateUserName(newUserName) {
userName = newUserName;
bridgeit.addPushListener(userName, 'handleOutbid');
}
function addAuctionItem(itemName, itemValue) {
console.log("addAuctionItem " + itemName + " " + itemValue);
if (!itemValue) {
itemValue = 0;
}
xhr = new XMLHttpRequest();
xhr.open("POST", SERVICE + "/docs/edge/documents?access_token=" + access_token,false);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
var auctionItem = {
auction: auctionName,
item: itemName,
bid: itemValue,
bidder: userName
}
xhr.send(JSON.stringify(auctionItem));
bridgeit.push(auctionName);
}
function bid(itemName, itemValue) {
console.log("bid " + itemName + " " + itemValue);
if (!itemValue) {
itemValue = 0;
}
xhr = new XMLHttpRequest();
xhr.open("POST", SERVICE + "/code/edge/bid?access_token=" + access_token,false);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
var auctionItem = {
auction: auctionName,
item: itemName,
bid: itemValue,
bidder: userName
}
xhr.send(JSON.stringify(auctionItem));
}
function notifyBidHolder() {
xhr = new XMLHttpRequest();
xhr.open("GET", SERVICE + "/code/bridgeit-demo/api/bidNotify?auction=" + auctionName,false);
xhr.send();
}
function updateAuctionName(newAuctionName) {
auctionName = newAuctionName;
bridgeit.addPushListener(auctionName, 'handlePush');
}
function handlePushRegistration(event) {
console.log('handlePushRegistration() called, registered=' + bridgeit.isRegistered());
if (bridgeit.isRegistered()) {
document.getElementById('regBtn').style.display = 'none';
}
}
function restoreAuction() {
var bids;
var xhr = new XMLHttpRequest();
xhr.open("GET", SERVICE + "/docs/edge/documents?access_token=" + access_token +
"&query=" + encodeURIComponent(JSON.stringify({auction:auctionName})),false);
xhr.send();
try {
bids = JSON.parse(xhr.responseText);
} catch (e) { };
var htmlOut = document.getElementById("auctionTable");
var newHtml = "";
var maxBids = { };
if (bids) {
for (i = 0; i < bids.length; i++) {
var itemName = bids[i].item;
var itemValue = parseInt(bids[i].bid);
if (!maxBids[itemName]) {
maxBids[itemName] = bids[i];
} else {
if (parseInt(maxBids[itemName].bid) < itemValue) {
maxBids[itemName] = bids[i];
}
}
}
}
for (var index in maxBids) {
var row = maxBids[index];
newHtml += "<span style='display:inline-block;min-width:60px'>" + row.item +
"</span><input type='text' value='" +
row.bid + "'><button onclick='bid(\"" +
row.item +
"\", this.previousElementSibling.value)'>Bid</button><br>";
}
newHtml += "<hr>";
newHtml += "<span style='color:white'>Outbid!</span>";
newHtml += "<div style='float:right'><input type='text'><button onclick='addAuctionItem(this.previousElementSibling.value)'>Add</button></div>";
htmlOut.innerHTML = newHtml;
}
function login() {
var username = document.getElementById('usernameField').value;
var password = document.getElementById('passwordField').value;
bridgeit.useServices({
realm:"edge",
serviceBase:SERVICE});
auth = bridgeit.login(username, password);
bridgeit.usePushService();
bridgeit.addPushListener(auctionName, 'handlePush');
bridgeit.addPushListener(username, 'handlePush');
access_token = auth.access_token;
cloudPushReady = true;
}
function handleOutbid() {
var theTable = document.getElementById("auctionTable");
theTable.style.backgroundColor = "orange";
setTimeout(function(){
theTable.style.backgroundColor = "white";
}, 3000);
}
var lastPushTimeStamp = 0;
function handlePush() {
console.log("received push");
var now = new Date();
//an Ajax Push may be delivered but unacknowledged
//leading to duplication http://jira.icesoft.org/browse/PUSH-301
if (now.getTime() - lastPushTimeStamp < 600) {
console.log("Debouncing duplicate push: " +
(now.getTime() - lastPushTimeStamp));
return;
}
restoreAuction();
}
</script>
</body>
</html>
| bridgeit/edge | auctionMonitor.html | HTML | apache-2.0 | 8,843 |
# frozen_string_literal: true
# Copyright 2016-2021 Copado NCS LLC
#
# 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.
require "delegate"
module Kitchen
module Terraform
# This class delegates to a logger but ensures the debug level is the default level used for logging messages.
class DebugLogger < ::SimpleDelegator
# This method overrides the #<< method of the delegate to call #debug.
#
# @param message [#to_s] the message to be logged.
# @return [nil, true] if the given severity is high enough for this particular logger then return
# <code>nil</code>; else return <code>true</code>.
def <<(message)
debug message
end
end
end
end
| newcontext-oss/kitchen-terraform | lib/kitchen/terraform/debug_logger.rb | Ruby | apache-2.0 | 1,203 |
#include <stdio.h>
#include <setjmp.h>
#include <coroutine.h>
//#include <call_in_stack.h>
#include <gc.h>
#undef GC_LOG_BRIEF
#define GC_LOG_BRIEF false
static jmp_buf buf;
void second(void) {
xgc_debug("second\n");
longjmp(buf,1); // 跳回setjmp的调用处 - 使得setjmp返回值为1
}
void first(void) {
second();
xgc_debug("first\n");
}
extern void check_jumpbuf_nextpc();
void check_jmpbuf()
{
jmp_buf xbuf;
int x=222;
if ( ! setjmp(xbuf))
{
for (int i=0; i < sizeof(xbuf[0].__jmpbuf)/sizeof(__jmp_buf_reg_t); i++)
xgc_debug("[%d] %p\n", i, cast(void *, cast(void*, xbuf[0].__jmpbuf[i])));
printf("\n");
xgc_debug("sp = %p, %p\n", &xbuf, &x);
xgc_debug("pc = %p, next pc=%p\n", &check_jmpbuf, &check_jumpbuf_nextpc);
xgc_debug("pc = %p, next pc=%p\n", &check_jmpbuf, &&__next_pc);
printf("\n");
}
else
{
xgc_debug("main, x = %d\n",x);
}
__next_pc:
xgc_info("reg_t sizeof=%u, sizeof_uint(int)=%u, sizeof_uint(long)=%u\n", sizeof_uint(xbuf[0].__jmpbuf[0]), sizeof_uint(int), sizeof_uint(long));
xgc_info("__WORDSIZE = %d\n", __WORDSIZE );
xgc_info("__sizeof(long long) = %u\n", sizeof_uint(long long) );
}
void check_jumpbuf_nextpc()
{
}
int main()
{
volatile int x=33;
void *p = cast(void*, &main);
char *cp = cast(char*, &main);
xgc_info("%p, %p\n", p, cp+10);
xgc_info("%d\n", cast(int, sizeof(__jmp_buf_reg_t)));
check_jmpbuf();
if ( ! setjmp(buf))
{
first();
}
else
{
xgc_debug("main, x = %d\n",x);
}
return 0;
}
| ncisoft/cgc-lib | test/setjump-test.c | C | apache-2.0 | 1,612 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_20) on Wed Sep 24 10:02:06 EDT 2014 -->
<title>Uses of Class org.openntf.domino.nsfdata.structs.cd.CDLSOBJECT</title>
<meta name="date" content="2014-09-24">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.openntf.domino.nsfdata.structs.cd.CDLSOBJECT";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/openntf/domino/nsfdata/structs/cd/CDLSOBJECT.html" title="class in org.openntf.domino.nsfdata.structs.cd">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/openntf/domino/nsfdata/structs/cd/class-use/CDLSOBJECT.html" target="_top">Frames</a></li>
<li><a href="CDLSOBJECT.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.openntf.domino.nsfdata.structs.cd.CDLSOBJECT" class="title">Uses of Class<br>org.openntf.domino.nsfdata.structs.cd.CDLSOBJECT</h2>
</div>
<div class="classUseContainer">No usage of org.openntf.domino.nsfdata.structs.cd.CDLSOBJECT</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/openntf/domino/nsfdata/structs/cd/CDLSOBJECT.html" title="class in org.openntf.domino.nsfdata.structs.cd">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/openntf/domino/nsfdata/structs/cd/class-use/CDLSOBJECT.html" target="_top">Frames</a></li>
<li><a href="CDLSOBJECT.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| mariusj/org.openntf.domino | domino/core/javadoc/org/openntf/domino/nsfdata/structs/cd/class-use/CDLSOBJECT.html | HTML | apache-2.0 | 4,728 |
package org.openestate.io.immobiliare_it.xml;
import java.io.Serializable;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.CopyStrategy2;
import org.jvnet.jaxb2_commons.lang.CopyTo2;
import org.jvnet.jaxb2_commons.lang.Equals2;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy2;
import org.jvnet.jaxb2_commons.lang.JAXBCopyStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy;
import org.jvnet.jaxb2_commons.lang.ToString2;
import org.jvnet.jaxb2_commons.lang.ToStringStrategy2;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
/**
* <p>Java class for features-property complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="features-property">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="rooms" type="{http://feed.immobiliare.it}roomsType" minOccurs="0"/>
* <element name="size" type="{http://feed.immobiliare.it}sizeType" minOccurs="0"/>
* <element name="sizes" type="{http://feed.immobiliare.it}sizes" minOccurs="0"/>
* <element name="descriptions" type="{http://feed.immobiliare.it}descriptions" minOccurs="0"/>
* <element name="energy-class" type="{http://feed.immobiliare.it}classEnergy"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "features-property", propOrder = {
})
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public class FeaturesProperty implements Serializable, Cloneable, CopyTo2, Equals2, ToString2
{
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
protected RoomsType rooms;
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
protected SizeType size;
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
protected Sizes sizes;
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
protected Descriptions descriptions;
@XmlElement(name = "energy-class", required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
protected ClassEnergy energyClass;
/**
* Gets the value of the rooms property.
*
* @return
* possible object is
* {@link RoomsType }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public RoomsType getRooms() {
return rooms;
}
/**
* Sets the value of the rooms property.
*
* @param value
* allowed object is
* {@link RoomsType }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public void setRooms(RoomsType value) {
this.rooms = value;
}
/**
* Gets the value of the size property.
*
* @return
* possible object is
* {@link SizeType }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public SizeType getSize() {
return size;
}
/**
* Sets the value of the size property.
*
* @param value
* allowed object is
* {@link SizeType }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public void setSize(SizeType value) {
this.size = value;
}
/**
* Gets the value of the sizes property.
*
* @return
* possible object is
* {@link Sizes }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public Sizes getSizes() {
return sizes;
}
/**
* Sets the value of the sizes property.
*
* @param value
* allowed object is
* {@link Sizes }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public void setSizes(Sizes value) {
this.sizes = value;
}
/**
* Gets the value of the descriptions property.
*
* @return
* possible object is
* {@link Descriptions }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public Descriptions getDescriptions() {
return descriptions;
}
/**
* Sets the value of the descriptions property.
*
* @param value
* allowed object is
* {@link Descriptions }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public void setDescriptions(Descriptions value) {
this.descriptions = value;
}
/**
* Gets the value of the energyClass property.
*
* @return
* possible object is
* {@link ClassEnergy }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public ClassEnergy getEnergyClass() {
return energyClass;
}
/**
* Sets the value of the energyClass property.
*
* @param value
* allowed object is
* {@link ClassEnergy }
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public void setEnergyClass(ClassEnergy value) {
this.energyClass = value;
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public String toString() {
final ToStringStrategy2 strategy = JAXBToStringStrategy.INSTANCE2;
final StringBuilder buffer = new StringBuilder();
append(null, buffer, strategy);
return buffer.toString();
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) {
strategy.appendStart(locator, this, buffer);
appendFields(locator, buffer, strategy);
strategy.appendEnd(locator, this, buffer);
return buffer;
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) {
{
RoomsType theRooms;
theRooms = this.getRooms();
strategy.appendField(locator, this, "rooms", buffer, theRooms, (this.rooms!= null));
}
{
SizeType theSize;
theSize = this.getSize();
strategy.appendField(locator, this, "size", buffer, theSize, (this.size!= null));
}
{
Sizes theSizes;
theSizes = this.getSizes();
strategy.appendField(locator, this, "sizes", buffer, theSizes, (this.sizes!= null));
}
{
Descriptions theDescriptions;
theDescriptions = this.getDescriptions();
strategy.appendField(locator, this, "descriptions", buffer, theDescriptions, (this.descriptions!= null));
}
{
ClassEnergy theEnergyClass;
theEnergyClass = this.getEnergyClass();
strategy.appendField(locator, this, "energyClass", buffer, theEnergyClass, (this.energyClass!= null));
}
return buffer;
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public Object clone() {
return copyTo(createNewInstance());
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public Object copyTo(Object target) {
final CopyStrategy2 strategy = JAXBCopyStrategy.INSTANCE2;
return copyTo(null, target, strategy);
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public Object copyTo(ObjectLocator locator, Object target, CopyStrategy2 strategy) {
final Object draftCopy = ((target == null)?createNewInstance():target);
if (draftCopy instanceof FeaturesProperty) {
final FeaturesProperty copy = ((FeaturesProperty) draftCopy);
{
Boolean roomsShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.rooms!= null));
if (roomsShouldBeCopiedAndSet == Boolean.TRUE) {
RoomsType sourceRooms;
sourceRooms = this.getRooms();
RoomsType copyRooms = ((RoomsType) strategy.copy(LocatorUtils.property(locator, "rooms", sourceRooms), sourceRooms, (this.rooms!= null)));
copy.setRooms(copyRooms);
} else {
if (roomsShouldBeCopiedAndSet == Boolean.FALSE) {
copy.rooms = null;
}
}
}
{
Boolean sizeShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.size!= null));
if (sizeShouldBeCopiedAndSet == Boolean.TRUE) {
SizeType sourceSize;
sourceSize = this.getSize();
SizeType copySize = ((SizeType) strategy.copy(LocatorUtils.property(locator, "size", sourceSize), sourceSize, (this.size!= null)));
copy.setSize(copySize);
} else {
if (sizeShouldBeCopiedAndSet == Boolean.FALSE) {
copy.size = null;
}
}
}
{
Boolean sizesShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.sizes!= null));
if (sizesShouldBeCopiedAndSet == Boolean.TRUE) {
Sizes sourceSizes;
sourceSizes = this.getSizes();
Sizes copySizes = ((Sizes) strategy.copy(LocatorUtils.property(locator, "sizes", sourceSizes), sourceSizes, (this.sizes!= null)));
copy.setSizes(copySizes);
} else {
if (sizesShouldBeCopiedAndSet == Boolean.FALSE) {
copy.sizes = null;
}
}
}
{
Boolean descriptionsShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.descriptions!= null));
if (descriptionsShouldBeCopiedAndSet == Boolean.TRUE) {
Descriptions sourceDescriptions;
sourceDescriptions = this.getDescriptions();
Descriptions copyDescriptions = ((Descriptions) strategy.copy(LocatorUtils.property(locator, "descriptions", sourceDescriptions), sourceDescriptions, (this.descriptions!= null)));
copy.setDescriptions(copyDescriptions);
} else {
if (descriptionsShouldBeCopiedAndSet == Boolean.FALSE) {
copy.descriptions = null;
}
}
}
{
Boolean energyClassShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.energyClass!= null));
if (energyClassShouldBeCopiedAndSet == Boolean.TRUE) {
ClassEnergy sourceEnergyClass;
sourceEnergyClass = this.getEnergyClass();
ClassEnergy copyEnergyClass = ((ClassEnergy) strategy.copy(LocatorUtils.property(locator, "energyClass", sourceEnergyClass), sourceEnergyClass, (this.energyClass!= null)));
copy.setEnergyClass(copyEnergyClass);
} else {
if (energyClassShouldBeCopiedAndSet == Boolean.FALSE) {
copy.energyClass = null;
}
}
}
}
return draftCopy;
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public Object createNewInstance() {
return new FeaturesProperty();
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) {
if ((object == null)||(this.getClass()!= object.getClass())) {
return false;
}
if (this == object) {
return true;
}
final FeaturesProperty that = ((FeaturesProperty) object);
{
RoomsType lhsRooms;
lhsRooms = this.getRooms();
RoomsType rhsRooms;
rhsRooms = that.getRooms();
if (!strategy.equals(LocatorUtils.property(thisLocator, "rooms", lhsRooms), LocatorUtils.property(thatLocator, "rooms", rhsRooms), lhsRooms, rhsRooms, (this.rooms!= null), (that.rooms!= null))) {
return false;
}
}
{
SizeType lhsSize;
lhsSize = this.getSize();
SizeType rhsSize;
rhsSize = that.getSize();
if (!strategy.equals(LocatorUtils.property(thisLocator, "size", lhsSize), LocatorUtils.property(thatLocator, "size", rhsSize), lhsSize, rhsSize, (this.size!= null), (that.size!= null))) {
return false;
}
}
{
Sizes lhsSizes;
lhsSizes = this.getSizes();
Sizes rhsSizes;
rhsSizes = that.getSizes();
if (!strategy.equals(LocatorUtils.property(thisLocator, "sizes", lhsSizes), LocatorUtils.property(thatLocator, "sizes", rhsSizes), lhsSizes, rhsSizes, (this.sizes!= null), (that.sizes!= null))) {
return false;
}
}
{
Descriptions lhsDescriptions;
lhsDescriptions = this.getDescriptions();
Descriptions rhsDescriptions;
rhsDescriptions = that.getDescriptions();
if (!strategy.equals(LocatorUtils.property(thisLocator, "descriptions", lhsDescriptions), LocatorUtils.property(thatLocator, "descriptions", rhsDescriptions), lhsDescriptions, rhsDescriptions, (this.descriptions!= null), (that.descriptions!= null))) {
return false;
}
}
{
ClassEnergy lhsEnergyClass;
lhsEnergyClass = this.getEnergyClass();
ClassEnergy rhsEnergyClass;
rhsEnergyClass = that.getEnergyClass();
if (!strategy.equals(LocatorUtils.property(thisLocator, "energyClass", lhsEnergyClass), LocatorUtils.property(thatLocator, "energyClass", rhsEnergyClass), lhsEnergyClass, rhsEnergyClass, (this.energyClass!= null), (that.energyClass!= null))) {
return false;
}
}
return true;
}
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-08-15T07:05:08+02:00", comments = "JAXB RI v2.3.0")
public boolean equals(Object object) {
final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE2;
return equals(null, null, object, strategy);
}
}
| OpenEstate/OpenEstate-IO | ImmobiliareIT/src/main/jaxb/org/openestate/io/immobiliare_it/xml/FeaturesProperty.java | Java | apache-2.0 | 16,285 |
/* ++++++++++++++++
++++++BASICS+++++++
+++++++++++++++++*/
/*---------------- adjust fonts ----------------*/
@font-face {
font-family: "railway";
src: url("fonts/railway/Raleway-Regular.ttf"); }
.aui body {
font-size: 14px;
max-width: 1440px;
font-family: railway, sans-serif; }
.aui {
font-family: railway, sans-serif; }
/*---------------- make anchors in texts look like normal text ----------------*/
.aui .journal-content-article a[name], .aui .journal-content-article a[name]:hover, .aui .journal-content-article a[name]:focus,
.aui .journal-content-article a:not([href]), .aui .journal-content-article a:not([href]):hover, .aui .journal-content-article a:not([href]):focus {
color: #555555;
font-weight: inherit;
text-decoration: none; }
.aui h1 {
font-size: 2em;
line-height: 34px; }
.aui h2 {
font-size: 1.6em;
line-height: 28px; }
.aui h3 {
font-size: 1.4em;
line-height: 25px; }
.aui h4 {
font-size: 1.2em;
line-height: 25px; }
.aui h5, .aui h6 {
line-height: 20px; }
.aui h1, .aui h2, .aui h3, .aui h4, .aui h5, .aui h6 {
margin: 0px;
font-weight: 600;
padding-bottom: 10px; }
.aui b, .aui strong {
font-weight: 600; }
.aui li, .aui ul {
line-height: 20px; }
/*---------------- content to the top ----------------*/
#wrapper {
padding: 0 5em 0; }
/*---------------- hyphenation ----------------*/
a.aui pre,
.aui .navbar .nav li > a,
.html-editor.portlet-message-boards,
.aui .portlet-asset-publisher .asset-content,
.aui .portlet-asset-publisher .asset-summary,
.aui .portlet-asset-publisher .asset-title,
.aui .portlet-asset-publisher .header-title,
.aui .portlet-asset-publisher li.title-list,
.aui .portlet-blogs .entry-body,
.aui .portlet-blogs .entry-title,
.aui .portlet-blogs .header-title,
.aui .portlet-journal-content .journal-content-article,
.aui .portlet-message-boards .header-title,
.aui .portlet-message-boards .thread-body {
word-break: normal;
-moz-hyphens: manual;
-webkit-hyphens: manual;
-ms-hyphens: manual; }
/* ++++++++++++++++
++++++HEADER+++++++
+++++++++++++++++*/
.static-social-bookmark {
float: right;
bottom: 0px;
right: 0px;
position: absolute;
padding-bottom: 6px; }
.aui #banner h1 {
clip: auto;
position: relative;
float: left;
width: 100%;
text-align: center;
font-size: 2.25em;
font-weight: 600;
margin: 0px;
padding-top: 10px; }
.aui #banner .page-title a, .aui #banner .page-title a:hover, .aui #banner .page-title a:active, .aui #banner .page-title a:focus {
color: #555555;
font-weight: 600;
text-decoration: none;
outline: 0;
outline-offset: 0px; }
.logo {
float: left;
text-align: center;
width: 13%;
margin-right: 1%;
margin-left: 1%;
padding-bottom: 6px;
position: absolute;
bottom: 0; }
#heading {
overflow: auto;
position: relative;
padding-top: 10px;
width: 100%; }
.aui .breadcrumb {
text-align: left;
font-size: 14px;
color: #676767;
background-color: white; }
ul.breadcrumb {
padding-bottom: 3px !important; }
.aui .lfr-hudcrumbs {
z-index: 1002;
/*TODO: update/remove this line, as soon as map2-portlet has its z-indices updated*/ }
.aui #breadcrumbs {
margin-bottom: 0px;
position: absolute;
bottom: 0px;
left: 16%; }
.aui #breadcrumbs ul {
padding: 0px; }
.page-title {
overflow: hidden;
width: 68%;
margin-top: 25px;
padding-bottom: 20px;
/*for breadcrumbs not to be overflew*/
margin-left: 16%; }
.ist-topbar {
background-color: black;
/*margin-left: 16%;
margin-right: 16%;*/
margin-left: 0px;
margin-right: 0px;
margin-top: 10px;
white-space: nowrap;
overflow: hidden;
font-size: 12px;
line-height: 18px;
background-color: #F4F4F4; }
.aui #banner .ist-topbar p {
margin: 0px; }
div .ist-topbar {
/*visibility: hidden;*/
/*
Anpassung durch OtN:
Daraus folgt: CSS-Hack muss das auf display:block setzen
*/
display: none; }
/* ++++++++++++++++
++++++IMAGE++++++++
+++++++BlOCK+++++++
+++++++++++++++++*/
#image-blocks {
display: inline-block;
float: left;
overflow: hidden;
direction: rtl;
padding: 0px !important; }
#left-image-block {
width: 15%;
float: right;
margin-right: 1%; }
#center-image-block {
width: 68%;
float: right;
margin-right: 1%; }
#right-image-block {
width: 15%;
float: right; }
#left-image-block img, #right-image-block img, #center-image-block img {
width: 100% !important; }
/* ++++++++++++++++
++++NAVIGATION+++++
+++++++++++++++++*/
.aui #navigation {
/* startseite theme: do not show navigtion in desktop view*/
visibility: hidden; }
.aui #navigation {
clear: both;
font-size: 12px;
font-weight: 600;
margin-bottom: 15px;
position: relative;
font-family: railway, sans-serif;
z-index: 1001;
/*TODO: update/remove this line, as soon as map2-portlet has its z-indices updated*/ }
.aui #navigation .navbar-inner {
min-height: 28px;
padding-left: 1px;
padding-right: 1px; }
.aui #navigation .nav > li > a {
padding-left: 5px;
padding-right: 5px; }
.aui #navigation li {
line-height: 16px;
padding: 1px 1px; }
.aui #navigation .navbar-inner {
background: none repeat scroll 0% 0% #f4f4f4;
border-top: 1px solid #CCC; }
.aui #navigation .navbar-inner li a {
color: #000; }
.aui #navigation .nav .dropdown-menu {
background: none repeat scroll 0% 0% #009AE5 !important; }
.aui #navigation .nav li.active > a {
background-image: linear-gradient(#118ade 0px, #118ade 47%, #1273c7 100%);
color: #FFF; }
.aui #navigation .nav .dropdown-menu li > a:hover {
background-color: #000;
background: #2FA4F5;
color: #FFF; }
.aui #navigation .nav .dropdown-menu a {
color: #FFF; }
.aui #navigation .nav .dropdown-menu a:hover {
background-color: none repeat scroll 0% 0% #2FA4F5; }
.aui .navbar .icon-caret-down {
margin-left: 3px;
padding: 1px 0px; }
.aui .dockbar-split .dockbar .navbar-inner .nav-account-controls {
z-index: 1002;
/*TODO: update/remove this line, as soon as map2-portlet has its z-indices updated*/ }
/* ++++++++++++++++
+++++++MAIN++++++++
+++++CONTENT+++++++
+++++++++++++++++*/
/* ---------- Layout Columns ---------- */
.aui .row-fluid .width5of12left {
width: 62%;
float: left;
margin-right: 1%; }
.aui .row-fluid .width5of12right {
width: 62%;
float: right; }
.aui .row-fluid .width3of12left {
width: 37%;
float: left;
margin-right: 1%; }
.aui .row-fluid .width3of12right {
width: 37%;
float: right; }
.aui .row-fluid .width4of12left {
width: 49.5%;
float: left;
margin-right: 1%; }
.aui .row-fluid .width4of12right {
width: 49.5%;
float: right; }
.aui .row-fluid .width2of12right {
width: 15%;
float: right;
margin-left: 1%; }
.aui .row-fluid .width2of12left {
width: 15%;
float: left; }
.aui .row-fluid .width8of12 {
margin-left: 1%;
width: 68%; }
/* ++++++++++++++++
++SMARTPHONE+++++++
+++++++EXCLUSIVE+++
+++++CONTENT+++++++
+++++++++++++++++*/
#smartphone-exclusive-content-container, #smartphone-help-text {
display: none; }
#smartphone-content-toggle {
color: white;
background-image: linear-gradient(#41f68e 0px, #169656 47%, #41f68e 100%);
position: fixed;
z-index: 325;
right: 0px;
top: 90%;
left: auto;
margin-right: 60px;
width: 150px; }
/* ++++++++++++++++
++++++FOOTER+++++++
+++++++++++++++++*/
#footer {
text-align: right;
padding-top: 53px; }
/*default footer styles*/
div.politaktiv-theme-footer {
border-top: 1px solid #000000;
text-align: center; }
div.politaktiv-theme-footer ul {
display: inline-block;
list-style-type: none;
margin: 0px;
border: 0px;
padding: 0px; }
div.politaktiv-theme-footer ul li {
float: left;
color: #000000;
font-size: 11px;
font-weight: bold;
margin: 5px 15px 5px 15px; }
div.politaktiv-theme-footer ul li a {
text-decoration: none;
color: #000000;
font-size: inherit;
font-weight: inherit; }
#footer {
text-align: right; }
/* ++++++++++++++++
++++++OTHER++++++++
+++++++STYLES++++++
+++++++++++++++++*/
/* ---------- login styles ---------- */
.login-description-article {
max-width: 50%;
float: right; }
.login-content {
max-width: 50%;
float: left; }
.login-navigation {
max-width: 100%;
clear: both; }
/* ---------- registration styles ---------- */
.registration-content {
max-width: 68%;
float: left; }
.registration-content .taglib-captcha input {
width: 50px; }
.registration-description-article {
max-width: 28%;
float: right; }
.registration-navigation {
max-width: 100%;
clear: both; }
/*-------- carousel styles -----------*/
div[id^="p_p_id_31"] > .portlet-borderless-container {
padding: 0; }
.carousel, .carousel-item {
height: initial !important;
width: initial !important;
background-color: #FFF; }
.carousel, .carousel-content, .carousel-item, .carousel-item img {
max-width: 100% !important;
max-height: inherit !important; }
.carousel-content menu {
visibility: hidden !important; }
| PolitAktiv/politaktiv-standard3-theme-startseite | docroot/css/.sass-cache/custom_pa.css | CSS | apache-2.0 | 8,960 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=emulateIE7" />
<title>Coverage for /Users/ramonserranolopez/SourceTree/PracticaVerificacion/venv/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/authorization.py: 44%</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.hotkeys.js"></script>
<script type="text/javascript" src="jquery.isonscreen.js"></script>
<script type="text/javascript" src="coverage_html.js"></script>
<script type="text/javascript">
jQuery(document).ready(coverage.pyfile_ready);
</script>
</head>
<body class="pyfile">
<div id="header">
<div class="content">
<h1>Coverage for <b>/Users/ramonserranolopez/SourceTree/PracticaVerificacion/venv/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/authorization.py</b> :
<span class="pc_cov">44%</span>
</h1>
<img id="keyboard_icon" src="keybd_closed.png" alt="Show keyboard shortcuts" />
<h2 class="stats">
36 statements
<span class="run hide_run shortkey_r button_toggle_run">16 run</span>
<span class="mis shortkey_m button_toggle_mis">20 missing</span>
<span class="exc shortkey_x button_toggle_exc">0 excluded</span>
</h2>
</div>
</div>
<div class="help_panel">
<img id="panel_icon" src="keybd_open.png" alt="Hide keyboard shortcuts" />
<p class="legend">Hot-keys on this page</p>
<div>
<p class="keyhelp">
<span class="key">r</span>
<span class="key">m</span>
<span class="key">x</span>
<span class="key">p</span> toggle line displays
</p>
<p class="keyhelp">
<span class="key">j</span>
<span class="key">k</span> next/prev highlighted chunk
</p>
<p class="keyhelp">
<span class="key">0</span> (zero) top of page
</p>
<p class="keyhelp">
<span class="key">1</span> (one) first highlighted chunk
</p>
</div>
</div>
<div id="source">
<table>
<tr>
<td class="linenos">
<p id="n1" class="pln"><a href="#n1">1</a></p>
<p id="n2" class="stm run hide_run"><a href="#n2">2</a></p>
<p id="n3" class="pln"><a href="#n3">3</a></p>
<p id="n4" class="pln"><a href="#n4">4</a></p>
<p id="n5" class="pln"><a href="#n5">5</a></p>
<p id="n6" class="pln"><a href="#n6">6</a></p>
<p id="n7" class="pln"><a href="#n7">7</a></p>
<p id="n8" class="pln"><a href="#n8">8</a></p>
<p id="n9" class="stm run hide_run"><a href="#n9">9</a></p>
<p id="n10" class="pln"><a href="#n10">10</a></p>
<p id="n11" class="stm run hide_run"><a href="#n11">11</a></p>
<p id="n12" class="pln"><a href="#n12">12</a></p>
<p id="n13" class="stm run hide_run"><a href="#n13">13</a></p>
<p id="n14" class="pln"><a href="#n14">14</a></p>
<p id="n15" class="stm run hide_run"><a href="#n15">15</a></p>
<p id="n16" class="pln"><a href="#n16">16</a></p>
<p id="n17" class="stm run hide_run"><a href="#n17">17</a></p>
<p id="n18" class="pln"><a href="#n18">18</a></p>
<p id="n19" class="pln"><a href="#n19">19</a></p>
<p id="n20" class="stm run hide_run"><a href="#n20">20</a></p>
<p id="n21" class="pln"><a href="#n21">21</a></p>
<p id="n22" class="pln"><a href="#n22">22</a></p>
<p id="n23" class="pln"><a href="#n23">23</a></p>
<p id="n24" class="pln"><a href="#n24">24</a></p>
<p id="n25" class="pln"><a href="#n25">25</a></p>
<p id="n26" class="pln"><a href="#n26">26</a></p>
<p id="n27" class="pln"><a href="#n27">27</a></p>
<p id="n28" class="pln"><a href="#n28">28</a></p>
<p id="n29" class="pln"><a href="#n29">29</a></p>
<p id="n30" class="pln"><a href="#n30">30</a></p>
<p id="n31" class="pln"><a href="#n31">31</a></p>
<p id="n32" class="pln"><a href="#n32">32</a></p>
<p id="n33" class="pln"><a href="#n33">33</a></p>
<p id="n34" class="pln"><a href="#n34">34</a></p>
<p id="n35" class="pln"><a href="#n35">35</a></p>
<p id="n36" class="pln"><a href="#n36">36</a></p>
<p id="n37" class="pln"><a href="#n37">37</a></p>
<p id="n38" class="pln"><a href="#n38">38</a></p>
<p id="n39" class="pln"><a href="#n39">39</a></p>
<p id="n40" class="pln"><a href="#n40">40</a></p>
<p id="n41" class="pln"><a href="#n41">41</a></p>
<p id="n42" class="pln"><a href="#n42">42</a></p>
<p id="n43" class="pln"><a href="#n43">43</a></p>
<p id="n44" class="pln"><a href="#n44">44</a></p>
<p id="n45" class="pln"><a href="#n45">45</a></p>
<p id="n46" class="pln"><a href="#n46">46</a></p>
<p id="n47" class="pln"><a href="#n47">47</a></p>
<p id="n48" class="pln"><a href="#n48">48</a></p>
<p id="n49" class="pln"><a href="#n49">49</a></p>
<p id="n50" class="pln"><a href="#n50">50</a></p>
<p id="n51" class="pln"><a href="#n51">51</a></p>
<p id="n52" class="pln"><a href="#n52">52</a></p>
<p id="n53" class="pln"><a href="#n53">53</a></p>
<p id="n54" class="pln"><a href="#n54">54</a></p>
<p id="n55" class="pln"><a href="#n55">55</a></p>
<p id="n56" class="pln"><a href="#n56">56</a></p>
<p id="n57" class="pln"><a href="#n57">57</a></p>
<p id="n58" class="pln"><a href="#n58">58</a></p>
<p id="n59" class="pln"><a href="#n59">59</a></p>
<p id="n60" class="pln"><a href="#n60">60</a></p>
<p id="n61" class="pln"><a href="#n61">61</a></p>
<p id="n62" class="pln"><a href="#n62">62</a></p>
<p id="n63" class="pln"><a href="#n63">63</a></p>
<p id="n64" class="stm run hide_run"><a href="#n64">64</a></p>
<p id="n65" class="pln"><a href="#n65">65</a></p>
<p id="n66" class="stm mis"><a href="#n66">66</a></p>
<p id="n67" class="stm mis"><a href="#n67">67</a></p>
<p id="n68" class="stm mis"><a href="#n68">68</a></p>
<p id="n69" class="stm mis"><a href="#n69">69</a></p>
<p id="n70" class="pln"><a href="#n70">70</a></p>
<p id="n71" class="stm run hide_run"><a href="#n71">71</a></p>
<p id="n72" class="pln"><a href="#n72">72</a></p>
<p id="n73" class="stm mis"><a href="#n73">73</a></p>
<p id="n74" class="pln"><a href="#n74">74</a></p>
<p id="n75" class="stm run hide_run"><a href="#n75">75</a></p>
<p id="n76" class="pln"><a href="#n76">76</a></p>
<p id="n77" class="stm mis"><a href="#n77">77</a></p>
<p id="n78" class="pln"><a href="#n78">78</a></p>
<p id="n79" class="stm run hide_run"><a href="#n79">79</a></p>
<p id="n80" class="pln"><a href="#n80">80</a></p>
<p id="n81" class="stm mis"><a href="#n81">81</a></p>
<p id="n82" class="pln"><a href="#n82">82</a></p>
<p id="n83" class="stm run hide_run"><a href="#n83">83</a></p>
<p id="n84" class="pln"><a href="#n84">84</a></p>
<p id="n85" class="stm mis"><a href="#n85">85</a></p>
<p id="n86" class="pln"><a href="#n86">86</a></p>
<p id="n87" class="stm run hide_run"><a href="#n87">87</a></p>
<p id="n88" class="stm run hide_run"><a href="#n88">88</a></p>
<p id="n89" class="pln"><a href="#n89">89</a></p>
<p id="n90" class="pln"><a href="#n90">90</a></p>
<p id="n91" class="stm mis"><a href="#n91">91</a></p>
<p id="n92" class="pln"><a href="#n92">92</a></p>
<p id="n93" class="stm mis"><a href="#n93">93</a></p>
<p id="n94" class="pln"><a href="#n94">94</a></p>
<p id="n95" class="stm mis"><a href="#n95">95</a></p>
<p id="n96" class="stm mis"><a href="#n96">96</a></p>
<p id="n97" class="stm mis"><a href="#n97">97</a></p>
<p id="n98" class="stm mis"><a href="#n98">98</a></p>
<p id="n99" class="pln"><a href="#n99">99</a></p>
<p id="n100" class="stm mis"><a href="#n100">100</a></p>
<p id="n101" class="pln"><a href="#n101">101</a></p>
<p id="n102" class="stm mis"><a href="#n102">102</a></p>
<p id="n103" class="pln"><a href="#n103">103</a></p>
<p id="n104" class="pln"><a href="#n104">104</a></p>
<p id="n105" class="stm run hide_run"><a href="#n105">105</a></p>
<p id="n106" class="stm run hide_run"><a href="#n106">106</a></p>
<p id="n107" class="pln"><a href="#n107">107</a></p>
<p id="n108" class="pln"><a href="#n108">108</a></p>
<p id="n109" class="stm mis"><a href="#n109">109</a></p>
<p id="n110" class="pln"><a href="#n110">110</a></p>
<p id="n111" class="stm mis"><a href="#n111">111</a></p>
<p id="n112" class="stm mis"><a href="#n112">112</a></p>
<p id="n113" class="pln"><a href="#n113">113</a></p>
<p id="n114" class="stm mis"><a href="#n114">114</a></p>
</td>
<td class="text">
<p id="t1" class="pln"><span class="com"># -*- coding: utf-8 -*-</span><span class="strut"> </span></p>
<p id="t2" class="stm run hide_run"><span class="str">"""</span><span class="strut"> </span></p>
<p id="t3" class="pln"><span class="str">oauthlib.oauth2.rfc6749</span><span class="strut"> </span></p>
<p id="t4" class="pln"><span class="str">~~~~~~~~~~~~~~~~~~~~~~~</span><span class="strut"> </span></p>
<p id="t5" class="pln"><span class="strut"> </span></p>
<p id="t6" class="pln"><span class="str">This module is an implementation of various logic needed</span><span class="strut"> </span></p>
<p id="t7" class="pln"><span class="str">for consuming and providing OAuth 2.0 RFC6749.</span><span class="strut"> </span></p>
<p id="t8" class="pln"><span class="str">"""</span><span class="strut"> </span></p>
<p id="t9" class="stm run hide_run"><span class="key">from</span> <span class="nam">__future__</span> <span class="key">import</span> <span class="nam">absolute_import</span><span class="op">,</span> <span class="nam">unicode_literals</span><span class="strut"> </span></p>
<p id="t10" class="pln"><span class="strut"> </span></p>
<p id="t11" class="stm run hide_run"><span class="key">import</span> <span class="nam">logging</span><span class="strut"> </span></p>
<p id="t12" class="pln"><span class="strut"> </span></p>
<p id="t13" class="stm run hide_run"><span class="key">from</span> <span class="nam">oauthlib</span><span class="op">.</span><span class="nam">common</span> <span class="key">import</span> <span class="nam">Request</span><span class="strut"> </span></p>
<p id="t14" class="pln"><span class="strut"> </span></p>
<p id="t15" class="stm run hide_run"><span class="key">from</span> <span class="op">.</span><span class="nam">base</span> <span class="key">import</span> <span class="nam">BaseEndpoint</span><span class="op">,</span> <span class="nam">catch_errors_and_unavailability</span><span class="strut"> </span></p>
<p id="t16" class="pln"><span class="strut"> </span></p>
<p id="t17" class="stm run hide_run"><span class="nam">log</span> <span class="op">=</span> <span class="nam">logging</span><span class="op">.</span><span class="nam">getLogger</span><span class="op">(</span><span class="nam">__name__</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t18" class="pln"><span class="strut"> </span></p>
<p id="t19" class="pln"><span class="strut"> </span></p>
<p id="t20" class="stm run hide_run"><span class="key">class</span> <span class="nam">AuthorizationEndpoint</span><span class="op">(</span><span class="nam">BaseEndpoint</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t21" class="pln"><span class="strut"> </span></p>
<p id="t22" class="pln"> <span class="str">"""Authorization endpoint - used by the client to obtain authorization</span><span class="strut"> </span></p>
<p id="t23" class="pln"><span class="str"> from the resource owner via user-agent redirection.</span><span class="strut"> </span></p>
<p id="t24" class="pln"><span class="strut"> </span></p>
<p id="t25" class="pln"><span class="str"> The authorization endpoint is used to interact with the resource</span><span class="strut"> </span></p>
<p id="t26" class="pln"><span class="str"> owner and obtain an authorization grant. The authorization server</span><span class="strut"> </span></p>
<p id="t27" class="pln"><span class="str"> MUST first verify the identity of the resource owner. The way in</span><span class="strut"> </span></p>
<p id="t28" class="pln"><span class="str"> which the authorization server authenticates the resource owner (e.g.</span><span class="strut"> </span></p>
<p id="t29" class="pln"><span class="str"> username and password login, session cookies) is beyond the scope of</span><span class="strut"> </span></p>
<p id="t30" class="pln"><span class="str"> this specification.</span><span class="strut"> </span></p>
<p id="t31" class="pln"><span class="strut"> </span></p>
<p id="t32" class="pln"><span class="str"> The endpoint URI MAY include an "application/x-www-form-urlencoded"</span><span class="strut"> </span></p>
<p id="t33" class="pln"><span class="str"> formatted (per `Appendix B`_) query component,</span><span class="strut"> </span></p>
<p id="t34" class="pln"><span class="str"> which MUST be retained when adding additional query parameters. The</span><span class="strut"> </span></p>
<p id="t35" class="pln"><span class="str"> endpoint URI MUST NOT include a fragment component::</span><span class="strut"> </span></p>
<p id="t36" class="pln"><span class="strut"> </span></p>
<p id="t37" class="pln"><span class="str"> https://example.com/path?query=component # OK</span><span class="strut"> </span></p>
<p id="t38" class="pln"><span class="str"> https://example.com/path?query=component#fragment # Not OK</span><span class="strut"> </span></p>
<p id="t39" class="pln"><span class="strut"> </span></p>
<p id="t40" class="pln"><span class="str"> Since requests to the authorization endpoint result in user</span><span class="strut"> </span></p>
<p id="t41" class="pln"><span class="str"> authentication and the transmission of clear-text credentials (in the</span><span class="strut"> </span></p>
<p id="t42" class="pln"><span class="str"> HTTP response), the authorization server MUST require the use of TLS</span><span class="strut"> </span></p>
<p id="t43" class="pln"><span class="str"> as described in Section 1.6 when sending requests to the</span><span class="strut"> </span></p>
<p id="t44" class="pln"><span class="str"> authorization endpoint::</span><span class="strut"> </span></p>
<p id="t45" class="pln"><span class="strut"> </span></p>
<p id="t46" class="pln"><span class="str"> # We will deny any request which URI schema is not with https</span><span class="strut"> </span></p>
<p id="t47" class="pln"><span class="strut"> </span></p>
<p id="t48" class="pln"><span class="str"> The authorization server MUST support the use of the HTTP "GET"</span><span class="strut"> </span></p>
<p id="t49" class="pln"><span class="str"> method [RFC2616] for the authorization endpoint, and MAY support the</span><span class="strut"> </span></p>
<p id="t50" class="pln"><span class="str"> use of the "POST" method as well::</span><span class="strut"> </span></p>
<p id="t51" class="pln"><span class="strut"> </span></p>
<p id="t52" class="pln"><span class="str"> # HTTP method is currently not enforced</span><span class="strut"> </span></p>
<p id="t53" class="pln"><span class="strut"> </span></p>
<p id="t54" class="pln"><span class="str"> Parameters sent without a value MUST be treated as if they were</span><span class="strut"> </span></p>
<p id="t55" class="pln"><span class="str"> omitted from the request. The authorization server MUST ignore</span><span class="strut"> </span></p>
<p id="t56" class="pln"><span class="str"> unrecognized request parameters. Request and response parameters</span><span class="strut"> </span></p>
<p id="t57" class="pln"><span class="str"> MUST NOT be included more than once::</span><span class="strut"> </span></p>
<p id="t58" class="pln"><span class="strut"> </span></p>
<p id="t59" class="pln"><span class="str"> # Enforced through the design of oauthlib.common.Request</span><span class="strut"> </span></p>
<p id="t60" class="pln"><span class="strut"> </span></p>
<p id="t61" class="pln"><span class="str"> .. _`Appendix B`: http://tools.ietf.org/html/rfc6749#appendix-B</span><span class="strut"> </span></p>
<p id="t62" class="pln"><span class="str"> """</span><span class="strut"> </span></p>
<p id="t63" class="pln"><span class="strut"> </span></p>
<p id="t64" class="stm run hide_run"> <span class="key">def</span> <span class="nam">__init__</span><span class="op">(</span><span class="nam">self</span><span class="op">,</span> <span class="nam">default_response_type</span><span class="op">,</span> <span class="nam">default_token_type</span><span class="op">,</span><span class="strut"> </span></p>
<p id="t65" class="pln"> <span class="nam">response_types</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t66" class="stm mis"> <span class="nam">BaseEndpoint</span><span class="op">.</span><span class="nam">__init__</span><span class="op">(</span><span class="nam">self</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t67" class="stm mis"> <span class="nam">self</span><span class="op">.</span><span class="nam">_response_types</span> <span class="op">=</span> <span class="nam">response_types</span><span class="strut"> </span></p>
<p id="t68" class="stm mis"> <span class="nam">self</span><span class="op">.</span><span class="nam">_default_response_type</span> <span class="op">=</span> <span class="nam">default_response_type</span><span class="strut"> </span></p>
<p id="t69" class="stm mis"> <span class="nam">self</span><span class="op">.</span><span class="nam">_default_token_type</span> <span class="op">=</span> <span class="nam">default_token_type</span><span class="strut"> </span></p>
<p id="t70" class="pln"><span class="strut"> </span></p>
<p id="t71" class="stm run hide_run"> <span class="op">@</span><span class="nam">property</span><span class="strut"> </span></p>
<p id="t72" class="pln"> <span class="key">def</span> <span class="nam">response_types</span><span class="op">(</span><span class="nam">self</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t73" class="stm mis"> <span class="key">return</span> <span class="nam">self</span><span class="op">.</span><span class="nam">_response_types</span><span class="strut"> </span></p>
<p id="t74" class="pln"><span class="strut"> </span></p>
<p id="t75" class="stm run hide_run"> <span class="op">@</span><span class="nam">property</span><span class="strut"> </span></p>
<p id="t76" class="pln"> <span class="key">def</span> <span class="nam">default_response_type</span><span class="op">(</span><span class="nam">self</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t77" class="stm mis"> <span class="key">return</span> <span class="nam">self</span><span class="op">.</span><span class="nam">_default_response_type</span><span class="strut"> </span></p>
<p id="t78" class="pln"><span class="strut"> </span></p>
<p id="t79" class="stm run hide_run"> <span class="op">@</span><span class="nam">property</span><span class="strut"> </span></p>
<p id="t80" class="pln"> <span class="key">def</span> <span class="nam">default_response_type_handler</span><span class="op">(</span><span class="nam">self</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t81" class="stm mis"> <span class="key">return</span> <span class="nam">self</span><span class="op">.</span><span class="nam">response_types</span><span class="op">.</span><span class="nam">get</span><span class="op">(</span><span class="nam">self</span><span class="op">.</span><span class="nam">default_response_type</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t82" class="pln"><span class="strut"> </span></p>
<p id="t83" class="stm run hide_run"> <span class="op">@</span><span class="nam">property</span><span class="strut"> </span></p>
<p id="t84" class="pln"> <span class="key">def</span> <span class="nam">default_token_type</span><span class="op">(</span><span class="nam">self</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t85" class="stm mis"> <span class="key">return</span> <span class="nam">self</span><span class="op">.</span><span class="nam">_default_token_type</span><span class="strut"> </span></p>
<p id="t86" class="pln"><span class="strut"> </span></p>
<p id="t87" class="stm run hide_run"> <span class="op">@</span><span class="nam">catch_errors_and_unavailability</span><span class="strut"> </span></p>
<p id="t88" class="stm run hide_run"> <span class="key">def</span> <span class="nam">create_authorization_response</span><span class="op">(</span><span class="nam">self</span><span class="op">,</span> <span class="nam">uri</span><span class="op">,</span> <span class="nam">http_method</span><span class="op">=</span><span class="str">'GET'</span><span class="op">,</span> <span class="nam">body</span><span class="op">=</span><span class="nam">None</span><span class="op">,</span><span class="strut"> </span></p>
<p id="t89" class="pln"> <span class="nam">headers</span><span class="op">=</span><span class="nam">None</span><span class="op">,</span> <span class="nam">scopes</span><span class="op">=</span><span class="nam">None</span><span class="op">,</span> <span class="nam">credentials</span><span class="op">=</span><span class="nam">None</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t90" class="pln"> <span class="str">"""Extract response_type and route to the designated handler."""</span><span class="strut"> </span></p>
<p id="t91" class="stm mis"> <span class="nam">request</span> <span class="op">=</span> <span class="nam">Request</span><span class="op">(</span><span class="strut"> </span></p>
<p id="t92" class="pln"> <span class="nam">uri</span><span class="op">,</span> <span class="nam">http_method</span><span class="op">=</span><span class="nam">http_method</span><span class="op">,</span> <span class="nam">body</span><span class="op">=</span><span class="nam">body</span><span class="op">,</span> <span class="nam">headers</span><span class="op">=</span><span class="nam">headers</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t93" class="stm mis"> <span class="nam">request</span><span class="op">.</span><span class="nam">scopes</span> <span class="op">=</span> <span class="nam">scopes</span><span class="strut"> </span></p>
<p id="t94" class="pln"> <span class="com"># TODO: decide whether this should be a required argument</span><span class="strut"> </span></p>
<p id="t95" class="stm mis"> <span class="nam">request</span><span class="op">.</span><span class="nam">user</span> <span class="op">=</span> <span class="nam">None</span> <span class="com"># TODO: explain this in docs</span><span class="strut"> </span></p>
<p id="t96" class="stm mis"> <span class="key">for</span> <span class="nam">k</span><span class="op">,</span> <span class="nam">v</span> <span class="key">in</span> <span class="op">(</span><span class="nam">credentials</span> <span class="key">or</span> <span class="op">{</span><span class="op">}</span><span class="op">)</span><span class="op">.</span><span class="nam">items</span><span class="op">(</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t97" class="stm mis"> <span class="nam">setattr</span><span class="op">(</span><span class="nam">request</span><span class="op">,</span> <span class="nam">k</span><span class="op">,</span> <span class="nam">v</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t98" class="stm mis"> <span class="nam">response_type_handler</span> <span class="op">=</span> <span class="nam">self</span><span class="op">.</span><span class="nam">response_types</span><span class="op">.</span><span class="nam">get</span><span class="op">(</span><span class="strut"> </span></p>
<p id="t99" class="pln"> <span class="nam">request</span><span class="op">.</span><span class="nam">response_type</span><span class="op">,</span> <span class="nam">self</span><span class="op">.</span><span class="nam">default_response_type_handler</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t100" class="stm mis"> <span class="nam">log</span><span class="op">.</span><span class="nam">debug</span><span class="op">(</span><span class="str">'Dispatching response_type %s request to %r.'</span><span class="op">,</span><span class="strut"> </span></p>
<p id="t101" class="pln"> <span class="nam">request</span><span class="op">.</span><span class="nam">response_type</span><span class="op">,</span> <span class="nam">response_type_handler</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t102" class="stm mis"> <span class="key">return</span> <span class="nam">response_type_handler</span><span class="op">.</span><span class="nam">create_authorization_response</span><span class="op">(</span><span class="strut"> </span></p>
<p id="t103" class="pln"> <span class="nam">request</span><span class="op">,</span> <span class="nam">self</span><span class="op">.</span><span class="nam">default_token_type</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t104" class="pln"><span class="strut"> </span></p>
<p id="t105" class="stm run hide_run"> <span class="op">@</span><span class="nam">catch_errors_and_unavailability</span><span class="strut"> </span></p>
<p id="t106" class="stm run hide_run"> <span class="key">def</span> <span class="nam">validate_authorization_request</span><span class="op">(</span><span class="nam">self</span><span class="op">,</span> <span class="nam">uri</span><span class="op">,</span> <span class="nam">http_method</span><span class="op">=</span><span class="str">'GET'</span><span class="op">,</span> <span class="nam">body</span><span class="op">=</span><span class="nam">None</span><span class="op">,</span><span class="strut"> </span></p>
<p id="t107" class="pln"> <span class="nam">headers</span><span class="op">=</span><span class="nam">None</span><span class="op">)</span><span class="op">:</span><span class="strut"> </span></p>
<p id="t108" class="pln"> <span class="str">"""Extract response_type and route to the designated handler."""</span><span class="strut"> </span></p>
<p id="t109" class="stm mis"> <span class="nam">request</span> <span class="op">=</span> <span class="nam">Request</span><span class="op">(</span><span class="strut"> </span></p>
<p id="t110" class="pln"> <span class="nam">uri</span><span class="op">,</span> <span class="nam">http_method</span><span class="op">=</span><span class="nam">http_method</span><span class="op">,</span> <span class="nam">body</span><span class="op">=</span><span class="nam">body</span><span class="op">,</span> <span class="nam">headers</span><span class="op">=</span><span class="nam">headers</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t111" class="stm mis"> <span class="nam">request</span><span class="op">.</span><span class="nam">scopes</span> <span class="op">=</span> <span class="nam">None</span><span class="strut"> </span></p>
<p id="t112" class="stm mis"> <span class="nam">response_type_handler</span> <span class="op">=</span> <span class="nam">self</span><span class="op">.</span><span class="nam">response_types</span><span class="op">.</span><span class="nam">get</span><span class="op">(</span><span class="strut"> </span></p>
<p id="t113" class="pln"> <span class="nam">request</span><span class="op">.</span><span class="nam">response_type</span><span class="op">,</span> <span class="nam">self</span><span class="op">.</span><span class="nam">default_response_type_handler</span><span class="op">)</span><span class="strut"> </span></p>
<p id="t114" class="stm mis"> <span class="key">return</span> <span class="nam">response_type_handler</span><span class="op">.</span><span class="nam">validate_authorization_request</span><span class="op">(</span><span class="nam">request</span><span class="op">)</span><span class="strut"> </span></p>
</td>
</tr>
</table>
</div>
<div id="footer">
<div class="content">
<p>
<a class="nav" href="index.html">« index</a> <a class="nav" href="https://coverage.readthedocs.org">coverage.py v4.0.3</a>,
created at 2016-06-01 05:35
</p>
</div>
</div>
</body>
</html>
| rslnautic/practica-verificacion | coverage/_Users_ramonserranolopez_SourceTree_PracticaVerificacion_venv_lib_python2_7_site-packages_oauthlib_oauth2_rfc6749_endpoints_authorization_py.html | HTML | apache-2.0 | 30,960 |
/*
Copyright 2011, 2014 Google Inc.
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 netutil identifies the system userid responsible for
// localhost TCP connections.
package netutil
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/user"
"regexp"
"runtime"
"strconv"
"strings"
)
var (
ErrNotFound = errors.New("netutil: connection not found")
ErrUnsupportedOS = errors.New("netutil: not implemented on this operating system")
)
// ConnUserid returns the uid that owns the given localhost connection.
// The returned error is ErrNotFound if the connection wasn't found.
func ConnUserid(conn net.Conn) (uid int, err error) {
return AddrPairUserid(conn.LocalAddr(), conn.RemoteAddr())
}
// HostPortToIP parses a host:port to a TCPAddr without resolving names.
// If given a context IP, it will resolve localhost to match the context's IP family.
func HostPortToIP(hostport string, ctx *net.TCPAddr) (hostaddr *net.TCPAddr, err error) {
host, port, err := net.SplitHostPort(hostport)
if err != nil {
return nil, err
}
iport, err := strconv.Atoi(port)
if err != nil || iport < 0 || iport > 0xFFFF {
return nil, fmt.Errorf("invalid port %s", iport)
}
var addr net.IP
if ctx != nil && host == "localhost" {
if ctx.IP.To4() != nil {
addr = net.IPv4(127, 0, 0, 1)
} else {
addr = net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
}
} else if addr = net.ParseIP(host); addr == nil {
return nil, fmt.Errorf("could not parse IP %s", host)
}
return &net.TCPAddr{IP: addr, Port: iport}, nil
}
// AddrPairUserid returns the local userid who owns the TCP connection
// given by the local and remote ip:port (lipport and ripport,
// respectively). Returns ErrNotFound for the error if the TCP connection
// isn't found.
func AddrPairUserid(local, remote net.Addr) (uid int, err error) {
lAddr, lOk := local.(*net.TCPAddr)
rAddr, rOk := remote.(*net.TCPAddr)
if !(lOk && rOk) {
return -1, fmt.Errorf("netutil: Could not convert Addr to TCPAddr.")
}
localv4 := (lAddr.IP.To4() != nil)
remotev4 := (rAddr.IP.To4() != nil)
if localv4 != remotev4 {
return -1, fmt.Errorf("netutil: address pairs of different families; localv4=%v, remotev4=%v",
localv4, remotev4)
}
switch runtime.GOOS {
case "darwin":
return uidFromLsof(lAddr.IP, lAddr.Port, rAddr.IP, rAddr.Port)
case "freebsd":
return uidFromSockstat(lAddr.IP, lAddr.Port, rAddr.IP, rAddr.Port)
case "linux":
file := "/proc/net/tcp"
if !localv4 {
file = "/proc/net/tcp6"
}
f, err := os.Open(file)
if err != nil {
return -1, fmt.Errorf("Error opening %s: %v", file, err)
}
defer f.Close()
return uidFromProcReader(lAddr.IP, lAddr.Port, rAddr.IP, rAddr.Port, f)
}
return 0, ErrUnsupportedOS
}
func toLinuxIPv4Order(b []byte) []byte {
binary.BigEndian.PutUint32(b, binary.LittleEndian.Uint32(b))
return b
}
func toLinuxIPv6Order(b []byte) []byte {
for i := 0; i < 16; i += 4 {
sb := b[i : i+4]
binary.BigEndian.PutUint32(sb, binary.LittleEndian.Uint32(sb))
}
return b
}
type maybeBrackets net.IP
func (p maybeBrackets) String() string {
s := net.IP(p).String()
if strings.Contains(s, ":") {
return "[" + s + "]"
}
return s
}
// Changed by tests.
var uidFromUsername = uidFromUsernameFn
func uidFromUsernameFn(username string) (uid int, err error) {
if uid := os.Getuid(); uid != 0 && username == os.Getenv("USER") {
return uid, nil
}
u, err := user.Lookup(username)
if err == nil {
uid, err := strconv.Atoi(u.Uid)
return uid, err
}
return 0, err
}
func uidFromLsof(lip net.IP, lport int, rip net.IP, rport int) (uid int, err error) {
seek := fmt.Sprintf("%s:%d->%s:%d", maybeBrackets(lip), lport, maybeBrackets(rip), rport)
seekb := []byte(seek)
if _, err = exec.LookPath("lsof"); err != nil {
return
}
cmd := exec.Command("lsof",
"-b", // avoid system calls that could block
"-w", // and don't warn about cases where -b fails
"-n", // don't resolve network names
"-P", // don't resolve network ports,
// TODO(bradfitz): pass down the uid we care about, then do: ?
//"-a", // AND the following together:
// "-u", strconv.Itoa(uid) // just this uid
"-itcp") // we only care about TCP connections
stdout, err := cmd.StdoutPipe()
if err != nil {
return
}
defer cmd.Wait()
defer stdout.Close()
err = cmd.Start()
if err != nil {
return
}
defer cmd.Process.Kill()
br := bufio.NewReader(stdout)
for {
line, err := br.ReadSlice('\n')
if err == io.EOF {
break
}
if err != nil {
return -1, err
}
if !bytes.Contains(line, seekb) {
continue
}
// SystemUIS 276 bradfitz 15u IPv4 0xffffff801a7c74e0 0t0 TCP 127.0.0.1:56718->127.0.0.1:5204 (ESTABLISHED)
f := bytes.Fields(line)
if len(f) < 8 {
continue
}
username := string(f[2])
return uidFromUsername(username)
}
return -1, ErrNotFound
}
func uidFromSockstat(lip net.IP, lport int, rip net.IP, rport int) (int, error) {
cmd := exec.Command("sockstat", "-Ptcp")
stdout, err := cmd.StdoutPipe()
if err != nil {
return -1, err
}
defer cmd.Wait()
defer stdout.Close()
err = cmd.Start()
if err != nil {
return -1, err
}
defer cmd.Process.Kill()
return uidFromSockstatReader(lip, lport, rip, rport, stdout)
}
func uidFromSockstatReader(lip net.IP, lport int, rip net.IP, rport int, r io.Reader) (int, error) {
pat, err := regexp.Compile(fmt.Sprintf(`^([^ ]+).*%s:%d *%s:%d$`,
lip.String(), lport, rip.String(), rport))
if err != nil {
return -1, err
}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
l := scanner.Text()
m := pat.FindStringSubmatch(l)
if len(m) == 2 {
return uidFromUsername(m[1])
}
}
if err := scanner.Err(); err != nil {
return -1, err
}
return -1, ErrNotFound
}
func uidFromProcReader(lip net.IP, lport int, rip net.IP, rport int, r io.Reader) (uid int, err error) {
buf := bufio.NewReader(r)
localHex := ""
remoteHex := ""
ipv4 := lip.To4() != nil
if ipv4 {
// In the kernel, the port is run through ntohs(), and
// the inet_request_socket in
// include/net/inet_socket.h says the "loc_addr" and
// "rmt_addr" fields are __be32, but get_openreq4's
// printf of them is raw, without byte order
// converstion.
localHex = fmt.Sprintf("%08X:%04X", toLinuxIPv4Order([]byte(lip.To4())), lport)
remoteHex = fmt.Sprintf("%08X:%04X", toLinuxIPv4Order([]byte(rip.To4())), rport)
} else {
localHex = fmt.Sprintf("%032X:%04X", toLinuxIPv6Order([]byte(lip.To16())), lport)
remoteHex = fmt.Sprintf("%032X:%04X", toLinuxIPv6Order([]byte(rip.To16())), rport)
}
for {
line, err := buf.ReadString('\n')
if err != nil {
return -1, ErrNotFound
}
parts := strings.Fields(strings.TrimSpace(line))
if len(parts) < 8 {
continue
}
// log.Printf("parts[1] = %q; localHex = %q", parts[1], localHex)
if parts[1] == localHex && parts[2] == remoteHex {
uid, err = strconv.Atoi(parts[7])
return uid, err
}
}
panic("unreachable")
}
// Localhost returns the first address found when
// doing a lookup of "localhost".
func Localhost() (net.IP, error) {
ips, err := net.LookupIP("localhost")
if err != nil {
return nil, err
}
if len(ips) < 1 {
return nil, errors.New("IP lookup for localhost returned no result")
}
return ips[0], nil
}
| zombiezen/cardcpx | netutil/ident.go | GO | apache-2.0 | 7,775 |
## Bloc-Jams Angular
A student project from Bloc's [Frontend Web Development Course](https://www.bloc.io/frontend-development-bootcamp).
Allows you to play music and select songs from a library.
## Features
- Plays, pauses and skips songs
- A player bar that allows you to continue listening while navigating through pages
- Anayltics data
| JDT4/bloc-jams-angular | README.md | Markdown | apache-2.0 | 342 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.sequencediagram.command;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexResult;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagram;
public class CommandAutoNewpage extends SingleLineCommand2<SequenceDiagram> {
public CommandAutoNewpage() {
super(getRegexConcat());
}
static IRegex getRegexConcat() {
return RegexConcat.build(CommandAutoNewpage.class.getName(), RegexLeaf.start(), //
new RegexLeaf("autonewpage"), //
RegexLeaf.spaceOneOrMore(), //
new RegexLeaf("VALUE", "(\\d+)"), RegexLeaf.end()); //
}
@Override
protected CommandExecutionResult executeArg(SequenceDiagram diagram, LineLocation location, RegexResult arg) {
diagram.setAutonewpage(Integer.parseInt(arg.get("VALUE", 0)));
return CommandExecutionResult.ok();
}
}
| talsma-ict/umldoclet | src/plantuml-asl/src/net/sourceforge/plantuml/sequencediagram/command/CommandAutoNewpage.java | Java | apache-2.0 | 2,240 |
/*******************************************************************************
* $FILE: main.c
* Atmel Corporation: http://www.atmel.com \n
* Support email: touch@atmel.com
******************************************************************************/
/* License
* Copyright (c) 2010, Atmel Corporation All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The name of ATMEL may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "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 EXPRESSLY AND
* SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*/
/*----------------------------------------------------------------------------
compiler information
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
include files
----------------------------------------------------------------------------*/
#include <avr/io.h>
#include <avr/interrupt.h>
#define __delay_cycles(n) __builtin_avr_delay_cycles(n)
#define __enable_interrupt() sei()
/* now include touch api.h with the localization defined above */
#include "touch_api.h"
#ifdef _DEBUG_INTERFACE_
/* Include files for QTouch Studio integration */
#include "QDebug.h"
#include "QDebugTransport.h"
#endif
/*----------------------------------------------------------------------------
manifest constants
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
type definitions
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
prototypes
----------------------------------------------------------------------------*/
/* initialise host app, pins, watchdog, etc */
static void init_system( void );
/* configure timer ISR to fire regularly */
static void init_timer_isr( void );
/* Assign the parameters values to global configuration parameter structure */
static void qt_set_parameters( void );
/* Configure the sensors */
static void config_sensors(void);
#if defined(_ROTOR_SLIDER_)
/* Configure the sensors with rotors/sliders with keys */
static void config_rotor_sliders(void);
#if (QT_NUM_CHANNELS == 4u)
/* Configure the sensors for 4 channel Key Rotor/sliders */
static void config_4ch_krs(void);
#endif
#if (QT_NUM_CHANNELS == 8u)
/* Configure the sensors for 8 channel Key Rotor/sliders */
static void config_8ch_krs(void);
#endif
#if (QT_NUM_CHANNELS == 12u)
/* Configure the sensors for 12 channel Key Rotor/sliders */
static void config_12ch_krs(void);
#endif
#if (QT_NUM_CHANNELS == 16u)
/* Configure the sensors for 16 channel Key Rotor/sliders */
static void config_16ch_krs(void);
#endif
#else
/* Configure the sensors for Keys configuration */
static void config_keys(void);
#endif /* _ROTOR_SLIDER_ */
/*----------------------------------------------------------------------------
Structure Declarations
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
macros
----------------------------------------------------------------------------*/
#define GET_SENSOR_STATE(SENSOR_NUMBER) qt_measure_data.qt_touch_status.sensor_states[(SENSOR_NUMBER/8)] & (1 << (SENSOR_NUMBER % 8))
#define GET_ROTOR_SLIDER_POSITION(ROTOR_SLIDER_NUMBER) qt_measure_data.qt_touch_status.rotor_slider_values[ROTOR_SLIDER_NUMBER]
/*----------------------------------------------------------------------------
global variables
----------------------------------------------------------------------------*/
/* Timer period in msec. */
uint16_t qt_measurement_period_msec = 25u;
/*----------------------------------------------------------------------------
extern variables
----------------------------------------------------------------------------*/
/* This configuration data structure parameters if needs to be changed will be
changed in the qt_set_parameters function */
extern qt_touch_lib_config_data_t qt_config_data;
/* touch output - measurement data */
extern qt_touch_lib_measure_data_t qt_measure_data;
/* Get sensor delta values */
extern int16_t qt_get_sensor_delta( uint8_t sensor);
#ifdef QTOUCH_STUDIO_MASKS
extern TOUCH_DATA_T SNS_array[2][2];
extern TOUCH_DATA_T SNSK_array[2][2];
#endif
/* Output can be observed in the watch window using this pointer */
qt_touch_lib_measure_data_t *pqt_measure_data = &qt_measure_data;
#ifdef _DEBUG_INTERFACE_
extern uint16_t timestamp1_hword;
extern uint16_t timestamp1_lword;
extern uint16_t timestamp2_hword;
extern uint16_t timestamp2_lword;
extern uint16_t timestamp3_hword;
extern uint16_t timestamp3_lword;
#endif
/*----------------------------------------------------------------------------
static variables
----------------------------------------------------------------------------*/
/* flag set by timer ISR when it's time to measure touch */
static volatile uint8_t time_to_measure_touch = 0u;
/* current time, set by timer ISR */
static volatile uint16_t current_time_ms_touch = 0u;
/*============================================================================
Name : main
------------------------------------------------------------------------------
Purpose : main code entry point
Input : n/a
Output : n/a
Notes :
============================================================================*/
int main( void )
{
/*status flags to indicate the re-burst for library*/
uint16_t status_flag = 0u;
uint16_t burst_flag = 0u;
#ifdef QTOUCH_STUDIO_MASKS
SNS_array[0][0]=0x22;
SNS_array[0][1]=0x04;
SNS_array[1][0]=0x00;
SNS_array[1][1]=0x00;
SNSK_array[0][0]=0x82;
SNSK_array[0][1]=0x08;
SNSK_array[1][0]=0x00;
SNSK_array[1][1]=0x00;
#endif
/* initialise host app, pins, watchdog, etc */
init_system();
/* Configure the Sensors as keys or Keys With Rotor/Sliders in this function */
config_sensors();
/* initialise touch sensing */
qt_init_sensing();
/* Set the parameters like recalibration threshold, Max_On_Duration etc in this function by the user */
qt_set_parameters( );
/* configure timer ISR to fire regularly */
init_timer_isr();
/* Address to pass address of user functions */
/* This function is called after the library has made capacitive measurements,
* but before it has processed them. The user can use this hook to apply filter
* functions to the measured signal values.(Possibly to fix sensor layout faults) */
qt_filter_callback = 0;
#ifdef _DEBUG_INTERFACE_
/* Initialize debug protocol */
QDebug_Init();
#endif
/* enable interrupts */
__enable_interrupt();
#ifdef _DEBUG_INTERFACE_
/* Process commands from PC */
QDebug_ProcessCommands();
#endif
/* loop forever */
for( ; ; )
{
if( time_to_measure_touch )
{
/* clear flag: it's time to measure touch */
time_to_measure_touch = 0u;
do {
/* one time measure touch sensors */
status_flag = qt_measure_sensors( current_time_ms_touch );
burst_flag = status_flag & QTLIB_BURST_AGAIN;
#ifdef _DEBUG_INTERFACE_
/* send debug data */
QDebug_SendData(status_flag);
#endif
/* Time-critical host application code goes here */
}while (burst_flag) ;
#ifdef _DEBUG_INTERFACE_
/* Process commands from PC */
QDebug_ProcessCommands();
#endif
}
/* Time Non-critical host application code goes here */
}
}
/*============================================================================
Name : init_timer_isr
------------------------------------------------------------------------------
Purpose : configure timer ISR to fire regularly
Input : n/a
Output : n/a
Notes :
============================================================================*/
static void init_timer_isr( void )
{
/* set timer compare value (how often timer ISR will fire) */
OCR1A = ( TICKS_PER_MS * qt_measurement_period_msec);
/* enable timer ISR */
TIMSK |= (1u << OCIE1A);
/* timer prescaler = system clock / 8 */
TCCR1B |= (1u << CS11);
/* timer mode = CTC (count up to compare value, then reset) */
TCCR1B |= (1u << WGM12);
}
/*============================================================================
Name : init_system
------------------------------------------------------------------------------
Purpose : initialise host app, pins, watchdog, etc
Input : n/a
Output : n/a
Notes :
============================================================================*/
static void init_system( void )
{
/* run at 4MHz (assuming internal clock is set to 8MHz)*/
// CLKPR = 0x80u;
// CLKPR = 0x01u;
/* disable pull-ups */
SFIOR |= (1u << PUD);
}
/*============================================================================
Name : timer_isr
------------------------------------------------------------------------------
Purpose : timer 1 compare ISR
Input : n/a
Output : n/a
Notes :
============================================================================*/
ISR(TIMER1_COMPA_vect)
{
/* set flag: it's time to measure touch */
time_to_measure_touch = 1u;
/* update the current time */
current_time_ms_touch += qt_measurement_period_msec;
}
/*============================================================================
Name : qt_set_parameters
------------------------------------------------------------------------------
Purpose : This will fill the default threshold values in the configuration
data structure.But User can change the values of these parameters .
Input : n/a
Output : n/a
Notes : initialize configuration data for processing
============================================================================*/
static void qt_set_parameters( void )
{
/* This will be modified by the user to different values */
qt_config_data.qt_di = DEF_QT_DI;
qt_config_data.qt_neg_drift_rate = DEF_QT_NEG_DRIFT_RATE;
qt_config_data.qt_pos_drift_rate = DEF_QT_POS_DRIFT_RATE;
qt_config_data.qt_max_on_duration = DEF_QT_MAX_ON_DURATION;
qt_config_data.qt_drift_hold_time = DEF_QT_DRIFT_HOLD_TIME;
qt_config_data.qt_recal_threshold = DEF_QT_RECAL_THRESHOLD;
qt_config_data.qt_pos_recal_delay = DEF_QT_POS_RECAL_DELAY;
}
/*============================================================================
Name : config_sensors
------------------------------------------------------------------------------
Purpose : Configure the sensors
Input : n/a
Output : n/a
Notes : n/a
============================================================================*/
static void config_sensors(void)
{
#if defined(_ROTOR_SLIDER_)
config_rotor_sliders();
#else /* !_ROTOR_SLIDER_ OR ONLY KEYS */
config_keys();
#endif /* _ROTOR_SLIDER_ */
}
/*============================================================================
Name : config_keys
------------------------------------------------------------------------------
Purpose : Configure the sensors as keys only
Input : n/a
Output : n/a
Notes : n/a
============================================================================*/
#ifndef _ROTOR_SLIDER_
static void config_keys(void)
{
/* enable sensors 0..3: keys on channels 0..3 */
qt_enable_key( CHANNEL_0, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_1, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_2, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_3, AKS_GROUP_1, 10u, HYST_6_25 );
#if(QT_NUM_CHANNELS >= 8u)
/* enable sensors 4..7: keys on channels 4..7 */
qt_enable_key( CHANNEL_4, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_5, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_6, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_7, AKS_GROUP_1, 10u, HYST_6_25 );
#endif
#if(QT_NUM_CHANNELS >= 12u)
/* enable sensors 8..11: keys on channels 4..7 */
qt_enable_key( CHANNEL_8, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_9, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_10, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_11, AKS_GROUP_1, 10u, HYST_6_25 );
#endif
#if (QT_NUM_CHANNELS >= 16u)
/* enable sensors 12..15: keys on channels 8..15 */
qt_enable_key( CHANNEL_12, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_13, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_14, AKS_GROUP_1, 10u, HYST_6_25 );
qt_enable_key( CHANNEL_15, AKS_GROUP_1, 10u, HYST_6_25 );
#endif
}
#else/* _ROTOR_SLIDER_ */
/*============================================================================
Name : config_rotor_sliders
------------------------------------------------------------------------------
Purpose: Configure the Sensors as keys and also as Rotors/Sliders
Input : n/a
Output : n/a
Notes : n/a
============================================================================*/
static void config_rotor_sliders(void)
{
#if (QT_NUM_CHANNELS == 4u)
{
/* Call this function if library used is 4 channel library with KRS Configuration */
config_4ch_krs();
}
#endif
#if (QT_NUM_CHANNELS == 8u)
{
/* Call this function if library used is 8 channel library with KRS Configuration */
config_8ch_krs();
}
#endif
#if (QT_NUM_CHANNELS == 12u)
{
/* Call this function if library used is 12 channel library with KRS Configuration */
config_12ch_krs();
}
#endif
#if (QT_NUM_CHANNELS == 16u)
{
/* Call this function if library used is 16 channel library with KRS Configuration */
config_16ch_krs();
}
#endif
}
/*============================================================================
Name : config_4ch_krs
------------------------------------------------------------------------------
Purpose : Configure the Sensors as keys and Rotor/Sliders for 4 channels only
Input : n/a
Output : n/a
Notes : n/a
============================================================================*/
#if (QT_NUM_CHANNELS == 4u)
static void config_4ch_krs(void)
{
/* enable sensor 0: a key on channel 0 */
qt_enable_key( CHANNEL_0, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 1: a slider on channels 0..2 */
qt_enable_slider( CHANNEL_1, CHANNEL_3, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
}
#endif /*QT_NUM_CHANNELS == 4u config_4ch_krs */
/*============================================================================
Name : config_8ch_krs
------------------------------------------------------------------------------
Purpose : Configure the Sensors as keys and Rotor/Sliders for 8 channels only
Input : n/a
Output : n/a
Notes : n/a
============================================================================*/
#if (QT_NUM_CHANNELS == 8u)
static void config_8ch_krs(void)
{
/* enable sensor 0: a keys on channel 0 */
qt_enable_key( CHANNEL_0, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 1: a slider on channels 1..3 */
qt_enable_slider( CHANNEL_1, CHANNEL_3, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
/* enable sensor 2: a key on channel 4 */
qt_enable_key( CHANNEL_4, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 3: a rotor on channels 5..7 */
qt_enable_rotor( CHANNEL_5, CHANNEL_7, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
}
#endif /* QT_NUM_CHANNELS == 8u config_8ch_krs */
/*============================================================================
Name : config_12ch_krs
------------------------------------------------------------------------------
Purpose : Configure the Sensors as keys and Rotor/Sliders for 12 channels only
Input : n/a
Output : n/a
Notes : n/a
============================================================================*/
#if (QT_NUM_CHANNELS == 12u)
static void config_12ch_krs(void)
{
/* enable sensor 0: a keys on channel 0 */
qt_enable_key( CHANNEL_0, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 1: a slider on channels 1..3 */
qt_enable_slider( CHANNEL_1, CHANNEL_3, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
/* enable sensor 2: a key on channel 4 */
qt_enable_key( CHANNEL_4, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 3: a rotor on channels 5..7 */
qt_enable_slider( CHANNEL_5, CHANNEL_7, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
/* enable sensor 4: a keys on channel 8 */
qt_enable_key( CHANNEL_8, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 5: a slider on channels 9..11 */
qt_enable_rotor( CHANNEL_9, CHANNEL_11, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
}
#endif
/*============================================================================
Name : config_16ch_krs
------------------------------------------------------------------------------
Purpose : Configure the Sensors as keys and Rotor/Sliders for 16 channels only
Input : n/a
Output : n/a
Notes : n/a
============================================================================*/
#if (QT_NUM_CHANNELS == 16u)
static void config_16ch_krs(void)
{
/* enable sensor 0: a keys on channel 0 */
qt_enable_key( CHANNEL_0, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 1: a slider on channels 1..3 */
qt_enable_slider( CHANNEL_1, CHANNEL_3, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
/* enable sensor 2: a key on channel 4 */
qt_enable_key( CHANNEL_4, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 3: a rotor on channels 5..7 */
qt_enable_rotor( CHANNEL_5, CHANNEL_7, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
/* enable sensor 4: a keys on channel 8 */
qt_enable_key( CHANNEL_8, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 5: a slider on channels 9..11 */
qt_enable_slider( CHANNEL_9, CHANNEL_11, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
/* enable sensor 6: a keys on channel 12 */
qt_enable_key( CHANNEL_12, AKS_GROUP_2, 10u, HYST_6_25 );
/* enable sensor 7: a slider on channels 13..15 */
qt_enable_rotor( CHANNEL_13, CHANNEL_15, NO_AKS_GROUP, 16u, HYST_6_25, RES_8_BIT, 0u );
}
#endif /* QT_NUM_CHANNELS == 16u config_16ch_krs */
#endif /* _ROTOR_SLIDER_ */
| GordonMcGregor/luminous | qtouchlib/thirdparty/qtouch/generic/avr8/qtouch/examples/avr4g1_qt_example/main_atmega8515.c | C | apache-2.0 | 20,824 |
/**************************************************************************************************
* File name : test.h
* Description : Perform the test cases here.
* Creator : Frederick Hsu
* Creation date: Wed. 28 Dec. 2016
* Copyright(C) 2016 All rights reserved.
*
**************************************************************************************************/
#ifndef TEST_H
#define TEST_H
void performTestCases(void);
void performTestCases4StringModule(void);
void performTestCases4ArrayModule(void);
void performTestCases4DictionaryModule(void);
void performTestCase4NumberModule(void);
#endif /* TEST_H */
| Frederick-Hsu/iOS_Objective_C_Development | Objective_C_Foundation/Foundation_Framework/Foundation_Framework/test.h | C | apache-2.0 | 660 |
/*
* (c) 2005 David B. Bracewell
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.davidbracewell.function;
import java.io.Serializable;
import java.util.function.Consumer;
/**
* Version of Consumer that is serializable
*
* @param <T> Functional parameter
*/
@FunctionalInterface
public interface SerializableConsumer<T> extends Consumer<T>, Serializable {
}//END OF SerializableConsumer
| dbracewell/mango | src/main/java/com/davidbracewell/function/SerializableConsumer.java | Java | apache-2.0 | 1,167 |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics.ConversionsTests.Parameters
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class ConversionsTests
Inherits BasicTestBase
Private Shared ReadOnly NoConversion As ConversionKind = Nothing
<Fact()>
Public Sub TryCastDirectCastConversions()
Dim dummyCode =
<file>
Class C1
Shared Sub MethodDecl()
End Sub
End Class
</file>
Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value)
' Tests are based on the source code used to compile VBConversions.dll, VBConversions.vb is
' checked in next to the DLL.
Dim vbConversionsRef = TestReferences.SymbolsTests.VBConversions
Dim modifiersRef = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll
Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib, vbConversionsRef, modifiersRef})
Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol)
Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol)
Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol)
Dim asmVBConversions = c1.GetReferencedAssemblySymbol(vbConversionsRef)
Dim asmModifiers = c1.GetReferencedAssemblySymbol(modifiersRef)
Dim test = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Test").Single()
Dim m13 = DirectCast(test.GetMembers("M13").Single(), MethodSymbol)
Dim m13p = m13.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningReference, ClassifyDirectCastAssignment(m13p(a), m13p(b), methodBodyBinder)) ' Object)
Assert.Equal(ConversionKind.WideningValue, ClassifyDirectCastAssignment(m13p(a), m13p(c), methodBodyBinder)) ' Object)
Assert.Equal(ConversionKind.NarrowingReference, ClassifyDirectCastAssignment(m13p(b), m13p(a), methodBodyBinder)) ' ValueType)
Assert.Equal(ConversionKind.WideningValue, ClassifyDirectCastAssignment(m13p(b), m13p(c), methodBodyBinder)) ' ValueType)
Assert.Equal(ConversionKind.NarrowingValue, ClassifyDirectCastAssignment(m13p(c), m13p(a), methodBodyBinder)) ' Integer)
Assert.Equal(ConversionKind.NarrowingValue, ClassifyDirectCastAssignment(m13p(c), m13p(b), methodBodyBinder)) ' Integer)
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(c), m13p(c), methodBodyBinder))) ' Integer)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(c), m13p(d), methodBodyBinder)) ' Integer) 'error BC30311: Value of type 'Long' cannot be converted to 'Integer'.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(c), m13p(e), methodBodyBinder)) ' Integer)
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(d), m13p(d), methodBodyBinder))) ' Long)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(d), m13p(c), methodBodyBinder)) ' Long) 'error BC30311: Value of type 'Integer' cannot be converted to 'Long'.
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(e), m13p(e), methodBodyBinder))) ' Enum1)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(e), m13p(f), methodBodyBinder)) ' Enum1) 'error BC30311: Value of type 'Enum2' cannot be converted to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(e), m13p(g), methodBodyBinder)) ' Enum1)
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(f), m13p(f), methodBodyBinder))) ' Enum2)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(f), m13p(g), methodBodyBinder)) ' Enum2) ' error BC30311: Value of type 'Enum4' cannot be converted to 'Enum2'.
Assert.Equal(ConversionKind.WideningArray, ClassifyDirectCastAssignment(m13p(h), m13p(i), methodBodyBinder)) ' Class8())
Assert.Equal(ConversionKind.NarrowingArray, ClassifyDirectCastAssignment(m13p(i), m13p(h), methodBodyBinder)) ' Class9())
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(i), m13p(j), methodBodyBinder)) ' Class9()) ' error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'.
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(k), m13p(k), methodBodyBinder))) ' MT1)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(k), m13p(l), methodBodyBinder)) ' MT1) ' error BC30311: Value of type 'MT2' cannot be converted to 'MT1'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyDirectCastAssignment(m13p(k), m13p(m), methodBodyBinder)) ' MT1)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(k), m13p(q), methodBodyBinder)) ' MT1) ' error BC30311: Value of type 'MT4' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(l), m13p(k), methodBodyBinder)) ' MT2) ' Value of type 'MT1' cannot be converted to 'MT2'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyDirectCastAssignment(m13p(m), m13p(k), methodBodyBinder)) ' MT3)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(n), m13p(o), methodBodyBinder)) ' MT1()) ' Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(n), m13p(p), methodBodyBinder)) ' MT1()) ' error BC30332: Value of type '2-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(n), m13p(u), methodBodyBinder)) ' MT1()) ' error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT1' because 'Integer' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(q), m13p(k), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'MT1' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(q), m13p(b), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'System.ValueType' cannot be converted
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(q), m13p(c), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'Integer' cannot be converted to 'MT4'
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(r), m13p(s), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(r), m13p(t), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(r), m13p(w), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(s), m13p(r), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT5' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(s), m13p(t), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT6'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyDirectCastAssignment(m13p(s), m13p(w), methodBodyBinder)) ' MT6)
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(t), m13p(r), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT5' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(t), m13p(s), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(t), m13p(w), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(u), m13p(n), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of Integer' because 'MT1' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(u), m13p(v), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of Integer' because 'MT4' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(v), m13p(u), methodBodyBinder)) ' MT4()) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT4' because 'Integer' is not derived from 'MT4'.
Dim [nothing] = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing)
Dim intZero = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Create(0I), m13p(c))
Dim longZero = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Create(0L), m13p(d))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(a), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(b), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(c), [nothing], methodBodyBinder))
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(c), intZero, methodBodyBinder)))
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(c), longZero, methodBodyBinder)) 'error BC30311: Value of type 'Long' cannot be converted to 'Integer'.
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(d), intZero, methodBodyBinder)) ' error BC30311: Value of type 'Integer' cannot be converted to 'Long'.
Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(d), longZero, methodBodyBinder)))
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(e), intZero, methodBodyBinder))
Assert.Equal(NoConversion, ClassifyDirectCastAssignment(m13p(e), longZero, methodBodyBinder)) ' error BC30311: Value of type 'Long' cannot be converted to 'Enum1'.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(e), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(k), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(q), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningReference, ClassifyTryCastAssignment(m13p(a), m13p(b), methodBodyBinder)) ' Object)
Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(a), m13p(c), methodBodyBinder)) ' Object)
Assert.Equal(ConversionKind.NarrowingReference, ClassifyTryCastAssignment(m13p(b), m13p(a), methodBodyBinder)) ' ValueType)
Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(b), m13p(c), methodBodyBinder)) ' ValueType)
Assert.Equal(ConversionKind.NarrowingValue, ClassifyTryCastAssignment(m13p(c), m13p(a), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyTryCastAssignment(m13p(c), m13p(b), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(c), m13p(c), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(c), m13p(d), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(c), m13p(e), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(d), m13p(d), methodBodyBinder)) ' Long) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(d), m13p(c), methodBodyBinder)) ' Long) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(e), m13p(e), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(e), m13p(f), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(e), m13p(g), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(f), m13p(f), methodBodyBinder)) ' Enum2) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum2' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(f), m13p(g), methodBodyBinder)) ' Enum2) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum2' is a value type.
Assert.Equal(ConversionKind.WideningArray, ClassifyTryCastAssignment(m13p(h), m13p(i), methodBodyBinder)) ' Class8())
Assert.Equal(ConversionKind.NarrowingArray, ClassifyTryCastAssignment(m13p(i), m13p(h), methodBodyBinder)) ' Class9())
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(i), m13p(j), methodBodyBinder)) ' Class9()) ' error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(k), m13p(k), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(k), m13p(l), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyTryCastAssignment(m13p(k), m13p(m), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(k), m13p(q), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(l), m13p(k), methodBodyBinder)) ' MT2) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT2' has no class constraint.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyTryCastAssignment(m13p(m), m13p(k), methodBodyBinder)) ' MT3) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT3' has no class constraint.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(o), methodBodyBinder)) ' MT1())
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(p), methodBodyBinder)) ' MT1())
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(u), methodBodyBinder)) ' MT1())
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(k), methodBodyBinder)) ' MT4)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(b), methodBodyBinder)) ' MT4)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(c), methodBodyBinder)) ' MT4)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(s), methodBodyBinder)) ' MT5)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(t), methodBodyBinder)) ' MT5)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(w), methodBodyBinder)) ' MT5)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(s), m13p(r), methodBodyBinder)) ' MT6)
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(s), m13p(t), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT6'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyTryCastAssignment(m13p(s), m13p(w), methodBodyBinder)) ' MT6)
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(t), m13p(r), methodBodyBinder)) ' MT7)
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(t), m13p(s), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(t), m13p(w), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT7'.
Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(u), m13p(n), methodBodyBinder)) ' Integer())
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(u), m13p(v), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of Integer' because 'MT4' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(v), m13p(u), methodBodyBinder)) ' MT4()) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT4' because 'Integer' is not derived from 'MT4'.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(a), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(a), intZero, methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(b), [nothing], methodBodyBinder))
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(c), [nothing], methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(c), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(c), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(d), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type.
Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(d), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(e), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(NoConversion, ClassifyTryCastAssignment(m13p(e), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(e), [nothing], methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(k), [nothing], methodBodyBinder)) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint.
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(q), [nothing], methodBodyBinder))
End Sub
Private Shared Function ClassifyDirectCastAssignment([to] As TypeSymbol, [from] As TypeSymbol, binder As Binder) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyDirectCastConversion([from], [to], Nothing) And Not ConversionKind.MightSucceedAtRuntime
Return result
End Function
Private Shared Function ClassifyDirectCastAssignment([to] As TypeSymbol, [from] As BoundLiteral, binder As Binder) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyDirectCastConversion([from], [to], binder, Nothing)
Return result
End Function
Private Shared Function ClassifyTryCastAssignment([to] As TypeSymbol, [from] As TypeSymbol, binder As Binder) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyTryCastConversion([from], [to], Nothing)
Return result
End Function
Private Shared Function ClassifyTryCastAssignment([to] As TypeSymbol, [from] As BoundLiteral, binder As Binder) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyTryCastConversion([from], [to], binder, Nothing)
Return result
End Function
Private Shared Function ClassifyConversion(source As TypeSymbol, destination As TypeSymbol) As ConversionKind
Dim result As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(source, destination, Nothing)
Assert.Null(result.Value)
Return result.Key
End Function
Private Shared Function ClassifyConversion(source As BoundExpression, destination As TypeSymbol, binder As Binder) As ConversionKind
Dim result As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(source, destination, binder, Nothing)
Assert.Null(result.Value)
Return result.Key
End Function
<Fact()>
Public Sub ConstantExpressionConversions()
Dim dummyCode =
<file>
Class C1
Shared Sub MethodDecl()
End Sub
End Class
</file>
Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value)
Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib})
Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol)
Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol)
Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol)
Assert.True(c1.Options.CheckOverflow)
Dim objectType = c1.GetSpecialType(System_Object)
Dim booleanType = c1.GetSpecialType(System_Boolean)
Dim byteType = c1.GetSpecialType(System_Byte)
Dim sbyteType = c1.GetSpecialType(System_SByte)
Dim int16Type = c1.GetSpecialType(System_Int16)
Dim uint16Type = c1.GetSpecialType(System_UInt16)
Dim int32Type = c1.GetSpecialType(System_Int32)
Dim uint32Type = c1.GetSpecialType(System_UInt32)
Dim int64Type = c1.GetSpecialType(System_Int64)
Dim uint64Type = c1.GetSpecialType(System_UInt64)
Dim doubleType = c1.GetSpecialType(System_Double)
Dim singleType = c1.GetSpecialType(System_Single)
Dim decimalType = c1.GetSpecialType(System_Decimal)
Dim dateType = c1.GetSpecialType(System_DateTime)
Dim stringType = c1.GetSpecialType(System_String)
Dim charType = c1.GetSpecialType(System_Char)
Dim intPtrType = c1.GetSpecialType(System_IntPtr)
Dim typeCodeType = c1.GlobalNamespace.GetMembers("System").OfType(Of NamespaceSymbol)().Single().GetTypeMembers("TypeCode").Single()
Dim allTestTypes = New TypeSymbol() {
objectType, booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType,
stringType, charType, intPtrType, typeCodeType}
Dim convertableTypes = New HashSet(Of TypeSymbol)({
booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType,
stringType, charType, typeCodeType})
Dim integralTypes = New HashSet(Of TypeSymbol)({
byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, typeCodeType})
Dim unsignedTypes = New HashSet(Of TypeSymbol)({
byteType, uint16Type, uint32Type, uint64Type})
Dim numericTypes = New HashSet(Of TypeSymbol)({
byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, typeCodeType})
Dim floatingTypes = New HashSet(Of TypeSymbol)({doubleType, singleType})
' -------------- NOTHING literal conversions
Dim _nothing = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing)
Dim resultValue As ConstantValue
Dim integerOverflow As Boolean
Dim literal As BoundExpression
Dim constant As BoundConversion
For Each testType In allTestTypes
Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyConversion(_nothing, testType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(_nothing, testType, integerOverflow)
If convertableTypes.Contains(testType) Then
Assert.NotNull(resultValue)
Assert.Equal(If(testType.IsStringType(), ConstantValueTypeDiscriminator.Nothing, testType.GetConstantValueTypeDiscriminator()), resultValue.Discriminator)
If testType IsNot dateType Then
Assert.Equal(0, Convert.ToInt64(resultValue.Value))
If testType Is stringType Then
Assert.Null(resultValue.StringValue)
End If
Else
Assert.Equal(New DateTime(), resultValue.DateTimeValue)
End If
Else
Assert.Null(resultValue)
End If
Assert.False(integerOverflow)
If resultValue IsNot Nothing Then
Assert.False(resultValue.IsBad)
End If
Next
' -------------- integer literal zero to enum conversions
For Each integralType In integralTypes
Dim zero = ConstantValue.Default(integralType.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), zero, integralType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), literal, ConversionKind.Widening, True, True, zero, integralType, Nothing)
Assert.Equal(If(integralType Is int32Type, ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, If(integralType Is typeCodeType, ConversionKind.Identity, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions)),
ClassifyConversion(literal, typeCodeType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, typeCodeType, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator)
Assert.Equal(0, resultValue.Int32Value)
Assert.Equal(If(integralType Is typeCodeType, ConversionKind.Identity, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions), ClassifyConversion(constant, typeCodeType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(constant, typeCodeType, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator)
Assert.Equal(0, resultValue.Int32Value)
Next
For Each convertibleType In convertableTypes
If Not integralTypes.Contains(convertibleType) Then
Dim zero = ConstantValue.Default(If(convertibleType.IsStringType(), ConstantValueTypeDiscriminator.Nothing, convertibleType.GetConstantValueTypeDiscriminator()))
If convertibleType.IsStringType() Then
literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.WideningNothingLiteral, False, True, zero, convertibleType, Nothing)
Else
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), zero, convertibleType)
End If
Assert.Equal(ClassifyConversion(convertibleType, typeCodeType), ClassifyConversion(literal, typeCodeType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, typeCodeType, integerOverflow)
If Not numericTypes.Contains(convertibleType) AndAlso convertibleType IsNot booleanType Then
Assert.Null(resultValue)
Assert.False(integerOverflow)
Else
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator)
Assert.Equal(0, resultValue.Int32Value)
End If
End If
Next
' -------------- Numeric conversions
Dim nullableType = c1.GetSpecialType(System_Nullable_T)
' Zero
For Each type1 In convertableTypes
Dim zero = ConstantValue.Default(If(type1.IsStringType(), ConstantValueTypeDiscriminator.Nothing, type1.GetConstantValueTypeDiscriminator()))
If type1.IsStringType() Then
literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.WideningNothingLiteral, False, True, zero, type1, Nothing)
Else
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), zero, type1)
End If
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing),
New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Default(ConstantValueTypeDiscriminator.Int32), int32Type),
ConversionKind.Widening, True, True, zero, type1, Nothing)
For Each type2 In allTestTypes
Dim expectedConv As ConversionKind
If numericTypes.Contains(type1) AndAlso numericTypes.Contains(type2) Then
If type1 Is type2 Then
expectedConv = ConversionKind.Identity
ElseIf type1.IsEnumType() Then
expectedConv = ClassifyConversion(type1.GetEnumUnderlyingTypeOrSelf(), type2)
If Conversions.IsWideningConversion(expectedConv) Then
expectedConv = expectedConv Or ConversionKind.InvolvesEnumTypeConversions
If (expectedConv And ConversionKind.Identity) <> 0 Then
expectedConv = (expectedConv And Not ConversionKind.Identity) Or ConversionKind.Widening Or ConversionKind.Numeric
End If
ElseIf Conversions.IsNarrowingConversion(expectedConv) Then
expectedConv = expectedConv Or ConversionKind.InvolvesEnumTypeConversions
End If
ElseIf type2.IsEnumType() Then
expectedConv = ClassifyConversion(type1, type2.GetEnumUnderlyingTypeOrSelf())
If Not Conversions.NoConversion(expectedConv) Then
expectedConv = (expectedConv And Not ConversionKind.Widening) Or ConversionKind.Narrowing Or ConversionKind.InvolvesEnumTypeConversions
If (expectedConv And ConversionKind.Identity) <> 0 Then
expectedConv = (expectedConv And Not ConversionKind.Identity) Or ConversionKind.Numeric
End If
End If
ElseIf integralTypes.Contains(type2) Then
If integralTypes.Contains(type1) Then
If Conversions.IsNarrowingConversion(ClassifyConversion(type1, type2)) Then
expectedConv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant
Else
expectedConv = ConversionKind.WideningNumeric
End If
Else
expectedConv = ConversionKind.NarrowingNumeric
End If
ElseIf floatingTypes.Contains(type2) Then
If Conversions.IsNarrowingConversion(ClassifyConversion(type1, type2)) Then
expectedConv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant
Else
expectedConv = ConversionKind.WideningNumeric
End If
Else
Assert.Same(decimalType, type2)
expectedConv = ClassifyConversion(type1, type2)
End If
Assert.Equal(If(type2.IsEnumType() AndAlso type1 Is int32Type, ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, expectedConv), ClassifyConversion(literal, type2, methodBodyBinder))
Assert.Equal(expectedConv, ClassifyConversion(constant, type2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(0, Convert.ToDouble(resultValue.Value))
resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(0, Convert.ToDouble(resultValue.Value))
Dim nullableType2 = nullableType.Construct(type2)
expectedConv = ClassifyConversion(type1, nullableType2) Or (expectedConv And ConversionKind.InvolvesNarrowingFromNumericConstant)
If type2.IsEnumType() AndAlso type1.SpecialType = SpecialType.System_Int32 Then
Assert.Equal(expectedConv Or ConversionKind.InvolvesNarrowingFromNumericConstant, ClassifyConversion(literal, nullableType2, methodBodyBinder))
Else
Assert.Equal(expectedConv, ClassifyConversion(literal, nullableType2, methodBodyBinder))
End If
Assert.Equal(expectedConv, ClassifyConversion(constant, nullableType2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
ElseIf type1 Is booleanType AndAlso numericTypes.Contains(type2) Then
' Will test separately
Continue For
ElseIf type2 Is booleanType AndAlso numericTypes.Contains(type1) Then
Assert.Equal(If(type1 Is typeCodeType, ConversionKind.NarrowingBoolean Or ConversionKind.InvolvesEnumTypeConversions, ConversionKind.NarrowingBoolean), ClassifyConversion(literal, type2, methodBodyBinder))
Assert.Equal(If(type1 Is typeCodeType, ConversionKind.NarrowingBoolean Or ConversionKind.InvolvesEnumTypeConversions, ConversionKind.NarrowingBoolean), ClassifyConversion(constant, type2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.False(DirectCast(resultValue.Value, Boolean))
resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.False(DirectCast(resultValue.Value, Boolean))
ElseIf type1 Is stringType AndAlso type2 Is charType Then
' Will test separately
Continue For
ElseIf type1 Is charType AndAlso type2 Is stringType Then
' Will test separately
Continue For
ElseIf type2 Is typeCodeType AndAlso integralTypes.Contains(type1) Then
' Already tested
Continue For
ElseIf (type1 Is dateType AndAlso type2 Is dateType) OrElse
(type1 Is booleanType AndAlso type2 Is booleanType) OrElse
(type1 Is stringType AndAlso type2 Is stringType) OrElse
(type1 Is charType AndAlso type2 Is charType) Then
Assert.True(Conversions.IsIdentityConversion(ClassifyConversion(literal, type2, methodBodyBinder)))
Assert.True(Conversions.IsIdentityConversion(ClassifyConversion(constant, type2, methodBodyBinder)))
resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.True(type2.IsValidForConstantValue(resultValue))
Assert.Equal(literal.ConstantValueOpt, resultValue)
resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.True(type2.IsValidForConstantValue(resultValue))
Assert.Equal(constant.ConstantValueOpt, resultValue)
Else
Dim expectedConv1 As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(type1, type2, Nothing)
Assert.Equal(expectedConv1, Conversions.ClassifyConversion(literal, type2, methodBodyBinder, Nothing))
Assert.Equal(expectedConv1, Conversions.ClassifyConversion(constant, type2, methodBodyBinder, Nothing))
resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
If type2.IsValueType Then
Dim nullableType2 = nullableType.Construct(type2)
expectedConv1 = Conversions.ClassifyConversion(type1, nullableType2, Nothing)
Assert.Equal(expectedConv1, Conversions.ClassifyConversion(literal, nullableType2, methodBodyBinder, Nothing))
Assert.Equal(expectedConv1, Conversions.ClassifyConversion(constant, nullableType2, methodBodyBinder, Nothing))
resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
End If
End If
Next
Next
' -------- Numeric non-zero values
Dim nonZeroValues = New TypeAndValue() {
New TypeAndValue(sbyteType, SByte.MinValue),
New TypeAndValue(int16Type, Int16.MinValue),
New TypeAndValue(int32Type, Int32.MinValue),
New TypeAndValue(int64Type, Int64.MinValue),
New TypeAndValue(doubleType, Double.MinValue),
New TypeAndValue(singleType, Single.MinValue),
New TypeAndValue(decimalType, Decimal.MinValue),
New TypeAndValue(sbyteType, SByte.MaxValue),
New TypeAndValue(int16Type, Int16.MaxValue),
New TypeAndValue(int32Type, Int32.MaxValue),
New TypeAndValue(int64Type, Int64.MaxValue),
New TypeAndValue(byteType, Byte.MaxValue),
New TypeAndValue(uint16Type, UInt16.MaxValue),
New TypeAndValue(uint32Type, UInt32.MaxValue),
New TypeAndValue(uint64Type, UInt64.MaxValue),
New TypeAndValue(doubleType, Double.MaxValue),
New TypeAndValue(singleType, Single.MaxValue),
New TypeAndValue(decimalType, Decimal.MaxValue),
New TypeAndValue(sbyteType, CSByte(-1)),
New TypeAndValue(int16Type, CShort(-2)),
New TypeAndValue(int32Type, CInt(-3)),
New TypeAndValue(int64Type, CLng(-4)),
New TypeAndValue(sbyteType, CSByte(5)),
New TypeAndValue(int16Type, CShort(6)),
New TypeAndValue(int32Type, CInt(7)),
New TypeAndValue(int64Type, CLng(8)),
New TypeAndValue(doubleType, CDbl(-9)),
New TypeAndValue(singleType, CSng(-10)),
New TypeAndValue(decimalType, CDec(-11)),
New TypeAndValue(doubleType, CDbl(12)),
New TypeAndValue(singleType, CSng(13)),
New TypeAndValue(decimalType, CDec(14)),
New TypeAndValue(byteType, CByte(15)),
New TypeAndValue(uint16Type, CUShort(16)),
New TypeAndValue(uint32Type, CUInt(17)),
New TypeAndValue(uint64Type, CULng(18)),
New TypeAndValue(decimalType, CDec(-11.3)),
New TypeAndValue(doubleType, CDbl(&HF000000000000000UL)),
New TypeAndValue(doubleType, CDbl(&H70000000000000F0L)),
New TypeAndValue(typeCodeType, Int32.MinValue),
New TypeAndValue(typeCodeType, Int32.MaxValue),
New TypeAndValue(typeCodeType, CInt(-3)),
New TypeAndValue(typeCodeType, CInt(7))
}
Dim resultValue2 As ConstantValue
Dim integerOverflow2 As Boolean
For Each mv In nonZeroValues
Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator())
Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing),
New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing),
ConversionKind.Widening, True, True, v, mv.Type, Nothing)
For Each numericType In numericTypes
Dim typeConv = ClassifyConversion(mv.Type, numericType)
Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder)
Assert.Equal(conv, conv2)
resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2)
Assert.Equal(resultValue Is Nothing, resultValue2 Is Nothing)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue IsNot Nothing AndAlso resultValue.IsBad, resultValue2 IsNot Nothing AndAlso resultValue2.IsBad)
If resultValue IsNot Nothing Then
Assert.Equal(resultValue2, resultValue)
If Not resultValue.IsBad Then
Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
End If
End If
Dim resultValueAsObject As Object = Nothing
Dim overflow As Boolean = False
Try
resultValueAsObject = CheckedConvert(v.Value, numericType)
Catch ex As OverflowException
overflow = True
End Try
If Not overflow Then
If Conversions.IsIdentityConversion(typeConv) Then
Assert.True(Conversions.IsIdentityConversion(conv))
ElseIf Conversions.IsNarrowingConversion(typeConv) Then
If mv.Type Is doubleType AndAlso numericType Is singleType Then
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
ElseIf integralTypes.Contains(mv.Type) AndAlso integralTypes.Contains(numericType) AndAlso Not mv.Type.IsEnumType() AndAlso Not numericType.IsEnumType() Then
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
Else
Assert.Equal(typeConv, conv)
End If
ElseIf mv.Type.IsEnumType() Then
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv)
Else
Assert.Equal(ConversionKind.WideningNumeric, conv)
End If
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(resultValueAsObject, resultValue.Value)
If mv.Type Is doubleType AndAlso numericType Is singleType Then
If v.DoubleValue = Double.MinValue Then
Dim min As Single = Double.MinValue
Assert.True(Single.IsNegativeInfinity(min))
Assert.Equal(resultValue.SingleValue, min)
ElseIf v.DoubleValue = Double.MaxValue Then
Dim max As Single = Double.MaxValue
Assert.Equal(Double.MaxValue, v.DoubleValue)
Assert.True(Single.IsPositiveInfinity(max))
Assert.Equal(resultValue.SingleValue, max)
End If
End If
ElseIf Not integralTypes.Contains(mv.Type) OrElse Not integralTypes.Contains(numericType) Then
'Assert.Equal(typeConv, conv)
If integralTypes.Contains(numericType) Then
Assert.NotNull(resultValue)
If resultValue.IsBad Then
Assert.False(integerOverflow)
Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv)
Else
Assert.True(integerOverflow)
Assert.Equal(ConversionKind.FailedDueToIntegerOverflow, conv)
Dim intermediate As Object
If unsignedTypes.Contains(numericType) Then
intermediate = Convert.ToUInt64(mv.Value)
Else
intermediate = Convert.ToInt64(mv.Value)
End If
Dim gotException As Boolean
Try
gotException = False
CheckedConvert(intermediate, numericType) ' Should get an overflow
Catch x As Exception
gotException = True
End Try
Assert.True(gotException)
Assert.Equal(UncheckedConvert(intermediate, numericType), resultValue.Value)
End If
Else
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.True(resultValue.IsBad)
Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv)
End If
Else
' An integer overflow case
Assert.Equal(ConversionKind.FailedDueToIntegerOverflow, conv)
Assert.NotNull(resultValue)
Assert.True(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(UncheckedConvert(v.Value, numericType), resultValue.Value)
End If
Dim nullableType2 = nullableType.Construct(numericType)
Dim zero = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Default(mv.Type.GetConstantValueTypeDiscriminator()), mv.Type, Nothing)
conv = ClassifyConversion(literal, numericType, methodBodyBinder)
If (conv And ConversionKind.FailedDueToNumericOverflowMask) = 0 Then
conv = ClassifyConversion(mv.Type, nullableType2) Or
(ClassifyConversion(zero, nullableType2, methodBodyBinder) And ConversionKind.InvolvesNarrowingFromNumericConstant)
End If
Assert.Equal(conv, ClassifyConversion(literal, nullableType2, methodBodyBinder))
Assert.Equal(conv, ClassifyConversion(constant, nullableType2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
Next
Next
Dim dbl As Double = -1.5
Dim doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, int32Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(-2, CInt(dbl))
Assert.Equal(-2, DirectCast(resultValue.Value, Int32))
dbl = -2.5
doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, int32Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(-2, CInt(dbl))
Assert.Equal(-2, DirectCast(resultValue.Value, Int32))
dbl = 1.5
doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, uint32Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(2UI, CUInt(dbl))
Assert.Equal(2UI, DirectCast(resultValue.Value, UInt32))
dbl = 2.5
doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, uint32Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(2UI, CUInt(dbl))
Assert.Equal(2UI, DirectCast(resultValue.Value, UInt32))
dbl = 2147483648.0 * 4294967296.0 + 10
doubleValue = ConstantValue.Create(dbl)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing)
resultValue = Conversions.TryFoldConstantConversion(constant, uint64Type, integerOverflow)
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(Convert.ToUInt64(dbl), DirectCast(resultValue.Value, UInt64))
' ------- Boolean
Dim falseValue = ConstantValue.Create(False)
Assert.Equal(falseValue.Discriminator, booleanType.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), falseValue, booleanType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, falseValue, booleanType, Nothing)
For Each numericType In numericTypes
Dim typeConv = ClassifyConversion(booleanType, numericType)
Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder)
Assert.Equal(conv, conv2)
Assert.Equal(typeConv, conv)
resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue.IsBad, resultValue2.IsBad)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(0, Convert.ToInt64(resultValue.Value))
Next
Dim trueValue = ConstantValue.Create(True)
Assert.Equal(falseValue.Discriminator, booleanType.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), trueValue, booleanType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, trueValue, booleanType, Nothing)
For Each numericType In numericTypes
Dim typeConv = ClassifyConversion(booleanType, numericType)
Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder)
Assert.Equal(conv, conv2)
Assert.Equal(typeConv, conv)
resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue.IsBad, resultValue2.IsBad)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
'The literal True converts to the literal 255 for Byte, 65535 for UShort, 4294967295 for UInteger, 18446744073709551615 for ULong,
'and to the expression -1 for SByte, Short, Integer, Long, Decimal, Single, and Double
If numericType Is byteType Then
Assert.Equal(255, DirectCast(resultValue.Value, Byte))
ElseIf numericType Is uint16Type Then
Assert.Equal(65535, DirectCast(resultValue.Value, UInt16))
ElseIf numericType Is uint32Type Then
Assert.Equal(4294967295, DirectCast(resultValue.Value, UInt32))
ElseIf numericType Is uint64Type Then
Assert.Equal(18446744073709551615UL, DirectCast(resultValue.Value, UInt64))
Else
Assert.Equal(-1, Convert.ToInt64(resultValue.Value))
End If
Next
resultValue = Conversions.TryFoldConstantConversion(literal, booleanType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, booleanType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue.IsBad, resultValue2.IsBad)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(booleanType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.True(DirectCast(resultValue.Value, Boolean))
For Each mv In nonZeroValues
Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator())
Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, v, mv.Type, Nothing)
Dim typeConv = ClassifyConversion(mv.Type, booleanType)
Dim conv = ClassifyConversion(literal, booleanType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, booleanType, methodBodyBinder)
Assert.Equal(conv, conv2)
Assert.Equal(typeConv, conv)
resultValue = Conversions.TryFoldConstantConversion(literal, booleanType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, booleanType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(booleanType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.True(DirectCast(resultValue.Value, Boolean))
Next
' ------- String <-> Char
Dim stringValue = ConstantValue.Nothing
Assert.Null(stringValue.StringValue)
literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, Nothing), ConversionKind.WideningNothingLiteral, False, True, stringValue, stringType, Nothing)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing)
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder))
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(ChrW(0), CChar(stringValue.StringValue))
Assert.Equal(ChrW(0), DirectCast(resultValue.Value, Char))
stringValue = ConstantValue.Create("")
Assert.Equal(0, stringValue.StringValue.Length)
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, stringType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing)
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder))
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal(ChrW(0), CChar(""))
Assert.Equal(ChrW(0), DirectCast(resultValue.Value, Char))
stringValue = ConstantValue.Create("abc")
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, stringType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing)
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder))
Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal("a"c, DirectCast(resultValue.Value, Char))
Dim charValue = ConstantValue.Create("b"c)
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), charValue, charType)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, charValue, charType, Nothing)
Assert.Equal(ConversionKind.WideningString, ClassifyConversion(literal, stringType, methodBodyBinder))
Assert.Equal(ConversionKind.WideningString, ClassifyConversion(constant, stringType, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, stringType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, stringType, integerOverflow2)
Assert.NotNull(resultValue)
Assert.NotNull(resultValue2)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(integerOverflow, integerOverflow2)
Assert.Equal(resultValue2, resultValue)
Assert.Equal(stringType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
Assert.Equal("b", DirectCast(resultValue.Value, String))
End Sub
<Fact()>
Public Sub ConstantExpressionConversions2()
Dim dummyCode =
<file>
Class C1
Shared Sub MethodDecl()
End Sub
End Class
</file>
Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value)
Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib},
options:=TestOptions.ReleaseExe.WithOverflowChecks(False))
Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol)
Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol)
Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol)
Assert.False(c1.Options.CheckOverflow)
Dim objectType = c1.GetSpecialType(System_Object)
Dim booleanType = c1.GetSpecialType(System_Boolean)
Dim byteType = c1.GetSpecialType(System_Byte)
Dim sbyteType = c1.GetSpecialType(System_SByte)
Dim int16Type = c1.GetSpecialType(System_Int16)
Dim uint16Type = c1.GetSpecialType(System_UInt16)
Dim int32Type = c1.GetSpecialType(System_Int32)
Dim uint32Type = c1.GetSpecialType(System_UInt32)
Dim int64Type = c1.GetSpecialType(System_Int64)
Dim uint64Type = c1.GetSpecialType(System_UInt64)
Dim doubleType = c1.GetSpecialType(System_Double)
Dim singleType = c1.GetSpecialType(System_Single)
Dim decimalType = c1.GetSpecialType(System_Decimal)
Dim dateType = c1.GetSpecialType(System_DateTime)
Dim stringType = c1.GetSpecialType(System_String)
Dim charType = c1.GetSpecialType(System_Char)
Dim intPtrType = c1.GetSpecialType(System_IntPtr)
Dim typeCodeType = c1.GlobalNamespace.GetMembers("System").OfType(Of NamespaceSymbol)().Single().GetTypeMembers("TypeCode").Single()
Dim allTestTypes = New TypeSymbol() {
objectType, booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType,
stringType, charType, intPtrType, typeCodeType}
Dim convertableTypes = New HashSet(Of TypeSymbol)({
booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType,
stringType, charType, typeCodeType})
Dim integralTypes = New HashSet(Of TypeSymbol)({
byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, typeCodeType})
Dim unsignedTypes = New HashSet(Of TypeSymbol)({
byteType, uint16Type, uint32Type, uint64Type})
Dim numericTypes = New HashSet(Of TypeSymbol)({
byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, typeCodeType})
Dim floatingTypes = New HashSet(Of TypeSymbol)({doubleType, singleType})
Dim _nothing = New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing)
Dim resultValue As ConstantValue
Dim integerOverflow As Boolean
Dim literal As BoundLiteral
Dim constant As BoundConversion
Dim nullableType = c1.GetSpecialType(System_Nullable_T)
' -------- Numeric non-zero values
Dim nonZeroValues = New TypeAndValue() {
New TypeAndValue(sbyteType, SByte.MinValue),
New TypeAndValue(int16Type, Int16.MinValue),
New TypeAndValue(int32Type, Int32.MinValue),
New TypeAndValue(int64Type, Int64.MinValue),
New TypeAndValue(doubleType, Double.MinValue),
New TypeAndValue(singleType, Single.MinValue),
New TypeAndValue(decimalType, Decimal.MinValue),
New TypeAndValue(sbyteType, SByte.MaxValue),
New TypeAndValue(int16Type, Int16.MaxValue),
New TypeAndValue(int32Type, Int32.MaxValue),
New TypeAndValue(int64Type, Int64.MaxValue),
New TypeAndValue(byteType, Byte.MaxValue),
New TypeAndValue(uint16Type, UInt16.MaxValue),
New TypeAndValue(uint32Type, UInt32.MaxValue),
New TypeAndValue(uint64Type, UInt64.MaxValue),
New TypeAndValue(doubleType, Double.MaxValue),
New TypeAndValue(singleType, Single.MaxValue),
New TypeAndValue(decimalType, Decimal.MaxValue),
New TypeAndValue(sbyteType, CSByte(-1)),
New TypeAndValue(int16Type, CShort(-2)),
New TypeAndValue(int32Type, CInt(-3)),
New TypeAndValue(int64Type, CLng(-4)),
New TypeAndValue(sbyteType, CSByte(5)),
New TypeAndValue(int16Type, CShort(6)),
New TypeAndValue(int32Type, CInt(7)),
New TypeAndValue(int64Type, CLng(8)),
New TypeAndValue(doubleType, CDbl(-9)),
New TypeAndValue(singleType, CSng(-10)),
New TypeAndValue(decimalType, CDec(-11)),
New TypeAndValue(doubleType, CDbl(12)),
New TypeAndValue(singleType, CSng(13)),
New TypeAndValue(decimalType, CDec(14)),
New TypeAndValue(byteType, CByte(15)),
New TypeAndValue(uint16Type, CUShort(16)),
New TypeAndValue(uint32Type, CUInt(17)),
New TypeAndValue(uint64Type, CULng(18)),
New TypeAndValue(decimalType, CDec(-11.3)),
New TypeAndValue(doubleType, CDbl(&HF000000000000000UL)),
New TypeAndValue(doubleType, CDbl(&H70000000000000F0L)),
New TypeAndValue(typeCodeType, Int32.MinValue),
New TypeAndValue(typeCodeType, Int32.MaxValue),
New TypeAndValue(typeCodeType, CInt(-3)),
New TypeAndValue(typeCodeType, CInt(7))
}
Dim resultValue2 As ConstantValue
Dim integerOverflow2 As Boolean
For Each mv In nonZeroValues
Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator())
Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator())
literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type)
constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing),
New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing),
ConversionKind.Widening, True, True, v, mv.Type, Nothing)
For Each numericType In numericTypes
Dim typeConv = ClassifyConversion(mv.Type, numericType)
Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder)
Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder)
Assert.Equal(conv, conv2)
resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow)
resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2)
Assert.Equal(resultValue Is Nothing, resultValue2 Is Nothing)
Assert.Equal(integerOverflow, integerOverflow2)
If resultValue IsNot Nothing Then
Assert.Equal(resultValue2, resultValue)
If Not resultValue.IsBad Then
Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator)
End If
End If
Dim resultValueAsObject As Object = Nothing
Dim overflow As Boolean = False
Try
resultValueAsObject = CheckedConvert(v.Value, numericType)
Catch ex As OverflowException
overflow = True
End Try
If Not overflow Then
If Conversions.IsIdentityConversion(typeConv) Then
Assert.True(Conversions.IsIdentityConversion(conv))
ElseIf Conversions.IsNarrowingConversion(typeConv) Then
If mv.Type Is doubleType AndAlso numericType Is singleType Then
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
ElseIf integralTypes.Contains(mv.Type) AndAlso numericType.IsEnumType() Then
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv)
ElseIf integralTypes.Contains(mv.Type) AndAlso integralTypes.Contains(numericType) AndAlso Not mv.Type.IsEnumType() AndAlso Not numericType.IsEnumType() Then
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
Else
Assert.Equal(typeConv, conv)
End If
ElseIf mv.Type.IsEnumType() Then
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv)
Else
Assert.Equal(ConversionKind.WideningNumeric, conv)
End If
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(resultValueAsObject, resultValue.Value)
If mv.Type Is doubleType AndAlso numericType Is singleType Then
If v.DoubleValue = Double.MinValue Then
Dim min As Single = Double.MinValue
Assert.True(Single.IsNegativeInfinity(min))
Assert.Equal(resultValue.SingleValue, min)
ElseIf v.DoubleValue = Double.MaxValue Then
Dim max As Single = Double.MaxValue
Assert.Equal(Double.MaxValue, v.DoubleValue)
Assert.True(Single.IsPositiveInfinity(max))
Assert.Equal(resultValue.SingleValue, max)
End If
End If
ElseIf Not integralTypes.Contains(mv.Type) OrElse Not integralTypes.Contains(numericType) Then
'Assert.Equal(typeConv, conv)
If integralTypes.Contains(numericType) Then
Assert.NotNull(resultValue)
If resultValue.IsBad Then
Assert.False(integerOverflow)
Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv)
Else
Assert.True(integerOverflow)
Assert.Equal(typeConv, conv)
Dim intermediate As Object
If unsignedTypes.Contains(numericType) Then
intermediate = Convert.ToUInt64(mv.Value)
Else
intermediate = Convert.ToInt64(mv.Value)
End If
Dim gotException As Boolean
Try
gotException = False
CheckedConvert(intermediate, numericType) ' Should get an overflow
Catch x As Exception
gotException = True
End Try
Assert.True(gotException)
Assert.Equal(UncheckedConvert(intermediate, numericType), resultValue.Value)
End If
Else
Assert.NotNull(resultValue)
Assert.False(integerOverflow)
Assert.True(resultValue.IsBad)
Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv)
End If
Else
' An integer overflow case
If numericType.IsEnumType() OrElse mv.Type.IsEnumType() Then
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv)
Else
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv)
End If
Assert.NotNull(resultValue)
Assert.True(integerOverflow)
Assert.False(resultValue.IsBad)
Assert.Equal(UncheckedConvert(v.Value, numericType), resultValue.Value)
End If
Dim nullableType2 = nullableType.Construct(numericType)
Dim zero = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing),
New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Default(ConstantValueTypeDiscriminator.Int32), int32Type),
ConversionKind.Widening, True, True, ConstantValue.Default(mv.Type.GetConstantValueTypeDiscriminator()), mv.Type, Nothing)
conv = ClassifyConversion(literal, numericType, methodBodyBinder)
If (conv And ConversionKind.FailedDueToNumericOverflowMask) = 0 Then
conv = ClassifyConversion(mv.Type, nullableType2) Or
(ClassifyConversion(zero, nullableType2, methodBodyBinder) And ConversionKind.InvolvesNarrowingFromNumericConstant)
End If
Assert.Equal(conv, ClassifyConversion(literal, nullableType2, methodBodyBinder))
Assert.Equal(conv, ClassifyConversion(constant, nullableType2, methodBodyBinder))
resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow)
Assert.Null(resultValue)
Assert.False(integerOverflow)
Next
Next
End Sub
Private Function CheckedConvert(value As Object, type As TypeSymbol) As Object
type = type.GetEnumUnderlyingTypeOrSelf()
Select Case type.SpecialType
Case System_Byte : Return CByte(value)
Case System_SByte : Return CSByte(value)
Case System_Int16 : Return CShort(value)
Case System_UInt16 : Return CUShort(value)
Case System_Int32 : Return CInt(value)
Case System_UInt32 : Return CUInt(value)
Case System_Int64 : Return CLng(value)
Case System_UInt64 : Return CULng(value)
Case System_Single : Return CSng(value)
Case System_Double : Return CDbl(value)
Case System_Decimal : Return CDec(value)
Case Else
Throw New NotSupportedException()
End Select
End Function
Private Function UncheckedConvert(value As Object, type As TypeSymbol) As Object
type = type.GetEnumUnderlyingTypeOrSelf()
Select Case System.Type.GetTypeCode(value.GetType())
Case TypeCode.Byte, TypeCode.UInt16, TypeCode.UInt32, TypeCode.UInt64
Dim val As UInt64 = Convert.ToUInt64(value)
Select Case type.SpecialType
Case System_Byte : Return UncheckedCByte(UncheckedCLng(val))
Case System_SByte : Return UncheckedCSByte(UncheckedCLng(val))
Case System_Int16 : Return UncheckedCShort(val)
Case System_UInt16 : Return UncheckedCUShort(UncheckedCLng(val))
Case System_Int32 : Return UncheckedCInt(val)
Case System_UInt32 : Return UncheckedCUInt(val)
Case System_Int64 : Return UncheckedCLng(val)
Case System_UInt64 : Return UncheckedCULng(val)
Case Else
Throw New NotSupportedException()
End Select
Case TypeCode.SByte, TypeCode.Int16, TypeCode.Int32, TypeCode.Int64
Dim val As Int64 = Convert.ToInt64(value)
Select Case type.SpecialType
Case System_Byte : Return UncheckedCByte(val)
Case System_SByte : Return UncheckedCSByte(val)
Case System_Int16 : Return UncheckedCShort(val)
Case System_UInt16 : Return UncheckedCUShort(val)
Case System_Int32 : Return UncheckedCInt(val)
Case System_UInt32 : Return UncheckedCUInt(val)
Case System_Int64 : Return UncheckedCLng(val)
Case System_UInt64 : Return UncheckedCULng(val)
Case Else
Throw New NotSupportedException()
End Select
Case Else
Throw New NotSupportedException()
End Select
Select Case type.SpecialType
Case System_Byte : Return CByte(value)
Case System_SByte : Return CSByte(value)
Case System_Int16 : Return CShort(value)
Case System_UInt16 : Return CUShort(value)
Case System_Int32 : Return CInt(value)
Case System_UInt32 : Return CUInt(value)
Case System_Int64 : Return CLng(value)
Case System_UInt64 : Return CULng(value)
Case System_Single : Return CSng(value)
Case System_Double : Return CDbl(value)
Case System_Decimal : Return CDec(value)
Case Else
Throw New NotSupportedException()
End Select
End Function
Friend Structure TypeAndValue
Public ReadOnly Type As TypeSymbol
Public ReadOnly Value As Object
Sub New(type As TypeSymbol, value As Object)
Me.Type = type
Me.Value = value
End Sub
End Structure
<Fact()>
Public Sub PredefinedNotBuiltIn()
' Tests are based on the source code used to compile VBConversions.dll, VBConversions.vb is
' checked in next to the DLL.
Dim vbConversionsRef = TestReferences.SymbolsTests.VBConversions
Dim modifiersRef = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll
Dim c1 = VisualBasicCompilation.Create("Test", references:={TestReferences.NetFx.v4_0_21006.mscorlib, vbConversionsRef, modifiersRef})
Dim asmVBConversions = c1.GetReferencedAssemblySymbol(vbConversionsRef)
Dim asmModifiers = c1.GetReferencedAssemblySymbol(modifiersRef)
Dim test = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Test").Single()
'--------------- Identity
Dim m1 = DirectCast(test.GetMembers("M1").Single(), MethodSymbol)
Dim m1p = m1.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(a), m1p(b))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(a), m1p(c))) 'error BC30311: Value of type 'Class2' cannot be converted to 'Class1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(a), m1p(d))) 'error BC30311: Value of type '1-dimensional array of Class1' cannot be converted to 'Class1'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(d), m1p(e))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(d), m1p(f))) 'error BC30332: Value of type '1-dimensional array of Class2' cannot be converted to '1-dimensional array of Class1' because 'Class2' is not derived from 'Class1'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(g), m1p(h))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(g), m1p(i))) 'error BC30311: Value of type 'Class2.Class3(Of Byte)' cannot be converted to 'Class2.Class3(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(g), m1p(j))) 'error BC30311: Value of type 'Class4(Of Integer)' cannot be converted to 'Class2.Class3(Of Integer)'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(j), m1p(k))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(j), m1p(l))) 'error BC30311: Value of type 'Class4(Of Byte)' cannot be converted to 'Class4(Of Integer)'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(m), m1p(n))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(m), m1p(o))) 'error BC30311: Value of type 'Class4(Of Byte).Class5(Of Integer)' cannot be converted to 'Class4(Of Integer).Class5(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(m), m1p(p))) 'error BC30311: Value of type 'Class4(Of Integer).Class5(Of Byte)' cannot be converted to 'Class4(Of Integer).Class5(Of Integer)'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(q), m1p(r))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(q), m1p(s))) 'error BC30311: Value of type 'Class4(Of Byte).Class6' cannot be converted to 'Class4(Of Integer).Class6'.
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(t), m1p(u))))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(t), m1p(v))) 'error BC30311: Value of type 'Class4(Of Byte).Class6.Class7(Of Integer)' cannot be converted to 'Class4(Of Integer).Class6.Class7(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m1p(t), m1p(w))) 'error BC30311: Value of type 'Class4(Of Integer).Class6.Class7(Of Byte)' cannot be converted to 'Class4(Of Integer).Class6.Class7(Of Integer)'.
Dim modifiers = asmModifiers.Modules(0).GlobalNamespace.GetTypeMembers("Modifiers").Single()
Dim modifiedArrayInt32 = modifiers.GetMembers("F5").OfType(Of MethodSymbol)().Single().Parameters(0).Type
Dim arrayInt32 = c1.CreateArrayTypeSymbol(c1.GetSpecialType(System_Int32))
Assert.NotEqual(modifiedArrayInt32, arrayInt32)
Assert.NotEqual(arrayInt32, modifiedArrayInt32)
Assert.True(arrayInt32.IsSameTypeIgnoringCustomModifiers(modifiedArrayInt32))
Assert.True(modifiedArrayInt32.IsSameTypeIgnoringCustomModifiers(arrayInt32))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(arrayInt32, modifiedArrayInt32)))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(modifiedArrayInt32, arrayInt32)))
Dim enumerable = c1.GetSpecialType(System_Collections_Generic_IEnumerable_T)
Dim enumerableOfModifiedArrayInt32 = enumerable.Construct(modifiedArrayInt32)
Dim enumerableOfArrayInt32 = enumerable.Construct(arrayInt32)
Assert.NotEqual(enumerableOfModifiedArrayInt32, enumerableOfArrayInt32)
Assert.NotEqual(enumerableOfArrayInt32, enumerableOfModifiedArrayInt32)
Assert.True(enumerableOfArrayInt32.IsSameTypeIgnoringCustomModifiers(enumerableOfModifiedArrayInt32))
Assert.True(enumerableOfModifiedArrayInt32.IsSameTypeIgnoringCustomModifiers(enumerableOfArrayInt32))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(enumerableOfArrayInt32, enumerableOfModifiedArrayInt32)))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(enumerableOfModifiedArrayInt32, enumerableOfArrayInt32)))
'--------------- Numeric
Dim m2 = DirectCast(test.GetMembers("M2").Single(), MethodSymbol)
Dim m2p = m2.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m2p(a), m2p(b))))
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum3' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(g))) 'error BC30512: Option Strict On disallows implicit conversions from 'Short' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(h))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum4' to 'Enum1'.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(a)))
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Integer'.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(d)))
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(a)))
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(c)))
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(d)))
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'Short'.
Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Short'.
Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(d)))
'--------------- Reference
Dim m3 = DirectCast(test.GetMembers("M3").Single(), MethodSymbol)
Dim m3p = m3.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(a), m3p(a))))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(d)))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(b), m3p(b))))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(b), m3p(c)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(b), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(c), m3p(d)))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Class10'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(c), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Class9'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Class10'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Class10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(c), m3p(e))) 'error BC30311: Value of type 'Class11' cannot be converted to 'Class9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(e), m3p(c))) 'error BC30311: Value of type 'Class9' cannot be converted to 'Class11'.
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(f), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(h)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(f), m3p(h)))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to '1-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Array' to '1-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Array' to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(j), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(k), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(l), m3p(c)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(l), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(b)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(c)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(n), m3p(d)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(p), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(p), m3p(h)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(q), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(r), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(s), m3p(g)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(v), m3p(u)))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(i), m3p(i))))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(j)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(k)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(o)))
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(n), m3p(o)))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class11' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(j), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface2'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(j), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface2'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(k), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface3'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(k), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface3'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(l), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface4'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(n), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface6'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(n), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface6'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class10' to 'Interface7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(q), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.IList(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(r), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.ICollection(Of Integer)'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(s), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.IEnumerable(Of Integer)'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(t), m3p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to 'System.Collections.Generic.IList(Of Long)'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(w), m3p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'System.Collections.Generic.IList(Of Class11)'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface4' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingReference Or ConversionKind.DelegateRelaxationLevelNarrowing, ClassifyPredefinedAssignment(m3p(o), m3p(x))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Action' to 'Interface7'.
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(o)))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(x), m3p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'System.Action'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(e), m3p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'Class11'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(g), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(h), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '2-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(u), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '1-dimensional array of Class9'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to '1-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Integer)' to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(h), m3p(q))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Integer)' cannot be converted to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Long)' to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(h), m3p(t))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Long)' cannot be converted to '2-dimensional array of Integer'.
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(w))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class11)' to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m3p(h), m3p(w))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Class11)' cannot be converted to '2-dimensional array of Integer'.
Dim [object] = c1.GetSpecialType(System_Object)
Dim module2 = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Module2").Single()
Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment([object], module2))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(module2, [object]))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), module2))
Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(module2, m3p(i)))
' ------------- Type Parameter
Dim m6 = DirectCast(test.GetMembers("M6").Single(), MethodSymbol)
Dim m6p = m6.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m6p(b), m6p(b))))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(b)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(c)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(d)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT2'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(d), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT3'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(f)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(h)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(h), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(f), m6p(g))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(g), m6p(f))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(h), m6p(i))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(i), m6p(h))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT7'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(j), m6p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(j), m6p(f)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT4'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(l), m6p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(m), m6p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(p), m6p(c)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class10' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(n), m6p(k))) 'error BC30311: Value of type 'MT8' cannot be converted to 'Class12'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(k), m6p(n))) 'error BC30311: Value of type 'Class12' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(k), m6p(o))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(o), m6p(k))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT9'.
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(q)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(r)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(t), m6p(s)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(m), m6p(s)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(q), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT10'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(r), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT11'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(s), m6p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'MT13'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(s), m6p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'MT13'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(l), m6p(s))) 'error BC30311: Value of type 'MT13' cannot be converted to 'Class10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(s), m6p(l))) 'error BC30311: Value of type 'Class10' cannot be converted to 'MT13'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(k))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT8' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT8'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT4' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'Interface7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(v), m6p(q))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT14'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m6p(q), m6p(v))) 'error BC30311: Value of type 'MT14' cannot be converted to 'MT10'.
Dim m7 = DirectCast(test.GetMembers("M7").Single(), MethodSymbol)
Dim m7p = m7.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(p), m7p(a)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(p), m7p(b)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(q), m7p(c)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(q), m7p(d)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(r), m7p(d)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(t), m7p(g)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(v), m7p(j)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(v), m7p(k)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(w), m7p(n)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(x), m7p(i)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(j)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(k)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(a), m7p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(b), m7p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT2'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(c), m7p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'MT3'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(r))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(g), m7p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to 'MT7'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(j), m7p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'MT10'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(k), m7p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'MT11'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(n), m7p(w))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure1' to 'MT14'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(i), m7p(x))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to 'MT9'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT9' to 'System.Collections.Generic.IList(Of Class9)'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(i), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT9'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(j), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT10'
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(k), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT11'
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(z))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT15' to 'System.Collections.Generic.IList(Of Class9)'
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(z), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT15'
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(n), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT14'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(n))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT14' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(m), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT13'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT13' to 'Interface1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT4' to 'Interface1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(r), m7p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(e), m7p(r))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(s), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'Enum2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(d), m7p(s))) 'error BC30311: Value of type 'Enum2' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(r), m7p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(f), m7p(r))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(t), m7p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to '1-dimensional array of Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(h), m7p(t))) 'error BC30311: Value of type '1-dimensional array of Integer' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(v), m7p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to '1-dimensional array of Class9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(i), m7p(v))) 'error BC30311: Value of type '1-dimensional array of Class9' cannot be converted to 'MT9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(a), m7p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(b), m7p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(g), m7p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(h), m7p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(g), m7p(l))) 'error BC30311: Value of type 'MT12' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(l), m7p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT12'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(c), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT3'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(d), m7p(c))) 'error BC30311: Value of type 'MT3' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(i), m7p(j))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(j), m7p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(a), m7p(n))) 'error BC30311: Value of type 'MT14' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(n), m7p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT14'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(d), m7p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m7p(f), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT6'.
Dim m8 = DirectCast(test.GetMembers("M8").Single(), MethodSymbol)
Dim m8p = m8.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m8p(a), m8p(a))))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(a), m8p(d)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(b), m8p(f)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(a), m8p(c)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(b), m8p(e)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(g), m8p(h)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(c), m8p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT3'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(d), m8p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT4'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(e), m8p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'MT5'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(f), m8p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'MT6'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(h), m8p(g))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT7' to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(a), m8p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(b), m8p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(b), m8p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(d), m8p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(a), m8p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m8p(g), m8p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT7'.
Dim m9 = DirectCast(test.GetMembers("M9").Single(), MethodSymbol)
Dim m9p = m9.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(a), m9p(b)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(j), m9p(a)))
Assert.Equal(ConversionKind.WideningTypeParameter Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m9p(j), m9p(e)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(l), m9p(e)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(m), m9p(n)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(p), m9p(q)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(s), m9p(u)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(t), m9p(u)))
Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(s), m9p(v)))
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(b), m9p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT2'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(a), m9p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'MT1'.
Assert.Equal(ConversionKind.NarrowingTypeParameter Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m9p(e), m9p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'MT5'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(e), m9p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'MT5'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(n), m9p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure1' to 'MT10'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(q), m9p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class1' to 'MT12'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(u), m9p(s))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT15'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(u), m9p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT14' to 'MT15'.
Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(v), m9p(s))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT16'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(g), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(l))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(l), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(c))) 'error BC30311: Value of type 'MT3' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(c), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT3'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(d), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(f), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(h), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(f), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(h), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(a), m9p(k))) 'error BC30311: Value of type 'UInteger' cannot be converted to 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(k), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'UInteger'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(e), m9p(k))) 'error BC30311: Value of type 'UInteger' cannot be converted to 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(k), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'UInteger'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(n), m9p(o))) 'error BC30311: Value of type 'MT11' cannot be converted to 'MT10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(o), m9p(n))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT11'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(q), m9p(r))) 'error BC30311: Value of type 'MT13' cannot be converted to 'MT12'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(r), m9p(q))) 'error BC30311: Value of type 'MT12' cannot be converted to 'MT13'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(v), m9p(w))) 'error BC30311: Value of type 'MT17' cannot be converted to 'MT16'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m9p(w), m9p(v))) 'error BC30311: Value of type 'MT16' cannot be converted to 'MT17'.
' ------------- Array conversions
Dim m4 = DirectCast(test.GetMembers("M4").Single(), MethodSymbol)
Dim m4p = m4.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(a), m4p(a))))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(l), m4p(l))))
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(n), m4p(n))))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(a), m4p(d)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(b), m4p(f)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(i), m4p(j)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(i), m4p(k)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(l), m4p(m)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(n), m4p(o)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(p), m4p(i)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(x), m4p(i)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(x), m4p(w)))
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(a), m4p(c))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT3' to '1-dimensional array of MT1'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(c), m4p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT3'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(d), m4p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT4'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(b), m4p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT2'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(e), m4p(b))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT2' to '1-dimensional array of MT5'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(f), m4p(b))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT2' to '1-dimensional array of MT6'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(g), m4p(h))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT8' to '1-dimensional array of MT7'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(h), m4p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT7' to '1-dimensional array of MT8'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(j), m4p(i))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class8' to '1-dimensional array of Class9'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(k), m4p(i))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class8' to '1-dimensional array of Class11'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(m), m4p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '2-dimensional array of Class8' to '2-dimensional array of Class9'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(o), m4p(n))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of 1-dimensional array of Class8' to '1-dimensional array of 1-dimensional array of Class9'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(i), m4p(p))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Interface5' to '1-dimensional array of Class8'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(i), m4p(x))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Object' to '1-dimensional array of Class8'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(w), m4p(x))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Object' to '1-dimensional array of System.ValueType'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(a), m4p(b))) 'error BC30332: Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(b), m4p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT2' because 'MT1' is not derived from 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(b), m4p(d))) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of MT2' because 'MT4' is not derived from 'MT2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(d), m4p(b))) 'error BC30332: Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT4' because 'MT2' is not derived from 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(a), m4p(g))) 'error BC30332: Value of type '1-dimensional array of MT7' cannot be converted to '1-dimensional array of MT1' because 'MT7' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(g), m4p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT7' because 'MT1' is not derived from 'MT7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(j), m4p(k))) 'error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(i), m4p(l))) 'error BC30414: Value of type '2-dimensional array of Class8' cannot be converted to '1-dimensional array of Class8' because the array types have different numbers of dimensions.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(l), m4p(i))) 'error BC30414: Value of type '1-dimensional array of Class8' cannot be converted to '2-dimensional array of Class8' because the array types have different numbers of dimensions.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(l), m4p(n))) 'error BC30332: Value of type '1-dimensional array of 1-dimensional array of Class8' cannot be converted to '2-dimensional array of Class8' because '1-dimensional array of Class8' is not derived from 'Class8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(n), m4p(l))) 'error BC30332: Value of type '2-dimensional array of Class8' cannot be converted to '1-dimensional array of 1-dimensional array of Class8' because 'Class8' is not derived from '1-dimensional array of Class8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(p), m4p(q))) 'error BC30332: Value of type '1-dimensional array of Structure1' cannot be converted to '1-dimensional array of Interface5' because 'Structure1' is not derived from 'Interface5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(q), m4p(p))) 'error BC30332: Value of type '1-dimensional array of Interface5' cannot be converted to '1-dimensional array of Structure1' because 'Interface5' is not derived from 'Structure1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(q), m4p(w))) 'error BC30332: Value of type '1-dimensional array of System.ValueType' cannot be converted to '1-dimensional array of Structure1' because 'System.ValueType' is not derived from 'Structure1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(w), m4p(q))) 'error BC30333: Value of type '1-dimensional array of Structure1' cannot be converted to '1-dimensional array of System.ValueType' because 'Structure1' is not a reference type.
Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(r), m4p(t)))
Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(s), m4p(u)))
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(t), m4p(r))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of Enum1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(u), m4p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Long' to '1-dimensional array of Enum2'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(t), m4p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum4' to '1-dimensional array of Enum1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(v), m4p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of Enum4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(r), m4p(s))) 'error BC30332: Value of type '1-dimensional array of Long' cannot be converted to '1-dimensional array of Integer' because 'Long' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(s), m4p(r))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of Long' because 'Integer' is not derived from 'Long'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(r), m4p(u))) 'error BC30332: Value of type '1-dimensional array of Enum2' cannot be converted to '1-dimensional array of Integer' because 'Enum2' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(u), m4p(r))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of Enum2' because 'Integer' is not derived from 'Enum2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(t), m4p(u))) 'error BC30332: Value of type '1-dimensional array of Enum2' cannot be converted to '1-dimensional array of Enum1' because 'Enum2' is not derived from 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m4p(u), m4p(t))) 'error BC30332: Value of type '1-dimensional array of Enum1' cannot be converted to '1-dimensional array of Enum2' because 'Enum1' is not derived from 'Enum2'.
Dim m5 = DirectCast(test.GetMembers("M5").Single(), MethodSymbol)
Dim m5p = m5.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(a), m5p(b)))
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(b), m5p(a))) ' error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT2'.
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(j), m5p(a)))
Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(j), m5p(e)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(l), m5p(e)))
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(a), m5p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT5'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT7' to '1-dimensional array of MT5'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(g), m5p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT7'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(a), m5p(j))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of MT1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(a), m5p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of MT1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(l), m5p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of Enum1'.
Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(j))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of MT5'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(e), m5p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(i))) 'error BC30332: Value of type '1-dimensional array of MT9' cannot be converted to '1-dimensional array of MT1' because 'MT9' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(c))) 'error BC30332: Value of type '1-dimensional array of MT3' cannot be converted to '1-dimensional array of MT1' because 'MT3' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(c), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT3' because 'MT1' is not derived from 'MT3'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(d))) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of MT1' because 'MT4' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(d), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT4' because 'MT1' is not derived from 'MT4'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(f))) 'error BC30332: Value of type '1-dimensional array of MT6' cannot be converted to '1-dimensional array of MT1' because 'MT6' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(f), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT6' because 'MT1' is not derived from 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(h))) 'error BC30332: Value of type '1-dimensional array of MT8' cannot be converted to '1-dimensional array of MT1' because 'MT8' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(h), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT8' because 'MT1' is not derived from 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(e), m5p(f))) 'error BC30332: Value of type '1-dimensional array of MT6' cannot be converted to '1-dimensional array of MT5' because 'MT6' is not derived from 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(f), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of MT6' because 'MT5' is not derived from 'MT6'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(e), m5p(h))) 'error BC30332: Value of type '1-dimensional array of MT8' cannot be converted to '1-dimensional array of MT5' because 'MT8' is not derived from 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(h), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of MT8' because 'MT5' is not derived from 'MT8'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(a), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of MT1' because 'UInteger' is not derived from 'MT1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(k), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of UInteger' because 'MT1' is not derived from 'UInteger'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(e), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of MT5' because 'UInteger' is not derived from 'MT5'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(k), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of UInteger' because 'MT5' is not derived from 'UInteger'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(j), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of Integer' because 'UInteger' is not derived from 'Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(k), m5p(j))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of UInteger' because 'Integer' is not derived from 'UInteger'.
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(m), m5p(n)))
Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(p), m5p(q)))
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(n), m5p(m))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Structure1' to '1-dimensional array of MT10'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(q), m5p(p))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class1' to '1-dimensional array of MT12'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(s), m5p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT15' to '1-dimensional array of System.ValueType'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(u), m5p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of System.ValueType' to '1-dimensional array of MT15'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(t), m5p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT15' to '1-dimensional array of MT14'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(u), m5p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT14' to '1-dimensional array of MT15'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(s), m5p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT16' to '1-dimensional array of System.ValueType'.
Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(v), m5p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of System.ValueType' to '1-dimensional array of MT16'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(n), m5p(o))) 'error BC30332: Value of type '1-dimensional array of MT11' cannot be converted to '1-dimensional array of MT10' because 'MT11' is not derived from 'MT10'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(o), m5p(n))) 'error BC30332: Value of type '1-dimensional array of MT10' cannot be converted to '1-dimensional array of MT11' because 'MT10' is not derived from 'MT11'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(q), m5p(r))) 'error BC30332: Value of type '1-dimensional array of MT13' cannot be converted to '1-dimensional array of MT12' because 'MT13' is not derived from 'MT12'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(r), m5p(q))) 'error BC30332: Value of type '1-dimensional array of MT12' cannot be converted to '1-dimensional array of MT13' because 'MT12' is not derived from 'MT13'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(v), m5p(w))) 'error BC30332: Value of type '1-dimensional array of MT17' cannot be converted to '1-dimensional array of MT16' because 'MT17' is not derived from 'MT16'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m5p(w), m5p(v))) 'error BC30332: Value of type '1-dimensional array of MT16' cannot be converted to '1-dimensional array of MT17' because 'MT16' is not derived from 'MT17'.
' ------------- Value Type
Dim void = c1.GetSpecialType(System_Void)
Dim valueType = c1.GetSpecialType(System_ValueType)
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(void, void)))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment([object], void))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(void, [object]))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(valueType, void))
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(void, valueType))
Dim m10 = DirectCast(test.GetMembers("M10").Single(), MethodSymbol)
Dim m10p = m10.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m10p(f), m10p(f))))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(a), m10p(f)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(b), m10p(f)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(a), m10p(h)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(b), m10p(h)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(c), m10p(h)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(d), m10p(f)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(i), m10p(f)))
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Structure2'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Structure2'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'Enum1'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'Structure2'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(c), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'System.Enum'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(f), m10p(c))) 'error BC30311: Value of type 'System.Enum' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(d), m10p(h))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'Interface1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(h), m10p(d))) 'error BC30311: Value of type 'Interface1' cannot be converted to 'Enum1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(e), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Interface7'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(f), m10p(e))) 'error BC30311: Value of type 'Interface7' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(f), m10p(g))) 'error BC30311: Value of type 'Structure1' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(g), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Structure1'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(f), m10p(h))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m10p(h), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Enum1'.
' ------------ Nullable
Dim m11 = DirectCast(test.GetMembers("M11").Single(), MethodSymbol)
Dim m11p = m11.Parameters.Select(Function(p) p.Type).ToArray()
Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m11p(d), m11p(d))))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m11p(a), m11p(d)))
Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m11p(b), m11p(d)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(d), m11p(c)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(e), m11p(d)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(f), m11p(d)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(i), m11p(h)))
Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(k), m11p(i)))
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m11p(d), m11p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Structure2?'.
Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m11p(d), m11p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Structure2?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(c), m11p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure2?' to 'Structure2'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(d), m11p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'Structure2?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(d), m11p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'Structure2?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(h), m11p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(i), m11p(k))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long?' to 'Integer?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(i), m11p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer?'.
Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(j), m11p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Long'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(c), m11p(i))) 'error BC30311: Value of type 'Integer?' cannot be converted to 'Structure2'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(i), m11p(c))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Integer?'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(d), m11p(h))) 'error BC30311: Value of type 'Integer' cannot be converted to 'Structure2?'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(h), m11p(d))) 'error BC30311: Value of type 'Structure2?' cannot be converted to 'Integer'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(d), m11p(i))) 'error BC30311: Value of type 'Integer?' cannot be converted to 'Structure2?'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m11p(i), m11p(d))) 'error BC30311: Value of type 'Structure2?' cannot be converted to 'Integer?'.
' ------------ String
Dim m12 = DirectCast(test.GetMembers("M12").Single(), MethodSymbol)
Dim m12p = m12.Parameters.Select(Function(p) p.Type).ToArray()
Assert.Equal(ConversionKind.WideningString, ClassifyPredefinedAssignment(m12p(a), m12p(b)))
Assert.Equal(ConversionKind.WideningString, ClassifyPredefinedAssignment(m12p(a), m12p(c)))
Assert.Equal(ConversionKind.NarrowingString, ClassifyPredefinedAssignment(m12p(b), m12p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'.
Assert.Equal(ConversionKind.NarrowingString, ClassifyPredefinedAssignment(m12p(c), m12p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'String' to '1-dimensional array of Char'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m12p(b), m12p(c))) 'error BC30311: Value of type '1-dimensional array of Char' cannot be converted to 'Char'.
Assert.Equal(NoConversion, ClassifyPredefinedAssignment(m12p(c), m12p(b))) 'error BC30311: Value of type 'Char' cannot be converted to '1-dimensional array of Char'.
End Sub
Private Shared Function ClassifyPredefinedAssignment([to] As TypeSymbol, [from] As TypeSymbol) As ConversionKind
Dim result As ConversionKind = Conversions.ClassifyPredefinedConversion([from], [to], Nothing) And Not ConversionKind.MightSucceedAtRuntime
Assert.Equal(result, ClassifyConversion([from], [to]))
Return result
End Function
Enum Parameters
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
End Enum
<Fact()>
Public Sub BuiltIn()
Dim c1 = VisualBasicCompilation.Create("Test", references:={TestReferences.NetFx.v4_0_21006.mscorlib})
Dim nullable = c1.GetSpecialType(System_Nullable_T)
Dim types As NamedTypeSymbol() = {
c1.GetSpecialType(System_Byte),
c1.GetSpecialType(System_SByte),
c1.GetSpecialType(System_UInt16),
c1.GetSpecialType(System_Int16),
c1.GetSpecialType(System_UInt32),
c1.GetSpecialType(System_Int32),
c1.GetSpecialType(System_UInt64),
c1.GetSpecialType(System_Int64),
c1.GetSpecialType(System_Decimal),
c1.GetSpecialType(System_Single),
c1.GetSpecialType(System_Double),
c1.GetSpecialType(System_String),
c1.GetSpecialType(System_Char),
c1.GetSpecialType(System_Boolean),
c1.GetSpecialType(System_DateTime),
c1.GetSpecialType(System_Object),
nullable.Construct(c1.GetSpecialType(System_Byte)),
nullable.Construct(c1.GetSpecialType(System_SByte)),
nullable.Construct(c1.GetSpecialType(System_UInt16)),
nullable.Construct(c1.GetSpecialType(System_Int16)),
nullable.Construct(c1.GetSpecialType(System_UInt32)),
nullable.Construct(c1.GetSpecialType(System_Int32)),
nullable.Construct(c1.GetSpecialType(System_UInt64)),
nullable.Construct(c1.GetSpecialType(System_Int64)),
nullable.Construct(c1.GetSpecialType(System_Decimal)),
nullable.Construct(c1.GetSpecialType(System_Single)),
nullable.Construct(c1.GetSpecialType(System_Double)),
nullable.Construct(c1.GetSpecialType(System_Char)),
nullable.Construct(c1.GetSpecialType(System_Boolean)),
nullable.Construct(c1.GetSpecialType(System_DateTime))
}
For i As Integer = 0 To types.Length - 1 Step 1
For j As Integer = 0 To types.Length - 1 Step 1
Dim convClass = Conversions.ClassifyPredefinedConversion(types(i), types(j), Nothing)
Assert.Equal(convClass, Conversions.ConversionEasyOut.ClassifyPredefinedConversion(types(i), types(j)))
Assert.Equal(convClass, ClassifyConversion(types(i), types(j)))
If (i = j) Then
Assert.True(Conversions.IsIdentityConversion(convClass))
Else
Dim baseline = HasBuiltInWideningConversions(types(i), types(j))
If baseline = NoConversion Then
baseline = HasBuiltInNarrowingConversions(types(i), types(j))
End If
Assert.Equal(baseline, convClass)
End If
Next
Next
End Sub
Private Function HasBuiltInWideningConversions(from As TypeSymbol, [to] As TypeSymbol) As ConversionKind
Dim result = HasBuiltInWideningConversions(from.SpecialType, [to].SpecialType)
If result = NoConversion Then
Dim fromIsNullable = from.IsNullableType()
Dim fromElement = If(fromIsNullable, from.GetNullableUnderlyingType(), Nothing)
If fromIsNullable AndAlso [to].SpecialType = System_Object Then
Return ConversionKind.WideningValue
End If
Dim toIsNullable = [to].IsNullableType()
Dim toElement = If(toIsNullable, [to].GetNullableUnderlyingType(), Nothing)
'Nullable Value Type conversions
'• From a type T? to a type S?, where there is a widening conversion from the type T to the type S.
If (fromIsNullable AndAlso toIsNullable) Then
If (HasBuiltInWideningConversions(fromElement, toElement) And ConversionKind.Widening) <> 0 Then
Return ConversionKind.WideningNullable
End If
End If
If (Not fromIsNullable AndAlso toIsNullable) Then
'• From a type T to the type T?.
If from.Equals(toElement) Then
Return ConversionKind.WideningNullable
End If
'• From a type T to a type S?, where there is a widening conversion from the type T to the type S.
If (HasBuiltInWideningConversions(from, toElement) And ConversionKind.Widening) <> 0 Then
Return ConversionKind.WideningNullable
End If
End If
End If
Return result
End Function
Private Function HasBuiltInNarrowingConversions(from As TypeSymbol, [to] As TypeSymbol) As ConversionKind
Dim result = HasBuiltInNarrowingConversions(from.SpecialType, [to].SpecialType)
If result = NoConversion Then
Dim toIsNullable = [to].IsNullableType()
Dim toElement = If(toIsNullable, [to].GetNullableUnderlyingType(), Nothing)
If from.SpecialType = System_Object AndAlso toIsNullable Then
Return ConversionKind.NarrowingValue
End If
Dim fromIsNullable = from.IsNullableType()
Dim fromElement = If(fromIsNullable, from.GetNullableUnderlyingType(), Nothing)
'Nullable Value Type conversions
If (fromIsNullable AndAlso Not toIsNullable) Then
'• From a type T? to a type T.
If fromElement.Equals([to]) Then
Return ConversionKind.NarrowingNullable
End If
'• From a type S? to a type T, where there is a conversion from the type S to the type T.
If HasBuiltInWideningConversions(fromElement, [to]) <> NoConversion OrElse
HasBuiltInNarrowingConversions(fromElement, [to]) <> NoConversion Then
Return ConversionKind.NarrowingNullable
End If
End If
'• From a type T? to a type S?, where there is a narrowing conversion from the type T to the type S.
If (fromIsNullable AndAlso toIsNullable) Then
If (HasBuiltInNarrowingConversions(fromElement, toElement) And ConversionKind.Narrowing) <> 0 Then
Return ConversionKind.NarrowingNullable
End If
End If
'• From a type T to a type S?, where there is a narrowing conversion from the type T to the type S.
If (Not fromIsNullable AndAlso toIsNullable) Then
If (HasBuiltInNarrowingConversions(from, toElement) And ConversionKind.Narrowing) <> 0 Then
Return ConversionKind.NarrowingNullable
End If
End If
End If
Return result
End Function
Const [Byte] = System_Byte
Const [SByte] = System_SByte
Const [UShort] = System_UInt16
Const [Short] = System_Int16
Const [UInteger] = System_UInt32
Const [Integer] = System_Int32
Const [ULong] = System_UInt64
Const [Long] = System_Int64
Const [Decimal] = System_Decimal
Const [Single] = System_Single
Const [Double] = System_Double
Const [String] = System_String
Const [Char] = System_Char
Const [Boolean] = System_Boolean
Const [Date] = System_DateTime
Const [Object] = System_Object
Private Function HasBuiltInWideningConversions(from As SpecialType, [to] As SpecialType) As ConversionKind
Select Case CInt(from)
'Numeric conversions
'• From Byte to UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
Case [Byte]
Select Case CInt([to])
Case [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From SByte to Short, Integer, Long, Decimal, Single, or Double.
Case [SByte]
Select Case CInt([to])
Case [Short], [Integer], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From UShort to UInteger, Integer, ULong, Long, Decimal, Single, or Double.
Case [UShort]
Select Case CInt([to])
Case [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Short to Integer, Long, Decimal, Single or Double.
Case [Short]
Select Case CInt([to])
Case [Integer], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From UInteger to ULong, Long, Decimal, Single, or Double.
Case [UInteger]
Select Case CInt([to])
Case [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Integer to Long, Decimal, Single or Double.
Case [Integer]
Select Case CInt([to])
Case [Long], [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From ULong to Decimal, Single, or Double.
Case [ULong]
Select Case CInt([to])
Case [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Long to Decimal, Single or Double.
Case [Long]
Select Case CInt([to])
Case [Decimal], [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Decimal to Single or Double.
Case [Decimal]
Select Case CInt([to])
Case [Single], [Double]
Return ConversionKind.WideningNumeric
End Select
'• From Single to Double.
Case [Single]
Select Case CInt([to])
Case [Double]
Return ConversionKind.WideningNumeric
End Select
'Reference conversions
'• From a reference type to a base type.
Case [String]
Select Case CInt([to])
Case [Object]
Return ConversionKind.WideningReference
End Select
'String conversions
'• From Char to String.
Case [Char]
Select Case CInt([to])
Case [String]
Return ConversionKind.WideningString
End Select
End Select
Select Case CInt([to])
'Value Type conversions
'• From a value type to a base type.
Case [Object]
Select Case CInt([from])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double],
[Char], [Boolean], [Date]
Return ConversionKind.WideningValue
End Select
End Select
Return NoConversion
End Function
Private Function HasBuiltInNarrowingConversions(from As SpecialType, [to] As SpecialType) As ConversionKind
Select Case CInt(from)
'Boolean conversions
'• From Boolean to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
Case [Boolean]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.NarrowingBoolean
End Select
'Numeric conversions
'• From Byte to SByte.
Case [Byte]
Select Case CInt([to])
Case [SByte]
Return ConversionKind.NarrowingNumeric
End Select
'• From SByte to Byte, UShort, UInteger, or ULong.
Case [SByte]
Select Case CInt([to])
Case [Byte], [UShort], [UInteger], [ULong]
Return ConversionKind.NarrowingNumeric
End Select
'• From UShort to Byte, SByte, or Short.
Case [UShort]
Select Case CInt([to])
Case [Byte], [SByte], [Short]
Return ConversionKind.NarrowingNumeric
End Select
'• From Short to Byte, SByte, UShort, UInteger, or ULong.
Case [Short]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [UInteger], [ULong]
Return ConversionKind.NarrowingNumeric
End Select
'• From UInteger to Byte, SByte, UShort, Short, or Integer.
Case [UInteger]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [Integer]
Return ConversionKind.NarrowingNumeric
End Select
'• From Integer to Byte, SByte, UShort, Short, UInteger, or ULong.
Case [Integer]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [ULong]
Return ConversionKind.NarrowingNumeric
End Select
'• From ULong to Byte, SByte, UShort, Short, UInteger, Integer, or Long.
Case [ULong]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [Long]
Return ConversionKind.NarrowingNumeric
End Select
'• From Long to Byte, SByte, UShort, Short, UInteger, Integer, or ULong.
Case [Long]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong]
Return ConversionKind.NarrowingNumeric
End Select
'• From Decimal to Byte, SByte, UShort, Short, UInteger, Integer, ULong, or Long.
Case [Decimal]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long]
Return ConversionKind.NarrowingNumeric
End Select
'• From Single to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, or Decimal.
Case [Single]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal]
Return ConversionKind.NarrowingNumeric
End Select
'• From Double to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, or Single.
Case [Double]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single]
Return ConversionKind.NarrowingNumeric
End Select
'String conversions
'• From String to Char.
'• From String to Boolean and from Boolean to String.
'• Conversions between String and Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
'• From String to Date and from Date to String.
Case [String]
Select Case CInt([to])
Case [Char],
[Boolean],
[Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double],
[Date]
Return ConversionKind.NarrowingString
End Select
'VB Runtime Conversions
Case [Object]
Select Case CInt([to])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double],
[Char], [Boolean], [Date]
Return ConversionKind.NarrowingValue
Case [String]
Return ConversionKind.NarrowingReference
End Select
End Select
Select Case CInt([to])
'Boolean conversions
'• From Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double to Boolean.
Case [Boolean]
Select Case CInt([from])
Case [Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double]
Return ConversionKind.NarrowingBoolean
End Select
'String conversions
'• From String to Boolean and from Boolean to String.
'• Conversions between String and Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
'• From String to Date and from Date to String.
Case [String]
Select Case CInt([from])
Case [Boolean],
[Byte], [SByte], [UShort], [Short], [UInteger], [Integer], [ULong], [Long], [Decimal], [Single], [Double],
[Date]
Return ConversionKind.NarrowingString
End Select
End Select
Return NoConversion
End Function
<Fact()>
Public Sub EnumConversions()
CompileAndVerify(
<compilation name="VBEnumConversions">
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Globalization
Imports System.Collections.Generic
Module Module1
Sub Main()
Dim BoFalse As Boolean
Dim BoTrue As Boolean
Dim SB As SByte
Dim By As Byte
Dim Sh As Short
Dim US As UShort
Dim [In] As Integer
Dim UI As UInteger
Dim Lo As Long
Dim UL As ULong
Dim De As Decimal
Dim Si As Single
Dim [Do] As Double
Dim St As String
Dim Ob As Object
Dim Tc As TypeCode
Dim TcAsVT As ValueType
BoFalse = False
BoTrue = True
SB = 1
By = 2
Sh = 3
US = 4
[In] = 5
UI = 6
Lo = 7
UL = 8
Si = 10
[Do] = 11
De = 9D
St = "12"
Ob = 13
Tc = TypeCode.Decimal
TcAsVT = Tc
System.Console.WriteLine("Conversions to enum:")
PrintResultTc(BoFalse)
PrintResultTc(BoTrue)
PrintResultTc(SB)
PrintResultTc(By)
PrintResultTc(Sh)
PrintResultTc(US)
PrintResultTc([In])
PrintResultTc(UI)
PrintResultTc(Lo)
PrintResultTc(UL)
PrintResultTc(Si)
PrintResultTc([Do])
PrintResultTc(De)
PrintResultTc(Ob)
PrintResultTc(St)
PrintResultTc(TcAsVT)
System.Console.WriteLine()
System.Console.WriteLine("Conversions from enum:")
PrintResultBo(Tc)
PrintResultSB(Tc)
PrintResultBy(Tc)
PrintResultSh(Tc)
PrintResultUs(Tc)
PrintResultIn(Tc)
PrintResultUI(Tc)
PrintResultLo(Tc)
PrintResultUL(Tc)
PrintResultSi(Tc)
PrintResultDo(Tc)
PrintResultDe(Tc)
PrintResultOb(Tc)
PrintResultSt(Tc)
PrintResultValueType(Tc)
End Sub
Sub PrintResultTc(val As TypeCode)
System.Console.WriteLine("TypeCode: {0}", val)
End Sub
Sub PrintResultBo(val As Boolean)
System.Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResultSB(val As SByte)
System.Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResultBy(val As Byte)
System.Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResultSh(val As Short)
System.Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResultUs(val As UShort)
System.Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResultIn(val As Integer)
System.Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResultUI(val As UInteger)
System.Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResultLo(val As Long)
System.Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResultUL(val As ULong)
System.Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResultDe(val As Decimal)
System.Console.WriteLine("Decimal: {0}", val)
End Sub
Sub PrintResultSi(val As Single)
System.Console.WriteLine("Single: {0}", val)
End Sub
Sub PrintResultDo(val As Double)
System.Console.WriteLine("Double: {0}", val)
End Sub
Sub PrintResultSt(val As String)
System.Console.WriteLine("String: {0}", val)
End Sub
Sub PrintResultOb(val As Object)
System.Console.WriteLine("Object: {0}", val)
End Sub
Sub PrintResultValueType(val As ValueType)
System.Console.WriteLine("ValueType: {0}", val)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Conversions to enum:
TypeCode: Empty
TypeCode: -1
TypeCode: Object
TypeCode: DBNull
TypeCode: Boolean
TypeCode: Char
TypeCode: SByte
TypeCode: Byte
TypeCode: Int16
TypeCode: UInt16
TypeCode: UInt32
TypeCode: Int64
TypeCode: Int32
TypeCode: Single
TypeCode: UInt64
TypeCode: Decimal
Conversions from enum:
Boolean: True
SByte: 15
Byte: 15
Short: 15
UShort: 15
Integer: 15
UInteger: 15
Long: 15
ULong: 15
Single: 15
Double: 15
Decimal: 15
Object: Decimal
String: 15
ValueType: Decimal
]]>)
End Sub
<Fact()>
Public Sub ConversionDiagnostic1()
Dim compilationDef =
<compilation name="VBConversionsDiagnostic1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim [In] As Integer
[In] = Console.WriteLine()
[In] = CType(Console.WriteLine(), Integer)
[In] = CType(1, UnknownType)
[In] = CType(unknownValue, Integer)
[In] = CType(unknownValue, UnknownType)
Dim tr As System.TypedReference = Nothing
Dim ai As System.ArgIterator = Nothing
Dim ra As System.RuntimeArgumentHandle = Nothing
Dim Ob As Object
Ob = tr
Ob = ai
Ob = ra
Ob = CType(tr, Object)
Ob = CType(ai, Object)
Ob = CType(ra, Object)
Dim vt As ValueType
vt = tr
vt = ai
vt = ra
vt = CType(tr, ValueType)
vt = CType(ai, ValueType)
vt = CType(ra, ValueType)
Dim collection As Microsoft.VisualBasic.Collection = Nothing
Dim _collection As _Collection = Nothing
collection = _collection
_collection = collection
collection = CType(_collection, Microsoft.VisualBasic.Collection)
_collection = CType(collection, _Collection)
Dim Si As Single
Dim De As Decimal
[In] = Int64.MaxValue
[In] = CInt(Int64.MaxValue)
Si = System.Double.MaxValue
Si = CSng(System.Double.MaxValue)
De = System.Double.MaxValue
De = CDec(System.Double.MaxValue)
De = 10.0F
De = CDec(10.0F)
Dim Da As DateTime = Nothing
[In] = Da
[In] = CInt(Da)
Da = [In]
Da = CDate([In])
Dim [Do] As Double = Nothing
Dim Ch As Char = Nothing
[Do] = Da
[Do] = CDbl(Da)
Da = [Do]
Da = CDate([Do])
[In] = Ch
[In] = CInt(Ch)
Ch = [In]
Ch = CChar([In])
Dim InArray As Integer() = Nothing
Dim ObArray As Object() = Nothing
Dim VtArray As ValueType() = Nothing
ObArray = InArray
ObArray = CType(InArray, Object())
VtArray = InArray
VtArray = CType(InArray, ValueType())
Dim TC1Array As TestClass1() = Nothing
Dim TC2Array As TestClass2() = Nothing
TC1Array = TC2Array
TC2Array = CType(TC1Array, TestClass2())
Dim InArray2 As Integer(,) = Nothing
InArray = InArray2
InArray2 = CType(InArray, Integer(,))
Dim TI1Array As TestInterface1() = Nothing
InArray = TI1Array
TI1Array = CType(InArray, TestInterface1())
End Sub
End Module
Interface TestInterface1
End Interface
Interface _Collection
End Interface
Class TestClass1
End Class
Class TestClass2
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.ERR_NarrowingConversionCollection2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_NarrowingConversionCollection2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "10.0F").WithArguments("Single", "Decimal"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"))
compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"))
compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "_collection").WithArguments("Implicit conversion from '_Collection' to 'Collection'."),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "collection").WithArguments("Implicit conversion from 'Collection' to '_Collection'."),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"),
Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "10.0F").WithArguments("Implicit conversion from 'Single' to 'Decimal'."),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"))
End Sub
<Fact()>
Public Sub DirectCastDiagnostic1()
Dim compilationDef =
<compilation name="DirectCastDiagnostic1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim [In] As Integer
[In] = DirectCast(Console.WriteLine(), Integer)
[In] = DirectCast(1, UnknownType)
[In] = DirectCast(unknownValue, Integer)
[In] = DirectCast(unknownValue, UnknownType)
Dim tr As System.TypedReference = Nothing
Dim ai As System.ArgIterator = Nothing
Dim ra As System.RuntimeArgumentHandle = Nothing
Dim Ob As Object
Ob = DirectCast(tr, Object)
Ob = DirectCast(ai, Object)
Ob = DirectCast(ra, Object)
Dim vt As ValueType
vt = DirectCast(tr, ValueType)
vt = DirectCast(ai, ValueType)
vt = DirectCast(ra, ValueType)
Dim collection As Microsoft.VisualBasic.Collection = Nothing
Dim _collection As _Collection = Nothing
collection = DirectCast(_collection, Microsoft.VisualBasic.Collection)
_collection = DirectCast(collection, _Collection)
Dim Si As Single
Dim De As Decimal
[In] = DirectCast(Int64.MaxValue, Int32)
De = DirectCast(System.Double.MaxValue, System.Decimal)
Dim Da As DateTime = Nothing
[In] = DirectCast(Da, Int32)
Da = DirectCast([In], DateTime)
Dim [Do] As Double = Nothing
Dim Ch As Char = Nothing
[Do] = DirectCast(Da, System.Double)
Da = DirectCast([Do], DateTime)
[In] = DirectCast(Ch, Int32)
Ch = DirectCast([In], System.Char)
Dim InArray As Integer() = Nothing
Dim ObArray As Object() = Nothing
Dim VtArray As ValueType() = Nothing
ObArray = DirectCast(InArray, Object())
VtArray = DirectCast(InArray, ValueType())
Dim TC1Array As TestClass1() = Nothing
Dim TC2Array As TestClass2() = Nothing
TC2Array = DirectCast(TC1Array, TestClass2())
Dim InArray2 As Integer(,) = Nothing
InArray2 = DirectCast(InArray, Integer(,))
Dim TI1Array As TestInterface1() = Nothing
TI1Array = DirectCast(InArray, TestInterface1())
Dim St As String = Nothing
Dim ChArray As Char() = Nothing
Ch = DirectCast(St, System.Char)
St = DirectCast(Ch, System.String)
St = DirectCast(ChArray, System.String)
ChArray = DirectCast(St, System.Char())
[In] = DirectCast([In], System.Int32)
Si = DirectCast(Si, System.Single)
[Do] = DirectCast([Do], System.Double)
[Do] = DirectCast(Si, System.Double)
End Sub
End Module
Interface TestInterface1
End Interface
Interface _Collection
End Interface
Class TestClass1
End Class
Class TestClass2
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Int64.MaxValue").WithArguments("Long", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "System.Double.MaxValue").WithArguments("Double", "Decimal"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "[In]"),
Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "Si"),
Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "[Do]"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Si").WithArguments("Single", "Double"))
compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Int64.MaxValue").WithArguments("Long", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "System.Double.MaxValue").WithArguments("Double", "Decimal"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"),
Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"),
Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"),
Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"),
Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"),
Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"),
Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "[In]"),
Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "Si"),
Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "[Do]"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Si").WithArguments("Single", "Double"))
End Sub
<Fact()>
Public Sub TryCastDiagnostic1()
Dim compilationDef =
<compilation name="TryCastDiagnostic1">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim [In] As Integer
[In] = TryCast(Console.WriteLine(), Integer)
[In] = TryCast(1, UnknownType)
[In] = TryCast(unknownValue, Integer)
[In] = TryCast(unknownValue, UnknownType)
Dim tr As System.TypedReference = Nothing
Dim ai As System.ArgIterator = Nothing
Dim ra As System.RuntimeArgumentHandle = Nothing
Dim Ob As Object
Ob = TryCast(tr, Object)
Ob = TryCast(ai, Object)
Ob = TryCast(ra, Object)
Dim vt As ValueType
vt = TryCast(tr, ValueType)
vt = TryCast(ai, ValueType)
vt = TryCast(ra, ValueType)
Dim collection As Microsoft.VisualBasic.Collection = Nothing
Dim _collection As _Collection = Nothing
collection = TryCast(_collection, Microsoft.VisualBasic.Collection)
_collection = TryCast(collection, _Collection)
Dim De As Decimal
[In] = TryCast(Int64.MaxValue, Int32)
De = TryCast(System.Double.MaxValue, System.Decimal)
Dim Ch As Char = Nothing
Dim InArray As Integer() = Nothing
Dim ObArray As Object() = Nothing
Dim VtArray As ValueType() = Nothing
ObArray = TryCast(InArray, Object())
VtArray = TryCast(InArray, ValueType())
Dim TC1Array As TestClass1() = Nothing
Dim TC2Array As TestClass2() = Nothing
TC2Array = TryCast(TC1Array, TestClass2())
Dim InArray2 As Integer(,) = Nothing
InArray2 = TryCast(InArray, Integer(,))
Dim TI1Array As TestInterface1() = Nothing
TI1Array = TryCast(InArray, TestInterface1())
Dim St As String = Nothing
Dim ChArray As Char() = Nothing
Ch = TryCast(St, System.Char)
St = TryCast(Ch, System.String)
St = TryCast(ChArray, System.String)
ChArray = TryCast(St, System.Char())
End Sub
End Module
Interface TestInterface1
End Interface
Interface _Collection
End Interface
Class TestClass1
End Class
Class TestClass2
End Class
Class TestClass3(Of T)
Sub Test(val As Object)
Dim x As T = TryCast(val, T)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "Int32").WithArguments("Integer"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Decimal").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Char").WithArguments("Char"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"),
Diagnostic(ERRID.ERR_TryCastOfUnconstrainedTypeParam1, "T").WithArguments("T"))
compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off))
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"),
Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"),
Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"),
Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "Int32").WithArguments("Integer"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Decimal").WithArguments("Decimal"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"),
Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"),
Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"),
Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"),
Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Char").WithArguments("Char"),
Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"),
Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"),
Diagnostic(ERRID.ERR_TryCastOfUnconstrainedTypeParam1, "T").WithArguments("T"))
End Sub
<Fact()>
Public Sub ExplicitConversions1()
' the argument past to CDate("") is following system setting,
' so "1/2/2012" could be Jan 2nd OR Feb 1st
Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
Try
Dim compilationDef =
<compilation name="VBExplicitConversions1">
<file name="lib.vb">
<%= My.Resources.Resource.PrintResultTestSource %>
</file>
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
PrintResult(CObj(Nothing))
PrintResult(CBool(Nothing))
PrintResult(CByte(Nothing))
'PrintResult(CChar(Nothing))
PrintResult(CDate(Nothing))
PrintResult(CDec(Nothing))
PrintResult(CDbl(Nothing))
PrintResult(CInt(Nothing))
PrintResult(CLng(Nothing))
PrintResult(CSByte(Nothing))
PrintResult(CShort(Nothing))
PrintResult(CSng(Nothing))
PrintResult(CStr(Nothing))
PrintResult(CUInt(Nothing))
PrintResult(CULng(Nothing))
PrintResult(CUShort(Nothing))
PrintResult(CType(Nothing, System.Object))
PrintResult(CType(Nothing, System.Boolean))
PrintResult(CType(Nothing, System.Byte))
'PrintResult(CType(Nothing, System.Char))
PrintResult(CType(Nothing, System.DateTime))
PrintResult(CType(Nothing, System.Decimal))
PrintResult(CType(Nothing, System.Double))
PrintResult(CType(Nothing, System.Int32))
PrintResult(CType(Nothing, System.Int64))
PrintResult(CType(Nothing, System.SByte))
PrintResult(CType(Nothing, System.Int16))
PrintResult(CType(Nothing, System.Single))
PrintResult(CType(Nothing, System.String))
PrintResult(CType(Nothing, System.UInt32))
PrintResult(CType(Nothing, System.UInt64))
PrintResult(CType(Nothing, System.UInt16))
PrintResult(CType(Nothing, System.Guid))
PrintResult(CType(Nothing, System.ValueType))
PrintResult(CByte(300))
PrintResult(CObj("String"))
PrintResult(CBool("False"))
PrintResult(CByte("1"))
PrintResult(CChar("a"))
PrintResult(CDate("11/12/2001 12:00:00 AM"))
PrintResult(CDec("-2"))
PrintResult(CDbl("3"))
PrintResult(CInt("-4"))
PrintResult(CLng("5"))
PrintResult(CSByte("-6"))
PrintResult(CShort("7"))
PrintResult(CSng("-8"))
PrintResult(CStr(9))
PrintResult(CUInt("10"))
PrintResult(CULng("11"))
PrintResult(CUShort("12"))
End Sub
Function Int32ToInt32(val As System.Int32) As Int32
Return CInt(val)
End Function
Function SingleToSingle(val As System.Single) As Single
Return CSng(val)
End Function
Function DoubleToDouble(val As System.Double) As Double
Return CDbl(val)
End Function
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
options:=TestOptions.ReleaseExe.WithOverflowChecks(False),
expectedOutput:=<![CDATA[
Object: []
Boolean: False
Byte: 0
Date: 1/1/0001 12:00:00 AM
Decimal: 0
Double: 0
Integer: 0
Long: 0
SByte: 0
Short: 0
Single: 0
String: []
UInteger: 0
ULong: 0
UShort: 0
Object: []
Boolean: False
Byte: 0
Date: 1/1/0001 12:00:00 AM
Decimal: 0
Double: 0
Integer: 0
Long: 0
SByte: 0
Short: 0
Single: 0
String: []
UInteger: 0
ULong: 0
UShort: 0
Guid: 00000000-0000-0000-0000-000000000000
ValueType: []
Byte: 44
Object: [String]
Boolean: False
Byte: 1
Char: [a]
Date: 11/12/2001 12:00:00 AM
Decimal: -2
Double: 3
Integer: -4
Long: 5
SByte: -6
Short: 7
Single: -8
String: [9]
UInteger: 10
ULong: 11
UShort: 12
]]>).
VerifyIL("Module1.Int32ToInt32",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.SingleToSingle",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.DoubleToDouble",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>)
Catch ex As Exception
Finally
System.Threading.Thread.CurrentThread.CurrentCulture = currCulture
End Try
End Sub
<Fact()>
Public Sub DirectCast1()
Dim compilationDef =
<compilation name="DirectCast1">
<file name="helper.vb"><%= My.Resources.Resource.PrintResultTestSource %></file>
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Globalization
Imports System.Collections.Generic
Module Module1
Sub Main()
PrintResult(DirectCast(Nothing, System.Object))
PrintResult(DirectCast(Nothing, System.Boolean))
PrintResult(DirectCast(Nothing, System.Byte))
PrintResult(DirectCast(Nothing, System.DateTime))
PrintResult(DirectCast(Nothing, System.Decimal))
PrintResult(DirectCast(Nothing, System.Double))
PrintResult(DirectCast(Nothing, System.Int32))
PrintResult(DirectCast(Nothing, System.Int64))
PrintResult(DirectCast(Nothing, System.SByte))
PrintResult(DirectCast(Nothing, System.Int16))
PrintResult(DirectCast(Nothing, System.Single))
PrintResult(DirectCast(Nothing, System.String))
PrintResult(DirectCast(Nothing, System.UInt32))
PrintResult(DirectCast(Nothing, System.UInt64))
PrintResult(DirectCast(Nothing, System.UInt16))
PrintResult(DirectCast(Nothing, System.ValueType))
PrintResult(DirectCast(1, System.Object))
PrintResult(DirectCast(3.5R, System.ValueType))
Dim guid As Guid = New Guid("8c5dffd5-1778-4dd3-a9f5-6a9708146a7c")
Dim guidObject As Object = guid
PrintResult(DirectCast(guid, System.Object))
PrintResult(DirectCast(guidObject, System.Guid))
PrintResult(DirectCast("abc", System.IComparable))
PrintResult(GenericParamTestHelperOfString.NothingToT())
'PrintResult(DirectCast(Nothing, System.Guid))
PrintResult(GenericParamTestHelperOfGuid.NothingToT())
PrintResult(GenericParamTestHelperOfString.TToObject("abcd"))
PrintResult(GenericParamTestHelperOfString.TToObject(Nothing))
PrintResult(GenericParamTestHelperOfGuid.TToObject(guid))
PrintResult(GenericParamTestHelperOfString.TToIComparable("abcde"))
PrintResult(GenericParamTestHelperOfString.TToIComparable(Nothing))
PrintResult(GenericParamTestHelperOfGuid.TToIComparable(guid))
PrintResult(GenericParamTestHelperOfGuid.ObjectToT(guidObject))
'PrintResult(GenericParamTestHelperOfGuid.ObjectToT(Nothing))
PrintResult(GenericParamTestHelperOfString.ObjectToT("ObString"))
PrintResult(GenericParamTestHelperOfString.ObjectToT(Nothing))
'PrintResult(GenericParamTestHelper(Of System.Int32).ObjectToT(Nothing))
PrintResult(GenericParamTestHelperOfString.IComparableToT("abcde"))
PrintResult(GenericParamTestHelperOfString.IComparableToT(Nothing))
PrintResult(GenericParamTestHelperOfGuid.IComparableToT(guid))
'PrintResult(GenericParamTestHelperOfGuid.IComparableToT(Nothing))
'PrintResult(GenericParamTestHelper(Of System.Double).IComparableToT(Nothing))
Dim [In] As Integer = 23
Dim De As Decimal = 24
PrintResult(DirectCast([In], System.Int32))
PrintResult(DirectCast(De, System.Decimal))
End Sub
Function NothingToGuid() As Guid
Return DirectCast(Nothing, System.Guid)
End Function
Function NothingToInt32() As Int32
Return DirectCast(Nothing, System.Int32)
End Function
Function Int32ToInt32(val As System.Int32) As Int32
Return DirectCast(val, System.Int32)
End Function
Class GenericParamTestHelper(Of T)
Public Shared Function ObjectToT(val As Object) As T
Return DirectCast(val, T)
End Function
Public Shared Function TToObject(val As T) As Object
Return DirectCast(val, Object)
End Function
Public Shared Function TToIComparable(val As T) As IComparable
Return DirectCast(val, IComparable)
End Function
Public Shared Function IComparableToT(val As IComparable) As T
Return DirectCast(val, T)
End Function
Public Shared Function NothingToT() As T
Return DirectCast(Nothing, T)
End Function
End Class
Class GenericParamTestHelperOfString
Inherits GenericParamTestHelper(Of String)
End Class
Class GenericParamTestHelperOfGuid
Inherits GenericParamTestHelper(Of Guid)
End Class
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
Object: []
Boolean: False
Byte: 0
Date: 1/1/0001 12:00:00 AM
Decimal: 0
Double: 0
Integer: 0
Long: 0
SByte: 0
Short: 0
Single: 0
String: []
UInteger: 0
ULong: 0
UShort: 0
ValueType: []
Object: [1]
ValueType: [3.5]
Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c
IComparable: [abc]
String: []
Guid: 00000000-0000-0000-0000-000000000000
Object: [abcd]
Object: []
Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
IComparable: [abcde]
IComparable: []
IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c
String: [ObString]
String: []
String: [abcde]
String: []
Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c
Integer: 23
Decimal: 24
]]>).
VerifyIL("Module1.NothingToGuid",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldnull
IL_0001: unbox.any "System.Guid"
IL_0006: ret
}
]]>).
VerifyIL("Module1.NothingToInt32",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.Int32ToInt32",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).ObjectToT",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any "T"
IL_0006: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).TToObject",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).TToIComparable",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: castclass "System.IComparable"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).IComparableToT",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: unbox.any "T"
IL_0006: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper(Of T).NothingToT",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (T V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "T"
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
Public Sub TryCast1()
Dim compilationDef =
<compilation name="TryCast1">
<file name="helper.vb"><%= My.Resources.Resource.PrintResultTestSource %></file>
<file name="a.vb">
Option Strict Off
Imports System
Imports System.Globalization
Imports System.Collections.Generic
Module Module1
Sub Main()
PrintResult(TryCast(Nothing, System.Object))
PrintResult(TryCast(Nothing, System.String))
PrintResult(TryCast(Nothing, System.ValueType))
PrintResult(TryCast(1, System.Object))
PrintResult(TryCast(3.5R, System.ValueType))
PrintResult(TryCast(CObj("sdf"), System.String))
PrintResult(TryCast(New Object(), System.String))
Dim guid As Guid = New Guid("8c5dffd5-1778-4dd3-a9f5-6a9708146a7c")
Dim guidObject As Object = guid
PrintResult(TryCast(guid, System.Object))
PrintResult(TryCast("abc", System.IComparable))
PrintResult(TryCast(guid, System.IComparable))
PrintResult(GenericParamTestHelperOfString2.NothingToT())
PrintResult(GenericParamTestHelperOfString1.TToObject("abcd"))
PrintResult(GenericParamTestHelperOfString1.TToObject(Nothing))
PrintResult(GenericParamTestHelperOfGuid1.TToObject(guid))
PrintResult(GenericParamTestHelperOfString1.TToIComparable("abcde"))
PrintResult(GenericParamTestHelperOfString1.TToIComparable(Nothing))
PrintResult(GenericParamTestHelperOfGuid1.TToIComparable(guid))
PrintResult(GenericParamTestHelperOfString2.ObjectToT("ObString"))
PrintResult(GenericParamTestHelperOfString2.ObjectToT(Nothing))
PrintResult(GenericParamTestHelperOfString2.IComparableToT("abcde"))
PrintResult(GenericParamTestHelperOfString2.IComparableToT(Nothing))
End Sub
Function NothingToString() As String
Return DirectCast(Nothing, System.String)
End Function
Function StringToString(val As String) As String
Return DirectCast(val, System.String)
End Function
Class GenericParamTestHelper1(Of T)
Public Shared Function TToObject(val As T) As Object
Return TryCast(val, Object)
End Function
Public Shared Function TToIComparable(val As T) As IComparable
Return TryCast(val, IComparable)
End Function
End Class
Class GenericParamTestHelper2(Of T As Class)
Public Shared Function ObjectToT(val As Object) As T
Return TryCast(val, T)
End Function
Public Shared Function IComparableToT(val As IComparable) As T
Return TryCast(val, T)
End Function
Public Shared Function NothingToT() As T
Return TryCast(Nothing, T)
End Function
End Class
Class GenericParamTestHelperOfString1
Inherits GenericParamTestHelper1(Of String)
End Class
Class GenericParamTestHelperOfString2
Inherits GenericParamTestHelper2(Of String)
End Class
Class GenericParamTestHelperOfGuid1
Inherits GenericParamTestHelper1(Of Guid)
End Class
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
Object: []
String: []
ValueType: []
Object: [1]
ValueType: [3.5]
String: [sdf]
String: []
Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
IComparable: [abc]
IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
String: []
Object: [abcd]
Object: []
Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
IComparable: [abcde]
IComparable: []
IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c]
String: [ObString]
String: []
String: [abcde]
String: []
]]>).
VerifyIL("Module1.NothingToString",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}
]]>).
VerifyIL("Module1.StringToString",
<![CDATA[
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper2(Of T).ObjectToT",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst "T"
IL_0006: unbox.any "T"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper1(Of T).TToObject",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: isinst "Object"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper1(Of T).TToIComparable",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box "T"
IL_0006: isinst "System.IComparable"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper2(Of T).IComparableToT",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst "T"
IL_0006: unbox.any "T"
IL_000b: ret
}
]]>).
VerifyIL("Module1.GenericParamTestHelper2(Of T).NothingToT",
<![CDATA[
{
// Code size 10 (0xa)
.maxstack 1
.locals init (T V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "T"
IL_0008: ldloc.0
IL_0009: ret
}
]]>)
End Sub
<Fact()>
Public Sub Bug4281_1()
Dim compilationDef =
<compilation name="Bug4281_1">
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim x As Object= DirectCast(1, DayOfWeek)
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(x)
Dim y As Integer = 2
x = DirectCast(y, DayOfWeek)
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
System.DayOfWeek
Monday
System.DayOfWeek
Tuesday
]]>).
VerifyIL("M.Main",
<![CDATA[
{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: box "System.DayOfWeek"
IL_0006: dup
IL_0007: callvirt "Function Object.GetType() As System.Type"
IL_000c: call "Sub System.Console.WriteLine(Object)"
IL_0011: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0016: call "Sub System.Console.WriteLine(Object)"
IL_001b: ldc.i4.2
IL_001c: box "System.DayOfWeek"
IL_0021: dup
IL_0022: callvirt "Function Object.GetType() As System.Type"
IL_0027: call "Sub System.Console.WriteLine(Object)"
IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0031: call "Sub System.Console.WriteLine(Object)"
IL_0036: ret
}
]]>)
End Sub
<Fact()>
Public Sub Bug4281_2()
Dim compilationDef =
<compilation name="Bug4281_2">
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim x As DayOfWeek= DirectCast(1, DayOfWeek)
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(x)
Dim y As Integer = 2
x = DirectCast(y, DayOfWeek)
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
System.DayOfWeek
1
System.DayOfWeek
2
]]>)
End Sub
<Fact()>
Public Sub Bug4256()
Dim compilationDef =
<compilation name="Bug4256">
<file name="a.vb">
Option Strict On
Module M
Sub Main()
Dim x As Object = 1
Dim y As Long = CLng(x)
System.Console.WriteLine(y.GetType())
System.Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>
CompileAndVerify(compilationDef,
expectedOutput:=<![CDATA[
System.Int64
1
]]>)
End Sub
<WorkItem(11515, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub TestIdentityConversionForGenericNested()
Dim vbCompilation = CreateVisualBasicCompilation("TestIdentityConversionForGenericNested",
<![CDATA[Option Strict On
Imports System
Public Module Program
Class C1(Of T)
Public EnumField As E1
Structure S1
Public EnumField As E1
End Structure
Enum E1
A
End Enum
End Class
Sub Main()
Dim outer As New C1(Of Integer)
Dim inner As New C1(Of Integer).S1
outer.EnumField = C1(Of Integer).E1.A
inner.EnumField = C1(Of Integer).E1.A
Foo(inner.EnumField)
End Sub
Sub Foo(x As Object)
Console.WriteLine(x.ToString)
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication))
CompileAndVerify(vbCompilation, expectedOutput:="A").VerifyDiagnostics()
End Sub
<WorkItem(544919, "DevDiv")>
<Fact>
Public Sub TestClassifyConversion()
Dim source =
<text>
Imports System
Module Program
Sub M()
End Sub
Sub M(l As Long)
End Sub
Sub M(s As Short)
End Sub
Sub M(i As Integer)
End Sub
Sub Main()
Dim ii As Integer = 0
Console.WriteLine(ii)
Dim jj As Short = 1
Console.WriteLine(jj)
Dim ss As String = String.Empty
Console.WriteLine(ss)
' Perform conversion classification here.
End Sub
End Module
</text>.Value
Dim tree = Parse(source)
Dim c As VisualBasicCompilation = VisualBasicCompilation.Create("MyCompilation").AddReferences(MscorlibRef).AddSyntaxTrees(tree)
Dim model = c.GetSemanticModel(tree)
' Get VariableDeclaratorSyntax corresponding to variable 'ii' above.
Dim variableDeclarator = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ii", StringComparison.Ordinal)).Parent.Parent, VariableDeclaratorSyntax)
' Get TypeSymbol corresponding to above VariableDeclaratorSyntax.
Dim targetType As TypeSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol).Type
Dim local As LocalSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol)
Assert.Equal(1, local.Locations.Length)
' Perform ClassifyConversion for expressions from within the above SyntaxTree.
Dim sourceExpression1 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("jj)", StringComparison.Ordinal)).Parent, ExpressionSyntax)
Dim conversion As Conversion = model.ClassifyConversion(sourceExpression1, targetType)
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
Dim sourceExpression2 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ss)", StringComparison.Ordinal)).Parent, ExpressionSyntax)
conversion = model.ClassifyConversion(sourceExpression2, targetType)
Assert.True(conversion.IsNarrowing)
Assert.True(conversion.IsString)
' Perform ClassifyConversion for constructed expressions
' at the position identified by the comment "' Perform ..." above.
Dim sourceExpression3 As ExpressionSyntax = SyntaxFactory.IdentifierName("jj")
Dim position = source.IndexOf("' ", StringComparison.Ordinal)
conversion = model.ClassifyConversion(position, sourceExpression3, targetType)
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
Dim sourceExpression4 As ExpressionSyntax = SyntaxFactory.IdentifierName("ss")
conversion = model.ClassifyConversion(position, sourceExpression4, targetType)
Assert.True(conversion.IsNarrowing)
Assert.True(conversion.IsString)
Dim sourceExpression5 As ExpressionSyntax = SyntaxFactory.ParseExpression("100L")
conversion = model.ClassifyConversion(position, sourceExpression5, targetType)
' This is Widening because the numeric literal constant 100L can be converted to Integer
' without any data loss. Note: This is special for literal constants.
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<WorkItem(544919, "DevDiv")>
<Fact>
Public Sub TestClassifyConversionStaticLocal()
Dim source =
<text>
Imports System
Module Program
Sub M()
End Sub
Sub M(l As Long)
End Sub
Sub M(s As Short)
End Sub
Sub M(i As Integer)
End Sub
Sub Main()
Static ii As Integer = 0
Console.WriteLine(ii)
Static jj As Short = 1
Console.WriteLine(jj)
Static ss As String = String.Empty
Console.WriteLine(ss)
' Perform conversion classification here.
End Sub
End Module
</text>.Value
Dim tree = Parse(source)
Dim c As VisualBasicCompilation = VisualBasicCompilation.Create("MyCompilation").AddReferences(MscorlibRef).AddSyntaxTrees(tree)
Dim model = c.GetSemanticModel(tree)
' Get VariableDeclaratorSyntax corresponding to variable 'ii' above.
Dim variableDeclarator = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ii", StringComparison.Ordinal)).Parent.Parent, VariableDeclaratorSyntax)
' Get TypeSymbol corresponding to above VariableDeclaratorSyntax.
Dim targetType As TypeSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol).Type
Dim local As LocalSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol)
Assert.Equal(1, local.Locations.Length)
' Perform ClassifyConversion for expressions from within the above SyntaxTree.
Dim sourceExpression1 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("jj)", StringComparison.Ordinal)).Parent, ExpressionSyntax)
Dim conversion As Conversion = model.ClassifyConversion(sourceExpression1, targetType)
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
Dim sourceExpression2 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ss)", StringComparison.Ordinal)).Parent, ExpressionSyntax)
conversion = model.ClassifyConversion(sourceExpression2, targetType)
Assert.True(conversion.IsNarrowing)
Assert.True(conversion.IsString)
' Perform ClassifyConversion for constructed expressions
' at the position identified by the comment "' Perform ..." above.
Dim sourceExpression3 As ExpressionSyntax = SyntaxFactory.IdentifierName("jj")
Dim position = source.IndexOf("' ", StringComparison.Ordinal)
conversion = model.ClassifyConversion(position, sourceExpression3, targetType)
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
Dim sourceExpression4 As ExpressionSyntax = SyntaxFactory.IdentifierName("ss")
conversion = model.ClassifyConversion(position, sourceExpression4, targetType)
Assert.True(conversion.IsNarrowing)
Assert.True(conversion.IsString)
Dim sourceExpression5 As ExpressionSyntax = SyntaxFactory.ParseExpression("100L")
conversion = model.ClassifyConversion(position, sourceExpression5, targetType)
' This is Widening because the numeric literal constant 100L can be converted to Integer
' without any data loss. Note: This is special for literal constants.
Assert.True(conversion.IsWidening)
Assert.True(conversion.IsNumeric)
End Sub
<WorkItem(544620, "DevDiv")>
<Fact()>
Public Sub Bug13088()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Public Const Z1 As Integer = 300
Public Const Z2 As Byte = Z1
Public Const Z3 As Byte = CByte(300)
Public Const Z4 As Byte = DirectCast(300, Byte)
Sub Main()
End Sub
End Module
]]></file>
</compilation>)
VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "Z1").WithArguments("Byte"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "300").WithArguments("Byte"),
Diagnostic(ERRID.ERR_TypeMismatch2, "300").WithArguments("Integer", "Byte"))
Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z2").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z3").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z4").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
End Sub
<WorkItem(545760, "DevDiv")>
<Fact()>
Public Sub Bug14409()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module M1
Sub Main()
Dim x As System.DayOfWeek? = 0
Test(0)
End Sub
Sub Test(x As System.DayOfWeek?)
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation)
End Sub
<WorkItem(545760, "DevDiv")>
<Fact()>
Public Sub Bug14409_2()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module M1
Sub Main()
Test(0)
End Sub
Sub Test(x As System.DayOfWeek?)
End Sub
Sub Test(x As System.TypeCode?)
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30519: Overload resolution failed because no accessible 'Test' can be called without a narrowing conversion:
'Public Sub Test(x As DayOfWeek?)': Argument matching parameter 'x' narrows from 'Integer' to 'DayOfWeek?'.
'Public Sub Test(x As TypeCode?)': Argument matching parameter 'x' narrows from 'Integer' to 'TypeCode?'.
Test(0)
~~~~
</expected>)
End Sub
<WorkItem(571095, "DevDiv")>
<Fact()>
Public Sub Bug571095()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
imports System
Module Module1
Sub Main()
Dim Y(10, 10) As Integer
'COMPILEERROR: BC30311, "Y"
For Each x As string() In Y
Console.WriteLine(x)
Next x
'COMPILEERROR: BC30311, "Y"
For Each x As Integer(,) In Y
Console.WriteLine(x)
Next x
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30311: Value of type 'Integer' cannot be converted to 'String()'.
For Each x As string() In Y
~
BC30311: Value of type 'Integer' cannot be converted to 'Integer(*,*)'.
For Each x As Integer(,) In Y
~
</expected>)
End Sub
<WorkItem(31)>
<Fact()>
Public Sub BugCodePlex_31()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module Module1
Property Value As BooleanEx?
Sub Main()
If Value Then
End If
System.Console.WriteLine("---")
Value = true
System.Console.WriteLine("---")
Dim x as Boolean? = Value
System.Console.WriteLine("---")
If Value Then
End If
End Sub
End Module
Structure BooleanEx
Private b As Boolean
Public Sub New(value As Boolean)
b = value
End Sub
Public Shared Widening Operator CType(value As Boolean) As BooleanEx
System.Console.WriteLine("CType(value As Boolean) As BooleanEx")
Return New BooleanEx(value)
End Operator
Public Shared Widening Operator CType(value As BooleanEx) As Boolean
System.Console.WriteLine("CType(value As BooleanEx) As Boolean")
Return value.b
End Operator
Public Shared Widening Operator CType(value As Integer) As BooleanEx
System.Console.WriteLine("CType(value As Integer) As BooleanEx")
Return New BooleanEx(CBool(value))
End Operator
Public Shared Widening Operator CType(value As BooleanEx) As Integer
System.Console.WriteLine("CType(value As BooleanEx) As Integer")
Return CInt(value.b)
End Operator
Public Shared Widening Operator CType(value As String) As BooleanEx
System.Console.WriteLine("CType(value As String) As BooleanEx")
Return New BooleanEx(CBool(value))
End Operator
Public Shared Widening Operator CType(value As BooleanEx) As String
System.Console.WriteLine("CType(value As BooleanEx) As String")
Return CStr(value.b)
End Operator
Public Shared Operator =(value1 As BooleanEx, value2 As Boolean) As Boolean
System.Console.WriteLine("=(value1 As BooleanEx, value2 As Boolean) As Boolean")
Return False
End Operator
Public Shared Operator <>(value1 As BooleanEx, value2 As Boolean) As Boolean
System.Console.WriteLine("<>(value1 As BooleanEx, value2 As Boolean) As Boolean")
Return False
End Operator
End Structure
]]></file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=
"---
CType(value As Boolean) As BooleanEx
---
CType(value As BooleanEx) As Boolean
---
CType(value As BooleanEx) As Boolean")
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_01()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Integer = Double.MaxValue
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErr = <expected>
BC30439: Constant expression not representable in type 'Integer'.
Dim x As Integer = Double.MaxValue
~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedErr)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedErr)
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_02()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Integer? = Double.MaxValue
End Sub
End Module
]]></file>
</compilation>)
Dim expectedError = <expected>
BC30439: Constant expression not representable in type 'Integer?'.
Dim x As Integer? = Double.MaxValue
~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_03()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Short = Integer.MaxValue
System.Console.WriteLine(x)
End Sub
End Module
]]></file>
</compilation>)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
Dim expectedError = <expected>
BC30439: Constant expression not representable in type 'Short'.
Dim x As Short = Integer.MaxValue
~~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_04()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Short? = Integer.MaxValue
System.Console.WriteLine(x)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedIL = <![CDATA[
{
// Code size 22 (0x16)
.maxstack 2
.locals init (Short? V_0) //x
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.m1
IL_0004: call "Sub Short?..ctor(Short)"
IL_0009: ldloc.0
IL_000a: box "Short?"
IL_000f: call "Sub System.Console.WriteLine(Object)"
IL_0014: nop
IL_0015: ret
}
]]>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
Dim verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
verifier.VerifyIL("Program.Main", expectedIL)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
verifier.VerifyIL("Program.Main", expectedIL)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics()
verifier.VerifyIL("Program.Main", expectedIL)
Dim expectedError = <expected>
BC30439: Constant expression not representable in type 'Short?'.
Dim x As Short? = Integer.MaxValue
~~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
AssertTheseDiagnostics(compilation, expectedError)
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_05()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Short = CInt(Short.MaxValue)
System.Console.WriteLine(x)
End Sub
End Module
]]></file>
</compilation>)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_06()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x As Short? = CInt(Short.MaxValue)
System.Console.WriteLine(x)
End Sub
End Module
]]></file>
</compilation>)
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True))
CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics()
End Sub
<WorkItem(1099862, "DevDiv")>
<Fact()>
Public Sub Bug1099862_07()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub Main(args As String())
Dim x = CType(Double.MaxValue, System.Nullable(Of Integer))
End Sub
End Module
]]></file>
</compilation>)
Dim expectedError = <expected>
BC30439: Constant expression not representable in type 'Integer?'.
Dim x = CType(Double.MaxValue, System.Nullable(Of Integer))
~~~~~~~~~~~~~~~
</expected>
compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False))
AssertTheseDiagnostics(compilation, expectedError)
End Sub
End Class
End Namespace
| ManishJayaswal/roslyn | src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb | Visual Basic | apache-2.0 | 285,552 |
function Controller() {
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
$model = arguments[0] ? arguments[0].$model : null;
var $ = this, exports = {};
Alloy.Models.instance("user");
_.extend($, $.__views);
var user = Alloy.Models.user;
user.set("id", "instance");
user.fetch();
Alloy.createController(user.authenticatedStatus() ? "home" : "login").getView().open();
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._, A$ = Alloy.A, $model;
module.exports = Controller; | antoniokaplan/Alloy-Widgets | Resources/alloy/controllers/index.js | JavaScript | apache-2.0 | 601 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_13) on Thu May 08 00:26:51 PDT 2014 -->
<title>T-Index</title>
<meta name="date" content="2014-05-08">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="T-Index";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../edu/uci/ics/ics163/gpsdrawupload/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-9.html">Prev Letter</a></li>
<li><a href="index-11.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-10.html" target="_top">Frames</a></li>
<li><a href="index-10.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">C</a> <a href="index-3.html">E</a> <a href="index-4.html">G</a> <a href="index-5.html">H</a> <a href="index-6.html">O</a> <a href="index-7.html">P</a> <a href="index-8.html">R</a> <a href="index-9.html">S</a> <a href="index-10.html">T</a> <a href="index-11.html">U</a> <a name="_T_">
<!-- -->
</a>
<h2 class="title">T</h2>
<dl>
<dt><span class="strong"><a href="../edu/uci/ics/ics163/gpsdrawupload/Point.html#toString()">toString()</a></span> - Method in class edu.uci.ics.ics163.gpsdrawupload.<a href="../edu/uci/ics/ics163/gpsdrawupload/Point.html" title="class in edu.uci.ics.ics163.gpsdrawupload">Point</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">C</a> <a href="index-3.html">E</a> <a href="index-4.html">G</a> <a href="index-5.html">H</a> <a href="index-6.html">O</a> <a href="index-7.html">P</a> <a href="index-8.html">R</a> <a href="index-9.html">S</a> <a href="index-10.html">T</a> <a href="index-11.html">U</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../edu/uci/ics/ics163/gpsdrawupload/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-9.html">Prev Letter</a></li>
<li><a href="index-11.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-filesindex-10.html" target="_top">Frames</a></li>
<li><a href="index-10.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| orsonteodoro/gpsdraw | gpsdrawupload/doc/index-files/index-10.html | HTML | apache-2.0 | 4,531 |
#ifndef _STRUCT_H_
#define _STRUCT_H_
#include <stdlib.h>
#include <cJSON.h>
#include "str.h"
typedef struct
{
str_t data;
size_t capacity;
} curl_data_t;
#define empty_curl_data {empty_str, 0}
extern void curl_data_free(curl_data_t* data);
typedef struct pair_array_s curl_header_t;
#define empty_curl_header empty_pair_array
typedef struct pair_array_s pair_array_t;
struct pair_array_s
{
str_t* keys;
str_t* vals;
size_t count;
};
extern pair_array_t static_empty_pair_array;
#define empty_pair_array {NULL, NULL, 0}
extern void pair_array_free(pair_array_t* array);
extern void pair_array_append_pointers(pair_array_t* array, const char* key, const char* val);
extern void pair_array_append_empty_value(pair_array_t* array, const char* key);
extern str_t pair_array_lookup(pair_array_t* array, str_t key);
extern int pair_array_set(pair_array_t* array, str_t key, str_t val);
typedef struct
{
enum
{
MSG_CONTENT_TYPE_NONE,
MSG_CONTENT_TYPE_STRING,
MSG_CONTENT_TYPE_FACE
} type;
union
{
str_t string;
uint face_id;
};
} msg_content_t;
typedef struct
{
msg_content_t* vals;
size_t count;
} msg_content_array_t;
#define empty_msg_content_array {NULL, 0}
#define msg_content_array_empty(array) ((array).count == 0)
extern void msg_content_array_free(msg_content_array_t* array);
extern void msg_content_array_append_string(msg_content_array_t* array, const char* val);
extern void msg_content_array_append_face(msg_content_array_t* array, uint face_id);
extern char* msg_content_array_to_json_object_string(msg_content_array_t* array, const char* key);
extern cJSON* msg_content_array_to_json_value(msg_content_array_t* array);
extern msg_content_array_t msg_content_array_from_json_value(cJSON* src);
#endif
| lwch/QQRobot | src/struct.h | C | apache-2.0 | 1,834 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.