repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
yangboz/north-american-adventure
|
RushuMicroService/eip-rushucloud/src/main/java/com/rushucloud/eip/models/SimplePerson.java
|
1993
|
/*
* Copyright 2015 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.
*
* All rights reserved.
*/
package com.rushucloud.eip.models;
import org.springframework.ldap.odm.annotations.Entry;
/**
* Simple person object for OdmPerson posting to LDAP server.
*
* @author yangboz
*/
@Entry(objectClasses = {"person", "top"}, base = "")
public class SimplePerson
{
private String mobile;
public String getMobile()
{
return mobile;
}
public void setMobile(String mobile)
{
this.mobile = mobile;
}
private String email;
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
private String password;
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
private String username;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
private String wxToken;
public String getWxToken()
{
return wxToken;
}
public void setWxToken(String wxToken)
{
this.wxToken = wxToken;
}
private String code;
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
}
|
unlicense
|
Grupp2/GameBoard-API-Games
|
testsrc/othello/backend/classhelpers/BoardHelperTest.java
|
3094
|
package othello.backend.classhelpers;
import othello.backend.State;
import othello.backend.classhelpers.BoardHelper;
import game.impl.Board;
import game.impl.BoardLocation;
import game.impl.GamePiece;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class BoardHelperTest {
@Test
public void testGetLocationById() throws Exception {
State state = mock(State.class);
Board board = mock(Board.class);
when(board.getLocations()).thenReturn(new ArrayList<BoardLocation>(){{
add(new BoardLocation("TEST1"));
add(new BoardLocation("TEST2"));
add(new BoardLocation("TEST3"));
add(new BoardLocation("TEST4"));
add(new BoardLocation("TEST5"));
add(new BoardLocation("TEST6"));
add(new BoardLocation("TEST7"));
}});
when(state.getBoard()).thenReturn(board);
BoardHelper boardHelper = new BoardHelper(state);
assertEquals("TEST4", boardHelper.getLocationById("TEST4").getId());
assertEquals("TEST7", boardHelper.getLocationById("TEST7").getId());
assertEquals("TEST1", boardHelper.getLocationById("TEST1").getId());
assertEquals(null, boardHelper.getLocationById("NON EXISTING"));
}
@Test
public void testIsLocationEmpty() throws Exception {
State state = mock(State.class);
BoardHelper boardHelper = new BoardHelper(state);
BoardLocation location = new BoardLocation("Test location");
assertTrue(boardHelper.isLocationEmpty(location));
location.setPiece(new GamePiece("Test Piece"));
assertFalse(boardHelper.isLocationEmpty(location));
location.setPiece(null);
assertTrue(boardHelper.isLocationEmpty(location));
}
@Test
public void testEmptyLocation() throws Exception {
State state = mock(State.class);
BoardHelper boardHelper = new BoardHelper(state);
BoardLocation location = new BoardLocation("Test location");
location.setPiece(new GamePiece("Test Piece"));
boardHelper.emptyLocation(location);
assertTrue(boardHelper.isLocationEmpty(location));
}
@Test
public void testDoesLocationExistOnBoard() throws Exception{
State state = mock(State.class);
Board board = mock(Board.class);
final BoardLocation theLocation = mock(BoardLocation.class);
ArrayList<BoardLocation> existingList = new ArrayList<BoardLocation>(){
{
add(theLocation);
}
};
ArrayList<BoardLocation> nonExistingList = new ArrayList<BoardLocation>();
when(state.getBoard()).thenReturn(board).thenReturn(board);
when(board.getLocations()).thenReturn(existingList).thenReturn(nonExistingList);
BoardHelper boardHelper = new BoardHelper(state);
assertTrue(boardHelper.doesLocationExistOnBoard(theLocation));
assertFalse(boardHelper.doesLocationExistOnBoard(theLocation));
}
}
|
unlicense
|
bfrick22/monetary-rewards
|
mysite/rewards/apps.py
|
130
|
from __future__ import unicode_literals
from django.apps import AppConfig
class RewardsConfig(AppConfig):
name = 'rewards'
|
unlicense
|
isogon/styled-mdl-website
|
demos/lists/demos/avatarsAndControls.js
|
1826
|
import React from 'react'
import {
List,
ListItem,
LiAction,
LiSecondary,
LiPrimary,
LiAvatar,
Checkbox,
Radio,
Switch,
Icon,
} from 'styled-mdl'
const demo = () => (
<List>
<ListItem>
<LiPrimary>
<LiAvatar>
<Icon name="person" />
</LiAvatar>
Bryan Cranston
</LiPrimary>
<LiSecondary>
<LiAction>
<Checkbox defaultChecked />
</LiAction>
</LiSecondary>
</ListItem>
<ListItem>
<LiPrimary>
<LiAvatar>
<Icon name="person" />
</LiAvatar>
Aaron Paul
</LiPrimary>
<LiSecondary>
<LiAction>
<Radio />
</LiAction>
</LiSecondary>
</ListItem>
<ListItem>
<LiPrimary>
<LiAvatar>
<Icon name="person" />
</LiAvatar>
Bob Odenkirk
</LiPrimary>
<LiSecondary>
<LiAction>
<Switch defaultChecked />
</LiAction>
</LiSecondary>
</ListItem>
</List>
)
const caption = 'Avatars and controls'
const code = `<List>
<ListItem>
<LiPrimary>
<LiAvatar><Icon name="person" /></LiAvatar>
Bryan Cranston
</LiPrimary>
<LiSecondary>
<LiAction>
<Checkbox defaultChecked />
</LiAction>
</LiSecondary>
</ListItem>
<ListItem>
<LiPrimary>
<LiAvatar><Icon name="person" /></LiAvatar>
Aaron Paul
</LiPrimary>
<LiSecondary>
<LiAction>
<Radio />
</LiAction>
</LiSecondary>
</ListItem>
<ListItem>
<LiPrimary>
<LiAvatar><Icon name="person" /></LiAvatar>
Bob Odenkirk
</LiPrimary>
<LiSecondary>
<LiAction>
<Switch defaultChecked />
</LiAction>
</LiSecondary>
</ListItem>
</List>`
export default { demo, caption, code }
|
unlicense
|
ronhandler/gitroot
|
pyglfw/glfw.py
|
77583
|
"""
Python bindings for GLFW.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = 'Florian Rhiem ([email protected])'
__copyright__ = 'Copyright (c) 2013-2016 Florian Rhiem'
__license__ = 'MIT'
__version__ = '1.3.1'
# By default (ERROR_REPORTING = True), GLFW errors will be reported as Python
# exceptions. Set ERROR_REPORTING to False or set a curstom error callback to
# disable this behavior.
ERROR_REPORTING = True
import ctypes
import os
import functools
import glob
import sys
import subprocess
import textwrap
# Python 3 compatibility:
try:
_getcwd = os.getcwdu
except AttributeError:
_getcwd = os.getcwd
if sys.version_info.major > 2:
_to_char_p = lambda s: s.encode('utf-8')
def _reraise(exception, traceback):
raise exception.with_traceback(traceback)
else:
_to_char_p = lambda s: s
def _reraise(exception, traceback):
raise (exception, None, traceback)
class GLFWError(Exception):
"""
Exception class used for reporting GLFW errors.
"""
def __init__(self, message):
super(GLFWError, self).__init__(message)
def _find_library_candidates(library_names,
library_file_extensions,
library_search_paths):
"""
Finds and returns filenames which might be the library you are looking for.
"""
candidates = set()
for library_name in library_names:
for search_path in library_search_paths:
glob_query = os.path.join(search_path, '*'+library_name+'*')
for filename in glob.iglob(glob_query):
filename = os.path.realpath(filename)
if filename in candidates:
continue
basename = os.path.basename(filename)
if basename.startswith('lib'+library_name):
basename_end = basename[len('lib'+library_name):]
elif basename.startswith(library_name):
basename_end = basename[len(library_name):]
else:
continue
for file_extension in library_file_extensions:
if basename_end.startswith(file_extension):
if basename_end[len(file_extension):][:1] in ('', '.'):
candidates.add(filename)
if basename_end.endswith(file_extension):
basename_middle = basename_end[:-len(file_extension)]
if all(c in '0123456789.' for c in basename_middle):
candidates.add(filename)
return candidates
def _load_library(library_names, library_file_extensions,
library_search_paths, version_check_callback):
"""
Finds, loads and returns the most recent version of the library.
"""
candidates = _find_library_candidates(library_names,
library_file_extensions,
library_search_paths)
library_versions = []
for filename in candidates:
version = version_check_callback(filename)
if version is not None and version >= (3, 0, 0):
library_versions.append((version, filename))
if not library_versions:
return None
library_versions.sort()
return ctypes.CDLL(library_versions[-1][1])
def _glfw_get_version(filename):
"""
Queries and returns the library version tuple or None by using a
subprocess.
"""
version_checker_source = '''
import sys
import ctypes
def get_version(library_handle):
"""
Queries and returns the library version tuple or None.
"""
major_value = ctypes.c_int(0)
major = ctypes.pointer(major_value)
minor_value = ctypes.c_int(0)
minor = ctypes.pointer(minor_value)
rev_value = ctypes.c_int(0)
rev = ctypes.pointer(rev_value)
if hasattr(library_handle, 'glfwGetVersion'):
library_handle.glfwGetVersion(major, minor, rev)
version = (major_value.value,
minor_value.value,
rev_value.value)
return version
else:
return None
try:
input_func = raw_input
except NameError:
input_func = input
filename = input_func().strip()
try:
library_handle = ctypes.CDLL(filename)
except OSError:
pass
else:
version = get_version(library_handle)
print(version)
'''
args = [sys.executable, '-c', textwrap.dedent(version_checker_source)]
process = subprocess.Popen(args, universal_newlines=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out = process.communicate(filename)[0]
out = out.strip()
if out:
return eval(out)
else:
return None
if sys.platform == 'win32':
# only try glfw3.dll on windows
try:
_glfw = ctypes.CDLL('glfw3.dll')
except OSError:
_glfw = None
else:
_glfw = _load_library(['glfw', 'glfw3'], ['.so', '.dylib'],
['',
'/usr/lib64', '/usr/local/lib64',
'/usr/lib', '/usr/local/lib',
'/usr/lib/x86_64-linux-gnu/'], _glfw_get_version)
if _glfw is None:
raise ImportError("Failed to load GLFW3 shared library.")
_callback_repositories = []
class _GLFWwindow(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWwindow GLFWwindow;
"""
_fields_ = [("dummy", ctypes.c_int)]
class _GLFWmonitor(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWmonitor GLFWmonitor;
"""
_fields_ = [("dummy", ctypes.c_int)]
class _GLFWvidmode(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWvidmode GLFWvidmode;
"""
_fields_ = [("width", ctypes.c_int),
("height", ctypes.c_int),
("red_bits", ctypes.c_int),
("green_bits", ctypes.c_int),
("blue_bits", ctypes.c_int),
("refresh_rate", ctypes.c_uint)]
def __init__(self):
ctypes.Structure.__init__(self)
self.width = 0
self.height = 0
self.red_bits = 0
self.green_bits = 0
self.blue_bits = 0
self.refresh_rate = 0
def wrap(self, video_mode):
"""
Wraps a nested python sequence.
"""
size, bits, self.refresh_rate = video_mode
self.width, self.height = size
self.red_bits, self.green_bits, self.blue_bits = bits
def unwrap(self):
"""
Returns a nested python sequence.
"""
size = self.width, self.height
bits = self.red_bits, self.green_bits, self.blue_bits
return size, bits, self.refresh_rate
class _GLFWgammaramp(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWgammaramp GLFWgammaramp;
"""
_fields_ = [("red", ctypes.POINTER(ctypes.c_ushort)),
("green", ctypes.POINTER(ctypes.c_ushort)),
("blue", ctypes.POINTER(ctypes.c_ushort)),
("size", ctypes.c_uint)]
def __init__(self):
ctypes.Structure.__init__(self)
self.red = None
self.red_array = None
self.green = None
self.green_array = None
self.blue = None
self.blue_array = None
self.size = 0
def wrap(self, gammaramp):
"""
Wraps a nested python sequence.
"""
red, green, blue = gammaramp
size = min(len(red), len(green), len(blue))
array_type = ctypes.c_ushort*size
self.size = ctypes.c_uint(size)
self.red_array = array_type()
self.green_array = array_type()
self.blue_array = array_type()
for i in range(self.size):
self.red_array[i] = int(red[i]*65535)
self.green_array[i] = int(green[i]*65535)
self.blue_array[i] = int(blue[i]*65535)
pointer_type = ctypes.POINTER(ctypes.c_ushort)
self.red = ctypes.cast(self.red_array, pointer_type)
self.green = ctypes.cast(self.green_array, pointer_type)
self.blue = ctypes.cast(self.blue_array, pointer_type)
def unwrap(self):
"""
Returns a nested python sequence.
"""
red = [self.red[i]/65535.0 for i in range(self.size)]
green = [self.green[i]/65535.0 for i in range(self.size)]
blue = [self.blue[i]/65535.0 for i in range(self.size)]
return red, green, blue
class _GLFWcursor(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWcursor GLFWcursor;
"""
_fields_ = [("dummy", ctypes.c_int)]
class _GLFWimage(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWimage GLFWimage;
"""
_fields_ = [("width", ctypes.c_int),
("height", ctypes.c_int),
("pixels", ctypes.POINTER(ctypes.c_ubyte))]
def __init__(self):
ctypes.Structure.__init__(self)
self.width = 0
self.height = 0
self.pixels = None
self.pixels_array = None
def wrap(self, image):
"""
Wraps a nested python sequence.
"""
self.width, self.height, pixels = image
array_type = ctypes.c_ubyte * 4 * self.width * self.height
self.pixels_array = array_type()
for i in range(self.height):
for j in range(self.width):
for k in range(4):
self.pixels_array[i][j][k] = pixels[i][j][k]
pointer_type = ctypes.POINTER(ctypes.c_ubyte)
self.pixels = ctypes.cast(self.pixels_array, pointer_type)
def unwrap(self):
"""
Returns a nested python sequence.
"""
pixels = [[[int(c) for c in p] for p in l] for l in self.pixels_array]
return self.width, self.height, pixels
VERSION_MAJOR = 3
VERSION_MINOR = 2
VERSION_REVISION = 1
RELEASE = 0
PRESS = 1
REPEAT = 2
KEY_UNKNOWN = -1
KEY_SPACE = 32
KEY_APOSTROPHE = 39
KEY_COMMA = 44
KEY_MINUS = 45
KEY_PERIOD = 46
KEY_SLASH = 47
KEY_0 = 48
KEY_1 = 49
KEY_2 = 50
KEY_3 = 51
KEY_4 = 52
KEY_5 = 53
KEY_6 = 54
KEY_7 = 55
KEY_8 = 56
KEY_9 = 57
KEY_SEMICOLON = 59
KEY_EQUAL = 61
KEY_A = 65
KEY_B = 66
KEY_C = 67
KEY_D = 68
KEY_E = 69
KEY_F = 70
KEY_G = 71
KEY_H = 72
KEY_I = 73
KEY_J = 74
KEY_K = 75
KEY_L = 76
KEY_M = 77
KEY_N = 78
KEY_O = 79
KEY_P = 80
KEY_Q = 81
KEY_R = 82
KEY_S = 83
KEY_T = 84
KEY_U = 85
KEY_V = 86
KEY_W = 87
KEY_X = 88
KEY_Y = 89
KEY_Z = 90
KEY_LEFT_BRACKET = 91
KEY_BACKSLASH = 92
KEY_RIGHT_BRACKET = 93
KEY_GRAVE_ACCENT = 96
KEY_WORLD_1 = 161
KEY_WORLD_2 = 162
KEY_ESCAPE = 256
KEY_ENTER = 257
KEY_TAB = 258
KEY_BACKSPACE = 259
KEY_INSERT = 260
KEY_DELETE = 261
KEY_RIGHT = 262
KEY_LEFT = 263
KEY_DOWN = 264
KEY_UP = 265
KEY_PAGE_UP = 266
KEY_PAGE_DOWN = 267
KEY_HOME = 268
KEY_END = 269
KEY_CAPS_LOCK = 280
KEY_SCROLL_LOCK = 281
KEY_NUM_LOCK = 282
KEY_PRINT_SCREEN = 283
KEY_PAUSE = 284
KEY_F1 = 290
KEY_F2 = 291
KEY_F3 = 292
KEY_F4 = 293
KEY_F5 = 294
KEY_F6 = 295
KEY_F7 = 296
KEY_F8 = 297
KEY_F9 = 298
KEY_F10 = 299
KEY_F11 = 300
KEY_F12 = 301
KEY_F13 = 302
KEY_F14 = 303
KEY_F15 = 304
KEY_F16 = 305
KEY_F17 = 306
KEY_F18 = 307
KEY_F19 = 308
KEY_F20 = 309
KEY_F21 = 310
KEY_F22 = 311
KEY_F23 = 312
KEY_F24 = 313
KEY_F25 = 314
KEY_KP_0 = 320
KEY_KP_1 = 321
KEY_KP_2 = 322
KEY_KP_3 = 323
KEY_KP_4 = 324
KEY_KP_5 = 325
KEY_KP_6 = 326
KEY_KP_7 = 327
KEY_KP_8 = 328
KEY_KP_9 = 329
KEY_KP_DECIMAL = 330
KEY_KP_DIVIDE = 331
KEY_KP_MULTIPLY = 332
KEY_KP_SUBTRACT = 333
KEY_KP_ADD = 334
KEY_KP_ENTER = 335
KEY_KP_EQUAL = 336
KEY_LEFT_SHIFT = 340
KEY_LEFT_CONTROL = 341
KEY_LEFT_ALT = 342
KEY_LEFT_SUPER = 343
KEY_RIGHT_SHIFT = 344
KEY_RIGHT_CONTROL = 345
KEY_RIGHT_ALT = 346
KEY_RIGHT_SUPER = 347
KEY_MENU = 348
KEY_LAST = KEY_MENU
MOD_SHIFT = 0x0001
MOD_CONTROL = 0x0002
MOD_ALT = 0x0004
MOD_SUPER = 0x0008
MOUSE_BUTTON_1 = 0
MOUSE_BUTTON_2 = 1
MOUSE_BUTTON_3 = 2
MOUSE_BUTTON_4 = 3
MOUSE_BUTTON_5 = 4
MOUSE_BUTTON_6 = 5
MOUSE_BUTTON_7 = 6
MOUSE_BUTTON_8 = 7
MOUSE_BUTTON_LAST = MOUSE_BUTTON_8
MOUSE_BUTTON_LEFT = MOUSE_BUTTON_1
MOUSE_BUTTON_RIGHT = MOUSE_BUTTON_2
MOUSE_BUTTON_MIDDLE = MOUSE_BUTTON_3
JOYSTICK_1 = 0
JOYSTICK_2 = 1
JOYSTICK_3 = 2
JOYSTICK_4 = 3
JOYSTICK_5 = 4
JOYSTICK_6 = 5
JOYSTICK_7 = 6
JOYSTICK_8 = 7
JOYSTICK_9 = 8
JOYSTICK_10 = 9
JOYSTICK_11 = 10
JOYSTICK_12 = 11
JOYSTICK_13 = 12
JOYSTICK_14 = 13
JOYSTICK_15 = 14
JOYSTICK_16 = 15
JOYSTICK_LAST = JOYSTICK_16
NOT_INITIALIZED = 0x00010001
NO_CURRENT_CONTEXT = 0x00010002
INVALID_ENUM = 0x00010003
INVALID_VALUE = 0x00010004
OUT_OF_MEMORY = 0x00010005
API_UNAVAILABLE = 0x00010006
VERSION_UNAVAILABLE = 0x00010007
PLATFORM_ERROR = 0x00010008
FORMAT_UNAVAILABLE = 0x00010009
NO_WINDOW_CONTEXT = 0x0001000A
FOCUSED = 0x00020001
ICONIFIED = 0x00020002
RESIZABLE = 0x00020003
VISIBLE = 0x00020004
DECORATED = 0x00020005
AUTO_ICONIFY = 0x00020006
FLOATING = 0x00020007
MAXIMIZED = 0x00020008
RED_BITS = 0x00021001
GREEN_BITS = 0x00021002
BLUE_BITS = 0x00021003
ALPHA_BITS = 0x00021004
DEPTH_BITS = 0x00021005
STENCIL_BITS = 0x00021006
ACCUM_RED_BITS = 0x00021007
ACCUM_GREEN_BITS = 0x00021008
ACCUM_BLUE_BITS = 0x00021009
ACCUM_ALPHA_BITS = 0x0002100A
AUX_BUFFERS = 0x0002100B
STEREO = 0x0002100C
SAMPLES = 0x0002100D
SRGB_CAPABLE = 0x0002100E
REFRESH_RATE = 0x0002100F
DOUBLEBUFFER = 0x00021010
CLIENT_API = 0x00022001
CONTEXT_VERSION_MAJOR = 0x00022002
CONTEXT_VERSION_MINOR = 0x00022003
CONTEXT_REVISION = 0x00022004
CONTEXT_ROBUSTNESS = 0x00022005
OPENGL_FORWARD_COMPAT = 0x00022006
OPENGL_DEBUG_CONTEXT = 0x00022007
OPENGL_PROFILE = 0x00022008
CONTEXT_RELEASE_BEHAVIOR = 0x00022009
CONTEXT_NO_ERROR = 0x0002200A
CONTEXT_CREATION_API = 0x0002200B
NO_API = 0
OPENGL_API = 0x00030001
OPENGL_ES_API = 0x00030002
NO_ROBUSTNESS = 0
NO_RESET_NOTIFICATION = 0x00031001
LOSE_CONTEXT_ON_RESET = 0x00031002
OPENGL_ANY_PROFILE = 0
OPENGL_CORE_PROFILE = 0x00032001
OPENGL_COMPAT_PROFILE = 0x00032002
CURSOR = 0x00033001
STICKY_KEYS = 0x00033002
STICKY_MOUSE_BUTTONS = 0x00033003
CURSOR_NORMAL = 0x00034001
CURSOR_HIDDEN = 0x00034002
CURSOR_DISABLED = 0x00034003
ANY_RELEASE_BEHAVIOR = 0
RELEASE_BEHAVIOR_FLUSH = 0x00035001
RELEASE_BEHAVIOR_NONE = 0x00035002
NATIVE_CONTEXT_API = 0x00036001
EGL_CONTEXT_API = 0x00036002
ARROW_CURSOR = 0x00036001
IBEAM_CURSOR = 0x00036002
CROSSHAIR_CURSOR = 0x00036003
HAND_CURSOR = 0x00036004
HRESIZE_CURSOR = 0x00036005
VRESIZE_CURSOR = 0x00036006
CONNECTED = 0x00040001
DISCONNECTED = 0x00040002
DONT_CARE = -1
_exc_info_from_callback = None
def _callback_exception_decorator(func):
@functools.wraps(func)
def callback_wrapper(*args, **kwargs):
global _exc_info_from_callback
if _exc_info_from_callback is not None:
# We are on the way back to Python after an exception was raised.
# Do not call further callbacks and wait for the errcheck function
# to handle the exception first.
return
try:
return func(*args, **kwargs)
except (KeyboardInterrupt, SystemExit):
raise
except:
_exc_info_from_callback = sys.exc_info()
return callback_wrapper
def _prepare_errcheck():
"""
This function sets the errcheck attribute of all ctypes wrapped functions
to evaluate the _exc_info_from_callback global variable and re-raise any
exceptions that might have been raised in callbacks.
It also modifies all callback types to automatically wrap the function
using the _callback_exception_decorator.
"""
def errcheck(result, *args):
global _exc_info_from_callback
if _exc_info_from_callback is not None:
exc = _exc_info_from_callback
_exc_info_from_callback = None
_reraise(exc[1], exc[2])
return result
for symbol in dir(_glfw):
if symbol.startswith('glfw'):
getattr(_glfw, symbol).errcheck = errcheck
_globals = globals()
for symbol in _globals:
if symbol.startswith('_GLFW') and symbol.endswith('fun'):
def wrapper_cfunctype(func, cfunctype=_globals[symbol]):
return cfunctype(_callback_exception_decorator(func))
_globals[symbol] = wrapper_cfunctype
_GLFWerrorfun = ctypes.CFUNCTYPE(None,
ctypes.c_int,
ctypes.c_char_p)
_GLFWwindowposfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int)
_GLFWwindowsizefun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int)
_GLFWwindowclosefun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow))
_GLFWwindowrefreshfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow))
_GLFWwindowfocusfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int)
_GLFWwindowiconifyfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int)
_GLFWframebuffersizefun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int)
_GLFWmousebuttonfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int,
ctypes.c_int)
_GLFWcursorposfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_double,
ctypes.c_double)
_GLFWcursorenterfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int)
_GLFWscrollfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_double,
ctypes.c_double)
_GLFWkeyfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int)
_GLFWcharfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int)
_GLFWmonitorfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWmonitor),
ctypes.c_int)
_GLFWdropfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.POINTER(ctypes.c_char_p))
_GLFWcharmodsfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_uint,
ctypes.c_int)
_GLFWjoystickfun = ctypes.CFUNCTYPE(None,
ctypes.c_int,
ctypes.c_int)
_glfw.glfwInit.restype = ctypes.c_int
_glfw.glfwInit.argtypes = []
def init():
"""
Initializes the GLFW library.
Wrapper for:
int glfwInit(void);
"""
cwd = _getcwd()
res = _glfw.glfwInit()
os.chdir(cwd)
return res
_glfw.glfwTerminate.restype = None
_glfw.glfwTerminate.argtypes = []
def terminate():
"""
Terminates the GLFW library.
Wrapper for:
void glfwTerminate(void);
"""
for callback_repository in _callback_repositories:
for window_addr in list(callback_repository.keys()):
del callback_repository[window_addr]
for window_addr in list(_window_user_data_repository.keys()):
del _window_user_data_repository[window_addr]
_glfw.glfwTerminate()
_glfw.glfwGetVersion.restype = None
_glfw.glfwGetVersion.argtypes = [ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_version():
"""
Retrieves the version of the GLFW library.
Wrapper for:
void glfwGetVersion(int* major, int* minor, int* rev);
"""
major_value = ctypes.c_int(0)
major = ctypes.pointer(major_value)
minor_value = ctypes.c_int(0)
minor = ctypes.pointer(minor_value)
rev_value = ctypes.c_int(0)
rev = ctypes.pointer(rev_value)
_glfw.glfwGetVersion(major, minor, rev)
return major_value.value, minor_value.value, rev_value.value
_glfw.glfwGetVersionString.restype = ctypes.c_char_p
_glfw.glfwGetVersionString.argtypes = []
def get_version_string():
"""
Returns a string describing the compile-time configuration.
Wrapper for:
const char* glfwGetVersionString(void);
"""
return _glfw.glfwGetVersionString()
@_callback_exception_decorator
def _raise_glfw_errors_as_exceptions(error_code, description):
"""
Default error callback that raises GLFWError exceptions for glfw errors.
Set an alternative error callback or set glfw.ERROR_REPORTING to False to
disable this behavior.
"""
global ERROR_REPORTING
if ERROR_REPORTING:
message = "(%d) %s" % (error_code, description)
raise GLFWError(message)
_default_error_callback = _GLFWerrorfun(_raise_glfw_errors_as_exceptions)
_error_callback = (_raise_glfw_errors_as_exceptions, _default_error_callback)
_glfw.glfwSetErrorCallback.restype = _GLFWerrorfun
_glfw.glfwSetErrorCallback.argtypes = [_GLFWerrorfun]
_glfw.glfwSetErrorCallback(_default_error_callback)
def set_error_callback(cbfun):
"""
Sets the error callback.
Wrapper for:
GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);
"""
global _error_callback
previous_callback = _error_callback
if cbfun is None:
cbfun = _raise_glfw_errors_as_exceptions
c_cbfun = _default_error_callback
else:
c_cbfun = _GLFWerrorfun(cbfun)
_error_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetErrorCallback(cbfun)
if previous_callback is not None and previous_callback[0] != _raise_glfw_errors_as_exceptions:
return previous_callback[0]
_glfw.glfwGetMonitors.restype = ctypes.POINTER(ctypes.POINTER(_GLFWmonitor))
_glfw.glfwGetMonitors.argtypes = [ctypes.POINTER(ctypes.c_int)]
def get_monitors():
"""
Returns the currently connected monitors.
Wrapper for:
GLFWmonitor** glfwGetMonitors(int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetMonitors(count)
monitors = [result[i] for i in range(count_value.value)]
return monitors
_glfw.glfwGetPrimaryMonitor.restype = ctypes.POINTER(_GLFWmonitor)
_glfw.glfwGetPrimaryMonitor.argtypes = []
def get_primary_monitor():
"""
Returns the primary monitor.
Wrapper for:
GLFWmonitor* glfwGetPrimaryMonitor(void);
"""
return _glfw.glfwGetPrimaryMonitor()
_glfw.glfwGetMonitorPos.restype = None
_glfw.glfwGetMonitorPos.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_monitor_pos(monitor):
"""
Returns the position of the monitor's viewport on the virtual screen.
Wrapper for:
void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos);
"""
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_int(0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetMonitorPos(monitor, xpos, ypos)
return xpos_value.value, ypos_value.value
_glfw.glfwGetMonitorPhysicalSize.restype = None
_glfw.glfwGetMonitorPhysicalSize.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_monitor_physical_size(monitor):
"""
Returns the physical size of the monitor.
Wrapper for:
void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetMonitorPhysicalSize(monitor, width, height)
return width_value.value, height_value.value
_glfw.glfwGetMonitorName.restype = ctypes.c_char_p
_glfw.glfwGetMonitorName.argtypes = [ctypes.POINTER(_GLFWmonitor)]
def get_monitor_name(monitor):
"""
Returns the name of the specified monitor.
Wrapper for:
const char* glfwGetMonitorName(GLFWmonitor* monitor);
"""
return _glfw.glfwGetMonitorName(monitor)
_monitor_callback = None
_glfw.glfwSetMonitorCallback.restype = _GLFWmonitorfun
_glfw.glfwSetMonitorCallback.argtypes = [_GLFWmonitorfun]
def set_monitor_callback(cbfun):
"""
Sets the monitor configuration callback.
Wrapper for:
GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun);
"""
global _monitor_callback
previous_callback = _monitor_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWmonitorfun(cbfun)
_monitor_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetMonitorCallback(cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_glfw.glfwGetVideoModes.restype = ctypes.POINTER(_GLFWvidmode)
_glfw.glfwGetVideoModes.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(ctypes.c_int)]
def get_video_modes(monitor):
"""
Returns the available video modes for the specified monitor.
Wrapper for:
const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetVideoModes(monitor, count)
videomodes = [result[i].unwrap() for i in range(count_value.value)]
return videomodes
_glfw.glfwGetVideoMode.restype = ctypes.POINTER(_GLFWvidmode)
_glfw.glfwGetVideoMode.argtypes = [ctypes.POINTER(_GLFWmonitor)]
def get_video_mode(monitor):
"""
Returns the current mode of the specified monitor.
Wrapper for:
const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor);
"""
videomode = _glfw.glfwGetVideoMode(monitor).contents
return videomode.unwrap()
_glfw.glfwSetGamma.restype = None
_glfw.glfwSetGamma.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.c_float]
def set_gamma(monitor, gamma):
"""
Generates a gamma ramp and sets it for the specified monitor.
Wrapper for:
void glfwSetGamma(GLFWmonitor* monitor, float gamma);
"""
_glfw.glfwSetGamma(monitor, gamma)
_glfw.glfwGetGammaRamp.restype = ctypes.POINTER(_GLFWgammaramp)
_glfw.glfwGetGammaRamp.argtypes = [ctypes.POINTER(_GLFWmonitor)]
def get_gamma_ramp(monitor):
"""
Retrieves the current gamma ramp for the specified monitor.
Wrapper for:
const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor);
"""
gammaramp = _glfw.glfwGetGammaRamp(monitor).contents
return gammaramp.unwrap()
_glfw.glfwSetGammaRamp.restype = None
_glfw.glfwSetGammaRamp.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(_GLFWgammaramp)]
def set_gamma_ramp(monitor, ramp):
"""
Sets the current gamma ramp for the specified monitor.
Wrapper for:
void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp);
"""
gammaramp = _GLFWgammaramp()
gammaramp.wrap(ramp)
_glfw.glfwSetGammaRamp(monitor, ctypes.pointer(gammaramp))
_glfw.glfwDefaultWindowHints.restype = None
_glfw.glfwDefaultWindowHints.argtypes = []
def default_window_hints():
"""
Resets all window hints to their default values.
Wrapper for:
void glfwDefaultWindowHints(void);
"""
_glfw.glfwDefaultWindowHints()
_glfw.glfwWindowHint.restype = None
_glfw.glfwWindowHint.argtypes = [ctypes.c_int,
ctypes.c_int]
def window_hint(target, hint):
"""
Sets the specified window hint to the desired value.
Wrapper for:
void glfwWindowHint(int target, int hint);
"""
_glfw.glfwWindowHint(target, hint)
_glfw.glfwCreateWindow.restype = ctypes.POINTER(_GLFWwindow)
_glfw.glfwCreateWindow.argtypes = [ctypes.c_int,
ctypes.c_int,
ctypes.c_char_p,
ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(_GLFWwindow)]
def create_window(width, height, title, monitor, share):
"""
Creates a window and its associated context.
Wrapper for:
GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share);
"""
return _glfw.glfwCreateWindow(width, height, _to_char_p(title),
monitor, share)
_glfw.glfwDestroyWindow.restype = None
_glfw.glfwDestroyWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def destroy_window(window):
"""
Destroys the specified window and its context.
Wrapper for:
void glfwDestroyWindow(GLFWwindow* window);
"""
_glfw.glfwDestroyWindow(window)
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_ulong)).contents.value
for callback_repository in _callback_repositories:
if window_addr in callback_repository:
del callback_repository[window_addr]
if window_addr in _window_user_data_repository:
del _window_user_data_repository[window_addr]
_glfw.glfwWindowShouldClose.restype = ctypes.c_int
_glfw.glfwWindowShouldClose.argtypes = [ctypes.POINTER(_GLFWwindow)]
def window_should_close(window):
"""
Checks the close flag of the specified window.
Wrapper for:
int glfwWindowShouldClose(GLFWwindow* window);
"""
return _glfw.glfwWindowShouldClose(window)
_glfw.glfwSetWindowShouldClose.restype = None
_glfw.glfwSetWindowShouldClose.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def set_window_should_close(window, value):
"""
Sets the close flag of the specified window.
Wrapper for:
void glfwSetWindowShouldClose(GLFWwindow* window, int value);
"""
_glfw.glfwSetWindowShouldClose(window, value)
_glfw.glfwSetWindowTitle.restype = None
_glfw.glfwSetWindowTitle.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_char_p]
def set_window_title(window, title):
"""
Sets the title of the specified window.
Wrapper for:
void glfwSetWindowTitle(GLFWwindow* window, const char* title);
"""
_glfw.glfwSetWindowTitle(window, _to_char_p(title))
_glfw.glfwGetWindowPos.restype = None
_glfw.glfwGetWindowPos.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_window_pos(window):
"""
Retrieves the position of the client area of the specified window.
Wrapper for:
void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos);
"""
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_int(0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetWindowPos(window, xpos, ypos)
return xpos_value.value, ypos_value.value
_glfw.glfwSetWindowPos.restype = None
_glfw.glfwSetWindowPos.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int]
def set_window_pos(window, xpos, ypos):
"""
Sets the position of the client area of the specified window.
Wrapper for:
void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos);
"""
_glfw.glfwSetWindowPos(window, xpos, ypos)
_glfw.glfwGetWindowSize.restype = None
_glfw.glfwGetWindowSize.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_window_size(window):
"""
Retrieves the size of the client area of the specified window.
Wrapper for:
void glfwGetWindowSize(GLFWwindow* window, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetWindowSize(window, width, height)
return width_value.value, height_value.value
_glfw.glfwSetWindowSize.restype = None
_glfw.glfwSetWindowSize.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int]
def set_window_size(window, width, height):
"""
Sets the size of the client area of the specified window.
Wrapper for:
void glfwSetWindowSize(GLFWwindow* window, int width, int height);
"""
_glfw.glfwSetWindowSize(window, width, height)
_glfw.glfwGetFramebufferSize.restype = None
_glfw.glfwGetFramebufferSize.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_framebuffer_size(window):
"""
Retrieves the size of the framebuffer of the specified window.
Wrapper for:
void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetFramebufferSize(window, width, height)
return width_value.value, height_value.value
_glfw.glfwIconifyWindow.restype = None
_glfw.glfwIconifyWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def iconify_window(window):
"""
Iconifies the specified window.
Wrapper for:
void glfwIconifyWindow(GLFWwindow* window);
"""
_glfw.glfwIconifyWindow(window)
_glfw.glfwRestoreWindow.restype = None
_glfw.glfwRestoreWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def restore_window(window):
"""
Restores the specified window.
Wrapper for:
void glfwRestoreWindow(GLFWwindow* window);
"""
_glfw.glfwRestoreWindow(window)
_glfw.glfwShowWindow.restype = None
_glfw.glfwShowWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def show_window(window):
"""
Makes the specified window visible.
Wrapper for:
void glfwShowWindow(GLFWwindow* window);
"""
_glfw.glfwShowWindow(window)
_glfw.glfwHideWindow.restype = None
_glfw.glfwHideWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def hide_window(window):
"""
Hides the specified window.
Wrapper for:
void glfwHideWindow(GLFWwindow* window);
"""
_glfw.glfwHideWindow(window)
_glfw.glfwGetWindowMonitor.restype = ctypes.POINTER(_GLFWmonitor)
_glfw.glfwGetWindowMonitor.argtypes = [ctypes.POINTER(_GLFWwindow)]
def get_window_monitor(window):
"""
Returns the monitor that the window uses for full screen mode.
Wrapper for:
GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window);
"""
return _glfw.glfwGetWindowMonitor(window)
_glfw.glfwGetWindowAttrib.restype = ctypes.c_int
_glfw.glfwGetWindowAttrib.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def get_window_attrib(window, attrib):
"""
Returns an attribute of the specified window.
Wrapper for:
int glfwGetWindowAttrib(GLFWwindow* window, int attrib);
"""
return _glfw.glfwGetWindowAttrib(window, attrib)
_window_user_data_repository = {}
_glfw.glfwSetWindowUserPointer.restype = None
_glfw.glfwSetWindowUserPointer.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_void_p]
def set_window_user_pointer(window, pointer):
"""
Sets the user pointer of the specified window. You may pass a normal python object into this function and it will
be wrapped automatically. The object will be kept in existence until the pointer is set to something else or
until the window is destroyed.
Wrapper for:
void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer);
"""
data = (False, pointer)
if not isinstance(pointer, ctypes.c_void_p):
data = (True, pointer)
# Create a void pointer for the python object
pointer = ctypes.cast(ctypes.pointer(ctypes.py_object(pointer)), ctypes.c_void_p)
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
_window_user_data_repository[window_addr] = data
_glfw.glfwSetWindowUserPointer(window, pointer)
_glfw.glfwGetWindowUserPointer.restype = ctypes.c_void_p
_glfw.glfwGetWindowUserPointer.argtypes = [ctypes.POINTER(_GLFWwindow)]
def get_window_user_pointer(window):
"""
Returns the user pointer of the specified window.
Wrapper for:
void* glfwGetWindowUserPointer(GLFWwindow* window);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_user_data_repository:
data = _window_user_data_repository[window_addr]
is_wrapped_py_object = data[0]
if is_wrapped_py_object:
return data[1]
return _glfw.glfwGetWindowUserPointer(window)
_window_pos_callback_repository = {}
_callback_repositories.append(_window_pos_callback_repository)
_glfw.glfwSetWindowPosCallback.restype = _GLFWwindowposfun
_glfw.glfwSetWindowPosCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowposfun]
def set_window_pos_callback(window, cbfun):
"""
Sets the position callback for the specified window.
Wrapper for:
GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_pos_callback_repository:
previous_callback = _window_pos_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowposfun(cbfun)
_window_pos_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowPosCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_size_callback_repository = {}
_callback_repositories.append(_window_size_callback_repository)
_glfw.glfwSetWindowSizeCallback.restype = _GLFWwindowsizefun
_glfw.glfwSetWindowSizeCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowsizefun]
def set_window_size_callback(window, cbfun):
"""
Sets the size callback for the specified window.
Wrapper for:
GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_size_callback_repository:
previous_callback = _window_size_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowsizefun(cbfun)
_window_size_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowSizeCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_close_callback_repository = {}
_callback_repositories.append(_window_close_callback_repository)
_glfw.glfwSetWindowCloseCallback.restype = _GLFWwindowclosefun
_glfw.glfwSetWindowCloseCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowclosefun]
def set_window_close_callback(window, cbfun):
"""
Sets the close callback for the specified window.
Wrapper for:
GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_close_callback_repository:
previous_callback = _window_close_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowclosefun(cbfun)
_window_close_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowCloseCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_refresh_callback_repository = {}
_callback_repositories.append(_window_refresh_callback_repository)
_glfw.glfwSetWindowRefreshCallback.restype = _GLFWwindowrefreshfun
_glfw.glfwSetWindowRefreshCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowrefreshfun]
def set_window_refresh_callback(window, cbfun):
"""
Sets the refresh callback for the specified window.
Wrapper for:
GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_refresh_callback_repository:
previous_callback = _window_refresh_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowrefreshfun(cbfun)
_window_refresh_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowRefreshCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_focus_callback_repository = {}
_callback_repositories.append(_window_focus_callback_repository)
_glfw.glfwSetWindowFocusCallback.restype = _GLFWwindowfocusfun
_glfw.glfwSetWindowFocusCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowfocusfun]
def set_window_focus_callback(window, cbfun):
"""
Sets the focus callback for the specified window.
Wrapper for:
GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_focus_callback_repository:
previous_callback = _window_focus_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowfocusfun(cbfun)
_window_focus_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowFocusCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_iconify_callback_repository = {}
_callback_repositories.append(_window_iconify_callback_repository)
_glfw.glfwSetWindowIconifyCallback.restype = _GLFWwindowiconifyfun
_glfw.glfwSetWindowIconifyCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowiconifyfun]
def set_window_iconify_callback(window, cbfun):
"""
Sets the iconify callback for the specified window.
Wrapper for:
GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_iconify_callback_repository:
previous_callback = _window_iconify_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowiconifyfun(cbfun)
_window_iconify_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowIconifyCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_framebuffer_size_callback_repository = {}
_callback_repositories.append(_framebuffer_size_callback_repository)
_glfw.glfwSetFramebufferSizeCallback.restype = _GLFWframebuffersizefun
_glfw.glfwSetFramebufferSizeCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWframebuffersizefun]
def set_framebuffer_size_callback(window, cbfun):
"""
Sets the framebuffer resize callback for the specified window.
Wrapper for:
GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _framebuffer_size_callback_repository:
previous_callback = _framebuffer_size_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWframebuffersizefun(cbfun)
_framebuffer_size_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetFramebufferSizeCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_glfw.glfwPollEvents.restype = None
_glfw.glfwPollEvents.argtypes = []
def poll_events():
"""
Processes all pending events.
Wrapper for:
void glfwPollEvents(void);
"""
_glfw.glfwPollEvents()
_glfw.glfwWaitEvents.restype = None
_glfw.glfwWaitEvents.argtypes = []
def wait_events():
"""
Waits until events are pending and processes them.
Wrapper for:
void glfwWaitEvents(void);
"""
_glfw.glfwWaitEvents()
_glfw.glfwGetInputMode.restype = ctypes.c_int
_glfw.glfwGetInputMode.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def get_input_mode(window, mode):
"""
Returns the value of an input option for the specified window.
Wrapper for:
int glfwGetInputMode(GLFWwindow* window, int mode);
"""
return _glfw.glfwGetInputMode(window, mode)
_glfw.glfwSetInputMode.restype = None
_glfw.glfwSetInputMode.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int]
def set_input_mode(window, mode, value):
"""
Sets an input option for the specified window.
@param[in] window The window whose input mode to set.
@param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or
`GLFW_STICKY_MOUSE_BUTTONS`.
@param[in] value The new value of the specified input mode.
Wrapper for:
void glfwSetInputMode(GLFWwindow* window, int mode, int value);
"""
_glfw.glfwSetInputMode(window, mode, value)
_glfw.glfwGetKey.restype = ctypes.c_int
_glfw.glfwGetKey.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def get_key(window, key):
"""
Returns the last reported state of a keyboard key for the specified
window.
Wrapper for:
int glfwGetKey(GLFWwindow* window, int key);
"""
return _glfw.glfwGetKey(window, key)
_glfw.glfwGetMouseButton.restype = ctypes.c_int
_glfw.glfwGetMouseButton.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def get_mouse_button(window, button):
"""
Returns the last reported state of a mouse button for the specified
window.
Wrapper for:
int glfwGetMouseButton(GLFWwindow* window, int button);
"""
return _glfw.glfwGetMouseButton(window, button)
_glfw.glfwGetCursorPos.restype = None
_glfw.glfwGetCursorPos.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double)]
def get_cursor_pos(window):
"""
Retrieves the last reported cursor position, relative to the client
area of the window.
Wrapper for:
void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos);
"""
xpos_value = ctypes.c_double(0.0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_double(0.0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetCursorPos(window, xpos, ypos)
return xpos_value.value, ypos_value.value
_glfw.glfwSetCursorPos.restype = None
_glfw.glfwSetCursorPos.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_double,
ctypes.c_double]
def set_cursor_pos(window, xpos, ypos):
"""
Sets the position of the cursor, relative to the client area of the window.
Wrapper for:
void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos);
"""
_glfw.glfwSetCursorPos(window, xpos, ypos)
_key_callback_repository = {}
_callback_repositories.append(_key_callback_repository)
_glfw.glfwSetKeyCallback.restype = _GLFWkeyfun
_glfw.glfwSetKeyCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWkeyfun]
def set_key_callback(window, cbfun):
"""
Sets the key callback.
Wrapper for:
GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _key_callback_repository:
previous_callback = _key_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWkeyfun(cbfun)
_key_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetKeyCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_char_callback_repository = {}
_callback_repositories.append(_char_callback_repository)
_glfw.glfwSetCharCallback.restype = _GLFWcharfun
_glfw.glfwSetCharCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWcharfun]
def set_char_callback(window, cbfun):
"""
Sets the Unicode character callback.
Wrapper for:
GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _char_callback_repository:
previous_callback = _char_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWcharfun(cbfun)
_char_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCharCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_mouse_button_callback_repository = {}
_callback_repositories.append(_mouse_button_callback_repository)
_glfw.glfwSetMouseButtonCallback.restype = _GLFWmousebuttonfun
_glfw.glfwSetMouseButtonCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWmousebuttonfun]
def set_mouse_button_callback(window, cbfun):
"""
Sets the mouse button callback.
Wrapper for:
GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _mouse_button_callback_repository:
previous_callback = _mouse_button_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWmousebuttonfun(cbfun)
_mouse_button_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetMouseButtonCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_cursor_pos_callback_repository = {}
_callback_repositories.append(_cursor_pos_callback_repository)
_glfw.glfwSetCursorPosCallback.restype = _GLFWcursorposfun
_glfw.glfwSetCursorPosCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWcursorposfun]
def set_cursor_pos_callback(window, cbfun):
"""
Sets the cursor position callback.
Wrapper for:
GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _cursor_pos_callback_repository:
previous_callback = _cursor_pos_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWcursorposfun(cbfun)
_cursor_pos_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCursorPosCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_cursor_enter_callback_repository = {}
_callback_repositories.append(_cursor_enter_callback_repository)
_glfw.glfwSetCursorEnterCallback.restype = _GLFWcursorenterfun
_glfw.glfwSetCursorEnterCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWcursorenterfun]
def set_cursor_enter_callback(window, cbfun):
"""
Sets the cursor enter/exit callback.
Wrapper for:
GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _cursor_enter_callback_repository:
previous_callback = _cursor_enter_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWcursorenterfun(cbfun)
_cursor_enter_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCursorEnterCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_scroll_callback_repository = {}
_callback_repositories.append(_scroll_callback_repository)
_glfw.glfwSetScrollCallback.restype = _GLFWscrollfun
_glfw.glfwSetScrollCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWscrollfun]
def set_scroll_callback(window, cbfun):
"""
Sets the scroll callback.
Wrapper for:
GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _scroll_callback_repository:
previous_callback = _scroll_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWscrollfun(cbfun)
_scroll_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetScrollCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_glfw.glfwJoystickPresent.restype = ctypes.c_int
_glfw.glfwJoystickPresent.argtypes = [ctypes.c_int]
def joystick_present(joy):
"""
Returns whether the specified joystick is present.
Wrapper for:
int glfwJoystickPresent(int joy);
"""
return _glfw.glfwJoystickPresent(joy)
_glfw.glfwGetJoystickAxes.restype = ctypes.POINTER(ctypes.c_float)
_glfw.glfwGetJoystickAxes.argtypes = [ctypes.c_int,
ctypes.POINTER(ctypes.c_int)]
def get_joystick_axes(joy):
"""
Returns the values of all axes of the specified joystick.
Wrapper for:
const float* glfwGetJoystickAxes(int joy, int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetJoystickAxes(joy, count)
return result, count_value.value
_glfw.glfwGetJoystickButtons.restype = ctypes.POINTER(ctypes.c_ubyte)
_glfw.glfwGetJoystickButtons.argtypes = [ctypes.c_int,
ctypes.POINTER(ctypes.c_int)]
def get_joystick_buttons(joy):
"""
Returns the state of all buttons of the specified joystick.
Wrapper for:
const unsigned char* glfwGetJoystickButtons(int joy, int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetJoystickButtons(joy, count)
return result, count_value.value
_glfw.glfwGetJoystickName.restype = ctypes.c_char_p
_glfw.glfwGetJoystickName.argtypes = [ctypes.c_int]
def get_joystick_name(joy):
"""
Returns the name of the specified joystick.
Wrapper for:
const char* glfwGetJoystickName(int joy);
"""
return _glfw.glfwGetJoystickName(joy)
_glfw.glfwSetClipboardString.restype = None
_glfw.glfwSetClipboardString.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_char_p]
def set_clipboard_string(window, string):
"""
Sets the clipboard to the specified string.
Wrapper for:
void glfwSetClipboardString(GLFWwindow* window, const char* string);
"""
_glfw.glfwSetClipboardString(window, _to_char_p(string))
_glfw.glfwGetClipboardString.restype = ctypes.c_char_p
_glfw.glfwGetClipboardString.argtypes = [ctypes.POINTER(_GLFWwindow)]
def get_clipboard_string(window):
"""
Retrieves the contents of the clipboard as a string.
Wrapper for:
const char* glfwGetClipboardString(GLFWwindow* window);
"""
return _glfw.glfwGetClipboardString(window)
_glfw.glfwGetTime.restype = ctypes.c_double
_glfw.glfwGetTime.argtypes = []
def get_time():
"""
Returns the value of the GLFW timer.
Wrapper for:
double glfwGetTime(void);
"""
return _glfw.glfwGetTime()
_glfw.glfwSetTime.restype = None
_glfw.glfwSetTime.argtypes = [ctypes.c_double]
def set_time(time):
"""
Sets the GLFW timer.
Wrapper for:
void glfwSetTime(double time);
"""
_glfw.glfwSetTime(time)
_glfw.glfwMakeContextCurrent.restype = None
_glfw.glfwMakeContextCurrent.argtypes = [ctypes.POINTER(_GLFWwindow)]
def make_context_current(window):
"""
Makes the context of the specified window current for the calling
thread.
Wrapper for:
void glfwMakeContextCurrent(GLFWwindow* window);
"""
_glfw.glfwMakeContextCurrent(window)
_glfw.glfwGetCurrentContext.restype = ctypes.POINTER(_GLFWwindow)
_glfw.glfwGetCurrentContext.argtypes = []
def get_current_context():
"""
Returns the window whose context is current on the calling thread.
Wrapper for:
GLFWwindow* glfwGetCurrentContext(void);
"""
return _glfw.glfwGetCurrentContext()
_glfw.glfwSwapBuffers.restype = None
_glfw.glfwSwapBuffers.argtypes = [ctypes.POINTER(_GLFWwindow)]
def swap_buffers(window):
"""
Swaps the front and back buffers of the specified window.
Wrapper for:
void glfwSwapBuffers(GLFWwindow* window);
"""
_glfw.glfwSwapBuffers(window)
_glfw.glfwSwapInterval.restype = None
_glfw.glfwSwapInterval.argtypes = [ctypes.c_int]
def swap_interval(interval):
"""
Sets the swap interval for the current context.
Wrapper for:
void glfwSwapInterval(int interval);
"""
_glfw.glfwSwapInterval(interval)
_glfw.glfwExtensionSupported.restype = ctypes.c_int
_glfw.glfwExtensionSupported.argtypes = [ctypes.c_char_p]
def extension_supported(extension):
"""
Returns whether the specified extension is available.
Wrapper for:
int glfwExtensionSupported(const char* extension);
"""
return _glfw.glfwExtensionSupported(_to_char_p(extension))
_glfw.glfwGetProcAddress.restype = ctypes.c_void_p
_glfw.glfwGetProcAddress.argtypes = [ctypes.c_char_p]
def get_proc_address(procname):
"""
Returns the address of the specified function for the current
context.
Wrapper for:
GLFWglproc glfwGetProcAddress(const char* procname);
"""
return _glfw.glfwGetProcAddress(_to_char_p(procname))
if hasattr(_glfw, 'glfwSetDropCallback'):
_window_drop_callback_repository = {}
_callback_repositories.append(_window_drop_callback_repository)
_glfw.glfwSetDropCallback.restype = _GLFWdropfun
_glfw.glfwSetDropCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWdropfun]
def set_drop_callback(window, cbfun):
"""
Sets the file drop callback.
Wrapper for:
GLFWdropfun glfwSetDropCallback(GLFWwindow* window, GLFWdropfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_drop_callback_repository:
previous_callback = _window_drop_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
else:
def cb_wrapper(window, count, c_paths, cbfun=cbfun):
paths = [c_paths[i].decode('utf-8') for i in range(count)]
cbfun(window, paths)
cbfun = cb_wrapper
c_cbfun = _GLFWdropfun(cbfun)
_window_drop_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetDropCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
if hasattr(_glfw, 'glfwSetCharModsCallback'):
_window_char_mods_callback_repository = {}
_callback_repositories.append(_window_char_mods_callback_repository)
_glfw.glfwSetCharModsCallback.restype = _GLFWcharmodsfun
_glfw.glfwSetCharModsCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWcharmodsfun]
def set_char_mods_callback(window, cbfun):
"""
Sets the Unicode character with modifiers callback.
Wrapper for:
GLFWcharmodsfun glfwSetCharModsCallback(GLFWwindow* window, GLFWcharmodsfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_char_mods_callback_repository:
previous_callback = _window_char_mods_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWcharmodsfun(cbfun)
_window_char_mods_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCharModsCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
if hasattr(_glfw, 'glfwVulkanSupported'):
_glfw.glfwVulkanSupported.restype = ctypes.c_int
_glfw.glfwVulkanSupported.argtypes = []
def vulkan_supported():
"""
Returns whether the Vulkan loader has been found.
Wrapper for:
int glfwVulkanSupported(void);
"""
return _glfw.glfwVulkanSupported() != 0
if hasattr(_glfw, 'glfwGetRequiredInstanceExtensions'):
_glfw.glfwGetRequiredInstanceExtensions.restype = ctypes.POINTER(ctypes.c_char_p)
_glfw.glfwGetRequiredInstanceExtensions.argtypes = [ctypes.POINTER(ctypes.c_uint32)]
def get_required_instance_extensions():
"""
Returns the Vulkan instance extensions required by GLFW.
Wrapper for:
const char** glfwGetRequiredInstanceExtensions(uint32_t* count);
"""
count_value = ctypes.c_uint32(0)
count = ctypes.pointer(count_value)
c_extensions = _glfw.glfwGetRequiredInstanceExtensions(count)
count = count_value.value
extensions = [c_extensions[i].decode('utf-8') for i in range(count)]
return extensions
if hasattr(_glfw, 'glfwGetTimerValue'):
_glfw.glfwGetTimerValue.restype = ctypes.c_uint64
_glfw.glfwGetTimerValue.argtypes = []
def get_timer_value():
"""
Returns the current value of the raw timer.
Wrapper for:
uint64_t glfwGetTimerValue(void);
"""
return int(_glfw.glfwGetTimerValue())
if hasattr(_glfw, 'glfwGetTimerFrequency'):
_glfw.glfwGetTimerFrequency.restype = ctypes.c_uint64
_glfw.glfwGetTimerFrequency.argtypes = []
def get_timer_frequency():
"""
Returns the frequency, in Hz, of the raw timer.
Wrapper for:
uint64_t glfwGetTimerFrequency(void);
"""
return int(_glfw.glfwGetTimerFrequency())
if hasattr(_glfw, 'glfwSetJoystickCallback'):
_joystick_callback = None
_glfw.glfwSetJoystickCallback.restype = _GLFWjoystickfun
_glfw.glfwSetJoystickCallback.argtypes = [_GLFWjoystickfun]
def set_joystick_callback(cbfun):
"""
Sets the error callback.
Wrapper for:
GLFWjoystickfun glfwSetJoystickCallback(GLFWjoystickfun cbfun);
"""
global _joystick_callback
previous_callback = _error_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWjoystickfun(cbfun)
_joystick_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetJoystickCallback(cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
if hasattr(_glfw, 'glfwGetKeyName'):
_glfw.glfwGetKeyName.restype = ctypes.c_char_p
_glfw.glfwGetKeyName.argtypes = [ctypes.c_int, ctypes.c_int]
def get_key_name(key, scancode):
"""
Returns the localized name of the specified printable key.
Wrapper for:
const char* glfwGetKeyName(int key, int scancode);
"""
key_name = _glfw.glfwGetKeyName(key, scancode)
if key_name:
return key_name.decode('utf-8')
return None
if hasattr(_glfw, 'glfwCreateCursor'):
_glfw.glfwCreateCursor.restype = ctypes.POINTER(_GLFWcursor)
_glfw.glfwCreateCursor.argtypes = [ctypes.POINTER(_GLFWimage),
ctypes.c_int,
ctypes.c_int]
def create_cursor(image, xhot, yhot):
"""
Creates a custom cursor.
Wrapper for:
GLFWcursor* glfwCreateCursor(const GLFWimage* image, int xhot, int yhot);
"""
c_image = _GLFWimage()
c_image.wrap(image)
return _glfw.glfwCreateCursor(ctypes.pointer(c_image), xhot, yhot)
if hasattr(_glfw, 'glfwCreateStandardCursor'):
_glfw.glfwCreateStandardCursor.restype = ctypes.POINTER(_GLFWcursor)
_glfw.glfwCreateStandardCursor.argtypes = [ctypes.c_int]
def create_standard_cursor(shape):
"""
Creates a cursor with a standard shape.
Wrapper for:
GLFWcursor* glfwCreateStandardCursor(int shape);
"""
return _glfw.glfwCreateStandardCursor(shape)
if hasattr(_glfw, 'glfwDestroyCursor'):
_glfw.glfwDestroyCursor.restype = None
_glfw.glfwDestroyCursor.argtypes = [ctypes.POINTER(_GLFWcursor)]
def destroy_cursor(cursor):
"""
Destroys a cursor.
Wrapper for:
void glfwDestroyCursor(GLFWcursor* cursor);
"""
_glfw.glfwDestroyCursor(cursor)
if hasattr(_glfw, 'glfwSetCursor'):
_glfw.glfwSetCursor.restype = None
_glfw.glfwSetCursor.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(_GLFWcursor)]
def set_cursor(window, cursor):
"""
Sets the cursor for the window.
Wrapper for:
void glfwSetCursor(GLFWwindow* window, GLFWcursor* cursor);
"""
_glfw.glfwSetCursor(window, cursor)
if hasattr(_glfw, 'glfwCreateWindowSurface'):
_glfw.glfwCreateWindowSurface.restype = ctypes.c_int
_glfw.glfwCreateWindowSurface.argtypes = [ctypes.c_void_p,
ctypes.POINTER(_GLFWwindow),
ctypes.c_void_p,
ctypes.c_void_p]
def create_window_surface(instance, window, allocator, surface):
"""
Creates a Vulkan surface for the specified window.
Wrapper for:
VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface);
"""
return _glfw.glfwCreateWindowSurface(instance, window, allocator, surface)
if hasattr(_glfw, 'glfwGetPhysicalDevicePresentationSupport'):
_glfw.glfwGetPhysicalDevicePresentationSupport.restype = ctypes.c_int
_glfw.glfwGetPhysicalDevicePresentationSupport.argtypes = [ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint32]
def get_physical_device_presentation_support(instance, device, queuefamily):
"""
Creates a Vulkan surface for the specified window.
Wrapper for:
int glfwGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily);
"""
return _glfw.glfwGetPhysicalDevicePresentationSupport(instance, device, queuefamily)
if hasattr(_glfw, 'glfwGetInstanceProcAddress'):
_glfw.glfwGetInstanceProcAddress.restype = ctypes.c_void_p
_glfw.glfwGetInstanceProcAddress.argtypes = [ctypes.c_void_p,
ctypes.c_char_p]
def get_instance_proc_address(instance, procname):
"""
Returns the address of the specified Vulkan instance function.
Wrapper for:
GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname);
"""
return _glfw.glfwGetInstanceProcAddress(instance, procname)
if hasattr(_glfw, 'glfwSetWindowIcon'):
_glfw.glfwSetWindowIcon.restype = None
_glfw.glfwSetWindowIcon.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.POINTER(_GLFWimage)]
def set_window_icon(window, count, image):
"""
Sets the icon for the specified window.
Wrapper for:
void glfwSetWindowIcon(GLFWwindow* window, int count, const GLFWimage* images);
"""
_image = _GLFWimage()
_image.wrap(image)
_glfw.glfwSetWindowIcon(window, count, ctypes.pointer(_image))
if hasattr(_glfw, 'glfwSetWindowSizeLimits'):
_glfw.glfwSetWindowSizeLimits.restype = None
_glfw.glfwSetWindowSizeLimits.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int]
def set_window_size_limits(window,
minwidth, minheight,
maxwidth, maxheight):
"""
Sets the size limits of the specified window.
Wrapper for:
void glfwSetWindowSizeLimits(GLFWwindow* window, int minwidth, int minheight, int maxwidth, int maxheight);
"""
_glfw.glfwSetWindowSizeLimits(window,
minwidth, minheight,
maxwidth, maxheight)
if hasattr(_glfw, 'glfwSetWindowAspectRatio'):
_glfw.glfwSetWindowAspectRatio.restype = None
_glfw.glfwSetWindowAspectRatio.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int, ctypes.c_int]
def set_window_aspect_ratio(window, numer, denom):
"""
Sets the aspect ratio of the specified window.
Wrapper for:
void glfwSetWindowAspectRatio(GLFWwindow* window, int numer, int denom);
"""
_glfw.glfwSetWindowAspectRatio(window, numer, denom)
if hasattr(_glfw, 'glfwGetWindowFrameSize'):
_glfw.glfwGetWindowFrameSize.restype = None
_glfw.glfwGetWindowFrameSize.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def set_get_window_frame_size(window):
"""
Retrieves the size of the frame of the window.
Wrapper for:
void glfwGetWindowFrameSize(GLFWwindow* window, int* left, int* top, int* right, int* bottom);
"""
left = ctypes.c_int(0)
top = ctypes.c_int(0)
right = ctypes.c_int(0)
bottom = ctypes.c_int(0)
_glfw.glfwGetWindowFrameSize(window,
ctypes.pointer(left),
ctypes.pointer(top),
ctypes.pointer(right),
ctypes.pointer(bottom))
return left.value, top.value, right.value, bottom.value
if hasattr(_glfw, 'glfwMaximizeWindow'):
_glfw.glfwMaximizeWindow.restype = None
_glfw.glfwMaximizeWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def maximize_window(window):
"""
Maximizes the specified window.
Wrapper for:
void glfwMaximizeWindow(GLFWwindow* window);
"""
_glfw.glfwMaximizeWindow(window)
if hasattr(_glfw, 'glfwFocusWindow'):
_glfw.glfwFocusWindow.restype = None
_glfw.glfwFocusWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def focus_window(window):
"""
Brings the specified window to front and sets input focus.
Wrapper for:
void glfwFocusWindow(GLFWwindow* window);
"""
_glfw.glfwFocusWindow(window)
if hasattr(_glfw, 'glfwSetWindowMonitor'):
_glfw.glfwSetWindowMonitor.restype = None
_glfw.glfwSetWindowMonitor.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(_GLFWmonitor),
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int]
def set_window_monitor(window, monitor, xpos, ypos, width, height,
refresh_rate):
"""
Sets the mode, monitor, video mode and placement of a window.
Wrapper for:
void glfwSetWindowMonitor(GLFWwindow* window, GLFWmonitor* monitor, int xpos, int ypos, int width, int height, int refreshRate);
"""
_glfw.glfwSetWindowMonitor(window, monitor,
xpos, ypos, width, height, refresh_rate)
if hasattr(_glfw, 'glfwWaitEventsTimeout'):
_glfw.glfwWaitEventsTimeout.restype = None
_glfw.glfwWaitEventsTimeout.argtypes = [ctypes.c_double]
def wait_events_timeout(timeout):
"""
Waits with timeout until events are queued and processes them.
Wrapper for:
void glfwWaitEventsTimeout(double timeout);
"""
_glfw.glfwWaitEventsTimeout(timeout)
if hasattr(_glfw, 'glfwPostEmptyEvent'):
_glfw.glfwPostEmptyEvent.restype = None
_glfw.glfwPostEmptyEvent.argtypes = []
def post_empty_event():
"""
Posts an empty event to the event queue.
Wrapper for:
void glfwPostEmptyEvent();
"""
_glfw.glfwPostEmptyEvent()
_prepare_errcheck()
|
unlicense
|
janaagaard75/framework-investigations
|
old-or-not-typescript/learn-redux/react-redux-counter/webpack.config.js
|
1059
|
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var appList = ['./app/index.tsx'];
if(process.env.NODE_ENV === 'development') {
appList.unshift('webpack/hot/only-dev-server');
}
var currentPath = process.cwd();
module.exports = {
entry: {
app: appList
},
output: {
path: path.resolve(__dirname, "build"),
publicPath: "/",
filename: "bundle.js"
},
plugins: [new HtmlWebpackPlugin({
template: './app/index.html'
})],
resolve: {
root: [
path.join(currentPath, 'app/assets/stylesheets')
],
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
{ test: /\.tsx?$/, loader: 'ts-loader' },
{ test: /\.less$/, loader: 'style!css!less?strictMath' },
{ test: /\.css$/, loader: 'style!css' }
]
},
devServer: {
contentBase: './app',
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
};
|
unlicense
|
skoenig/kochbuch
|
docs/hauptgerichte/Matcha-Minz-Erbsensuppe-mit-Garnelen.html
|
5395
|
<!DOCTYPE html>
<html>
<head>
<title>Matcha Minz Erbsensuppe mit Garnelen</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="favicon.ico">
<meta charset="utf-8">
<!-- Bootstrap -->
<link href="//netdna.bootstrapcdn.com/bootswatch/3.4.1/journal/bootstrap.min.css" rel="stylesheet" media="screen">
<!-- customizations -->
<link href="/kochbuch/css/site.css" rel="stylesheet" media="screen">
<!-- pygments -->
<link href="/kochbuch/css/syntax.css" rel="stylesheet" media="screen">
<!-- icons -->
<link href="//netdna.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-SD0TGLWYNV"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-SD0TGLWYNV');
</script>
</head>
<body>
<!-- Fixed navbar -->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/kochbuch/">Kochbuch</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-left">
<li class="active"><a href="/kochbuch/hauptgerichte/">Hauptgerichte</a></li>
<li><a href="/kochbuch/beilagen/">Beilagen</a></li>
<li><a href="/kochbuch/desserts/">Desserts</a></li>
<li><a href="/kochbuch/snacks-und-shakes/">Snacks & Shakes</a></li>
<li><a href="/kochbuch/salate/">Salate</a></li>
</ul>
<form class="navbar-form navbar-left" action="/kochbuch/search.html" role="search">
<div class="form-group">
<input type="text" required name="q" id="tipue_search_input" class="form-control" placeholder="Suche">
</div>
</form>
<ul class="nav navbar-nav navbar-right">
<li><a href="/kochbuch/tag/">Kategorien</a></li>
<li><a href="/kochbuch/README.html">Über</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<ol class="breadcrumb">
<li><a href="/kochbuch/">Home</a></li>
<li><a href="/kochbuch/hauptgerichte/">Hauptgerichte</a></li>
<li class="active">Matcha Minz Erbsensuppe mit Garnelen</li>
</ol>
<div class="page-header">
<h1>Matcha Minz Erbsensuppe mit Garnelen</h1>
<span class="label label-primary">lowcarb</span>
<span class="pull-right">16-Sep-2020</span>
<div class="clearfix"></div>
</div>
<div class="row">
<div class="content">
<div class="col-md-7" role="main">
<main>
<h3 id="zutaten-fur-2-portionen">Zutaten für 2 Portionen</h3>
<ul>
<li>200 g Garnelen</li>
<li>400 g Bio Tiefkühlerbsen</li>
<li>300 ml Wasser</li>
<li>1 Zwiebel</li>
<li>1 TL gekörnte Gemüsebrühe</li>
<li>100 ml Sahne oder Kokosmilch</li>
<li>2 g Matcha Pulver</li>
<li>½ Teebeutel Pfefferminztee</li>
<li>1 EL Olivenöl</li>
<li>Pfeffer & Salz</li>
</ul>
<h3 id="zubereitung">Zubereitung</h3>
<ol>
<li>
<p>Die Bio Tiefkühlerbsen mit Wasser in einen Topf geben, aufkochen lassen und die Bio Gemüsebrühe einrühren. Auf mittlerer Flamme 10 bis 15 Minuten köcheln, bis die Bio Tiefkühlerbsen gar sind.</p>
</li>
<li>
<p>Nun mit Sahne aufgießen und mit einem Passierstab sämig pürieren. Aufkochen, dann die Hälfte des Matcha Pulvers und den halben Beutel Pfefferminztee einrühren. Mit etwas Pfeffer und - falls nicht würzig genug - etwas Salz abschmecken.</p>
</li>
<li>
<p>Die Zwiebel schälen und fein würfeln. Garnelen kalt waschen und trocknen. Olivenöl in einer Pfanne erhitzen, Zwiebeln und Garnelen darin braten, leicht salzen und pfeffern.</p>
</li>
<li>
<p>Die Matcha Minz-Erbsensuppe in Teller oder Schalen füllen, Garnelen dazugeben und mit dem restlichen Matcha bestäuben und genießen.</p>
</li>
</ol>
</main>
</div>
</div>
</div>
<div class="footer">
<p>Website powered by <a href="http://urubu.jandecaluwe.com">Urubu</a></p>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<!-- <script src="https://code.jquery.com/jquery.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</body>
</html>
|
unlicense
|
flipk/pfkutils
|
libWebAppServer/simpleWsTestServer.cc
|
3939
|
#include "simpleWebSocket.h"
#ifndef DEPENDING
#include PROXYMSGS_PB_H
#endif
#include <map>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#define DEBUG false
void *connection_thread(void*arg);
int main()
{
SimpleWebSocket::WebSocketServer srv(1081, INADDR_ANY, DEBUG);
if (srv.ok() == false)
{
printf("server setup fail\n");
return 3;
}
while (1)
{
SimpleWebSocket::WebSocketServerConn *nc = srv.handle_accept();
if (nc)
{
pthread_t id;
pthread_create(&id, NULL,
&connection_thread, (void*) nc);
}
}
return 0;
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int conns_pos = 1;
std::map<int,SimpleWebSocket::WebSocketServerConn *> conns;
void *connection_thread(void*arg)
{
::proxyTcp::ProxyMsg msg;
SimpleWebSocket::WebSocketServerConn *nc =
(SimpleWebSocket::WebSocketServerConn *) arg;
printf("got connection\n");
pthread_mutex_lock(&mutex);
int pos = conns_pos++;
conns[pos] = nc;
pthread_mutex_unlock(&mutex);
int fd = nc->get_fd();
fcntl( fd, F_SETFL,
fcntl( fd, F_GETFL, 0 ) | O_NONBLOCK );
bool doselect = false;
bool done = false;
while (!done)
{
if (doselect) {
bool doservice = false;
while (!doservice) {
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 1; // 1 second polling
tv.tv_usec = 0;
(void) select(fd+1, &rfds, NULL, NULL, &tv);
if (FD_ISSET(fd, &rfds))
doservice = true;
}
}
SimpleWebSocket::WebSocketRet ret = nc->handle_read(msg);
switch (ret)
{
case SimpleWebSocket::WEBSOCKET_CONNECTED:
{
std::string path;
doselect = false;
nc->get_path(path);
printf("WebSocket connected! path = '%s'\n",
path.c_str());
msg.Clear();
msg.set_type(proxyTcp::PMT_PROTOVERSION);
msg.set_sequence(0);
msg.mutable_protover()->set_version(1);
nc->sendMessage(msg);
break;
}
case SimpleWebSocket::WEBSOCKET_NO_MESSAGE:
// go round again
doselect = true;
break;
case SimpleWebSocket::WEBSOCKET_MESSAGE:
doselect = false;
switch (msg.type())
{
case proxyTcp::PMT_PROTOVERSION:
printf("remote proto version = %d\n",
msg.protover().version());
break;
case proxyTcp::PMT_CLOSING:
printf("remote side is closing, so we are too\n");
done = true;
break;
case proxyTcp::PMT_DATA:
{
printf("got data length %d\n",
(int) msg.data().data().size());
pthread_mutex_lock(&mutex);
for (int ind = 0; ind < conns_pos; ind++)
if (ind != pos && conns[ind] != NULL)
{
conns[ind]->sendMessage(msg);
}
pthread_mutex_unlock(&mutex);
break;
}
case proxyTcp::PMT_PING:
printf("got ping\n");
break;
default:
printf("msg.type() = %d\n", msg.type());
}
break;
case SimpleWebSocket::WEBSOCKET_CLOSED:
printf("WebSocket closed!\n");
done = true;
break;
}
}
printf("closing connection\n");
pthread_mutex_lock(&mutex);
conns[pos] = NULL;
pthread_mutex_unlock(&mutex);
delete nc;
return NULL;
}
|
unlicense
|
larjen/modulaise
|
modulaise/boilerplates/modules/bla_blank/html_foot_10/index.html
|
124
|
<?php ModulaiseController::printComment("__MODULE_SHORTNAME__-__MODULE_LONGNAME__/html_foot_10/index.html: Says, hi!"); ?>
|
unlicense
|
austinhaws/custom-bracket
|
public/js/views/bracket-round.js
|
2838
|
var GamesList = React.createClass({
getInitialState: function() {
return {
games: this.props.initialGames
};
},
scoreChanged: function(gameId, teamNumber, score) {
var game = this.state.games.filter(function(game) {
return game.id == gameId;
})[0];
game['pool_entry_' + teamNumber + '_score'] = score;
this.setState({games:this.state.games});
},
saveGames: function() {
$.ajax({
url: 'admin/bracket/score/save',
dataType: 'json',
data: csrf({games: this.state.games}),
cache: false,
method: 'post',
success: function(data) {
// show a spinner instead
alert('saved');
}.bind(this),
});
},
render: function() {
var that = this;
var games = this.state.games.map(function(game) {
return (
<Game game={game} teams={that.props.teams} rolls={that.props.rolls} key={game.id} scoreChanged={that.scoreChanged}/>
);
});
return (
<div>
<h2>Round {this.props.round}</h2>
{games}
<button onClick={this.saveGames}>Save</button>
</div>
);
}
});
var Game = React.createClass({
getInitialState : function() {
if (!this.props.game.pool_entry_1_score) {
this.props.game.pool_entry_1_score = '';
}
if (!this.props.game.pool_entry_2_score) {
this.props.game.pool_entry_2_score = '';
}
return this.props.game;
},
scoreChanged: function(e) {
this.props.scoreChanged(this.state.id, e.target.dataset.team, e.target.value);
},
render: function() {
var team1Name;
var team2Name;
var state = this.state;
this.props.teams.forEach(function(team) {
if (team.id == state.pool_entry_1_id) {
team1Name = team.name;
}
if (team.id == state.pool_entry_2_id) {
team2Name = team.name;
}
});
var team1Roll, team2Roll;
this.props.rolls.forEach(function(roll) {
if (roll.rank == state.pool_entry_1_rank) {
team1Roll = roll.roll;
}
if (roll.rank == state.pool_entry_2_rank) {
team2Roll = roll.roll;
}
});
return (
<div className="game">
<div className="team"><div className="team-name">{team1Name} ({this.state.pool_entry_1_rank} : {team1Roll})</div> <input type="text" value={this.state.pool_entry_1_score} onChange={this.scoreChanged} data-team="1"/></div>
<div className="team"><div className="team-name">{team2Name} ({this.state.pool_entry_2_rank} : {team2Roll})</div> <input type="text" value={this.state.pool_entry_2_score} onChange={this.scoreChanged} data-team="2"/></div>
</div>
)
}
});
var teams = globals.pools[0].teams.concat(globals.pools[1].teams.concat(globals.pools[2].teams.concat(globals.pools[3].teams.concat())));
ReactDOM.render(
<div>
<a href={'admin/bracket/' + globals.bracket.id}>Back To Bracket</a>
<GamesList initialGames={globals.games} round={globals.round} teams={teams} rolls={globals.rolls}/>
</div>,
document.getElementById('bracket-round')
);
|
unlicense
|
guilhermeasg/outspeak
|
models/User.js
|
2102
|
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
facebook: String,
twitter: String,
google: String,
github: String,
instagram: String,
linkedin: String,
tokens: Array,
profile: {
name: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
picture: { type: String, default: '' }
},
/*
* Data related to the Cards.
* This should be moved to a separate table
* as soon more than one language is supported
*/
cardsLastGenerated: Date, //have we generated cards for this user today
lastWordUsed: { type: Number, default: 0 }, //last word offset from database
resetPasswordToken: String,
resetPasswordExpires: Date
});
/**
* Password hashing Mongoose middleware.
*/
userSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) { return next(); }
bcrypt.genSalt(5, function(err, salt) {
if (err) { return next(err); }
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) { return next(err); }
user.password = hash;
next();
});
});
});
/**
* Helper method for validationg user's password.
*/
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) { return cb(err); }
cb(null, isMatch);
});
};
/**
* Helper method for getting user's gravatar.
*/
userSchema.methods.gravatar = function(size) {
if (!size) { size = 200; }
if (!this.email) {
return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';
}
var md5 = crypto.createHash('md5').update(this.email).digest('hex');
return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';
};
module.exports = mongoose.model('User', userSchema);
|
unlicense
|
jsanders/work-throughs
|
asm-step-by-step/listings/chapter9/hexdump1/hexdump1.asm
|
3507
|
; Executable name : hexdump1
; Version : 1.0
; Created date : 4/4/2009
; Last update : 4/4/2009
; Author : Jeff Duntemann
; Description : A simple program in assembly for Linux, using NASM 2.05,
; demonstrating the conversion of binary values to hexadecimal strings.
; It acts as a very simple hex dump utility for files, though without the
; ASCII equivalent column.
;
; Run it this way:
; hexdump1 < (input file)
;
; Build using these commands:
; nasm -f elf -g -F stabs hexdump1.asm
; ld -o hexdump1 hexdump1.o
;
SECTION .bss ; Section containing uninitialized data
BUFFLEN equ 16 ; We read the file 16 bytes at a time
Buff: resb BUFFLEN ; Text buffer itself
SECTION .data ; Section containing initialised data
HexStr: db " 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",10
HEXLEN equ $-HexStr
Digits: db "0123456789ABCDEF"
SECTION .text ; Section containing code
global _start ; Linker needs this to find the entry point!
_start:
nop ; This no-op keeps gdb happy...
; Read a buffer full of text from stdin:
Read:
mov eax,3 ; Specify sys_read call
mov ebx,0 ; Specify File Descriptor 0: Standard Input
mov ecx,Buff ; Pass offset of the buffer to read to
mov edx,BUFFLEN ; Pass number of bytes to read at one pass
int 80h ; Call sys_read to fill the buffer
mov ebp,eax ; Save # of bytes read from file for later
cmp eax,0 ; If eax=0, sys_read reached EOF on stdin
je Done ; Jump If Equal (to 0, from compare)
; Set up the registers for the process buffer step:
mov esi,Buff ; Place address of file buffer into esi
mov edi,HexStr ; Place address of line string into edi
xor ecx,ecx ; Clear line string pointer to 0
; Go through the buffer and convert binary values to hex digits:
Scan:
xor eax,eax ; Clear eax to 0
; Here we calculate the offset into the line string, which is ecx X 3
mov edx,ecx ; Copy the pointer into line string into edx
; shl edx,1 ; Multiply pointer by 2 using left shift
; add edx,ecx ; Complete the multiplication X3
lea edx,[edx*2+edx]
; Get a character from the buffer and put it in both eax and ebx:
mov al,byte [esi+ecx] ; Put a byte from the input buffer into al
mov ebx,eax ; Duplicate the byte in bl for second nybble
; Look up low nybble character and insert it into the string:
and al,0Fh ; Mask out all but the low nybble
mov al,byte [Digits+eax] ; Look up the char equivalent of nybble
mov byte [HexStr+edx+2],al ; Write the char equivalent to line string
; Look up high nybble character and insert it into the string:
shr bl,4 ; Shift high 4 bits of char into low 4 bits
mov bl,byte [Digits+ebx] ; Look up char equivalent of nybble
mov byte [HexStr+edx+1],bl ; Write the char equivalent to line string
; Bump the buffer pointer to the next character and see if we're done:
inc ecx ; Increment line string pointer
cmp ecx,ebp ; Compare to the number of characters in the buffer
jna Scan ; Loop back if ecx is <= number of chars in buffer
; Write the line of hexadecimal values to stdout:
mov eax,4 ; Specify sys_write call
mov ebx,1 ; Specify File Descriptor 1: Standard output
mov ecx,HexStr ; Pass offset of line string
mov edx,HEXLEN ; Pass size of the line string
int 80h ; Make kernel call to display line string
jmp Read ; Loop back and load file buffer again
; All done! Let's end this party:
Done:
mov eax,1 ; Code for Exit Syscall
mov ebx,0 ; Return a code of zero
int 80H ; Make kernel call
|
unlicense
|
ilucin/relsem-bridge-frontend
|
app/views/editor/editor.js
|
9433
|
define([
'app',
'collections/tables',
'collections/connections',
'collections/rdf-entities',
'collections/rdf-attributes',
'models/connection',
'models/table',
'views/abstract/base',
'views/shared/message-dialog',
'views/editor/connection-form',
'views/editor/rdf-entity-list',
'views/editor/rdf-attribute-list',
'views/editor/table-list',
'views/editor/table'
], function(
app,
TablesCollection,
ConnectionsCollection,
RdfEntitiesCollection,
RdfAttributesCollection,
ConnectionModel,
TableModel,
BaseView,
MessageDialogView,
ConnectionFormView,
RdfEntityListView,
RdfAttributeListView,
TableListView,
TableView
) {
'use strict';
var EditorView = BaseView.extend({
className: 'editor container',
template: app.fetchTemplate('editor/editor'),
events: {
'click .entity-breadcrumb': 'onEntityBreadcrumbClick',
'click .rdf-settings-icon': 'onRdfSettingsIconClick',
'change .rdf-settings input': 'onRdfSettingsInputChange'
},
settingsSlideSpeed: 150,
initialize: function(options) {
options = options || {};
this.conn = new ConnectionModel();
this.table = new TableModel();
this.tables = new TablesCollection();
this.connections = new ConnectionsCollection();
this.rdfEntities = new RdfEntitiesCollection();
this.rdfAttributes = new RdfAttributesCollection();
this.connectionForm = new ConnectionFormView({
connections: this.connections,
conn: this.conn
});
this.rdfEntityListView = new RdfEntityListView({
collection: this.rdfEntities
});
this.rdfAttributeListView = new RdfAttributeListView({
collection: this.rdfAttributes
});
this.tableView = new TableView({
model: this.table,
rdfAttributes: this.rdfAttributes,
rdfEntities: this.rdfEntities
});
this.tableListView = new TableListView({
collection: this.tables
});
this.tables.fetch({
reset: true
});
window.tables = this.tables;
$(document).on('click', _.bind(function(e) {
if (!$(e.target).hasClass('rdf-settings')) {
this.$('.rdf-settings').slideUp(this.settingsSlideSpeed);
}
}, this));
},
setListeners: function() {
BaseView.prototype.setListeners.call(this);
this.listenTo(this.conn, 'connect:success', this.onConnect, this);
this.listenTo(this.conn, 'disconnect', this.onDisconnect, this);
this.listenTo(this.rdfEntityListView, 'selected-item:change', this.onRdfEntityListSelectedItemChange, this);
this.listenTo(this.tableListView, 'item:select', this.onTableListItemSelect, this);
this.listenTo(this.rdfEntityListView, 'item:branch', this.onRdfEntityListItemBranch, this);
this.listenTo(this.table, 'save:success', this.onTableSaveSuccess, this);
this.listenTo(this.table, 'save:error', this.defaultActionErrorHandler, this);
this.listenTo(this.table, 'save:validationError', this.onTableValidationError, this);
this.listenTo(this.table, 'delete:success', this.onTableDeleteSuccess, this);
this.listenTo(this.table, 'delete:error', this.defaultActionErrorHandler, this);
this.listenTo(this.rdfEntities, 'change:parents', this.onRdfEntitiesParentsChange, this);
},
onConnect: function() {
this.$('.editor-rdf').slideDown().addClass('collapsed');
this.$('.editor-rdf-title .collapse-arrow').addClass('collapsed');
this.$('.editor-connection').slideUp().removeClass('collapsed');
this.$('.editor-connection-title .collapse-arrow').removeClass('collapsed');
this.rdfEntities.setEndpoint(this.conn.get('endpoint'));
this.rdfAttributes.setEndpoint(this.conn.get('endpoint'));
this.rdfEntities.fetch();
},
onDisconnect: function() {
this.$('.editor-rdf').slideUp().removeClass('collapsed');
this.$('.editor-rdf-title .collapse-arrow').removeClass('collapsed');
this.$('.editor-connection').slideDown().addClass('collapsed');
this.$('.editor-connection-title .collapse-arrow').addClass('collapsed');
this.rdfEntities.reset();
this.rdfAttributes.reset();
},
render: function() {
this.$el.html(this.template({
attributesLimit: this.rdfAttributes.limit,
attributesOffset: this.rdfAttributes.offset,
attributesSort: this.rdfAttributes.sorting,
entitiesLimit: this.rdfEntities.limit,
entitiesOffset: this.rdfEntities.offset,
entitiesLoadRootAttributes: this.rdfEntities.loadRootAttributes
}));
this.$('.editor-connection-form').html(this.connectionForm.render().$el);
this.$('.editor-rdf-entity-list-container').html(this.rdfEntityListView.render().$el);
this.$('.editor-rdf-attribute-list-container').html(this.rdfAttributeListView.render().$el);
this.$('.editor-table-list-container').html(this.tableListView.render().$el);
this.$('.editor-table-container').html(this.tableView.render().$el);
this.$('.editor-rdf').resizable({
handles: 's',
minHeight: 100,
maxHeight: 500
});
this.$('.editor-connection-title').on('click', _.bind(function() {
if (this.$('.editor-connection').hasClass('collapsed')) {
this.$('.editor-connection').slideUp().removeClass('collapsed');
} else {
this.$('.editor-connection').slideDown().addClass('collapsed');
}
this.$('.editor-connection-title .collapse-arrow').toggleClass('collapsed');
}, this));
this.$('.editor-rdf-title').on('click', _.bind(function() {
if (this.conn.get('connected')) {
if (this.$('.editor-rdf').hasClass('collapsed')) {
this.$('.editor-rdf').slideUp().removeClass('collapsed');
} else {
this.$('.editor-rdf').slideDown().addClass('collapsed');
}
this.$('.editor-rdf-title .collapse-arrow').toggleClass('collapsed');
}
}, this));
this.$('.editor-relational-title').on('click', _.bind(function() {
if (this.$('.editor-relational').hasClass('collapsed')) {
this.$('.editor-relational').slideUp().removeClass('collapsed');
} else {
this.$('.editor-relational').slideDown().addClass('collapsed');
}
this.$('.editor-relational-title .collapse-arrow').toggleClass('collapsed');
}, this));
this.setListeners();
return this;
},
onRdfEntitiesParentsChange: function() {
var parents = this.rdfEntities.getParentLabels();
var $breadcrumbs = this.$('.entity-breadcrumbs').html('Entities: ');
for (var i = 0; i < this.rdfEntities.parents.length; i++) {
if (i > 0) {
$breadcrumbs.append('<img class="breadcrumb-divider" src="assets/images/arrow_right.png"></img>');
}
var en = this.rdfEntities.parents[i];
var $en = $('<li>').addClass('entity-breadcrumb').attr('data-uri', en.get('uri')).html(en.get('label'));
$breadcrumbs.append($en);
}
},
onRdfEntityListSelectedItemChange: function(rdfEntity) {
this.rdfAttributes.setRdfEntity(rdfEntity);
if (this.rdfEntities.shouldLoadAttributes()) {
this.rdfAttributes.fetch();
}
},
onTableListItemSelect: function(tableListItem, tableModel) {
this.table = tableModel;
this.tableView.setModel(tableModel);
this.table.loadTableDefinition();
},
onTableDelete: function(model) {
(new MessageDialogView()).showMessage('', 'Your relational table has been removed');
this.tables.remove(this.tables.findWhere({
name: model.get('name')
}));
},
onTableSaveSuccess: function(model) {
(new MessageDialogView()).showSuccessMessage('Your relational table has been saved');
this.tables.add(model);
},
onEntityBreadcrumbClick: function(e) {
var uri = $(e.target).attr('data-uri');
this.rdfEntities.setParentEntityUri(uri);
},
onRdfSettingsIconClick: function(e) {
var $sett = $(e.target).find('.rdf-settings');
if ($sett.css('display') === 'block') {
$sett.slideUp(this.settingsSlideSpeed);
} else {
$sett.slideDown(this.settingsSlideSpeed);
}
e.stopPropagation();
},
onRdfEntityListItemBranch: function(itemView, rdfEntity) {
this.rdfEntities.setParentEntity(rdfEntity);
},
onRdfSettingsInputChange: function(e) {
var $input = $(e.target);
if ($input.attr('data-type') === 'entities') {
if ($input.attr('data-property') === 'limit') {
this.rdfEntities.setLimit(parseInt($input.val(), 10));
} else if ($input.attr('data-property') === 'offset') {
this.rdfEntities.setOffset(parseInt($input.val(), 10));
} else {
this.rdfEntities.setLoadRootAttributes($input.prop('checked'));
}
} else {
if ($input.attr('data-property') === 'limit') {
this.rdfAttributes.setLimit(parseInt($input.val(), 10));
} else if ($input.attr('data-property') === 'sort') {
this.rdfAttributes.setSort($input.prop('checked'));
} else {
this.rdfAttributes.setOffset(parseInt($input.val(), 10));
}
}
this.$('.rdf-settings').slideUp(this.settingsSlideSpeed);
}
});
return EditorView;
});
|
unlicense
|
jerryasher/hackerrank30
|
0/Helloworld.java
|
588
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Helloworld {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); // use the Scanner class to read from stdin
String inputString = scan.nextLine(); // read a line of input and save it to a variable
scan.close(); // close the scanner
// Your first line of output goes here
System.out.println("Hello, World.");
// Write the second line of output
System.out.println(inputString);
}
}
|
unlicense
|
prjemian/lake
|
lake.c
|
18720
|
/** @file lake.c
* @brief lake-jemian desmearing method
*/
#define VERSION_INFORMATION "svnid: $Id$"
/*
See the README for more information.
CITATION
Use this reference to cite this code in a publication.
PhD Thesis, 1990, Northwestern University,
Evanston, IL, USA, Pete R. Jemian.
http://jemian.org/pjthesis.pdf
PURPOSE
This program applies the iterative desmearing technique of Lake
to small-angle scattering data.
*/
/*****************************************************************
*** global definitions ***
*****************************************************************/
#define LakeUnit (1)
#define LakeFast (2)
#define LakeChi2 (3)
#define InfItr (10000)
/*****************************************************************
*** global variables ***
*****************************************************************/
int NumPts; /* number of data points read in */
double *q; /* q : scattering vector, horizontal axis */
double *E, *dE; /* E, dE : experimental intensity and estimated error */
double *S; /* S : re-smeared intensity */
double *C, *dC; /* C, dC : corrected intensity and estimated error */
double *resid; /* resid : normalized residuals, = (E-S)/dE */
int NumItr = InfItr; /* maximum number of iterations to run */
char InFile[256], OutFil[256];
double sLengt = 1.0; /* slit length, as defined by Lake */
double sFinal = 1.0; /* to start evaluating the constants for extrapolation */
int mForm = 1; /* model final data as a constant */
int LakeForm = 2; /* shows the fastest convergence most times */
double fSlope; /* linear coefficient of data fit */
double fIntercept; /* constant coefficient of data fit */
/*****************************************************************
*** subroutines & functions ***
*****************************************************************/
double Plengt (double x);
double FindIc (double x, double y, int NumPts, double *q, double *C);
/* from toolbox.c */
void AskString (char *question, char *answer);
void AskDouble (char *question, double *answer);
void AskInt (char *question, int *answer);
char AskYesOrNo (char *question, char standard);
/*****************************************************************
*** #includes ***
*****************************************************************/
#ifdef THINK_C
#include <console.h>
extern long _fcreator;
#endif
#ifdef __MWERKS__
#include <sioux.h>
#if TARGET_OS_WIN32
#include <WinSIOUX.h>
#endif
#endif
#include <math.h>
#include "recipes.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/**
* Get information about the desmearing parameters.
* This is designed to be independent of wavelength
* or radiation-type (i.e. neutrons, X rays, etc.)
*/
void GetInf (
char *InFile,
char *OutFil,
double *sLengt,
double *sFinal,
int *NumItr,
int MaxItr,
int *mForm,
int *LakeForm)
{
InFile[0] = (char) 0;
AskString ("What is the input data file name? <Quit>", InFile);
if (!InFile[0]) return;
do
AskString ("What is the output data file?", OutFil);
while (!strcmp (InFile, OutFil));
AskDouble ("What is the slit length (x-axis units)?", sLengt);
printf (
"Extrapolation forms to avoid truncation-error.\n"
" 1 = flat background, I(q) = B\n"
" 2 = linear, I(q) = b + q * m\n"
" 3 = power law, I(q) = b * q^m\n"
" 4 = Porod law, I(q) = Cp + Bkg / q^4\n"
);
AskInt ("Which form?", mForm);
AskDouble ("What X to begin evaluating extrapolation (x-axis units)?",
sFinal);
AskInt ("How many iteration(s)? (10000 = infinite)", NumItr);
printf (
" Weighting methods for iterative corrections:\n"
" Correction = weight * (MeasuredI - SmearedI)\n"
" #1) weight = 1.0\n"
" #2) weight = CorrectedI / SmearedI\n"
" #3) weight = 2*SQRT(ChiSqr(0) / ChiSqr(i))\n"
);
AskInt ("Which method?", LakeForm);
}
/**
* Estimate the error on Z based on data point scatter and
* previous error values and smooth that estimate.
*/
void FixErr (int n, double *x, double *y, double *dy, double *z, double *dz)
{
int i, j;
double slope, intercept, zNew, w1, w2;
/* Error proportional to input error */
for (i = 1; i <= n; i++)
dz[i] = z[i] * dy[i] / y[i];
/*
* Error based on scatter of desmeared data points.
* Determine this by fitting a line to the points
* i-1, i, i+1 and take the difference. Add this to dz.
*/
SumClr ();
SumAdd (x[1], z[1]);
SumAdd (x[2], z[2]);
SumAdd (x[3], z[3]);
SumLR (&slope, &intercept);
dz[1] += fabs (intercept + slope*x[1] - z[1]);
dz[2] += fabs (intercept + slope*x[2] - z[2]);
for (i = 3; i < n; i++) {
SumClr ();
SumAdd (x[i-1], z[i-1]);
SumAdd (x[i], z[i]);
SumAdd (x[i+1], z[i+1]);
SumLR (&slope, &intercept);
zNew = intercept + slope * x[i];
dz[i] += fabs (zNew - z[i]);
}
dz[n] += fabs (intercept + slope*x[n] - z[n]);
/*
* Smooth the error by a 3-point moving average filter.
* Do this 5 times. Don't smooth the end points.
* Weight the data points by distance^2 (as a penalty)
* using the function weight(u,v)=(1 - |1 - u/v|)**2
* By its definition, weight(x0,x0) == 1.0. I speed
* computation using this definition. Why I can't use
* this definition of weight as a statement function
* with some compilers is beyond me!
* Smoothing is necessary to increase the error estimate
* for some grossly under-estimated errors.
*/
for (j = 1; j <= 5; j++) {
for (i = 2; i < n; i++) {
w1 = SQR(1 - fabs (1 - (x[i-1]/x[i])));
w2 = SQR(1 - fabs (1 - (x[i+1]/x[i])));
dz[i] = (w1 * dz[i-1] + dz[i] + w2 * dz[i+1])
/ (w1 + 1.0 + w2);
}
}
}
/**
* Calculate the constants for an extrapolation fit
* from all the data that satisfy x(i) >= sFinal.
*/
void Prep (double *x, double *y, double *dy, int NumPts)
{
double h4;
int i;
SumClr ();
for (i = 1; i < NumPts; i++) {
if (x[i] >= sFinal) {
switch (mForm) {
case 1:
SwtAdd (x[i], y[i], dy[i]); /* weighted */
break;
case 2:
SumAdd (x[i], y[i]); /* un-weighted */
break;
case 3:
SumAdd (log(x[i]), log(y[i])); /* un-weighted */
break;
case 4:
h4 = SQR(SQR(x[i]));
SwtAdd (h4, y[i]*h4, dy[i]*h4); /* weighted */
break;
}
}
}
switch (mForm) {
case 1:
MeanXY (&fSlope, &fIntercept);
fSlope = 0.0; /* flat background */
break;
case 2:
case 3:
case 4:
SumLR (&fSlope, &fIntercept);
break;
}
}
/**
* Smear the data of C(q) into S using the slit-length
* weighting function "Plengt" and a power-law extrapolation
* of the data to avoid truncation errors. Assume that
* Plengt goes to zero for l > lo (the slit length).
* Also assume that the slit length function is symmetrical
* about l = zero.
* This routine is written so that if "Plengt" is changed
* (for example) to a Gaussian, that no further modification
* is necessary to the integration procedure. That is,
* this routine will integrate the data out to "lo".
*/
void Smear (double *S, int NumPts, double *q, double *C, double *dC)
{
double *x, *w, hLo, hNow, sum, ratio;
int i, j, k;
x = dvector ((long) 1, (long) NumPts);
w = dvector ((long) 1, (long) NumPts);
Prep (q, C, dC, NumPts-2); /* get coefficients */
switch (mForm) {
case 1:
#ifdef __MWERKS__
printf ("%25s fit: I = %g\n",
"constant background", fIntercept);
#else
printf ("%25s fit: I = %lg\n",
"constant background", fIntercept);
#endif
break;
case 2:
#ifdef __MWERKS__
printf ("%25s fit: I = (%g) + q*(%g)\n",
"linear", fIntercept, fSlope);
#else
printf ("%25s fit: I = (%lg) + q*(%lg)\n",
"linear", fIntercept, fSlope);
#endif
break;
case 3:
#ifdef __MWERKS__
printf ("%25s fit: I = (%g) * q^(%g)\n",
"Power law", fIntercept, fSlope);
#else
printf ("%25s fit: I = (%lg) * q^(%lg)\n",
"Power law", fIntercept, fSlope);
#endif
break;
case 4:
#ifdef __MWERKS__
printf ("%25s fit: I = (%g) + (%g)/q^4\n",
"Power law", fIntercept, fSlope);
#else
printf ("%25s fit: I = (%lg) + (%lg)/q^4\n",
"Power law", fIntercept, fSlope);
#endif
break;
}
hLo = q[1];
ratio = sLengt / (q[NumPts] - hLo);
for (i = 1; i <= NumPts; i++) {
x[i] = ratio * (q[i] - hLo); /* values for "l" */
w[i] = Plengt (x[i]); /* probability at "l" */
}
w[1] *= x[2] - x[1];
for (i = 2; i < NumPts; i++)
w[i] *= x[i+1] - x[i-1]; /* step sizes */
w[NumPts] = x[NumPts] - x[NumPts-1];
for (i = 1; i <= NumPts; i++) { /* evaluate each integral ... */
Spinner (i);
hNow = q[i]; /* ... using trapezoid rule */
sum = w[1] * FindIc (hNow, x[1], NumPts, q, C);
for (k = 2; k < NumPts; k++)
sum += w[k] * FindIc (hNow, x[k], NumPts, q, C);
S[i] = sum + w[NumPts] * FindIc(hNow, x[NumPts], NumPts, q, C);
}
free_dvector (x, 1, NumPts);
free_dvector (w, 1, NumPts);
}
/**
* Here is the definition of the slit-length weighting function.
* It is defined for a rectangular slit of length 2*sLengt
* and probability 1/(2*sLengt). It is zero elsewhere.
* It is not necessary to change the limit of the integration
* if the functional form here is changed. You may, however,
* need to ask the user for more parameters. Pass these
* around to the various routines through the use of the
* /PrepCm/ COMMON block.
*/
double Plengt (double x)
{
return (fabs(x) > sLengt) ? 0.0 : 0.5 / sLengt;
}
#define GetIt(x,x1,y1,x2,y2) (y1 + (y2-y1) * (x-x1) / (x2-x1))
/**
* Determine the "corrected" intensity at u = SQRT (x*x + y*y)
* Note that only positive values of "u" will be searched!
*/
double FindIc (double x, double y, int NumPts, double *q, double *C)
{
double u, value;
int iTest, iLo, iHi;
u = sqrt (x*x + y*y); /* circularly symmetric */
/*
* dhunt(q, (unsigned long) NumPts, u, &iTest);
* iTest++;
*/
BSearch (u, q, NumPts, &iTest); /* find index */
iLo = iTest - 1;
iHi = iLo + 1;
if (iTest < 1) {
printf ("\n\n Bad value of U or array Q in routine FindIc\n");
exit (0);
}
if (iTest <= NumPts) {
if (u == q[iLo])
value = C[iLo]; /* exactly! */
else /* linear interpolation */
value = GetIt(u, q[iLo],C[iLo], q[iHi],C[iHi]);
} else { /* functional extrapolation */
switch (mForm) {
case 1:
value = fIntercept;
break;
case 2:
value = fIntercept + fSlope * u;
break;
case 3:
value = exp(fIntercept + fSlope * log(u));
break;
case 4:
value = fIntercept + fSlope / SQR(SQR(u));
break;
}
}
return value;
}
/**
* Do the work of the Lake method.
*/
void DesmearData ()
{
double ChiSqr, ChiSq0, weighting;
int i, j, iteration;
char reply[256], trimReply[256];
printf ("Number of points read: %d\n", NumPts);
printf ("Output file: %s\n", OutFil);
#ifdef __MWERKS__
printf ("Slit length: %g (x-axis units)\n", sLengt);
printf ("Final form approx. will begin at: %g (x-axis units)\n", sFinal);
#else
printf ("Slit length: %lg (x-axis units)\n", sLengt);
printf ("Final form approx. will begin at: %lg (x-axis units)\n", sFinal);
#endif
printf ("Final form approximation: ");
switch (mForm) {
case 1: printf ("flat background, I(q) = B\n"); break;
case 2: printf ("linear, I(h) = b + q * m\n"); break;
case 3: printf ("power law, I = b * q^m\n"); break;
case 4: printf ("Porod, I = Cp + B / q^4\n"); break;
}
printf ("Number of iterations: ");
if (NumItr < InfItr)
printf ("%d\n", NumItr);
else
printf ("infinite\n");
printf ("Iterative weighting: ");
switch (LakeForm) {
case LakeUnit: printf ("unity\n"); break;
case LakeFast: printf ("fast\n"); break;
case LakeChi2: printf ("ChiSqr\n"); break;
}
/*
* To start Lake's method, assume that the 0-th approximation
* of the corrected intensity is the measured intensity.
*/
for (i = 1; i <= NumPts; i++) {
C[i] = E[i];
dC[i] = dE[i];
}
printf ("\n Smearing to get first approximation...\n");
fflush (stdout);
Smear (S, NumPts, q, C, dC);
ChiSqr = 0.0; /* find the ChiSqr */
for (j = 1; j <= NumPts; j++)
ChiSqr += SQR((S[j] - E[j])/dE[j]);
ChiSq0 = ChiSqr; /* remember the first one */
iteration = 0;
do {
#ifdef __MWERKS__
#ifdef __INTEL__
WinSIOUXclrscr();
#endif
#endif
iteration++;
if (NumItr < InfItr)
printf ("\n Iteration #%d of %d iterations\n",
iteration, NumItr);
else
printf ("\n Iteration #%d\n", iteration);
printf ("Applying the iterative correction ...\n");
fflush (stdout);
switch (LakeForm) {
case LakeUnit: weighting = 1.0; break;
case LakeChi2: weighting = 2*sqrt(ChiSq0/ChiSqr); break;
}
for (j = 1; j <= NumPts; j++) {
if (LakeForm == LakeFast)
weighting = C[j] / S[j];
C[j] += weighting * (E[j] - S[j]);
}
printf ("Examining scatter to calculate the errors ...\n");
fflush (stdout);
FixErr (NumPts, q, E, dE, C, dC);
printf ("Smearing again ...\n");
fflush (stdout);
Smear (S, NumPts, q, C, dC);
ChiSqr = 0.0;
for (j = 1; j <= NumPts; j++) {
resid[j] = (S[j] - E[j]) / dE[j];
ChiSqr += SQR(resid[j]);
}
printf ("\n Residuals plot for iteration #%d\n", iteration);
ResPlot (NumPts-1, resid);
#ifdef __MWERKS__
printf ("ChiSqr = %g for #%d points\n", ChiSqr, NumPts);
#else
printf ("ChiSqr = %lg for #%d points\n", ChiSqr, NumPts);
#endif
fflush (stdout);
if (NumItr >= InfItr) {
if (AskYesOrNo ("Save this data?", 'n') == 'y') {
printf ("What file name? (%s) ==> ", OutFil);
fgets (reply, 256, stdin);
/*
* need a string trim function here
On Windows under CodeWarrior, the user
presses <return> and the code receives
the EOL symbols. Got to fix this.
*/
/* printf ("(%s,%d) <%s>\n", __FUNCTION__, __LINE__, reply); */
strtrim(reply, trimReply, NULL);
strcpy(reply, trimReply);
/* printf ("(%s,%d) <%s>\n", __FUNCTION__, __LINE__, reply); */
if (!reply[0] || (reply[0] == '\n'))
SavDat (OutFil, q, C, dC, NumPts);
else
SavDat (reply, q, C, dC, NumPts);
}
if (AskYesOrNo ("Continue iterating?", 'y') == 'n')
iteration = InfItr;
fflush (stdout);
}
} while (iteration < NumItr);
if (NumItr < InfItr)
SavDat (OutFil, q, C, dC, NumPts);
printf ("Plot of log(desmeared intensity) vs. q ...\n");
fflush (stdout);
for (i = 1; i <= NumPts; i++)
C[i] = log (fabs (C[i]));
Plot (NumPts, q, C);
fflush (stdout);
printf ("Same, but now log-log ...\n");
for (i = 1; i <= NumPts; i++)
q[i] = log (fabs (q[i]));
Plot (NumPts, q, C);
fflush (stdout);
}
/**
* CLI program starts here.
*/
main ()
{
#ifdef THINK_C
cecho2file("Lake.log", 0, stdout);
_fcreator = 'QKPT'; /* output file owner is Kaleidagraph */
#endif
#ifdef __MWERKS__
SIOUXSettings.autocloseonquit = 0; /* don't automatically exit */
SIOUXSettings.asktosaveonclose = 0; /* don't ask to save window */
SIOUXSettings.showstatusline = 0; /* don't show the status line */
#endif
printf ("\n");
printf (" %s, by Pete R. Jemian\n", VERSION_INFORMATION);
printf (" This executable was built %s, %s\n\n", __DATE__, __TIME__);
printf (" SAS data desmearing using the iterative technique of JA Lake.\n");
printf (" P.R. Jemian; Ph.D. Thesis (1990) Northwestern University, Evanston, IL, USA.\n\n");
printf (" J.A. Lake; ACTA CRYST 23 (1967) 191-194.\n\n");
/*
* console_options.pause_atexit = 0;
*/
do {
GetInf (InFile, OutFil, &sLengt, &sFinal,
&NumItr, InfItr, &mForm, &LakeForm);
if (!InFile[0]) break; /* no file name given, so exit */
if (NumItr == 0) NumItr = InfItr;
fflush (stdout);
printf ("Input file: %s\n", InFile);
GetDat (InFile, &q, &E, &dE, &NumPts);
C = dvector ((long) 1, (long) NumPts);
dC = dvector ((long) 1, (long) NumPts);
S = dvector ((long) 1, (long) NumPts);
resid = dvector ((long) 1, (long) NumPts);
if (NumPts == 0) break;
if (sFinal > q[NumPts-1]) break;
fflush (stdout);
DesmearData ();
fflush (stdout);
free_dvector (q, 1, NumPts);
free_dvector (E, 1, NumPts);
free_dvector (dE, 1, NumPts);
free_dvector (C, 1, NumPts);
free_dvector (dC, 1, NumPts);
free_dvector (S, 1, NumPts);
free_dvector (resid, 1, NumPts);
} while (InFile[0]);
printf ("\n");
return (0);
}
|
unlicense
|
Themakew/Grupo8
|
EPF/Publicacao/openup/guidances/concepts/transition_phase_DD5986E5.html
|
7217
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="pt" xml:lang="pt" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Concept: Fase de Transição</title>
<meta name="uma.type" content="Concept">
<meta name="uma.name" content="transition_phase">
<meta name="uma.presentationName" content="Fase de Transição">
<meta name="element_type" content="concept">
<meta name="filetype" content="description">
<meta name="role" content="none">
<link rel="StyleSheet" href="./../../../css/default.css" type="text/css">
<script src="./../../../scripts/ContentPageResource.js" type="text/javascript" language="JavaScript"></script><script src="./../../../scripts/ContentPageSection.js" type="text/javascript" language="JavaScript"></script><script src="./../../../scripts/ContentPageSubSection.js" type="text/javascript" language="JavaScript"></script><script src="./../../../scripts/ContentPageToolbar.js" type="text/javascript" language="JavaScript"></script><script src="./../../../scripts/contentPage.js" type="text/javascript" language="JavaScript"></script><script type="text/javascript" language="JavaScript">
var backPath = './../../../';
var imgPath = './../../../images/';
var nodeInfo=null;
contentPage.preload(imgPath, backPath, nodeInfo, '', false, false, false);
</script>
</head>
<body>
<div id="breadcrumbs"></div>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td valign="top"><a name="Top"></a>
<div id="page-guid" value="__ca5UBOMEduCNqgZdt_OaA"></div>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tr>
<td class="pageTitle" nowrap="true">Concept: Fase de Transição</td><td width="100%">
<div align="right" id="contentPageToolbar"></div>
</td><td width="100%" class="expandCollapseLink" align="right"><a name="mainIndex" href="./../../../index.htm"></a><script language="JavaScript" type="text/javascript" src="./../../../scripts/treebrowser.js"></script></td>
</tr>
</table>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="pageTitleSeparator"><img src="./../../../images/shim.gif" alt="" title="" height="1"></td>
</tr>
</table>
<div class="overview">
<table width="97%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50"><img src="./../../../images/concept.gif" alt="" title=""></td><td>
<table class="overviewTable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top">Esta é a quarta fase do processo, a qual foca na transição do software para o ambiente do cliente e na obtenção da concordância dos Stakeholders de que o desenvolvimento do produto está completo.</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div class="sectionHeading">Relationships</div>
<div class="sectionContent">
<table class="sectionTable" border="0" cellspacing="0" cellpadding="0">
<tr valign="top">
<th class="sectionTableHeading" scope="row">Related Elements</th><td class="sectionTableCell">
<ul>
<li>
<a href="./../../../openup/guidances/concepts/project_lifecycle_203F87.html" guid="_nSfVwCNYEdyCq8v2ZO4QcA">Ciclo de Vida de Projeto</a>
</li>
<li>
<a href="./../../../openup/guidances/concepts/phase_milestones_5678231E.html" guid="_HNxbwMBJEdqSgKaj2SZBmg">Marco de Fase</a>
</li>
</ul>
</td>
</tr>
</table>
</div>
<div class="sectionHeading">Main Description</div>
<div class="sectionContent">
<table class="sectionTable" border="0" cellspacing="0" cellpadding="0">
<tr valign="top">
<td class="sectionTableSingleCell"><p>A finalidade desta fase é assegurar que o software esteja pronto para ser entregue aos usuários.</p>
<p>Existem objetivos na fase de Transição que lhe ajudam a fazer um ajuste-fino na funcionalidade, no desempenho e na qualidade geral do produto beta oriundo da fase precedente <a class="elementlinkwithusertext" href="./../../../openup/guidances/supportingmaterials/references_6CCF393.html#KRO03" guid="_9ToeIB83Edqsvps02rpOOg">[KRO03]</a>:</p>
<ol>
<li>
<p>
<b>Executar o teste Beta para validar se as expectativas dos usuários foram atendidas</b>. Isto normalmente requer algumas atividades de ajuste fino, tais como reparação de erros e melhorias no desempenho e na usabilidade.</p>
</li>
<li>
<p>
<b>Obter a concordância dos stakeholders de que a implantação está completa</b>. Isto pode envolver vários níveis de testes para a aceitação do produto, incluindo testes formais, informais e testes beta.</p>
</li>
<li>
<p>
<b>Melhorar o desempenho de projetos futuros com as lições aprendidas.</b> Documente as lições aprendidas e melhore o ambiente de processos e ferramentas para o projeto.</p>
</li>
</ol>
<h4>
<br />Principais considerações<br />
</h2>
<p>A fase de Transição pode incluir a execução paralela de sistemas antigos e novos, migração de dados, treinamento de usuários e ajustes nos processos de negócio.</p>
<p>A quantidade de iterações na fase de Transição varia de uma iteração (para um sistema simples que necessita principalmente de reparos de pequenos erros), até muitas iterações (para um sistema complexo, envolvendo a adição de características e a execução de atividades) para fazer a transição, no negócio, do uso do sistema antigo para o sistema novo.</p>
<p>Quando os objetivos da fase de Transição são alcançados, o projeto está pronto para ser encerrado. Para alguns produtos, o fim do ciclo de vida do projeto atual pode coincidir com o começo do ciclo de vida do seguinte, conduzindo à nova geração do mesmo produto.</p></td>
</tr>
</table>
</div>
<div class="sectionHeading">More Information</div>
<div class="sectionContent">
<table class="sectionTable" border="0" cellspacing="0" cellpadding="0">
<tr valign="top">
<th class="sectionTableHeading" scope="row">Concepts</th><td class="sectionTableCell">
<ul>
<li>
<a href="./../../../openup/guidances/concepts/project_lifecycle_203F87.html" guid="_nSfVwCNYEdyCq8v2ZO4QcA">Ciclo de Vida de Projeto</a>
</li>
<li>
<a href="./../../../openup/guidances/concepts/core_principle_collaborate_EC5EB51F.html" guid="_KkTIsMp7EdqC_NfSivunjA">Colaborar para alinhar os interesses e compartilhar o entendimento</a>
</li>
<li>
<a href="./../../../openup/guidances/concepts/iteration_C20B1904.html" guid="_lam4ADkBEduxovfWMDsntw">Iteração</a>
</li>
</ul>
</td>
</tr>
</table>
</div>
<table class="copyright" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="copyright"><p>Este programa e o material que o acompanha são disponibilizados sob a<br /> <a href="http://www.eclipse.org/org/documents/epl-v10.php" target="_blank">Eclipse Public License v1.0</a> que acompanha esta distribuição.</p><p/><p>
<a class="elementLink" href="./../../../openup/guidances/supportingmaterials/openup_copyright_C3031062.html" guid="_UaGfECcTEduSX6N2jUafGA">Direitos Autorais do OpenUP</a>.</p></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
<script type="text/javascript" language="JavaScript">
contentPage.onload();
</script>
</html>
|
unlicense
|
mike10004/nbis-upstream
|
misc/nistmeshlab/meshlab/src/external/structuresynth/ssynth/SyntopiaCore/GLEngine/Mesh.cpp
|
4001
|
#include "Mesh.h"
#include "SyntopiaCore/Math/Vector3.h"
#include "../Logging/Logging.h"
using namespace SyntopiaCore::Logging;
using namespace SyntopiaCore::Math;
namespace SyntopiaCore {
namespace GLEngine {
Mesh::Mesh(SyntopiaCore::Math::Vector3f startBase,
SyntopiaCore::Math::Vector3f startDir1 ,
SyntopiaCore::Math::Vector3f startDir2,
SyntopiaCore::Math::Vector3f endBase,
SyntopiaCore::Math::Vector3f endDir1 ,
SyntopiaCore::Math::Vector3f endDir2) :
startBase(startBase), startDir1(startDir1), startDir2(startDir2),
endBase(endBase), endDir1(endDir1), endDir2(endDir2)
{
/// Bounding Mesh (not really accurate)
from = startBase;
to = endBase;
};
Mesh::~Mesh() { };
void Mesh::draw() const {
// --- TODO: Rewrite - way to many state changes...
glPushMatrix();
glTranslatef( startBase.x(), startBase.y(), startBase.z() );
GLfloat col[4] = {0.0f, 1.0f, 1.0f, 0.1f} ;
glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, col );
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
Vector3f O(0,0,0);
Vector3f end = endBase - startBase;
glEnable (GL_LIGHTING);
glDisable(GL_CULL_FACE); // TODO: do we need this?
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLfloat c3[4] = {0.3f, 0.3f, 0.3f, 0.5f};
glMaterialfv( GL_FRONT, GL_SPECULAR, c3 );
glMateriali(GL_FRONT, GL_SHININESS, 127);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
glBegin( GL_QUADS );
glColor4fv(primaryColor);
GLfloat secondaryColor[4] = {oldRgb[0], oldRgb[1], oldRgb[2], oldAlpha};
//vertex4n(O, startDir1,startDir2+startDir1,startDir2);
Vector3f c1(startDir1*0.5f+startDir2*0.5f);
Vector3f c2(end+endDir1*0.5f+endDir2*0.5f);
vertex4(primaryColor, c1, O, startDir1, secondaryColor,c2, end+endDir1,end,false);
vertex4(primaryColor,c1, O, startDir2, secondaryColor,c2, end+endDir2,end,false);
vertex4(primaryColor,c1, startDir1, startDir1+startDir2,secondaryColor,c2, end+endDir1+endDir2, end+endDir1,false);
vertex4(primaryColor,c1, startDir2, startDir1+startDir2,secondaryColor,c2, end+endDir1+endDir2, end+endDir2,false);
//vertex4n(O+end, endDir1+end,endDir2+endDir1+end,endDir2+end);
glEnd();
glDisable(GL_COLOR_MATERIAL);
glPopMatrix();
};
bool Mesh::intersectsRay(RayInfo* ri) {
if (triangles.count()==0) initTriangles();
for (int i = 0; i < triangles.count(); i++) {
if (triangles[i].intersectsRay(ri)) return true;
}
return false;
};
void Mesh::initTriangles() {
triangles.clear();
RaytraceTriangle::Vertex4(startBase, startBase+startDir1,endBase+endDir1,endBase, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]);
RaytraceTriangle::Vertex4(startBase, endBase,endBase+endDir2,startBase+startDir2, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]);
RaytraceTriangle::Vertex4(startBase+startDir1, startBase+startDir1+startDir2, endBase+endDir1+endDir2, endBase+endDir1, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]);
RaytraceTriangle::Vertex4(startBase+startDir2, endBase+endDir2, endBase+endDir1+endDir2, startBase+startDir1+startDir2, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]);
from = startBase;
to = startBase;
for (int i = 0; i < triangles.count(); i++) {
triangles[i].expandBoundingBox(from,to);
}
}
bool Mesh::intersectsAABB(Vector3f from2, Vector3f to2) {
if (triangles.count()==0) initTriangles();
return
(from.x() < to2.x()) && (to.x() > from2.x()) &&
(from.y() < to2.y()) && (to.y() > from2.y()) &&
(from.z() < to2.z()) && (to.z() > from2.z());
};
}
}
|
unlicense
|
GarrettCG/SuperMap
|
src/tasks/ConstantZoneCheck.java
|
2587
|
package tasks;
import java.util.ArrayList;
import listeners.SuperMapListener;
import mapstuff.CartographersMap;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import plugin.SuperMap;
public class ConstantZoneCheck extends BukkitRunnable {
public ConstantZoneCheck(JavaPlugin plugin,SuperMapListener sml) {
this.plugin = plugin;
this.sml=sml;
playerList=new ArrayList<String>();
enabled=true;
dead=false;
}
private ConstantZoneCheck(JavaPlugin plugin, ArrayList<String> l){
this.plugin=plugin;
playerList=l;
}
public void disableMapCheck(){
enabled=false;
}
public void enableMapCheck(){
enabled=true;
}
public void run() {
if(!enabled){
cancel();
dead=true;
}
Player p;
for(String player:playerList){
p=Bukkit.getPlayer(player);
if(p.getItemInHand().hasItemMeta()&&p.getItemInHand().getType().equals(Material.MAP)){
if(p.getItemInHand().getItemMeta().getDisplayName().equals("Cartographer's Map")){
//this is where i do the zone checks
try{
CartographersMap cm=SuperMap.mapItemToCMap.get(Integer.valueOf(p.getItemInHand().getDurability()));
cm.mapCheck(p.getLocation(),p);
}catch(NullPointerException npe){
CartographersMap cm=new CartographersMap(p,p.getItemInHand(),sml);
cm.mapCheck(p.getLocation(), p);
}
}
}
}
}
public void addPlayer(Player p){
if(!playerList.contains(p.getDisplayName())){
playerList.add(p.getDisplayName());
}
}
public void removePlayer(Player p){
playerList.remove(p.getDisplayName());
}
public ConstantZoneCheck clone(){
ConstantZoneCheck newczc =new ConstantZoneCheck(plugin,playerList);
newczc.enabled=enabled;
newczc.dead=false;
return newczc;
}
public boolean isDead(){
return dead;
}
private final JavaPlugin plugin;
private SuperMapListener sml;
private ArrayList <String> playerList;
private boolean enabled,dead;
}
|
unlicense
|
HeroSizy/Sizy
|
C5515_Support_Files/C5515_Lib/dsplib_2.40.00/EXAMPLES/cfft32/t6_scale.h
|
17769
|
/* Test for cfft: rand */
#define NX 256
#define FNAME "t6"
#define MAXERROR 16
#pragma DATA_SECTION (x,".input")
LDATA x[2*NX] ={
826286438, 735932609, /* 0 */
514969054, 1135381008, /* 1 */
-1144038767, 1521896844, /* 2 */
-1254184256, 12175212, /* 3 */
-1503878114, 400153915, /* 4 */
-656582100, 907066396, /* 5 */
981839053, -159182972, /* 6 */
1504956409, 75504902, /* 7 */
-1496133430, -1018404274, /* 8 */
990090149, -1144903861, /* 9 */
375519390, -871753915, /* 10 */
186683058, -1222975929, /* 11 */
-793479853, -1111548490, /* 12 */
998195354, -133394503, /* 13 */
-734022309, 893187234, /* 14 */
786244868, -678682522, /* 15 */
494884910, -853137059, /* 16 */
-886380133, 1267475902, /* 17 */
316553482, -1527237481, /* 18 */
325295861, 275084173, /* 19 */
494440845, 130561713, /* 20 */
-981545040, 475910910, /* 21 */
423283461, -578335253, /* 22 */
-1022012917, -833384125, /* 23 */
122759963, -260194781, /* 24 */
382511171, -623706157, /* 25 */
576242655, 534537726, /* 26 */
549756938, 1358559848, /* 27 */
1168140109, -486228428, /* 28 */
-1509996837, 195178465, /* 29 */
-587736513, -1181412132, /* 30 */
865121253, -1026005138, /* 31 */
-597365279, -685404864, /* 32 */
1322665436, 176120468, /* 33 */
554015980, -44672341, /* 34 */
-1319566134, 1401852441, /* 35 */
-1330887949, -831021935, /* 36 */
-1512972857, -66157114, /* 37 */
-845799615, 82217121, /* 38 */
50379768, 907408852, /* 39 */
-129563277, -951649423, /* 40 */
629912572, 1269725549, /* 41 */
255692796, 1308771883, /* 42 */
28537800, -1508831687, /* 43 */
-1319664971, 829380458, /* 44 */
-950940592, 1386723045, /* 45 */
-373216655, 971219718, /* 46 */
-693032809, 1313835283, /* 47 */
839709995, -933082167, /* 48 */
-576800754, 540226845, /* 49 */
428386889, 1323982203, /* 50 */
1508314713, -484154900, /* 51 */
8914739, 292919841, /* 52 */
1387841302, 357999607, /* 53 */
1016851413, -1539496923, /* 54 */
1294390801, 1494196794, /* 55 */
-1199418682, 1238455634, /* 56 */
967563003, 597530915, /* 57 */
1265578230, -187068324, /* 58 */
-1065203970, 623153444, /* 59 */
-1171398766, 340106867, /* 60 */
814243077, -620336944, /* 61 */
687561478, 1103684154, /* 62 */
470070165, -1202542337, /* 63 */
787448041, -646144493, /* 64 */
505787950, -1247879929, /* 65 */
1188796307, -317902323, /* 66 */
-706292016, -516716196, /* 67 */
-249751534, 1377088750, /* 68 */
-889694550, 1049492287, /* 69 */
-1439599476, -748853918, /* 70 */
-1298355878, -1416975825, /* 71 */
1086726360, -1531713926, /* 72 */
-495355335, 230689188, /* 73 */
-104916607, 756074715, /* 74 */
1282629846, 951148587, /* 75 */
-841388468, 426456962, /* 76 */
1122307518, -771037169, /* 77 */
485503759, -1102575486, /* 78 */
1212632466, 469795252, /* 79 */
-36754057, 1382830461, /* 80 */
1527158407, 979221433, /* 81 */
-392678503, 1333728264, /* 82 */
97270040, -589165160, /* 83 */
-987891502, -716646732, /* 84 */
6027268, 112995019, /* 85 */
-241189229, -1043807827, /* 86 */
497310904, -895911849, /* 87 */
538309143, -877857747, /* 88 */
1417683559, 470535192, /* 89 */
-955189233, -1386354700, /* 90 */
-1205195031, -839176450, /* 91 */
201661308, 519024951, /* 92 */
1454374401, -586089062, /* 93 */
-1476352337, -599421212, /* 94 */
1147636661, 684088335, /* 95 */
-1466641174, 1408620429, /* 96 */
60537225, -1143438714, /* 97 */
-953869678, -1338304125, /* 98 */
668617176, -1161762682, /* 99 */
-772892567, -1034895208, /* 100 */
1344942974, 1275358149, /* 101 */
-1124681393, -1127561351, /* 102 */
67027359, 362675569, /* 103 */
1225090667, -716136687, /* 104 */
1371361788, -865917063, /* 105 */
-511227099, 659974543, /* 106 */
-194166668, 151884684, /* 107 */
-89414159, 1368141504, /* 108 */
-1087107282, -527404305, /* 109 */
-1128788524, 633889647, /* 110 */
100741670, 1374580136, /* 111 */
699927106, 252935308, /* 112 */
-314011680, 1178444716, /* 113 */
-438890215, 773774261, /* 114 */
-665615039, -373175708, /* 115 */
1142737007, 699220233, /* 116 */
391868232, -1045296071, /* 117 */
-802343202, 1414194389, /* 118 */
1482011301, -941664052, /* 119 */
435540126, 856172606, /* 120 */
-837445560, 351206807, /* 121 */
562123116, -1046901740, /* 122 */
514038059, -1453691411, /* 123 */
-1132342326, -655232182, /* 124 */
-1480229018, 1460258056, /* 125 */
-737160904, 1396508549, /* 126 */
-1188769458, -843028006, /* 127 */
-1335075786, 1421390750, /* 128 */
1094053667, 557544869, /* 129 */
-990946951, -1379556523, /* 130 */
-1449461546, 309499350, /* 131 */
725150932, -331238073, /* 132 */
113198955, -882339926, /* 133 */
-694288451, -984533380, /* 134 */
-407768218, -1312025499, /* 135 */
-1510009840, -1526943452, /* 136 */
1206504813, 895202025, /* 137 */
1134631846, -1494816163, /* 138 */
-761813004, 1171585480, /* 139 */
215383771, -457107619, /* 140 */
-1056249257, 688613847, /* 141 */
292521435, 1452156621, /* 142 */
-523574973, -1067399129, /* 143 */
491685351, -1044808335, /* 144 */
1127234265, -578451834, /* 145 */
209626357, -1458876031, /* 146 */
1489449918, -441349683, /* 147 */
904652437, -1465668404, /* 148 */
-1076929381, 910342067, /* 149 */
1032355288, 1547571665, /* 150 */
-955196925, -1208226478, /* 151 */
430846201, 380052866, /* 152 */
523885461, -1138995137, /* 153 */
843448377, -588891036, /* 154 */
-372554463, -1132126219, /* 155 */
-181079886, -857664228, /* 156 */
-52512538, -320695907, /* 157 */
335118077, -1131023248, /* 158 */
-1004385168, -802695411, /* 159 */
-1543677198, 1325262664, /* 160 */
899669017, -337577765, /* 161 */
42185164, 34913612, /* 162 */
-888963846, -1261986426, /* 163 */
-1229270942, -1482691524, /* 164 */
-1062226360, -1055412254, /* 165 */
-286695472, 1067969287, /* 166 */
-285945163, 1175342626, /* 167 */
-1386613538, -970305088, /* 168 */
1369588314, 1523002269, /* 169 */
-1085057159, 657273959, /* 170 */
-358430342, 1151197824, /* 171 */
-585701938, -63141546, /* 172 */
-1027514230, -12384379, /* 173 */
1229574553, -658632635, /* 174 */
-549538755, -1361043093, /* 175 */
725368111, -736329338, /* 176 */
-276189241, -972563401, /* 177 */
-310630313, 1292941851, /* 178 */
17118359, -1167803092, /* 179 */
-1025122908, -1508276749, /* 180 */
76708854, -403947373, /* 181 */
437715903, 615770058, /* 182 */
-1499745477, 1206942300, /* 183 */
1044210354, 290680406, /* 184 */
940706234, -1064228188, /* 185 */
613115671, -568246766, /* 186 */
-118144543, -826450672, /* 187 */
-1293864372, -1523848599, /* 188 */
994194670, -319589227, /* 189 */
-951611090, 464578094, /* 190 */
-169395563, -1286461817, /* 191 */
-1509788122, 833285944, /* 192 */
-592883699, 1456034195, /* 193 */
1163555211, 665852628, /* 194 */
1039274807, 874057043, /* 195 */
-517390690, -813525288, /* 196 */
1180153224, -943208015, /* 197 */
-62969126, -734016149, /* 198 */
188526535, 662714998, /* 199 */
359306692, 1480517411, /* 200 */
501872783, 425066021, /* 201 */
361552825, 142360863, /* 202 */
573917804, 1078946947, /* 203 */
31473495, 936476313, /* 204 */
663259900, 521735147, /* 205 */
47143157, 530031207, /* 206 */
328174700, 993967364, /* 207 */
1446737324, 1458423203, /* 208 */
998535766, -40531371, /* 209 */
-564956951, 984124687, /* 210 */
271852321, 438858235, /* 211 */
-1146342469, -600300045, /* 212 */
-761480314, 498875531, /* 213 */
939369275, -440134528, /* 214 */
520307587, 1358379899, /* 215 */
-1507715758, -38231300, /* 216 */
190890659, -1267894111, /* 217 */
-140857117, 538870555, /* 218 */
1255307156, 46127687, /* 219 */
-675288505, -863079670, /* 220 */
-1348355452, 697509365, /* 221 */
-72563108, -1338397736, /* 222 */
1499464630, 1438744629, /* 223 */
1309246754, -906239002, /* 224 */
189703036, -1050503856, /* 225 */
472193224, 428474194, /* 226 */
845282897, -1549248944, /* 227 */
-1220820588, -509523497, /* 228 */
-1546628921, -697170879, /* 229 */
129464094, -1411924842, /* 230 */
-1528697705, -1258885332, /* 231 */
-150848960, -279000188, /* 232 */
-943421016, 982338468, /* 233 */
890118579, 1148570509, /* 234 */
367533763, -1480037360, /* 235 */
-1501842650, 704228775, /* 236 */
1211613098, 1078798844, /* 237 */
811256999, 708640593, /* 238 */
1261773018, 1410765950, /* 239 */
801540037, 484674765, /* 240 */
-369726760, 751124716, /* 241 */
-523541790, -480591795, /* 242 */
12642818, 1190434449, /* 243 */
200156992, -473529969, /* 244 */
828288431, -1365583753, /* 245 */
867565633, 677066125, /* 246 */
-49295166, 1420424222, /* 247 */
936834559, -1063781898, /* 248 */
-89859788, -259298054, /* 249 */
-921421421, -1258456392, /* 250 */
246799202, -155161615, /* 251 */
516136238, 1144340225, /* 252 */
547956929, -335977129, /* 253 */
1371746142, -766349055, /* 254 */
837436820, -451403289, /* 255 */
};
#pragma DATA_SECTION (rtest,".test")
LDATA rtest[2*NX] ={
7270299, -41883120, /* 0 */
66748444, 35987053, /* 1 */
-61169701, -347598, /* 2 */
35868257, -48297571, /* 3 */
-17912583, 11898086, /* 4 */
65847398, 95980167, /* 5 */
-152916238, 49518150, /* 6 */
-1591542, -11477936, /* 7 */
-46421411, -29009425, /* 8 */
44944676, 37731013, /* 9 */
55737937, 27324282, /* 10 */
5946397, 4617266, /* 11 */
-46015047, 71283093, /* 12 */
41821564, 9519263, /* 13 */
62449208, 64912263, /* 14 */
61578167, 48322613, /* 15 */
-29836793, 90742652, /* 16 */
92079538, 51472667, /* 17 */
-87584979, 50234511, /* 18 */
63888478, 79988974, /* 19 */
76843659, -31803965, /* 20 */
-41703398, -69614233, /* 21 */
-40431447, 68676418, /* 22 */
119370730, -9767564, /* 23 */
81698120, 55600334, /* 24 */
-1348747, -90143325, /* 25 */
73773825, 15425859, /* 26 */
-39248228, 79163455, /* 27 */
44838897, 26522780, /* 28 */
-2243902, 80546691, /* 29 */
8995772, -4532451, /* 30 */
104856716, 55513880, /* 31 */
109583896, -14731457, /* 32 */
-3171545, -8993130, /* 33 */
-126158203, 16303772, /* 34 */
39066430, 69645307, /* 35 */
-81251049, 27135518, /* 36 */
-61688901, 46217572, /* 37 */
50652022, 119493032, /* 38 */
108297606, -76665824, /* 39 */
-53750739, -83892186, /* 40 */
106303435, 3739097, /* 41 */
72351230, -86252681, /* 42 */
3801648, 7305276, /* 43 */
1364141, -56115040, /* 44 */
1487411, 99862419, /* 45 */
58442704, 29853294, /* 46 */
10142613, -113922636, /* 47 */
71095240, 41127412, /* 48 */
58993128, 18906775, /* 49 */
6395705, -20318264, /* 50 */
-21793290, 37210426, /* 51 */
42772507, -21276208, /* 52 */
36704348, -45680572, /* 53 */
98658060, -38510297, /* 54 */
5266506, 58268698, /* 55 */
8189813, 34592211, /* 56 */
-9408401, 8456416, /* 57 */
13346647, -22923264, /* 58 */
-58969534, -10525560, /* 59 */
-25927265, -4366936, /* 60 */
1460518, -8048710, /* 61 */
144918302, 6121221, /* 62 */
-89877887, 105748327, /* 63 */
-19628717, -46494186, /* 64 */
-33307335, -14713372, /* 65 */
-12199627, 46477038, /* 66 */
11619615, -69963739, /* 67 */
27079878, -20070172, /* 68 */
2091575, 25061752, /* 69 */
-27239757, 2959526, /* 70 */
20518230, -55360646, /* 71 */
-58929375, 10345693, /* 72 */
-23601565, -6385223, /* 73 */
-26759856, 124716278, /* 74 */
97393221, 37642037, /* 75 */
77079767, -39137874, /* 76 */
-71074184, 45831414, /* 77 */
-6302779, 55397579, /* 78 */
94350604, 16937087, /* 79 */
24700564, 32668510, /* 80 */
15728109, 51108347, /* 81 */
10788950, -44974455, /* 82 */
-1367274, 26333724, /* 83 */
19933899, -113677083, /* 84 */
-31737631, -51016797, /* 85 */
-57410924, -89728428, /* 86 */
-78663988, -21240897, /* 87 */
-30104866, 67568605, /* 88 */
-43555230, -37150152, /* 89 */
-79238125, -112235361, /* 90 */
-17870872, -53052647, /* 91 */
45707490, 29831147, /* 92 */
-31859394, -29553926, /* 93 */
15686962, -14363556, /* 94 */
-18462052, -61102589, /* 95 */
-13417789, -29176856, /* 96 */
-9518456, -8576655, /* 97 */
7716095, -26032318, /* 98 */
70984559, -24295519, /* 99 */
151626914, 34678755, /* 100 */
-44168256, 40755680, /* 101 */
-79706150, -33035380, /* 102 */
-22388561, -47194222, /* 103 */
-88271118, 82213218, /* 104 */
16228410, -49653840, /* 105 */
1386395, 60200378, /* 106 */
62324968, -174623, /* 107 */
4426849, 9339524, /* 108 */
-9429960, 84702920, /* 109 */
-1981796, -19908653, /* 110 */
14693843, 34952843, /* 111 */
7183725, 71460299, /* 112 */
34937137, -21282941, /* 113 */
-5491420, -69214411, /* 114 */
-36291856, 28072385, /* 115 */
39452926, 66962571, /* 116 */
87209600, -42634661, /* 117 */
36967556, -9784098, /* 118 */
-44838191, 18067593, /* 119 */
-8692193, -22854824, /* 120 */
-9720325, -15438463, /* 121 */
-28358945, -66152128, /* 122 */
-95659206, 30357632, /* 123 */
46200143, 14381867, /* 124 */
-33689711, -31017843, /* 125 */
53450564, 66607384, /* 126 */
26866833, -76089979, /* 127 */
-96981609, -35754983, /* 128 */
-600219, -13786687, /* 129 */
13112355, -90663799, /* 130 */
-41221881, 76954639, /* 131 */
-22951442, 54009341, /* 132 */
6846610, -5896488, /* 133 */
-97870487, 5802390, /* 134 */
113575803, 35370789, /* 135 */
-62374498, 48833477, /* 136 */
96303365, -27119617, /* 137 */
45286107, 91104448, /* 138 */
13150530, 137643896, /* 139 */
41893867, -9511489, /* 140 */
-9591746, -447287, /* 141 */
-13209601, -8540073, /* 142 */
-24786708, -91335768, /* 143 */
-37225172, 29938061, /* 144 */
-10917439, -31090853, /* 145 */
2837323, -65650813, /* 146 */
-32319038, 40492031, /* 147 */
14434626, 61447853, /* 148 */
-32855321, -41105312, /* 149 */
133105620, 59148377, /* 150 */
-87241916, -13143300, /* 151 */
4848078, 24837618, /* 152 */
97745949, 102604597, /* 153 */
-17190044, 61932304, /* 154 */
23138574, 11277135, /* 155 */
-125317715, -109982102, /* 156 */
37274919, -14962820, /* 157 */
-174270746, -100330129, /* 158 */
183629778, -52018455, /* 159 */
21956636, 33807056, /* 160 */
-4140184, -17407557, /* 161 */
-58822098, 107092845, /* 162 */
5406876, 20026695, /* 163 */
34853211, 34324275, /* 164 */
23047725, -36063275, /* 165 */
-17470175, -18822020, /* 166 */
7688063, -25143967, /* 167 */
-105045111, 10503475, /* 168 */
-49501576, 3659908, /* 169 */
136362810, 133422670, /* 170 */
76847298, -52103718, /* 171 */
-18948293, 37316392, /* 172 */
65900685, -80667205, /* 173 */
-18408595, 44055812, /* 174 */
28913691, -36210661, /* 175 */
30901160, 3627090, /* 176 */
-9922611, -14710213, /* 177 */
17651909, 88583468, /* 178 */
-30610984, 21174271, /* 179 */
-82706156, 17250686, /* 180 */
47542533, -35165942, /* 181 */
-73760564, 13519110, /* 182 */
10633997, -60509162, /* 183 */
-37295187, 36017338, /* 184 */
98130889, -184451459, /* 185 */
6481030, -55335404, /* 186 */
79548961, 35370148, /* 187 */
-50720457, 27334323, /* 188 */
2607152, 107449159, /* 189 */
34932791, -79171917, /* 190 */
-40257571, -52236194, /* 191 */
-97347697, -2542659, /* 192 */
28222241, -71114214, /* 193 */
-26654346, 64125774, /* 194 */
12406087, -13761462, /* 195 */
9043159, 57059967, /* 196 */
-9842341, 47643203, /* 197 */
-10274897, 50229442, /* 198 */
-1623057, 20810486, /* 199 */
-44418253, 105592305, /* 200 */
7920442, 43816490, /* 201 */
58595909, 80225997, /* 202 */
-93282276, 65960116, /* 203 */
-81772185, -47179041, /* 204 */
-120708991, 26879848, /* 205 */
66013032, -28765053, /* 206 */
3968380, 27770532, /* 207 */
-19880263, -35504286, /* 208 */
45171326, -59635799, /* 209 */
31142323, 37413541, /* 210 */
-93535907, 109335118, /* 211 */
76837660, -85847040, /* 212 */
-8928996, -34888634, /* 213 */
-70056545, 3356344, /* 214 */
-38593308, 69975503, /* 215 */
-5297490, 1782237, /* 216 */
-37673889, -26267117, /* 217 */
40900385, 33319258, /* 218 */
60476220, 8924730, /* 219 */
-9824034, -67005274, /* 220 */
-32399199, -70977876, /* 221 */
19403425, -51788082, /* 222 */
47961178, -52219280, /* 223 */
111466635, 90209673, /* 224 */
-68442769, -62691761, /* 225 */
65320959, -33332659, /* 226 */
18533082, -43194672, /* 227 */
-36875275, -25857327, /* 228 */
21586275, -50284219, /* 229 */
13147209, -64467100, /* 230 */
138048025, -24104334, /* 231 */
-10526889, 51619952, /* 232 */
-104287510, -125386564, /* 233 */
-32756139, 3541781, /* 234 */
-17855496, 34326314, /* 235 */
-54361437, 57549526, /* 236 */
-54682850, -154951249, /* 237 */
31861672, 4096301, /* 238 */
2190850, -47515247, /* 239 */
51005656, 31144968, /* 240 */
46288827, -27233744, /* 241 */
-92290997, 100250229, /* 242 */
-9695375, 53094006, /* 243 */
-67280866, 50778316, /* 244 */
-101317334, 36392452, /* 245 */
5063662, -227297, /* 246 */
69194276, 30692197, /* 247 */
-105650459, -176550211, /* 248 */
4499455, -37699462, /* 249 */
39364959, 45967451, /* 250 */
62307009, 45965549, /* 251 */
100887632, 93003711, /* 252 */
-14150852, -96089314, /* 253 */
17071418, -83455393, /* 254 */
33790031, 62260967, /* 255 */
};
LDATA error;
|
unlicense
|
Vexatos/EnderIO
|
src/main/java/crazypants/enderio/machine/farm/FarmersRegistry.java
|
6917
|
package crazypants.enderio.machine.farm;
import crazypants.enderio.config.Config;
import crazypants.enderio.machine.farm.farmers.*;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
public final class FarmersRegistry {
public static final PlantableFarmer DEFAULT_FARMER = new PlantableFarmer();
public static void addFarmers() {
addExtraUtilities();
addNatura();
addTiC();
addStillHungry();
addIC2();
addMFR();
addThaumcraft();
FarmersCommune.joinCommune(new StemFarmer(Blocks.reeds, new ItemStack(Items.reeds)));
FarmersCommune.joinCommune(new StemFarmer(Blocks.cactus, new ItemStack(Blocks.cactus)));
FarmersCommune.joinCommune(new TreeFarmer(Blocks.sapling, Blocks.log));
FarmersCommune.joinCommune(new TreeFarmer(Blocks.sapling, Blocks.log2));
FarmersCommune.joinCommune(new TreeFarmer(true,Blocks.red_mushroom, Blocks.red_mushroom_block));
FarmersCommune.joinCommune(new TreeFarmer(true,Blocks.brown_mushroom, Blocks.brown_mushroom_block));
//special case of plantables to get spacing correct
FarmersCommune.joinCommune(new MelonFarmer(Blocks.melon_stem, Blocks.melon_block, new ItemStack(Items.melon_seeds)));
FarmersCommune.joinCommune(new MelonFarmer(Blocks.pumpkin_stem, Blocks.pumpkin, new ItemStack(Items.pumpkin_seeds)));
//'BlockNetherWart' is not an IGrowable
FarmersCommune.joinCommune(new NetherWartFarmer());
//Cocoa is odd
FarmersCommune.joinCommune(new CocoaFarmer());
//Handles all 'vanilla' style crops
FarmersCommune.joinCommune(DEFAULT_FARMER);
}
public static void addPickable(String mod, String blockName, String itemName) {
Block cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, itemName);
if(seedItem != null) {
FarmersCommune.joinCommune(new PickableFarmer(cropBlock, new ItemStack(seedItem)));
}
}
}
public static CustomSeedFarmer addSeed(String mod, String blockName, String itemName, Block... extraFarmland) {
Block cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, itemName);
if(seedItem != null) {
CustomSeedFarmer farmer = new CustomSeedFarmer(cropBlock, new ItemStack(seedItem));
if(extraFarmland != null) {
for (Block farmland : extraFarmland) {
if(farmland != null) {
farmer.addTilledBlock(farmland);
}
}
}
FarmersCommune.joinCommune(farmer);
return farmer;
}
}
return null;
}
private static void addTiC() {
String mod = "TConstruct";
String blockName = "ore.berries.two";
Block cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, blockName);
if(seedItem != null) {
for (int i = 0; i < 2; i++) {
PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 8 + i));
farmer.setRequiresFarmland(false);
FarmersCommune.joinCommune(farmer);
}
}
}
blockName = "ore.berries.one";
cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, blockName);
if(seedItem != null) {
for (int i = 0; i < 4; i++) {
PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 8 + i));
farmer.setRequiresFarmland(false);
FarmersCommune.joinCommune(farmer);
}
}
}
}
private static void addNatura() {
String mod = "Natura";
String blockName = "N Crops";
Block cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
DEFAULT_FARMER.addHarvestExlude(cropBlock);
Item seedItem = GameRegistry.findItem(mod, "barley.seed");
if(seedItem != null) {
//barley
FarmersCommune.joinCommune(new CustomSeedFarmer(cropBlock, 3, new ItemStack(seedItem)));
// cotton
FarmersCommune.joinCommune(new PickableFarmer(cropBlock, 4, 8, new ItemStack(seedItem, 1, 1)));
}
}
blockName = "BerryBush";
cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, blockName);
if(seedItem != null) {
for (int i = 0; i < 4; i++) {
PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 12 + i));
farmer.setRequiresFarmland(false);
FarmersCommune.joinCommune(farmer);
}
}
}
blockName = "florasapling";
Block saplingBlock = GameRegistry.findBlock(mod, blockName);
if(saplingBlock != null) {
FarmersCommune.joinCommune(new TreeFarmer(saplingBlock,
GameRegistry.findBlock(mod, "tree"),
GameRegistry.findBlock(mod, "willow"),
GameRegistry.findBlock(mod, "Dark Tree")));
}
blockName = "Rare Sapling";
saplingBlock = GameRegistry.findBlock(mod, blockName);
if(saplingBlock != null) {
FarmersCommune.joinCommune(new TreeFarmer(saplingBlock, GameRegistry.findBlock(mod, "Rare Tree")));
}
}
private static void addThaumcraft()
{
String mod = "Thaumcraft";
String manaBean = "ItemManaBean";
String manaPod = "blockManaPod";
Block block = GameRegistry.findBlock(mod,manaPod);
Item item = GameRegistry.findItem(mod,manaBean);
if (Config.farmManaBeansEnabled && block!=null && item!=null)
{
FarmersCommune.joinCommune(new ManaBeanFarmer(block, new ItemStack(item)));
}
}
private static void addMFR() {
String mod = "MineFactoryReloaded";
String blockName = "rubberwood.sapling";
Block saplingBlock = GameRegistry.findBlock(mod, blockName);
if(saplingBlock != null) {
FarmersCommune.joinCommune(new TreeFarmer(saplingBlock, GameRegistry.findBlock(mod, "rubberwood.log")));
}
}
private static void addIC2() {
RubberTreeFarmerIC2 rtf = new RubberTreeFarmerIC2();
if(rtf.isValid()) {
FarmersCommune.joinCommune(rtf);
}
}
private static void addStillHungry() {
String mod = "stillhungry";
addPickable(mod, "grapeBlock", "StillHungry_grapeSeed");
}
private static void addExtraUtilities() {
String mod = "ExtraUtilities";
String name = "plant/ender_lilly";
CustomSeedFarmer farmer = addSeed(mod, name, name, Blocks.end_stone, GameRegistry.findBlock(mod, "decorativeBlock1"));
if(farmer != null) {
farmer.setIgnoreGroundCanSustainCheck(true);
}
}
private FarmersRegistry() {
}
}
|
unlicense
|
DubhAd/Home-AssistantConfig
|
automation/platform/README.md
|
692
|
# Automations, automations everywhere, and all the brains did hurt
Documentation: [automation](https://home-assistant.io/docs/automation/)
_Some of these were first written when I started with HA, and didn't know better. You'll find that I've used hyphens (-) in some file names and underscores (\_) to match Home Assistant in others. Mostly I'm not renaming files._
## Platforms
These are for Home Assistant
### clear_states.yaml
### ha-ready.yaml
### ha-started-later.yaml
### ha-started.yaml
### ha-stopped.yaml
### plex_hook.yaml
### recorder_purge.yaml
### sunrise-enable-automations.yaml
### test_zwave.yaml
### updater-notify.yaml
### zwave_check.yaml
### zwave_health_check.yaml
|
unlicense
|
clilystudio/NetBook
|
allsrc/com/ushaqi/zhuishushenqi/model/UserInfo.java
|
3520
|
package com.ushaqi.zhuishushenqi.model;
import com.ushaqi.zhuishushenqi.api.ApiService;
import java.io.Serializable;
import java.util.Date;
public class UserInfo
implements Serializable
{
private static final long serialVersionUID = 2519451769850149545L;
private String _id;
private String avatar;
private UserInfo.BookListCount book_list_count;
private String code;
private int exp;
private String gender;
private boolean genderChanged;
private int lv;
private String nickname;
private Date nicknameUpdated;
private boolean ok;
private UserInfo.UserPostCount post_count;
private float rank;
private UserInfo.ThisWeekTasks this_week_tasks;
private UserInfo.UserTodayTask today_tasks;
public String getAvatar()
{
return this.avatar;
}
public UserInfo.BookListCount getBook_list_count()
{
return this.book_list_count;
}
public String getCode()
{
return this.code;
}
public int getExp()
{
return this.exp;
}
public String getGender()
{
return this.gender;
}
public String getId()
{
return this._id;
}
public int getLv()
{
return this.lv;
}
public String getNickname()
{
return this.nickname;
}
public Date getNicknameUpdated()
{
return this.nicknameUpdated;
}
public UserInfo.UserPostCount getPost_count()
{
return this.post_count;
}
public float getRank()
{
return this.rank;
}
public String getScaleAvatar(int paramInt)
{
if (paramInt == 2)
return ApiService.a + this.avatar + "-avatarl";
return ApiService.a + this.avatar + "-avatars";
}
public UserInfo.ThisWeekTasks getThis_week_tasks()
{
return this.this_week_tasks;
}
public UserInfo.UserTodayTask getToday_tasks()
{
return this.today_tasks;
}
public boolean isGenderChanged()
{
return this.genderChanged;
}
public boolean isOk()
{
return this.ok;
}
public void setAvatar(String paramString)
{
this.avatar = paramString;
}
public void setBook_list_count(UserInfo.BookListCount paramBookListCount)
{
this.book_list_count = paramBookListCount;
}
public void setCode(String paramString)
{
this.code = paramString;
}
public void setExp(int paramInt)
{
this.exp = paramInt;
}
public void setGender(String paramString)
{
this.gender = paramString;
}
public void setGenderChanged(boolean paramBoolean)
{
this.genderChanged = paramBoolean;
}
public void setId(String paramString)
{
this._id = paramString;
}
public void setLv(int paramInt)
{
this.lv = paramInt;
}
public void setNickname(String paramString)
{
this.nickname = paramString;
}
public void setNicknameUpdated(Date paramDate)
{
this.nicknameUpdated = paramDate;
}
public void setOk(boolean paramBoolean)
{
this.ok = paramBoolean;
}
public void setPost_count(UserInfo.UserPostCount paramUserPostCount)
{
this.post_count = paramUserPostCount;
}
public void setRank(float paramFloat)
{
this.rank = paramFloat;
}
public void setThis_week_tasks(UserInfo.ThisWeekTasks paramThisWeekTasks)
{
this.this_week_tasks = paramThisWeekTasks;
}
public void setToday_tasks(UserInfo.UserTodayTask paramUserTodayTask)
{
this.today_tasks = paramUserTodayTask;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.model.UserInfo
* JD-Core Version: 0.6.0
*/
|
unlicense
|
UAF-CS372-Spring-2015/the-platformer
|
src/GameTextures.cpp
|
744
|
#include "GameTextures.h"
#include <iostream>
GameTextures::GameTextures()
{
if (!_image.loadFromFile("assets/DungeonCrawl_ProjectUtumnoTileset.png"))
{
std::cout << "Error loading texture." << std::endl;
}
}
std::shared_ptr<sf::Texture> GameTextures::getTexture(std::string name, int x, int y)
{
std::cout << "Loading " << name << std::endl;
auto texture = _textures.find(name);
if (texture == _textures.end())
{
_textures[name]=getTexture(x, y);
}
return _textures[name];
}
std::shared_ptr<sf::Texture> GameTextures::getTexture(int x, int y)
{
auto texture = std::make_shared<sf::Texture>();
texture->loadFromImage(_image, sf::IntRect(x*32, y*32, 32, 32));
texture->setRepeated(true);
return texture;
}
|
unlicense
|
pythonpatterns/patterns
|
p0081.py
|
81
|
a = 'a|b|c|d|e'
b = a.split('|', 3)
print(b)
"""<
['a', 'b', 'c', 'd|e']
>"""
|
unlicense
|
craigbro/tichy
|
resources/corpus/www.bartleby.com/122/46.html
|
17417
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>
<!-- 122.46 -->
<TITLE>46. 'Patience, hard thing! the hard thing but to pray'. Hopkins, Gerard Manley. 1918. Poems</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="description" CONTENT="46. 'Patience, hard thing! the hard thing but to pray'. Hopkins, Gerard Manley. 1918. Poems">
<META NAME="keywords" CONTENT="46. 'Patience, hard thing! the hard thing but to pray'. Hopkins, Gerard Manley. 1918. Poems">
<META NAME="bart_colls" CONTENT="colHopkinsG, colVerse, col122">
<STYLE TYPE="text/css">
.FormLt1 { font-family: arial, helvetica;
font-size: 12px;
color: #000000;
font-weight: normal;
background-color: #ffffff; }
.sizeLt1 { font-family: arial, helvetica;
font-size: 12px;
font-weight: normal; }
</STYLE>
</HEAD>
<!-- BEGIN MAIN HEADER CODE -->
<BODY BGCOLOR="#FFFFFF" LINK="#003366" TEXT="#000020" ALINK="#888645" VLINK="#888645" ALINK="#888645">
<MAP NAME="Tabs">
<AREA SHAPE="rect" COORDS="8,8,220,47" HREF="/">
<AREA SHAPE="rect" COORDS="509,32,589,48" HREF="/nonfiction/">
<AREA SHAPE="rect" COORDS="424,30,505,47" HREF="/fiction/">
<AREA SHAPE="rect" COORDS="340,29,414,49" HREF="/verse/">
<AREA SHAPE="rect" COORDS="253,29,329,47" HREF="/reference/">
</MAP>
<MAP NAME="Links">
<AREA SHAPE="rect" COORDS="252,3,318,16" HREF="/usage/">
<AREA SHAPE="rect" COORDS="189,2,247,16" HREF="/quotations/">
<AREA SHAPE="rect" COORDS="133,3,185,16" HREF="/thesauri/">
<AREA SHAPE="rect" COORDS="75,4,127,16" HREF="/61/">
<AREA SHAPE="rect" COORDS="4,3,68,17" HREF="/65/">
</MAP>
<MAP NAME="Links2">
<AREA SHAPE="rect" COORDS="5,3,37,16" HREF="/">
<AREA SHAPE="rect" COORDS="45,3,89,17" HREF="/subjects/">
<AREA SHAPE="rect" COORDS="133,3,175,16" HREF="/authors/">
<AREA SHAPE="rect" COORDS="96,3,126,16" HREF="/titles/">
</MAP>
<!-- TOP AD CODE BEGIN -->
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3" ALIGN="center"><TR><TD ALIGN="center"><A HREF="http://www.amazon.com/exec/obidos/redirect?tag=bartlebylibrary&path=tg/browse/-/283155/"><img src="/adimages/bkused120x60-static.gif" border=0 WIDTH=120 HEIGHT=60></A></TD>
<TD ALIGN="center">
<!-- ---------- Advertising.com Banner Code -------------- -->
<CENTER>
<SCRIPT LANGUAGE=JavaScript>
var bnum=new Number(Math.floor(99999999 * Math.random())+1);
document.write('<SCR'+'IPT LANGUAGE="JavaScript" ');
document.write('SRC="http://servedby.advertising.com/site=62058/size=468060/bnum='+bnum+'/optn=1"></SCR'+'IPT>');
</SCRIPT>
<NOSCRIPT>
<A HREF="http://servedby.advertising.com/click/site=62058/bnum=16721052" TARGET="_blank">
<IMG SRC="http://servedby.advertising.com/site=62058/size=468060/bnum=16721052/bins=1/rich=0" WIDTH="468" HEIGHT="60" BORDER="0" ALT="Click to learn more...">
</A>
</NOSCRIPT>
</CENTER>
<!-- ---------- Copyright 2000, Advertising.com ---------- -->
</TD></TR></TABLE>
<!-- TOP AD CODE END -->
<!-- ---------- Advertising.com Banner Code -------------- -->
<script language="JavaScript">
<!--
function setCookie(NameOfCookie, value, expirehours) {
var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expirehours * 3600 * 1000));
document.cookie = NameOfCookie + "=" + escape(value) +
((expirehours == null) ? "" : "; expires=" + ExpireDate.toGMTString()) +
"; path=/;" ;
}
if (document.cookie.indexOf('AdComPop30858')==-1)
{
setCookie('AdComPop30858','yes');
var bnum=new Number(Math.floor(99999999 * Math.random())+1);
document.write('<SCR'+'IPT LANGUAGE="JavaScript" ');
document.write(' SRC="http://servedby.advertising.com/pops=6/site=30858/bnum='+bnum+'">');
document.write('</SCR');
document.write('IPT>');
}
// -->
</script>
<!-- ----------Copyright 2000, Advertising.com---------- -->
<FORM METHOD=GET ACTION="/cgi-bin/texis/webinator/sitesearch">
<TABLE ALIGN="center" WIDTH="603" BORDER="0" CELLSPACING="0" CELLPADDING="0">
<!-- BEGIN SEARCH CODE -->
<TR BGCOLOR="#FFFFFF"><TD><IMG SRC="/images/top_nav.gif" WIDTH="603" HEIGHT="50" BORDER="0" USEMAP="#Tabs"></TD></TR>
<TR BGCOLOR="#B1B1B1" ALIGN="left"><TD HEIGHT="33" ALIGN="center">
<TABLE WIDTH="602" BORDER="0" CELLSPACING="0" CELLPADDING="0" ALIGN="left">
<TR><TD VALIGN="top" WIDTH="194" BGCOLOR="#F2F1ED"><IMG SRC="/images/great_books.gif" WIDTH="193" HEIGHT="33"></TD>
<TD BGCOLOR="#F2F1ED" ALIGN="left" VALIGN="middle" CLASS="sizeLt1">
<SELECT NAME=FILTER CLASS="FormLt1" SIZE="1">
<OPTION VALUE="">Select Search</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="">All Bartleby.com</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="colReference">All Reference</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="col65">Columbia Encyclopedia</OPTION>
<OPTION VALUE="col67">World History Encyclopedia</OPTION>
<OPTION VALUE="col151">World Factbook</OPTION>
<OPTION VALUE="col69">Columbia Gazetteer</OPTION>
<OPTION VALUE="colAM">American Heritage Coll.</OPTION>
<OPTION VALUE="col61">Dictionary</OPTION>
<OPTION VALUE="colThesaurus">Roget's Thesauri</OPTION>
<OPTION VALUE="col62">Roget's II: Thesaurus</OPTION>
<OPTION VALUE="col110">Roget's Int'l Thesaurus</OPTION>
<OPTION VALUE="colQuotations">Quotations</OPTION>
<OPTION VALUE="col100">Bartlett's Quotations</OPTION>
<OPTION VALUE="col66">Columbia Quotations</OPTION>
<OPTION VALUE="col63">Simpson's Quotations</OPTION>
<OPTION VALUE="colUsage">English Usage</OPTION>
<OPTION VALUE="col64">Modern Usage</OPTION>
<OPTION VALUE="col68">American English</OPTION>
<OPTION VALUE="col116">Fowler's King's English</OPTION>
<OPTION VALUE="col141">Strunk's Style</OPTION>
<OPTION VALUE="col185">Mencken's Language</OPTION>
<OPTION VALUE="colCamb-Hi">Cambridge History</OPTION>
<OPTION VALUE="col108">The King James Bible</OPTION>
<OPTION VALUE="colShakespe">Oxford Shakespeare</OPTION>
<OPTION VALUE="col107">Gray's Anatomy</OPTION>
<OPTION VALUE="col87">Farmer's Cookbook</OPTION>
<OPTION VALUE="col95">Post's Etiquette</OPTION>
<OPTION VALUE="col81">Brewer's Phrase & Fable</OPTION>
<OPTION VALUE="colBulfinchT">Bulfinch's Mythology</OPTION>
<OPTION VALUE="col196">Frazer's Golden Bough</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="colVerse">All Verse</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="colAnthology">Anthologies</OPTION>
<OPTION VALUE="colDickinsoE">Dickinson, E.</OPTION>
<OPTION VALUE="colEliot-Th">Eliot, T.S.</OPTION>
<OPTION VALUE="colFrost-Ro">Frost, R.</OPTION>
<OPTION SELECTED VALUE="colHopkinsG">Hopkins, G.M.</OPTION>
<OPTION VALUE="colKeats-Jo">Keats, J.</OPTION>
<OPTION VALUE="colLawrencDH">Lawrence, D.H.</OPTION>
<OPTION VALUE="colMasters">Masters, E.L.</OPTION>
<OPTION VALUE="colSandburg">Sandburg, C.</OPTION>
<OPTION VALUE="colSassoon">Sassoon, S.</OPTION>
<OPTION VALUE="colWhitmnW">Whitman, W.</OPTION>
<OPTION VALUE="colWordswthW">Wordsworth, W.</OPTION>
<OPTION VALUE="colYeats-Wi">Yeats, W.B.</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="colNonfiction">All Nonfiction</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="colHC">Harvard Classics</OPTION>
<OPTION VALUE="col109">American Essays</OPTION>
<OPTION VALUE="col173">Einstein's Relativity</OPTION>
<OPTION VALUE="colGrant-Ul">Grant, U.S.</OPTION>
<OPTION VALUE="colRsvltT">Roosevelt, T.</OPTION>
<OPTION VALUE="col86">Wells's History</OPTION>
<OPTION VALUE="col124">Presidential Inaugurals</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="colFiction">All Fiction</OPTION>
<OPTION VALUE="">-----</OPTION>
<OPTION VALUE="colSF">Shelf of Fiction</OPTION>
<OPTION VALUE="col166">Ghost Stories</OPTION>
<OPTION VALUE="col195">Short Stories</OPTION>
<OPTION VALUE="colShaw-Geo">Shaw, G.B.</OPTION>
<OPTION VALUE="colStein-Ge">Stein, G.</OPTION>
<OPTION VALUE="colStvnsnR">Stevenson, R.L.</OPTION>
<OPTION VALUE="colWells-HG">Wells, H.G.</OPTION>
</SELECT></TD><TD BGCOLOR="#F2F1ED" ALIGN="left" VALIGN="middle" CLASS="sizeLt1">
<SCRIPT LANGUAGE="JavaScript">
<!-----
bName = navigator.appName;
function isWin(){ if (navigator.appVersion.indexOf("Win") != -1) { return true; } else { return false; } }
if (isWin() && bName != "Netscape")
document.write("<input name=\"query\" class=\"FormLt1\" type=text maxlength=\"40\" size=\"35\">");
else if (isWin() && bName == "Netscape")
document.write("<input name=\"query\" class=\"FormLt1\" type=text maxlength=\"40\" size=\"17\">");
else
document.write("<input name=\"query\" class=\"FormLt1\" type=text maxlength=\"40\" size=\"21\">");
// -->
</SCRIPT>
<NOSCRIPT><INPUT NAME="query" TYPE=TEXT MAXLENGTH="40" SIZE="17"></NOSCRIPT>
</TD><TD BGCOLOR="#F2F1ED" ALIGN="left" VALIGN="middle" CLASS="sizeLt1"><INPUT WIDTH=22 HEIGHT=23 TYPE=IMAGE SRC="/images/go.gif" BORDER="0"></TD></TR></TABLE></TD></TR>
<!-- END SEARCH CODE -->
<!-- BEGIN FEATURED CODE -->
<TR BGCOLOR="#B1B1B1"><TD HEIGHT="1"><IMG SRC="/images/horiz_bar602.gif" WIDTH=602 HEIGHT=1></TD></TR>
<TR VALIGN="top" ALIGN="center"><TD HEIGHT="27" BGCOLOR="#B1B1B1"><TABLE WIDTH="601" BORDER="0" CELLSPACING="0" CELLPADDING="0" BGCOLOR="#F2F1ED"><TR BGCOLOR="#F2F1ED"><TD ALIGN="left" VALIGN="middle" HEIGHT="27"><IMG SRC="/images/bar_z.gif" width="176" height="19" border="0" USEMAP="#Links2"></TD><TD ALIGN="right" VALIGN="middle"><IMG SRC="/images/bar_r.gif" WIDTH="321" HEIGHT="19" HSPACE="12" BORDER="0" USEMAP="#Links" ALT=""></TD></TR></TABLE></TD></TR><TR BGCOLOR="#B1B1B1"> <TD HEIGHT="1"><IMG SRC="/images/horiz_bar602.gif" WIDTH=602 HEIGHT=1></TD></TR>
<!-- END FEATURED CODE -->
<!-- TOP CHAPTER/SECTION NAV CODE -->
<TR><TD VALIGN=MIDDLE HEIGHT=25><FONT FACE="Arial, Helvetica" SIZE=-1><A HREF="/verse/">Verse</A> > <A HREF="/people/HopkinsG.html">Gerard Manley Hopkins</A> > <A HREF="/122/">Poems</A></FONT></TD></TR>
<TR BGCOLOR="#B1B1B1"><TD HEIGHT="1"><IMG SRC="/images/newsite/horiz_bar602.gif" WIDTH=602 HEIGHT=1 ALT=""></TD></TR><TR><TD>
<TABLE WIDTH="601" BORDER="0" CELLSPACING="0" CELLPADDING="0" BGCOLOR="#ffffff"><TR>
<TD ALIGN=LEFT HEIGHT=25 WIDTH=1% VALIGN=MIDDLE><A HREF="/122/45.html"><IMG SRC="/images/newsite/lt.gif" BORDER=0 WIDTH=8 HEIGHT=17></A></TD>
<TD ALIGN=LEFT><FONT FACE="Arial, Helvetica" SIZE=-1> <A HREF="/122/45.html">PREVIOUS</A></FONT></TD>
<TD ALIGN=RIGHT HEIGHT=25><FONT FACE="Arial, Helvetica" SIZE=-1><A HREF="/122/47.html">NEXT</A> </FONT></TD>
<TD ALIGN=RIGHT WIDTH=1% VALIGN=MIDDLE><A HREF="/122/47.html"><IMG SRC="/images/newsite/gt.gif" BORDER=0 WIDTH=8 HEIGHT=17></A></TD></TR></TABLE></TD></TR>
<TR BGCOLOR="#B1B1B1"> <TD HEIGHT="1"><IMG SRC="/images/newsite/horiz_bar602.gif" WIDTH="603" HEIGHT="1"></TD></TR><TR><TD ALIGN=CENTER VALIGN=BOTTOM HEIGHT=25><FONT SIZE="-1">
<A HREF="/122/">CONTENTS</A> · <A HREF="/br/122.html">BIBLIOGRAPHIC RECORD</A>
</FONT></TD></TR></TABLE></FORM>
<!-- END TOP CHAPTER/SECTION NAV CODE -->
<TABLE ALIGN="CENTER" WIDTH="601" BORDER="0" CELLSPACING="2" CELLPADDING="0" BGCOLOR="#ffffff">
<!-- BEGIN CHAPTERTITLE -->
<TR><TD ALIGN="CENTER">Gerard Manley Hopkins <FONT SIZE="-1">(1844–89).</FONT> Poems. <FONT SIZE="-1">1918.</FONT></TD></TR>
<TR><TD> </TD></TR>
<TR><TD ALIGN="CENTER"><FONT COLOR="#9C9C63" SIZE="+1"><B>46. ‘Patience, hard thing! the hard thing but to pray’</B></FONT></TD></TR>
<TR><TD> </TD></TR>
<!-- END CHAPTERTITLE -->
</TABLE>
<TABLE ALIGN="CENTER" BORDER="0" WIDTH="601" CELLSPACING="0" CELLPADDING="3" BGCOLOR="#ffffff">
<TR><TD><TABLE ALIGN="CENTER" CELLSPACING="0" CELLPADDING="0">
<!-- BEGIN CHAPTER -->
<TR><TD> </TD></TR>
<TR><TD>P<FONT SIZE="-1">ATIENCE,</FONT> hard thing! the hard thing but to pray,</TD><TD><A NAME="1"></A></TD></TR>
<TR><TD>But bid for, Patience is! Patience who asks</TD><TD><A NAME="2"></A></TD></TR>
<TR><TD>Wants war, wants wounds; weary his times, his tasks;</TD><TD><A NAME="3"></A></TD></TR>
<TR><TD>To do without, take tosses, and obey.</TD><TD><A NAME="4"></A></TD></TR>
<TR><TD> Rare patience roots in these, and, these away,</TD><TD VALIGN="TOP" ALIGN="RIGHT"><FONT SIZE="-2"><A NAME="5"><I> 5</I></A></FONT></TD></TR>
<TR><TD>Nowhere. Natural heart’s ivy, Patience masks</TD><TD><A NAME="6"></A></TD></TR>
<TR><TD>Our ruins of wrecked past purpose. There she basks</TD><TD><A NAME="7"></A></TD></TR>
<TR><TD>Purple eyes and seas of liquid leaves all day.</TD><TD><A NAME="8"></A></TD></TR>
<TR><TD> </TD></TR>
<tr><TD> We hear our hearts grate on themselves: it kills</TD><TD><A NAME="9"></A></TD></TR>
<TR><TD>To bruise them dearer. Yet the rebellious wills</TD><TD VALIGN="TOP" ALIGN="RIGHT"><FONT SIZE="-2"><A NAME="10"><I> 10</I></A></FONT></TD></TR>
<TR><TD>Of us we do bid God bend to him even so.</TD><TD><A NAME="11"></A></TD></TR>
<TR><TD> And where is he who more and more distils</TD><TD><A NAME="12"></A></TD></TR>
<TR><TD>Delicious kindness?—He is patient. Patience fills</TD><TD><A NAME="13"></A></TD></TR>
<TR><TD>His crisp combs, and that comes those ways we know.</TD><TD><A NAME="14"></A></TD></TR>
<TR><TD> </TD></TR><TR><TD>See <A HREF="/122/1000.html#46">Notes</A>.</TD></TR>
<TR><TD> </TD></TR>
</TABLE>
</TABLE></TD></TR>
<!-- END CHAPTER -->
<!-- BOTTOM CHAPTER/SECTION NAV CODE -->
<TABLE ALIGN="CENTER" WIDTH="601" BORDER="0" CELLSPACING="0" CELLPADDING="0" BGCOLOR="#ffffff">
<TR><TD><BR></TD></TR><TR><TD ALIGN=CENTER VALIGN=TOP HEIGHT=25><FONT SIZE="-1">
<A HREF="/122/">CONTENTS</A> · <A HREF="/br/122.html">BIBLIOGRAPHIC RECORD</A></FONT></TD></TR>
<TR BGCOLOR="#B1B1B1"><TD HEIGHT="1"><IMG SRC="/images/newsite/horiz_bar602.gif" WIDTH="601" ALT="" HEIGHT="1"></TD></TR>
<TR><TD><TABLE WIDTH="601" BORDER="0" CELLSPACING="0" CELLPADDING="0" BGCOLOR="#ffffff"><TR><TD ALIGN=LEFT HEIGHT=25 WIDTH=1% VALIGN=MIDDLE><A HREF="/122/45.html"><IMG SRC="/images/newsite/lt.gif" BORDER=0 WIDTH=8 HEIGHT=17></A></TD>
<TD ALIGN=LEFT><FONT FACE="Arial, Helvetica" SIZE=-1> <A HREF="/122/45.html">PREVIOUS</A></FONT></TD>
<TD ALIGN=RIGHT HEIGHT=25><FONT FACE="Arial, Helvetica" SIZE=-1><A HREF="/122/47.html">NEXT</A> </FONT></TD>
<TD ALIGN=RIGHT WIDTH=1% VALIGN=MIDDLE><A HREF="/122/47.html"><IMG SRC="/images/newsite/gt.gif" BORDER=0 WIDTH=8 HEIGHT=17></A></TD></TR></TABLE></TD></TR>
<TR BGCOLOR="#B1B1B1"> <TD HEIGHT="1"><IMG SRC="/images/newsite/horiz_bar602.gif" ALT="" WIDTH="603" HEIGHT="1"></TD></TR>
<!-- END BOTTOM CHAPTER/SECTION NAV CODE -->
<!-- AMAZON -->
<TR><TD> </TD></TR>
<TR><TD><TABLE ALIGN="CENTER"><TR><TD ALIGN="RIGHT"><FORM METHOD="get" ACTION="http://www.amazon.com/exec/obidos/external-search">
<FONT FACE="verdana,arial,helvetica" SIZE=2><B>Search Amazon: </B></FONT><FONT FACE="verdana,arial,helvetica"><INPUT type="text" name="keyword" size="20" value=""> <INPUT BORDER=0 NAME=GO SRC="/adimages/go-button.gif" TYPE=IMAGE VALUE=GO></FONT><INPUT TYPE="hidden" NAME="mode" VALUE="blended"><INPUT TYPE="hidden" NAME="tag" VALUE="bartlebylibrary"></FORM></TD></TR></TABLE></TD></TR>
<TR><TD ALIGN=CENTER HEIGHT=25 WIDTH=1% VALIGN=MIDDLE><FONT FACE="Arial, Helvetica" SIZE=-1>Click <A href="/bookstore/HopkinsG.html">here</A> to shop the <A href="/bookstore/HopkinsG.html">Bartleby Bookstore</A>.</FONT></TD></TR>
<TR BGCOLOR="#B1B1B1"> <TD HEIGHT="1"><IMG SRC="/images/newsite/horiz_bar602.gif" ALT="" WIDTH="603" HEIGHT="1"></TD></TR>
<!-- insert footer -->
<TR VALIGN="bottom" ALIGN="center"><TD>
<A HREF="/sv/welcome.html" TARGET="_top"><FONT COLOR="#0b074f" FACE="Arial, Helvetica, sans-serif" SIZE="-2">Welcome</FONT></A> <FONT FACE="Arial, Helvetica, sans-serif" SIZE="-2">· <A HREF="/press/index.html" TARGET="_top"><FONT COLOR="#0b074f">Press</FONT></A> · <A HREF="/sv/advertising.html" TARGET="_top"><FONT COLOR="#0b074f">Advertising</FONT></A> · <A HREF="/link/" TARGET="_top"><FONT COLOR="#0b074f">Linking</FONT></A> · <A HREF="/sv/terms.html" TARGET="_top"><FONT COLOR="#0b074f">Terms of Use</FONT></A> · © 2003 <A HREF="/" TARGET="_top"><FONT COLOR="#0b074f">Bartleby.com</FONT></A></FONT>
</TD></TR>
<TR><TD> </TD></TR>
<!-- END FOOTER -->
</TABLE>
<TABLE BORDER="0" CELLPADDING="3" CELLSPACING="3" ALIGN="center"><TR><TD ALIGN="center"><A HREF="http://www.amazon.com/exec/obidos/redirect?tag=bartlebylibrary&path=ASIN/043935806X"><img src=/adimages/hp_120x60-hp-5-an.gif WIDTH="120" HEIGHT="60" BORDER="0"></A></TD>
<TD ALIGN="center">
<!-- BOTTOM AD CODE BEGIN -->
<!-- ---------- Advertising.com Banner Code -------------- -->
<CENTER>
<SCRIPT LANGUAGE=JavaScript>
var bnum=new Number(Math.floor(99999999 * Math.random())+1);
document.write('<SCR'+'IPT LANGUAGE="JavaScript" ');
document.write('SRC="http://servedby.advertising.com/site=62058/size=468060/bnum='+bnum+'/optn=1"></SCR'+'IPT>');
</SCRIPT>
<NOSCRIPT>
<A HREF="http://servedby.advertising.com/click/site=62058/bnum=16721052" TARGET="_blank">
<IMG SRC="http://servedby.advertising.com/site=62058/size=468060/bnum=16721052/bins=1/rich=0" WIDTH="468" HEIGHT="60" BORDER="0" ALT="Click to learn more...">
</A>
</NOSCRIPT>
</CENTER>
<!-- ---------- Copyright 2000, Advertising.com ---------- -->
</TD></TR></TABLE>
<!-- BOTTOM AD CODE END -->
</BODY>
</HTML>
|
unlicense
|
WALDOISCOMING/Java_Study
|
Java_BP/src/Chap05/StaticInitalizerExample2.java
|
279
|
package Chap05;
/*
* ÀÛ¼ºÀÏÀÚ:2017_03_09
* ÀÛ¼ºÀÚ:±æ°æ¿Ï
* ThreeArrays ÀÌ¿ë
* ¿¹Á¦ 5-43
*/
public class StaticInitalizerExample2 {
public static void main(String[] args){
for(int cnt=0;cnt<10;cnt++){
System.out.println(ThreeArrays.arr3[cnt]);
}
}
}
|
unlicense
|
jasonhutchens/thrust_harder
|
score.cpp
|
9032
|
//==============================================================================
#include <hgeresource.h>
#include <hgefont.h>
#include <hgesprite.h>
#include <sqlite3.h>
#include <Database.h>
#include <Query.h>
#include <score.hpp>
#include <engine.hpp>
//------------------------------------------------------------------------------
Score::Score( Engine * engine )
:
Context( engine ),
m_dark( 0 ),
m_calculate( false ),
m_lives( 0 ),
m_urchins( 0 ),
m_coins( 0 ),
m_time( 0 ),
m_timer( 0.0f ),
m_buffer( 0 ),
m_high_score()
{
}
//------------------------------------------------------------------------------
Score::~Score()
{
}
//------------------------------------------------------------------------------
// public:
//------------------------------------------------------------------------------
void
Score::init()
{
hgeResourceManager * rm( m_engine->getResourceManager() );
m_dark = new hgeSprite( 0, 0, 0, 1, 1 );
m_calculate = false;
HMUSIC music = m_engine->getResourceManager()->GetMusic( "score" );
m_engine->getHGE()->Music_Play( music, true, 100, 0, 0 );
_updateScore();
}
//------------------------------------------------------------------------------
void
Score::fini()
{
m_engine->getHGE()->Channel_StopAll();
delete m_dark;
m_dark = 0;
}
//------------------------------------------------------------------------------
bool
Score::update( float dt )
{
HGE * hge( m_engine->getHGE() );
hgeResourceManager * rm( m_engine->getResourceManager() );
hgeParticleManager * pm( m_engine->getParticleManager() );
if ( hge->Input_GetKey() != 0 && ! m_engine->isPaused() && ! m_calculate )
{
m_engine->switchContext( STATE_MENU );
}
if ( m_engine->isPaused() )
{
return false;
}
if ( m_calculate )
{
m_timer += dt;
if ( static_cast< int >( m_timer * 1000.0f ) % 2 == 0 )
{
if ( m_buffer > 0 )
{
m_buffer -= 1;
m_coins += 1;
float x( hge->Random_Float( 550.0f, 560.0f ) );
float y( hge->Random_Float( 268.0f, 278.0f ) );
hgeParticleSystem * particle =
pm->SpawnPS(& rm->GetParticleSystem("collect")->info, x, y);
if ( particle != 0 )
{
particle->SetScale( 1.0f );
}
hge->Effect_Play( rm->GetEffect( "bounce" ) );
}
else if ( m_lives > 0 )
{
m_lives -= 1;
m_buffer += 100;
hge->Effect_Play( rm->GetEffect( "collect" ) );
}
else if ( m_urchins > 0 )
{
m_urchins -= 1;
m_buffer += 10;
hge->Effect_Play( rm->GetEffect( "collect" ) );
}
else if ( m_time > 0 )
{
m_time -= 7;
if ( m_time < 0 )
{
m_time = 0;
}
m_buffer += 1;
hge->Effect_Play( rm->GetEffect( "collect" ) );
}
}
if ( m_buffer == 0 && m_lives == 0 && m_urchins == 0 && m_time == 0 )
{
int character( hge->Input_GetChar() );
if ( character != 0 )
{
if ( ( character == ' ' ||
character == '.' ||
character == '!' ||
character == '?' ||
( character >= '0' && character <= '9' ) ||
( character >= 'a' && character <= 'z' ) ||
( character >= 'A' && character <= 'Z' ) ) &&
m_name.size() <= 15 )
{
m_name.push_back( character );
}
}
if ( hge->Input_KeyDown( HGEK_BACKSPACE ) ||
hge->Input_KeyDown( HGEK_DELETE ) )
{
if ( m_name.size() > 0 )
{
m_name.erase( m_name.end() - 1 );
}
}
if ( hge->Input_KeyDown( HGEK_ENTER ) )
{
if ( m_name.size() == 0 )
{
m_name = "Anonymous";
}
Database db( "world.db3" );
Query q( db );
char query[1024];
sprintf_s( query, 1024, "INSERT INTO score(name, coins) "
"VALUES('%s',%d)", m_name.c_str(), m_coins );
q.execute( query );
_updateScore();
m_calculate = false;
}
}
}
else if ( dt > 0.0f && hge->Random_Float( 0.0f, 1.0f ) < 0.07f )
{
float x( hge->Random_Float( 0.0f, 800.0f ) );
float y( hge->Random_Float( 0.0f, 600.0f ) );
hgeParticleSystem * particle =
pm->SpawnPS( & rm->GetParticleSystem( "explode" )->info, x, y );
particle->SetScale( hge->Random_Float( 0.5f, 2.0f ) );
}
return false;
}
//------------------------------------------------------------------------------
void
Score::render()
{
hgeResourceManager * rm( m_engine->getResourceManager() );
if ( ! m_calculate )
{
m_engine->getParticleManager()->Render();
}
m_dark->SetColor( 0xCC000309 );
m_dark->RenderStretch( 100.0f, 50.0f, 700.0f, 550.0f );
hgeFont * font( rm->GetFont( "menu" ) );
if ( m_calculate )
{
font->printf( 400.0f, 80.0f, HGETEXT_CENTER, "G A M E O V E R" );
font->printf( 200.0f, 200.0f, HGETEXT_LEFT, "x %d", m_lives );
font->printf( 200.0f, 260.0f, HGETEXT_LEFT, "x %02d/99", m_urchins );
font->printf( 200.0f, 320.0f, HGETEXT_LEFT, "%03d", m_time );
font->printf( 580.0f, 260.0f, HGETEXT_LEFT, "x %04d", m_coins );
m_engine->getParticleManager()->Render();
rm->GetSprite( "ship" )->Render( 175.0f, 213.0f );
rm->GetSprite( "coin")->SetColor( 0xFFFFFFFF );
rm->GetSprite( "coin" )->Render( 555.0f, 273.0f );
rm->GetSprite( "urchin_green" )->Render( 175.0f, 273.0f );
if ( m_buffer == 0 && m_lives == 0 && m_urchins == 0 && m_time == 0 )
{
font->printf( 400.0f, 400.0f, HGETEXT_CENTER,
"%s", m_name.c_str() );
font->printf( 400.0f, 500.0f, HGETEXT_CENTER,
"(well done, you)" );
if ( static_cast<int>( m_timer * 2.0f ) % 2 != 0 )
{
float width = font->GetStringWidth( m_name.c_str() );
m_dark->SetColor( 0xFFFFFFFF );
m_dark->RenderStretch( 400.0f + width * 0.5f, 425.0f,
400.0f + width * 0.5f + 16.0f, 427.0f );
}
}
}
else
{
font->printf( 400.0f, 80.0f, HGETEXT_CENTER,
"H I G H S C O R E T A B L E" );
int i = 0;
std::vector< std::pair< std::string, int > >::iterator j;
for ( j = m_high_score.begin(); j != m_high_score.end(); ++j )
{
i += 1;
font->printf( 200.0f, 120.0f + i * 30.0f, HGETEXT_LEFT,
"(%d)", i );
font->printf( 400.0f, 120.0f + i * 30.0f, HGETEXT_CENTER,
"%s", j->first.c_str() );
font->printf( 600.0f, 120.0f + i * 30.0f, HGETEXT_RIGHT,
"%04d", j->second );
}
font->printf( 400.0f, 500.0f, HGETEXT_CENTER,
"(but you're all winners, really)" );
}
}
//------------------------------------------------------------------------------
void
Score::calculateScore( int lives, int urchins, int coins, int time )
{
m_timer = 0.0f;
m_buffer = 0;
m_calculate = true;
m_lives = lives;
m_urchins = urchins;
m_coins = coins;
m_time = time;
if ( lives == 0 || urchins == 0 )
{
m_time = 0;
}
m_name.clear();
if ( m_lives == 0 && m_time == 0 && m_coins == 0 && m_urchins == 0 )
{
m_calculate = false;
}
}
//------------------------------------------------------------------------------
// private:
//------------------------------------------------------------------------------
void
Score::_updateScore()
{
m_high_score.clear();
Database db( "world.db3" );
Query q( db );
q.get_result("SELECT coins, name FROM score ORDER BY coins DESC LIMIT 10");
while ( q.fetch_row() )
{
std::pair< std::string, int > pair( q.getstr(), q.getval() );
m_high_score.push_back( pair );
}
q.free_result();
}
|
unlicense
|
will-gilbert/SmartGWT-Mobile
|
mobile/src/main/java/com/smartgwt/mobile/client/widgets/tab/TabSet.java
|
42796
|
/*
* SmartGWT Mobile
* Copyright 2008 and beyond, Isomorphic Software, Inc.
*
* SmartGWT Mobile is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3
* as published by the Free Software Foundation. SmartGWT Mobile is also
* available under typical commercial license terms - see
* http://smartclient.com/license
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
/**
*
*/
package com.smartgwt.mobile.client.widgets.tab;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.smartgwt.mobile.SGWTInternal;
import com.smartgwt.mobile.client.core.Function;
import com.smartgwt.mobile.client.data.Record;
import com.smartgwt.mobile.client.data.RecordList;
import com.smartgwt.mobile.client.internal.EventHandler;
import com.smartgwt.mobile.client.internal.theme.TabSetCssResourceBase;
import com.smartgwt.mobile.client.internal.util.AnimationUtil;
import com.smartgwt.mobile.client.internal.widgets.tab.TabSetItem;
import com.smartgwt.mobile.client.theme.ThemeResources;
import com.smartgwt.mobile.client.types.SelectionStyle;
import com.smartgwt.mobile.client.types.TableMode;
import com.smartgwt.mobile.client.widgets.Canvas;
import com.smartgwt.mobile.client.widgets.ContainerFeatures;
import com.smartgwt.mobile.client.widgets.Panel;
import com.smartgwt.mobile.client.widgets.PanelContainer;
import com.smartgwt.mobile.client.widgets.ScrollablePanel;
import com.smartgwt.mobile.client.widgets.events.DropEvent;
import com.smartgwt.mobile.client.widgets.events.DropHandler;
import com.smartgwt.mobile.client.widgets.events.HasDropHandlers;
import com.smartgwt.mobile.client.widgets.events.HasPanelHideHandlers;
import com.smartgwt.mobile.client.widgets.events.HasPanelShowHandlers;
import com.smartgwt.mobile.client.widgets.events.PanelHideEvent;
import com.smartgwt.mobile.client.widgets.events.PanelHideHandler;
import com.smartgwt.mobile.client.widgets.events.PanelShowEvent;
import com.smartgwt.mobile.client.widgets.events.PanelShowHandler;
import com.smartgwt.mobile.client.widgets.grid.CellFormatter;
import com.smartgwt.mobile.client.widgets.grid.ListGridField;
import com.smartgwt.mobile.client.widgets.icons.IconResources;
import com.smartgwt.mobile.client.widgets.layout.HLayout;
import com.smartgwt.mobile.client.widgets.layout.Layout;
import com.smartgwt.mobile.client.widgets.layout.NavStack;
import com.smartgwt.mobile.client.widgets.tab.events.HasTabDeselectedHandlers;
import com.smartgwt.mobile.client.widgets.tab.events.HasTabSelectedHandlers;
import com.smartgwt.mobile.client.widgets.tab.events.TabDeselectedEvent;
import com.smartgwt.mobile.client.widgets.tab.events.TabDeselectedHandler;
import com.smartgwt.mobile.client.widgets.tab.events.TabSelectedEvent;
import com.smartgwt.mobile.client.widgets.tab.events.TabSelectedHandler;
import com.smartgwt.mobile.client.widgets.tableview.TableView;
import com.smartgwt.mobile.client.widgets.tableview.events.RecordNavigationClickEvent;
import com.smartgwt.mobile.client.widgets.tableview.events.RecordNavigationClickHandler;
public class TabSet extends Layout implements PanelContainer, HasTabSelectedHandlers, HasTabDeselectedHandlers, HasPanelShowHandlers, HasPanelHideHandlers, HasDropHandlers {
@SGWTInternal
public static final TabSetCssResourceBase _CSS = ThemeResources.INSTANCE.tabsCSS();
private static final int NO_TAB_SELECTED = -1,
MORE_TAB_SELECTED = -2;
private static class More extends NavStack {
private static final String ID_PROPERTY = "_id",
ICON_PROPERTY = "icon",
TAB_PROPERTY = "tab";
private static final ListGridField TITLE_FIELD = new ListGridField("-title") {{
setCellFormatter(new CellFormatter() {
@Override
public String format(Object value, Record record, int rowNum, int fieldNum) {
final Tab tab = (Tab)record.getAttributeAsObject(TAB_PROPERTY);
if (tab.getTitle() != null) return tab.getTitle();
final Canvas pane = tab.getPane();
if (pane != null) return pane.getTitle();
return null;
}
});
}};
private static int nextMoreRecordID = 1;
private static Record createMoreRecord(Tab tab) {
assert tab != null;
final Canvas pane = tab.getPane();
final Record record = new Record();
record.setAttribute(ID_PROPERTY, Integer.toString(nextMoreRecordID++));
Object icon = tab.getIcon();
if (icon == null && pane instanceof Panel) {
icon = ((Panel)pane).getIcon();
}
record.setAttribute(ICON_PROPERTY, icon);
record.setAttribute(TAB_PROPERTY, tab);
return record;
}
private ScrollablePanel morePanel;
private RecordList recordList;
private TableView tableView;
private HandlerRegistration recordNavigationClickRegistration;
//TileLayout tileLayout = null;
public More() {
super("More", IconResources.INSTANCE.more());
morePanel = new ScrollablePanel("More", IconResources.INSTANCE.more());
morePanel.getElement().getStyle().setBackgroundColor("#f7f7f7");
recordList = new RecordList();
tableView = new TableView();
tableView.setTitleField(TITLE_FIELD.getName());
tableView.setShowNavigation(true);
tableView.setSelectionType(SelectionStyle.SINGLE);
tableView.setParentNavStack(this);
tableView.setTableMode(TableMode.PLAIN);
tableView.setShowIcons(true);
recordNavigationClickRegistration = tableView.addRecordNavigationClickHandler(new RecordNavigationClickHandler() {
@Override
public void onRecordNavigationClick(RecordNavigationClickEvent event) {
final Record record = event.getRecord();
final Tab tab = (Tab)record.getAttributeAsObject(TAB_PROPERTY);
final TabSet tabSet = tab.getTabSet();
assert tabSet != null;
tabSet.swapTabs(recordList.indexOf(record) + tabSet.moreTabCount, tabSet.moreTabCount - 1);
tabSet.selectTab(tabSet.moreTabCount - 1, true);
}
});
tableView.setFields(TITLE_FIELD);
tableView.setData(recordList);
morePanel.addMember(tableView);
push(morePanel);
}
@Override
public void destroy() {
if (recordNavigationClickRegistration != null) {
recordNavigationClickRegistration.removeHandler();
recordNavigationClickRegistration = null;
}
super.destroy();
}
public final boolean containsNoTabs() {
return recordList.isEmpty();
}
public void addTab(Tab tab, int position) {
if (tab == null) throw new NullPointerException("`tab' cannot be null.");
final Record moreRecord = createMoreRecord(tab);
recordList.add(position, moreRecord);
}
public Tab removeTab(int position) {
return (Tab)recordList.remove(position).getAttributeAsObject(TAB_PROPERTY);
}
public void setTab(int position, Tab tab) {
if (tab == null) throw new NullPointerException("`tab' cannot be null.");
recordList.set(position, createMoreRecord(tab));
}
public void swapTabs(int i, int j) {
recordList.swap(i, j);
}
}
private final List<Tab> tabs = new ArrayList<Tab>();
// Tab bar to show tab widgets
private HLayout tabBar = new HLayout();
private int moreTabCount = 4;
private boolean showMoreTab = true;
private More more;
private Tab moreTab;
// paneContainer panel to hold tab panes
private Layout paneContainer;
//private final HashMap<Element, Tab> draggableMap = new HashMap<Element, Tab>();
//private Canvas draggable, droppable;
// Currently selected tab
private int selectedTabIndex = NO_TAB_SELECTED;
private transient Timer clearHideTabBarDuringFocusTimer;
public TabSet() {
getElement().addClassName(_CSS.tabSetClass());
setWidth("100%");
setHeight("100%");
paneContainer = new Layout();
paneContainer._setClassName(_CSS.tabPaneClass(), false);
addMember(paneContainer);
tabBar._setClassName(_CSS.tabBarClass(), false);
tabBar._setClassName("sc-layout-box-pack-center", false);
addMember(tabBar);
//sinkEvents(Event.ONCLICK | Event.ONMOUSEWHEEL | Event.GESTUREEVENTS | Event.TOUCHEVENTS | Event.MOUSEEVENTS | Event.FOCUSEVENTS | Event.KEYEVENTS);
_sinkFocusInEvent();
_sinkFocusOutEvent();
}
@SGWTInternal
public final Tab _getMoreTab() {
return moreTab;
}
public final Tab[] getTabs() {
return tabs.toArray(new Tab[tabs.size()]);
}
/**
* Sets the pane of the given tab.
*
* @param tab
* @param pane
*/
public void updateTab(Tab tab, Canvas pane) {
if (tab == null) throw new NullPointerException("`tab' cannot be null.");
final TabSet otherTabSet = tab.getTabSet();
assert otherTabSet != null : "`tab' is not in any TabSet. In particular, it is not in this TabSet.";
if (otherTabSet == null) {
tab._setPane(pane);
} else {
assert this == otherTabSet : "`tab' is in a different TabSet.";
if (this != otherTabSet) {
assert otherTabSet != null;
otherTabSet.updateTab(tab, pane);
} else {
final int tabPosition = getTabPosition(tab);
if (tabPosition < 0) throw new IllegalArgumentException("`tab' is not in this TabSet.");
updateTab(tabPosition, pane);
}
}
}
public void updateTab(int index, Canvas pane) throws IndexOutOfBoundsException {
if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index);
final Tab tab = tabs.get(index);
assert tab != null;
final Canvas oldPane = tab.getPane();
if (oldPane != pane) {
if (oldPane != null) paneContainer.removeMember(oldPane);
if (pane != null) {
paneContainer.addMember(pane);
if (selectedTabIndex != index) paneContainer.hideMember(pane);
}
tab._setPane(pane);
}
}
/*******************************************************
* Event handler registrations
******************************************************/
/**
* Add a tabSelected handler.
* <p/>
* Notification fired when a tab is selected.
*
* @param handler the tabSelectedHandler
* @return {@link HandlerRegistration} used to remove this handler
*/
@Override
public HandlerRegistration addTabSelectedHandler(TabSelectedHandler handler) {
return addHandler(handler, TabSelectedEvent.getType());
}
@Override
public HandlerRegistration addDropHandler(DropHandler handler) {
return addHandler(handler, DropEvent.getType());
}
/**
* Add a tabDeselected handler.
* <p/>
* Notification fired when a tab is unselected.
*
* @param handler the tabDeselectedHandler
* @return {@link HandlerRegistration} used to remove this handler
*/
@Override
public HandlerRegistration addTabDeselectedHandler(TabDeselectedHandler handler) {
return addHandler(handler, TabDeselectedEvent.getType());
}
/**
* ****************************************************
* Settings
* ****************************************************
*/
@SuppressWarnings("unused")
private Tab findTarget(Event event) {
Tab tab = null;
final int Y = (event.getTouches() != null && event.getTouches().length() > 0) ? event.getTouches().get(0).getClientY(): event.getClientY();
final int X = (event.getTouches() != null && event.getTouches().length() > 0) ? event.getTouches().get(0).getClientX(): event.getClientX();
if (Y >= tabBar.getAbsoluteTop() && !tabs.isEmpty()) {
final int width = tabs.get(0)._getTabSetItem().getElement().getOffsetWidth();
final int index = X / width;
if (0 <= index &&
((showMoreTab && index < moreTabCount) ||
(!showMoreTab && index < tabs.size())))
{
tab = tabs.get(index);
}
}
return tab;
}
@Override
public void onBrowserEvent(Event event) {
/*switch(event.getTypeInt()) {
case Event.ONMOUSEOVER:
if (!touched) {
if (draggable != null) {
final Tab tab = findTarget(event);
if (tab != null) {
droppable = tab._getTabSetItem();
droppable.fireEvent(new DropOverEvent());
} else if (droppable != null) {
droppable.fireEvent(new DropOutEvent());
droppable = null;
}
}
}
break;
case Event.ONTOUCHMOVE:
case Event.ONGESTURECHANGE:
if (draggable != null) {
final Tab tab = findTarget(event);
if (tab != null) {
droppable = tab._getTabSetItem();
droppable.fireEvent(new DropOverEvent());
} else if (droppable != null) {
droppable.fireEvent(new DropOutEvent());
droppable = null;
}
}
super.onBrowserEvent(event);
break;
case Event.ONMOUSEUP:
if (!touched) {
super.onBrowserEvent(event);
if (more != null && more.tileLayout != null) {
more.tileLayout.onEnd(event);
}
if (draggable != null && droppable != null) {
droppable.fireEvent(new DropEvent(draggable));
droppable = null;
}
}
break;
case Event.ONTOUCHEND:
case Event.ONGESTUREEND:
super.onBrowserEvent(event);
if (draggable != null && droppable != null) {
droppable.fireEvent(new DropEvent(draggable));
droppable = null;
}
break;
default:
super.onBrowserEvent(event);
break;
}*/
if (Canvas._getHideTabBarDuringKeyboardFocus()) {
// On Android devices, SGWT.mobile uses a technique similar to jQuery Mobile's hideDuringFocus
// setting to fix the issue that the tabBar unnecessarily takes up a portion of the screen
// when the soft keyboard is open. To work around this problem, when certain elements receive
// keyboard focus, we add a special class to the TabSet element that hides the tabBar.
// This special class is removed on focusout.
//
// One important consideration is that the user can move between input elements (such as
// by using the Next/Previous buttons or by tapping on a different input) and the soft
// keyboard will remain on screen. We don't want to show the tabBar only to hide it again.
// See: JQM Issue 4724 - Moving through form in Mobile Safari with "Next" and "Previous"
// system controls causes fixed position, tap-toggle false Header to reveal itself
// https://github.com/jquery/jquery-mobile/issues/4724
final String eventType = event.getType();
if ("focusin".equals(eventType)) {
if (EventHandler.couldShowSoftKeyboard(event)) {
if (clearHideTabBarDuringFocusTimer != null) {
clearHideTabBarDuringFocusTimer.cancel();
clearHideTabBarDuringFocusTimer = null;
}
getElement().addClassName(_CSS.hideTabBarDuringFocusClass());
}
} else if ("focusout".equals(eventType)) {
// If the related event target cannot result in the soft keyboard showing, then
// there is no need to wait; we can remove the hideTabBarDuringFocus class now.
if (event.getRelatedEventTarget() != null && !EventHandler.couldShowSoftKeyboard(event)) {
if (clearHideTabBarDuringFocusTimer != null) {
clearHideTabBarDuringFocusTimer.cancel();
clearHideTabBarDuringFocusTimer = null;
}
getElement().removeClassName(_CSS.hideTabBarDuringFocusClass());
// We use a timeout to clear the special CSS class because on Android 4.0.3 (possibly
// affects other versions as well), there is an issue where tapping in the 48px above
// the soft keyboard (where the tabBar would be) dismisses the soft keyboard.
} else {
clearHideTabBarDuringFocusTimer = new Timer() {
@Override
public void run() {
clearHideTabBarDuringFocusTimer = null;
getElement().removeClassName(_CSS.hideTabBarDuringFocusClass());
}
};
clearHideTabBarDuringFocusTimer.schedule(1);
}
}
}
}
@Override
public void onLoad() {
super.onLoad();
// There is a very strange `TabSet' issue on iOS 6 Mobile Safari, but which does not appear
// in iOS 5.0 or 5.1. For some reason, if the tabSelectedClass() is added to a `TabSetItem',
// but the selected class is removed before the `TabSetItem' element is added to the document
// later on, then the SGWT.mobile app will fail to load. However, if Web Inspector is attached,
// then the app runs fine.
//
// This issue affects Showcase. In Showcase, the "Overview" tab is first selected when
// it is added to the app's `TabSet' instance. It is then deselected when the "Widgets"
// tab is programmatically selected.
// To see the issue, comment out the check `if (Canvas._isIOSMin6_0() && !isAttached()) return;' in TabSetItem.setSelected(), then
// compile & run Showcase in iOS 6 Mobile Safari.
if (Canvas._isIOSMin6_0() && selectedTabIndex > 0) {
tabs.get(selectedTabIndex)._getTabSetItem().setSelected(true);
}
}
/*******************************************************
* Add/Remove tabs
******************************************************/
@SGWTInternal
public void _onTabDrop(TabSetItem tabSetItem, DropEvent event) {
/*Object source = event.getSource();
if(source instanceof Tab) {
tab.getElement().getStyle().setProperty("backgroundImage", "none");
TileLayout.Tile draggable = (TileLayout.Tile)event.getData();
Record record = TabSet.this.more.recordList.find("title",draggable.getTitle());
if(record != null) {
Panel newPanel = (Panel)record.get("panel");
final int currentPosition = tabBar.getMemberNumber(tab);
TabSet.this.replacePanel(currentPosition, newPanel);
TileLayout tileLayout = (TileLayout)more.top();
tileLayout.replaceTile(draggable, tab.getTitle(), tab.getIcon());
more.recordList.remove(record);
// final Panel oldPanel = tab.getPane() instanceof NavStack ? ((NavStack)tab.getPane()).top() : (Panel)tab.getPane();
final Panel oldPanel = (Panel)tab.getPane();
oldPanel.getElement().getStyle().clearDisplay();
final Record finalRecord = record;
more.recordList.add(0,new Record() {{put("_id", finalRecord.getAttribute("_id")); put("title", tab.getTitle()); put("icon", tab.getIcon());put("panel", oldPanel);}});
more.tableView.setData(more.recordList);
}
}*/
}
private void swapTabs(int i, int j) {
final int numTabs = tabs.size();
assert 0 <= i && i < numTabs;
assert 0 <= j && j < numTabs;
if (i == j) return;
// Make sure that i < j.
if (!(i < j)) {
final int tmp = i;
i = j;
j = tmp;
}
assert i < j;
final Tab tabI = tabs.get(i), tabJ = tabs.get(j);
assert tabI != null && tabJ != null;
final TabSetItem tabSetItemI = tabI._getTabSetItem(),
tabSetItemJ = tabJ._getTabSetItem();
final Canvas paneI = tabI.getPane(), paneJ = tabJ.getPane();
tabs.set(i, tabJ);
tabs.set(j, tabI);
if (showMoreTab && numTabs > moreTabCount) {
assert more != null;
if (j >= moreTabCount) {
if (i >= moreTabCount) {
// Both tabs are in the More NavStack.
assert i != selectedTabIndex : "The tab at index " + i + " is supposed to be selected, but it is still in the More NavStack.";
assert j != selectedTabIndex : "The tab at index " + j + " is supposed to be selected, but it is still in the More NavStack.";
more.swapTabs(i - moreTabCount, j - moreTabCount);
} else {
// The Tab at `j' is in the More NavStack, but the Tab at `i' is not.
assert j != selectedTabIndex : "The tab at index " + j + " is supposed to be selected, but it is still in the More NavStack.";
if (i == selectedTabIndex) {
tabSetItemI.setSelected(false);
if (paneI != null) paneContainer.hideMember(paneI);
}
tabBar.removeMember(tabSetItemI);
more.setTab(j - moreTabCount, tabI);
tabBar.addMember(tabSetItemJ, i);
if (i == selectedTabIndex) {
tabSetItemJ.setSelected(true);
if (paneJ != null) paneContainer.showMember(paneJ);
TabDeselectedEvent._fire(this, tabI, j, tabJ);
TabSelectedEvent._fire(this, tabJ, i);
} else {
if (paneJ != null) paneContainer.hideMember(paneJ);
}
}
} else {
// Neither tab is in the More NavStack.
assert selectedTabIndex != MORE_TAB_SELECTED;
tabBar.removeMember(tabSetItemI);
// TODO Don't remove the panes to save on calls to onLoad(), onUnload(), onAttach(), and onDetach().
if (paneI != null && paneContainer.hasMember(paneI)) paneContainer.removeMember(paneI);
tabBar.removeMember(tabSetItemJ);
if (paneJ != null && paneContainer.hasMember(paneJ)) paneContainer.removeMember(paneJ);
tabSetItemJ.setSelected(i == selectedTabIndex);
tabBar.addMember(tabSetItemJ, i);
if (paneJ != null) {
paneContainer.addMember(paneJ);
if (i != selectedTabIndex) paneContainer.hideMember(paneJ);
}
tabSetItemI.setSelected(j == selectedTabIndex);
tabBar.addMember(tabSetItemI, j);
if (paneI != null) {
paneContainer.addMember(paneI);
if (j != selectedTabIndex) paneContainer.hideMember(paneI);
}
if (i == selectedTabIndex) {
selectedTabIndex = j;
TabDeselectedEvent._fire(this, tabI, j, tabJ);
TabSelectedEvent._fire(this, tabJ, i);
} else if (j == selectedTabIndex) {
selectedTabIndex = i;
TabDeselectedEvent._fire(this, tabJ, i, tabI);
TabSelectedEvent._fire(this, tabI, j);
}
}
}
}
/**
* Creates a {@link com.smartgwt.mobile.client.widgets.tab.Tab} and adds it to the end.
*
* <p>This is equivalent to:
* <pre>
* final Tab tab = new Tab(panel.getTitle(), panel.getIcon());
* tabSet.addTab(tab);
* </pre>
*
* @param panel the panel to add.
* @return the automatically created <code>Tab</code>.
*/
public Tab addPanel(Panel panel) {
final Tab tab = new Tab(panel.getTitle(), panel.getIcon());
tab.setPane(panel);
addTab(tab);
return tab;
}
/**
* Add a tab to the end.
*
* @param tab the tab to add.
*/
public void addTab(Tab tab) {
addTab(tab, tabs.size());
}
/**
* Add a tab at the given position.
*
* @param tab the tab to add.
* @param position the index where the tab should be added. It is clamped within range
* (0 through {@link #getNumTabs()}, inclusive) if out of bounds.
*/
public void addTab(Tab tab, int position) {
if (tab == null) throw new NullPointerException("`tab' cannot be null.");
assert tab != moreTab;
// Clamp `position' within range.
position = Math.max(0, Math.min(position, tabs.size()));
// Remove the tab if it exists.
final int existingIndex = getTabPosition(tab);
if (existingIndex >= 0) {
// If the tab is being added in the exact same place, then return early.
if (existingIndex == position) return;
removeTab(existingIndex);
if (existingIndex < position) --position;
}
final int currentNumTabs = tabs.size();
tabs.add(position, tab);
final TabSetItem tabSetItem = tab._ensureTabSetItem(this);
assert tab.getTabSet() == this;
// Add the tab's pane to `paneContainer'.
final Canvas pane = tab.getPane();
if (pane != null) {
paneContainer.addMember(pane);
paneContainer.hideMember(pane);
}
if (currentNumTabs + 1 > moreTabCount && showMoreTab) {
if (more == null) {
more = new More();
assert moreTab == null;
moreTab = new Tab(more.getTitle(), more.getIcon());
moreTab.setPane(more);
// The TabSetItem of `moreTab' and its pane (`more') are added to `tabBar' and
// `paneContainer', respectively, but we don't want to add `moreTab' to `tabs';
// we don't want to treat the More tab like a tab that was explicitly added.
tabBar.addMember(moreTab._ensureTabSetItem(this), moreTabCount);
paneContainer.addMember(more);
paneContainer.hideMember(more);
}
if (position >= moreTabCount) {
// Add to the More.
more.addTab(tab, position - moreTabCount);
} else {
// Add the TabSetItem to `tabBar'.
tabBar.addMember(tabSetItem, position);
// That pushes one of the visible tabs into More.
final Tab otherTab = tabs.get(moreTabCount);
final TabSetItem otherTabSetItem = otherTab._getTabSetItem();
if (moreTabCount == selectedTabIndex) {
otherTabSetItem.setSelected(false);
selectedTabIndex = NO_TAB_SELECTED;
}
tabBar.removeMember(otherTabSetItem);
final Canvas otherPane = otherTab.getPane();
if (otherPane != null) paneContainer.removeMember(otherPane);
more.addTab(otherTab, 0);
}
} else {
// Add the TabSetItem to `tabBar'.
tabBar.addMember(tabSetItem, position);
}
if (selectedTabIndex == NO_TAB_SELECTED) {
selectTab(position);
}
}
/**
* Remove a tab.
*
* @param tab to remove
*/
public void removeTab(Tab tab) {
assert tab == null || tab != moreTab;
int index = tabs.indexOf(tab);
if (index >= 0) {
removeTab(index);
}
}
/**
* Remove a tab at the specified index.
*
* @param position the index of the tab to remove
*/
public void removeTab(int position) {
final int currentNumTabs = tabs.size();
if (0 <= position && position < currentNumTabs) {
final Tab tab = tabs.get(position);
assert tab != null;
assert tab != moreTab;
tabs.remove(position);
final TabSetItem tabSetItem = tab._getTabSetItem();
if (!showMoreTab || position < moreTabCount) {
tabBar.removeMember(tabSetItem);
if (showMoreTab && currentNumTabs - 1 >= moreTabCount) {
// Move a tab from More to the tab bar.
final Tab firstMoreTab = more.removeTab(0);
final Tab otherTab = tabs.get(moreTabCount - 1);
assert firstMoreTab == otherTab;
final TabSetItem otherTabSetItem = otherTab._getTabSetItem();
tabBar.addMember(otherTabSetItem, moreTabCount - 1);
}
} else {
assert more != null;
more.removeTab(position - moreTabCount);
}
if (showMoreTab && currentNumTabs - 1 == moreTabCount) {
// The More tab is no longer needed. Remove & destroy it.
assert more.containsNoTabs();
final TabSetItem moreTabSetItem = moreTab._getTabSetItem();
tabBar.removeMember(moreTabSetItem);
assert paneContainer.hasMember(more);
paneContainer.removeMember(more);
if (selectedTabIndex == MORE_TAB_SELECTED) {
assert more != null && moreTab.getPane() == more;
selectedTabIndex = NO_TAB_SELECTED;
}
moreTab._destroyTabSetItem();
moreTab._setTabSet(null);
moreTab.setPane(null);
moreTab = null;
more.destroy();
more = null;
}
final Canvas pane = tab.getPane();
if (pane != null) paneContainer.removeMember(pane);
tab._setTabSet(null);
if (position == selectedTabIndex) {
selectedTabIndex = -1;
tabSetItem.setSelected(false);
TabDeselectedEvent._fire(this, tab, -1, null);
}
}
}
/**
* Remove one or more tabs at the specified indexes.
*
* @param tabIndexes array of tab indexes
*/
public void removeTabs(int[] tabIndexes) {
if (tabIndexes == null) return;
// Sort the indexes and remove the corresponding tabs in descending order.
Arrays.sort(tabIndexes);
for (int ri = tabIndexes.length; ri > 0; --ri) {
removeTab(tabIndexes[ri - 1]);
}
}
/*******************************************************
* Update tabs
******************************************************/
/*******************************************************
* Selections
******************************************************/
/**
* Returns the index of the currently selected tab.
*
* @return -2 if the More tab is selected; otherwise, the index of the currently selected tab,
* or -1 if no tab is selected.
*/
public final int getSelectedTabNumber() {
return selectedTabIndex;
}
/**
* Returns the currently selected tab.
*
* @return the currently selected tab, or <code>null</code> if the More tab is selected
* or no tab is selected.
*/
public final Tab getSelectedTab() {
final int index = selectedTabIndex;
return (index >= 0 ? tabs.get(index) : null);
}
@SGWTInternal
public void _selectMoreTab() {
assert more != null && moreTab != null;
if (selectedTabIndex != MORE_TAB_SELECTED) {
if (selectedTabIndex != NO_TAB_SELECTED) {
final Tab otherTab = tabs.get(selectedTabIndex);
final TabSetItem otherTabSetItem = otherTab._getTabSetItem();
final Canvas otherPane = otherTab.getPane();
otherTabSetItem.setSelected(false);
if (otherPane != null) paneContainer.hideMember(otherPane);
// Even though the event's `newTab' could be considered `moreTab', we don't
// pass `moreTab' as the third parameter to avoid exposing a reference to this
// internal object.
TabDeselectedEvent._fire(this, otherTab, selectedTabIndex, null);
}
final TabSetItem moreTabSetItem = moreTab._getTabSetItem();
assert moreTab.getPane() == more;
moreTabSetItem.setSelected(true);
paneContainer.showMember(more);
selectedTabIndex = MORE_TAB_SELECTED;
}
}
/**
* Select a tab by index
*
* @param index the tab index
*/
public void selectTab(int index) throws IndexOutOfBoundsException {
selectTab(index, false);
}
private void selectTab(int index, boolean animate) throws IndexOutOfBoundsException {
if (tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index);
final Tab tab;
if (index < 0) {
// Allow a negative `index' to mean deselect the currently selected Tab (if any).
tab = null;
index = NO_TAB_SELECTED;
} else {
tab = tabs.get(index);
if (tab.getDisabled()) return;
}
if (selectedTabIndex >= 0) {
final Tab oldSelectedTab = tabs.get(selectedTabIndex);
if (index == selectedTabIndex) return;
final TabSetItem oldSelectedTabSetItem = oldSelectedTab._getTabSetItem();
oldSelectedTabSetItem.setSelected(false);
final Canvas oldSelectedPane = oldSelectedTab.getPane();
if (oldSelectedPane != null) {
paneContainer.hideMember(oldSelectedPane);
if (oldSelectedPane instanceof Panel) PanelHideEvent.fire(this, (Panel)oldSelectedPane);
}
TabDeselectedEvent._fire(this, oldSelectedTab, selectedTabIndex, tab);
} else if (selectedTabIndex == MORE_TAB_SELECTED) {
assert more != null && moreTab != null;
final TabSetItem moreTabSetItem = moreTab._getTabSetItem();
moreTabSetItem.setSelected(false);
assert moreTab.getPane() == more;
if (!animate) paneContainer.hideMember(more);
}
if (index >= 0) {
assert tab != null;
final TabSetItem tabSetItem = tab._getTabSetItem();
if (showMoreTab && index >= moreTabCount) {
final Tab otherTab = tabs.get(moreTabCount - 1);
tabs.set(moreTabCount - 1, tab);
tabs.set(index, otherTab);
tabBar.removeMember(otherTab._getTabSetItem());
tabBar.addMember(tabSetItem, moreTabCount - 1);
assert more != null;
more.setTab(index - moreTabCount, otherTab);
index = moreTabCount - 1;
}
tabSetItem.setSelected(true);
final Canvas pane = tab.getPane();
if (pane != null) {
if (selectedTabIndex == MORE_TAB_SELECTED && animate) {
final Function<Void> callback;
if (!(pane instanceof Panel)) callback = null;
else {
callback = new Function<Void>() {
@Override
public Void execute() {
assert pane instanceof Panel;
PanelShowEvent.fire(TabSet.this, (Panel)pane);
return null;
}
};
}
AnimationUtil.slideTransition(more, pane, paneContainer, AnimationUtil.Direction.LEFT, null, callback, false);
} else {
paneContainer.showMember(pane);
if (pane instanceof Panel) PanelShowEvent.fire(this, (Panel)pane);
}
}
selectedTabIndex = index;
TabSelectedEvent._fire(this, tab, index);
if (_HISTORY_ENABLED) History.newItem(tab.getTitle());
} else selectedTabIndex = NO_TAB_SELECTED;
}
/**
* Select a tab.
*
* @param tab the canvas representing the tab
*/
public void selectTab(Tab tab) {
assert tab == null || tab != moreTab;
int index = tab == null ? -1 : getTabPosition(tab);
selectTab(index);
}
/*******************************************************
* Enable/disable tabs
******************************************************/
public void enableTab(String id) {
enableTab(getTab(id));
}
public void enableTab(Tab tab) {
final int position = getTabPosition(tab);
if (position >= 0) {
assert position < tabs.size();
enableTab(position);
}
}
/**
* Enable a tab if it is currently disabled.
*
* @param index the tab index
*/
public void enableTab(int index) throws IndexOutOfBoundsException {
if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index);
final Tab tab = tabs.get(index);
tab.setDisabled(false);
}
/**
* Disable a tab if it is currently enabled. If the tab is selected, it is deselected.
*
* @param index the tab index
*/
public void disableTab(int index) throws IndexOutOfBoundsException {
if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index);
final Tab tab = tabs.get(index);
tab.setDisabled(true);
if (selectedTabIndex == index) {
selectTab(-1);
}
}
/*******************************************************
* State and tab query methods
******************************************************/
public final int getNumTabs() {
return tabs.size();
}
public final int getTabCount() {
return getNumTabs();
}
private final int getTabPosition(Tab other) {
if (other == null) return -1;
final int tabs_size = tabs.size();
for (int i = 0; i < tabs_size; ++i) {
if (tabs.get(i).equals(other)) return i;
}
return -1;
}
/**
* Returns the canvas representing a tab.
*
* @param tabIndex index of tab
* @return the tab widget or null if not found
*/
public final Tab getTab(int tabIndex) {
if (0 <= tabIndex && tabIndex < tabs.size()) {
return tabs.get(tabIndex);
}
return null;
}
public final Tab getTab(String id) {
if (id == null) return null;
final int tabs_size = tabs.size();
for (int i = 0; i < tabs_size; ++i) {
final Tab tab = tabs.get(i);
if (id.equals(tab.getID())) return tab;
}
return null;
}
/**
* ****************************************************
* Helper methods
* ****************************************************
*/
@Override
public ContainerFeatures getContainerFeatures() {
return new ContainerFeatures(this, true, false, false, true, 0);
}
@Override
public HandlerRegistration addPanelHideHandler(PanelHideHandler handler) {
return addHandler(handler, PanelHideEvent.getType());
}
@Override
public HandlerRegistration addPanelShowHandler(PanelShowHandler handler) {
return addHandler(handler, PanelShowEvent.getType());
}
public void setMoreTabCount(int moreTabCount) {
if (this.moreTabCount == moreTabCount) return;
// We need moreTabCount to be at least one so that we can swap out a non-More tab
// with the selected tab.
if (moreTabCount < 1) throw new IllegalArgumentException("`moreTabCount' must be at least 1.");
if (more != null) throw new IllegalStateException("`moreTabCount' cannot be changed once the More tab has been created.");
if (tabs.size() > moreTabCount && showMoreTab) throw new IllegalArgumentException("`moreTabCount` cannot be set to a number less than the current number of tabs.");
this.moreTabCount = moreTabCount;
}
public final int getMoreTabCount() {
return moreTabCount;
}
public void setShowMoreTab(boolean showMoreTab) {
if (this.showMoreTab == showMoreTab) return;
if (more != null) throw new IllegalStateException("`showMoreTab' cannot be changed once the More tab has been created.");
if (tabs.size() > moreTabCount && showMoreTab) throw new IllegalArgumentException("The More tab cannot be enabled now that there are already more than `this.getMoreTabCount()' tabs in this TabSet.");
this.showMoreTab = showMoreTab;
}
//public void setDraggable(Canvas draggable) {
// this.draggable = draggable;
//}
}
|
unlicense
|
dret/HTML5-overview
|
_posts/2014-02-11-update.md
|
471
|
---
layout: post
title: "added \"Navigation Error Logging\"; changed status of \"Progress Events\" from PR to REC; changed status of \"Vibration API\" from CR to WD"
date: 2014-02-11
tags: [ navigation-error-logging , progress-events , vibration ]
---
added "[Navigation Error Logging](/spec/navigation-error-logging)"; changed status of "[Progress Events](/spec/progress-events)" from PR to REC; changed status of "[Vibration API](/spec/vibration)" from CR to WD
|
unlicense
|
cartman300/Kernel
|
3rdParty/PDCLib/functions/uchar/mbrtoc32.c
|
1726
|
/* size_t mbrtoc32( char32_t *, const char *, size_t, mbstate_t * )
This file is part of the Public Domain C Library (PDCLib).
Permission is granted to use, modify, and / or redistribute at will.
*/
#ifndef REGTEST
#include <uchar.h>
#include <errno.h>
#include <stdint.h>
#include <assert.h>
#include "_PDCLIB_encoding.h"
#include "_PDCLIB_locale.h"
size_t mbrtoc32_l(
char32_t *restrict pc32,
const char *restrict s,
size_t n,
mbstate_t *restrict ps,
locale_t l
)
{
size_t dstlen = 1;
size_t nr = n;
if(l->_Codec->__mbstoc32s(&pc32, &dstlen, &s, &nr, ps)) {
// Successful conversion
if(dstlen == 0) {
// A character was output
if(nr == n) {
// The output character resulted entirely from stored state
// With UTF-32, this shouldn't be possible?
return (size_t) -3;
} else if(pc32[-1] == 0) {
// Was null character
return 0;
} else {
// Count of processed characters
return n - nr;
}
} else {
assert(nr == 0 && "Must have processed whole input");
return (size_t) -2;
}
} else {
// Failed conversion
errno = EILSEQ;
return (size_t) -1;
}
}
size_t mbrtoc32(
char32_t *restrict pc32,
const char *restrict s,
size_t n,
mbstate_t *restrict ps
)
{
return mbrtoc32_l(pc32, s, n, ps, _PDCLIB_threadlocale());
}
#endif
#ifdef TEST
#include "_PDCLIB_test.h"
int main( void )
{
TESTCASE( NO_TESTDRIVER );
return TEST_RESULTS;
}
#endif
|
unlicense
|
zugoth/1314-adb
|
src/main/java/com/rhcloud/zugospoint/DAO/ApplicationDAO.java
|
1320
|
/**
*
*/
package com.rhcloud.zugospoint.DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.rhcloud.zugospoint.model.*;
import com.rhcloud.zugospoint.util.HibernateUtil;
/**
* Klasa zawiera zbior niskopoziomowych metod dostepu do danych z bazy
* @author zugo
*
*/
public class ApplicationDAO {
private SessionFactory sessionF;
public ApplicationDAO (){
sessionF = HibernateUtil.getSessionFactory();
}
public void addAdres(Adres theAdres)
{
Session session = sessionF.getCurrentSession();
try{
session.beginTransaction();
session.save(theAdres);
session.getTransaction().commit();
session.close();
}catch (HibernateException e){
session.getTransaction().rollback();
e.printStackTrace();
session.close();
}
}
@SuppressWarnings("unchecked")
public List<Adres> getAllAdreses(){
Session s = sessionF.getCurrentSession();
List<Adres> res = null;
try{
s.beginTransaction();
res = s.createQuery("from Adres").list();
s.getTransaction().commit();
s.close();
}catch (HibernateException e){
s.getTransaction().rollback();
e.printStackTrace();// TODO throw apropriate exception when catch it, or not, considere it
s.close();
}
return res;
}
}
|
unlicense
|
thakurarun/Basic-nodejs-express-app
|
samplenode/samplenode/server/model/User.js
|
104
|
var User = {
title : 'Customer',
LoginTitleText : 'Register yourself'
}
module.exports = User;
|
unlicense
|
KenetJervet/rust-notes
|
tutorials/05-functions/src/main.rs
|
191
|
fn main() {
println!("3 + 4.3 = {}", add(3, 4.3));
}
// Cannot omit any argument type or return value type
// unless you return void
fn add(a: i32, b: f64) -> f64 {
(a as f64) + b
}
|
unlicense
|
Thatdamnqa/mancmetfeed2
|
vendor/phpunit/phpunit/tests/Util/JsonTest.php
|
2567
|
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Util;
use PHPUnit\Framework\TestCase;
class JsonTest extends TestCase
{
/**
* @dataProvider canonicalizeProvider
*
* @param mixed $actual
* @param mixed $expected
* @param mixed $expectError
*
* @throws \Exception
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testCanonicalize($actual, $expected, $expectError): void
{
[$error, $canonicalized] = Json::canonicalize($actual);
$this->assertEquals($expectError, $error);
if (!$expectError) {
$this->assertEquals($expected, $canonicalized);
}
}
/**
* @return array
*/
public function canonicalizeProvider()
{
return [
['{"name":"John","age":"35"}', '{"age":"35","name":"John"}', false],
['{"name":"John","age":"35","kids":[{"name":"Petr","age":"5"}]}', '{"age":"35","kids":[{"age":"5","name":"Petr"}],"name":"John"}', false],
['"name":"John","age":"35"}', '{"age":"35","name":"John"}', true],
];
}
/**
* @dataProvider prettifyProvider
*
* @param mixed $actual
* @param mixed $expected
*
* @throws \Exception
* @throws \PHPUnit\Framework\Exception
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function testPrettify($actual, $expected): void
{
$this->assertEquals($expected, Json::prettify($actual));
}
/**
* @return array
*/
public function prettifyProvider()
{
return [
['{"name":"John","age": "5"}', "{\n \"name\": \"John\",\n \"age\": \"5\"\n}"],
];
}
/**
* @dataProvider prettifyExceptionProvider
* @expectedException \PHPUnit\Framework\Exception
* @expectedExceptionMessage Cannot prettify invalid json
*
* @param mixed $json
*/
public function testPrettifyException($json): void
{
Json::prettify($json);
}
/**
* @return array
*/
public function prettifyExceptionProvider()
{
return [
['"name":"John","age": "5"}'],
[''],
];
}
}
|
unlicense
|
dk00/old-stuff
|
csie/08design-patterns/src/com/sun/tools/javac/code/BoundKind.java
|
473
|
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package com.sun.tools.javac.code;
public enum BoundKind {
EXTENDS("? extends "),
SUPER("? super "),
UNBOUND("?");
private final String name;
BoundKind(String name) {
this.name = name;
}
public String toString() { return name; }
}
|
unlicense
|
gkellogg/gkellogg.github.io
|
galleries/channel-islands-2011-08-01/content/Channel_Islands_20100731_81_large.html
|
3548
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<meta name="Keywords" content="photography,software,photos,digital darkroom,gallery,image,photographer,adobe,photoshop,lightroom" >
<meta name="generator" content="Adobe Photoshop Lightroom" >
<title>Channel Islands July/August 2011</title>
<link rel="stylesheet" type="text/css" media="screen" title="Custom Settings" href="./custom.css" >
<link rel="stylesheet" type="text/css" media="screen" title="Custom Settings" href="../resources/css/master.css" >
<script type="text/javascript">
window.AgMode = "publish";
cellRolloverColor="#A1A1A1";
cellColor="#949494";
</script>
<script type="text/javascript" src="../resources/js/live_update.js">
</script>
<!--[if lt IE 7.]> <script defer type="text/javascript" src="../resources/js/pngfix.js"></script> <![endif]-->
<!--[if gt IE 6]> <link rel="stylesheet" href="../resources/css/ie7.css"></link> <![endif]-->
<!--[if lt IE 7.]> <link rel="stylesheet" href="../resources/css/ie6.css"></link> <![endif]-->
</head>
<body>
<div id="wrapper_large">
<div id="sitetitle">
<h1 onclick="clickTarget( this, 'metadata.siteTitle.value' );" id="metadata.siteTitle.value" class="textColor">Channel Islands July/August 2011</h1>
</div>
<div id="collectionHeader">
<h1 onclick="clickTarget( this, 'metadata.groupTitle.value' );" id="metadata.groupTitle.value" class="textColor">Diving on the Horizon</h1>
<p onclick="clickTarget( this, 'metadata.groupDescription.value' );" id="metadata.groupDescription.value" class="textColor">Web Photo Gallery created by Adobe Lightroom.</p>
</div>
<div id="stage2">
<div id="previewFull" class="borderTopLeft borderBottomRight">
<div id="detailTitle" class="detailText">
</div>
<div class="detailNav">
<ul>
<li class="previous"> <a class="paginationLinks detailText" href="../content/Channel_Islands_20100731_78_large.html">Previous</a> </li>
<li class="index"> <a href="../index_2.html" class="detailLinks detailText">Index</a> </li>
<li class="next"> <a class="paginationLinks detailText" href="../content/Channel_Islands_20100731_115_large.html">Next</a> </li>
</ul>
</div>
<a href="../index_2.html">
<div style="margin-left:15px;">
<div class="dropShadow">
<div class="inner">
<img src="images/large/Channel_Islands_20100731_81.jpg"
class="previewFullImage preview"
id="previewImage"
alt=""
onclick="var node=parentNode.parentNode.parentNode.parentNode; if( node.click ) { return node.click(); } else { return true; }">
</div>
</div>
</div>
</a>
<div style="clear:both; height:5px"></div>
<div id="detailCaption" class="detailText">
</div>
</div>
</div>
<div class="clear">
</div>
<div id="contact">
<a href="mailto:[email protected]"> <span
class="textColor" id="metadata.contactInfo.value">Gregg Kellogg</span>
</a>
</div>
<div class="clear">
</div>
</div>
</body>
</html>
|
unlicense
|
en/clrs
|
bucket_sort_test.go
|
863
|
package clrs
import (
"reflect"
"testing"
)
func TestBucketSort(t *testing.T) {
cases := []struct {
a []float64
want []float64
}{
{
[]float64{0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68},
[]float64{0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94},
},
{
[]float64{0.79, 0.13, 0.16, 0.64, 0.39, 0.20, 0.89, 0.53, 0.71, 0.42},
[]float64{0.13, 0.16, 0.20, 0.39, 0.42, 0.53, 0.64, 0.71, 0.79, 0.89},
},
{
[]float64{0.79, 0.13, 0.16, 0.64, 0.39, 0.20, 0.89, 0.53, 0.71, 0.42, 0.99},
[]float64{0.13, 0.16, 0.20, 0.39, 0.42, 0.53, 0.64, 0.71, 0.79, 0.89, 0.99},
},
}
for _, c := range cases {
in := make([]float64, len(c.a))
copy(in, c.a)
bucketSort(in)
if !reflect.DeepEqual(in, c.want) {
t.Errorf("sorted %v", c.a)
t.Errorf(" got %v", in)
t.Errorf(" want %v", c.want)
}
}
}
|
unlicense
|
lvdlvd/go-net-http-tmpl
|
demo/main.go
|
1273
|
// Demo for the template server
package main
import (
"database/sql"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"os"
tmpl "../../go-net-http-tmpl"
_ "github.com/mattn/go-sqlite3"
)
var (
port = flag.String("http", ":6060", "Port to serve http on.")
templates = flag.String("templates", "./*.html", "Path to dir with template webpages.")
)
func main() {
os.Remove("./foo.db")
defer os.Remove("./foo.db")
db, err := sql.Open("sqlite3", "./foo.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
prepareDB(db)
h := tmpl.NewHandler(*templates, nil, template.FuncMap{
"sql": tmpl.SqlDebug(db),
"sqlr": tmpl.SqlRDebug(db),
"group": tmpl.Group,
})
log.Fatal(http.ListenAndServe(*port, tmpl.Gzip(h)))
}
func prepareDB(db *sql.DB) {
if _, err := db.Exec(`
create table foo (id integer not null primary key, grp integer, name text);
delete from foo;
`); err != nil {
log.Fatal(err)
}
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
stmt, err := tx.Prepare("insert into foo(id, grp, name) values(?, ?, ?)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
for i := 0; i < 100; i++ {
if _, err = stmt.Exec(i, i%10, fmt.Sprintf("foo-%03d", i)); err != nil {
log.Fatal(err)
}
}
tx.Commit()
}
|
unlicense
|
sunflowerdeath/broccoli-render-handlebars
|
index.js
|
2724
|
var path = require('path')
var fs = require('fs')
var crypto = require('crypto')
var dirmatch = require('dirmatch')
var _ = require('underscore')
var handlebars = require('handlebars')
var Filter = require('broccoli-glob-filter')
var makePartialName = function(partialPath) {
var name = partialPath
var ext = path.extname(partialPath)
if (ext === '.hbs' || ext === '.handlebars') {
name = path.basename(partialPath, ext)
}
return name
}
var Tree = function(inputTree, options) {
if (!(this instanceof Tree)) return new Tree(inputTree, options)
if (!options) options = {}
if (options.files === undefined) options.files = ['**/*.hbs', '**/*.handlebars']
if (options.targetExtension === undefined) options.targetExtension = 'html'
if (options.makePartialName === undefined) options.makePartialName = makePartialName
this.handlebars = options.handlebars || handlebars.create()
if (options.helpers) this.handlebars.registerHelper(options.helpers)
Filter.apply(this, arguments)
}
Tree.prototype = Object.create(Filter.prototype)
Tree.prototype.description = 'Handlebars'
Tree.prototype.read = function(readTree) {
var _this = this
return readTree(this.inputTree).then(function(srcDir) {
// Don't cache when context is dynamic
if (typeof _this.options.context === 'function') _this.invalidateCache()
_this.cachePartials(srcDir)
return Filter.prototype.read.call(_this, readTree)
})
}
Tree.prototype.cachePartials = function(srcDir) {
if (!this.options.partials) return
var partials = dirmatch(srcDir, this.options.partials)
var absPartials = _.map(partials, function(file) { return path.join(srcDir, file) })
var partialsHash = this.hashFiles(absPartials)
if (this.cachedPartialsHash !== partialsHash) {
this.cachedPartialsHash = partialsHash
this.cachedPartials = this.loadPartials(srcDir, partials)
this.invalidateCache()
}
}
Tree.prototype.loadPartials = function(srcDir, partialsPaths) {
var partials = {}
_.each(partialsPaths, function(partialPath) {
var name = this.options.makePartialName(partialPath)
var content = fs.readFileSync(path.join(srcDir, partialPath), 'utf8')
partials[name] = this.handlebars.compile(content)
}, this)
return partials
}
Tree.prototype.hashFiles = function(files) {
var keys = _.map(files, this.hashFile.bind(this))
return crypto.createHash('md5').update(keys.join(''))
}
Tree.prototype.processFileContent = function(content, relPath) {
var template = this.handlebars.compile(content, {partials: this.cachedPartials})
var context = this.options.context
if (typeof this.options.context === 'function') context = context(relPath)
return template(this.options.context, {
partials: this.cachedPartials
})
}
module.exports = Tree
|
unlicense
|
jeremybroutin/BlogReader
|
app/src/main/java/com/jeremybroutin/blogreader2/BlogWebViewActivity.java
|
1534
|
package com.jeremybroutin.blogreader2;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import com.jeremybroutin.blogreader2.R;
public class BlogWebViewActivity extends Activity {
protected String mUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_web_view);
Intent intent = getIntent();
Uri blogUri = intent.getData();
mUrl = blogUri.toString();
WebView webView = (WebView) findViewById(R.id.webView1);
webView.loadUrl(mUrl);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.blog_web_view, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_share){
sharePost();
}
return super.onOptionsItemSelected(item);
}
private void sharePost() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mUrl);
startActivity(Intent.createChooser(shareIntent, getString(R.string.share_chooser_title)));
}
}
|
unlicense
|
executive-consultants-of-los-angeles/rsum
|
rsum/export/sections/values.py
|
498
|
"""Values export object module."""
class Values(object):
"""Class for Values export object."""
name = None
document = None
def save(self, section, document, graphics=True):
"""Get intro."""
self.document = document
section = self.name
return document
def save_with_graphics(self, name, section, document):
"""Get intro."""
self.name = name
self.document = document
section = self.name
return document
|
unlicense
|
Hardmath123/quackoverflow
|
index.js
|
147
|
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/static'));
app.listen(process.env.PORT || 8080);
|
unlicense
|
dret/webconcepts
|
concepts/oauth-client-metadata/client_uri.md
|
1560
|
---
layout: concept
permalink: "/concepts/oauth-client-metadata/client_uri"
title: "OAuth Dynamic Client Registration Metadata: client_uri"
concept-name: OAuth Dynamic Client Registration Metadata
concept-value: client_uri
description: "URL string of a web page providing information about the client."
---
[URL string of a web page providing information about the client.](https://datatracker.ietf.org/doc/html/rfc7591#section-2 "Read documentation for OAuth Dynamic Client Registration Metadata "client_uri"") (**[RFC 7591: OAuth 2.0 Dynamic Client Registration Protocol](/specs/IETF/RFC/7591 "This specification defines mechanisms for dynamically registering OAuth 2.0 clients with authorization servers. Registration requests send a set of desired client metadata values to the authorization server. The resulting registration responses return a client identifier to use at the authorization server and the client metadata values registered for the client. The client can then use this registration information to communicate with the authorization server using the OAuth 2.0 protocol. This specification also defines a set of common client metadata fields and values for clients to use during registration.")**)
<br/>
<hr/>
<p style="float : left"><a href="./client_uri.json" title="JSON representing this particular Web Concept value">JSON</a></p>
<p style="text-align: right">Return to list of all ( <a href="../oauth-client-metadata/">OAuth Dynamic Client Registration Metadata</a> | <a href="../">Web Concepts</a> )</p>
|
unlicense
|
pvvx/RTL00_WEB
|
USDK/component/common/drivers/wlan/realtek/include/lxbus_osintf.h
|
1161
|
/******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
*
******************************************************************************/
#ifndef __LXBUS_OSINTF_H
#define __LXBUS_OSINTF_H
//void rtw_pci_disable_aspm(_adapter *padapter);
//void rtw_pci_enable_aspm(_adapter *padapter);
//void PlatformClearPciPMEStatus(PADAPTER Adapter);
#endif //__LXBUS_OSINTF_H
|
unlicense
|
toolgood/ToolGood.ReadyGo
|
ToolGood.ReadyGo3/SqlHelper.cs
|
41728
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using ToolGood.ReadyGo3.Gadget.Events;
using ToolGood.ReadyGo3.Gadget.Internals;
using ToolGood.ReadyGo3.Internals;
using ToolGood.ReadyGo3.PetaPoco;
using ToolGood.ReadyGo3.PetaPoco.Core;
namespace ToolGood.ReadyGo3
{
public partial class SqlHelper : IDisposable
{
#region 私有变量
//是否设置默认值
internal bool _setDateTimeDefaultNow;
internal bool _setStringDefaultNotNull;
internal bool _setGuidDefaultNew;
internal bool _sql_firstWithLimit1;
// 读写数据库
internal readonly string _connectionString;
internal readonly DbProviderFactory _factory;
internal Database _database;
// 连接时间 事务级别
internal int _commandTimeout;
internal int _oneTimeCommandTimeout;
internal IsolationLevel? _isolationLevel;
internal readonly SqlEvents _events;
private readonly SqlConfig _sqlConfig;
internal readonly SqlType _sqlType;
internal readonly SqlRecord _sql = new SqlRecord();
private readonly DatabaseProvider _provider;
internal bool _isDisposable;
#endregion 私有变量
#region 共公属性
/// <summary>
/// SQL操作事件
/// </summary>
public SqlEvents _Events { get { return _events; } }
/// <summary>
/// 数据库配置
/// </summary>
public SqlConfig _Config { get { return _sqlConfig; } }
/// <summary>
/// SQL设置
/// </summary>
public SqlRecord _Sql { get { return _sql; } }
/// <summary>
/// SQL语言类型
/// </summary>
public SqlType _SqlType { get { return _sqlType; } }
/// <summary>
/// 是否释放
/// </summary>
public bool _IsDisposed { get { return _isDisposable; } }
#endregion 共公属性
#region 构造方法 释放方法
/// <summary>
/// SqlHelper 构造方法
/// </summary>
/// <param name="connectionString">数据库链接字符串</param>
/// <param name="factory">provider工厂</param>
/// <param name="type"></param>
public SqlHelper(string connectionString, DbProviderFactory factory, SqlType type)
{
_sqlType = type;
_factory = factory;
_events = new SqlEvents(this);
_connectionString = connectionString;
_sqlConfig = new SqlConfig(this);
_provider = DatabaseProvider.Resolve(_sqlType);
}
/// <summary>
/// 释放
/// </summary>
public void Dispose()
{
_isDisposable = true;
if (_database != null) {
_database.Dispose();
_database = null;
}
}
#endregion 构造方法 释放方法
#region 私有方法
internal Database GetDatabase()
{
if (_database == null) {
_database = new Database(this);
}
Database db = _database;
db.CommandTimeout = _commandTimeout;
db.OneTimeCommandTimeout = _oneTimeCommandTimeout;
_oneTimeCommandTimeout = 0;
return db;
}
/// <summary>
/// 格式SQL语句
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
internal string FormatSql(string sql)
{
if (sql == null) { return ""; }
bool usedEscapeSql = false;
char escapeSql = '`';
if (_sqlType == SqlType.MySql || _sqlType == SqlType.MariaDb) {
usedEscapeSql = true;
escapeSql = '`';
} else if (_sqlType == SqlType.Oracle || _sqlType == SqlType.FirebirdDb || _sqlType == SqlType.PostgreSQL) {
usedEscapeSql = true;
escapeSql = '"';
}
if (usedEscapeSql == false) return sql;
StringBuilder _where = new StringBuilder();
bool isInText = false, isInTableColumn = false, jump = false;
var c = 'a';
for (int i = 0; i < sql.Length; i++) {
var t = sql[i];
if (jump) {
jump = false;
} else if (isInText) {
if (t == c) isInText = false;
if (t == '\\') jump = true;
} else if (isInTableColumn) {
if (t == ']') {
isInTableColumn = false;
_where.Append(escapeSql);
continue;
}
} else if (t == '[') {
isInTableColumn = true;
_where.Append(escapeSql);
continue;
} else if ("\"'`".Contains(t)) {
isInText = true;
c = t;
}
_where.Append(t);
}
return _where.ToString();
}
#endregion 私有方法
#region UseTransaction
/// <summary>
/// 使用事务
/// </summary>
/// <returns></returns>
public Transaction UseTransaction()
{
return new Transaction(GetDatabase());
}
#endregion UseTransaction UseCache UseRecord
#region Execute ExecuteScalar ExecuteDataTable ExecuteDataSet Exists
/// <summary>
/// 执行 SQL 语句,并返回受影响的行数
/// </summary>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns>返回受影响的行数</returns>
public int Execute(string sql, params object[] args)
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
sql = FormatSql(sql);
return GetDatabase().Execute(sql, args);
}
/// <summary>
/// 执行SQL 查询,并返回查询所返回的结果集中第一行的第一列。忽略额外的列或行。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns>返回查询所返回的结果集中第一行的第一列。忽略额外的列或行</returns>
public T ExecuteScalar<T>(string sql = "", params object[] args)
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
sql = FormatSql(sql);
return GetDatabase().ExecuteScalar<T>(sql, args);
}
/// <summary>
/// 执行SQL 查询,返回 DataTable
/// </summary>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns>返回 DataTable</returns>
public DataTable ExecuteDataTable(string sql, params object[] args)
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
sql = FormatSql(sql);
return GetDatabase().ExecuteDataTable(sql, args);
}
/// <summary>
/// 执行SQL 查询,返回 DataSet
/// </summary>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns>返回 DataSet</returns>
public DataSet ExecuteDataSet(string sql, params object[] args)
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
sql = FormatSql(sql);
return GetDatabase().ExecuteDataSet(sql, args);
}
/// <summary>
/// 执行SQL 查询,判断是否存在,返回bool类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public bool Exists<T>(string sql, params object[] args)
{
sql = FormatSql(sql);
return Count<T>(sql, args) > 0;
}
/// <summary>
/// 执行SQL 查询,判断是否存在,返回bool类型
/// </summary>
/// <param name="table"></param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public bool Table_Exists(string table, string sql, params object[] args)
{
sql = FormatSql(sql);
return Count(table, sql, args) > 0;
}
/// <summary>
/// 执行SQL 查询,返回数量
/// </summary>
/// <param name="table"></param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public int Table_Count(string table, string sql, params object[] args)
{
sql = sql.Trim();
if (sql.StartsWith("SELECT ", StringComparison.CurrentCultureIgnoreCase) == false) {
sql = FormatSql(sql);
sql = $"SELECT COUNT(*) FROM {table} {sql}";
}
return GetDatabase().ExecuteScalar<int>(sql, args);
}
/// <summary>
/// 执行SQL 查询,返回数量
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public int Count<T>(string sql = "", params object[] args)
{
sql = sql.Trim();
if (sql.StartsWith("SELECT ", StringComparison.CurrentCultureIgnoreCase) == false) {
var pd = PocoData.ForType(typeof(T));
var table = _provider.GetTableName(pd);
sql = FormatSql(sql);
sql = $"SELECT COUNT(*) FROM {table} {sql}";
}
return GetDatabase().ExecuteScalar<int>(sql, args);
}
/// <summary>
/// 执行SQL 查询,返回数量
/// </summary>
/// <param name="sql"></param>
/// <param name="args"></param>
/// <returns></returns>
public int Count(string sql, params object[] args)
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
return GetDatabase().ExecuteScalar<int>(sql, args);
}
#endregion Execute ExecuteScalar ExecuteDataTable ExecuteDataSet Exists
#region Select Page Select
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> Select<T>(string sql = "", params object[] args)
{
sql = FormatSql(sql);
return GetDatabase().Query<T>(sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> Table_Select<T>(string table, string sql = "", params object[] args) where T : class
{
sql = FormatSql(sql);
return GetDatabase().Table_Query<T>(table, sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="limit">获取个数</param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> Select<T>(int limit, string sql = "", params object[] args) where T : class
{
sql = FormatSql(sql);
return GetDatabase().Query<T>(0, limit, sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="limit">获取个数</param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> Table_Select<T>(string table, int limit, string sql = "", params object[] args) where T : class
{
sql = FormatSql(sql);
return GetDatabase().Table_Query<T>(table, 0, limit, sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="offset">跳过</param>
/// <param name="limit">获取个数</param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> Select<T>(int limit, int offset, string sql = "", params object[] args) where T : class
{
sql = FormatSql(sql);
return GetDatabase().Query<T>(offset, limit, sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="offset">跳过</param>
/// <param name="limit">获取个数</param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> Table_Select<T>(string table, int limit, int offset, string sql = "", params object[] args) where T : class
{
sql = FormatSql(sql);
return GetDatabase().Table_Query<T>(table, offset, limit, sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="page"></param>
/// <param name="itemsPerPage"></param>
/// <param name="sql"></param>
/// <param name="args"></param>
/// <returns></returns>
public List<T> SelectPage<T>(int page, int itemsPerPage, string sql = "", params object[] args) where T : class
{
if (page <= 0) { page = 1; }
if (itemsPerPage <= 0) { itemsPerPage = 20; }
sql = FormatSql(sql);
return GetDatabase().Query<T>((page - 1) * itemsPerPage, itemsPerPage, sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="page"></param>
/// <param name="itemsPerPage"></param>
/// <param name="sql"></param>
/// <param name="args"></param>
/// <returns></returns>
public List<T> Table_SelectPage<T>(string table, int page, int itemsPerPage, string sql = "", params object[] args) where T : class
{
if (page <= 0) { page = 1; }
if (itemsPerPage <= 0) { itemsPerPage = 20; }
sql = FormatSql(sql);
return GetDatabase().Table_Query<T>(table, (page - 1) * itemsPerPage, itemsPerPage, sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回Page类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="page">页数</param>
/// <param name="itemsPerPage">每页数量</param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public Page<T> Page<T>(int page, int itemsPerPage, string sql = "", params object[] args) where T : class
{
if (page <= 0) { page = 1; }
if (itemsPerPage <= 0) { itemsPerPage = 20; }
sql = FormatSql(sql);
return GetDatabase().Page<T>(page, itemsPerPage, sql, args);
}
/// <summary>
/// 执行SQL 查询,返回Page类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="page">页数</param>
/// <param name="itemsPerPage">每页数量</param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public Page<T> Table_Page<T>(string table, int page, int itemsPerPage, string sql = "", params object[] args) where T : class
{
if (page <= 0) { page = 1; }
if (itemsPerPage <= 0) { itemsPerPage = 20; }
sql = FormatSql(sql);
return GetDatabase().Table_Page<T>(table, page, itemsPerPage, sql, args);
}
/// <summary>
/// 执行SQL 查询, 返回单个
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="columnSql"></param>
/// <param name="tableSql"></param>
/// <param name="whereSql"></param>
/// <param name="args"></param>
/// <returns></returns>
public T SQL_FirstOrDefault<T>(string columnSql, string tableSql, string whereSql, params object[] args)
where T : class
{
if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); }
if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); }
columnSql = RemoveStart(columnSql, "SELECT ");
tableSql = RemoveStart(tableSql, "FROM ");
whereSql = RemoveStart(whereSql, "WHERE ");
var sql = $"SELECT {columnSql} FROM {tableSql} WHERE {whereSql}";
sql = FormatSql(sql);
return GetDatabase().Query<T>(sql, args).FirstOrDefault();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="page">页数</param>
/// <param name="itemsPerPage">每页数量</param>
/// <param name="columnSql">查询列 SQL语句</param>
/// <param name="tableSql">TABLE SQL语句</param>
/// <param name="orderSql">ORDER BY SQL语句</param>
/// <param name="whereSql">WHERE SQL语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> SQL_Select<T>(int page, int itemsPerPage, string columnSql, string tableSql, string orderSql, string whereSql, params object[] args)
where T : class
{
if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); }
if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); }
if (page <= 0) { page = 1; }
if (itemsPerPage <= 0) { itemsPerPage = 20; }
columnSql = RemoveStart(columnSql, "SELECT ");
tableSql = RemoveStart(tableSql, "FROM ");
orderSql = RemoveStart(orderSql, "ORDER BY ");
whereSql = RemoveStart(whereSql, "WHERE ");
var sql = _provider.CreateSql((int)itemsPerPage, (int)((Math.Max(0, page - 1)) * itemsPerPage), columnSql, tableSql, orderSql, whereSql);
sql = FormatSql(sql);
return GetDatabase().Query<T>(sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="limit">每页数量</param>
/// <param name="columnSql">查询列 SQL语句</param>
/// <param name="tableSql">TABLE SQL语句</param>
/// <param name="orderSql">ORDER BY SQL语句</param>
/// <param name="whereSql">WHERE SQL语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> SQL_Select<T>(int limit, string columnSql, string tableSql, string orderSql, string whereSql, params object[] args)
where T : class
{
if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); }
if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); }
if (limit <= 0) { limit = 20; }
columnSql = RemoveStart(columnSql, "SELECT ");
tableSql = RemoveStart(tableSql, "FROM ");
orderSql = RemoveStart(orderSql, "ORDER BY ");
whereSql = RemoveStart(whereSql, "WHERE ");
var sql = _provider.CreateSql(limit, 0, columnSql, tableSql, orderSql, whereSql);
sql = FormatSql(sql);
return GetDatabase().Query<T>(sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="columnSql">查询列 SQL语句</param>
/// <param name="tableSql">TABLE SQL语句</param>
/// <param name="orderSql">ORDER BY SQL语句</param>
/// <param name="whereSql">WHERE SQL语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public List<T> SQL_Select<T>(string columnSql, string tableSql, string orderSql, string whereSql, params object[] args)
where T : class
{
if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); }
if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); }
columnSql = RemoveStart(columnSql, "SELECT ");
tableSql = RemoveStart(tableSql, "FROM ");
orderSql = RemoveStart(orderSql, "ORDER BY ");
whereSql = RemoveStart(whereSql, "WHERE ");
var sql = _provider.CreateSql(columnSql, tableSql, orderSql, whereSql);
sql = FormatSql(sql);
return GetDatabase().Query<T>(sql, args).ToList();
}
/// <summary>
/// 执行SQL 查询,返回Page类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="page">页数</param>
/// <param name="itemsPerPage">每页数量</param>
/// <param name="columnSql">查询列 SQL语句</param>
/// <param name="tableSql">TABLE SQL语句</param>
/// <param name="orderSql">ORDER BY SQL语句</param>
/// <param name="whereSql">WHERE SQL语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public Page<T> SQL_Page<T>(int page, int itemsPerPage, string columnSql, string tableSql, string orderSql, string whereSql, params object[] args)
where T : class
{
if (string.IsNullOrWhiteSpace(columnSql)) { throw new ArgumentNullException("columnSql is null."); }
if (string.IsNullOrWhiteSpace(tableSql)) { throw new ArgumentNullException("tableSql is null."); }
if (page <= 0) { page = 1; }
if (itemsPerPage <= 0) { itemsPerPage = 20; }
columnSql = RemoveStart(columnSql, "SELECT ");
tableSql = RemoveStart(tableSql, "FROM ");
orderSql = RemoveStart(orderSql, "ORDER BY ");
whereSql = RemoveStart(whereSql, "WHERE ");
string countSql = string.IsNullOrEmpty(whereSql) ? $"SELECT COUNT(1) FROM {tableSql}" : $"SELECT COUNT(1) FROM {tableSql} WHERE {whereSql}";
countSql = FormatSql(countSql);
var sql = _provider.CreateSql((int)itemsPerPage, (int)((Math.Max(0, page - 1)) * itemsPerPage), columnSql, tableSql, orderSql, whereSql);
sql = FormatSql(sql);
return GetDatabase().PageSql<T>(page, itemsPerPage, sql, countSql, args);
}
private string RemoveStart(string txt, string startsText)
{
if (string.IsNullOrEmpty(txt) == false) {
txt = txt.Trim();
if (txt.StartsWith(startsText, StringComparison.InvariantCultureIgnoreCase)) {
txt = txt.Substring(startsText.Length);
}
}
return txt;
}
#endregion Select Page Select
#region FirstOrDefault
/// <summary>
/// 获取唯一一个类型,若数量大于1,则抛出异常
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="primaryKey">主键名</param>
/// <returns></returns>
private T SingleOrDefaultById<T>(object primaryKey) where T : class
{
var pd = PocoData.ForType(typeof(T));
var pk = _provider.EscapeSqlIdentifier(pd.TableInfo.PrimaryKey);
var sql = $"WHERE {pk}=@0";
return GetDatabase().Query<T>(sql, new object[] { primaryKey }).FirstOrDefault();
}
/// <summary>
/// 获取唯一一个类型,若数量大于1,则抛出异常
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="primaryKey">主键名</param>
/// <returns></returns>
private T Table_SingleOrDefaultById<T>(string table, object primaryKey) where T : class
{
var pd = PocoData.ForType(typeof(T));
var pk = _provider.EscapeSqlIdentifier(pd.TableInfo.PrimaryKey);
var sql = $"WHERE {pk}=@0";
return GetDatabase().Table_Query<T>(table, sql, new object[] { primaryKey }).FirstOrDefault();
}
/// <summary>
/// 获取第一个类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public T FirstOrDefault<T>(string sql = "", params object[] args)
{
sql = FormatSql(sql);
if (_sql_firstWithLimit1 == false) {
return GetDatabase().Query<T>(sql, args).FirstOrDefault();
}
return GetDatabase().Query<T>(0, 1, sql, args).FirstOrDefault();
}
/// <summary>
/// 获取第一个类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public T Table_FirstOrDefault<T>(string table, string sql = "", params object[] args) where T : class
{
sql = FormatSql(sql);
if (_sql_firstWithLimit1 == false) {
return GetDatabase().Table_Query<T>(table, sql, args).FirstOrDefault();
}
return GetDatabase().Table_Query<T>(table, 0, 1, sql, args).FirstOrDefault();
}
#endregion FirstOrDefault
#region Object Insert Update Delete DeleteById Save
/// <summary>
/// 插入集合,不返回主键
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
public void InsertList<T>(List<T> list) where T : class
{
if (list == null) throw new ArgumentNullException("list is null.");
if (list.Count == 0) return;
if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) {
foreach (var item in list) {
DefaultValue.SetDefaultValue<T>(item, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew);
}
}
if (_Events.OnBeforeInsert(list)) return;
GetDatabase().Insert(list);
_Events.OnAfterInsert(list);
}
/// <summary>
/// 插入集合,不返回主键
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="list"></param>
public void InsertList<T>(string table, List<T> list) where T : class
{
if (list == null) throw new ArgumentNullException("list is null.");
if (list.Count == 0) return;
if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) {
foreach (var item in list) {
DefaultValue.SetDefaultValue<T>(item, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew);
}
}
if (_Events.OnBeforeInsert(list)) return;
GetDatabase().Table_Insert(table, list);
_Events.OnAfterInsert(list);
}
/// <summary>
/// 插入,支持主键自动获取。
/// </summary>
/// <param name="poco">对象</param>
/// <returns></returns>
public object Insert<T>(T poco) where T : class
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon .");
if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) {
DefaultValue.SetDefaultValue<T>(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew);
}
if (_Events.OnBeforeInsert(poco)) return null;
var obj = GetDatabase().Insert(poco);
_Events.OnAfterInsert(poco);
return obj;
}
/// <summary>
/// 插入,支持主键自动获取。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="poco">对象</param>
/// <returns></returns>
public object Table_Insert<T>(string table, T poco) where T : class
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon .");
if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) {
DefaultValue.SetDefaultValue<T>(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew);
}
if (_Events.OnBeforeInsert(poco)) return null;
var obj = GetDatabase().Table_Insert(table, poco);
_Events.OnAfterInsert(poco);
return obj;
}
/// <summary>
/// 插入
/// </summary>
/// <param name="table"></param>
/// <param name="poco"></param>
/// <param name="autoIncrement"></param>
/// <returns></returns>
public object Table_Insert(string table, object poco, bool autoIncrement)
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon .");
if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) {
DefaultValue.SetDefaultValue(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew);
}
if (_Events.OnBeforeInsert(poco)) return null;
var obj = GetDatabase().Insert(table, poco, autoIncrement, null);
_Events.OnAfterInsert(poco);
return obj;
}
/// <summary>
/// 插入
/// </summary>
/// <param name="table"></param>
/// <param name="poco"></param>
/// <param name="ignoreFields"></param>
/// <returns></returns>
public object Table_Insert(string table, object poco, IEnumerable<string> ignoreFields)
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon .");
if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) {
DefaultValue.SetDefaultValue(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew);
}
if (_Events.OnBeforeInsert(poco)) return null;
var obj = GetDatabase().Insert(table, poco, false, ignoreFields);
_Events.OnAfterInsert(poco);
return obj;
}
/// <summary>
/// 插入
/// </summary>
/// <param name="table"></param>
/// <param name="poco"></param>
/// <param name="autoIncrement"></param>
/// <param name="ignoreFields"></param>
/// <returns></returns>
public object Table_Insert(string table, object poco, bool autoIncrement, IEnumerable<string> ignoreFields)
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (poco is IList) throw new ArgumentException("poco is a list type, use InsertList methon .");
if (_setDateTimeDefaultNow || _setStringDefaultNotNull || _setGuidDefaultNew) {
DefaultValue.SetDefaultValue(poco, _setStringDefaultNotNull, _setDateTimeDefaultNow, _setGuidDefaultNew);
}
if (_Events.OnBeforeInsert(poco)) return null;
var obj = GetDatabase().Insert(table, poco, autoIncrement, ignoreFields);
_Events.OnAfterInsert(poco);
return obj;
}
/// <summary>
/// 更新
/// </summary>
/// <param name="poco">对象</param>
/// <returns></returns>
public int Update<T>(T poco) where T : class
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (_Events.OnBeforeUpdate(poco)) return -1;
int r = GetDatabase().Update(poco);
_Events.OnAfterUpdate(poco);
return r;
}
/// <summary>
/// 更新
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="poco"></param>
/// <returns></returns>
public int Table_Update<T>(string table, T poco) where T : class
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (_Events.OnBeforeUpdate(poco)) return -1;
int r = GetDatabase().Table_Update(table, poco);
_Events.OnAfterUpdate(poco);
return r;
}
/// <summary>
/// 删除
/// </summary>
/// <param name="poco">对象</param>
/// <returns></returns>
public int Delete<T>(T poco) where T : class
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (_Events.OnBeforeDelete(poco)) return -1;
var t = GetDatabase().Delete(poco);
_Events.OnAfterDelete(poco);
return t;
}
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="poco">对象</param>
/// <returns></returns>
public int Table_Delete<T>(string table, T poco) where T : class
{
if (poco == null) throw new ArgumentNullException("poco is null");
if (_Events.OnBeforeDelete(poco)) return -1;
var t = GetDatabase().Table_Delete(table, poco);
_Events.OnAfterDelete(poco);
return t;
}
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public int Delete<T>(string sql, params object[] args) where T : class
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
sql = FormatSql(sql);
return GetDatabase().Delete<T>(sql, args);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="table"></param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public int Table_Delete(string table, string sql, params object[] args)
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
sql = FormatSql(sql);
return GetDatabase().Table_Delete(table, sql, args);
}
/// <summary>
/// 根据ID 删除表数据, 注: 单独从delete方法,防止出错
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="primaryKey">主键</param>
/// <returns></returns>
public int DeleteById<T>(object primaryKey) where T : class
{
return GetDatabase().Delete<T>(primaryKey);
}
/// <summary>
/// 根据ID 删除表数据, 注: 单独从delete方法,防止出错
/// </summary>
/// <param name="table"></param>
/// <param name="primaryKey">主键</param>
/// <returns></returns>
public int Table_DeleteById(string table, object primaryKey)
{
return GetDatabase().Table_Delete(table, primaryKey);
}
/// <summary>
/// 保存
/// </summary>
/// <param name="poco"></param>
public void Save<T>(T poco) where T : class
{
if (poco == null) throw new ArgumentNullException("poco is null");
GetDatabase().Save(poco);
}
/// <summary>
/// 保存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <param name="poco"></param>
public void Table_Save<T>(string table, T poco) where T : class
{
if (poco == null) throw new ArgumentNullException("poco is null");
GetDatabase().SaveTable(table, poco);
}
/// <summary>
/// 更新
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public int Update<T>(string sql, params object[] args)
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
sql = FormatSql(sql);
return GetDatabase().Update<T>(sql, args);
}
/// <summary>
/// 更新
/// </summary>
/// <param name="table"></param>
/// <param name="sql">SQL 语句</param>
/// <param name="args">SQL 参数</param>
/// <returns></returns>
public int Table_Update(string table, string sql, params object[] args)
{
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException("sql is empty.");
sql = FormatSql(sql);
return GetDatabase().Table_Update(table, sql, args);
}
#endregion Object Insert Update Delete DeleteById Save
/// <summary>
/// 获取动态表名,适合绑定数据表列名
/// <para>var so = helper.GetTableName(typeof(DbSaleOrder), "so");</para>
/// <para>var select = $"select {so.Code} from {so} where {so.Id}='123'";</para>
/// </summary>
/// <param name="type"></param>
/// <param name="asName"></param>
/// <returns></returns>
public dynamic GetTableName(Type type, string asName = null)
{
return new TableName(type, _provider, asName);
}
/// <summary>
/// 获取动态表名,适合绑定数据表列名
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="asName"></param>
/// <returns></returns>
public TableName<T> GetTableName<T>(string asName = null) where T : class, new()
{
return new TableName<T>(typeof(T), _provider, asName);
}
}
}
|
apache-2.0
|
mujina/hierachecker
|
README.md
|
4236
|
# Hiera Checker
Courtesy of [Pugme Ltd](http://pugme.co.uk)
Hierachecker is a Ruby script for testing Hiera resolution indpendently of Puppet.
It is released under the Apache 2.0 License.
## Quick Start
gem install bundle
bundle install
./hierachecker.rb
## Standard Start
The program is structured around a common precedence hierarchy of environments, roles and client configs, though Hierachecker should work for any precedence hierarchy you have adopted.
To get running with hierachecker, after setup you need to,
* Create some tests
* Create global facts (optional)
* Clone your hieradata
### Setup
Make sure you have a Ruby 1.9+ installed. Personally I prefer to install Ruby using [RVM](http://rvm.io) and then create a new Gemset for Hierachecker
rvm gemset create hierachecker
rvm use ruby@hierachecker
First install the [Bundle](http://bundler.io) Gem and run bundle install to satisfy Gem depenedencies.
gem install bundle
bundle install
### Test Creation
Tests are written in YAML. They have the following format
<hiera_key>:
assert: type e.g. String
facts: Hash
clientcert:
<fqdn>:
assert: type e.g. Array
facts: Hash
The hiera_key is the value you are attempting to resolve.
Assertions can be any type. If you are simply comparing a string
assert: "size=5"
Or, the value is an array
assert:
"sizes"
- 5
- 6
The facts key is used to pass facts. Perhaps your hieradata contains memory: "size=#{::size}". The facts Hash allows you to assert this correctly.
facts:
"size": 5
The clientcert key accepts a Hash of client specific configs, using the same keys as described above. This allows you to override assertions on a per client basis to reflect your hiera config data.
In the following example, servers that belong to the web role have a fixed memory allocation set by the ::size fact, which has a value of 4. However web3 has double this memory. A test for this scenario would be as follows:
memory:
assert: "size=4"
facts:
size: "4"
clientcert:
web3:
assert: "size=8
facts:
cpu: "2" # Optional fact
Your Hiera data might look like this
roles/web.yaml # memory: "size=#{::size}"
nodes/web3.yaml # memory: "size=8"
Role level assertions are optional as are facts. If a fact is set at the role level, this will apply to all clientcerts unless a fact of the same name overrides it.
Client level assertions are mandatory, on the basis that there is no justification for having a client cert record without it.
Hieracheck is bundled with some example tests, please take a look at these for further clarification on usage as required.
### Hiera YAML config
You can use or customise the existing hiera.yaml config in the root directory of Hierachecker or point to your own hiera.yaml as follows.
./hierachecker.rb --hierayaml /path/to/hiera.yaml
Set in config.json
{
"hiera_yaml": "/home/mujina/hiera.yaml",
...
}
You should update :datadir: to reflect the location of your cloned hieradata.
You may also want to change the :merge_behavior: from 'native' to 'deep' or 'deeper' to reflect your current setup. Using the deep merge options requires the deep_merge Gem which is in the Gemfile. If you're only using native feel free to remove this depedency.
### Limitations, Follow Ups and Contributing
Hierchecker works by creating a scope to satisfy the hierarchy defined in hiera.yaml. At present the dynamic variables defined in hiera.yaml that make up the keys of this scope are hardcoded, so only the following keys may be used.
* environment: environment
* role: ::role
* clientcert: clientcert
This limitation will be overcome in a later version. For example ::fqdn, trusted.certname and clientcert should all be suitable alternative keys for clientcert.
I developed this script to allow me to test the Hiera config prior to a production platform migration. I didn't want to be debugging Hiera config on migration night. If you want to help develop it further contact me [email protected] or raise a pull request.
|
apache-2.0
|
ctnitchie/freemarkerdoclet
|
src/main/java/org/ctnitchie/doclet/freemarker/EchoDirective.java
|
646
|
package org.ctnitchie.doclet.freemarker;
import java.io.IOException;
import java.util.Map;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
@SuppressWarnings("rawtypes")
public class EchoDirective implements TemplateDirectiveModel {
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
System.out.println(params.get("message"));
}
}
|
apache-2.0
|
o3project/openflowj-otn
|
src/main/java/org/projectfloodlight/openflow/protocol/OFBsnDebugCounterDescStatsReply.java
|
2321
|
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_interface.java
// Do not modify
package org.projectfloodlight.openflow.protocol;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import java.util.Set;
import java.util.List;
import org.jboss.netty.buffer.ChannelBuffer;
public interface OFBsnDebugCounterDescStatsReply extends OFObject, OFBsnStatsReply {
OFVersion getVersion();
OFType getType();
long getXid();
OFStatsType getStatsType();
Set<OFStatsReplyFlags> getFlags();
long getExperimenter();
long getSubtype();
List<OFBsnDebugCounterDescStatsEntry> getEntries();
void writeTo(ChannelBuffer channelBuffer);
Builder createBuilder();
public interface Builder extends OFBsnStatsReply.Builder {
OFBsnDebugCounterDescStatsReply build();
OFVersion getVersion();
OFType getType();
long getXid();
Builder setXid(long xid);
OFStatsType getStatsType();
Set<OFStatsReplyFlags> getFlags();
Builder setFlags(Set<OFStatsReplyFlags> flags);
long getExperimenter();
long getSubtype();
List<OFBsnDebugCounterDescStatsEntry> getEntries();
Builder setEntries(List<OFBsnDebugCounterDescStatsEntry> entries);
}
}
|
apache-2.0
|
yauritux/venice-legacy
|
Venice/Venice-Web/src/main/java/com/gdn/venice/server/app/fraud/presenter/commands/UpdateFraudParameterRule31DataCommand.java
|
2763
|
package com.gdn.venice.server.app.fraud.presenter.commands;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.djarum.raf.utilities.Locator;
import com.gdn.venice.client.app.DataNameTokens;
import com.gdn.venice.facade.FrdParameterRule31SessionEJBRemote;
import com.gdn.venice.persistence.FrdParameterRule31;
import com.gdn.venice.server.command.RafDsCommand;
import com.gdn.venice.server.data.RafDsRequest;
import com.gdn.venice.server.data.RafDsResponse;
/**
* Update Command for Parameter Rule 31 - Genuine List
*
* @author Roland
*/
public class UpdateFraudParameterRule31DataCommand implements RafDsCommand {
RafDsRequest request;
public UpdateFraudParameterRule31DataCommand(RafDsRequest request) {
this.request = request;
}
@Override
public RafDsResponse execute() {
RafDsResponse rafDsResponse = new RafDsResponse();
List<FrdParameterRule31> rule31List = new ArrayList<FrdParameterRule31>();
List<HashMap<String,String >> dataList = request.getData();
FrdParameterRule31 entityRule31 = new FrdParameterRule31();
Locator<Object> locator = null;
try {
locator = new Locator<Object>();
FrdParameterRule31SessionEJBRemote sessionHome = (FrdParameterRule31SessionEJBRemote) locator.lookup(FrdParameterRule31SessionEJBRemote.class, "FrdParameterRule31SessionEJBBean");
for (int i=0;i<dataList.size();i++) {
Map<String, String> data = dataList.get(i);
Iterator<String> iter = data.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
if(key.equals(DataNameTokens.FRDPARAMETERRULE31_ID)){
try{
entityRule31 = sessionHome.queryByRange("select o from FrdParameterRule31 o where o.id="+new Long(data.get(key)), 0, 1).get(0);
}catch(IndexOutOfBoundsException e){
entityRule31.setId(new Long(data.get(key)));
}
break;
}
}
iter = data.keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
if(key.equals(DataNameTokens.FRDPARAMETERRULE31_EMAIL)){
entityRule31.setEmail(data.get(key));
} else if(key.equals(DataNameTokens.FRDPARAMETERRULE31_CCNUMBER)){
entityRule31.setNoCc(data.get(key));
}
}
rule31List.add(entityRule31);
}
sessionHome.mergeFrdParameterRule31List((ArrayList<FrdParameterRule31>)rule31List);
rafDsResponse.setStatus(0);
} catch (Exception ex) {
ex.printStackTrace();
rafDsResponse.setStatus(-1);
} finally {
try {
if(locator!=null){
locator.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
rafDsResponse.setData(dataList);
return rafDsResponse;
}
}
|
apache-2.0
|
trustedanalytics/hdfs-broker
|
src/test/java/org/trustedanalytics/servicebroker/hdfs/integration/config/HdfsLocalConfiguration.java
|
2976
|
/**
* Copyright (c) 2015 Intel Corporation
*
* 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.trustedanalytics.servicebroker.hdfs.integration.config;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.trustedanalytics.servicebroker.hdfs.config.ExternalConfiguration;
@Configuration
@Profile("integration-test")
public class HdfsLocalConfiguration {
@Autowired
private ExternalConfiguration externalConfiguration;
@Bean
@Qualifier("user")
public FileSystem getUserFileSystem() throws InterruptedException, IOException,
URISyntaxException {
return FileSystemFactory.getFileSystem(externalConfiguration.getUserspaceChroot());
}
@Bean
@Qualifier("superUser")
public FileSystem getSuperUserFileSystem() throws InterruptedException, IOException,
URISyntaxException {
return FileSystemFactory.getFileSystem(externalConfiguration.getUserspaceChroot());
}
static class FileSystemFactory {
private static FileSystem fileSystem;
public static FileSystem getFileSystem(String userspace) throws IOException,
InterruptedException, URISyntaxException {
if (fileSystem == null) {
File baseDir = new File("./target/hdfs/" + "testName").getAbsoluteFile();
FileUtil.fullyDelete(baseDir);
org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration(false);
conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
MiniDFSCluster cluster = builder.build();
fileSystem = cluster.getFileSystem();
tryMkdirOrThrowException(fileSystem, userspace);
}
return fileSystem;
}
private static void tryMkdirOrThrowException(FileSystem fs, String path) throws IOException {
if (!fs.mkdirs(new Path(path))) {
throw new RuntimeException("Failure when try to create test root dir: " + path);
}
}
}
}
|
apache-2.0
|
allaryin/Carnivora
|
src/main/java/org/mcupdater/carnivora/render/ModelSmoker.java
|
6215
|
package org.mcupdater.carnivora.render;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import org.mcupdater.carnivora.Version;
public class ModelSmoker extends ModelBase {
public static ModelSmoker INSTANCE = null;
public static ModelSmoker getInstance() {
if( INSTANCE == null ) {
INSTANCE = new ModelSmoker();
}
return INSTANCE;
}
ResourceLocation texture;
public ResourceLocation getTexture() {
return texture;
}
ModelRenderer handle;
ModelRenderer leg1;
ModelRenderer leg2;
ModelRenderer leg3;
ModelRenderer leg4;
ModelRenderer chimney1;
ModelRenderer chimney2;
ModelRenderer chimney3;
ModelRenderer chimney4;
ModelRenderer bodyleft;
ModelRenderer bodyback;
ModelRenderer bodyfrontright;
ModelRenderer bodytop;
ModelRenderer bodyfrontleft;
ModelRenderer bodybottom;
ModelRenderer bodyback2;
ModelRenderer bodyright;
public ModelSmoker() {
texture = new ResourceLocation(Version.TEXTURE_PREFIX+"textures/blocks/smoker.png");
textureWidth = 69;
textureHeight = 38;
handle = new ModelRenderer(this, 62, 30);
handle.addBox(-1F, -2F, -1F, 1, 4, 1);
handle.setRotationPoint(0F, 13F, -5.5F);
handle.setTextureSize(69, 38);
handle.mirror = true;
setRotation(handle, 0F, 0F, 1.570796F);
leg1 = new ModelRenderer(this, 0, 13);
leg1.addBox(-1F, 0F, -1F, 2, 5, 2);
leg1.setRotationPoint(6F, 19F, -3F);
leg1.setTextureSize(69, 38);
leg1.mirror = true;
setRotation(leg1, 0F, 0.7853982F, 0F);
leg2 = new ModelRenderer(this, 0, 13);
leg2.addBox(-1F, 0F, -1F, 2, 5, 2);
leg2.setRotationPoint(-6F, 19F, -3F);
leg2.setTextureSize(69, 38);
leg2.mirror = true;
setRotation(leg2, 0F, 0.7853982F, 0F);
leg3 = new ModelRenderer(this, 0, 13);
leg3.addBox(-1F, 0F, -1F, 2, 5, 2);
leg3.setRotationPoint(-6F, 19F, 3F);
leg3.setTextureSize(69, 38);
leg3.mirror = true;
setRotation(leg3, 0F, 0.7853982F, 0F);
leg4 = new ModelRenderer(this, 0, 13);
leg4.addBox(-1F, 0F, -1F, 2, 5, 2);
leg4.setRotationPoint(6F, 19F, 3F);
leg4.setTextureSize(69, 38);
leg4.mirror = true;
setRotation(leg4, 0F, 0.7853982F, 0F);
chimney1 = new ModelRenderer(this, 0, 23);
chimney1.addBox(-2F, -1F, -1F, 1, 2, 2);
chimney1.setRotationPoint(0F, 9F, 0F);
chimney1.setTextureSize(69, 38);
chimney1.mirror = true;
setRotation(chimney1, 0F, 3.141593F, 0F);
chimney2 = new ModelRenderer(this, 0, 23);
chimney2.addBox(-2F, -1F, -1F, 1, 2, 2);
chimney2.setRotationPoint(0F, 9F, 0F);
chimney2.setTextureSize(69, 38);
chimney2.mirror = true;
setRotation(chimney2, 0F, 0F, 0F);
chimney3 = new ModelRenderer(this, 0, 23);
chimney3.addBox(-2F, -1F, -1F, 1, 2, 2);
chimney3.setRotationPoint(0F, 9F, 0F);
chimney3.setTextureSize(69, 38);
chimney3.mirror = true;
setRotation(chimney3, 0F, 1.570796F, 0F);
chimney4 = new ModelRenderer(this, 0, 23);
chimney4.addBox(-2F, -1F, -1F, 1, 2, 2);
chimney4.setRotationPoint(0F, 9F, 0F);
chimney4.setTextureSize(69, 38);
chimney4.mirror = true;
setRotation(chimney4, 0F, -1.570796F, 0F);
bodyleft = new ModelRenderer(this, 31, 30);
bodyleft.addBox(-4F, -7.5F, -4F, 8, 1, 7);
bodyleft.setRotationPoint(0F, 14F, 0F);
bodyleft.setTextureSize(69, 38);
bodyleft.mirror = true;
setRotation(bodyleft, 1.570796F, -1.570796F, 0F);
bodyback = new ModelRenderer(this, 9, 12);
bodyback.addBox(-6F, -0.5F, 0F, 12, 1, 7);
bodyback.setRotationPoint(0F, 18F, -5F);
bodyback.setTextureSize(69, 38);
bodyback.mirror = true;
setRotation(bodyback, 1.570796F, 0F, 0F);
bodyfrontright = new ModelRenderer(this, 48, 12);
bodyfrontright.addBox(-8F, -5F, -4F, 2, 1, 7);
bodyfrontright.setRotationPoint(0F, 14F, 0F);
bodyfrontright.setTextureSize(69, 38);
bodyfrontright.mirror = true;
setRotation(bodyfrontright, 1.570796F, 0F, 0F);
bodytop = new ModelRenderer(this, 35, 0);
bodytop.addBox(-8F, -5F, 3F, 16, 10, 1);
bodytop.setRotationPoint(0F, 14F, 0F);
bodytop.setTextureSize(69, 38);
bodytop.mirror = true;
setRotation(bodytop, 1.570796F, 0F, 0F);
bodyfrontleft = new ModelRenderer(this, 48, 21);
bodyfrontleft.addBox(6F, -5F, -4F, 2, 1, 7);
bodyfrontleft.setRotationPoint(0F, 14F, 0F);
bodyfrontleft.setTextureSize(69, 38);
bodyfrontleft.mirror = true;
setRotation(bodyfrontleft, 1.570796F, 0F, 0F);
bodybottom = new ModelRenderer(this, 0, 0);
bodybottom.addBox(-8F, -5F, -5F, 16, 10, 1);
bodybottom.setRotationPoint(0F, 14F, 0F);
bodybottom.setTextureSize(69, 38);
bodybottom.mirror = true;
setRotation(bodybottom, 1.570796F, 0F, 0F);
bodyback2 = new ModelRenderer(this, 1, 21);
bodyback2.addBox(-8F, 4F, -4F, 16, 1, 7);
bodyback2.setRotationPoint(0F, 14F, 0F);
bodyback2.setTextureSize(69, 38);
bodyback2.mirror = true;
setRotation(bodyback2, 1.570796F, 0F, 0F);
bodyright = new ModelRenderer(this, 0, 30);
bodyright.addBox(-4F, -7.5F, -4F, 8, 1, 7);
bodyright.setRotationPoint(0F, 14F, 0F);
bodyright.setTextureSize(69, 38);
bodyright.mirror = true;
setRotation(bodyright, 1.570796F, 1.570796F, 0F);
}
@Override
public void render(final Entity entity, final float f, final float f1, final float f2, final float f3, final float f4, final float f5) {
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
handle.render(f5);
leg1.render(f5);
leg2.render(f5);
leg3.render(f5);
leg4.render(f5);
chimney1.render(f5);
chimney2.render(f5);
chimney3.render(f5);
chimney4.render(f5);
bodyleft.render(f5);
bodyback.render(f5);
bodyfrontright.render(f5);
bodytop.render(f5);
bodyfrontleft.render(f5);
bodybottom.render(f5);
bodyback2.render(f5);
bodyright.render(f5);
}
private void setRotation(final ModelRenderer model, final float x, final float y, final float z) {
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
@Override
public void setRotationAngles(final float f, final float f1, final float f2, final float f3, final float f4, final float f5, final Entity entity) {
super.setRotationAngles(f, f1, f2, f3, f4, f5, entity);
}
}
|
apache-2.0
|
ibissource/iaf
|
test-integration/src/test/java/nl/nn/adapterframework/pipes/EsbSoapWrapperPipeTest.java
|
9165
|
package nl.nn.adapterframework.pipes;
import org.junit.Test;
import nl.nn.adapterframework.core.PipeLineSession;
import nl.nn.adapterframework.core.PipeRunResult;
import nl.nn.adapterframework.extensions.esb.EsbSoapWrapperPipe;
import nl.nn.adapterframework.parameters.Parameter;
import nl.nn.adapterframework.stream.Message;
import nl.nn.adapterframework.testutil.TestAssertions;
import nl.nn.adapterframework.util.XmlUtils;
public class EsbSoapWrapperPipeTest extends SoapWrapperPipeTest<EsbSoapWrapperPipe> {
@Override
public EsbSoapWrapperPipe createPipe() {
EsbSoapWrapperPipe pipe = new EsbSoapWrapperPipe();
return pipe;
}
@Override
public void addParam(String name, String value) {
Parameter param = new Parameter();
param.setName(name);
param.setValue(value);
pipe.addParameter(param);
}
@Test
public void testWrapCMH2() throws Exception {
pipe.setOutputNamespace("http://nn.nl/XSD/Archiving/Document/3/GetDocumentAndAttributes/1");
pipe.setCmhVersion(2);
addParam("destination","destination-value");
addParam("errorCode","errorCode-value");
addParam("errorReason","errorReason-value");
addParam("errorDetailCode","errorDetailCode-value");
addParam("errorDetailText","errorDetailText-value");
addParam("operation","operation-value");
addParam("operationVersion","operationVersion-value");
pipe.setNamespaceAware(true);
pipe.configure();
pipe.start();
String input = "<GetDocumentAndAttributes_Response><attrib>1</attrib><attrib>2</attrib></GetDocumentAndAttributes_Response>";
PipeRunResult prr = pipe.doPipe(new Message(input),new PipeLineSession());
String result=prr.getResult().asString();
System.out.println("result ["+result+"]");
TestAssertions.assertXpathValueEquals("test", result, "/Envelope/Header/MessageHeader/From/Id");
// TestAssertions.assertXpathValueEquals("test", result, "/Envelope/Header/MessageHeader/Service/Name");
// TestAssertions.assertXpathValueEquals("operationVersion-value", result, "**/Envelope/Header/MessageHeader/Service/Version");
TestAssertions.assertXpathValueEquals("OK", result, "/Envelope/Body/MessageHeader/Result/Status");
}
@Test
public void testWrapFindDocumentsOK() throws Exception {
String outputNamespace="http://nn.nl/XSD/Archiving/Document/3/GetDocumentAndAttributes/1";
String rootElement="GetDocumentAndAttributes_Response";
String messagingLayer="ESB";
String businessDomain="Archiving";
String applicationName="BS";
String serviceName="Document";
String serviceVersion="3";
String operation="FindDocuments";
String operationVersion="1";
String paradigm="Request";
String errorCode=null;
String errorReason=null;
String errorDetailCode=null;
String errorDetailText=null;
String destination=messagingLayer+"."+businessDomain+"."+applicationName+"."+serviceName+"."+serviceVersion+"."+operation+"."+operationVersion+"."+paradigm;
pipe.setOutputNamespace(outputNamespace);
pipe.setCmhVersion(2);
addParam("destination",destination);
addParam("errorCode",errorCode);
addParam("errorReason",errorReason);
addParam("errorDetailCode",errorDetailCode);
addParam("errorDetailText",errorDetailText);
addParam("operation",null);
addParam("operationVersion",null);
pipe.setNamespaceAware(true);
pipe.configure();
pipe.start();
String input = "<"+rootElement+"><attrib>1</attrib><attrib>2</attrib></"+rootElement+">";
PipeRunResult prr = pipe.doPipe(new Message(input),new PipeLineSession());
String result=prr.getResult().asString();
System.out.println("result ["+result+"]");
TestAssertions.assertXpathValueEquals("test", result, "/Envelope/Header/MessageHeader/From/Id");
TestAssertions.assertXpathValueEquals(destination, result, "/Envelope/Header/MessageHeader/To/Location");
TestAssertions.assertXpathValueEquals(serviceName, result, "/Envelope/Header/MessageHeader/Service/Name");
TestAssertions.assertXpathValueEquals(paradigm, result, "/Envelope/Header/MessageHeader/Service/Action/Paradigm");
TestAssertions.assertXpathValueEquals(operation, result, "/Envelope/Header/MessageHeader/Service/Action/Name");
TestAssertions.assertXpathValueEquals(operationVersion, result, "/Envelope/Header/MessageHeader/Service/Action/Version");
TestAssertions.assertXpathValueEquals("ERROR", result, "/Envelope/Body/"+rootElement+"/Result/Status");
TestAssertions.assertXpathValueEquals(errorCode, result, "/Envelope/Body/"+rootElement+"/Result/ErrorList/Error/Code");
TestAssertions.assertXpathValueEquals(errorReason, result, "/Envelope/Body/"+rootElement+"/Result/ErrorList/Error/Reason");
TestAssertions.assertXpathValueEquals(errorDetailCode, result, "/Envelope/Body/"+rootElement+"/Result/ErrorList/Error/DetailList/Detail/Code");
TestAssertions.assertXpathValueEquals(XmlUtils.encodeChars(errorDetailText), result, "/Envelope/Body/"+rootElement+"/Result/ErrorList/Error/DetailList/Detail/Text");
}
@Test
public void testWrapFindDocumentsWithError() throws Exception {
String outputNamespace="http://nn.nl/XSD/Archiving/Document/3/GetDocumentAndAttributes/1";
String rootElement="GetDocumentAndAttributes_Response";
String messagingLayer="ESB";
String businessDomain="Archiving";
String applicationName="BS";
String serviceName="Document";
String serviceVersion="3";
String operation="FindDocuments";
String operationVersion="1";
String paradigm="Request";
String errorCode="errorCode-value";
String errorReason="errorReason-value";
String errorDetailCode="errorDetailCode-value";
String errorDetailText="<reasons>errorDetailText-value</reasons>";
String destination=messagingLayer+"."+businessDomain+"."+applicationName+"."+serviceName+"."+serviceVersion+"."+operation+"."+operationVersion+"."+paradigm;
pipe.setOutputNamespace(outputNamespace);
pipe.setCmhVersion(2);
addParam("destination",destination);
addParam("errorCode",errorCode);
addParam("errorReason",errorReason);
addParam("errorDetailCode",errorDetailCode);
addParam("errorDetailText",errorDetailText);
addParam("operation",operation);
addParam("operationVersion",operationVersion);
pipe.setNamespaceAware(true);
pipe.configure();
pipe.start();
String input = "<"+rootElement+"><attrib>1</attrib><attrib>2</attrib></"+rootElement+">";
PipeRunResult prr = pipe.doPipe(new Message(input),new PipeLineSession());
String result=prr.getResult().asString();
System.out.println("result ["+result+"]");
TestAssertions.assertXpathValueEquals("test", result, "/Envelope/Header/MessageHeader/From/Id");
TestAssertions.assertXpathValueEquals(destination, result, "/Envelope/Header/MessageHeader/To/Location");
TestAssertions.assertXpathValueEquals(serviceName, result, "/Envelope/Header/MessageHeader/Service/Name");
TestAssertions.assertXpathValueEquals(paradigm, result, "/Envelope/Header/MessageHeader/Service/Action/Paradigm");
TestAssertions.assertXpathValueEquals(operation, result, "/Envelope/Header/MessageHeader/Service/Action/Name");
TestAssertions.assertXpathValueEquals(operationVersion, result, "/Envelope/Header/MessageHeader/Service/Action/Version");
TestAssertions.assertXpathValueEquals("ERROR", result, "/Envelope/Body/"+rootElement+"/Result/Status");
TestAssertions.assertXpathValueEquals(errorCode, result, "/Envelope/Body/"+rootElement+"/Result/ErrorList/Error/Code");
TestAssertions.assertXpathValueEquals(errorReason, result, "/Envelope/Body/"+rootElement+"/Result/ErrorList/Error/Reason");
TestAssertions.assertXpathValueEquals(errorDetailCode, result, "/Envelope/Body/"+rootElement+"/Result/ErrorList/Error/DetailList/Detail/Code");
TestAssertions.assertXpathValueEquals(XmlUtils.encodeChars(errorDetailText), result, "/Envelope/Body/"+rootElement+"/Result/ErrorList/Error/DetailList/Detail/Text");
}
@Test
public void testWithError() throws Exception {
pipe.setOutputNamespace("http://nn.nl/XSD/Archiving/Document/3/GetDocumentAndAttributes/1");
pipe.setCmhVersion(2);
addParam("destination","destination-value");
addParam("errorCode","errorCode-value");
addParam("errorReason","errorReason-value");
addParam("errorDetailCode","errorDetailCode-value");
addParam("errorDetailText","errorDetailText-value");
addParam("operation","operation-value");
addParam("operationVersion","operationVersion-value");
pipe.configure();
pipe.start();
String input = "<GetDocumentAndAttributes_Response><attrib>1</attrib><attrib>2</attrib></GetDocumentAndAttributes_Response>";
PipeRunResult prr = pipe.doPipe(new Message(input),new PipeLineSession());
String result=prr.getResult().asString();
System.out.println("result ["+result+"]");
}
// @Override
// @Test
// @Ignore("Must incorporate CMH in test")
// public void testBasicUnWrap() throws Exception {
// // TODO Auto-generated method stub
// super.testBasicWrap();
// }
//
//
// @Override
// @Test
// @Ignore("Must incorporate CMH in test")
// public void testBasicWrapChangeRoot() throws Exception {
// // TODO Auto-generated method stub
// super.testBasicWrapChangeRoot();
// }
//
}
|
apache-2.0
|
rcbops/python-novaclient-buildpackage
|
tests/v1_1/test_servers.py
|
9616
|
import StringIO
from novaclient.v1_1 import servers
from tests import utils
from tests.v1_1 import fakes
cs = fakes.FakeClient()
class ServersTest(utils.TestCase):
def test_list_servers(self):
sl = cs.servers.list()
cs.assert_called('GET', '/servers/detail')
[self.assertTrue(isinstance(s, servers.Server)) for s in sl]
def test_list_servers_undetailed(self):
sl = cs.servers.list(detailed=False)
cs.assert_called('GET', '/servers')
[self.assertTrue(isinstance(s, servers.Server)) for s in sl]
def test_get_server_details(self):
s = cs.servers.get(1234)
cs.assert_called('GET', '/servers/1234')
self.assertTrue(isinstance(s, servers.Server))
self.assertEqual(s.id, 1234)
self.assertEqual(s.status, 'BUILD')
def test_create_server(self):
s = cs.servers.create(
name="My server",
image=1,
flavor=1,
meta={'foo': 'bar'},
userdata="hello moto",
key_name="fakekey",
files={
'/etc/passwd': 'some data', # a file
'/tmp/foo.txt': StringIO.StringIO('data'), # a stream
}
)
cs.assert_called('POST', '/servers')
self.assertTrue(isinstance(s, servers.Server))
def test_create_server_userdata_file_object(self):
s = cs.servers.create(
name="My server",
image=1,
flavor=1,
meta={'foo': 'bar'},
userdata=StringIO.StringIO('hello moto'),
files={
'/etc/passwd': 'some data', # a file
'/tmp/foo.txt': StringIO.StringIO('data'), # a stream
},
)
cs.assert_called('POST', '/servers')
self.assertTrue(isinstance(s, servers.Server))
def test_update_server(self):
s = cs.servers.get(1234)
# Update via instance
s.update(name='hi')
cs.assert_called('PUT', '/servers/1234')
s.update(name='hi')
cs.assert_called('PUT', '/servers/1234')
# Silly, but not an error
s.update()
# Update via manager
cs.servers.update(s, name='hi')
cs.assert_called('PUT', '/servers/1234')
def test_delete_server(self):
s = cs.servers.get(1234)
s.delete()
cs.assert_called('DELETE', '/servers/1234')
cs.servers.delete(1234)
cs.assert_called('DELETE', '/servers/1234')
cs.servers.delete(s)
cs.assert_called('DELETE', '/servers/1234')
def test_delete_server_meta(self):
s = cs.servers.delete_meta(1234, ['test_key'])
cs.assert_called('DELETE', '/servers/1234/metadata/test_key')
def test_set_server_meta(self):
s = cs.servers.set_meta(1234, {'test_key': 'test_value'})
reval = cs.assert_called('POST', '/servers/1234/metadata',
{'metadata': {'test_key': 'test_value'}})
def test_find(self):
s = cs.servers.find(name='sample-server')
cs.assert_called('GET', '/servers/detail')
self.assertEqual(s.name, 'sample-server')
# Find with multiple results arbitraility returns the first item
s = cs.servers.find(flavor={"id": 1, "name": "256 MB Server"})
sl = cs.servers.findall(flavor={"id": 1, "name": "256 MB Server"})
self.assertEqual(sl[0], s)
self.assertEqual([s.id for s in sl], [1234, 5678])
def test_reboot_server(self):
s = cs.servers.get(1234)
s.reboot()
cs.assert_called('POST', '/servers/1234/action')
cs.servers.reboot(s, type='HARD')
cs.assert_called('POST', '/servers/1234/action')
def test_rebuild_server(self):
s = cs.servers.get(1234)
s.rebuild(image=1)
cs.assert_called('POST', '/servers/1234/action')
cs.servers.rebuild(s, image=1)
cs.assert_called('POST', '/servers/1234/action')
s.rebuild(image=1, password='5678')
cs.assert_called('POST', '/servers/1234/action')
cs.servers.rebuild(s, image=1, password='5678')
cs.assert_called('POST', '/servers/1234/action')
def test_resize_server(self):
s = cs.servers.get(1234)
s.resize(flavor=1)
cs.assert_called('POST', '/servers/1234/action')
cs.servers.resize(s, flavor=1)
cs.assert_called('POST', '/servers/1234/action')
def test_confirm_resized_server(self):
s = cs.servers.get(1234)
s.confirm_resize()
cs.assert_called('POST', '/servers/1234/action')
cs.servers.confirm_resize(s)
cs.assert_called('POST', '/servers/1234/action')
def test_revert_resized_server(self):
s = cs.servers.get(1234)
s.revert_resize()
cs.assert_called('POST', '/servers/1234/action')
cs.servers.revert_resize(s)
cs.assert_called('POST', '/servers/1234/action')
def test_migrate_server(self):
s = cs.servers.get(1234)
s.migrate()
cs.assert_called('POST', '/servers/1234/action')
cs.servers.migrate(s)
cs.assert_called('POST', '/servers/1234/action')
def test_add_fixed_ip(self):
s = cs.servers.get(1234)
s.add_fixed_ip(1)
cs.assert_called('POST', '/servers/1234/action')
cs.servers.add_fixed_ip(s, 1)
cs.assert_called('POST', '/servers/1234/action')
def test_remove_fixed_ip(self):
s = cs.servers.get(1234)
s.remove_fixed_ip('10.0.0.1')
cs.assert_called('POST', '/servers/1234/action')
cs.servers.remove_fixed_ip(s, '10.0.0.1')
cs.assert_called('POST', '/servers/1234/action')
def test_add_floating_ip(self):
s = cs.servers.get(1234)
s.add_floating_ip('11.0.0.1')
cs.assert_called('POST', '/servers/1234/action')
cs.servers.add_floating_ip(s, '11.0.0.1')
cs.assert_called('POST', '/servers/1234/action')
f = cs.floating_ips.list()[0]
cs.servers.add_floating_ip(s, f)
cs.assert_called('POST', '/servers/1234/action')
s.add_floating_ip(f)
cs.assert_called('POST', '/servers/1234/action')
def test_remove_floating_ip(self):
s = cs.servers.get(1234)
s.remove_floating_ip('11.0.0.1')
cs.assert_called('POST', '/servers/1234/action')
cs.servers.remove_floating_ip(s, '11.0.0.1')
cs.assert_called('POST', '/servers/1234/action')
f = cs.floating_ips.list()[0]
cs.servers.remove_floating_ip(s, f)
cs.assert_called('POST', '/servers/1234/action')
s.remove_floating_ip(f)
cs.assert_called('POST', '/servers/1234/action')
def test_rescue(self):
s = cs.servers.get(1234)
s.rescue()
cs.assert_called('POST', '/servers/1234/action')
cs.servers.rescue(s)
cs.assert_called('POST', '/servers/1234/action')
def test_unrescue(self):
s = cs.servers.get(1234)
s.unrescue()
cs.assert_called('POST', '/servers/1234/action')
cs.servers.unrescue(s)
cs.assert_called('POST', '/servers/1234/action')
def test_get_console_output_without_length(self):
success = 'foo'
s = cs.servers.get(1234)
s.get_console_output()
self.assertEqual(s.get_console_output(), success)
cs.assert_called('POST', '/servers/1234/action')
cs.servers.get_console_output(s)
self.assertEqual(cs.servers.get_console_output(s), success)
cs.assert_called('POST', '/servers/1234/action')
def test_get_console_output_with_length(self):
success = 'foo'
s = cs.servers.get(1234)
s.get_console_output(length=50)
self.assertEqual(s.get_console_output(length=50), success)
cs.assert_called('POST', '/servers/1234/action')
cs.servers.get_console_output(s, length=50)
self.assertEqual(cs.servers.get_console_output(s, length=50), success)
cs.assert_called('POST', '/servers/1234/action')
def test_get_server_actions(self):
s = cs.servers.get(1234)
actions = s.actions()
self.assertTrue(actions is not None)
cs.assert_called('GET', '/servers/1234/actions')
actions_from_manager = cs.servers.actions(1234)
self.assertTrue(actions_from_manager is not None)
cs.assert_called('GET', '/servers/1234/actions')
self.assertEqual(actions, actions_from_manager)
def test_get_server_diagnostics(self):
s = cs.servers.get(1234)
diagnostics = s.diagnostics()
self.assertTrue(diagnostics is not None)
cs.assert_called('GET', '/servers/1234/diagnostics')
diagnostics_from_manager = cs.servers.diagnostics(1234)
self.assertTrue(diagnostics_from_manager is not None)
cs.assert_called('GET', '/servers/1234/diagnostics')
self.assertEqual(diagnostics, diagnostics_from_manager)
def test_get_vnc_console(self):
s = cs.servers.get(1234)
s.get_vnc_console('fake')
cs.assert_called('POST', '/servers/1234/action')
cs.servers.get_vnc_console(s, 'fake')
cs.assert_called('POST', '/servers/1234/action')
def test_create_image(self):
s = cs.servers.get(1234)
s.create_image('123')
cs.assert_called('POST', '/servers/1234/action')
s.create_image('123', {})
cs.assert_called('POST', '/servers/1234/action')
cs.servers.create_image(s, '123')
cs.assert_called('POST', '/servers/1234/action')
cs.servers.create_image(s, '123', {})
|
apache-2.0
|
dasomel/egovframework
|
common-component/v3.6.2/src/script/altibase/ddl/uss.ion.uas_create_altibase.sql
|
5416
|
CREATE TABLE COMTECOPSEQ
(
TABLE_NAME VARCHAR2(20) NOT NULL ,
NEXT_ID NUMBER(30) NULL ,
CONSTRAINT COMTECOPSEQ_PK PRIMARY KEY (TABLE_NAME)
);
CREATE TABLE COMTNUSERABSNCE
(
EMPLYR_ID VARCHAR2(20) NOT NULL ,
USER_ABSNCE_AT CHAR(1) NOT NULL ,
FRST_REGISTER_ID VARCHAR2(20) NULL ,
FRST_REGIST_PNTTM DATE NULL ,
LAST_UPDUSR_ID VARCHAR2(20) NULL ,
LAST_UPDT_PNTTM DATE NULL ,
CONSTRAINT COMTNUSERABSNCE_PK PRIMARY KEY (EMPLYR_ID)
);
CREATE TABLE COMTCCMMNCLCODE
(
CL_CODE CHAR(3) NOT NULL ,
CL_CODE_NM VARCHAR2(60) NULL ,
CL_CODE_DC VARCHAR2(200) NULL ,
USE_AT CHAR(1) NULL ,
FRST_REGIST_PNTTM DATE NULL ,
FRST_REGISTER_ID VARCHAR2(20) NULL ,
LAST_UPDT_PNTTM DATE NULL ,
LAST_UPDUSR_ID VARCHAR2(20) NULL ,
CONSTRAINT COMTCCMMNCLCODE_PK PRIMARY KEY (CL_CODE)
);
CREATE TABLE COMTCCMMNCODE
(
CODE_ID VARCHAR2(6) NOT NULL ,
CODE_ID_NM VARCHAR2(60) NULL ,
CODE_ID_DC VARCHAR2(200) NULL ,
USE_AT CHAR(1) NULL ,
CL_CODE CHAR(3) NULL ,
FRST_REGIST_PNTTM DATE NULL ,
FRST_REGISTER_ID VARCHAR2(20) NULL ,
LAST_UPDT_PNTTM DATE NULL ,
LAST_UPDUSR_ID VARCHAR2(20) NULL ,
CONSTRAINT COMTCCMMNCODE_PK PRIMARY KEY (CODE_ID),
CONSTRAINT COMTCCMMNCODE_FK1 FOREIGN KEY (CL_CODE) REFERENCES COMTCCMMNCLCODE(CL_CODE) ON DELETE CASCADE
);
CREATE INDEX COMTCCMMNCODE_i01 ON COMTCCMMNCODE
(CL_CODE ASC);
CREATE TABLE COMTCCMMNDETAILCODE
(
CODE_ID VARCHAR2(6) NOT NULL ,
CODE VARCHAR2(15) NOT NULL ,
CODE_NM VARCHAR2(60) NULL ,
CODE_DC VARCHAR2(200) NULL ,
USE_AT CHAR(1) NULL ,
FRST_REGIST_PNTTM DATE NULL ,
FRST_REGISTER_ID VARCHAR2(20) NULL ,
LAST_UPDT_PNTTM DATE NULL ,
LAST_UPDUSR_ID VARCHAR2(20) NULL ,
CONSTRAINT COMTCCMMNDETAILCODE_PK PRIMARY KEY (CODE_ID,CODE),
CONSTRAINT COMTCCMMNDETAILCODE_FK1 FOREIGN KEY (CODE_ID) REFERENCES COMTCCMMNCODE(CODE_ID)
);
CREATE INDEX COMTCCMMNDETAILCODE_i01 ON COMTCCMMNDETAILCODE
(CODE_ID ASC);
CREATE TABLE COMTNAUTHORGROUPINFO
(
GROUP_ID CHAR(20) NOT NULL ,
GROUP_NM VARCHAR2(60) NOT NULL ,
GROUP_CREAT_DE CHAR(20) NOT NULL ,
GROUP_DC VARCHAR2(100) NULL ,
CONSTRAINT COMTNAUTHORGROUPINFO_PK PRIMARY KEY (GROUP_ID)
);
CREATE TABLE COMTNORGNZTINFO
(
ORGNZT_ID CHAR(20) NOT NULL ,
ORGNZT_NM VARCHAR2(20) NOT NULL ,
ORGNZT_DC VARCHAR2(100) NULL ,
CONSTRAINT COMTNORGNZTINFO_PK PRIMARY KEY (ORGNZT_ID)
);
CREATE TABLE COMTNEMPLYRINFO
(
EMPLYR_ID VARCHAR2(20) NOT NULL ,
ORGNZT_ID CHAR(20) NULL ,
USER_NM VARCHAR2(60) NOT NULL ,
PASSWORD VARCHAR2(200) NOT NULL ,
EMPL_NO VARCHAR2(20) NULL ,
IHIDNUM VARCHAR2(200) NULL ,
SEXDSTN_CODE CHAR(1) NULL ,
BRTHDY CHAR(20) NULL ,
FXNUM VARCHAR2(20) NULL ,
HOUSE_ADRES VARCHAR2(100) NOT NULL ,
PASSWORD_HINT VARCHAR2(100) NOT NULL ,
PASSWORD_CNSR VARCHAR2(100) NOT NULL ,
HOUSE_END_TELNO VARCHAR2(4) NOT NULL ,
AREA_NO VARCHAR2(4) NOT NULL ,
DETAIL_ADRES VARCHAR2(100) NULL ,
ZIP VARCHAR2(6) NOT NULL ,
OFFM_TELNO VARCHAR2(20) NULL ,
MBTLNUM VARCHAR2(20) NULL ,
EMAIL_ADRES VARCHAR2(50) NULL ,
OFCPS_NM VARCHAR2(60) NULL ,
HOUSE_MIDDLE_TELNO VARCHAR2(4) NOT NULL ,
GROUP_ID CHAR(20) NULL ,
PSTINST_CODE CHAR(8) NULL ,
EMPLYR_STTUS_CODE CHAR(1) NOT NULL ,
ESNTL_ID CHAR(20) NOT NULL ,
CRTFC_DN_VALUE VARCHAR2(100) NULL ,
SBSCRB_DE DATE NULL ,
CONSTRAINT COMTNEMPLYRINFO_PK PRIMARY KEY (EMPLYR_ID),
CONSTRAINT COMTNEMPLYRINFO_FK2 FOREIGN KEY (ORGNZT_ID) REFERENCES COMTNORGNZTINFO(ORGNZT_ID) ON DELETE CASCADE,
CONSTRAINT COMTNEMPLYRINFO_FK1 FOREIGN KEY (GROUP_ID) REFERENCES COMTNAUTHORGROUPINFO(GROUP_ID) ON DELETE CASCADE
);
CREATE INDEX COMTNEMPLYRINFO_i01 ON COMTNEMPLYRINFO
(ORGNZT_ID ASC);
CREATE INDEX COMTNEMPLYRINFO_i02 ON COMTNEMPLYRINFO
(GROUP_ID ASC);
CREATE TABLE COMTNFILE
(
ATCH_FILE_ID CHAR(20) NOT NULL ,
CREAT_DT DATE NOT NULL ,
USE_AT CHAR(1) NULL ,
CONSTRAINT COMTNFILE_PK PRIMARY KEY (ATCH_FILE_ID)
);
CREATE TABLE COMTNFILEDETAIL
(
ATCH_FILE_ID CHAR(20) NOT NULL ,
FILE_SN NUMBER(10) NOT NULL ,
FILE_STRE_COURS VARCHAR2(2000) NOT NULL ,
STRE_FILE_NM VARCHAR2(255) NOT NULL ,
ORIGNL_FILE_NM VARCHAR2(255) NULL ,
FILE_EXTSN VARCHAR2(20) NOT NULL ,
FILE_CN CLOB NULL ,
FILE_SIZE NUMBER(8) NULL ,
CONSTRAINT COMTNFILEDETAIL_PK PRIMARY KEY (ATCH_FILE_ID,FILE_SN),
CONSTRAINT COMTNFILEDETAIL_FK1 FOREIGN KEY (ATCH_FILE_ID) REFERENCES COMTNFILE(ATCH_FILE_ID)
);
CREATE INDEX COMTNFILEDETAIL_i01 ON COMTNFILEDETAIL
(ATCH_FILE_ID ASC);
|
apache-2.0
|
LewisTao/depot
|
app/controllers/carts_controller.rb
|
2122
|
class CartsController < ApplicationController
before_action :set_cart, only: [:edit, :update]
# GET /carts
# GET /carts.json
def index
@carts = Cart.all
end
# GET /carts/1
# GET /carts/1.json
def show
begin
@cart = Cart.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to root_path, notice: 'Invalid cart'
else
respond_to do |format|
format.html
format.json { render json: @cart }
end
end
end
# GET /carts/new
def new
@cart = Cart.new
end
# GET /carts/1/edit
def edit
end
# POST /carts
# POST /carts.json
def create
@cart = Cart.new(cart_params)
respond_to do |format|
if @cart.save
format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
format.json { render :show, status: :created, location: @cart }
else
format.html { render :new }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /carts/1
# PATCH/PUT /carts/1.json
def update
respond_to do |format|
if @cart.update(cart_params)
format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
format.json { render :show, status: :ok, location: @cart }
else
format.html { render :edit }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
# DELETE /carts/1
# DELETE /carts/1.json
def destroy
@cart = current_cart
@cart.destroy
session[:cart_id] = nil
flash[:success]= 'Cart was successfully destroyed.'
respond_to do |format|
format.html { redirect_to root_path}
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cart
@cart = Cart.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cart_params
params[:cart]
end
end
|
apache-2.0
|
ben-ng/swift
|
lib/SILOptimizer/Analysis/FunctionOrder.cpp
|
2705
|
//===--- FunctionOrder.cpp - Utility for function ordering ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SILOptimizer/Analysis/FunctionOrder.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <algorithm>
using namespace swift;
/// Use Tarjan's strongly connected components (SCC) algorithm to find
/// the SCCs in the call graph.
void BottomUpFunctionOrder::DFS(SILFunction *Start) {
// Set the DFSNum for this node if we haven't already, and if we
// have, which indicates it's already been visited, return.
if (!DFSNum.insert(std::make_pair(Start, NextDFSNum)).second)
return;
assert(MinDFSNum.find(Start) == MinDFSNum.end() &&
"Function should not already have a minimum DFS number!");
MinDFSNum[Start] = NextDFSNum;
++NextDFSNum;
DFSStack.insert(Start);
// Visit all the instructions, looking for apply sites.
for (auto &B : *Start) {
for (auto &I : B) {
auto FAS = FullApplySite::isa(&I);
if (!FAS && !isa<StrongReleaseInst>(&I) && !isa<ReleaseValueInst>(&I))
continue;
auto Callees = FAS ? BCA->getCalleeList(FAS) : BCA->getCalleeList(&I);
for (auto *CalleeFn : Callees) {
// If not yet visited, visit the callee.
if (DFSNum.find(CalleeFn) == DFSNum.end()) {
DFS(CalleeFn);
MinDFSNum[Start] = std::min(MinDFSNum[Start], MinDFSNum[CalleeFn]);
} else if (DFSStack.count(CalleeFn)) {
// If the callee is on the stack, it update our minimum DFS
// number based on it's DFS number.
MinDFSNum[Start] = std::min(MinDFSNum[Start], DFSNum[CalleeFn]);
}
}
}
}
// If our DFS number is the minimum found, we've found a
// (potentially singleton) SCC, so pop the nodes off the stack and
// push the new SCC on our stack of SCCs.
if (DFSNum[Start] == MinDFSNum[Start]) {
SCC CurrentSCC;
SILFunction *Popped;
do {
Popped = DFSStack.pop_back_val();
CurrentSCC.push_back(Popped);
} while (Popped != Start);
TheSCCs.push_back(CurrentSCC);
}
}
void BottomUpFunctionOrder::FindSCCs(SILModule &M) {
for (auto &F : M)
DFS(&F);
}
|
apache-2.0
|
gefangshuai/baseFinal-noshiro
|
src/main/java/io/github/eternalpro/model/User.java
|
631
|
package io.github.eternalpro.model;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Model;
import io.github.gefangshuai.wfinal.model.core.WModel;
import java.util.List;
/**
* Created by gefangshuai on 2015-05-18-0018.
*/
@TableBind(tableName = "sec_user", pkName = "id")
public class User extends WModel<User> {
public static final User dao = new User();
public User findByUsername(String loginName) {
return dao.findFirst("select * from sec_user t where t.username = ?", loginName);
}
public User findByMobile(String username) {
return null;
}
}
|
apache-2.0
|
caterpillar/interfacedesign
|
design-auth/src/test/java/org/interfacedesign/auth/domain/model/RolesRepositoryTest.java
|
1376
|
package org.interfacedesign.auth.domain.model;
import org.interfacedesign.auth.domain.model.repository.RoleRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Created by lishaohua on 16-6-7.
*/
@ContextConfiguration(
locations = {"classpath:config/applicationContext-jpa.xml", "classpath:config/applicationContext-beans.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class RolesRepositoryTest {
@Autowired
private RoleRepository roleRepository;
@Test
@Transactional
public void testRoleSave() {
Role role = new Role("UNIT_TEST", "the role to design the interface");
roleRepository.save(role);
}
@Test
@Transactional
public void testGetRoleByName() {
Role role = new Role("UNIT_TEST", "the role to design the interface");
roleRepository.save(role);
Role designer = roleRepository.findByName("UNIT_TEST");
assertNotNull(designer);
assertEquals(designer.getName(), "UNIT_TEST");
}
}
|
apache-2.0
|
jessemull/MicroFlex
|
src/main/java/com/github/jessemull/microflex/bigintegerflex/stat/InterquartileRangeBigInteger.java
|
6309
|
/**
* 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 -------------------------------- */
package com.github.jessemull.microflex.bigintegerflex.stat;
/* ----------------------------- Dependencies ------------------------------ */
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Collections;
import java.util.List;
/**
* This class calculates the inter-quartile range of BigInteger plate stacks, plates,
* wells and well sets.
*
* <br><br>
*
* Statistical operations can be performed on stacks, plates, sets and wells using
* standard or aggregated functions. Standard functions calculate the desired
* statistic for each well in the stack, plate or set. Aggregated functions aggregate
* the values from all the wells in the stack, plate or set and perform the statistical
* operation on the aggregated values. Both standard and aggregated functions can
* be performed on a subset of data within the stack, plate, set or well.
*
* <br><br>
*
* The methods within the MicroFlex library are meant to be flexible and the
* descriptive statistic object supports operations using a single stack, plate,
* set or well as well as collections and arrays of stacks, plates, sets or wells.
*
* <table cellspacing="10px" style="text-align:left; margin: 20px;">
* <th><div style="border-bottom: 1px solid black; padding-bottom: 5px; padding-top: 18px;">Operation<div></th>
* <th><div style="border-bottom: 1px solid black; padding-bottom: 5px;">Beginning<br>Index<div></th>
* <th><div style="border-bottom: 1px solid black; padding-bottom: 5px;">Length of<br>Subset<div></th>
* <th><div style="border-bottom: 1px solid black; padding-bottom: 5px; padding-top: 18px;">Input/Output</div></th>
* <tr>
* <td valign="top">
* <table>
* <tr>
* <td>Standard</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>+/-</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>+/-</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>Accepts a single well, set, plate or stack as input</td>
* </tr>
* <tr>
* <td>Calculates the statistic for each well in a well, set, plate or stack</td>
* </tr>
* </table>
* </td>
* </tr>
* <tr>
* <td valign="top">
* <table>
* <tr>
* <td>Aggregated</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>+/-</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>+/-</td>
* </tr>
* </table>
* </td>
* <td valign="top">
* <table>
* <tr>
* <td>Accepts a single well/set/plate/stack or a collection/array of wells/sets/plates/stacks as input</td>
* </tr>
* <tr>
* <td>Aggregates the data from all the wells in a well/set/plate/stack and calculates the statistic using the aggregated data</td>
* </tr>
* </table>
* </td>
* </tr>
* </table>
*
* @author Jesse L. Mull
* @update Updated Oct 18, 2016
* @address http://www.jessemull.com
* @email [email protected]
*/
public class InterquartileRangeBigInteger extends DescriptiveStatisticBigIntegerContext {
/**
* Calculates the inter-quartile range.
* @param List<BigDecimal> the list
* @param MathContext the math context
* @return the result
*/
public BigDecimal calculate(List<BigDecimal> list, MathContext mc) {
Collections.sort(list);
if(list.size() < 2) {
return BigDecimal.ZERO;
}
int index = list.size() / 2;
List<BigDecimal> listQ1 = list.subList(0, index);
int lowQ1 = (int) Math.floor((listQ1.size() - 1.0) / 2.0);
int highQ1 = (int) Math.ceil((listQ1.size() - 1.0) / 2.0);
BigDecimal q1 = (listQ1.get(lowQ1).add(listQ1.get(highQ1))).divide(new BigDecimal(2), mc);
if(list.size() % 2 != 0) {
index++;
}
List<BigDecimal> listQ3 = list.subList(index, list.size());
int lowQ3 = (int) Math.floor((listQ3.size() - 1.0) / 2.0);
int highQ3 = (int) Math.ceil((listQ3.size() - 1.0) / 2.0);
BigDecimal q3 = (listQ3.get(lowQ3).add(listQ3.get(highQ3))).divide(new BigDecimal(2), mc);
return q3.subtract(q1);
}
/**
* Calculates the inter-quartile range of the values between the beginning and
* ending indices.
* @param List<BigDecimal> the list
* @param int beginning index of subset
* @param int length of subset
* @param MathContext the math context
* @return the result
*/
public BigDecimal calculate(List<BigDecimal> list, int begin, int length, MathContext mc) {
return calculate(list.subList(begin, begin + length), mc);
}
}
|
apache-2.0
|
TITcs/TITcs.SharePoint
|
src/TITcs.SharePoint/Query/LinqProvider/Parsing/ExpressionTreeVisitors/SubQueryFindingExpressionTreeVisitor.cs
|
3201
|
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon 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.
//
using System;
using System.Linq.Expressions;
using TITcs.SharePoint.Query.LinqProvider.Clauses.Expressions;
using TITcs.SharePoint.Query.LinqProvider.Parsing.Structure;
using TITcs.SharePoint.Query.LinqProvider.Parsing.Structure.ExpressionTreeProcessors;
using TITcs.SharePoint.Query.SharedSource.Utilities;
namespace TITcs.SharePoint.Query.LinqProvider.Parsing.ExpressionTreeVisitors
{
/// <summary>
/// Preprocesses an expression tree for parsing. The preprocessing involves detection of sub-queries and VB-specific expressions.
/// </summary>
public class SubQueryFindingExpressionTreeVisitor : ExpressionTreeVisitor
{
public static Expression Process (Expression expressionTree, INodeTypeProvider nodeTypeProvider)
{
ArgumentUtility.CheckNotNull ("expressionTree", expressionTree);
ArgumentUtility.CheckNotNull ("nodeTypeProvider", nodeTypeProvider);
var visitor = new SubQueryFindingExpressionTreeVisitor (nodeTypeProvider);
return visitor.VisitExpression (expressionTree);
}
private readonly INodeTypeProvider _nodeTypeProvider;
private readonly ExpressionTreeParser _expressionTreeParser;
private readonly QueryParser _queryParser;
private SubQueryFindingExpressionTreeVisitor (INodeTypeProvider nodeTypeProvider)
{
ArgumentUtility.CheckNotNull ("nodeTypeProvider", nodeTypeProvider);
_nodeTypeProvider = nodeTypeProvider;
_expressionTreeParser = new ExpressionTreeParser (_nodeTypeProvider, new NullExpressionTreeProcessor());
_queryParser = new QueryParser (_expressionTreeParser);
}
public override Expression VisitExpression (Expression expression)
{
var potentialQueryOperatorExpression = _expressionTreeParser.GetQueryOperatorExpression (expression);
if (potentialQueryOperatorExpression != null && _nodeTypeProvider.IsRegistered (potentialQueryOperatorExpression.Method))
return CreateSubQueryNode (potentialQueryOperatorExpression);
else
return base.VisitExpression (expression);
}
protected internal override Expression VisitUnknownNonExtensionExpression (Expression expression)
{
//ignore
return expression;
}
private SubQueryExpression CreateSubQueryNode (MethodCallExpression methodCallExpression)
{
QueryModel queryModel = _queryParser.GetParsedQuery (methodCallExpression);
return new SubQueryExpression (queryModel);
}
}
}
|
apache-2.0
|
libra/libra
|
testsuite/cli/diem-wallet/README.md
|
2698
|
# Diem Wallet
Diem Wallet is a pure-rust implementation of hierarchical key derivation for SecretKey material in Diem.
# Overview
`diem-wallet` is a library providing hierarchical key derivation for SecretKey material in Diem. The following crate is largely inspired by [`rust-wallet`](https://github.com/rust-bitcoin/rust-wallet) with minor modifications to the key derivation function. Note that Diem makes use of the ed25519 Edwards Curve Digital Signature Algorithm (EdDSA) over the Edwards Cruve cruve25519. Therefore, BIP32-like PublicKey derivation is not possible without falling back to a traditional non-deterministic Schnorr signature algorithm. For this reason, we modified the key derivation function to a simpler alternative.
The `internal_macros.rs` is taken from [`rust-bitcoin`](https://github.com/rust-bitcoin/rust-bitcoin/blob/master/src/internal_macros.rs) and `mnemonic.rs` is a slightly modified version of the file with the same name from [`rust-wallet`](https://github.com/rust-bitcoin/rust-wallet/blob/master/src/mnemonic.rs), while `error.rs`, `key_factor.rs` and `wallet_library.rs` are modified to present a minimalist wallet library for the Diem Client. Note that `mnemonic.rs` from `rust-wallet` adheres to the [`BIP39`](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) spec.
# Implementation Details
`key_factory.rs` implements the key derivation functions. The `KeyFactory` struct holds the Master Secret Material used to derive the Child Key(s). The constructor of a particular `KeyFactory` accepts a `[u8; 64]` `Seed` and computes both the `Master` Secret Material as well as the `ChainCode` from the HMAC-512 of the `Seed`. Finally, the `KeyFactory` allows to derive a child PrivateKey at a particular `ChildNumber` from the Master and ChainCode, as well as the `ChildNumber`'s u64 member.
`wallet_library.rs` is a thin wrapper around `KeyFactory` which enables to keep track of Diem `AccountAddresses` and the information required to restore the current wallet from a `Mnemonic` backup. The `WalletLibrary` struct includes constructors that allow to generate a new `WalletLibrary` from OS randomness or generate a `WalletLibrary` from an instance of `Mnemonic`. `WalletLibrary` also allows to generate new addresses in-order or out-of-order via the `fn new_address` and `fn new_address_at_child_number`. Finally, `WalletLibrary` is capable of signing a Diem `RawTransaction` with the PrivateKey associated to the `AccountAddress` submitted. Note that in the future, Diem will support rotating authentication keys and therefore, `WalletLibrary` will need to understand more general inputs when mapping `AuthenticationKeys` to `PrivateKeys`
|
apache-2.0
|
freeVM/freeVM
|
standard/site/docs/subcomponents/drlvm/doxygen/vmcore/html/structjvmti_event_callbacks-members.html
|
9734
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>VM Infrastructure: Member List</title>
<link href="hydoxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.2 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<h1>jvmtiEventCallbacks Member List</h1>This is the complete list of members for <a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a>, including all inherited members.<p><table>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#86b1461ef814791428da2141b0204e52">Breakpoint</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#e31f3704e6f584f715a75710ba43e9a9">ClassFileLoadHook</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#18daf3767848c23ed6bf766bb90eda95">ClassLoad</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#b99ae017750c14ccf7c5dc83f7a39002">ClassPrepare</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#b9c7824e830e4c7dd1406a996f2e7e51">CompiledMethodLoad</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#af1d04c6db38a34d574e524ac4e4837c">CompiledMethodUnload</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#eac5104364eaca6fa5fae047d7963e93">DataDumpRequest</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#9fd1aa2684fe57044a44b96fe76ba12d">DataResetRequest</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#f1677b344466b34cefcbcf93fcd1a544">DynamicCodeGenerated</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#863cee2b81d592ad55cb9f8743c7be83">Exception</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#e5cae764ac6a8897ab35579caaf1a2a2">ExceptionCatch</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#0ae577ee8281827b83c594038c245f74">FieldAccess</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#94da64aef9b223866ed2cb6ded58e59c">FieldModification</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#9480db6798e1b3515f450a19c8d324cb">FramePop</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#7f56e4023ef5a6a486bf2ac32681e206">GarbageCollectionFinish</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#5fb412eebdc10c94dbcd3505f4171d0b">GarbageCollectionStart</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#b85cf60f3b5ebbce8c22e74fe4bd1e49">MethodEntry</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#a0837b390d09717b7a64fee37abb2f41">MethodExit</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#2fc693300ea999871600de9f4b27cc14">MonitorContendedEnter</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#628db21d1d2fc231e1279ab3d580be42">MonitorContendedEntered</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#431a77079a7a76f1592c583de463c156">MonitorWait</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#6ef67bdf9374624b635d183f3932f19e">MonitorWaited</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#efe89f27ad7001e28d5ece800a332e9d">NativeMethodBind</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#9fd15400405c6a0d8a8e19e9c7ec4721">ObjectFree</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#fa175b26a429759aa61f9315490c28c7">reserved77</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#e2b377c3e969b26734a9011605d9d4f3">reserved78</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#01a960529196acbaea93b7cc1cc1df11">reserved79</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#568a9841233d8960413d275d0e297402">reserved80</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#db5d26e2bd94795cbc27649278d23057">SingleStep</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#e5179ebafde2b993cd2987d11a3b87aa">ThreadEnd</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#43a91d996ea568ec99ba2318e39ca6dc">ThreadStart</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#b5c049b15f5e2011fa4f6a8365166545">VMDeath</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#a9742b13b594fb129173ff872953d896">VMInit</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#16298c2de787a8df610f146fde22a882">VMObjectAlloc</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structjvmti_event_callbacks.html#f63fa01030238f4d5a5eb04b877d620d">VMStart</a></td><td><a class="el" href="structjvmti_event_callbacks.html">jvmtiEventCallbacks</a></td><td></td></tr>
</table><hr size="1">
<address style="text-align: center;">
<small>
<p>Genereated on Tue Mar 11 19:26:02 2008 by Doxygen.</p>
<p>(c) Copyright 2005, 2008 The Apache Software Foundation or its licensors, as applicable. </p>
</small>
</address>
</body>
</html>
|
apache-2.0
|
hoge1e3/soyText
|
src/jp/tonyu/soytext2/servlet/Httpd.java
|
1747
|
/*
* 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 jp.tonyu.soytext2.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;
public class Httpd {
public static void respondByString(HttpServletResponse response, String str) throws IOException
{
response.getWriter().println(str);
}
public static void respondByFile(HttpServletResponse response, File file) throws IOException
{
String con=HttpContext.detectContentType(file.getName());
response.setContentType(con);
FileInputStream in = new FileInputStream(file);
outputFromStream(response, in);
in.close();
}
public static void outputFromStream(HttpServletResponse res, InputStream in) throws IOException {
byte[] buf= new byte[1024];
while (true) {
int r=in.read(buf);
if (r<=0) break;
res.getOutputStream().write(buf,0,r);
}
}
}
|
apache-2.0
|
eSDK/esdk_uc_native_java
|
source/esdk_uc_native_professional_java/src/main/java/com/huawei/esdk/uc/professional/local/impl/autogen/ModifyTalkMode.java
|
3578
|
package com.huawei.esdk.uc.professional.local.impl.autogen;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ucAccount" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="confId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="number" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="talkMode" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ucAccount",
"confId",
"number",
"talkMode"
})
@XmlRootElement(name = "modifyTalkMode")
public class ModifyTalkMode {
@XmlElement(required = true)
protected String ucAccount;
@XmlElement(required = true)
protected String confId;
@XmlElement(required = true)
protected String number;
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter3 .class)
@XmlSchemaType(name = "int")
protected Integer talkMode;
/**
* Gets the value of the ucAccount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUcAccount() {
return ucAccount;
}
/**
* Sets the value of the ucAccount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUcAccount(String value) {
this.ucAccount = value;
}
/**
* Gets the value of the confId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConfId() {
return confId;
}
/**
* Sets the value of the confId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConfId(String value) {
this.confId = value;
}
/**
* Gets the value of the number property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNumber() {
return number;
}
/**
* Sets the value of the number property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNumber(String value) {
this.number = value;
}
/**
* Gets the value of the talkMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public Integer getTalkMode() {
return talkMode;
}
/**
* Sets the value of the talkMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTalkMode(Integer value) {
this.talkMode = value;
}
}
|
apache-2.0
|
yong-at-git/CourseRecommenderParent
|
CourseRecommenderRuleMiner/src/main/java/se/uu/it/cs/recsys/ruleminer/util/HeaderTableUtil.java
|
2270
|
package se.uu.it.cs.recsys.ruleminer.util;
/*
* #%L
* CourseRecommenderRuleMiner
* %%
* Copyright (C) 2015 Yong Huang <[email protected] >
* %%
* 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.
* #L%
*/
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.uu.it.cs.recsys.ruleminer.datastructure.HeaderTableItem;
/**
*
* @author Yong Huang <[email protected]>
*/
public class HeaderTableUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HeaderTableUtil.class);
public static List<Integer> getOrderedItemId(List<HeaderTableItem> headerTable) {
return headerTable.stream()
.map(tableItem -> tableItem.getItem().getId())
.collect(Collectors.toList());
}
/**
*
* @param headerTable non-null header table
* @param id, non-null id of an item.
* @return the found table item or null if not found
* @throws IllegalArgumentException, if input is null;
*/
public static HeaderTableItem getTableItemByItemId(List<HeaderTableItem> headerTable, Integer id) {
if (headerTable == null || id == null) {
throw new IllegalArgumentException("item id can not be null!");
}
HeaderTableItem result = null;
for (HeaderTableItem item : headerTable) {
if (item.getItem().getId().equals(id)) {
result = item;
}
}
// if (result == null) {
// LOGGER.debug("No match item found for id: {} in table: {}", id,
// headerTable.stream().map(headItem -> headItem.getItem()).collect(Collectors.toList()));
// }
return result;
}
}
|
apache-2.0
|
verejnedigital/verejne.digital
|
obstaravania/utils.py
|
7620
|
# -*- coding: utf-8 -*-
from dateutil.parser import parse
import json
import os
import yaml
import db_old
# TODO: This function is currently only used by the db.py module,
# imported from serving.py via sys.path modification. Due to the new
# sys.path content, db.py attempts to find the `yaml_load` function in
# this file, instead of in its own "utils.py". When imports are done
# properly, delete this function from here.
def yaml_load(path):
with open(path, 'r', encoding='utf-8') as f:
data_yaml = yaml.load(f, Loader=yaml.FullLoader)
return data_yaml
def NormalizeIco(ico):
if ico is None:
return None
ico = ico.replace(" ", "")
try:
a = int(ico)
return a
except:
return None
def IcoToLatLngMap():
output_map = {}
for table in ["orsresd_data", "firmy_data", "new_orsr_data"]:
with db_old.getCursor() as cur:
sql = "SELECT ico, lat, lng FROM " + table + \
" JOIN entities on entities.id = " + table + ".id" + \
" WHERE ico IS NOT NULL"
db_old.execute(cur, sql)
for row in cur:
output_map[int(row["ico"])] = (row["lat"], row["lng"])
return output_map
# Returns the value of 'entities.column' for the entitity with 'table'.ico='ico'
def getColumnForTableIco(table, column, ico):
sql = "SELECT " + column + " FROM " + table + \
" JOIN entities ON entities.id = " + table + ".id" + \
" WHERE ico = %s" + \
" LIMIT 1"
with db_old.getCursor() as cur:
try:
cur = db_old.execute(cur, sql, [ico])
row = cur.fetchone()
if row is None:
return None
return row[column]
except:
return None
# TODO: refactor as this is also done in server
def getEidForIco(ico):
ico = NormalizeIco(ico)
for table in ["new_orsr_data", "firmy_data", "orsresd_data"]:
value = getColumnForTableIco(table, "eid", ico)
if value is not None:
return value
return None
def getAddressForIco(ico):
ico = NormalizeIco(ico)
for table in ["new_orsr_data", "firmy_data", "orsresd_data"]:
value = getColumnForTableIco(table, "address", ico)
if value is not None:
return value.decode("utf8")
return ""
# Returns estimated/final value
def getValue(obstaravanie):
if obstaravanie.final_price is not None:
return obstaravanie.final_price
if obstaravanie.draft_price is not None:
return obstaravanie.draft_price
return None
def obstaravanieToJson(obstaravanie, candidates, full_candidates=1, compute_range=False):
current = {}
current["id"] = obstaravanie.id
if obstaravanie.description is None:
current["text"] = "N/A"
else:
current["text"] = obstaravanie.description
if obstaravanie.title is not None:
current["title"] = obstaravanie.title
if obstaravanie.bulletin_year is not None:
current["bulletin_year"] = obstaravanie.bulletin_year
if obstaravanie.bulleting_number is not None:
current["bulletin_number"] = obstaravanie.bulleting_number
current["price"] = getValue(obstaravanie)
predictions = obstaravanie.predictions
if (predictions is not None) and (len(predictions) > 0):
prediction = predictions[0]
current["price_avg"] = prediction.mean
current["price_stdev"] = prediction.stdev
current["price_num"] = prediction.num
if obstaravanie.json is not None:
j = json.loads(obstaravanie.json)
if ("bulletin_issue" in j) and ("published_on" in j["bulletin_issue"]):
bdate = parse(j["bulletin_issue"]["published_on"])
current["bulletin_day"] = bdate.day
current["bulletin_month"] = bdate.month
current["bulletin_date"] = "%d. %s %d" % (bdate.day,
["január", "február", "marec", "apríl", "máj", "jún",
"júl", "august", "september", "október", "november",
"december"][bdate.month - 1], bdate.year)
current["customer"] = obstaravanie.customer.name
if candidates > 0:
# Generate at most one candidate in full, others empty, so we know the count
current["kandidati"] = [{
"id": c.reason.id,
"eid": getEidForIco(c.company.ico),
"name": c.company.name,
"ico": c.company.ico,
"text": c.reason.description,
"title": c.reason.title,
"customer": c.reason.customer.name,
"price": getValue(c.reason),
"score": c.score} for c in obstaravanie.candidates[:full_candidates]]
for _ in obstaravanie.candidates[full_candidates:candidates]:
current["kandidati"].append({})
return current
def getAddressJson(eid):
# json with all geocoded data
j = {}
with db_old.getCursor() as cur:
cur = db_old.execute(cur, "SELECT json FROM entities WHERE eid=%s", [eid])
row = cur.fetchone()
if row is None:
return None
j = json.loads(row["json"])
# TODO: do not duplicate this with code in verejne/
def getComponent(json, typeName):
try:
for component in json[0]["address_components"]:
if typeName in component["types"]:
return component["long_name"]
return ""
except:
return ""
# types description: https://developers.google.com/maps/documentation/geocoding/intro#Types
# street / city can be defined in multiple ways
address = {
"street": (
getComponent(j, "street_address") +
getComponent(j, "route") +
getComponent(j, "intersection") +
" " + getComponent(j, "street_number")
),
"city": getComponent(j, "locality"),
"zip": getComponent(j, "postal_code"),
"country": getComponent(j, "country"),
}
return address
# Generates report with notifications,
# saving pdf file to filename
def generateReport(notifications):
# Bail out if no notifications
if len(notifications) == 0:
return False
company = notifications[0].candidate.company
eid = getEidForIco(company.ico)
if eid is None:
return False
data = {}
data["company"] = {
"name": company.name,
"ico": company.ico,
"address_full": getAddressForIco(company.ico),
}
data["company"].update(getAddressJson(eid))
notifications_json = []
for notification in notifications:
notifications_json.append({
"reason": obstaravanieToJson(
notification.candidate.reason, candidates=0, full_candidates=0),
"what": obstaravanieToJson(
notification.candidate.obstaravanie, candidates=0, full_candidates=0),
})
data["notifications"] = notifications_json
# Generate .json file atomically into the following directory. It is picked up
# from there and automatically turned into .pdf and then send.
shared_path = "/data/notifikacie/in/"
tmp_filename = shared_path + ("json_%d_%d.tmp" % (eid, os.getpid()))
final_filename = shared_path + ("data_%d_%d.json" % (eid, os.getpid()))
with open(tmp_filename, "w") as tmp_file:
json.dump(data, tmp_file, sort_keys=True, indent=4, separators=(',', ': '))
os.rename(tmp_filename, final_filename)
return True
|
apache-2.0
|
weld/core
|
tests-arquillian/src/test/java/org/jboss/weld/tests/decorators/broken/FooDecorator.java
|
1152
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.weld.tests.decorators.broken;
import jakarta.decorator.Decorator;
import jakarta.decorator.Delegate;
import jakarta.enterprise.inject.Any;
import jakarta.inject.Inject;
@Decorator
public class FooDecorator extends Foo {
@Inject
@Any
@Delegate
private Foo delegate;
@Override
public void ping() {
delegate.ping();
}
}
|
apache-2.0
|
Chemaclass/invaders
|
src/main/Main.java
|
2315
|
package main;
import view.Tienda;
import view.Principal;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.UnsupportedLookAndFeelException;
/**
*
* @author Chema_class
*/
public class Main extends JFrame{
private Principal principal;
private Tienda tienda;
private Decorador decorador;
private Main(String s){
super(s);
setSize(new Dimension(1100, 600));
setMinimumSize(new Dimension(950, 550));
setExtendedState(JFrame.MAXIMIZED_BOTH);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponent();
setVisible(true);
}
private void initComponent(){
this.principal = new Principal(this);
this.tienda = new Tienda(this);
this.decorador = Decorador.getInstance(this);
getContentPane().add(decorador);
}
public Principal getPrincipal(){
return principal;
}
public Tienda getTienda(){
return tienda;
}
public Decorador getDecorador(){
return decorador;
}
private void begin(){
principal.setVisible(true);
decorador.begin();
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
//java.util.logging.Logger.getLogger(Opciones.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
new Main("ChemaInvaders").begin();
}
}
|
apache-2.0
|
dimone-kun/cuba
|
modules/web-toolkit/src/com/haulmont/cuba/web/widgets/client/addons/aceeditor/SuggestPopup.java
|
7560
|
/*
* Copyright 2017 Antti Nieminen
*
* 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.haulmont.cuba.web.widgets.client.addons.aceeditor;
import java.util.LinkedList;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ListBox;
import com.vaadin.client.ui.VOverlay;
public class SuggestPopup extends VOverlay implements KeyDownHandler,
DoubleClickHandler, ChangeHandler {
protected ListBox choiceList;
protected String startOfValue = "";
public interface SuggestionSelectedListener {
void suggestionSelected(TransportSuggestion s);
void noSuggestionSelected();
}
protected SuggestionSelectedListener listener;
protected VOverlay descriptionPopup;
protected List<TransportSuggestion> suggs;
protected List<TransportSuggestion> visibleSuggs = new LinkedList<TransportSuggestion>();
protected boolean showDescriptions = true;
protected Image loadingImage;
public static final int WIDTH = 150;
public static final int HEIGHT = 200;
public static final int DESCRIPTION_WIDTH = 225;
// TODO addSuggestionSelectedListener?
public void setSuggestionSelectedListener(SuggestionSelectedListener ssl) {
listener = ssl;
}
public SuggestPopup() {
super(true);
setWidth(WIDTH + "px");
SuggestionResources resources = GWT.create(SuggestionResources.class);
loadingImage = new Image(resources.loading());
setWidget(loadingImage);
}
protected void createChoiceList() {
choiceList = new ListBox();
choiceList.setStyleName("list");
choiceList.addKeyDownHandler(this);
choiceList.addDoubleClickHandler(this);
choiceList.addChangeHandler(this);
choiceList.setStylePrimaryName("aceeditor-suggestpopup-list");
setWidget(choiceList);
}
protected void startLoading() {
if (descriptionPopup!=null) {
descriptionPopup.hide();
}
setWidget(loadingImage);
}
public void setSuggestions(List<TransportSuggestion> suggs) {
this.suggs = suggs;
createChoiceList();
populateList();
if (choiceList.getItemCount() == 0) {
close();
}
}
protected void populateList() {
choiceList.clear();
visibleSuggs.clear();
int i = 0;
for (TransportSuggestion s : suggs) {
if (s.suggestionText.toLowerCase().startsWith(startOfValue)) {
visibleSuggs.add(s);
choiceList.addItem(s.displayText, "" + i);
}
i++;
}
if (choiceList.getItemCount() > 0) {
int vic = Math.max(2, Math.min(10, choiceList.getItemCount()));
choiceList.setVisibleItemCount(vic);
choiceList.setSelectedIndex(0);
this.onChange(null);
}
}
public void close() {
hide();
if (listener != null)
listener.noSuggestionSelected();
}
@Override
public void hide() {
super.hide();
if (descriptionPopup != null)
descriptionPopup.hide();
descriptionPopup = null;
}
@Override
public void hide(boolean ac) {
super.hide(ac);
if (ac) {
// This happens when user clicks outside this popup (or something
// similar) while autohide is on. We must cancel the suggestion.
if (listener != null)
listener.noSuggestionSelected();
}
if (descriptionPopup != null)
descriptionPopup.hide();
descriptionPopup = null;
}
@Override
public void onKeyDown(KeyDownEvent event) {
int keyCode = event.getNativeKeyCode();
if (keyCode == KeyCodes.KEY_ENTER
&& choiceList.getSelectedIndex() != -1) {
event.preventDefault();
event.stopPropagation();
select();
} else if (keyCode == KeyCodes.KEY_ESCAPE) {
event.preventDefault();
close();
}
}
@Override
public void onDoubleClick(DoubleClickEvent event) {
event.preventDefault();
event.stopPropagation();
select();
}
@Override
public void onBrowserEvent(Event event) {
if (event.getTypeInt() == Event.ONCONTEXTMENU) {
event.stopPropagation();
event.preventDefault();
return;
}
super.onBrowserEvent(event);
}
public void up() {
if (suggs==null) {
return;
}
int current = this.choiceList.getSelectedIndex();
int next = (current - 1 >= 0) ? current - 1 : 0;
this.choiceList.setSelectedIndex(next);
// Note that setting the selection programmatically does not cause the
// ChangeHandler.onChange(ChangeEvent) event to be fired.
// Doing it manually.
this.onChange(null);
}
public void down() {
if (suggs==null) {
return;
}
int current = this.choiceList.getSelectedIndex();
int next = (current + 1 < choiceList.getItemCount()) ? current + 1
: current;
this.choiceList.setSelectedIndex(next);
// Note that setting the selection programmatically does not cause the
// ChangeHandler.onChange(ChangeEvent) event to be fired.
// Doing it manually.
this.onChange(null);
}
public void select() {
if (suggs==null) {
return;
}
int selected = choiceList.getSelectedIndex();
if (listener != null) {
if (selected == -1) {
this.hide();
listener.noSuggestionSelected();
} else {
startLoading();
listener.suggestionSelected(visibleSuggs.get(selected));
}
}
}
@Override
public void onChange(ChangeEvent event) {
if (descriptionPopup == null) {
createDescriptionPopup();
}
int selected = choiceList.getSelectedIndex();
String descr = visibleSuggs.get(selected).descriptionText;
if (descr != null && !descr.isEmpty()) {
((HTML) descriptionPopup.getWidget()).setHTML(descr);
if (showDescriptions) {
descriptionPopup.show();
}
} else {
descriptionPopup.hide();
}
}
@Override
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (descriptionPopup!=null) {
updateDescriptionPopupPosition();
}
}
protected void updateDescriptionPopupPosition() {
int x = getAbsoluteLeft() + WIDTH;
int y = getAbsoluteTop();
descriptionPopup.setPopupPosition(x, y);
if (descriptionPopup!=null) {
descriptionPopup.setPopupPosition(x, y);
}
}
protected void createDescriptionPopup() {
descriptionPopup = new VOverlay();
descriptionPopup.setOwner(getOwner());
descriptionPopup.setStylePrimaryName("aceeditor-suggestpopup-description");
HTML lbl = new HTML();
lbl.setWordWrap(true);
descriptionPopup.setWidget(lbl);
updateDescriptionPopupPosition();
descriptionPopup.setWidth(DESCRIPTION_WIDTH+"px");
// descriptionPopup.setSize(DESCRIPTION_WIDTH+"px", HEIGHT+"px");
}
public void setStartOfValue(String startOfValue) {
this.startOfValue = startOfValue.toLowerCase();
if (suggs==null) {
return;
}
populateList();
if (choiceList.getItemCount() == 0) {
close();
}
}
}
|
apache-2.0
|
aceofall/zephyr-iotos
|
include/entropy.h
|
1479
|
/**
* @file entropy.h
*
* @brief Public APIs for the entropy driver.
*/
/*
* Copyright (c) 2016 ARM Ltd.
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef __ENTROPY_H__
#define __ENTROPY_H__
/**
* @brief Entropy Interface
* @defgroup entropy_interface Entropy Interface
* @ingroup io_interfaces
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <zephyr/types.h>
#include <device.h>
/**
* @typedef entropy_get_entropy_t
* @brief Callback API to get entropy.
*
* See entropy_get_entropy() for argument description
*/
typedef int (*entropy_get_entropy_t)(struct device *dev,
u8_t *buffer,
u16_t length);
struct entropy_driver_api {
entropy_get_entropy_t get_entropy;
};
/**
* @brief Fills a buffer with entropy.
*
* @param dev Pointer to the entropy device.
* @param buffer Buffer to fill with entropy.
* @param length Buffer length.
* @retval 0 on success.
* @retval -ERRNO errno code on error.
*/
__syscall int entropy_get_entropy(struct device *dev,
u8_t *buffer,
u16_t length);
static inline int _impl_entropy_get_entropy(struct device *dev,
u8_t *buffer,
u16_t length)
{
const struct entropy_driver_api *api = dev->driver_api;
__ASSERT(api->get_entropy, "Callback pointer should not be NULL");
return api->get_entropy(dev, buffer, length);
}
#ifdef __cplusplus
}
#endif
/**
* @}
*/
#include <syscalls/entropy.h>
#endif /* __ENTROPY_H__ */
|
apache-2.0
|
actframework/act-asm
|
src/main/java/act/asm/tree/IntInsnNode.java
|
3081
|
/**
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
* <p/>
* Redistribution and use in srccode and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of srccode 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. Neither the className of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* <p/>
* 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 act.asm.tree;
import act.asm.MethodVisitor;
import java.util.Map;
/**
* A node that represents an instruction with a single int operand.
*
* @author Eric Bruneton
*/
public class IntInsnNode extends AbstractInsnNode {
/**
* The operand of this instruction.
*/
public int operand;
/**
* Constructs a new {@link IntInsnNode}.
*
* @param opcode
* the opcode of the instruction to be constructed. This opcode
* must be BIPUSH, SIPUSH or NEWARRAY.
* @param operand
* the operand of the instruction to be constructed.
*/
public IntInsnNode(final int opcode, final int operand) {
super(opcode);
this.operand = operand;
}
/**
* Sets the opcode of this instruction.
*
* @param opcode
* the new instruction opcode. This opcode must be BIPUSH, SIPUSH
* or NEWARRAY.
*/
public void setOpcode(final int opcode) {
this.opcode = opcode;
}
@Override
public int getType() {
return INT_INSN;
}
@Override
public void accept(final MethodVisitor mv) {
mv.visitIntInsn(opcode, operand);
acceptAnnotations(mv);
}
@Override
public AbstractInsnNode clone(final Map<LabelNode, LabelNode> labels) {
return new IntInsnNode(opcode, operand).cloneAnnotations(this);
}
}
|
apache-2.0
|
MicroStrategy/RIntegrationPack
|
scripts/README.md
|
24829
|
## Off-the-shelf R scripts
These ready-to-use R scripts can easily be added to your R-enabled MicroStrategy environment. Simply save them to your desktop or Intelligence Server and reference them with a MicroStrategy metric.
#### Contents
| Forecasting | Classification | Descriptive |
| :----------------------------------- | :----------------------------------------- | :------------------------------- |
| [ARIMA][arima] | [k-Nearest Neighbors][knn] | [k-Means Clustering][kcluster] |
| [Seasonal Forecasting][seasforecast] | [Neural Network][nn] | [k-Medoids Clustering][kmedoids] |
| [Stepwise Regression][stepreg] | [Naive Bayes][nb] | [Pairwise Correlation][pairwise] |
| [Survival Analysis][survival] | [Random Forest][rf] | [Sentiment Analysis][sentiment] |
| | [Stepwise Logistic Regression][steplogreg] | |
## ARIMA
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_ARIMA.png" width="250">
A time-series method that uses the Auto-Regressive Integrated Moving Average (ARIMA) model for forecasting values. It leverages the “auto.arima” function from R’s “forecast” package to search through a variety of ARIMA configurations in order to find the best one. This script generates the forecast value and confidence intervals, nominally set at 80% and 95%.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Forecasted value | `RScript<_RScriptFile="ARIMA.R", _InputNames="Target", SortBy=(Month), _Params="CycleLength=12, Horizon=12, Conf1=80, Conf2=95, ImageName='', FileName=''">(Target)` |
| First value of the lower confidence band | `RScript<_RScriptFile="ARIMA.R", _InputNames="Target", _OutputVar="ForecastLo1", SortBy=(Month), _Params="CycleLength=12, Horizon=12, Conf1=80, Conf2=95, ImageName='', FileName=''">(Target)` |
| Second value of the lower confidence band | `RScript<_RScriptFile="ARIMA.R", _InputNames="Target", _OutputVar="ForecastLo2", SortBy=(Month), _Params="CycleLength=12, Horizon=12, Conf1=80, Conf2=95, ImageName='', FileName=''">(Target)`|
| First value of the upper confidence band | `RScript<_RScriptFile="ARIMA.R", _InputNames="Target", _OutputVar="ForecastHi1", SortBy=(Month), _Params="CycleLength=12, Horizon=12, Conf1=80, Conf2=95, ImageName='', FileName=''">(Target)`|
| Second value of the upper confidence band | `RScript<_RScriptFile="ARIMA.R", _InputNames="Target", _OutputVar="ForecastHi2", SortBy=(Month), _Params="CycleLength=12, Horizon=12, Conf1=80, Conf2=95, ImageName='', FileName=''">(Target)`|
* [RScript][arima_script]
* [Documentation][arima_doc]
* [Back to the top][lnk_top]
<br></br>
## k-Means Clustering
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_kMeans.PNG" width="250">
A clustering algorithm that separates observations into k-number of clusters, where each cluster is defined by its mean. The algorithm seeks to minimize the variance within each cluster; this is interpreted as observations belonging to the cluster with the "nearest mean".
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Cluster to which each record belongs | `RScript<_RScriptFile="kMeansClustering.R", _InputNames="Vars", _Params="Exact_k=4, Max_k=10, FileName='', Seed=42">(Vars)` |
* [RScript][kcluster_script]
* [Documentation][kcluster_doc]
* [Back to the top][lnk_top]
<br></br>
## k-Medoids Clustering
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_kMedoids.PNG" width="250">
A clustering algorithm that separates observations into k-number of clusters, where each cluster is defined by its medoid, a point within the cluster that is on average the least dissimilar to all the observations in the cluster. The algorithm seeks to minimize the absolute distance between the observations and the medoid of each cluster.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Cluster to which each record belongs | `RScript<_RScriptFile="kMedoidsClustering.R", _InputNames="Vars", _Params="Exact_k=4, Max_k=10, FileName='', Seed=42">(Vars)` |
| Cluster if a record is the medoid of that cluster, 0 otherwise | `RScript<_RScriptFile="kMedoidsClustering.R", _InputNames="Vars", _OutputVar="Medoids", _Params="Exact_k=4, Max_k=10, FileName='', Seed=42">(Vars)` |
* [RScript][kmedoids_script]
* [Documentation][kmedoids_doc]
* [Back to the top][lnk_top]
<br></br>
## k-Nearest Neighbors
A classification algorithm which assigns observations to a known classification group. Classifications for the test set are made by determining the k nearest observations in the training dataset, known as neighbors, and assigning the observation to a group based on the majority vote amongst those neighbors.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Predicted class as a string | `RScript<_RScriptFile="kNN.R", _InputNames="ID, Target, Training, Vars", _Params="TrainIncluded=TRUE, k=1, FileName='kNN', Seed=42">(ID, Target, Training, Vars)` |
| Predicted class as a number | `RScript<_RScriptFile="kNN.R", _InputNames="ID, Target, Training, Vars", _OutputVar="ClassId", _Params="TrainIncluded=TRUE, k=1, FileName='kNN', Seed=42">(ID, Target, Training, Vars)` |
* [RScript][knn_script]
* [Documentation][knn_doc]
* [Back to the top][lnk_top]
<br></br>
## Naive Bayes
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_NaiveBayes.PNG" width="250">
Naïve Bayes, also known as simple Bayes, is a classification technique that makes the assumption that the effect of the value of each variable feature is independent from all other features for each classification; this is known as naive independence. For each independent variable, the algorithm calculates the conditional likelihood of each potential classification given the value for each feature and multiplies the effects together to determine the probability that an observation belongs to each classification. The classification with the highest probability is returned as the predicted class.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Predicted class as a string | `RScript<_RScriptFile="NaiveBayes.R", _InputNames="Target, Vars", _Params="TrainMode=TRUE, FileName='NaiveBayes', Correction=1">(Target, Vars)` |
| Predicted class as a number | `RScript<_RScriptFile="NaiveBayes.R", _InputNames="Target, Vars", _OutputVar="ClassId", _Params="TrainMode=TRUE, FileName='NaiveBayes', Correction=1">(Target, Vars)` |
* [RScript][nb_script]
* [Documentation][nb_doc]
* [Back to the top][lnk_top]
<br></br>
## Neural Networks
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_NeuralNetwork.PNG" width="250">
Neural networks are an advanced machine learning technique inspired by the innerworkings of the human brain. A neural network consists of “neurons”, weights, and an activation function. Data is passed from each layer of the network to the output layer through a series of weights and transformations defined by the activation function.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Predicted class as a string | `RScript<_RScriptFile="NeuralNetwork.R", _InputNames="Target, Vars", _Params="FileName='NeuralNetwork', TrainMode=TRUE, NumLayer=3, Seed=42">(Target, Vars)` |
| Predicted class as a number | `RScript<_RScriptFile="NeuralNetwork.R", _InputNames="Target, Vars", _OutputVar="ClassId", _Params="FileName='NeuralNetwork', TrainMode=TRUE, NumLayer=3, Seed=42">(Target, Vars)` |
* [RScript][nn_script]
* [Documentation][nn_doc]
* [Back to the top][lnk_top]
<br></br>
## Pairwise Correlation
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_PairwiseCorr.PNG" width="250">
Pairwise correlation is a measure of the direction and strength of the relationship between pairs of metrics with respect to each other. This R script produces a correlation plot and a correlation table containing correlations of the variables when taken in pairs.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Correlation matrix plot | `RScript<_RScriptFile="PairwiseCorr.R", _InputNames="Labels, Vars", _Params="HasLabels=TRUE, WindowSize=0, ImageName='PairwiseCorr', FileName='PairwiseCorr'">(Labels, Vars)` |
* [RScript][pairwise_script]
* [Documentation][pairwise_doc]
* [Back to the top][lnk_top]
<br></br>
## Random Forest
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_RandomForest.PNG" width="250">
Random Forest is a machine learning technique wherein numerous, independent decision trees are trained on randomized subsets of the training data in order to reduce overfitting. Data is passed into each individual decision tree for classification, and the class that is predicted by the majority of those decision trees is returned as the predicted class for that record.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Predicted class as a string | `RScript<_RScriptFile="RandomForest.R", _InputNames="Target, Vars", _Params="TrainMode=TRUE, FileName='RandomForest', NumTree=750, NumVar=3, Seed=42">(Target, Vars)` |
| Predicted class as a number | `RScript<_RScriptFile="RandomForest.R", _InputNames="Target, Vars", _OutputVar="ClassId", _Params="TrainMode=TRUE, FileName='RandomForest', NumTree=750, NumVar=3, Seed=42">(Target, Vars)`|
* [RScript][rf_script]
* [Documentation][rf_doc]
* [Back to the top][lnk_top]
<br></br>
## Seasonal Forecasting
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_SeasonalForecast.PNG" width="250">
A time-series forecast method that uses R’s ordinary least squares regression algorithm to fit a function that captures the trend and seasonal variability of numerical data and can be used predict future values.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Forecasted value | `RScript<_RScriptFile="SeasonalForecasting.R", _InputNames="Target, Trend, Season", _Params="FileName=''">(Target, Trend, Season)` |
* [RScript][seasforecast_script]
* [Documentation][seasforecast_doc]
* [Back to the top][lnk_top]
<br></br>
## Sentiment Analysis
<img src="https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_SentimentAnalysis.png" width="250">
Sentiment analysis aims to measure the attitude of a writer’s words within a given text. It is an application of text mining and is used to extract sentiment from social media sources such as survey results, Twitter tweets, and Facebook comments. This metric uses R’s tidytext package to analyze text for sentiment by associating each word with classifications from two lexicons and returns the sentiment analyses as 14 different results, each can be represented by a MicroStrategy metric. In addition to these results which are returned “in-band” to MicroStrategy metrics in a report, dashboard or document, this metric optionally can persist output “out-of-band” to the file system, including a result table as a comma-separated-value file, a word cloud and a sentiment score histogram.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Sentiment Score (numeric, negative/positive) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)` |
| Sentiment Grade (string, negative/positive) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)` |
| Anger (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)` |
| Anger (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)` |
| Anticipation (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| Disgust (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| Fear (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| Joy (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| Negative (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| Positive (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| Sadness (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| Surprise (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| Trust (numeric, word count) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| WordCount (numeric, words with sentiment) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
| TotalWordCount (numeric, all words) | `RScript<_RScriptFile="SentimentAnalysis.R", _InputNames="Text", _OutputVar="Grade", _Params="FileName='SA_mstr', PlotWordCloud=TRUE, PlotHistogram=TRUE, RemoveRetweets=TRUE, SaveCSV=TRUE">(Text)`|
* [RScript][sentiment_script]
* [Documentation][sentiment_doc]
* [Back to the top][lnk_top]
<br></br>
## Stepwise Regression
A type of linear regression in which variables are only included in the model if they have a significant effect. Initially all variables are included and are eliminated one-by-one if a variable is statistically insignificant according to the specified significance criterion until the remaining model only includes variables which are deemed significant. This specification uses the Aikaike information criterion as the determination criterion.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Forecasted value | `RScript<_RScriptFile="StepwiseRegression.R", _InputNames="Target, Vars", _Params="FileName='StepwiseRegression', Stepwise=TRUE">(Target, Vars)` |
* [RScript][stepreg_script]
* [Documentation][stepreg_doc]
* [Back to the top][lnk_top]
<br></br>
## Stepwise Logistic Regression
A type of regression in which the variable being forecasted is categorical ie. a class. This script creates a logistic regression model in which variables are only included in the model if they have a significant effect. Initially all variables are included and are eliminated one-by-one if a variable is statistically insignificant according to the specified significance criterion until the remaining model only includes variables which are deemed significant. This specification uses the Aikaike information criterion as the determination criterion.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Probability of the target class | `RScript<_RScriptFile="StepwiseLogistic.R", _InputNames="Target, Vars", _Params="FileName='StepwiseLogistic', Stepwise=TRUE">(Target, Vars)` |
* [RScript][steplogreg_script]
* [Documentation][steplogreg_doc]
* [Back to the top][lnk_top]
<br></br>
## Survival Analysis
Survival Analysis can be used to predict the probability of an event occuring over time, such as a component failure or a customer being lost. This script uses the Cox Regression algorithm to quantify the effect of each independent variable on the likelihood that an event will occur at some point in the future.
| Output | MicroStrategy Metric Expression |
| :----- | :------------------------------ |
| Probability of an event occurring | `RScript<_RScriptFile="Survival.R", _InputNames="Time, Status, Vars", _Params="TrainMode=FALSE, FileName='Survival'">(Time, Status, Vars)`|
* [RScript][survival_script]
* [Documentation][survival_doc]
* [Back to the top][lnk_top]
<br></br>
## How to use these scripts in a MicroStrategy dashboard
These R metrics are deployed to MicroStrategy as metrics by copying the metric expressions provided here into any MicroStrategy Metric Editor. The shelf includes metric expressions for Version 1 of the R Integration Pack as well as variations that take advantage of the new features in Version 2.
Version 2 of the R Integration Pack makes it even simpler for end-users to control the metric's execution thanks to the _Params parameter that allows function parameters to be referenced by name using a string of name-value pairs. This is in addition to the original set of 27 pre-defined parameters (9 boolean, 9 numeric and 9 string).
After you've copied the metric expression for the metric you wish to deploy:
1. Paste the Metric Expression into any MicroStrategy metric editor
2. Match metric's inputs and function parameters for your application
3. Name and save the metric so it can be added to any MicroStrategy report or dashboard
## Disclaimers
This page provides programming examples. MicroStrategy grants you a nonexclusive copyright license to use all programming code examples from which you can use or generate similar function tailored to your own specific needs. All sample code is provided for illustrative purposes only. These examples have not been thoroughly tested under all conditions. MicroStrategy, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.
[lnk_top]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#off-the-shelf-r-scripts>
[arima]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#arima>
[arima_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/ARIMA.R>
[arima_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/ARIMA.pdf>
[arima_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_ARIMA.png
[kcluster]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#k-means-clustering>
[kcluster_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/kMeansClustering.R>
[kcluster_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/kMeansClustering.pdf>
[kcluster_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_kMeans.PNG
[kmedoids]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#k-medoids-clustering>
[kmedoids_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/kMedoidsClustering.R>
[kmedoids_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/kMedoidsClustering.pdf>
[kmedoids_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_kMedoids.PNG
[knn]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#k-nearest-neighbors>
[knn_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/kNN.R>
[knn_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/kNN.pdf>
[nb]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#naive-bayes>
[nb_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/NaiveBayes.R>
[nb_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/NaiveBayes.pdf>
[nb_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_NaiveBayes.PNG
[nn]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#neural-network>
[nn_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/NeuralNetwork.R>
[nn_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/NeuralNetwork.pdf>
[nn_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_NeuralNetwork.PNG
[pairwise]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#pairwise-correlation>
[pairwise_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/PairwiseCorr.R>
[pairwise_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/PairwiseCorr.pdf>
[pairwise_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_PairwiseCorr.PNG
[rf]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#random-forest>
[rf_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/RandomForest.R>
[rf_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/RandomForest.pdf>
[rf_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_RandomForest.PNG
[seasforecast]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#seasonal-forecasting>
[seasforecast_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/SeasonalForecasting.R>
[seasforecast_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/SeasonalForecasting.pdf>
[seasforecast_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_SeasonalForecast.PNG
[stepreg]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#stepwise-regression>
[stepreg_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/StepwiseRegression.R>
[stepreg_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/StepwiseRegression.pdf>
[steplogreg]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#stepwise-logistic-regression>
[steplogreg_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/StepwiseLogistic.R>
[steplogreg_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/StepwiseLogistic.pdf>
[survival]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#survival-analysis>
[survival_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/Survival.R>
[survival_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/Survival.pdf>
[survival_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_Survival.PNG
[sentiment]: <https://github.com/MicroStrategy/RIntegrationPack/tree/master/scripts#sentiment-analysis>
[sentiment_script]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/SentimentAnalysis.R>
[sentiment_doc]: <https://github.com/MicroStrategy/RIntegrationPack/blob/master/scripts/SentimentAnalysis.pdf>
[sentiment_img]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_SentimentAnalysis.png
[img_howtouse]: https://github.com/MicroStrategy/RIntegrationPack/blob/master/assets/RShelf_Params3.png
|
apache-2.0
|
sonatype/maven-demo
|
maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleExecutionPlanCalculator.java
|
2629
|
package org.apache.maven.lifecycle.internal;
/*
* 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.
*/
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.LifecycleNotFoundException;
import org.apache.maven.lifecycle.LifecyclePhaseNotFoundException;
import org.apache.maven.lifecycle.MavenExecutionPlan;
import org.apache.maven.plugin.InvalidPluginDescriptorException;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoNotFoundException;
import org.apache.maven.plugin.PluginDescriptorParsingException;
import org.apache.maven.plugin.PluginNotFoundException;
import org.apache.maven.plugin.PluginResolutionException;
import org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException;
import org.apache.maven.plugin.version.PluginVersionResolutionException;
import org.apache.maven.project.MavenProject;
import java.util.List;
/**
* @since 3.0
* @author Benjamin Bentmann
* @author Kristian Rosenvold (extract interface only)
* <p/>
*/
public interface LifecycleExecutionPlanCalculator
{
MavenExecutionPlan calculateExecutionPlan( MavenSession session, MavenProject project, List<Object> tasks )
throws PluginNotFoundException, PluginResolutionException, LifecyclePhaseNotFoundException,
PluginDescriptorParsingException, MojoNotFoundException, InvalidPluginDescriptorException,
NoPluginFoundForPrefixException, LifecycleNotFoundException, PluginVersionResolutionException;
void calculateForkedExecutions( MojoExecution mojoExecution, MavenSession session )
throws MojoNotFoundException, PluginNotFoundException, PluginResolutionException,
PluginDescriptorParsingException, NoPluginFoundForPrefixException, InvalidPluginDescriptorException,
LifecyclePhaseNotFoundException, LifecycleNotFoundException, PluginVersionResolutionException;
}
|
apache-2.0
|
zhanqu/yii2adm
|
app/themes/upbond/ThemeAsset.php
|
482
|
<?php
/**
* 主题 upbond
*/
namespace app\themes\upbond;
use yii\web\AssetBundle;
/**
* @author zhanqu.im
*/
class ThemeAsset extends AssetBundle
{
const name = 'upbond';
const themeId = 'upbond';
public $sourcePath = '@app/themes/'.self::themeId.'/assets';
public $css = [
];
public $js = [
];
public $jsOptions = ['position' => \yii\web\View::POS_END];
public $depends = [
'app\themes\upbond\AdminltePluginsAsset'
];
}
|
apache-2.0
|
stweil/tesseract-ocr.github.io
|
4.0.0-beta.1/a01205.html
|
5026
|
<!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"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>tesseract: /home/stweil/src/github/tesseract-ocr/tesseract/textord/ccnontextdetect.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</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: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">tesseract
 <span id="projectnumber">4.00.00dev</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></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('a01205.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)">
</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="summary">
<a href="#nested-classes">Classes</a> |
<a href="#namespaces">Namespaces</a> </div>
<div class="headertitle">
<div class="title">ccnontextdetect.h File Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><code>#include "<a class="el" href="a01199_source.html">blobgrid.h</a>"</code><br />
<code>#include "<a class="el" href="a01604_source.html">scrollview.h</a>"</code><br />
</div>
<p><a href="a01205_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="a04702.html">tesseract::CCNonTextDetect</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a>
Namespaces</h2></td></tr>
<tr class="memitem:a01744"><td class="memItemLeft" align="right" valign="top">  </td><td class="memItemRight" valign="bottom"><a class="el" href="a01744.html">tesseract</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_9755ee342a92885af0731133719bff63.html">textord</a></li><li class="navelem"><a class="el" href="a01205.html">ccnontextdetect.h</a></li>
<li class="footer">Generated on Wed Mar 28 2018 19:53:41 for tesseract by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
|
apache-2.0
|
CMPUT301W15T10/301-Project
|
doc/com/cmput301/cs/project/serialization/LocalSaver.html
|
14118
|
<!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.6.0_34) on Tue Apr 07 14:51:42 MDT 2015 -->
<title>LocalSaver</title>
<meta name="date" content="2015-04-07">
<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="LocalSaver";
}
//-->
</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/LocalSaver.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-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 CLASS</li>
<li><a href="../../../../../com/cmput301/cs/project/serialization/RemoteSaver.html" title="class in com.cmput301.cs.project.serialization"><span class="strong">NEXT CLASS</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/cmput301/cs/project/serialization/LocalSaver.html" target="_top">FRAMES</a></li>
<li><a href="LocalSaver.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><a href="#constructor_summary">CONSTR</a> | </li>
<li><a href="#method_summary">METHOD</a></li>
</ul>
<ul class="subNavList">
<li>DETAIL: </li>
<li>FIELD | </li>
<li><a href="#constructor_detail">CONSTR</a> | </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">
<p class="subTitle">com.cmput301.cs.project.serialization</p>
<h2 title="Class LocalSaver" class="title">Class LocalSaver</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.cmput301.cs.project.serialization.LocalSaver</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public abstract class <strong>LocalSaver</strong>
extends java.lang.Object</pre>
<div class="block">This class is used to save claims via saveAllClaims()
<p>
It can be used by calling <a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#ofAndroid(Context)"><code>ofAndroid(Context)</code></a></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#LocalSaver()">LocalSaver</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== 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>static com.google.gson.Gson</code></td>
<td class="colLast"><code><strong><a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#getGson()">getGson</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html" title="class in com.cmput301.cs.project.serialization">LocalSaver</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#ofAndroid(Context)">ofAndroid</a></strong>(Context context)</code>
<div class="block">Obtains the singleton of <code>LocalClaimSaver</code>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../../com/cmput301/cs/project/models/Claim.html" title="class in com.cmput301.cs.project.models">Claim</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#readAllClaims()">readAllClaims</a></strong>()</code>
<div class="block">Reads all the <a href="../../../../../com/cmput301/cs/project/models/Claim.html" title="class in com.cmput301.cs.project.models"><code>Claims</code></a> in the file <a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#CLAIMS_FILE_NAME"><code>CLAIMS_FILE_NAME</code></a>, in the same order in the file.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../../com/cmput301/cs/project/models/Tag.html" title="class in com.cmput301.cs.project.models">Tag</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#readAllTags()">readAllTags</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#saveAllClaims(java.lang.Iterable)">saveAllClaims</a></strong>(java.lang.Iterable<<a href="../../../../../com/cmput301/cs/project/models/Claim.html" title="class in com.cmput301.cs.project.models">Claim</a>> claims)</code>
<div class="block">Saves all the claims to the file <a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#CLAIMS_FILE_NAME"><code>CLAIMS_FILE_NAME</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#saveAllTags(java.lang.Iterable)">saveAllTags</a></strong>(java.lang.Iterable<<a href="../../../../../com/cmput301/cs/project/models/Tag.html" title="class in com.cmput301.cs.project.models">Tag</a>> tags)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="LocalSaver()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>LocalSaver</h4>
<pre>public LocalSaver()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="ofAndroid(Context)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ofAndroid</h4>
<pre>public static <a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html" title="class in com.cmput301.cs.project.serialization">LocalSaver</a> ofAndroid(Context context)</pre>
<div class="block">Obtains the singleton of <code>LocalClaimSaver</code>.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>context</code> - a non-null instance of <code>Context</code></dd>
<dt><span class="strong">Returns:</span></dt><dd>a non-null instance of <code>LocalClaimSaver</code></dd></dl>
</li>
</ul>
<a name="getGson()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getGson</h4>
<pre>public static com.google.gson.Gson getGson()</pre>
<dl><dt><span class="strong">Returns:</span></dt><dd>the <code>Gson</code> instance that <code>ClaimSaves</code> uses</dd></dl>
</li>
</ul>
<a name="saveAllClaims(java.lang.Iterable)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>saveAllClaims</h4>
<pre>public boolean saveAllClaims(java.lang.Iterable<<a href="../../../../../com/cmput301/cs/project/models/Claim.html" title="class in com.cmput301.cs.project.models">Claim</a>> claims)</pre>
<div class="block">Saves all the claims to the file <a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#CLAIMS_FILE_NAME"><code>CLAIMS_FILE_NAME</code></a>. Overwrites the previous contents in the file.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>claims</code> - non-null instance of an <code>Iterable</code></dd>
<dt><span class="strong">Returns:</span></dt><dd>if the operation is successful</dd></dl>
</li>
</ul>
<a name="readAllClaims()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>readAllClaims</h4>
<pre>public java.util.List<<a href="../../../../../com/cmput301/cs/project/models/Claim.html" title="class in com.cmput301.cs.project.models">Claim</a>> readAllClaims()</pre>
<div class="block">Reads all the <a href="../../../../../com/cmput301/cs/project/models/Claim.html" title="class in com.cmput301.cs.project.models"><code>Claims</code></a> in the file <a href="../../../../../com/cmput301/cs/project/serialization/LocalSaver.html#CLAIMS_FILE_NAME"><code>CLAIMS_FILE_NAME</code></a>, in the same order in the file. The returned list is safe to be modified.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>a list of <code>Claims</code> in the file; otherwise, an empty list if the file does not exist; never null</dd></dl>
</li>
</ul>
<a name="saveAllTags(java.lang.Iterable)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>saveAllTags</h4>
<pre>public boolean saveAllTags(java.lang.Iterable<<a href="../../../../../com/cmput301/cs/project/models/Tag.html" title="class in com.cmput301.cs.project.models">Tag</a>> tags)</pre>
</li>
</ul>
<a name="readAllTags()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>readAllTags</h4>
<pre>public java.util.List<<a href="../../../../../com/cmput301/cs/project/models/Tag.html" title="class in com.cmput301.cs.project.models">Tag</a>> readAllTags()</pre>
</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/LocalSaver.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-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 CLASS</li>
<li><a href="../../../../../com/cmput301/cs/project/serialization/RemoteSaver.html" title="class in com.cmput301.cs.project.serialization"><span class="strong">NEXT CLASS</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/cmput301/cs/project/serialization/LocalSaver.html" target="_top">FRAMES</a></li>
<li><a href="LocalSaver.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><a href="#constructor_summary">CONSTR</a> | </li>
<li><a href="#method_summary">METHOD</a></li>
</ul>
<ul class="subNavList">
<li>DETAIL: </li>
<li>FIELD | </li>
<li><a href="#constructor_detail">CONSTR</a> | </li>
<li><a href="#method_detail">METHOD</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/ApplicationSettingsResource.java
|
20385
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.pinpoint.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Provides information about an application, including the default settings for an application.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/ApplicationSettingsResource"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ApplicationSettingsResource implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon
* Pinpoint console.
* </p>
*/
private String applicationId;
/**
* <p>
* The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the application.
* You can use this hook to customize segments that are used by campaigns in the application.
* </p>
*/
private CampaignHook campaignHook;
/**
* <p>
* The date and time, in ISO 8601 format, when the application's settings were last modified.
* </p>
*/
private String lastModifiedDate;
/**
* <p>
* The default sending limits for campaigns in the application.
* </p>
*/
private CampaignLimits limits;
/**
* <p>
* The default quiet time for campaigns in the application. Quiet time is a specific time range when messages aren't
* sent to endpoints, if all the following conditions are met:
* </p>
* <ul>
* <li>
* <p>
* The EndpointDemographic.Timezone property of the endpoint is set to a valid value.
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is later than or equal to the time specified by the QuietTime.Start
* property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is earlier than or equal to the time specified by the QuietTime.End
* property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* </ul>
* <p>
* If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or journey, even
* if quiet time is enabled.
* </p>
*/
private QuietTime quietTime;
/**
* <p>
* The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon
* Pinpoint console.
* </p>
*
* @param applicationId
* The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the
* Amazon Pinpoint console.
*/
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
/**
* <p>
* The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon
* Pinpoint console.
* </p>
*
* @return The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the
* Amazon Pinpoint console.
*/
public String getApplicationId() {
return this.applicationId;
}
/**
* <p>
* The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon
* Pinpoint console.
* </p>
*
* @param applicationId
* The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the
* Amazon Pinpoint console.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ApplicationSettingsResource withApplicationId(String applicationId) {
setApplicationId(applicationId);
return this;
}
/**
* <p>
* The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the application.
* You can use this hook to customize segments that are used by campaigns in the application.
* </p>
*
* @param campaignHook
* The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the
* application. You can use this hook to customize segments that are used by campaigns in the application.
*/
public void setCampaignHook(CampaignHook campaignHook) {
this.campaignHook = campaignHook;
}
/**
* <p>
* The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the application.
* You can use this hook to customize segments that are used by campaigns in the application.
* </p>
*
* @return The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the
* application. You can use this hook to customize segments that are used by campaigns in the application.
*/
public CampaignHook getCampaignHook() {
return this.campaignHook;
}
/**
* <p>
* The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the application.
* You can use this hook to customize segments that are used by campaigns in the application.
* </p>
*
* @param campaignHook
* The settings for the AWS Lambda function to invoke by default as a code hook for campaigns in the
* application. You can use this hook to customize segments that are used by campaigns in the application.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ApplicationSettingsResource withCampaignHook(CampaignHook campaignHook) {
setCampaignHook(campaignHook);
return this;
}
/**
* <p>
* The date and time, in ISO 8601 format, when the application's settings were last modified.
* </p>
*
* @param lastModifiedDate
* The date and time, in ISO 8601 format, when the application's settings were last modified.
*/
public void setLastModifiedDate(String lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
/**
* <p>
* The date and time, in ISO 8601 format, when the application's settings were last modified.
* </p>
*
* @return The date and time, in ISO 8601 format, when the application's settings were last modified.
*/
public String getLastModifiedDate() {
return this.lastModifiedDate;
}
/**
* <p>
* The date and time, in ISO 8601 format, when the application's settings were last modified.
* </p>
*
* @param lastModifiedDate
* The date and time, in ISO 8601 format, when the application's settings were last modified.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ApplicationSettingsResource withLastModifiedDate(String lastModifiedDate) {
setLastModifiedDate(lastModifiedDate);
return this;
}
/**
* <p>
* The default sending limits for campaigns in the application.
* </p>
*
* @param limits
* The default sending limits for campaigns in the application.
*/
public void setLimits(CampaignLimits limits) {
this.limits = limits;
}
/**
* <p>
* The default sending limits for campaigns in the application.
* </p>
*
* @return The default sending limits for campaigns in the application.
*/
public CampaignLimits getLimits() {
return this.limits;
}
/**
* <p>
* The default sending limits for campaigns in the application.
* </p>
*
* @param limits
* The default sending limits for campaigns in the application.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ApplicationSettingsResource withLimits(CampaignLimits limits) {
setLimits(limits);
return this;
}
/**
* <p>
* The default quiet time for campaigns in the application. Quiet time is a specific time range when messages aren't
* sent to endpoints, if all the following conditions are met:
* </p>
* <ul>
* <li>
* <p>
* The EndpointDemographic.Timezone property of the endpoint is set to a valid value.
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is later than or equal to the time specified by the QuietTime.Start
* property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is earlier than or equal to the time specified by the QuietTime.End
* property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* </ul>
* <p>
* If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or journey, even
* if quiet time is enabled.
* </p>
*
* @param quietTime
* The default quiet time for campaigns in the application. Quiet time is a specific time range when messages
* aren't sent to endpoints, if all the following conditions are met:</p>
* <ul>
* <li>
* <p>
* The EndpointDemographic.Timezone property of the endpoint is set to a valid value.
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is later than or equal to the time specified by the
* QuietTime.Start property for the application (or a campaign or journey that has custom quiet time
* settings).
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is earlier than or equal to the time specified by the
* QuietTime.End property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* </ul>
* <p>
* If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or
* journey, even if quiet time is enabled.
*/
public void setQuietTime(QuietTime quietTime) {
this.quietTime = quietTime;
}
/**
* <p>
* The default quiet time for campaigns in the application. Quiet time is a specific time range when messages aren't
* sent to endpoints, if all the following conditions are met:
* </p>
* <ul>
* <li>
* <p>
* The EndpointDemographic.Timezone property of the endpoint is set to a valid value.
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is later than or equal to the time specified by the QuietTime.Start
* property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is earlier than or equal to the time specified by the QuietTime.End
* property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* </ul>
* <p>
* If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or journey, even
* if quiet time is enabled.
* </p>
*
* @return The default quiet time for campaigns in the application. Quiet time is a specific time range when
* messages aren't sent to endpoints, if all the following conditions are met:</p>
* <ul>
* <li>
* <p>
* The EndpointDemographic.Timezone property of the endpoint is set to a valid value.
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is later than or equal to the time specified by the
* QuietTime.Start property for the application (or a campaign or journey that has custom quiet time
* settings).
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is earlier than or equal to the time specified by the
* QuietTime.End property for the application (or a campaign or journey that has custom quiet time
* settings).
* </p>
* </li>
* </ul>
* <p>
* If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or
* journey, even if quiet time is enabled.
*/
public QuietTime getQuietTime() {
return this.quietTime;
}
/**
* <p>
* The default quiet time for campaigns in the application. Quiet time is a specific time range when messages aren't
* sent to endpoints, if all the following conditions are met:
* </p>
* <ul>
* <li>
* <p>
* The EndpointDemographic.Timezone property of the endpoint is set to a valid value.
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is later than or equal to the time specified by the QuietTime.Start
* property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is earlier than or equal to the time specified by the QuietTime.End
* property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* </ul>
* <p>
* If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or journey, even
* if quiet time is enabled.
* </p>
*
* @param quietTime
* The default quiet time for campaigns in the application. Quiet time is a specific time range when messages
* aren't sent to endpoints, if all the following conditions are met:</p>
* <ul>
* <li>
* <p>
* The EndpointDemographic.Timezone property of the endpoint is set to a valid value.
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is later than or equal to the time specified by the
* QuietTime.Start property for the application (or a campaign or journey that has custom quiet time
* settings).
* </p>
* </li>
* <li>
* <p>
* The current time in the endpoint's time zone is earlier than or equal to the time specified by the
* QuietTime.End property for the application (or a campaign or journey that has custom quiet time settings).
* </p>
* </li>
* </ul>
* <p>
* If any of the preceding conditions isn't met, the endpoint will receive messages from a campaign or
* journey, even if quiet time is enabled.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ApplicationSettingsResource withQuietTime(QuietTime quietTime) {
setQuietTime(quietTime);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getApplicationId() != null)
sb.append("ApplicationId: ").append(getApplicationId()).append(",");
if (getCampaignHook() != null)
sb.append("CampaignHook: ").append(getCampaignHook()).append(",");
if (getLastModifiedDate() != null)
sb.append("LastModifiedDate: ").append(getLastModifiedDate()).append(",");
if (getLimits() != null)
sb.append("Limits: ").append(getLimits()).append(",");
if (getQuietTime() != null)
sb.append("QuietTime: ").append(getQuietTime());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ApplicationSettingsResource == false)
return false;
ApplicationSettingsResource other = (ApplicationSettingsResource) obj;
if (other.getApplicationId() == null ^ this.getApplicationId() == null)
return false;
if (other.getApplicationId() != null && other.getApplicationId().equals(this.getApplicationId()) == false)
return false;
if (other.getCampaignHook() == null ^ this.getCampaignHook() == null)
return false;
if (other.getCampaignHook() != null && other.getCampaignHook().equals(this.getCampaignHook()) == false)
return false;
if (other.getLastModifiedDate() == null ^ this.getLastModifiedDate() == null)
return false;
if (other.getLastModifiedDate() != null && other.getLastModifiedDate().equals(this.getLastModifiedDate()) == false)
return false;
if (other.getLimits() == null ^ this.getLimits() == null)
return false;
if (other.getLimits() != null && other.getLimits().equals(this.getLimits()) == false)
return false;
if (other.getQuietTime() == null ^ this.getQuietTime() == null)
return false;
if (other.getQuietTime() != null && other.getQuietTime().equals(this.getQuietTime()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getApplicationId() == null) ? 0 : getApplicationId().hashCode());
hashCode = prime * hashCode + ((getCampaignHook() == null) ? 0 : getCampaignHook().hashCode());
hashCode = prime * hashCode + ((getLastModifiedDate() == null) ? 0 : getLastModifiedDate().hashCode());
hashCode = prime * hashCode + ((getLimits() == null) ? 0 : getLimits().hashCode());
hashCode = prime * hashCode + ((getQuietTime() == null) ? 0 : getQuietTime().hashCode());
return hashCode;
}
@Override
public ApplicationSettingsResource clone() {
try {
return (ApplicationSettingsResource) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.pinpoint.model.transform.ApplicationSettingsResourceMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
apache-2.0
|
dipanjanS/text-analytics-with-python
|
Old-First-Edition/Ch07_Semantic_and_Sentiment_Analysis/utils.py
|
3381
|
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 11 23:06:06 2016
@author: DIP
"""
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
def build_feature_matrix(documents, feature_type='frequency',
ngram_range=(1, 1), min_df=0.0, max_df=1.0):
feature_type = feature_type.lower().strip()
if feature_type == 'binary':
vectorizer = CountVectorizer(binary=True, min_df=min_df,
max_df=max_df, ngram_range=ngram_range)
elif feature_type == 'frequency':
vectorizer = CountVectorizer(binary=False, min_df=min_df,
max_df=max_df, ngram_range=ngram_range)
elif feature_type == 'tfidf':
vectorizer = TfidfVectorizer(min_df=min_df, max_df=max_df,
ngram_range=ngram_range)
else:
raise Exception("Wrong feature type entered. Possible values: 'binary', 'frequency', 'tfidf'")
feature_matrix = vectorizer.fit_transform(documents).astype(float)
return vectorizer, feature_matrix
from sklearn import metrics
import numpy as np
import pandas as pd
def display_evaluation_metrics(true_labels, predicted_labels, positive_class=1):
print 'Accuracy:', np.round(
metrics.accuracy_score(true_labels,
predicted_labels),
2)
print 'Precision:', np.round(
metrics.precision_score(true_labels,
predicted_labels,
pos_label=positive_class,
average='binary'),
2)
print 'Recall:', np.round(
metrics.recall_score(true_labels,
predicted_labels,
pos_label=positive_class,
average='binary'),
2)
print 'F1 Score:', np.round(
metrics.f1_score(true_labels,
predicted_labels,
pos_label=positive_class,
average='binary'),
2)
def display_confusion_matrix(true_labels, predicted_labels, classes=[1,0]):
cm = metrics.confusion_matrix(y_true=true_labels,
y_pred=predicted_labels,
labels=classes)
cm_frame = pd.DataFrame(data=cm,
columns=pd.MultiIndex(levels=[['Predicted:'], classes],
labels=[[0,0],[0,1]]),
index=pd.MultiIndex(levels=[['Actual:'], classes],
labels=[[0,0],[0,1]]))
print cm_frame
def display_classification_report(true_labels, predicted_labels, classes=[1,0]):
report = metrics.classification_report(y_true=true_labels,
y_pred=predicted_labels,
labels=classes)
print report
|
apache-2.0
|
pubudu538/carbon-apimgt
|
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/AuthenticationContext.java
|
5431
|
/*
* Copyright WSO2 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 org.wso2.carbon.apimgt.gateway.handlers.security;
import org.wso2.carbon.apimgt.gateway.MethodStats;
import java.util.List;
/**
* Contains some context information related to an authenticated request. This can be used
* to access API keys and tier information related to already authenticated requests.
*/
public class AuthenticationContext {
private boolean authenticated;
private String username;
private String applicationTier;
private String tier;
private String apiTier;
private boolean isContentAwareTierPresent;
private String apiKey;
private String keyType;
private String callerToken;
private String applicationId;
private String applicationName;
private String consumerKey;
private String subscriber;
private List<String> throttlingDataList;
private int spikeArrestLimit;
private String subscriberTenantDomain;
private String spikeArrestUnit;
private boolean stopOnQuotaReach;
private String productName;
private String productProvider;
public List<String> getThrottlingDataList() {
return throttlingDataList;
}
public void setThrottlingDataList(List<String> throttlingDataList) {
this.throttlingDataList = throttlingDataList;
}
//Following throttle data list can be use to hold throttle data and api level throttle key
//should be its first element.
public boolean isContentAwareTierPresent() {
return isContentAwareTierPresent;
}
public void setIsContentAware(boolean isContentAware) {
this.isContentAwareTierPresent = isContentAware;
}
public String getApiTier() {
return apiTier;
}
public void setApiTier(String apiTier) {
this.apiTier = apiTier;
}
public String getSubscriber() {
return subscriber;
}
public void setSubscriber(String subscriber) {
this.subscriber = subscriber;
}
public boolean isAuthenticated() {
return authenticated;
}
public String getUsername() {
return username;
}
public String getTier() {
return tier;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public void setAuthenticated(boolean authenticated) {
this.authenticated = authenticated;
}
public void setUsername(String username) {
this.username = username;
}
public void setTier(String tier) {
this.tier = tier;
}
public String getKeyType() {
return keyType;
}
public void setKeyType(String keyType) {
this.keyType = keyType;
}
@MethodStats
public String getCallerToken() {
return callerToken;
}
public void setCallerToken(String callerToken) {
this.callerToken = callerToken;
}
public String getApplicationTier() {
return applicationTier;
}
public void setApplicationTier(String applicationTier) {
this.applicationTier = applicationTier;
}
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getConsumerKey() {
return consumerKey;
}
public void setConsumerKey(String consumerKey) {
this.consumerKey = consumerKey;
}
public int getSpikeArrestLimit() {
return spikeArrestLimit;
}
public void setSpikeArrestLimit(int spikeArrestLimit) {
this.spikeArrestLimit = spikeArrestLimit;
}
public String getSubscriberTenantDomain() {
return subscriberTenantDomain;
}
public void setSubscriberTenantDomain(String subscriberTenantDomain) {
this.subscriberTenantDomain = subscriberTenantDomain;
}
public String getSpikeArrestUnit() {
return spikeArrestUnit;
}
public void setSpikeArrestUnit(String spikeArrestUnit) {
this.spikeArrestUnit = spikeArrestUnit;
}
public boolean isStopOnQuotaReach() {
return stopOnQuotaReach;
}
public void setStopOnQuotaReach(boolean stopOnQuotaReach) {
this.stopOnQuotaReach = stopOnQuotaReach;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductName() {
return productName;
}
public void setProductProvider(String productProvider) {
this.productProvider = productProvider;
}
public String getProductProvider() {
return productProvider;
}
}
|
apache-2.0
|
tyrone-sudeium/project-euler
|
ruby/0016.rb
|
174
|
# 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#
# What is the sum of the digits of the number 2^1000?
puts (2**1000).to_s.chars.map(&:to_i).reduce(:+)
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Gentianaceae/Gentianopsis/Gentianopsis virgata/ Syn. Gentianella crinita macounii/README.md
|
218
|
# Gentianella crinita subsp. macounii (T. Holm) J.M. Gillett SUBSPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Myrcia/Myrcia bolivarensis/README.md
|
196
|
# Myrcia bolivarensis (Steyerm.) McVaugh SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Marchantiophyta/Jungermanniopsida/Jungermanniales/Cephaloziaceae/Cephalozia/Cephalozia pleniceps/Cephalozia pleniceps pleniceps/README.md
|
193
|
# Cephalozia pleniceps var. pleniceps VARIETY
#### Status
ACCEPTED
#### According to
Integrated Taxonomic Information System
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Protozoa/Granuloreticulosea/Foraminiferida/Chernyshinellidae/README.md
|
182
|
# Chernyshinellidae FAMILY
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Amaryllidaceae/Allium/Allium ericetorum/ Syn. Allium ochroleucum ericetorum/README.md
|
191
|
# Allium ochroleucum var. ericetorum VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Ramalinaceae/Bacidia/Bacidia myriocarpella/Bacidia myriocarpella myriocarpella/README.md
|
209
|
# Bacidia myriocarpella var. myriocarpella VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Bacidia myriocarpella var. myriocarpella
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Pentagonocarpus/README.md
|
182
|
# Pentagonocarpus P.Micheli ex Parl. GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Potentilla/Potentilla neglecta/ Syn. Potentilla albipellis/README.md
|
198
|
# Potentilla albipellis Borb s ex Zimmeter SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
apache-2.0
|
ek9852/gapid
|
core/app/run.go
|
4928
|
// Copyright (C) 2017 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 app
import (
"context"
"flag"
"fmt"
"os"
"syscall"
"github.com/google/gapid/core/event/task"
"github.com/google/gapid/core/fault"
"github.com/google/gapid/core/log"
"github.com/google/gapid/core/os/file"
"github.com/pkg/errors"
)
var (
// Name is the full name of the application
Name string
// ExitFuncForTesting can be set to change the behaviour when there is a command line parsing failure.
// It defaults to os.Exit
ExitFuncForTesting = os.Exit
// ShortHelp should be set to add a help message to the usage text.
ShortHelp = ""
// ShortUsage is usage text for the additional non-flag arguments.
ShortUsage = ""
// UsageFooter is printed at the bottom of the usage text
UsageFooter = ""
// Version holds the version specification for the application.
// The default version is the one defined in version.cmake.
// If valid a command line option to report it will be added automatically.
Version VersionSpec
// Restart is the error to return to cause the app to restart itself.
Restart = fault.Const("Restart")
)
// VersionSpec is the structure for the version of an application.
type VersionSpec struct {
// Major version, the version structure is in valid if <0
Major int
// Minor version, not used if <0
Minor int
// Point version, not used if <0
Point int
// The build identifier, not used if an empty string
Build string
}
// IsValid reports true if the VersionSpec is valid, ie it has a Major version.
func (v VersionSpec) IsValid() bool {
return v.Major >= 0
}
// GreaterThan returns true if v is greater than o.
func (v VersionSpec) GreaterThan(o VersionSpec) bool {
switch {
case v.Major > o.Major:
return true
case v.Major < o.Major:
return false
case v.Minor > o.Minor:
return true
case v.Minor < o.Minor:
return false
case v.Point > o.Point:
return true
default:
return false
}
}
// Format implements fmt.Formatter to print the version.
func (v VersionSpec) Format(f fmt.State, c rune) {
fmt.Fprint(f, v.Major)
if v.Minor >= 0 {
fmt.Fprint(f, ".", v.Minor)
}
if v.Point >= 0 {
fmt.Fprint(f, ".", v.Point)
}
if v.Build != "" {
fmt.Fprint(f, ":", v.Build)
}
}
func init() {
Name = file.Abs(os.Args[0]).Basename()
}
// Run performs all the work needed to start up an application.
// It parsers the main command line arguments, builds a primary context that will be cancelled on exit
// runs the provided task, cancels the primary context and then waits for either the maximum shutdown delay
// or all registered signals whichever comes first.
func Run(main task.Task) {
// Defer the panic handling
defer func() {
switch cause := recover().(type) {
case nil:
case ExitCode:
ExitFuncForTesting(int(cause))
default:
panic(cause)
}
}()
flags := &AppFlags{Log: logDefaults()}
// install all the common application flags
rootCtx, closeLogs := prepareContext(&flags.Log)
defer closeLogs()
// parse the command line
flag.CommandLine.Usage = func() { Usage(rootCtx, "") }
verbMainPrepare(flags)
globalVerbs.flags.Parse(os.Args[1:]...)
// Force the global verb's flags back into the default location for
// main programs that still look in flag.Args()
//TODO: We need to stop doing this
globalVerbs.flags.ForceCommandLine()
// apply the flags
if flags.Version {
fmt.Fprint(os.Stdout, Name, " version ", Version, "\n")
return
}
endProfile := applyProfiler(rootCtx, &flags.Profile)
ctx, cancel := context.WithCancel(rootCtx)
// Defer the shutdown code
defer func() {
cancel()
WaitForCleanup(rootCtx)
endProfile()
}()
ctx, closeLogs = updateContext(ctx, &flags.Log, closeLogs)
defer closeLogs()
// Add the abort signal handler
handleAbortSignals(task.CancelFunc(cancel))
// Now we are ready to run the main task
err := main(ctx)
if errors.Cause(err) == Restart {
err = doRestart()
}
if err != nil {
log.F(ctx, "Main failed\nError: %v", err)
}
}
func doRestart() error {
argv0 := file.ExecutablePath().System()
files := make([]*os.File, syscall.Stderr+1)
files[syscall.Stdin] = os.Stdin
files[syscall.Stdout] = os.Stdout
files[syscall.Stderr] = os.Stderr
wd, err := os.Getwd()
if nil != err {
return err
}
_, err = os.StartProcess(argv0, os.Args, &os.ProcAttr{
Dir: wd,
Env: os.Environ(),
Files: files,
Sys: &syscall.SysProcAttr{},
})
return err
}
|
apache-2.0
|
ayongw/shadowsocks-jclient
|
README.md
|
46
|
# shadowsocks-jclient
shadowsocks java client
|
apache-2.0
|
adangel/yal10n
|
src/main/java/net/sf/yal10n/charset/UTF8BOM.java
|
5421
|
package net.sf.yal10n.charset;
/*
* 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 java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
/**
* UTF-8 charset implementation that supports an optional BOM (Byte-Order-Mark).
* Base on the Java UTF-8 charset.
*/
public class UTF8BOM extends Charset
{
private static final float MAXIMUM_BYTES_PER_CHARACTER = 7.0f;
private static final float AVERAGE_BYTES_PER_CHARACTER = 1.1f;
/** Name of the charset - used if you select a charset via a String. */
public static final String NAME = "UTF-8-BOM";
private static final Charset UTF8_CHARSET = Charset.forName( "UTF-8" );
private static final byte[] UTF8_BOM_BYTES = new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf };
/**
* Creates a new UTF8BOM charset.
*/
protected UTF8BOM()
{
super( NAME, null );
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains( Charset cs )
{
return UTF8_CHARSET.contains( cs );
}
/**
* {@inheritDoc}
*/
@Override
public CharsetDecoder newDecoder()
{
return new CharsetDecoder( this, 1.0f, 1.0f )
{
private final CharsetDecoder utf8decoder = UTF8_CHARSET.newDecoder()
.onMalformedInput( malformedInputAction() ).onUnmappableCharacter( unmappableCharacterAction() );
private boolean bomDone = false;
private int bomIndexDone = 0;
private byte[] bom = new byte[3];
@Override
protected CoderResult decodeLoop( ByteBuffer in, CharBuffer out )
{
utf8decoder.reset();
if ( !bomDone )
{
try
{
while ( bomIndexDone < 3 )
{
bom[bomIndexDone] = in.get();
if ( bom[bomIndexDone] == UTF8_BOM_BYTES[bomIndexDone] )
{
bomIndexDone++;
}
else
{
break;
}
}
bomDone = true;
if ( bomIndexDone != 3 )
{
ByteBuffer in2 = ByteBuffer.allocate( 3 + in.capacity() );
in2.mark();
in2.put( bom, 0, bomIndexDone + 1 );
in2.limit( in2.position() );
in2.reset();
utf8decoder.decode( in2, out, false );
return utf8decoder.decode( in, out, true );
}
}
catch ( BufferUnderflowException e )
{
return CoderResult.UNDERFLOW;
}
}
return utf8decoder.decode( in, out, true );
}
/**
* {@inheritDoc}
*/
@Override
protected void implReset()
{
bomDone = false;
bomIndexDone = 0;
}
};
}
/**
* {@inheritDoc}
*/
@Override
public CharsetEncoder newEncoder()
{
return new CharsetEncoder( this, AVERAGE_BYTES_PER_CHARACTER, MAXIMUM_BYTES_PER_CHARACTER )
{
private CharsetEncoder utf8encoder = UTF8_CHARSET.newEncoder().onMalformedInput( CodingErrorAction.REPORT )
.onUnmappableCharacter( CodingErrorAction.REPORT );
private boolean bomDone = false;
/**
* {@inheritDoc}
*/
@Override
protected CoderResult encodeLoop( CharBuffer in, ByteBuffer out )
{
utf8encoder.reset();
if ( !bomDone )
{
try
{
out.put( UTF8_BOM_BYTES );
bomDone = true;
}
catch ( BufferOverflowException e )
{
return CoderResult.OVERFLOW;
}
}
return utf8encoder.encode( in, out, true );
}
/**
* {@inheritDoc}
*/
@Override
protected void implReset()
{
bomDone = false;
}
};
}
}
|
apache-2.0
|
elisska/cloudera-cassandra
|
DATASTAX_CASSANDRA-3.5.0/javadoc/org/apache/cassandra/cql3/functions/ScalarFunction.html
|
13675
|
<!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_40) on Wed Apr 13 18:09:35 UTC 2016 -->
<title>ScalarFunction (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<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="ScalarFunction (apache-cassandra API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/ScalarFunction.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/cassandra/cql3/functions/NativeScalarFunction.html" title="class in org.apache.cassandra.cql3.functions"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/cassandra/cql3/functions/SecurityThreadGroup.html" title="class in org.apache.cassandra.cql3.functions"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/cql3/functions/ScalarFunction.html" target="_top">Frames</a></li>
<li><a href="ScalarFunction.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.cassandra.cql3.functions</div>
<h2 title="Interface ScalarFunction" class="title">Interface ScalarFunction</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd><a href="../../../../../org/apache/cassandra/cql3/AssignmentTestable.html" title="interface in org.apache.cassandra.cql3">AssignmentTestable</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html" title="interface in org.apache.cassandra.cql3.functions">Function</a></dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../org/apache/cassandra/cql3/functions/FromJsonFct.html" title="class in org.apache.cassandra.cql3.functions">FromJsonFct</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/JavaBasedUDFunction.html" title="class in org.apache.cassandra.cql3.functions">JavaBasedUDFunction</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/NativeScalarFunction.html" title="class in org.apache.cassandra.cql3.functions">NativeScalarFunction</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/ToJsonFct.html" title="class in org.apache.cassandra.cql3.functions">ToJsonFct</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/TokenFct.html" title="class in org.apache.cassandra.cql3.functions">TokenFct</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/UDFunction.html" title="class in org.apache.cassandra.cql3.functions">UDFunction</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="typeNameLabel">ScalarFunction</span>
extends <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html" title="interface in org.apache.cassandra.cql3.functions">Function</a></pre>
<div class="block">Determines a single output value based on a single input value.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested.class.summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested.classes.inherited.from.class.org.apache.cassandra.cql3.AssignmentTestable">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from interface org.apache.cassandra.cql3.<a href="../../../../../org/apache/cassandra/cql3/AssignmentTestable.html" title="interface in org.apache.cassandra.cql3">AssignmentTestable</a></h3>
<code><a href="../../../../../org/apache/cassandra/cql3/AssignmentTestable.TestResult.html" title="enum in org.apache.cassandra.cql3">AssignmentTestable.TestResult</a></code></li>
</ul>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.nio.ByteBuffer</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/cql3/functions/ScalarFunction.html#execute-int-java.util.List-">execute</a></span>(int protocolVersion,
java.util.List<java.nio.ByteBuffer> parameters)</code>
<div class="block">Applies this function to the specified parameter.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/cql3/functions/ScalarFunction.html#isCalledOnNullInput--">isCalledOnNullInput</a></span>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.org.apache.cassandra.cql3.functions.Function">
<!-- -->
</a>
<h3>Methods inherited from interface org.apache.cassandra.cql3.functions.<a href="../../../../../org/apache/cassandra/cql3/functions/Function.html" title="interface in org.apache.cassandra.cql3.functions">Function</a></h3>
<code><a href="../../../../../org/apache/cassandra/cql3/functions/Function.html#argTypes--">argTypes</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html#columnName-java.util.List-">columnName</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html#getFunctions--">getFunctions</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html#hasReferenceTo-org.apache.cassandra.cql3.functions.Function-">hasReferenceTo</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html#isAggregate--">isAggregate</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html#isNative--">isNative</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html#name--">name</a>, <a href="../../../../../org/apache/cassandra/cql3/functions/Function.html#returnType--">returnType</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.org.apache.cassandra.cql3.AssignmentTestable">
<!-- -->
</a>
<h3>Methods inherited from interface org.apache.cassandra.cql3.<a href="../../../../../org/apache/cassandra/cql3/AssignmentTestable.html" title="interface in org.apache.cassandra.cql3">AssignmentTestable</a></h3>
<code><a href="../../../../../org/apache/cassandra/cql3/AssignmentTestable.html#testAssignment-java.lang.String-org.apache.cassandra.cql3.ColumnSpecification-">testAssignment</a></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="isCalledOnNullInput--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isCalledOnNullInput</h4>
<pre>boolean isCalledOnNullInput()</pre>
</li>
</ul>
<a name="execute-int-java.util.List-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>execute</h4>
<pre>java.nio.ByteBuffer execute(int protocolVersion,
java.util.List<java.nio.ByteBuffer> parameters)
throws <a href="../../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></pre>
<div class="block">Applies this function to the specified parameter.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>protocolVersion</code> - protocol version used for parameters and return value</dd>
<dd><code>parameters</code> - the input parameters</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the result of applying this function to the parameter</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code><a href="../../../../../org/apache/cassandra/exceptions/InvalidRequestException.html" title="class in org.apache.cassandra.exceptions">InvalidRequestException</a></code> - if this function cannot not be applied to the parameter</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= 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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/ScalarFunction.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/cassandra/cql3/functions/NativeScalarFunction.html" title="class in org.apache.cassandra.cql3.functions"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/cassandra/cql3/functions/SecurityThreadGroup.html" title="class in org.apache.cassandra.cql3.functions"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/cql3/functions/ScalarFunction.html" target="_top">Frames</a></li>
<li><a href="ScalarFunction.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 © 2016 The Apache Software Foundation</small></p>
</body>
</html>
|
apache-2.0
|
Shynixn/PetBlocks
|
docs/build_old/customizing/flying.html
|
12781
|
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flying — PetBlocks 8.18.0 documentation</title>
<link rel="shortcut icon" href="../_static/favicon.png"/>
<link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<link rel="index" title="Index"
href="../genindex.html"/>
<link rel="search" title="Search" href="../search.html"/>
<link rel="top" title="PetBlocks 8.18.0 documentation" href="../index.html"/>
<link rel="up" title="AIS" href="ai.html"/>
<link rel="next" title="Fly Riding" href="flyriding.html"/>
<link rel="prev" title="Float in Water" href="floatinwater.html"/>
<script src="../_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../index.html" class="icon icon-home"> PetBlocks
<img src="../_static/PetBlocks-small.png" class="logo" />
</a>
<div class="version">
8.18.0
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../gettingstarted/index.html">Getting Started</a></li>
<li class="toctree-l1"><a class="reference internal" href="../pets/index.html">Pets</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="index.html">Customizing</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="gui.html">GUI</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="ai.html">AIS</a><ul class="current">
<li class="toctree-l3"><a class="reference internal" href="afraidofwater.html">Afraid of Water</a></li>
<li class="toctree-l3"><a class="reference internal" href="ambientsound.html">Ambient Sound</a></li>
<li class="toctree-l3"><a class="reference internal" href="buffeffect.html">Buff Effect</a></li>
<li class="toctree-l3"><a class="reference internal" href="carry.html">Carry</a></li>
<li class="toctree-l3"><a class="reference internal" href="entitynbt.html">Entity-NBT</a></li>
<li class="toctree-l3"><a class="reference internal" href="feeding.html">Feeding</a></li>
<li class="toctree-l3"><a class="reference internal" href="fleeincombat.html">Flee in Combat</a></li>
<li class="toctree-l3"><a class="reference internal" href="floatinwater.html">Float in Water</a></li>
<li class="toctree-l3 current"><a class="current reference internal" href="#">Flying</a><ul>
<li class="toctree-l4"><a class="reference internal" href="#requirements">Requirements</a></li>
<li class="toctree-l4"><a class="reference internal" href="#configuring-in-your-config-yml">Configuring in your config.yml</a></li>
<li class="toctree-l4"><a class="reference internal" href="#properties">Properties</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="flyriding.html">Fly Riding</a></li>
<li class="toctree-l3"><a class="reference internal" href="followback.html">Follow Back</a></li>
<li class="toctree-l3"><a class="reference internal" href="followowner.html">Follow Owner</a></li>
<li class="toctree-l3"><a class="reference internal" href="groundriding.html">Ground Riding</a></li>
<li class="toctree-l3"><a class="reference internal" href="health.html">Health</a></li>
<li class="toctree-l3"><a class="reference internal" href="hopping.html">Hopping</a></li>
<li class="toctree-l3"><a class="reference internal" href="inventory.html">Inventory</a></li>
<li class="toctree-l3"><a class="reference internal" href="walking.html">Walking</a></li>
<li class="toctree-l3"><a class="reference internal" href="wearing.html">Wearing</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="example.html">Examples</a></li>
<li class="toctree-l2"><a class="reference internal" href="regions.html">Worlds and Regions</a></li>
<li class="toctree-l2"><a class="reference internal" href="minecraftheads.html">Minecraft-Heads.com</a></li>
<li class="toctree-l2"><a class="reference internal" href="headdatabase.html">Head Database</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../commands/index.html">Commands</a></li>
<li class="toctree-l1"><a class="reference internal" href="../general/index.html">General</a></li>
<li class="toctree-l1"><a class="reference internal" href="../api/index.html">Developer API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../faq/index.html">FAQ</a></li>
<li class="toctree-l1"><a class="reference internal" href="../contributing/index.html">Contributing to PetBlock</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../index.html">PetBlocks</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../index.html">Docs</a> »</li>
<li><a href="index.html">Customizing</a> »</li>
<li><a href="ai.html">AIS</a> »</li>
<li>Flying</li>
<li class="wy-breadcrumbs-aside">
<a href="https://github.com/Shynixn/PetBlocks/tree/master/docs/source/customizing/flying.rst" class="fa fa-github"> Edit on GitHub</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="flying">
<h1>Flying<a class="headerlink" href="#flying" title="Permalink to this headline">¶</a></h1>
<p>The AI called “Flying” is a behaviour ai which lets the pet move around the world.</p>
<p>In this case the pet will always stay at the same height as the player eventhough it might be hovering above the ground.
Therefore the <strong>offset</strong> parameter is the offset from the player’s head position instead of the ground.</p>
<p>Movement sound and particles can also be defined.</p>
<div class="section" id="requirements">
<h2>Requirements<a class="headerlink" href="#requirements" title="Permalink to this headline">¶</a></h2>
<p>This ai is a <strong>pathfinder based ai</strong>, which is one of the 3 base ais. (Walking, Hopping, Flying)</p>
</div>
<div class="section" id="configuring-in-your-config-yml">
<h2>Configuring in your config.yml<a class="headerlink" href="#configuring-in-your-config-yml" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li><p>Only the type parameter is required, all other parameters are optional.</p></li>
<li><p>You can specify this ai multiple times in order to play multiple movement sounds and particles.</p></li>
<li><p>Set the sound or particle name to none in order to send no sound or particles.</p></li>
</ul>
<p>config.yml</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">type</span><span class="p">:</span> <span class="s1">'flying'</span>
<span class="n">speed</span><span class="p">:</span> <span class="mf">1.0</span>
<span class="n">offset</span><span class="o">-</span><span class="n">y</span><span class="p">:</span> <span class="o">-</span><span class="mf">1.0</span>
<span class="n">sound</span><span class="p">:</span>
<span class="n">name</span><span class="p">:</span> <span class="s1">'CHICKEN_WALK'</span>
<span class="n">volume</span><span class="p">:</span> <span class="mf">1.0</span>
<span class="n">itch</span><span class="p">:</span> <span class="mf">1.0</span>
<span class="n">particle</span><span class="p">:</span>
<span class="n">name</span><span class="p">:</span> <span class="s1">'reddust'</span>
<span class="n">speed</span><span class="p">:</span> <span class="mf">0.01</span>
<span class="n">amount</span><span class="p">:</span> <span class="mi">20</span>
<span class="n">offx</span><span class="p">:</span> <span class="mi">0</span>
<span class="n">offy</span><span class="p">:</span> <span class="mi">0</span>
<span class="n">offz</span><span class="p">:</span> <span class="mi">255</span>
</pre></div>
</div>
<p>You can find all options explained at the bottom of this page.</p>
</div>
<div class="section" id="properties">
<h2>Properties<a class="headerlink" href="#properties" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li><p>Type: Unique identifier of the ai.</p></li>
<li><p>Tag: Optional tag to identify a specific ai configuration.</p></li>
<li><p>Speed: The flying speed of the pet.</p></li>
<li><p>Offset-Y: The offset value from the player’s head position.</p></li>
<li><p>ClickParticle.Name: Name of the particle effect. All names can be found <a class="reference external" href="https://shynixn.github.io/PetBlocks/apidocs/com/github/shynixn/petblocks/api/business/enumeration/ParticleType.html">here.</a></p></li>
<li><p>ClickParticle.Speed: Speed of the particle effect.</p></li>
<li><p>ClickParticle.Amount: Amount fo particles being displayed.</p></li>
<li><p>ClickParticle.OffXYZ: Offset values for the particle effect.</p></li>
<li><p>ClickSound.Name: Name of the sound. All names can be found <a class="reference external" href="https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Sound.html">here.</a></p></li>
<li><p>ClickSound.Volume: Volume of the sound.</p></li>
<li><p>ClickSound.Pitch: Pitch of the sound.</p></li>
</ul>
</div>
</div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="flyriding.html" class="btn btn-neutral float-right" title="Fly Riding" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="floatinwater.html" class="btn btn-neutral" title="Float in Water" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2015 - 2020, Shynixn.
</p>
</div>
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'../',
VERSION:'8.18.0',
LANGUAGE:'None',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script type="text/javascript" src="../_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-111364476-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-111364476-1');
</script>
</body>
</html>
|
apache-2.0
|
qintengfei/ionic-site
|
_site/docs/1.0.0-rc.4/api/directive/ionSpinner/index.html
|
33343
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Ionic makes it incredibly easy to build beautiful and interactive mobile apps using HTML5 and AngularJS.">
<meta name="keywords" content="html5,javascript,mobile,drifty,ionic,hybrid,phonegap,cordova,native,ios,android,angularjs">
<meta name="author" content="Drifty">
<meta property="og:image" content="http://ionicframework.com/img/ionic-logo-blog.png"/>
<title>ion-spinner - Directive in module ionic - Ionic Framework</title>
<link href="/css/site.css?12" rel="stylesheet">
<!--<script src="//cdn.optimizely.com/js/595530035.js"></script>-->
<script type="text/javascript">var _sf_startpt=(new Date()).getTime()</script>
<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-44023830-1', 'ionicframework.com');
ga('send', 'pageview');
</script>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body class="docs docs-page docs-api">
<nav class="navbar navbar-default horizontal-gradient" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle button ionic" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<i class="icon ion-navicon"></i>
</button>
<a class="navbar-brand" href="/">
<img src="/img/ionic-logo-white.svg" width="123" height="43" alt="Ionic Framework">
</a>
<a href="http://blog.ionic.io/announcing-ionic-1-0/" target="_blank">
<img src="/img/ionic1-tag.png" alt="Ionic 1.0 is out!" width="28" height="32" style="margin-left: 140px; margin-top:22px; display:block">
</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a class="getting-started-nav nav-link" href="/getting-started/">Getting Started</a></li>
<li><a class="docs-nav nav-link" href="/docs/">Docs</a></li>
<li><a class="nav-link" href="http://ionic.io/support">Support</a></li>
<li><a class="blog-nav nav-link" href="http://blog.ionic.io/">Blog <span id="blog-badge">1</span></a></li>
<li><a class="nav-link" href="http://forum.ionicframework.com/">Forum</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle nav-link " data-toggle="dropdown" role="button" aria-expanded="false">More <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<div class="arrow-up"></div>
<li><a class="products-nav nav-link" href="http://ionic.io/">Ionic.io</a></li>
<li><a class="examples-nav nav-link" href="http://showcase.ionicframework.com/">Showcase</a></li>
<li><a class="nav-link" href="http://jobs.ionic.io/">Job Board</a></li>
<li><a class="nav-link" href="http://market.ionic.io/">Market</a></li>
<li><a class="nav-link" href="http://ionicworldwide.herokuapp.com/">Ionic Worldwide</a></li>
<li><a class="nav-link" href="http://play.ionic.io/">Playground</a></li>
<li><a class="nav-link" href="http://creator.ionic.io/">Creator</a></li>
<li><a class="nav-link" href="http://shop.ionic.io/">Shop</a></li>
<!--<li><a class="nav-link" href="http://ngcordova.com/">ngCordova</a></li>-->
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="header horizontal-gradient">
<div class="container">
<h3>ion-spinner</h3>
<h4>Directive in module ionic</h4>
</div>
<div class="news">
<div class="container">
<div class="row">
<div class="col-sm-8 news-col">
<div class="picker">
<select onchange="window.location.href=this.options[this.selectedIndex].value">
<option
value="/docs/nightly/api/directive/ionSpinner/"
>
nightly
</option>
<option
value="/docs/api/directive/ionSpinner/"
>
1.1.0 (latest)
</option>
<option
value="/docs/1.0.1/api/directive/ionSpinner/"
>
1.0.1
</option>
<option
value="/docs/1.0.0/api/directive/ionSpinner/"
>
1.0.0
</option>
<option
value="/docs/1.0.0-rc.5/api/directive/ionSpinner/"
>
1.0.0-rc.5
</option>
<option
value="/docs/1.0.0-rc.4/api/directive/ionSpinner/"
selected>
1.0.0-rc.4
</option>
<option
value="/docs/1.0.0-rc.3/api/directive/ionSpinner/"
>
1.0.0-rc.3
</option>
<option
value="/docs/1.0.0-rc.2/api/directive/ionSpinner/"
>
1.0.0-rc.2
</option>
<option
value="/docs/1.0.0-rc.1/api/directive/ionSpinner/"
>
1.0.0-rc.1
</option>
<option
value="/docs/1.0.0-rc.0/api/directive/ionSpinner/"
>
1.0.0-rc.0
</option>
<option
value="/docs/1.0.0-beta.14/api/directive/ionSpinner/"
>
1.0.0-beta.14
</option>
<option
value="/docs/1.0.0-beta.13/api/directive/ionSpinner/"
>
1.0.0-beta.13
</option>
<option
value="/docs/1.0.0-beta.12/api/directive/ionSpinner/"
>
1.0.0-beta.12
</option>
<option
value="/docs/1.0.0-beta.11/api/directive/ionSpinner/"
>
1.0.0-beta.11
</option>
<option
value="/docs/1.0.0-beta.10/api/directive/ionSpinner/"
>
1.0.0-beta.10
</option>
</select>
</div>
</div>
<div class="col-sm-4 search-col">
<div class="search-bar">
<span class="search-icon ionic"><i class="ion-ios7-search-strong"></i></span>
<input type="search" id="search-input" value="Search">
</div>
</div>
</div>
</div>
</div>
</div>
<div id="search-results" class="search-results" style="display:none">
<div class="container">
<div class="search-section search-api">
<h4>JavaScript</h4>
<ul id="results-api"></ul>
</div>
<div class="search-section search-css">
<h4>CSS</h4>
<ul id="results-css"></ul>
</div>
<div class="search-section search-content">
<h4>Resources</h4>
<ul id="results-content"></ul>
</div>
</div>
</div>
<div class="container content-container">
<div class="row">
<div class="col-md-2 col-sm-3 aside-menu">
<div>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/overview/">Overview</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/components/">CSS</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/platform-customization/">Platform Customization</a>
</li>
</ul>
<!-- Docs: JavaScript -->
<ul class="nav left-menu active-menu">
<li class="menu-title">
<a href="/docs/api/">
JavaScript
</a>
</li>
<!-- Action Sheet -->
<li class="menu-section">
<a href="/docs/api/service/$ionicActionSheet/" class="api-section">
Action Sheet
</a>
<ul>
<li>
<a href="/docs/api/service/$ionicActionSheet/">
$ionicActionSheet
</a>
</li>
</ul>
</li>
<!-- Backdrop -->
<li class="menu-section">
<a href="/docs/api/service/$ionicBackdrop/" class="api-section">
Backdrop
</a>
<ul>
<li>
<a href="/docs/api/service/$ionicBackdrop/">
$ionicBackdrop
</a>
</li>
</ul>
</li>
<!-- Content -->
<li class="menu-section">
<a href="/docs/api/directive/ionContent/" class="api-section">
Content
</a>
<ul>
<li>
<a href="/docs/api/directive/ionContent/">
ion-content
</a>
</li>
<li>
<a href="/docs/api/directive/ionRefresher/">
ion-refresher
</a>
</li>
<li>
<a href="/docs/api/directive/ionPane/">
ion-pane
</a>
</li>
</ul>
</li>
<!-- Form Inputs -->
<li class="menu-section">
<a href="/docs/api/directive/ionCheckbox/" class="api-section">
Form Inputs
</a>
<ul>
<li>
<a href="/docs/api/directive/ionCheckbox/">
ion-checkbox
</a>
</li>
<li>
<a href="/docs/api/directive/ionRadio/">
ion-radio
</a>
</li>
<li>
<a href="/docs/api/directive/ionToggle/">
ion-toggle
</a>
</li>
</ul>
</li>
<!-- Gesture and Events -->
<li class="menu-section">
<a href="/docs/api/directive/onHold/" class="api-section">
Gestures and Events
</a>
<ul>
<li>
<a href="/docs/api/directive/onHold/">
on-hold
</a>
</li>
<li>
<a href="/docs/api/directive/onTap/">
on-tap
</a>
</li>
<li>
<a href="/docs/api/directive/onDoubleTap/">
on-double-tap
</a>
</li>
<li>
<a href="/docs/api/directive/onTouch/">
on-touch
</a>
</li>
<li>
<a href="/docs/api/directive/onRelease/">
on-release
</a>
</li>
<li>
<a href="/docs/api/directive/onDrag/">
on-drag
</a>
</li>
<li>
<a href="/docs/api/directive/onDragUp/">
on-drag-up
</a>
</li>
<li>
<a href="/docs/api/directive/onDragRight/">
on-drag-right
</a>
</li>
<li>
<a href="/docs/api/directive/onDragDown/">
on-drag-down
</a>
</li>
<li>
<a href="/docs/api/directive/onDragLeft/">
on-drag-left
</a>
</li>
<li>
<a href="/docs/api/directive/onSwipe/">
on-swipe
</a>
</li>
<li>
<a href="/docs/api/directive/onSwipeUp/">
on-swipe-up
</a>
</li>
<li>
<a href="/docs/api/directive/onSwipeRight/">
on-swipe-right
</a>
</li>
<li>
<a href="/docs/api/directive/onSwipeDown/">
on-swipe-down
</a>
</li>
<li>
<a href="/docs/api/directive/onSwipeLeft/">
on-swipe-left
</a>
</li>
<li>
<a href="/docs/api/service/$ionicGesture/">
$ionicGesture
</a>
</li>
</ul>
</li>
<!-- Headers/Footers -->
<li class="menu-section">
<a href="/docs/api/directive/ionHeaderBar/" class="api-section">
Headers/Footers
</a>
<ul>
<li>
<a href="/docs/api/directive/ionHeaderBar/">
ion-header-bar
</a>
</li>
<li>
<a href="/docs/api/directive/ionFooterBar/">
ion-footer-bar
</a>
</li>
</ul>
</li>
<!-- Keyboard -->
<li class="menu-section">
<a href="/docs/api/page/keyboard/" class="api-section">
Keyboard
</a>
<ul>
<li>
<a href="/docs/api/page/keyboard/">
Keyboard
</a>
</li>
<li>
<a href="/docs/api/directive/keyboardAttach/">
keyboard-attach
</a>
</li>
</ul>
</li>
<!-- Lists -->
<li class="menu-section">
<a href="/docs/api/directive/ionList/" class="api-section">
Lists
</a>
<ul>
<li>
<a href="/docs/api/directive/ionList/">
ion-list
</a>
</li>
<li>
<a href="/docs/api/directive/ionItem/">
ion-item
</a>
</li>
<li>
<a href="/docs/api/directive/ionDeleteButton/">
ion-delete-button
</a>
</li>
<li>
<a href="/docs/api/directive/ionReorderButton/">
ion-reorder-button
</a>
</li>
<li>
<a href="/docs/api/directive/ionOptionButton/">
ion-option-button
</a>
</li>
<li>
<a href="/docs/api/directive/collectionRepeat/">
collection-repeat
</a>
</li>
<li>
<a href="/docs/api/service/$ionicListDelegate/">
$ionicListDelegate
</a>
</li>
</ul>
</li>
<!-- Loading -->
<li class="menu-section">
<a href="/docs/api/service/$ionicLoading/" class="api-section">
Loading
</a>
<ul>
<li>
<a href="/docs/api/service/$ionicLoading/">
$ionicLoading
</a>
</li>
</ul>
<ul>
<li>
<a href="/docs/api/object/$ionicLoadingConfig/">
$ionicLoadingConfig
</a>
</li>
</ul>
</li>
<!-- Modal -->
<li class="menu-section">
<a href="/docs/api/service/$ionicModal/" class="api-section">
Modal
</a>
<ul>
<li>
<a href="/docs/api/service/$ionicModal/">
$ionicModal
</a>
</li>
<li>
<a href="/docs/api/controller/ionicModal/">
ionicModal
</a>
</li>
</ul>
</li>
<!-- Navigation -->
<li class="menu-section">
<a href="/docs/api/directive/ionNavView/" class="api-section">
Navigation
</a>
<ul>
<li>
<a href="/docs/api/directive/ionNavView/">
ion-nav-view
</a>
</li>
<li>
<a href="/docs/api/directive/ionView/">
ion-view
</a>
</li>
<li>
<a href="/docs/api/directive/ionNavBar/">
ion-nav-bar
</a>
</li>
<li>
<a href="/docs/api/directive/ionNavBackButton/">
ion-nav-back-button
</a>
</li>
<li>
<a href="/docs/api/directive/ionNavButtons/">
ion-nav-buttons
</a>
</li>
<li>
<a href="/docs/api/directive/ionNavTitle/">
ion-nav-title
</a>
</li>
<li>
<a href="/docs/api/directive/navTransition/">
nav-transition
</a>
</li>
<li>
<a href="/docs/api/directive/navDirection/">
nav-direction
</a>
</li>
<li>
<a href="/docs/api/service/$ionicNavBarDelegate/">
$ionicNavBarDelegate
</a>
</li>
<li>
<a href="/docs/api/service/$ionicHistory/">
$ionicHistory
</a>
</li>
</ul>
</li>
<!-- Platform -->
<li class="menu-section">
<a href="/docs/api/service/$ionicPlatform/" class="api-section">
Platform
</a>
<ul>
<li>
<a href="/docs/api/service/$ionicPlatform/">
$ionicPlatform
</a>
</li>
</ul>
</li>
<!-- Popover -->
<li class="menu-section">
<a href="/docs/api/service/$ionicPopover/" class="api-section">
Popover
</a>
<ul>
<li>
<a href="/docs/api/service/$ionicPopover/">
$ionicPopover
</a>
</li>
<li>
<a href="/docs/api/controller/ionicPopover/">
ionicPopover
</a>
</li>
</ul>
</li>
<!-- Popup -->
<li class="menu-section">
<a href="/docs/api/service/$ionicPopup/" class="api-section">
Popup
</a>
<ul>
<li>
<a href="/docs/api/service/$ionicPopup/">
$ionicPopup
</a>
</li>
</ul>
</li>
<!-- Scroll -->
<li class="menu-section">
<a href="/docs/api/directive/ionScroll/" class="api-section">
Scroll
</a>
<ul>
<li>
<a href="/docs/api/directive/ionScroll/">
ion-scroll
</a>
</li>
<li>
<a href="/docs/api/directive/ionInfiniteScroll/">
ion-infinite-scroll
</a>
</li>
<li>
<a href="/docs/api/service/$ionicScrollDelegate/">
$ionicScrollDelegate
</a>
</li>
</ul>
</li>
<!-- Side Menus -->
<li class="menu-section">
<a href="/docs/api/directive/ionSideMenus/" class="api-section">
Side Menus
</a>
<ul>
<li>
<a href="/docs/api/directive/ionSideMenus/">
ion-side-menus
</a>
</li>
<li>
<a href="/docs/api/directive/ionSideMenuContent/">
ion-side-menu-content
</a>
</li>
<li>
<a href="/docs/api/directive/ionSideMenu/">
ion-side-menu
</a>
</li>
<li>
<a href="/docs/api/directive/exposeAsideWhen/">
expose-aside-when
</a>
</li>
<li>
<a href="/docs/api/directive/menuToggle/">
menu-toggle
</a>
</li>
<li>
<a href="/docs/api/directive/menuClose/">
menu-close
</a>
</li>
<li>
<a href="/docs/api/service/$ionicSideMenuDelegate/">
$ionicSideMenuDelegate
</a>
</li>
</ul>
</li>
<!-- Slide Box -->
<li class="menu-section">
<a href="/docs/api/directive/ionSlideBox/" class="api-section">
Slide Box
</a>
<ul>
<li>
<a href="/docs/api/directive/ionSlideBox/">
ion-slide-box
</a>
</li>
<li>
<a href="/docs/api/directive/ionSlidePager/">
ion-slide-pager
</a>
</li>
<li>
<a href="/docs/api/directive/ionSlide/">
ion-slide
</a>
</li>
<li>
<a href="/docs/api/service/$ionicSlideBoxDelegate/">
$ionicSlideBoxDelegate
</a>
</li>
</ul>
</li>
<!-- Spinner -->
<li class="menu-section">
<a href="/docs/api/directive/ionSpinner/" class="api-section">
Spinner
</a>
<ul>
<li>
<a href="/docs/api/directive/ionSpinner/">
ion-spinner
</a>
</li>
</ul>
</li>
<!-- Tabs -->
<li class="menu-section">
<a href="/docs/api/directive/ionTabs/" class="api-section">
Tabs
</a>
<ul>
<li>
<a href="/docs/api/directive/ionTabs/">
ion-tabs
</a>
</li>
<li>
<a href="/docs/api/directive/ionTab/">
ion-tab
</a>
</li>
<li>
<a href="/docs/api/service/$ionicTabsDelegate/">
$ionicTabsDelegate
</a>
</li>
</ul>
</li>
<!-- Tap -->
<li class="menu-section">
<a href="/docs/api/page/tap/" class="api-section">
Tap & Click
</a>
</li>
<!-- Utility -->
<li class="menu-section">
<a href="#" class="api-section">
Utility
</a>
<ul>
<li>
<a href="/docs/api/provider/$ionicConfigProvider/">
$ionicConfigProvider
</a>
</li>
<li>
<a href="/docs/api/utility/ionic.Platform/">
ionic.Platform
</a>
</li>
<li>
<a href="/docs/api/utility/ionic.DomUtil/">
ionic.DomUtil
</a>
</li>
<li>
<a href="/docs/api/utility/ionic.EventController/">
ionic.EventController
</a>
</li>
<li>
<a href="/docs/api/service/$ionicPosition/">
$ionicPosition
</a>
</li>
</ul>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/cli/">CLI</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="http://learn.ionicframework.com/">Learn Ionic</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/guide/">Guide</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/ionic-cli-faq/">FAQ</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/getting-help/">Getting Help</a>
</li>
</ul>
<ul class="nav left-menu">
<li class="menu-title">
<a href="/docs/concepts/">Ionic Concepts</a>
</li>
</ul>
</div>
</div>
<div class="col-md-10 col-sm-9 main-content">
<div class="improve-docs">
<a href='http://github.com/driftyco/ionic/tree/master/js/angular/directive/spinner.js#L1'>
View Source
</a>
<a href='http://github.com/driftyco/ionic/edit/master/js/angular/directive/spinner.js#L1'>
Improve this doc
</a>
</div>
<h1 class="api-title">
ion-spinner
</h1>
<p>The <code>ionSpinner</code> directive provides a variety of animated spinners.
Spinners enables you to give your users feedback that the app is
processing/thinking/waiting/chillin' out, or whatever you'd like it to indicate.
By default, the <a href="/docs/api/directive/ionRefresher/"><code>ionRefresher</code></a> feature uses this spinner, rather
than rotating font icons (previously included in <a href="http://ionicons.com/">ionicons</a>).
While font icons are great for simple or stationary graphics, they're not suited to
provide great animations, which is why Ionic uses SVG instead.</p>
<p>Ionic offers ten spinners out of the box, and by default, it will use the appropriate spinner
for the platform on which it's running. Under the hood, the <code>ionSpinner</code> directive dynamically
builds the required SVG element, which allows Ionic to provide all ten of the animated SVGs
within 3KB.</p>
<style>
.spinner-table {
max-width: 280px;
}
.spinner-table tbody > tr > th, .spinner-table tbody > tr > td {
vertical-align: middle;
width: 42px;
height: 42px;
}
.spinner {
stroke: #444;
fill: #444; }
.spinner svg {
width: 28px;
height: 28px; }
.spinner.spinner-inverse {
stroke: #fff;
fill: #fff; }
.spinner-android {
stroke: #4b8bf4; }
.spinner-ios, .spinner-ios-small {
stroke: #69717d; }
.spinner-spiral .stop1 {
stop-color: #fff;
stop-opacity: 0; }
.spinner-spiral.spinner-inverse .stop1 {
stop-color: #000; }
.spinner-spiral.spinner-inverse .stop2 {
stop-color: #fff; }
</style>
<script src="http://code.ionicframework.com/nightly/js/ionic.bundle.min.js"></script>
<table class="table spinner-table" ng-app="ionic">
<tr>
<th>
<code>android</code>
</th>
<td>
<ion-spinner icon="android"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>ios</code>
</th>
<td>
<ion-spinner icon="ios"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>ios-small</code>
</th>
<td>
<ion-spinner icon="ios-small"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>bubbles</code>
</th>
<td>
<ion-spinner icon="bubbles"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>circles</code>
</th>
<td>
<ion-spinner icon="circles"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>crescent</code>
</th>
<td>
<ion-spinner icon="crescent"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>dots</code>
</th>
<td>
<ion-spinner icon="dots"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>lines</code>
</th>
<td>
<ion-spinner icon="lines"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>ripple</code>
</th>
<td>
<ion-spinner icon="ripple"></ion-spinner>
</td>
</tr>
<tr>
<th>
<code>spiral</code>
</th>
<td>
<ion-spinner icon="spiral"></ion-spinner>
</td>
</tr>
</table>
<p>Each spinner uses SVG with SMIL animations, however, the Android spinner also uses JavaScript
so it also works on Android 4.0-4.3. Additionally, each spinner can be styled with CSS,
and scaled to any size.</p>
<h2 id="usage">Usage</h2>
<p>The following code would use the default spinner for the platform it's running from. If it's neither
iOS or Android, it'll default to use <code>ios</code>.</p>
<div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><ion-spinner></ion-spinner></span>
</code></pre></div>
<p>By setting the <code>icon</code> attribute, you can specify which spinner to use, no matter what
the platform is.</p>
<div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><ion-spinner</span> <span class="na">icon=</span><span class="s">"spiral"</span><span class="nt">></ion-spinner></span>
</code></pre></div>
<h2>Spinner Colors</h2>
<p>Like with most of Ionic's other components, spinners can also be styled using
Ionic's standard color naming convention. For example:</p>
<div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><ion-spinner</span> <span class="na">class=</span><span class="s">"spinner-energized"</span><span class="nt">></ion-spinner></span>
</code></pre></div>
<h2>Styling SVG with CSS</h2>
<p>One cool thing about SVG is its ability to be styled with CSS! Some of the properties
have different names, for example, SVG uses the term <code>stroke</code> instead of <code>border</code>, and
<code>fill</code> instead of <code>background-color</code>.</p>
<div class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.spinner</span> <span class="nt">svg</span> <span class="p">{</span>
<span class="k">width</span><span class="o">:</span> <span class="m">28px</span><span class="p">;</span>
<span class="k">height</span><span class="o">:</span> <span class="m">28px</span><span class="p">;</span>
<span class="n">stroke</span><span class="o">:</span> <span class="m">#444</span><span class="p">;</span>
<span class="n">fill</span><span class="o">:</span> <span class="m">#444</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
</div>
</div>
</div>
<div class="pre-footer">
<div class="row ionic">
<div class="col-sm-6 col-a">
<h4>
<a href="/getting-started/">Getting started <span class="icon ion-arrow-right-c"></span></a>
</h4>
<p>
Learn more about how Ionic was built, why you should use it, and what's included. We'll cover
the basics and help you get started from the ground up.
</p>
</div>
<div class="col-sm-6 col-b">
<h4>
<a href="/docs/">Documentation <span class="icon ion-arrow-right-c"></span></a>
</h4>
<p>
What are you waiting for? Take a look and get coding! Our documentation covers all you need to know
to get an app up and running in minutes.
</p>
</div>
</div>
</div>
<footer class="footer">
<nav class="base-links">
<dl>
<dt>Docs</dt>
<dd><a href="http://ionicframework.com/docs/">Documentation</a></dd>
<dd><a href="http://ionicframework.com/getting-started/">Getting Started</a></dd>
<dd><a href="http://ionicframework.com/docs/overview/">Overview</a></dd>
<dd><a href="http://ionicframework.com/docs/components/">Components</a></dd>
<dd><a href="http://ionicframework.com/docs/api/">JavaScript</a></dd>
<dd><a href="http://ionicframework.com/submit-issue/">Submit Issue</a></dd>
</dl>
<dl>
<dt>Resources</dt>
<dd><a href="http://learn.ionicframework.com/">Learn Ionic</a></dd>
<dd><a href="http://ngcordova.com/">ngCordova</a></dd>
<dd><a href="http://ionicons.com/">Ionicons</a></dd>
<dd><a href="http://creator.ionic.io/">Creator</a></dd>
<dd><a href="http://showcase.ionicframework.com/">Showcase</a></dd>
<dd><a href="http://manning.com/wilken/?a_aid=ionicinactionben&a_bid=1f0a0e1d">The Ionic Book</a></dd>
</dl>
<dl>
<dt>Contribute</dt>
<dd><a href="http://forum.ionicframework.com/">Community Forum</a></dd>
<dd><a href="http://webchat.freenode.net/?randomnick=1&channels=%23ionic&uio=d4">Ionic IRC</a></dd>
<dd><a href="http://ionicframework.com/present-ionic/">Present Ionic</a></dd>
<dd><a href="http://ionicframework.com/contribute/">Contribute</a></dd>
<dd><a href="https://github.com/driftyco/ionic-learn/issues/new">Write for us</a></dd>
<dd><a href="http://shop.ionic.io/">Ionic Shop</a></dd>
</dl>
<dl class="small-break">
<dt>About</dt>
<dd><a href="http://blog.ionic.io/">Blog</a></dd>
<dd><a href="http://ionic.io">Services</a></dd>
<dd><a href="http://drifty.com">Company</a></dd>
<dd><a href="https://s3.amazonaws.com/ionicframework.com/logo-pack.zip">Logo Pack</a></dd>
<dd><a href="mailto:[email protected]">Contact</a></dd>
<dd><a href="http://ionicframework.com/jobs/">Jobs</a></dd>
</dl>
<dl>
<dt>Connect</dt>
<dd><a href="https://twitter.com/IonicFramework">Twitter</a></dd>
<dd><a href="https://github.com/driftyco/ionic">GitHub</a></dd>
<dd><a href="https://www.facebook.com/ionicframework">Facebook</a></dd>
<dd><a href="https://plus.google.com/b/112280728135675018538/+Ionicframework/posts">Google+</a></dd>
<dd><a href="https://www.youtube.com/channel/UChYheBnVeCfhCmqZfCUdJQw">YouTube</a></dd>
<dd><a href="https://twitter.com/ionitron">Ionitron</a></dd>
</dl>
</nav>
<div class="newsletter row">
<div class="newsletter-container">
<div class="col-sm-7">
<div class="newsletter-text">Stay in the loop</div>
<div class="sign-up">Sign up to receive emails for the latest updates, features, and news on the framework.</div>
</div>
<form action="http://codiqa.createsend.com/t/t/s/jytylh/" method="post" class="input-group col-sm-5">
<input id="fieldEmail" name="cm-jytylh-jytylh" class="form-control" type="email" placeholder="Email" required />
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Subscribe</button>
</span>
</form>
</div>
</div>
<div class="copy">
<div class="copy-container">
<p class="authors">
Code licensed under <a href="/docs/#license">MIT</a>.
Docs under <a href="https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)">Apache 2</a>
<span>|</span>
© 2013-2015 <a href="http://drifty.com/">Drifty Co</a>
</p>
</div>
</div>
</footer>
<script type="text/javascript">
var _sf_async_config = { uid: 54141, domain: 'ionicframework.com', useCanonical: true };
(function() {
function loadChartbeat() {
window._sf_endpt = (new Date()).getTime();
var e = document.createElement('script');
e.setAttribute('language', 'javascript');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src','//static.chartbeat.com/js/chartbeat.js');
document.body.appendChild(e);
};
var oldonload = window.onload;
window.onload = (typeof window.onload != 'function') ?
loadChartbeat : function() { oldonload(); loadChartbeat(); };
})();
</script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<script src="/js/site.js?1"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Cookies.js/0.4.0/cookies.min.js"></script>
<script>
$('.navbar .dropdown').on('show.bs.dropdown', function(e){
//$(this).find('.dropdown-menu').addClass('animated fadeInDown');
});
// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.navbar .dropdown').on('hide.bs.dropdown', function(e){
//$(this).find('.dropdown-menu').first().stop(true, true).slideUp(200);
//$(this).find('.dropdown-menu').removeClass('animated fadeInDown');
});
try {
var d = new Date('2015-03-20 05:00:00 -0500');
var ts = d.getTime();
var cd = Cookies.get('_iondj');
if(cd) {
cd = JSON.parse(atob(cd));
if(parseInt(cd.lp) < ts) {
var bt = document.getElementById('blog-badge');
bt.style.display = 'block';
}
cd.lp = ts;
} else {
var bt = document.getElementById('blog-badge');
bt.style.display = 'block';
cd = {
lp: ts
}
}
Cookies.set('_iondj', btoa(JSON.stringify(cd)));
} catch(e) {
}
</script>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
</body>
</html>
|
apache-2.0
|
camilesing/zstack
|
sdk/src/main/java/org/zstack/sdk/sns/platform/dingtalk/CreateSNSDingTalkEndpointAction.java
|
3482
|
package org.zstack.sdk.sns.platform.dingtalk;
import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;
public class CreateSNSDingTalkEndpointAction extends AbstractAction {
private static final HashMap<String, Parameter> parameterMap = new HashMap<>();
private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();
public static class Result {
public ErrorCode error;
public org.zstack.sdk.sns.platform.dingtalk.CreateSNSDingTalkEndpointResult value;
public Result throwExceptionIfError() {
if (error != null) {
throw new ApiException(
String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
);
}
return this;
}
}
@Param(required = true, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String url;
@Param(required = false)
public java.lang.Boolean atAll;
@Param(required = false, nonempty = true, nullElements = false, emptyString = true, noTrim = false)
public java.util.List atPersonPhoneNumbers;
@Param(required = true, maxLength = 255, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String name;
@Param(required = false, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String description;
@Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String platformUuid;
@Param(required = false)
public java.lang.String resourceUuid;
@Param(required = false)
public java.util.List systemTags;
@Param(required = false)
public java.util.List userTags;
@Param(required = true)
public String sessionId;
@NonAPIParam
public long timeout = -1;
@NonAPIParam
public long pollingInterval = -1;
private Result makeResult(ApiResult res) {
Result ret = new Result();
if (res.error != null) {
ret.error = res.error;
return ret;
}
org.zstack.sdk.sns.platform.dingtalk.CreateSNSDingTalkEndpointResult value = res.getResult(org.zstack.sdk.sns.platform.dingtalk.CreateSNSDingTalkEndpointResult.class);
ret.value = value == null ? new org.zstack.sdk.sns.platform.dingtalk.CreateSNSDingTalkEndpointResult() : value;
return ret;
}
public Result call() {
ApiResult res = ZSClient.call(this);
return makeResult(res);
}
public void call(final Completion<Result> completion) {
ZSClient.call(this, new InternalCompletion() {
@Override
public void complete(ApiResult res) {
completion.complete(makeResult(res));
}
});
}
protected Map<String, Parameter> getParameterMap() {
return parameterMap;
}
protected Map<String, Parameter> getNonAPIParameterMap() {
return nonAPIParameterMap;
}
protected RestInfo getRestInfo() {
RestInfo info = new RestInfo();
info.httpMethod = "POST";
info.path = "/sns/application-endpoints/ding-talk";
info.needSession = true;
info.needPoll = true;
info.parameterName = "params";
return info;
}
}
|
apache-2.0
|
metaborg/spoofax
|
org.metaborg.core/src/main/java/org/metaborg/core/completion/Completion.java
|
4484
|
package org.metaborg.core.completion;
import java.io.Serializable;
public class Completion implements ICompletion, Serializable {
/**
* Serializable because it is necessary to pass an object as a String to Eclipse additional info menu
*/
private static final long serialVersionUID = 6960435974459583999L;
private final String name;
private final String sort;
private final String text;
private final String additionalInfo;
private String prefix = "";
private String suffix = "";
private Iterable<ICompletionItem> items;
private final int startOffset;
private final int endOffset;
private boolean nested;
private boolean fromOptionalPlaceholder;
private final CompletionKind kind;
public Completion(String name, String sort, String text, String additionalInfo, int startOffset, int endOffset,
CompletionKind kind) {
this.name = name;
this.sort = sort;
this.text = text;
this.additionalInfo = additionalInfo;
this.startOffset = startOffset;
this.endOffset = endOffset;
this.nested = false;
this.fromOptionalPlaceholder = false;
this.kind = kind;
}
public Completion(String name, String sort, String text, String additionalInfo, int startOffset, int endOffset,
CompletionKind kind, String prefix, String suffix) {
this.name = name;
this.sort = sort;
this.text = text;
this.additionalInfo = additionalInfo;
this.startOffset = startOffset;
this.endOffset = endOffset;
this.nested = false;
this.fromOptionalPlaceholder = false;
this.kind = kind;
this.prefix = prefix;
this.suffix = suffix;
}
@Override public String name() {
return name;
}
@Override public String sort() {
return sort;
}
@Override public String text() {
return text;
}
@Override public String additionalInfo() {
return additionalInfo;
}
@Override public String prefix() {
return this.prefix;
}
@Override public String suffix() {
return this.suffix;
}
@Override public Iterable<ICompletionItem> items() {
return items;
}
@Override public void setItems(Iterable<ICompletionItem> items) {
this.items = items;
}
@Override public int startOffset() {
return startOffset;
}
@Override public int endOffset() {
return endOffset;
}
@Override public boolean isNested() {
return nested;
}
@Override public void setNested(boolean nested) {
this.nested = nested;
}
@Override public boolean fromOptionalPlaceholder() {
return fromOptionalPlaceholder;
}
@Override public void setOptionalPlaceholder(boolean optional) {
this.fromOptionalPlaceholder = optional;
}
@Override public CompletionKind kind() {
return this.kind;
}
@Override public String toString() {
return name;
}
@Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((additionalInfo == null) ? 0 : additionalInfo.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sort == null) ? 0 : sort.hashCode());
result = prime * result + ((text == null) ? 0 : text.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;
Completion other = (Completion) obj;
if(additionalInfo == null) {
if(other.additionalInfo != null)
return false;
} else if(!additionalInfo.equals(other.additionalInfo))
return false;
if(name == null) {
if(other.name != null)
return false;
} else if(!name.equals(other.name))
return false;
if(sort == null) {
if(other.sort != null)
return false;
} else if(!sort.equals(other.sort))
return false;
if(text == null) {
if(other.text != null)
return false;
} else if(!text.equals(other.text))
return false;
return true;
}
}
|
apache-2.0
|
Dakror/WebcamParser
|
src/de/dakror/webcamparser/EBookReader.java
|
2948
|
/*******************************************************************************
* Copyright 2015 Maximilian Stark | Dakror <[email protected]>
*
* 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 de.dakror.webcamparser;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
/**
* @author Maximilian Stark | Dakror
*/
public class EBookReader {
static int start;
static int page;
public static void main(String[] args) throws Exception {
Reader.language = "eng";
Reader.voice = "cmu-rms-hsmm";
Reader.init();
PdfReader reader = new PdfReader("Midnight_Tides.pdf");
start = 7;
page = start;
JFrame frame = new JFrame("Menu");
Container panel = frame.getContentPane();
panel.setLayout(new GridLayout(3, 1));
panel.add(new JButton(new AbstractAction("Prev") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
page -= 2;
Reader.player.cancel();
}
}));
panel.add(new JButton(new AbstractAction("Next") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
if (Reader.player != null) Reader.player.cancel();
}
}));
panel.add(new JButton(new AbstractAction("Go to page") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
page = Integer.parseInt(JOptionPane.showInputDialog("page number (start at 1):")) - 1;
if (Reader.player != null) Reader.player.cancel();
}
}));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
for (; page <= reader.getNumberOfPages(); page++) {
String s = PdfTextExtractor.getTextFromPage(reader, page);
s = s.replace("—", ", ").replace(" - ", ", ").replace("Andü", "Andii");
System.out.println();
System.out.println("############## - Page " + page + " - ##############");
System.out.println();
System.out.println(s);
Reader.read(s);
}
}
}
|
apache-2.0
|
richarddan/SmartStick
|
src/com/guanshuwei/smartstick/data/HistoryDatabase.java
|
17431
|
package com.guanshuwei.smartstick.data;
import java.util.Calendar;
import java.util.Locale;
import java.util.Vector;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import com.guanshuwei.smartstick.instance.HistoryModule;
import com.guanshuwei.smartstick.instance.HistoryModule.LogType;
import com.guanshuwei.smartstick.util.Utilities;
public class HistoryDatabase {
private static class Data {
private static class Tables {
public static class HistoryTable implements BaseColumns {
public static final String TABLE_NAME = "HistoryDatabase";
public static final String NAME = "_NAME";
public static final String PHONEMUNBER = "_PHONENUMBER";
public static final String LOGTYPE = "_LOGTYPE";
public static final String LANGTITUDE = "_LANGTITUDE";
public static final String LONGITUDE = "_LONGITUDE";
public static final String DATE = "_DATE";
public static final String UNIQUE = "_UNIQUE";
public static final String CREATE_QUERY = "CREATE TABLE "
+ TABLE_NAME + " (" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME
+ " TEXT NOT NULL, " + PHONEMUNBER + " TEXT NOT NULL,"
+ LOGTYPE + " TEXT NOT NULL," + DATE
+ " TEXT NOT NULL," + LANGTITUDE + " TEXT NOT NULL,"
+ LONGITUDE + " TEXT NOT NULL);";
public static final String CREATE_UNIQUE = "CREATE UNIQUE INDEX "
+ UNIQUE + " ON " + TABLE_NAME + " (" + DATE + ");";
public static final String DROP_QUERY = "DROP TABLE IF EXISTS "
+ TABLE_NAME + ";";
}
}
private static boolean AnyMatch = false;
private final Context applicationContext;
private static class DataHelper extends SQLiteOpenHelper {
public static final int USERINFO_DATABASE_VERSION = 2;
public static final String USERINFO_DATABASE_NAME = "HistoryDatabase.db";
public DataHelper(Context context) {
super(context, USERINFO_DATABASE_NAME, null,
USERINFO_DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.beginTransaction();
try {
db.execSQL(Tables.HistoryTable.CREATE_QUERY);
db.execSQL(Tables.HistoryTable.CREATE_UNIQUE);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
if (newVersion <= oldVersion) {
return;
}
db.beginTransaction();
try {
db.execSQL(Tables.HistoryTable.DROP_QUERY);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
this.onCreate(db);
}
}
private DataHelper dataHelper;
private boolean adapterInitialized;
public Data(Context context) {
this.applicationContext = context;
}
public synchronized void initialize() {
if (this.adapterInitialized) {
return;
}
this.dataHelper = new DataHelper(this.applicationContext);
this.adapterInitialized = true;
}
public synchronized void release() {
if (this.dataHelper != null) {
this.dataHelper.close();
this.dataHelper = null;
}
this.adapterInitialized = false;
}
public synchronized void insert(HistoryModule item) throws Exception {
if (!this.adapterInitialized) {
this.initialize();
}
SQLiteDatabase database = this.dataHelper.getWritableDatabase();
database.beginTransaction();
try {
int y, m, d, h, mi, s;
Calendar cal = Calendar.getInstance();
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DATE);
h = cal.get(Calendar.HOUR_OF_DAY);
mi = cal.get(Calendar.MINUTE);
s = cal.get(Calendar.SECOND);
ContentValues values = new ContentValues();
values.put(Tables.HistoryTable.NAME, item.getUserName());
values.put(Tables.HistoryTable.PHONEMUNBER,
item.getUserPhoneNumber());
values.put(Tables.HistoryTable.LOGTYPE, item.getLogType()
.toString());
values.put(Tables.HistoryTable.LONGITUDE,
String.valueOf(item.getLongitude()));
values.put(Tables.HistoryTable.LANGTITUDE,
String.valueOf(item.getLatitude()));
values.put(Tables.HistoryTable.DATE, y + "年" + m + "月" + d
+ "日" + h + "时" + mi + "分" + s + "秒");
long id = database.replace(Tables.HistoryTable.TABLE_NAME,
null, values);
// Validate root id.
if (id <= 0) {
throw new Exception("Failed to save History");
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
// private synchronized String getDateTime() {
// SimpleDateFormat dateFormat = new SimpleDateFormat(
// "yyyy-MM-dd HH:mm:ss", Locale.getDefault());
// Date date = new Date();
// return dateFormat.format(date);
// }
public synchronized long getCount() {
if (!this.adapterInitialized) {
this.initialize();
}
// Obtain total number of records in main table.
SQLiteDatabase database = this.dataHelper.getReadableDatabase();
long result = DatabaseUtils.queryNumEntries(database,
Tables.HistoryTable.TABLE_NAME);
return result;
}
public synchronized Vector<HistoryModule> getAll() {
if (!this.adapterInitialized) {
this.initialize();
}
Vector<HistoryModule> items = new Vector<HistoryModule>();
// Obtain database.
SQLiteDatabase database = this.dataHelper.getReadableDatabase();
// Select all data, order depending or specified sort order.
String where = Tables.HistoryTable._ID + " DESC";
Cursor reader = database.query(Tables.HistoryTable.TABLE_NAME,
null, null, null, null, null, where);
if (reader == null || reader.getCount() == 0) {
if (reader != null) {
reader.close();
}
return items;
}
int columnIdIndex = reader.getColumnIndex(Tables.HistoryTable._ID);
int columnNameIndex = reader
.getColumnIndex(Tables.HistoryTable.NAME);
int columnPhoneIndex = reader
.getColumnIndex(Tables.HistoryTable.PHONEMUNBER);
int columnTypeIndex = reader
.getColumnIndex(Tables.HistoryTable.LOGTYPE);
int columnLatIndex = reader
.getColumnIndex(Tables.HistoryTable.LANGTITUDE);
int columnLngIndex = reader
.getColumnIndex(Tables.HistoryTable.LONGITUDE);
int columnDateIndex = reader
.getColumnIndex(Tables.HistoryTable.DATE);
reader.moveToFirst();
while (!reader.isAfterLast()) {
HistoryModule item = new HistoryModule();
item.setID(reader.getLong(columnIdIndex));
item.setUserName(reader.getString(columnNameIndex));
item.setUserPhoneNumber(reader.getString(columnPhoneIndex));
item.setLongitude(Double.parseDouble(reader
.getString(columnLngIndex)));
item.setLatitude(Double.parseDouble(reader
.getString(columnLatIndex)));
LogType type;
if (reader.getString(columnTypeIndex).equals(
LogType.ALERT.toString())) {
type = LogType.ALERT;
} else {
type = LogType.LOCATE;
}
item.setLogType(type);
item.setmDate(reader.getString(columnDateIndex));
items.add(item);
reader.moveToNext();
}
reader.close();
return items;
}
public synchronized void removeAll() {
if (!this.adapterInitialized) {
this.initialize();
}
SQLiteDatabase database = this.dataHelper.getWritableDatabase();
database.beginTransaction();
try {
database.delete(Tables.HistoryTable.TABLE_NAME, null, null);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public synchronized boolean exists(HistoryModule item) throws Exception {
if (!this.adapterInitialized) {
this.initialize();
}
// Get original item Id first.
long recordId = this.getRecordId(item);
return recordId > 0;
}
public synchronized void remove(HistoryModule item) throws Exception {
if (!this.adapterInitialized) {
this.initialize();
}
long recordId = this.getRecordId(item);
SQLiteDatabase database = this.dataHelper.getReadableDatabase();
database.beginTransaction();
try {
String deleteWhere = Tables.HistoryTable._ID + " = ?";
String[] deleteArgs = new String[] { String.valueOf(recordId) };
database.delete(Tables.HistoryTable.TABLE_NAME, deleteWhere,
deleteArgs);
database.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
database.endTransaction();
}
}
public synchronized Vector<HistoryModule> getLatestRecords(int limit) {
if (!this.adapterInitialized) {
this.initialize();
}
Vector<HistoryModule> items = new Vector<HistoryModule>();
try {
// Obtain database.
SQLiteDatabase database = this.dataHelper.getReadableDatabase();
// Select recently data, order depending or specified sort
// order.
String where = Tables.HistoryTable.PHONEMUNBER + " DESC";
Cursor reader = database.query(Tables.HistoryTable.TABLE_NAME,
null, null, null, null, null, where,
"0, " + String.valueOf(limit));
if (reader == null || reader.getCount() == 0) {
if (reader != null) {
reader.close();
}
return items;
}
int columnIdIndex = reader
.getColumnIndex(Tables.HistoryTable._ID);
int columnNameIndex = reader
.getColumnIndex(Tables.HistoryTable.NAME);
int columnPhoneIndex = reader
.getColumnIndex(Tables.HistoryTable.PHONEMUNBER);
int columnTypeIndex = reader
.getColumnIndex(Tables.HistoryTable.LOGTYPE);
int columnLatIndex = reader
.getColumnIndex(Tables.HistoryTable.LANGTITUDE);
int columnLngIndex = reader
.getColumnIndex(Tables.HistoryTable.LONGITUDE);
int columnDateIndex = reader
.getColumnIndex(Tables.HistoryTable.DATE);
reader.moveToFirst();
while (!reader.isAfterLast()) {
HistoryModule item = new HistoryModule();
item.setID(reader.getLong(columnIdIndex));
item.setUserName(reader.getString(columnNameIndex));
item.setUserPhoneNumber(reader.getString(columnPhoneIndex));
item.setLongitude(Double.parseDouble(reader
.getString(columnLngIndex)));
item.setLatitude(Double.parseDouble(reader
.getString(columnLatIndex)));
LogType type;
if (reader.getString(columnTypeIndex).equals(
LogType.ALERT.toString())) {
type = LogType.ALERT;
} else {
type = LogType.LOCATE;
}
item.setLogType(type);
item.setmDate(reader.getString(columnDateIndex));
items.add(item);
reader.moveToNext();
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return items;
}
public synchronized Vector<HistoryModule> findMatches(String substring) {
Vector<HistoryModule> items = new Vector<HistoryModule>();
if (Utilities.isStringNullOrEmpty(substring)) {
return items;
}
if (!this.adapterInitialized) {
this.initialize();
}
SQLiteDatabase database = this.dataHelper.getReadableDatabase();
String where = "LOWER(" + Tables.HistoryTable.NAME + ") LIKE ?";
String[] args;
if (Data.AnyMatch) {
args = new String[] { "%" + substring.toLowerCase(Locale.US)
+ "%" };
} else {
args = new String[] { substring.toLowerCase(Locale.US) + "%" };
}
Cursor reader = database.query(Tables.HistoryTable.TABLE_NAME,
null, where, args, null, null,
Tables.HistoryTable.PHONEMUNBER + " DESC");
if (reader == null || reader.getCount() == 0) {
if (reader != null) {
reader.close();
}
return items;
}
int columnIdIndex = reader.getColumnIndex(Tables.HistoryTable._ID);
int columnNameIndex = reader
.getColumnIndex(Tables.HistoryTable.NAME);
int columnPhoneIndex = reader
.getColumnIndex(Tables.HistoryTable.PHONEMUNBER);
int columnTypeIndex = reader
.getColumnIndex(Tables.HistoryTable.LOGTYPE);
int columnLatIndex = reader
.getColumnIndex(Tables.HistoryTable.LANGTITUDE);
int columnLngIndex = reader
.getColumnIndex(Tables.HistoryTable.LONGITUDE);
int columnDateIndex = reader
.getColumnIndex(Tables.HistoryTable.DATE);
reader.moveToFirst();
while (!reader.isAfterLast()) {
HistoryModule item = new HistoryModule();
item.setID(reader.getLong(columnIdIndex));
item.setUserName(reader.getString(columnNameIndex));
item.setUserPhoneNumber(reader.getString(columnPhoneIndex));
item.setLongitude(Double.parseDouble(reader
.getString(columnLngIndex)));
item.setLatitude(Double.parseDouble(reader
.getString(columnLatIndex)));
LogType type;
if (reader.getString(columnTypeIndex).equals(
LogType.ALERT.toString())) {
type = LogType.ALERT;
} else {
type = LogType.LOCATE;
}
item.setLogType(type);
item.setmDate(reader.getString(columnDateIndex));
items.add(item);
reader.moveToNext();
}
reader.close();
return items;
}
private long getRecordId(HistoryModule item) throws Exception {
// Obtain item id first.
SQLiteDatabase database = this.dataHelper.getReadableDatabase();
String[] columns = new String[] { Tables.HistoryTable._ID };
// unique name match
final String where = Tables.HistoryTable.NAME + " = ?";
final String[] args = new String[] { String.valueOf(item
.getUserName()) };
// Select records.
Cursor reader = database.query(Tables.HistoryTable.TABLE_NAME,
columns, where, args, null, null, null);
// Skip it, nothing to remove.
if (reader == null || reader.getCount() == 0) {
if (reader != null) {
reader.close();
}
return 0;
}
// Check total number of records.
if (reader.getCount() > 1) {
reader.close();
throw new Exception(
"More than one record was found. Can't proceed.");
}
reader.moveToFirst();
int columnIndex = reader.getColumnIndex(Tables.HistoryTable._ID);
long recordId = reader.getLong(columnIndex);
reader.close();
if (recordId <= 0) {
throw new Exception("Record id is: " + recordId
+ ". Can't proceed.");
}
return recordId;
}
}
public static final String LOG_TAG = "AutoSuggestionHostory";
private static final long HISTORY_LIMIT = 1000;
private final Context applicationContext;
public HistoryDatabase(Context context) {
this.applicationContext = context;
}
public synchronized boolean addItem(HistoryModule item) {
Data adapter = new Data(this.applicationContext);
try {
adapter.initialize();
if (!Utilities.isStringNullOrEmpty(item.getUserPhoneNumber())
&& !Utilities
.isStringNullOrEmpty(item.getUserPhoneNumber())) {
adapter.insert(item);
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
adapter.release();
}
}
public synchronized long getCount() {
Data adapter = new Data(this.applicationContext);
long result = 0;
try {
adapter.initialize();
result = adapter.getCount();
} catch (Exception e) {
e.printStackTrace();
} finally {
adapter.release();
}
return result;
}
public synchronized Vector<HistoryModule> getAll() {
Data adapter = new Data(this.applicationContext);
try {
adapter.initialize();
return adapter.getAll();
} catch (SQLiteException sqlEx) {
// TODO: Find another way to deal with database lock, maybe
// semaphore with acquire/release.
sqlEx.printStackTrace();
return null;
} finally {
adapter.release();
}
}
public synchronized Vector<HistoryModule> getLatestRecords(int limit) {
Data adapter = new Data(this.applicationContext);
try {
adapter.initialize();
return adapter.getLatestRecords(limit);
} catch (SQLiteException sqlEx) {
// TODO: Find another way to deal with database lock, maybe
// semaphore with acquire/release.
sqlEx.printStackTrace();
return null;
} finally {
adapter.release();
}
}
public synchronized void removeAll() {
Data adapter = new Data(this.applicationContext);
try {
adapter.initialize();
adapter.removeAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
adapter.release();
}
}
public synchronized boolean exists(HistoryModule item) {
Data adapter = new Data(this.applicationContext);
try {
adapter.initialize();
return adapter.exists(item);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
adapter.release();
}
}
public synchronized void remove(HistoryModule item) {
Data adapter = new Data(this.applicationContext);
try {
adapter.initialize();
adapter.remove(item);
} catch (Exception e) {
e.printStackTrace();
} finally {
adapter.release();
}
}
public synchronized Vector<HistoryModule> findMatches(String substring) {
Data adapter = new Data(this.applicationContext);
try {
adapter.initialize();
return adapter.findMatches(substring);
} catch (Exception e) {
e.printStackTrace();
return new Vector<HistoryModule>();
} finally {
adapter.release();
}
}
public synchronized boolean canSave() {
Data adapter = new Data(this.applicationContext);
try {
adapter.initialize();
return adapter.getCount() < HISTORY_LIMIT;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
adapter.release();
}
}
}
|
apache-2.0
|
cictourgune/EmocionometroWeb
|
src/org/tourgune/apptrack/bean/Variable.java
|
2054
|
package org.tourgune.apptrack.bean;
/**
* AppTrack
*
* Created by CICtourGUNE on 10/04/13.
* Copyright (c) 2013 CICtourGUNE. All rights reserved.
*
* Bean de la tabla variables de la base de datos
*/
public class Variable {
private int idvariable;
private int idaplicacion;
private int idtipo;
private String nombrevariable;
private double max;
private double min;
private String fechadesde;
private String fechahasta;
private Boolean multiopcion;
private Boolean obligatorio;
private java.util.List<Opcion> opciones;
public java.util.List<Opcion> getOpciones() {
return opciones;
}
public void setOpciones(java.util.List<Opcion> opciones) {
this.opciones = opciones;
}
public int getIdvariable() {
return idvariable;
}
public void setIdvariable(int idvariable) {
this.idvariable = idvariable;
}
public int getIdaplicacion() {
return idaplicacion;
}
public void setIdaplicacion(int idaplicacion) {
this.idaplicacion = idaplicacion;
}
public int getIdtipo() {
return idtipo;
}
public void setIdtipo(int idtipo) {
this.idtipo = idtipo;
}
public String getNombrevariable() {
return nombrevariable;
}
public void setNombrevariable(String nombrevariable) {
this.nombrevariable = nombrevariable;
}
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
public double getMin() {
return min;
}
public void setMin(Double min) {
this.min = min;
}
public String getFechadesde() {
return fechadesde;
}
public void setFechadesde(String fechadesde) {
this.fechadesde = fechadesde;
}
public String getFechahasta() {
return fechahasta;
}
public void setFechahasta(String fechahasta) {
this.fechahasta = fechahasta;
}
public Boolean getMultiopcion() {
return multiopcion;
}
public void setMultiopcion(Boolean multiopcion) {
this.multiopcion = multiopcion;
}
public Boolean getObligatorio() {
return obligatorio;
}
public void setObligatorio(Boolean obligatorio) {
this.obligatorio = obligatorio;
}
}
|
apache-2.0
|
googleapis/java-dialogflow
|
proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/BatchUpdateEntityTypesResponse.java
|
33021
|
/*
* Copyright 2020 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
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2beta1/entity_type.proto
package com.google.cloud.dialogflow.v2beta1;
/**
*
*
* <pre>
* The response message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse}
*/
public final class BatchUpdateEntityTypesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse)
BatchUpdateEntityTypesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use BatchUpdateEntityTypesResponse.newBuilder() to construct.
private BatchUpdateEntityTypesResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BatchUpdateEntityTypesResponse() {
entityTypes_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new BatchUpdateEntityTypesResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private BatchUpdateEntityTypesResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
entityTypes_ =
new java.util.ArrayList<com.google.cloud.dialogflow.v2beta1.EntityType>();
mutable_bitField0_ |= 0x00000001;
}
entityTypes_.add(
input.readMessage(
com.google.cloud.dialogflow.v2beta1.EntityType.parser(), extensionRegistry));
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
entityTypes_ = java.util.Collections.unmodifiableList(entityTypes_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2beta1.EntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2beta1.EntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.class,
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.Builder.class);
}
public static final int ENTITY_TYPES_FIELD_NUMBER = 1;
private java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType> entityTypes_;
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType> getEntityTypesList() {
return entityTypes_;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder>
getEntityTypesOrBuilderList() {
return entityTypes_;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
@java.lang.Override
public int getEntityTypesCount() {
return entityTypes_.size();
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.EntityType getEntityTypes(int index) {
return entityTypes_.get(index);
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder getEntityTypesOrBuilder(
int index) {
return entityTypes_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < entityTypes_.size(); i++) {
output.writeMessage(1, entityTypes_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < entityTypes_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, entityTypes_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse other =
(com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) obj;
if (!getEntityTypesList().equals(other.getEntityTypesList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getEntityTypesCount() > 0) {
hash = (37 * hash) + ENTITY_TYPES_FIELD_NUMBER;
hash = (53 * hash) + getEntityTypesList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse)
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2beta1.EntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2beta1.EntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.class,
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.Builder.class);
}
// Construct using
// com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getEntityTypesFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (entityTypesBuilder_ == null) {
entityTypes_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
entityTypesBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2beta1.EntityTypeProto
.internal_static_google_cloud_dialogflow_v2beta1_BatchUpdateEntityTypesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse
getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse build() {
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse buildPartial() {
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse result =
new com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse(this);
int from_bitField0_ = bitField0_;
if (entityTypesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
entityTypes_ = java.util.Collections.unmodifiableList(entityTypes_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.entityTypes_ = entityTypes_;
} else {
result.entityTypes_ = entityTypesBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) {
return mergeFrom(
(com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse other) {
if (other
== com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse
.getDefaultInstance()) return this;
if (entityTypesBuilder_ == null) {
if (!other.entityTypes_.isEmpty()) {
if (entityTypes_.isEmpty()) {
entityTypes_ = other.entityTypes_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureEntityTypesIsMutable();
entityTypes_.addAll(other.entityTypes_);
}
onChanged();
}
} else {
if (!other.entityTypes_.isEmpty()) {
if (entityTypesBuilder_.isEmpty()) {
entityTypesBuilder_.dispose();
entityTypesBuilder_ = null;
entityTypes_ = other.entityTypes_;
bitField0_ = (bitField0_ & ~0x00000001);
entityTypesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getEntityTypesFieldBuilder()
: null;
} else {
entityTypesBuilder_.addAllMessages(other.entityTypes_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType> entityTypes_ =
java.util.Collections.emptyList();
private void ensureEntityTypesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
entityTypes_ =
new java.util.ArrayList<com.google.cloud.dialogflow.v2beta1.EntityType>(entityTypes_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.EntityType,
com.google.cloud.dialogflow.v2beta1.EntityType.Builder,
com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder>
entityTypesBuilder_;
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType> getEntityTypesList() {
if (entityTypesBuilder_ == null) {
return java.util.Collections.unmodifiableList(entityTypes_);
} else {
return entityTypesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public int getEntityTypesCount() {
if (entityTypesBuilder_ == null) {
return entityTypes_.size();
} else {
return entityTypesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.EntityType getEntityTypes(int index) {
if (entityTypesBuilder_ == null) {
return entityTypes_.get(index);
} else {
return entityTypesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder setEntityTypes(int index, com.google.cloud.dialogflow.v2beta1.EntityType value) {
if (entityTypesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntityTypesIsMutable();
entityTypes_.set(index, value);
onChanged();
} else {
entityTypesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder setEntityTypes(
int index, com.google.cloud.dialogflow.v2beta1.EntityType.Builder builderForValue) {
if (entityTypesBuilder_ == null) {
ensureEntityTypesIsMutable();
entityTypes_.set(index, builderForValue.build());
onChanged();
} else {
entityTypesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder addEntityTypes(com.google.cloud.dialogflow.v2beta1.EntityType value) {
if (entityTypesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntityTypesIsMutable();
entityTypes_.add(value);
onChanged();
} else {
entityTypesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder addEntityTypes(int index, com.google.cloud.dialogflow.v2beta1.EntityType value) {
if (entityTypesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntityTypesIsMutable();
entityTypes_.add(index, value);
onChanged();
} else {
entityTypesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder addEntityTypes(
com.google.cloud.dialogflow.v2beta1.EntityType.Builder builderForValue) {
if (entityTypesBuilder_ == null) {
ensureEntityTypesIsMutable();
entityTypes_.add(builderForValue.build());
onChanged();
} else {
entityTypesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder addEntityTypes(
int index, com.google.cloud.dialogflow.v2beta1.EntityType.Builder builderForValue) {
if (entityTypesBuilder_ == null) {
ensureEntityTypesIsMutable();
entityTypes_.add(index, builderForValue.build());
onChanged();
} else {
entityTypesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder addAllEntityTypes(
java.lang.Iterable<? extends com.google.cloud.dialogflow.v2beta1.EntityType> values) {
if (entityTypesBuilder_ == null) {
ensureEntityTypesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, entityTypes_);
onChanged();
} else {
entityTypesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder clearEntityTypes() {
if (entityTypesBuilder_ == null) {
entityTypes_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
entityTypesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public Builder removeEntityTypes(int index) {
if (entityTypesBuilder_ == null) {
ensureEntityTypesIsMutable();
entityTypes_.remove(index);
onChanged();
} else {
entityTypesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.EntityType.Builder getEntityTypesBuilder(int index) {
return getEntityTypesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder getEntityTypesOrBuilder(
int index) {
if (entityTypesBuilder_ == null) {
return entityTypes_.get(index);
} else {
return entityTypesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder>
getEntityTypesOrBuilderList() {
if (entityTypesBuilder_ != null) {
return entityTypesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(entityTypes_);
}
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.EntityType.Builder addEntityTypesBuilder() {
return getEntityTypesFieldBuilder()
.addBuilder(com.google.cloud.dialogflow.v2beta1.EntityType.getDefaultInstance());
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public com.google.cloud.dialogflow.v2beta1.EntityType.Builder addEntityTypesBuilder(int index) {
return getEntityTypesFieldBuilder()
.addBuilder(index, com.google.cloud.dialogflow.v2beta1.EntityType.getDefaultInstance());
}
/**
*
*
* <pre>
* The collection of updated or created entity types.
* </pre>
*
* <code>repeated .google.cloud.dialogflow.v2beta1.EntityType entity_types = 1;</code>
*/
public java.util.List<com.google.cloud.dialogflow.v2beta1.EntityType.Builder>
getEntityTypesBuilderList() {
return getEntityTypesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.EntityType,
com.google.cloud.dialogflow.v2beta1.EntityType.Builder,
com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder>
getEntityTypesFieldBuilder() {
if (entityTypesBuilder_ == null) {
entityTypesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.EntityType,
com.google.cloud.dialogflow.v2beta1.EntityType.Builder,
com.google.cloud.dialogflow.v2beta1.EntityTypeOrBuilder>(
entityTypes_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
entityTypes_ = null;
}
return entityTypesBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse)
private static final com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse();
}
public static com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BatchUpdateEntityTypesResponse> PARSER =
new com.google.protobuf.AbstractParser<BatchUpdateEntityTypesResponse>() {
@java.lang.Override
public BatchUpdateEntityTypesResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new BatchUpdateEntityTypesResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<BatchUpdateEntityTypesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BatchUpdateEntityTypesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.