text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* Copyright (c) 2014, The Linux Foundation. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/bitops.h>
#include <linux/regmap.h>
#include <linux/export.h>
#include "clk-regmap-mux.h"
static inline struct clk_regmap_mux *to_clk_regmap_mux(struct clk_hw *hw)
{
return container_of(to_clk_regmap(hw), struct clk_regmap_mux, clkr);
}
static u8 mux_get_parent(struct clk_hw *hw)
{
struct clk_regmap_mux *mux = to_clk_regmap_mux(hw);
struct clk_regmap *clkr = to_clk_regmap(hw);
unsigned int mask = GENMASK(mux->width - 1, 0);
unsigned int val;
regmap_read(clkr->regmap, mux->reg, &val);
val >>= mux->shift;
val &= mask;
if (mux->parent_map)
return qcom_find_src_index(hw, mux->parent_map, val);
return val;
}
static int mux_set_parent(struct clk_hw *hw, u8 index)
{
struct clk_regmap_mux *mux = to_clk_regmap_mux(hw);
struct clk_regmap *clkr = to_clk_regmap(hw);
unsigned int mask = GENMASK(mux->width + mux->shift - 1, mux->shift);
unsigned int val;
if (mux->parent_map)
index = mux->parent_map[index].cfg;
val = index;
val <<= mux->shift;
return regmap_update_bits(clkr->regmap, mux->reg, mask, val);
}
const struct clk_ops clk_regmap_mux_closest_ops = {
.get_parent = mux_get_parent,
.set_parent = mux_set_parent,
.determine_rate = __clk_mux_determine_rate_closest,
};
EXPORT_SYMBOL_GPL(clk_regmap_mux_closest_ops);
| {
"pile_set_name": "Github"
} |
FROM nodesource/precise-base
MAINTAINER William Blankenship <[email protected]>
RUN curl https://deb.nodesource.com/node_6.x/pool/main/n/nodejs/nodejs_6.7.0-1nodesource1~precise1_amd64.deb > node.deb \
&& dpkg -i node.deb \
&& rm node.deb
RUN npm install -g pangyp\
&& ln -s $(which pangyp) $(dirname $(which pangyp))/node-gyp\
&& npm cache clear\
&& node-gyp configure || echo ""
ENV NODE_ENV production
WORKDIR /usr/src/app
CMD ["npm","start"]
RUN apt-get update \
&& apt-get upgrade -y --force-yes \
&& rm -rf /var/lib/apt/lists/*; | {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 537addb2274f5ac4b8c91f451066f83b
folderAsset: yes
timeCreated: 1509230184
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
@media (max-width: $screen-tablet) {
body:not([class="login"]) {
.container-fluid {
padding-left: 0px;
aside ul li.active .list-selected {
display: none;
}
}
}
}
//icons in alerts
@media (max-width: $screen-sm-max) {
.alert-icon {
.fa {
//.fa-lg;
font-size: 1.3em;
}
}
.login-picture {
width: 180px;
margin: 0 0 3em 0;
}
}
@media (min-width: $screen-sm-min) {
.alert-icon {
.fa {
//.fa-2x;
font-size: 2em;
}
}
}
@media (min-width: $screen-md-min) {
.alert-icon {
.fa {
//.fa-3x;
font-size: 3em
}
}
}
@media (max-width: $screen-sm-max) {
body:not([class*="login"]) footer {
.aside-footer {
display: none;
}
.container-footer {
margin-left: 0px;
}
}
}
| {
"pile_set_name": "Github"
} |
#===========================================================
# CoolReader3
# Key to Command map file
#
# all identifiers should be declared in keydefs.ini
#===========================================================
#main viewer window, commands possible to use in override
[main-override-commands]
#main viewer window, keys possible to override
[main-override-keys]
# key translation map for different screen orientations
#[key-substitution-90]
#[key-substitution-180]
#[key-substitution-270]
# main viewer window
[main]
# possible actions (not all of them will work for PB):
# MCMD_QUIT
# MCMD_MAIN_MENU
# MCMD_SETTINGS_FONTSIZE
# MCMD_SETTINGS_ORIENTATION
# MCMD_SETTINGS
# MCMD_RECENT_BOOK_LIST
# MCMD_OPEN_RECENT_BOOK
# MCMD_SWITCH_TO_RECENT_BOOK
# MCMD_ABOUT
# MCMD_CITE
# MCMD_HELP
# document scope commands DCMD...
KEY_BACK = MCMD_QUIT
KEY_LEFT = DCMD_PAGEUP
#KEY_LEFT = PB_CMD_UPDATE_WINDOW
KEY_PREV = DCMD_PAGEUP
KEY_PREV, LONG = PB_CMD_PAGEUP_REPEAT, 10
KEY_RIGHT = DCMD_PAGEDOWN
KEY_NEXT = DCMD_PAGEDOWN
KEY_NEXT, LONG = PB_CMD_PAGEDOWN_REPEAT, 10
KEY_OK = PB_QUICK_MENU
KEY_HOME = MCMD_MAIN_MENU
KEY_OK, LONG = MCMD_MAIN_MENU
KEY_UP = DCMD_ZOOM_IN
KEY_DOWN = DCMD_ZOOM_OUT
KEY_PREV, LONG = MCMD_QUIT
[menu]
KEY_BACK = MCMD_OK
KEY_BACK, LONG = MCMD_CANCEL
KEY_OK = MCMD_SELECT
KEY_OK, LONG = MCMD_SELECT_LONG
KEY_DOWN = MCMD_NEXT_ITEM
KEY_UP = MCMD_PREV_ITEM
KEY_RIGHT = MCMD_NEXT_PAGE
KEY_LEFT = MCMD_PREV_PAGE
KEY_NEXT = MCMD_PREV_ITEM
KEY_PREV = MCMD_NEXT_ITEM
KEY_NEXT2 = MCMD_PREV_PAGE
KEY_PREV2 = MCMD_NEXT_PAGE
[menu10]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_OK
KEY_UP = MCMD_SELECT_1
KEY_RIGHT = MCMD_SELECT_2
KEY_DOWN = MCMD_SELECT_3
KEY_LEFT = MCMD_SELECT_4
KEY_UP, LONG = MCMD_SELECT_5
KEY_RIGHT, LONG = MCMD_SELECT_6
KEY_DOWN, LONG = MCMD_SELECT_7
KEY_LEFT, LONG = MCMD_SELECT_8
KEY_HOME = MCMD_SELECT_9
KEY_HOME, LONG = MCMD_SELECT_0
KEY_NEXT = MCMD_SCROLL_FORWARD
KEY_PREV = MCMD_SCROLL_BACK
KEY_NEXT, LONG = MCMD_SCROLL_FORWARD_LONG
KEY_PREV, LONG = MCMD_SCROLL_BACK_LONG
[cite]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_OK
KEY_OK, LONG = MCMD_CANCEL
KEY_NEXT = MCMD_SCROLL_BACK
KEY_PREV = MCMD_SCROLL_FORWARD
KEY_UP = MCMD_SCROLL_BACK
KEY_DOWN = MCMD_SCROLL_FORWARD
KEY_RIGHT = PB_CMD_RIGHT
KEY_LEFT = PB_CMD_LEFT
KEY_NEXT, LONG = MCMD_SCROLL_BACK_LONG
KEY_PREV, LONG = MCMD_SCROLL_FORWARD_LONG
[dialog]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_OK
KEY_NEXT = MCMD_SCROLL_BACK
KEY_PREV = MCMD_SCROLL_FORWARD
KEY_UP = MCMD_SCROLL_BACK
KEY_DOWN = MCMD_SCROLL_FORWARD
KEY_RIGHT = MCMD_SCROLL_FORWARD
KEY_LEFT = MCMD_SCROLL_BACK
KEY_NEXT, LONG = MCMD_SCROLL_BACK_LONG
KEY_PREV, LONG = MCMD_SCROLL_FORWARD_LONG
[vkeyboard]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_OK
[txkeyboard]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_OK
KEY_NEXT = MCMD_SCROLL_BACK
KEY_PREV = MCMD_SCROLL_FORWARD
# custom document view dialog
[browse]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_OK
KEY_RIGHT = DCMD_PAGEDOWN
KEY_LEFT = DCMD_PAGEUP
KEY_NEXT = DCMD_PAGEDOWN
KEY_PREV = DCMD_PAGEUP
KEY_UP = DCMD_ZOOM_IN
KEY_DOWN = DCMD_ZOOM_OUT
[bookmarks]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_SELECT
KEY_OK, LONG = MCMD_SELECT_LONG
KEY_HOME = MCMD_SELECT_LONG
KEY_DOWN = MCMD_NEXT_ITEM
KEY_UP = MCMD_PREV_ITEM
KEY_RIGHT = MCMD_NEXT_PAGE
KEY_LEFT = MCMD_PREV_PAGE
KEY_NEXT = MCMD_NEXT_MODE
KEY_PREV = MCMD_PREV_MODE
KEY_NEXT2 = MCMD_PREV_PAGE
KEY_PREV2 = MCMD_NEXT_PAGE
KEY_DELETE = PB_CMD_BOOKMARK_REMOVE
# this is Main Menu definition
# place items for main menu here
# left side will be ignored
[mainMenuItems]
1 = PB_CMD_MAIN_MENU
2 = MCMD_ABOUT
3 = MCMD_RECENT_BOOK_LIST
4 = MCMD_CITES_LIST
5 = MCMD_CITE
6 = DCMD_SAVE_HISTORY
7 = DCMD_SAVE_TO_CACHE
8 = MCMD_HELP
9 = MCMD_HELP_KEYS
# this is Quick Menu definition
# place items for main menu here
# left side will be ignored
[quickMenuItems]
1 = MCMD_GO_PAGE
2 = MCMD_QUIT
3 = MCMD_SEARCH
4 = MCMD_BOOKMARK_LIST_GO_MODE
5 = PB_CMD_NONE
6 = PB_CMD_ROTATE
7 = MCMD_DICT
8 = PB_CMD_CONTENTS
9 = MCMD_SETTINGS
[txkeyboard]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_OK
KEY_UP = PB_CMD_UP
KEY_DOWN = PB_CMD_DOWN
KEY_LEFT = PB_CMD_LEFT
KEY_RIGHT = PB_CMD_RIGHT
[dict]
KEY_BACK = MCMD_CANCEL
KEY_OK = MCMD_OK
KEY_LEFT = PB_CMD_LEFT
KEY_RIGHT = PB_CMD_RIGHT
KEY_UP = PB_CMD_UP
KEY_DOWN = PB_CMD_DOWN
KEY_NEXT = DCMD_PAGEDOWN
KEY_PREV = DCMD_PAGEUP
KEY_NEXT, LONG = DCMD_PAGEDOWN, 10
KEY_PREV, LONG = DCMD_PAGEUP, 10
KEY_LEFT, LONG = PB_CMD_LEFT
KEY_RIGHT, LONG = PB_CMD_RIGHT
KEY_UP, LONG = PB_CMD_UP, 5
KEY_DOWN, LONG = PB_CMD_DOWN, 5
| {
"pile_set_name": "Github"
} |
import Foundation
import Ice
do {
let communicator = try Ice.initialize(CommandLine.arguments)
defer {
communicator.destroy()
}
let hello = try uncheckedCast(prx: communicator.stringToProxy("hello:default -h localhost -p 10000")!,
type: HelloPrx.self)
try hello.sayHello()
} catch {
print("Error: \(error)\n")
exit(1)
}
| {
"pile_set_name": "Github"
} |
sha256:3c2a19b979436e3b884e977dd5f7f9ab5646197edb61efcf9443898c739f4531
| {
"pile_set_name": "Github"
} |
#ifndef MDAL_CONFIG_HPP
#define MDAL_CONFIG_HPP
#cmakedefine MDAL_VERSION
#cmakedefine HAVE_HDF5
#cmakedefine HAVE_GDAL
#cmakedefine HAVE_NETCDF
#cmakedefine HAVE_XML
#cmakedefine HAVE_SQLITE3
#endif // MDAL_CONFIG_HPP
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xalan.internal.xsltc.compiler.util;
import java.util.ListResourceBundle;
/**
* @author Morten Jorgensen
*/
public class ErrorMessages_ja extends ListResourceBundle {
/*
* XSLTC compile-time error messages.
*
* General notes to translators and definitions:
*
* 1) XSLTC is the name of the product. It is an acronym for "XSLT Compiler".
* XSLT is an acronym for "XML Stylesheet Language: Transformations".
*
* 2) A stylesheet is a description of how to transform an input XML document
* into a resultant XML document (or HTML document or text). The
* stylesheet itself is described in the form of an XML document.
*
* 3) A template is a component of a stylesheet that is used to match a
* particular portion of an input document and specifies the form of the
* corresponding portion of the output document.
*
* 4) An axis is a particular "dimension" in a tree representation of an XML
* document; the nodes in the tree are divided along different axes.
* Traversing the "child" axis, for instance, means that the program
* would visit each child of a particular node; traversing the "descendant"
* axis means that the program would visit the child nodes of a particular
* node, their children, and so on until the leaf nodes of the tree are
* reached.
*
* 5) An iterator is an object that traverses nodes in a tree along a
* particular axis, one at a time.
*
* 6) An element is a mark-up tag in an XML document; an attribute is a
* modifier on the tag. For example, in <elem attr='val' attr2='val2'>
* "elem" is an element name, "attr" and "attr2" are attribute names with
* the values "val" and "val2", respectively.
*
* 7) A namespace declaration is a special attribute that is used to associate
* a prefix with a URI (the namespace). The meanings of element names and
* attribute names that use that prefix are defined with respect to that
* namespace.
*
* 8) DOM is an acronym for Document Object Model. It is a tree
* representation of an XML document.
*
* SAX is an acronym for the Simple API for XML processing. It is an API
* used inform an XML processor (in this case XSLTC) of the structure and
* content of an XML document.
*
* Input to the stylesheet processor can come from an XML parser in the
* form of a DOM tree or through the SAX API.
*
* 9) DTD is a document type declaration. It is a way of specifying the
* grammar for an XML file, the names and types of elements, attributes,
* etc.
*
* 10) XPath is a specification that describes a notation for identifying
* nodes in a tree-structured representation of an XML document. An
* instance of that notation is referred to as an XPath expression.
*
* 11) Translet is an invented term that refers to the class file that contains
* the compiled form of a stylesheet.
*/
// These message should be read from a locale-specific resource bundle
/** Get the lookup table for error messages.
*
* @return The message lookup table.
*/
public Object[][] getContents()
{
return new Object[][] {
{ErrorMsg.MULTIPLE_STYLESHEET_ERR,
"\u540C\u3058\u30D5\u30A1\u30A4\u30EB\u306B\u8907\u6570\u306E\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u304C\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002"},
/*
* Note to translators: The substitution text is the name of a
* template. The same name was used on two different templates in the
* same stylesheet.
*/
{ErrorMsg.TEMPLATE_REDEF_ERR,
"\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8''{0}''\u306F\u3053\u306E\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u5185\u3067\u3059\u3067\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002"},
/*
* Note to translators: The substitution text is the name of a
* template. A reference to the template name was encountered, but the
* template is undefined.
*/
{ErrorMsg.TEMPLATE_UNDEF_ERR,
"\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8''{0}''\u306F\u3053\u306E\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u5185\u3067\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The substitution text is the name of a variable
* that was defined more than once.
*/
{ErrorMsg.VARIABLE_REDEF_ERR,
"\u5909\u6570''{0}''\u306F\u540C\u3058\u30B9\u30B3\u30FC\u30D7\u5185\u3067\u8907\u6570\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002"},
/*
* Note to translators: The substitution text is the name of a variable
* or parameter. A reference to the variable or parameter was found,
* but it was never defined.
*/
{ErrorMsg.VARIABLE_UNDEF_ERR,
"\u5909\u6570\u307E\u305F\u306F\u30D1\u30E9\u30E1\u30FC\u30BF''{0}''\u304C\u672A\u5B9A\u7FA9\u3067\u3059\u3002"},
/*
* Note to translators: The word "class" here refers to a Java class.
* Processing the stylesheet required a class to be loaded, but it could
* not be found. The substitution text is the name of the class.
*/
{ErrorMsg.CLASS_NOT_FOUND_ERR,
"\u30AF\u30E9\u30B9''{0}''\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The word "method" here refers to a Java method.
* Processing the stylesheet required a reference to the method named by
* the substitution text, but it could not be found. "public" is the
* Java keyword.
*/
{ErrorMsg.METHOD_NOT_FOUND_ERR,
"\u5916\u90E8\u30E1\u30BD\u30C3\u30C9''{0}''\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093(public\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059)\u3002"},
/*
* Note to translators: The word "method" here refers to a Java method.
* Processing the stylesheet required a reference to the method named by
* the substitution text, but no method with the required types of
* arguments or return type could be found.
*/
{ErrorMsg.ARGUMENT_CONVERSION_ERR,
"\u30E1\u30BD\u30C3\u30C9''{0}''\u306E\u547C\u51FA\u3057\u306E\u5F15\u6570\u30BF\u30A4\u30D7\u307E\u305F\u306F\u623B\u308A\u578B\u3092\u5909\u63DB\u3067\u304D\u307E\u305B\u3093"},
/*
* Note to translators: The file or URI named in the substitution text
* is missing.
*/
{ErrorMsg.FILE_NOT_FOUND_ERR,
"\u30D5\u30A1\u30A4\u30EB\u307E\u305F\u306FURI ''{0}''\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: This message is displayed when the URI
* mentioned in the substitution text is not well-formed syntactically.
*/
{ErrorMsg.INVALID_URI_ERR,
"URI ''{0}''\u304C\u7121\u52B9\u3067\u3059\u3002"},
/*
* Note to translators: This message is displayed when the URI
* mentioned in the substitution text is not well-formed syntactically.
*/
{ErrorMsg.CATALOG_EXCEPTION,
"JAXP08090001: CatalogResolver\u306F\u30AB\u30BF\u30ED\u30B0\"{0}\"\u3067\u6709\u52B9\u3067\u3059\u304C\u3001CatalogException\u304C\u8FD4\u3055\u308C\u307E\u3059\u3002"},
/*
* Note to translators: The file or URI named in the substitution text
* exists but could not be opened.
*/
{ErrorMsg.FILE_ACCESS_ERR,
"\u30D5\u30A1\u30A4\u30EB\u307E\u305F\u306FURI ''{0}''\u3092\u958B\u304F\u3053\u3068\u304C\u3067\u304D\u307E\u305B\u3093\u3002"},
/*
* Note to translators: <xsl:stylesheet> and <xsl:transform> are
* keywords that should not be translated.
*/
{ErrorMsg.MISSING_ROOT_ERR,
"<xsl:stylesheet>\u307E\u305F\u306F<xsl:transform>\u306E\u8981\u7D20\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The stylesheet contained a reference to a
* namespace prefix that was undefined. The value of the substitution
* text is the name of the prefix.
*/
{ErrorMsg.NAMESPACE_UNDEF_ERR,
"\u30CD\u30FC\u30E0\u30B9\u30DA\u30FC\u30B9\u306E\u63A5\u982D\u8F9E''{0}''\u306F\u5BA3\u8A00\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The Java function named in the stylesheet could
* not be found.
*/
{ErrorMsg.FUNCTION_RESOLVE_ERR,
"\u95A2\u6570''{0}''\u306E\u547C\u51FA\u3057\u3092\u89E3\u6C7A\u3067\u304D\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The substitution text is the name of a
* function. A literal string here means a constant string value.
*/
{ErrorMsg.NEED_LITERAL_ERR,
"''{0}''\u3078\u306E\u5F15\u6570\u306F\u30EA\u30C6\u30E9\u30EB\u6587\u5B57\u5217\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: This message indicates there was a syntactic
* error in the form of an XPath expression. The substitution text is
* the expression.
*/
{ErrorMsg.XPATH_PARSER_ERR,
"XPath\u5F0F''{0}''\u306E\u89E3\u6790\u4E2D\u306B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002"},
/*
* Note to translators: An element in the stylesheet requires a
* particular attribute named by the substitution text, but that
* attribute was not specified in the stylesheet.
*/
{ErrorMsg.REQUIRED_ATTR_ERR,
"\u5FC5\u9808\u5C5E\u6027''{0}''\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: This message indicates that a character not
* permitted in an XPath expression was encountered. The substitution
* text is the offending character.
*/
{ErrorMsg.ILLEGAL_CHAR_ERR,
"XPath\u5F0F\u306E\u6587\u5B57''{0}''\u306F\u7121\u52B9\u3067\u3059\u3002"},
/*
* Note to translators: A processing instruction is a mark-up item in
* an XML document that request some behaviour of an XML processor. The
* form of the name of was invalid in this case, and the substitution
* text is the name.
*/
{ErrorMsg.ILLEGAL_PI_ERR,
"\u51E6\u7406\u547D\u4EE4\u306E\u540D\u524D''{0}''\u306F\u7121\u52B9\u3067\u3059\u3002"},
/*
* Note to translators: This message is reported if the stylesheet
* being processed attempted to construct an XML document with an
* attribute in a place other than on an element. The substitution text
* specifies the name of the attribute.
*/
{ErrorMsg.STRAY_ATTRIBUTE_ERR,
"\u5C5E\u6027''{0}''\u304C\u8981\u7D20\u306E\u5916\u5074\u306B\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: An attribute that wasn't recognized was
* specified on an element in the stylesheet. The attribute is named
* by the substitution
* text.
*/
{ErrorMsg.ILLEGAL_ATTRIBUTE_ERR,
"\u4E0D\u6B63\u306A\u5C5E\u6027''{0}''\u3067\u3059\u3002"},
/*
* Note to translators: "import" and "include" are keywords that should
* not be translated. This messages indicates that the stylesheet
* named in the substitution text imported or included itself either
* directly or indirectly.
*/
{ErrorMsg.CIRCULAR_INCLUDE_ERR,
"\u30A4\u30F3\u30DD\u30FC\u30C8\u307E\u305F\u306F\u30A4\u30F3\u30AF\u30EB\u30FC\u30C9\u304C\u5FAA\u74B0\u3057\u3066\u3044\u307E\u3059\u3002\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8''{0}''\u306F\u3059\u3067\u306B\u30ED\u30FC\u30C9\u3055\u308C\u3066\u3044\u307E\u3059\u3002"},
/*
* Note to translators: "xsl:import" and "xsl:include" are keywords that
* should not be translated.
*/
{ErrorMsg.IMPORT_PRECEDE_OTHERS_ERR,
"xsl:import\u8981\u7D20\u306E\u5B50\u306F\u3001xsl:stylesheet\u8981\u7D20\u306E\u4ED6\u306E\u3059\u3079\u3066\u306E\u8981\u7D20\u306E\u5B50(\u3059\u3079\u3066\u306Exsl:include\u8981\u7D20\u306E\u5B50\u3092\u542B\u3080)\u3088\u308A\u524D\u306B\u7F6E\u304F\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: A result-tree fragment is a portion of a
* resulting XML document represented as a tree. "<xsl:sort>" is a
* keyword and should not be translated.
*/
{ErrorMsg.RESULT_TREE_SORT_ERR,
"\u7D50\u679C\u30C4\u30EA\u30FC\u30FB\u30D5\u30E9\u30B0\u30E1\u30F3\u30C8\u306F\u30BD\u30FC\u30C8\u3067\u304D\u307E\u305B\u3093(<xsl:sort>\u8981\u7D20\u306F\u7121\u8996\u3055\u308C\u307E\u3059)\u3002\u7D50\u679C\u30C4\u30EA\u30FC\u3092\u4F5C\u6210\u3059\u308B\u3068\u304D\u306B\u30CE\u30FC\u30C9\u3092\u30BD\u30FC\u30C8\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: A name can be given to a particular style to be
* used to format decimal values. The substitution text gives the name
* of such a style for which more than one declaration was encountered.
*/
{ErrorMsg.SYMBOLS_REDEF_ERR,
"10\u9032\u6570\u30D5\u30A9\u30FC\u30DE\u30C3\u30C8''{0}''\u306F\u3059\u3067\u306B\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u3059\u3002"},
/*
* Note to translators: The stylesheet version named in the
* substitution text is not supported.
*/
{ErrorMsg.XSL_VERSION_ERR,
"XSL\u30D0\u30FC\u30B8\u30E7\u30F3''{0}''\u306FXSLTC\u306B\u3088\u3063\u3066\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The definitions of one or more variables or
* parameters depend on one another.
*/
{ErrorMsg.CIRCULAR_VARIABLE_ERR,
"''{0}''\u5185\u306E\u5909\u6570\u53C2\u7167\u307E\u305F\u306F\u30D1\u30E9\u30E1\u30FC\u30BF\u53C2\u7167\u304C\u5FAA\u74B0\u3057\u3066\u3044\u307E\u3059\u3002"},
/*
* Note to translators: The operator in an expresion with two operands was
* not recognized.
*/
{ErrorMsg.ILLEGAL_BINARY_OP_ERR,
"2\u9032\u6570\u306E\u5F0F\u306B\u5BFE\u3059\u308B\u4E0D\u660E\u306A\u6F14\u7B97\u5B50\u3067\u3059\u3002"},
/*
* Note to translators: This message is produced if a reference to a
* function has too many or too few arguments.
*/
{ErrorMsg.ILLEGAL_ARG_ERR,
"\u95A2\u6570\u547C\u51FA\u3057\u306E\u5F15\u6570\u304C\u4E0D\u6B63\u3067\u3059\u3002"},
/*
* Note to translators: "document()" is the name of function and must
* not be translated. A node-set is a set of the nodes in the tree
* representation of an XML document.
*/
{ErrorMsg.DOCUMENT_ARG_ERR,
"document()\u95A2\u6570\u306E2\u756A\u76EE\u306E\u5F15\u6570\u306F\u30CE\u30FC\u30C9\u30BB\u30C3\u30C8\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: "<xsl:when>" and "<xsl:choose>" are keywords
* and should not be translated. This message describes a syntax error
* in the stylesheet.
*/
{ErrorMsg.MISSING_WHEN_ERR,
"<xsl:choose>\u5185\u306B\u306F\u5C11\u306A\u304F\u3068\u30821\u3064\u306E<xsl:when>\u8981\u7D20\u304C\u5FC5\u8981\u3067\u3059\u3002"},
/*
* Note to translators: "<xsl:otherwise>" and "<xsl:choose>" are
* keywords and should not be translated. This message describes a
* syntax error in the stylesheet.
*/
{ErrorMsg.MULTIPLE_OTHERWISE_ERR,
"<xsl:choose>\u5185\u3067\u306F1\u3064\u306E<xsl:otherwise>\u8981\u7D20\u306E\u307F\u304C\u8A31\u53EF\u3055\u308C\u3066\u3044\u307E\u3059\u3002"},
/*
* Note to translators: "<xsl:otherwise>" and "<xsl:choose>" are
* keywords and should not be translated. This message describes a
* syntax error in the stylesheet.
*/
{ErrorMsg.STRAY_OTHERWISE_ERR,
"<xsl:otherwise>\u306F<xsl:choose>\u5185\u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002"},
/*
* Note to translators: "<xsl:when>" and "<xsl:choose>" are keywords
* and should not be translated. This message describes a syntax error
* in the stylesheet.
*/
{ErrorMsg.STRAY_WHEN_ERR,
"<xsl:when>\u306F<xsl:choose>\u5185\u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002"},
/*
* Note to translators: "<xsl:when>", "<xsl:otherwise>" and
* "<xsl:choose>" are keywords and should not be translated. This
* message describes a syntax error in the stylesheet.
*/
{ErrorMsg.WHEN_ELEMENT_ERR,
"<xsl:choose>\u5185\u3067\u306F<xsl:when>\u3068<xsl:otherwise>\u306E\u8981\u7D20\u306E\u307F\u304C\u8A31\u53EF\u3055\u308C\u307E\u3059\u3002"},
/*
* Note to translators: "<xsl:attribute-set>" and "name" are keywords
* that should not be translated.
*/
{ErrorMsg.UNNAMED_ATTRIBSET_ERR,
"<xsl:attribute-set>\u306B'name'\u5C5E\u6027\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: An element in the stylesheet contained an
* element of a type that it was not permitted to contain.
*/
{ErrorMsg.ILLEGAL_CHILD_ERR,
"\u5B50\u8981\u7D20\u304C\u4E0D\u6B63\u3067\u3059\u3002"},
/*
* Note to translators: The stylesheet tried to create an element with
* a name that was not a valid XML name. The substitution text contains
* the name.
*/
{ErrorMsg.ILLEGAL_ELEM_NAME_ERR,
"\u8981\u7D20''{0}''\u3092\u547C\u3073\u51FA\u3059\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093"},
/*
* Note to translators: The stylesheet tried to create an attribute
* with a name that was not a valid XML name. The substitution text
* contains the name.
*/
{ErrorMsg.ILLEGAL_ATTR_NAME_ERR,
"\u5C5E\u6027''{0}''\u3092\u547C\u3073\u51FA\u3059\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093"},
/*
* Note to translators: The children of the outermost element of a
* stylesheet are referred to as top-level elements. No text should
* occur within that outermost element unless it is within a top-level
* element. This message indicates that that constraint was violated.
* "<xsl:stylesheet>" is a keyword that should not be translated.
*/
{ErrorMsg.ILLEGAL_TEXT_NODE_ERR,
"\u30C6\u30AD\u30B9\u30C8\u30FB\u30C7\u30FC\u30BF\u306F\u30C8\u30C3\u30D7\u30EC\u30D9\u30EB\u306E<xsl:stylesheet>\u8981\u7D20\u306E\u5916\u5074\u306B\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: JAXP is an acronym for the Java API for XML
* Processing. This message indicates that the XML parser provided to
* XSLTC to process the XML input document had a configuration problem.
*/
{ErrorMsg.SAX_PARSER_CONFIG_ERR,
"JAXP\u30D1\u30FC\u30B5\u30FC\u304C\u6B63\u3057\u304F\u69CB\u6210\u3055\u308C\u3066\u3044\u307E\u305B\u3093"},
/*
* Note to translators: The substitution text names the internal error
* encountered.
*/
{ErrorMsg.INTERNAL_ERR,
"\u30EA\u30AB\u30D0\u30EA\u4E0D\u80FD\u306AXSLTC\u5185\u90E8\u30A8\u30E9\u30FC: ''{0}''"},
/*
* Note to translators: The stylesheet contained an element that was
* not recognized as part of the XSL syntax. The substitution text
* gives the element name.
*/
{ErrorMsg.UNSUPPORTED_XSL_ERR,
"XSL\u8981\u7D20''{0}''\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The stylesheet referred to an extension to the
* XSL syntax and indicated that it was defined by XSLTC, but XSTLC does
* not recognized the particular extension named. The substitution text
* gives the extension name.
*/
{ErrorMsg.UNSUPPORTED_EXT_ERR,
"XSLTC\u62E1\u5F35''{0}''\u306F\u8A8D\u8B58\u3055\u308C\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The XML document given to XSLTC as a stylesheet
* was not, in fact, a stylesheet. XSLTC is able to detect that in this
* case because the outermost element in the stylesheet has to be
* declared with respect to the XSL namespace URI, but no declaration
* for that namespace was seen.
*/
{ErrorMsg.MISSING_XSLT_URI_ERR,
"\u5165\u529B\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u306F\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u3067\u306F\u3042\u308A\u307E\u305B\u3093(XSL\u306E\u30CD\u30FC\u30E0\u30B9\u30DA\u30FC\u30B9\u306F\u30EB\u30FC\u30C8\u8981\u7D20\u5185\u3067\u5BA3\u8A00\u3055\u308C\u3066\u3044\u307E\u305B\u3093)\u3002"},
/*
* Note to translators: XSLTC could not find the stylesheet document
* with the name specified by the substitution text.
*/
{ErrorMsg.MISSING_XSLT_TARGET_ERR,
"\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u30FB\u30BF\u30FC\u30B2\u30C3\u30C8''{0}''\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},
/*
* Note to translators: access to the stylesheet target is denied
*/
{ErrorMsg.ACCESSING_XSLT_TARGET_ERR,
"accessExternalStylesheet\u30D7\u30ED\u30D1\u30C6\u30A3\u3067\u8A2D\u5B9A\u3055\u308C\u305F\u5236\u9650\u306B\u3088\u308A''{1}''\u30A2\u30AF\u30BB\u30B9\u304C\u8A31\u53EF\u3055\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u30FB\u30BF\u30FC\u30B2\u30C3\u30C8''{0}''\u3092\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},
/*
* Note to translators: This message represents an internal error in
* condition in XSLTC. The substitution text is the class name in XSLTC
* that is missing some functionality.
*/
{ErrorMsg.NOT_IMPLEMENTED_ERR,
"''{0}''\u304C\u5B9F\u88C5\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The XML document given to XSLTC as a stylesheet
* was not, in fact, a stylesheet.
*/
{ErrorMsg.NOT_STYLESHEET_ERR,
"\u5165\u529B\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u306BXSL\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The element named in the substitution text was
* encountered in the stylesheet but is not recognized.
*/
{ErrorMsg.ELEMENT_PARSE_ERR,
"\u8981\u7D20''{0}''\u3092\u89E3\u6790\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"},
/*
* Note to translators: "use", "<key>", "node", "node-set", "string"
* and "number" are keywords in this context and should not be
* translated. This message indicates that the value of the "use"
* attribute was not one of the permitted values.
*/
{ErrorMsg.KEY_USE_ATTR_ERR,
"<key>\u306Euse\u5C5E\u6027\u306F\u3001\u30CE\u30FC\u30C9\u3001\u30CE\u30FC\u30C9\u30BB\u30C3\u30C8\u3001\u6587\u5B57\u5217\u307E\u305F\u306F\u6570\u5024\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: An XML document can specify the version of the
* XML specification to which it adheres. This message indicates that
* the version specified for the output document was not valid.
*/
{ErrorMsg.OUTPUT_VERSION_ERR,
"\u51FA\u529BXML\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u306F1.0\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
/*
* Note to translators: The operator in a comparison operation was
* not recognized.
*/
{ErrorMsg.ILLEGAL_RELAT_OP_ERR,
"\u95A2\u4FC2\u5F0F\u306E\u4E0D\u660E\u306A\u6F14\u7B97\u5B50\u3067\u3059"},
/*
* Note to translators: An attribute set defines as a set of XML
* attributes that can be added to an element in the output XML document
* as a group. This message is reported if the name specified was not
* used to declare an attribute set. The substitution text is the name
* that is in error.
*/
{ErrorMsg.ATTRIBSET_UNDEF_ERR,
"\u5B58\u5728\u3057\u306A\u3044\u5C5E\u6027\u30BB\u30C3\u30C8''{0}''\u3092\u4F7F\u7528\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002"},
/*
* Note to translators: The term "attribute value template" is a term
* defined by XSLT which describes the value of an attribute that is
* determined by an XPath expression. The message indicates that the
* expression was syntactically incorrect; the substitution text
* contains the expression that was in error.
*/
{ErrorMsg.ATTR_VAL_TEMPLATE_ERR,
"\u5C5E\u6027\u5024\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8''{0}''\u3092\u89E3\u6790\u3067\u304D\u307E\u305B\u3093\u3002"},
/*
* Note to translators: ???
*/
{ErrorMsg.UNKNOWN_SIG_TYPE_ERR,
"\u30AF\u30E9\u30B9''{0}''\u306E\u7F72\u540D\u306B\u4E0D\u660E\u306A\u30C7\u30FC\u30BF\u578B\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: The substitution text refers to data types.
* The message is displayed if a value in a particular context needs to
* be converted to type {1}, but that's not possible for a value of
* type {0}.
*/
{ErrorMsg.DATA_CONVERSION_ERR,
"\u30C7\u30FC\u30BF\u578B''{0}''\u3092''{1}''\u306B\u5909\u63DB\u3067\u304D\u307E\u305B\u3093\u3002"},
/*
* Note to translators: "Templates" is a Java class name that should
* not be translated.
*/
{ErrorMsg.NO_TRANSLET_CLASS_ERR,
"\u3053\u306E\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u306B\u306F\u6709\u52B9\u306Atranslet\u30AF\u30E9\u30B9\u5B9A\u7FA9\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: "Templates" is a Java class name that should
* not be translated.
*/
{ErrorMsg.NO_MAIN_TRANSLET_ERR,
"\u3053\u306E\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u306B\u306F\u540D\u524D''{0}''\u3092\u6301\u3064\u30AF\u30E9\u30B9\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The substitution text is the name of a class.
*/
{ErrorMsg.TRANSLET_CLASS_ERR,
"translet\u30AF\u30E9\u30B9''{0}''\u3092\u30ED\u30FC\u30C9\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},
{ErrorMsg.TRANSLET_OBJECT_ERR,
"Translet\u30AF\u30E9\u30B9\u304C\u30ED\u30FC\u30C9\u3055\u308C\u307E\u3057\u305F\u304C\u3001translet\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u4F5C\u6210\u3067\u304D\u307E\u305B\u3093\u3002"},
/*
* Note to translators: "ErrorListener" is a Java interface name that
* should not be translated. The message indicates that the user tried
* to set an ErrorListener object on object of the class named in the
* substitution text with "null" Java value.
*/
{ErrorMsg.ERROR_LISTENER_NULL_ERR,
"''{0}''\u306EErrorListener\u3092null\u306B\u8A2D\u5B9A\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F"},
/*
* Note to translators: StreamSource, SAXSource and DOMSource are Java
* interface names that should not be translated.
*/
{ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR,
"StreamSource\u3001SAXSource\u304A\u3088\u3073DOMSource\u306E\u307F\u304CXSLTC\u306B\u3088\u3063\u3066\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u3059"},
/*
* Note to translators: "Source" is a Java class name that should not
* be translated. The substitution text is the name of Java method.
*/
{ErrorMsg.JAXP_NO_SOURCE_ERR,
"''{0}''\u306B\u6E21\u3055\u308C\u305F\u30BD\u30FC\u30B9\u30FB\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u306B\u30B3\u30F3\u30C6\u30F3\u30C4\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The message indicates that XSLTC failed to
* compile the stylesheet into a translet (class file).
*/
{ErrorMsg.JAXP_COMPILE_ERR,
"\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u3092\u30B3\u30F3\u30D1\u30A4\u30EB\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F"},
/*
* Note to translators: "TransformerFactory" is a class name. In this
* context, an attribute is a property or setting of the
* TransformerFactory object. The substitution text is the name of the
* unrecognised attribute. The method used to retrieve the attribute is
* "getAttribute", so it's not clear whether it would be best to
* translate the term "attribute".
*/
{ErrorMsg.JAXP_INVALID_ATTR_ERR,
"TransformerFactory\u306F\u5C5E\u6027''{0}''\u3092\u8A8D\u8B58\u3057\u307E\u305B\u3093\u3002"},
{ErrorMsg.JAXP_INVALID_ATTR_VALUE_ERR,
"''{0}''\u5C5E\u6027\u306B\u6307\u5B9A\u3055\u308C\u305F\u5024\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: "setResult()" and "startDocument()" are Java
* method names that should not be translated.
*/
{ErrorMsg.JAXP_SET_RESULT_ERR,
"setResult()\u306FstartDocument()\u3088\u308A\u3082\u524D\u306B\u547C\u3073\u51FA\u3059\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: "Transformer" is a Java interface name that
* should not be translated. A Transformer object should contained a
* reference to a translet object in order to be used for
* transformations; this message is produced if that requirement is not
* met.
*/
{ErrorMsg.JAXP_NO_TRANSLET_ERR,
"\u30C8\u30E9\u30F3\u30B9\u30D5\u30A9\u30FC\u30DE\u306B\u306F\u30AB\u30D7\u30BB\u30EB\u5316\u3055\u308C\u305Ftranslet\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The XML document that results from a
* transformation needs to be sent to an output handler object; this
* message is produced if that requirement is not met.
*/
{ErrorMsg.JAXP_NO_HANDLER_ERR,
"\u5909\u63DB\u7D50\u679C\u306B\u5BFE\u3057\u3066\u5B9A\u7FA9\u6E08\u306E\u51FA\u529B\u30CF\u30F3\u30C9\u30E9\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: "Result" is a Java interface name in this
* context. The substitution text is a method name.
*/
{ErrorMsg.JAXP_NO_RESULT_ERR,
"''{0}''\u306B\u6E21\u3055\u308C\u305F\u7D50\u679C\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u306F\u7121\u52B9\u3067\u3059\u3002"},
/*
* Note to translators: "Transformer" is a Java interface name. The
* user's program attempted to access an unrecognized property with the
* name specified in the substitution text. The method used to retrieve
* the property is "getOutputProperty", so it's not clear whether it
* would be best to translate the term "property".
*/
{ErrorMsg.JAXP_UNKNOWN_PROP_ERR,
"\u7121\u52B9\u306A\u30C8\u30E9\u30F3\u30B9\u30D5\u30A9\u30FC\u30DE\u30FB\u30D7\u30ED\u30D1\u30C6\u30A3''{0}''\u306B\u30A2\u30AF\u30BB\u30B9\u3057\u3088\u3046\u3068\u3057\u307E\u3057\u305F\u3002"},
/*
* Note to translators: SAX2DOM is the name of a Java class that should
* not be translated. This is an adapter in the sense that it takes a
* DOM object and converts it to something that uses the SAX API.
*/
{ErrorMsg.SAX2DOM_ADAPTER_ERR,
"SAX2DOM\u30A2\u30C0\u30D7\u30BF''{0}''\u3092\u4F5C\u6210\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},
/*
* Note to translators: "XSLTCSource.build()" is a Java method name.
* "systemId" is an XML term that is short for "system identification".
*/
{ErrorMsg.XSLTC_SOURCE_ERR,
"systemId\u3092\u8A2D\u5B9A\u305B\u305A\u306BXSLTCSource.build()\u304C\u547C\u3073\u51FA\u3055\u308C\u307E\u3057\u305F\u3002"},
{ ErrorMsg.ER_RESULT_NULL,
"\u7D50\u679C\u306Fnull\u306B\u3067\u304D\u307E\u305B\u3093"},
/*
* Note to translators: This message indicates that the value argument
* of setParameter must be a valid Java Object.
*/
{ErrorMsg.JAXP_INVALID_SET_PARAM_VALUE,
"\u30D1\u30E9\u30E1\u30FC\u30BF{0}\u306F\u6709\u52B9\u306AJava\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{ErrorMsg.COMPILE_STDIN_ERR,
"-i\u30AA\u30D7\u30B7\u30E7\u30F3\u306F-o\u30AA\u30D7\u30B7\u30E7\u30F3\u3068\u3068\u3082\u306B\u4F7F\u7528\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: This message contains usage information for a
* means of invoking XSLTC from the command-line. The message is
* formatted for presentation in English. The strings <output>,
* <directory>, etc. indicate user-specified argument values, and can
* be translated - the argument <package> refers to a Java package, so
* it should be handled in the same way the term is handled for JDK
* documentation.
*/
{ErrorMsg.COMPILE_USAGE_STR,
"\u5F62\u5F0F\n java com.sun.org.apache.xalan.internal.xsltc.cmdline.Compile [-o <output>]\n [-d <directory>] [-j <jarfile>] [-p <package>]\n [-n] [-x] [-u] [-v] [-h] { <stylesheet> | -i }\n\nOPTIONS\n -o <output> \u540D\u524D<output>\u3092\u751F\u6210\u6E08translet\u306B\n \u5272\u308A\u5F53\u3066\u308B\u3002\u30C7\u30D5\u30A9\u30EB\u30C8\u3067\u306F\u3001translet\u540D\u306F\n <stylesheet>\u540D\u306B\u7531\u6765\u3057\u307E\u3059\u3002\u3053\u306E\u30AA\u30D7\u30B7\u30E7\u30F3\u306F\n \u8907\u6570\u306E\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u3092\u30B3\u30F3\u30D1\u30A4\u30EB\u3059\u308B\u5834\u5408\u306F\u7121\u8996\u3055\u308C\u307E\u3059\u3002\n -d <directory> translet\u306E\u5B9B\u5148\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u6307\u5B9A\u3059\u308B\n -j <jarfile> <jarfile>\u3067\u6307\u5B9A\u3055\u308C\u308B\u540D\u524D\u306Ejar\u30D5\u30A1\u30A4\u30EB\u306Btranslet\u30AF\u30E9\u30B9\u3092\n \u30D1\u30C3\u30B1\u30FC\u30B8\u3059\u308B\n -p <package> \u751F\u6210\u3055\u308C\u308B\u3059\u3079\u3066\u306Etranslet\u30AF\u30E9\u30B9\u306E\u30D1\u30C3\u30B1\u30FC\u30B8\u540D\n \u63A5\u982D\u8F9E\u3092\u6307\u5B9A\u3059\u308B\u3002\n -n \u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u306E\u30A4\u30F3\u30E9\u30A4\u30F3\u5316\u3092\u6709\u52B9\u306B\u3059\u308B(\u5E73\u5747\u3057\u3066\u30C7\u30D5\u30A9\u30EB\u30C8\u52D5\u4F5C\u306E\u65B9\u304C\n \u512A\u308C\u3066\u3044\u307E\u3059)\u3002\n -x \u8FFD\u52A0\u306E\u30C7\u30D0\u30C3\u30B0\u30FB\u30E1\u30C3\u30BB\u30FC\u30B8\u51FA\u529B\u3092\u30AA\u30F3\u306B\u3059\u308B\n -u <stylesheet>\u5F15\u6570\u3092URL\u3068\u3057\u3066\u89E3\u91C8\u3059\u308B\n -i \u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u3092stdin\u304B\u3089\u8AAD\u307F\u8FBC\u3080\u3053\u3068\u3092\u30B3\u30F3\u30D1\u30A4\u30E9\u306B\u5F37\u5236\u3059\u308B\n -v \u30B3\u30F3\u30D1\u30A4\u30E9\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u3092\u51FA\u529B\u3059\u308B\n -h \u3053\u306E\u4F7F\u7528\u65B9\u6CD5\u306E\u6587\u3092\u51FA\u529B\u3059\u308B\n"},
/*
* Note to translators: This message contains usage information for a
* means of invoking XSLTC from the command-line. The message is
* formatted for presentation in English. The strings <jarfile>,
* <document>, etc. indicate user-specified argument values, and can
* be translated - the argument <class> refers to a Java class, so it
* should be handled in the same way the term is handled for JDK
* documentation.
*/
{ErrorMsg.TRANSFORM_USAGE_STR,
"\u5F62\u5F0F \n java com.sun.org.apache.xalan.internal.xsltc.cmdline.Transform [-j <jarfile>]\n [-x] [-n <iterations>] {-u <document_url> | <document>}\n <class> [<param1>=<value1> ...]\n\n translet <class>\u3092\u4F7F\u7528\u3057\u3066\u3001<document>\u3067\u6307\u5B9A\u3055\u308C\u308B\n XML\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u5909\u63DB\u3059\u308B\u3002translet <class>\u306F\n \u30E6\u30FC\u30B6\u30FC\u306ECLASSPATH\u5185\u304B\u3001\u30AA\u30D7\u30B7\u30E7\u30F3\u3067\u6307\u5B9A\u3055\u308C\u305F<jarfile>\u5185\u306B\u3042\u308A\u307E\u3059\u3002\nOPTIONS\n -j <jarfile> translet\u3092\u30ED\u30FC\u30C9\u3059\u308Bjarfile\u3092\u6307\u5B9A\u3059\u308B\n -x \u8FFD\u52A0\u306E\u30C7\u30D0\u30C3\u30B0\u30FB\u30E1\u30C3\u30BB\u30FC\u30B8\u51FA\u529B\u3092\u30AA\u30F3\u306B\u3059\u308B\n -n <iterations> \u5909\u63DB\u3092<iterations>\u56DE\u5B9F\u884C\u3057\u3001\n \u30D7\u30ED\u30D5\u30A1\u30A4\u30EA\u30F3\u30B0\u60C5\u5831\u3092\u8868\u793A\u3059\u308B\n -u <document_url> XML\u5165\u529B\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092URL\u3068\u3057\u3066\u6307\u5B9A\u3059\u308B\n"},
/*
* Note to translators: "<xsl:sort>", "<xsl:for-each>" and
* "<xsl:apply-templates>" are keywords that should not be translated.
* The message indicates that an xsl:sort element must be a child of
* one of the other kinds of elements mentioned.
*/
{ErrorMsg.STRAY_SORT_ERR,
"<xsl:sort>\u306F<xsl:for-each>\u307E\u305F\u306F<xsl:apply-templates>\u306E\u5185\u90E8\u3067\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059\u3002"},
/*
* Note to translators: The message indicates that the encoding
* requested for the output document was on that requires support that
* is not available from the Java Virtual Machine being used to execute
* the program.
*/
{ErrorMsg.UNSUPPORTED_ENCODING,
"\u51FA\u529B\u30A8\u30F3\u30B3\u30FC\u30C7\u30A3\u30F3\u30B0''{0}''\u306F\u3053\u306EJVM\u3067\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002"},
/*
* Note to translators: The message indicates that the XPath expression
* named in the substitution text was not well formed syntactically.
*/
{ErrorMsg.SYNTAX_ERR,
"''{0}''\u306B\u69CB\u6587\u30A8\u30E9\u30FC\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: The substitution text is the name of a Java
* class. The term "constructor" here is the Java term. The message is
* displayed if XSLTC could not find a constructor for the specified
* class.
*/
{ErrorMsg.CONSTRUCTOR_NOT_FOUND,
"\u5916\u90E8\u30B3\u30F3\u30B9\u30C8\u30E9\u30AF\u30BF''{0}''\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: "static" is the Java keyword. The substitution
* text is the name of a function. The first argument of that function
* is not of the required type.
*/
{ErrorMsg.NO_JAVA_FUNCT_THIS_REF,
"static\u3067\u306A\u3044Java\u95A2\u6570''{0}''\u306E\u6700\u521D\u306E\u5F15\u6570\u306F\u7121\u52B9\u306A\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u53C2\u7167\u3067\u3059\u3002"},
/*
* Note to translators: An XPath expression was not of the type
* required in a particular context. The substitution text is the
* expression that was in error.
*/
{ErrorMsg.TYPE_CHECK_ERR,
"\u5F0F''{0}''\u306E\u30BF\u30A4\u30D7\u306E\u78BA\u8A8D\u4E2D\u306B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002"},
/*
* Note to translators: An XPath expression was not of the type
* required in a particular context. However, the location of the
* problematic expression is unknown.
*/
{ErrorMsg.TYPE_CHECK_UNK_LOC_ERR,
"\u4E0D\u660E\u306A\u5834\u6240\u3067\u306E\u5F0F\u306E\u30BF\u30A4\u30D7\u306E\u78BA\u8A8D\u4E2D\u306B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002"},
/*
* Note to translators: The substitution text is the name of a command-
* line option that was not recognized.
*/
{ErrorMsg.ILLEGAL_CMDLINE_OPTION_ERR,
"\u30B3\u30DE\u30F3\u30C9\u884C\u30AA\u30D7\u30B7\u30E7\u30F3''{0}''\u306F\u7121\u52B9\u3067\u3059\u3002"},
/*
* Note to translators: The substitution text is the name of a command-
* line option.
*/
{ErrorMsg.CMDLINE_OPT_MISSING_ARG_ERR,
"\u30B3\u30DE\u30F3\u30C9\u884C\u30AA\u30D7\u30B7\u30E7\u30F3''{0}''\u306B\u5FC5\u9808\u306E\u5F15\u6570\u304C\u3042\u308A\u307E\u305B\u3093\u3002"},
/*
* Note to translators: This message is used to indicate the severity
* of another message. The substitution text contains two error
* messages. The spacing before the second substitution text indents
* it the same amount as the first in English.
*/
{ErrorMsg.WARNING_PLUS_WRAPPED_MSG,
"WARNING: ''{0}''\n :{1}"},
/*
* Note to translators: This message is used to indicate the severity
* of another message. The substitution text is an error message.
*/
{ErrorMsg.WARNING_MSG,
"WARNING: ''{0}''"},
/*
* Note to translators: This message is used to indicate the severity
* of another message. The substitution text contains two error
* messages. The spacing before the second substitution text indents
* it the same amount as the first in English.
*/
{ErrorMsg.FATAL_ERR_PLUS_WRAPPED_MSG,
"FATAL ERROR: ''{0}''\n :{1}"},
/*
* Note to translators: This message is used to indicate the severity
* of another message. The substitution text is an error message.
*/
{ErrorMsg.FATAL_ERR_MSG,
"FATAL ERROR: ''{0}''"},
/*
* Note to translators: This message is used to indicate the severity
* of another message. The substitution text contains two error
* messages. The spacing before the second substitution text indents
* it the same amount as the first in English.
*/
{ErrorMsg.ERROR_PLUS_WRAPPED_MSG,
"ERROR: ''{0}''\n :{1}"},
/*
* Note to translators: This message is used to indicate the severity
* of another message. The substitution text is an error message.
*/
{ErrorMsg.ERROR_MSG,
"ERROR: ''{0}''"},
/*
* Note to translators: The substitution text is the name of a class.
*/
{ErrorMsg.TRANSFORM_WITH_TRANSLET_STR,
"translet ''{0}''\u3092\u4F7F\u7528\u3057\u3066\u5909\u63DB\u3057\u307E\u3059 "},
/*
* Note to translators: The first substitution is the name of a class,
* while the second substitution is the name of a jar file.
*/
{ErrorMsg.TRANSFORM_WITH_JAR_STR,
"translet ''{0}''\u3092\u4F7F\u7528\u3057\u3066jar\u30D5\u30A1\u30A4\u30EB''{1}''\u304B\u3089\u5909\u63DB\u3057\u307E\u3059"},
/*
* Note to translators: "TransformerFactory" is the name of a Java
* interface and must not be translated. The substitution text is
* the name of the class that could not be instantiated.
*/
{ErrorMsg.COULD_NOT_CREATE_TRANS_FACT,
"TransformerFactory\u30AF\u30E9\u30B9''{0}''\u306E\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u4F5C\u6210\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"},
/*
* Note to translators: This message is produced when the user
* specified a name for the translet class that contains characters
* that are not permitted in a Java class name. The substitution
* text "{0}" specifies the name the user requested, while "{1}"
* specifies the name the processor used instead.
*/
{ErrorMsg.TRANSLET_NAME_JAVA_CONFLICT,
"\u540D\u524D''{0}''\u306B\u306FJava\u30AF\u30E9\u30B9\u306E\u540D\u524D\u306B\u8A31\u53EF\u3055\u308C\u3066\u3044\u306A\u3044\u6587\u5B57\u304C\u542B\u307E\u308C\u3066\u3044\u308B\u305F\u3081\u3001translet\u30AF\u30E9\u30B9\u306E\u540D\u524D\u3068\u3057\u3066\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u540D\u524D''{1}''\u304C\u304B\u308F\u308A\u306B\u4F7F\u7528\u3055\u308C\u307E\u3059\u3002"},
/*
* Note to translators: The following message is used as a header.
* All the error messages are collected together and displayed beneath
* this message.
*/
{ErrorMsg.COMPILER_ERROR_KEY,
"\u30B3\u30F3\u30D1\u30A4\u30E9\u30FB\u30A8\u30E9\u30FC:"},
/*
* Note to translators: The following message is used as a header.
* All the warning messages are collected together and displayed
* beneath this message.
*/
{ErrorMsg.COMPILER_WARNING_KEY,
"\u30B3\u30F3\u30D1\u30A4\u30E9\u306E\u8B66\u544A:"},
/*
* Note to translators: The following message is used as a header.
* All the error messages that are produced when the stylesheet is
* applied to an input document are collected together and displayed
* beneath this message. A 'translet' is the compiled form of a
* stylesheet (see above).
*/
{ErrorMsg.RUNTIME_ERROR_KEY,
"Translet\u30A8\u30E9\u30FC:"},
/*
* Note to translators: An attribute whose value is constrained to
* be a "QName" or a list of "QNames" had a value that was incorrect.
* 'QName' is an XML syntactic term that must not be translated. The
* substitution text contains the actual value of the attribute.
*/
{ErrorMsg.INVALID_QNAME_ERR,
"\u5024\u304C1\u3064\u306EQName\u307E\u305F\u306FQName\u306E\u7A7A\u767D\u6587\u5B57\u533A\u5207\u308A\u30EA\u30B9\u30C8\u3067\u3042\u308B\u3053\u3068\u304C\u5FC5\u8981\u306A\u5C5E\u6027\u306E\u5024\u304C''{0}''\u3067\u3057\u305F"},
/*
* Note to translators: An attribute whose value is required to
* be an "NCName".
* 'NCName' is an XML syntactic term that must not be translated. The
* substitution text contains the actual value of the attribute.
*/
{ErrorMsg.INVALID_NCNAME_ERR,
"\u5024\u304CNCName\u3067\u3042\u308B\u3053\u3068\u304C\u5FC5\u8981\u306A\u5C5E\u6027\u306E\u5024\u304C''{0}''\u3067\u3057\u305F"},
/*
* Note to translators: An attribute with an incorrect value was
* encountered. The permitted value is one of the literal values
* "xml", "html" or "text"; it is also permitted to have the form of
* a QName that is not also an NCName. The terms "method",
* "xsl:output", "xml", "html" and "text" are keywords that must not
* be translated. The term "qname-but-not-ncname" is an XML syntactic
* term. The substitution text contains the actual value of the
* attribute.
*/
{ErrorMsg.INVALID_METHOD_IN_OUTPUT,
"<xsl:output>\u8981\u7D20\u306E\u30E1\u30BD\u30C3\u30C9\u5C5E\u6027\u306E\u5024\u304C''{0}''\u3067\u3057\u305F\u3002\u5024\u306F''xml''\u3001''html''\u3001''text''\u307E\u305F\u306Fqname-but-not-ncname\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059"},
{ErrorMsg.JAXP_GET_FEATURE_NULL_NAME,
"\u6A5F\u80FD\u540D\u306FTransformerFactory.getFeature(String name)\u5185\u3067null\u306B\u3067\u304D\u307E\u305B\u3093\u3002"},
{ErrorMsg.JAXP_SET_FEATURE_NULL_NAME,
"\u6A5F\u80FD\u540D\u306FTransformerFactory.setFeature(String name, boolean value)\u5185\u3067null\u306B\u3067\u304D\u307E\u305B\u3093\u3002"},
{ErrorMsg.JAXP_UNSUPPORTED_FEATURE,
"\u6A5F\u80FD''{0}''\u3092\u3053\u306ETransformerFactory\u306B\u8A2D\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002"},
{ErrorMsg.JAXP_SECUREPROCESSING_FEATURE,
"FEATURE_SECURE_PROCESSING: \u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30FB\u30DE\u30CD\u30FC\u30B8\u30E3\u304C\u5B58\u5728\u3059\u308B\u3068\u304D\u3001\u6A5F\u80FD\u3092false\u306B\u8A2D\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002"},
/*
* Note to translators: This message describes an internal error in the
* processor. The term "byte code" is a Java technical term for the
* executable code in a Java method, and "try-catch-finally block"
* refers to the Java keywords with those names. "Outlined" is a
* technical term internal to XSLTC and should not be translated.
*/
{ErrorMsg.OUTLINE_ERR_TRY_CATCH,
"\u5185\u90E8XSLTC\u30A8\u30E9\u30FC: \u751F\u6210\u3055\u308C\u305F\u30D0\u30A4\u30C8\u30FB\u30B3\u30FC\u30C9\u306F\u3001try-catch-finally\u30D6\u30ED\u30C3\u30AF\u3092\u542B\u3093\u3067\u3044\u308B\u305F\u3081\u3001\u30A2\u30A6\u30C8\u30E9\u30A4\u30F3\u5316\u3067\u304D\u307E\u305B\u3093\u3002"},
/*
* Note to translators: This message describes an internal error in the
* processor. The terms "OutlineableChunkStart" and
* "OutlineableChunkEnd" are the names of classes internal to XSLTC and
* should not be translated. The message indicates that for every
* "start" there must be a corresponding "end", and vice versa, and
* that if one of a pair of "start" and "end" appears between another
* pair of corresponding "start" and "end", then the other half of the
* pair must also be between that same enclosing pair.
*/
{ErrorMsg.OUTLINE_ERR_UNBALANCED_MARKERS,
"\u5185\u90E8XSLTC\u30A8\u30E9\u30FC: OutlineableChunkStart\u30DE\u30FC\u30AB\u30FC\u3068OutlineableChunkEnd\u30DE\u30FC\u30AB\u30FC\u306F\u3001\u5BFE\u306B\u306A\u3063\u3066\u304A\u308A\u3001\u304B\u3064\u6B63\u3057\u304F\u30CD\u30B9\u30C8\u3055\u308C\u3066\u3044\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"},
/*
* Note to translators: This message describes an internal error in the
* processor. The term "byte code" is a Java technical term for the
* executable code in a Java method. The "method" that is being
* referred to is a Java method in a translet that XSLTC is generating
* in processing a stylesheet. The "instruction" that is being
* referred to is one of the instrutions in the Java byte code in that
* method. "Outlined" is a technical term internal to XSLTC and
* should not be translated.
*/
{ErrorMsg.OUTLINE_ERR_DELETED_TARGET,
"\u5185\u90E8XSLTC\u30A8\u30E9\u30FC: \u30A2\u30A6\u30C8\u30E9\u30A4\u30F3\u5316\u3055\u308C\u305F\u30D0\u30A4\u30C8\u30FB\u30B3\u30FC\u30C9\u306E\u30D6\u30ED\u30C3\u30AF\u306E\u4E00\u90E8\u3067\u3042\u3063\u305F\u547D\u4EE4\u306F\u3001\u5143\u306E\u30E1\u30BD\u30C3\u30C9\u306E\u4E2D\u3067\u307E\u3060\u53C2\u7167\u3055\u308C\u3066\u3044\u307E\u3059\u3002"
},
/*
* Note to translators: This message describes an internal error in the
* processor. The "method" that is being referred to is a Java method
* in a translet that XSLTC is generating.
*
*/
{ErrorMsg.OUTLINE_ERR_METHOD_TOO_BIG,
"\u5185\u90E8XSLTC\u30A8\u30E9\u30FC: \u30C8\u30E9\u30F3\u30B9\u30EC\u30C3\u30C8\u5185\u306E\u30E1\u30BD\u30C3\u30C9\u304C\u3001Java\u4EEE\u60F3\u30DE\u30B7\u30F3\u306E\u5236\u9650(1\u30E1\u30BD\u30C3\u30C9\u306E\u9577\u3055\u306F\u6700\u592764\u30AD\u30ED\u30D0\u30A4\u30C8)\u3092\u8D85\u3048\u3066\u3044\u307E\u3059\u3002\u4E00\u822C\u7684\u306B\u3001\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u5185\u306E\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u306E\u30B5\u30A4\u30BA\u304C\u5927\u304D\u904E\u304E\u308B\u3053\u3068\u304C\u539F\u56E0\u3068\u3057\u3066\u8003\u3048\u3089\u308C\u307E\u3059\u3002\u5C0F\u3055\u3044\u30B5\u30A4\u30BA\u306E\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u3092\u4F7F\u7528\u3057\u3066\u3001\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u3092\u518D\u69CB\u6210\u3057\u3066\u304F\u3060\u3055\u3044\u3002"
},
{ErrorMsg.DESERIALIZE_TRANSLET_ERR, "Java\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u304C\u6709\u52B9\u5316\u3055\u308C\u3066\u3044\u308B\u5834\u5408\u3001TemplatesImpl\u306E\u30C7\u30B7\u30EA\u30A2\u30E9\u30A4\u30BA\u306E\u30B5\u30DD\u30FC\u30C8\u306F\u7121\u52B9\u5316\u3055\u308C\u307E\u3059\u3002\u3053\u308C\u306F\u3001jdk.xml.enableTemplatesImplDeserialization\u30B7\u30B9\u30C6\u30E0\u30FB\u30D7\u30ED\u30D1\u30C6\u30A3\u3092true\u306B\u8A2D\u5B9A\u3057\u3066\u30AA\u30FC\u30D0\u30FC\u30E9\u30A4\u30C9\u3067\u304D\u307E\u3059\u3002"}
};
}
}
| {
"pile_set_name": "Github"
} |
version https://git-lfs.github.com/spec/v1
oid sha256:88e1e45dbaf2a2cacee871646938d28411a35f9bae4a6f39a3f1a195b3737f71
size 8184
| {
"pile_set_name": "Github"
} |
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include "layers.h"
CLayers::CLayers()
{
m_GroupsNum = 0;
m_GroupsStart = 0;
m_LayersNum = 0;
m_LayersStart = 0;
m_pGameGroup = 0;
m_pGameLayer = 0;
m_pMap = 0;
}
void CLayers::Init(class IKernel *pKernel, IMap *pMap)
{
m_pMap = pMap ? pMap : pKernel->RequestInterface<IMap>();
m_pMap->GetType(MAPITEMTYPE_GROUP, &m_GroupsStart, &m_GroupsNum);
m_pMap->GetType(MAPITEMTYPE_LAYER, &m_LayersStart, &m_LayersNum);
for(int g = 0; g < NumGroups(); g++)
{
CMapItemGroup *pGroup = GetGroup(g);
for(int l = 0; l < pGroup->m_NumLayers; l++)
{
CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l);
if(pLayer->m_Type == LAYERTYPE_TILES)
{
CMapItemLayerTilemap *pTilemap = reinterpret_cast<CMapItemLayerTilemap *>(pLayer);
if(pTilemap->m_Flags&TILESLAYERFLAG_GAME)
{
m_pGameLayer = pTilemap;
m_pGameGroup = pGroup;
// make sure the game group has standard settings
m_pGameGroup->m_OffsetX = 0;
m_pGameGroup->m_OffsetY = 0;
m_pGameGroup->m_ParallaxX = 100;
m_pGameGroup->m_ParallaxY = 100;
if(m_pGameGroup->m_Version >= 2)
{
m_pGameGroup->m_UseClipping = 0;
m_pGameGroup->m_ClipX = 0;
m_pGameGroup->m_ClipY = 0;
m_pGameGroup->m_ClipW = 0;
m_pGameGroup->m_ClipH = 0;
}
break;
}
}
}
}
InitTilemapSkip();
}
void CLayers::InitTilemapSkip()
{
for(int g = 0; g < NumGroups(); g++)
{
CMapItemGroup *pGroup = GetGroup(g);
for(int l = 0; l < pGroup->m_NumLayers; l++)
{
CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l);
if(pLayer->m_Type == LAYERTYPE_TILES)
{
CMapItemLayerTilemap *pTmap = (CMapItemLayerTilemap *)pLayer;
CTile *pTiles = (CTile *)Map()->GetData(pTmap->m_Data);
for(int y = 0; y < pTmap->m_Height; y++)
{
for(int x = 1; x < pTmap->m_Width;)
{
int sx;
for(sx = 1; x+sx < pTmap->m_Width && sx < 255; sx++)
{
if(pTiles[y*pTmap->m_Width+x+sx].m_Index)
break;
}
pTiles[y*pTmap->m_Width+x].m_Skip = sx-1;
x += sx;
}
}
}
}
}
}
CMapItemGroup *CLayers::GetGroup(int Index) const
{
return static_cast<CMapItemGroup *>(m_pMap->GetItem(m_GroupsStart+Index, 0, 0));
}
CMapItemLayer *CLayers::GetLayer(int Index) const
{
return static_cast<CMapItemLayer *>(m_pMap->GetItem(m_LayersStart+Index, 0, 0));
}
| {
"pile_set_name": "Github"
} |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from ._application_gateways_operations import ApplicationGatewaysOperations
from ._application_security_groups_operations import ApplicationSecurityGroupsOperations
from ._network_management_client_operations import NetworkManagementClientOperationsMixin
from ._available_endpoint_services_operations import AvailableEndpointServicesOperations
from ._express_route_circuit_authorizations_operations import ExpressRouteCircuitAuthorizationsOperations
from ._express_route_circuit_peerings_operations import ExpressRouteCircuitPeeringsOperations
from ._express_route_circuits_operations import ExpressRouteCircuitsOperations
from ._express_route_service_providers_operations import ExpressRouteServiceProvidersOperations
from ._load_balancers_operations import LoadBalancersOperations
from ._load_balancer_backend_address_pools_operations import LoadBalancerBackendAddressPoolsOperations
from ._load_balancer_frontend_ip_configurations_operations import LoadBalancerFrontendIPConfigurationsOperations
from ._inbound_nat_rules_operations import InboundNatRulesOperations
from ._load_balancer_load_balancing_rules_operations import LoadBalancerLoadBalancingRulesOperations
from ._load_balancer_network_interfaces_operations import LoadBalancerNetworkInterfacesOperations
from ._load_balancer_probes_operations import LoadBalancerProbesOperations
from ._network_interfaces_operations import NetworkInterfacesOperations
from ._network_interface_ip_configurations_operations import NetworkInterfaceIPConfigurationsOperations
from ._network_interface_load_balancers_operations import NetworkInterfaceLoadBalancersOperations
from ._network_security_groups_operations import NetworkSecurityGroupsOperations
from ._security_rules_operations import SecurityRulesOperations
from ._default_security_rules_operations import DefaultSecurityRulesOperations
from ._network_watchers_operations import NetworkWatchersOperations
from ._packet_captures_operations import PacketCapturesOperations
from ._connection_monitors_operations import ConnectionMonitorsOperations
from ._operations import Operations
from ._public_ip_addresses_operations import PublicIPAddressesOperations
from ._route_filters_operations import RouteFiltersOperations
from ._route_filter_rules_operations import RouteFilterRulesOperations
from ._route_tables_operations import RouteTablesOperations
from ._routes_operations import RoutesOperations
from ._bgp_service_communities_operations import BgpServiceCommunitiesOperations
from ._usages_operations import UsagesOperations
from ._virtual_networks_operations import VirtualNetworksOperations
from ._subnets_operations import SubnetsOperations
from ._virtual_network_peerings_operations import VirtualNetworkPeeringsOperations
from ._virtual_network_gateways_operations import VirtualNetworkGatewaysOperations
from ._virtual_network_gateway_connections_operations import VirtualNetworkGatewayConnectionsOperations
from ._local_network_gateways_operations import LocalNetworkGatewaysOperations
__all__ = [
'ApplicationGatewaysOperations',
'ApplicationSecurityGroupsOperations',
'NetworkManagementClientOperationsMixin',
'AvailableEndpointServicesOperations',
'ExpressRouteCircuitAuthorizationsOperations',
'ExpressRouteCircuitPeeringsOperations',
'ExpressRouteCircuitsOperations',
'ExpressRouteServiceProvidersOperations',
'LoadBalancersOperations',
'LoadBalancerBackendAddressPoolsOperations',
'LoadBalancerFrontendIPConfigurationsOperations',
'InboundNatRulesOperations',
'LoadBalancerLoadBalancingRulesOperations',
'LoadBalancerNetworkInterfacesOperations',
'LoadBalancerProbesOperations',
'NetworkInterfacesOperations',
'NetworkInterfaceIPConfigurationsOperations',
'NetworkInterfaceLoadBalancersOperations',
'NetworkSecurityGroupsOperations',
'SecurityRulesOperations',
'DefaultSecurityRulesOperations',
'NetworkWatchersOperations',
'PacketCapturesOperations',
'ConnectionMonitorsOperations',
'Operations',
'PublicIPAddressesOperations',
'RouteFiltersOperations',
'RouteFilterRulesOperations',
'RouteTablesOperations',
'RoutesOperations',
'BgpServiceCommunitiesOperations',
'UsagesOperations',
'VirtualNetworksOperations',
'SubnetsOperations',
'VirtualNetworkPeeringsOperations',
'VirtualNetworkGatewaysOperations',
'VirtualNetworkGatewayConnectionsOperations',
'LocalNetworkGatewaysOperations',
]
| {
"pile_set_name": "Github"
} |
[{include file="headitem.tpl" title="GENERAL_ADMIN_TITLE"|oxmultilangassign}]
<script type="text/javascript">
<!--
function editThis( sID )
{
var oTransfer = top.basefrm.edit.document.getElementById( "transfer" );
oTransfer.oxid.value = sID;
oTransfer.cl.value = top.basefrm.list.sDefClass;
//forcing edit frame to reload after submit
top.forceReloadingEditFrame();
var oSearch = top.basefrm.list.document.getElementById( "search" );
oSearch.oxid.value = sID;
oSearch.actedit.value = 0;
oSearch.submit();
}
[{if !$oxparentid}]
window.onload = function ()
{
[{if $updatelist == 1}]
top.oxid.admin.updateList('[{$oxid}]');
[{/if}]
var oField = top.oxid.admin.getLockTarget();
oField.onchange = oField.onkeyup = oField.onmouseout = top.oxid.admin.unlockSave;
}
[{/if}]
//-->
</script>
[{if $readonly}]
[{assign var="readonly" value="readonly disabled"}]
[{else}]
[{assign var="readonly" value=""}]
[{/if}]
<form name="transfer" id="transfer" action="[{$oViewConf->getSelfLink()}]" method="post">
[{$oViewConf->getHiddenSid()}]
<input type="hidden" name="oxid" value="[{$oxid}]">
<input type="hidden" name="oxidCopy" value="[{$oxid}]">
<input type="hidden" name="cl" value="article_main">
<input type="hidden" name="editlanguage" value="[{$editlanguage}]">
</form>
<form name="myedit" id="myedit" action="[{$oViewConf->getSelfLink()}]" method="post" onSubmit="return copyLongDesc('oxarticles__oxlongdesc');" style="padding: 0px;margin: 0px;height:0px;">
[{$oViewConf->getHiddenSid()}]
<input type="hidden" name="cl" value="article_main">
<input type="hidden" name="fnc" value="">
<input type="hidden" name="oxid" value="[{$oxid}]">
<input type="hidden" name="voxid" value="[{$oxid}]">
<input type="hidden" name="oxparentid" value="[{$oxparentid}]">
<input type="hidden" name="editval[oxarticles__oxid]" value="[{$oxid}]">
<input type="hidden" name="editval[oxarticles__oxlongdesc]" value="">
<table cellspacing="0" cellpadding="0" border="0" style="width:98%;">
<tr>
<td valign="top" class="edittext" style="padding-top:10px;padding-left:10px;">
<table cellspacing="0" cellpadding="0" border="0">
[{block name="admin_article_main_form"}]
[{if $errorsavingatricle}]
<tr>
<td colspan="2">
[{if $errorsavingatricle eq 1}]
<div class="errorbox">[{oxmultilang ident="ARTICLE_MAIN_ERRORSAVINGARTICLE"}]</div>
[{/if}]
</td>
</tr>
[{/if}]
[{block name="admin_article_main_extended_errorbox"}][{/block}]
[{if $oxparentid}]
<tr>
<td class="edittext" width="120">
<b>[{oxmultilang ident="ARTICLE_MAIN_VARIANTE"}]</b>
</td>
<td class="edittext">
<a href="Javascript:editThis('[{$parentarticle->oxarticles__oxid->value}]');" class="edittext"><b>[{$parentarticle->oxarticles__oxartnum->value}] [{$parentarticle->oxarticles__oxtitle->value}] [{if !$parentarticle->oxarticles__oxtitle->value}][{$parentarticle->oxarticles__oxvarselect->value}][{/if}]</b></a>
</td>
</tr>
[{/if}]
<tr>
<td class="edittext" width="120">
[{oxmultilang ident="ARTICLE_MAIN_ACTIVE"}]
</td>
<td class="edittext">
<input type="hidden" name="editval[oxarticles__oxactive]" value="0">
<input class="edittext" type="checkbox" name="editval[oxarticles__oxactive]" value='1' [{if $edit->oxarticles__oxactive->value == 1}]checked[{/if}] [{$readonly}]>
[{oxmultilang ident="ARTICLE_MAIN_HIDDEN"}]
<input type="hidden" name="editval[oxarticles__oxhidden]" value="0">
<input class="edittext" type="checkbox" name="editval[oxarticles__oxhidden]" value='1' [{if $edit->oxarticles__oxhidden->value == 1}]checked[{/if}] [{$readonly}]>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_ACTIVE"}]
</td>
</tr>
[{if $blUseTimeCheck}]
<tr>
<td class="edittext">
[{ oxmultilang ident="ARTICLE_MAIN_ACTIVFROMTILL" }]
</td>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_ACTIVEFROM"}] <input type="text" class="editinput" size="27" name="editval[oxarticles__oxactivefrom]" value="[{$edit->oxarticles__oxactivefrom|oxformdate}]" [{include file="help.tpl" helpid=article_vonbis}] [{$readonly}]><br>
[{oxmultilang ident="ARTICLE_MAIN_ACTIVETO"}] <input type="text" class="editinput" size="27" name="editval[oxarticles__oxactiveto]" value="[{$edit->oxarticles__oxactiveto|oxformdate}]" [{include file="help.tpl" helpid=article_vonbis}] [{$readonly}]>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_ACTIVFROMTILL"}]
</td>
</tr>
[{/if}]
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_TITLE"}]
</td>
<td class="edittext">
<input type="text" class="editinput" size="32" maxlength="[{$edit->oxarticles__oxtitle->fldmax_length}]" id="oLockTarget" name="editval[oxarticles__oxtitle]" value="[{$edit->oxarticles__oxtitle->value}]">
[{oxinputhelp ident="HELP_ARTICLE_MAIN_TITLE"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_ARTNUM"}]
</td>
<td class="edittext">
<input type="text" class="editinput" size="32" maxlength="[{$edit->oxarticles__oxartnum->fldmax_length}]" name="editval[oxarticles__oxartnum]" value="[{$edit->oxarticles__oxartnum->value}]" [{$readonly}]>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_ARTNUM"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_EAN"}]
</td>
<td class="edittext">
<input type="text" class="editinput" size="32" maxlength="[{$edit->oxarticles__oxean->fldmax_length}]" name="editval[oxarticles__oxean]" value="[{$edit->oxarticles__oxean->value}]">
[{oxinputhelp ident="HELP_ARTICLE_MAIN_EAN"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_DISTEAN"}]
</td>
<td class="edittext">
<input type="text" class="editinput" size="32" maxlength="[{$edit->oxarticles__oxdistean->fldmax_length}]" name="editval[oxarticles__oxdistean]" value="[{$edit->oxarticles__oxdistean->value}]">
[{oxinputhelp ident="HELP_ARTICLE_MAIN_DISTEAN"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_MPN"}]
</td>
<td class="edittext">
<input type="text" class="editinput" size="32" maxlength="[{$edit->oxarticles__oxmpn->fldmax_length}]" name="editval[oxarticles__oxmpn]" value="[{$edit->oxarticles__oxmpn->value}]">
[{oxinputhelp ident="HELP_ARTICLE_MAIN_MPN"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_SHORTDESC"}]
</td>
<td class="edittext">
<input type="text" class="editinput" size="32" maxlength="[{$edit->oxarticles__oxshortdesc->fldmax_length}]" name="editval[oxarticles__oxshortdesc]" value="[{$edit->oxarticles__oxshortdesc->value}]" [{$readonly}]>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_SHORTDESC"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_SEARCHKEYS"}]
</td>
<td class="edittext">
<input type="text" class="editinput" size="32" maxlength="[{$edit->oxarticles__oxsearchkeys->fldmax_length}]" name="editval[oxarticles__oxsearchkeys]" value="[{$edit->oxarticles__oxsearchkeys->value}]" [{$readonly}]>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_SEARCHKEYS"}]
</td>
</tr>
[{block name="admin_article_main_extended"}][{/block}]
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_VENDORID"}]
</td>
<td class="edittext">
<select class="editinput" name="editval[oxarticles__oxvendorid]" [{$readonly}]>
<option value="" selected>---</option>
[{foreach from=$oView->getVendorList() item=oVendor}]
<option value="[{$oVendor->oxvendor__oxid->value}]"[{if $edit->oxarticles__oxvendorid->value == $oVendor->oxvendor__oxid->value}] selected[{/if}]>[{ $oVendor->oxvendor__oxtitle->value }]</option>
[{/foreach}]
</select>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_VENDORID"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_MANUFACTURERID"}]
</td>
<td class="edittext">
<select class="editinput" name="editval[oxarticles__oxmanufacturerid]" [{$readonly}]>
<option value="" selected>---</option>
[{foreach from=$oView->getManufacturerList() item=oManufacturer }]
<option value="[{$oManufacturer->oxmanufacturers__oxid->value}]"[{if $edit->oxarticles__oxmanufacturerid->value == $oManufacturer->oxmanufacturers__oxid->value}] selected[{/if}]>[{ $oManufacturer->oxmanufacturers__oxtitle->value }]</option>
[{/foreach}]
</select>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_MANUFACTURERID"}]
</td>
</tr>
[{if $edit->isParentNotBuyable()}]
<tr>
<td colspan="2">
<div class="errorbox">[{oxmultilang ident="ARTICLE_MAIN_PARENTNOTBUYABLE"}]</div>
</td>
</tr>
[{/if}]
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_PRICE"}] ([{$oActCur->sign}])
</td>
<td class="edittext">
<input type="text" class="editinput" size="8" maxlength="[{$edit->oxarticles__oxprice->fldmax_length}]" name="editval[oxarticles__oxprice]" value="[{$edit->oxarticles__oxprice->value}]" [{$readonly}]>
[{assign var="oPrice" value=$edit->getPrice()}]
<em>( [{$oPrice->getBruttoPrice()}] )</em>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_PRICE"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_ALDPRICE"}] ([{$oActCur->sign}])
</td>
<td class="edittext" nowrap>
[{oxmultilang ident="ARTICLE_MAIN_PRICEA"}]: <input type="text" class="editinput" size="4" maxlength="[{$edit->oxarticles__oxpricea->fldmax_length}]" name="editval[oxarticles__oxpricea]" value="[{$edit->oxarticles__oxpricea->value}]" [{$readonly}]>
[{oxmultilang ident="ARTICLE_MAIN_PRICEB"}]: <input type="text" class="editinput" size="4" maxlength="[{$edit->oxarticles__oxpriceb->fldmax_length}]" name="editval[oxarticles__oxpriceb]" value="[{$edit->oxarticles__oxpriceb->value}]" [{$readonly}]>
[{oxmultilang ident="ARTICLE_MAIN_PRICEC"}]: <input type="text" class="editinput" size="4" maxlength="[{$edit->oxarticles__oxpricec->fldmax_length}]" name="editval[oxarticles__oxpricec]" value="[{$edit->oxarticles__oxpricec->value}]" [{$readonly}]>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_ALDPRICE"}]
</td>
</tr>
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_VAT"}]
</td>
<td class="edittext">
<input type="text" class="editinput" size="10" maxlength="[{$edit->oxarticles__oxvat->fldmax_length}]" name="editval[oxarticles__oxvat]" value="[{$edit->oxarticles__oxvat->value}]" [{include file="help.tpl" helpid=article_vat}] [{$readonly}]>
[{oxinputhelp ident="HELP_ARTICLE_MAIN_VAT"}]
</td>
</tr>
[{/block}]
<tr>
<td class="edittext" colspan="2"><br><br>
<input type="submit" class="edittext" id="oLockButton" name="saveArticle" value="[{oxmultilang ident="ARTICLE_MAIN_SAVE"}]" onClick="Javascript:document.myedit.fnc.value='save'" [{if !$edit->oxarticles__oxtitle->value && !$oxparentid}]disabled[{/if}] [{$readonly}]>
[{if $oxid!=-1 && !$readonly}]
<input type="submit" class="edittext" name="save" value="[{oxmultilang ident="ARTICLE_MAIN_ARTCOPY"}]" onClick="Javascript:document.myedit.fnc.value='copyArticle';" [{$readonly}]>
[{/if}]
</td>
</tr>
[{if $oxid == -1}]
<tr>
<td class="edittext">
[{oxmultilang ident="ARTICLE_MAIN_INCATEGORY"}]:
</td>
<td class="edittext">
<select name="art_category" class="editinput" onChange="Javascript:top.oxid.admin.changeLstrt()" [{$readonly}]>
<option value="-1">[{oxmultilang ident="ARTICLE_MAIN_NONE"}]</option>
[{foreach from=$oView->getCategoryList() item=pcat}]
<option value="[{$pcat->oxcategories__oxid->value}]">[{$pcat->oxcategories__oxtitle->getRawValue()|oxtruncate:40:"..":true}]</option>
[{/foreach}]
</select>
[{oxinputhelp ident="HELP_"}]
</td>
</tr>
[{/if}]
<tr>
<td class="edittext" colspan="2"><br>
[{include file="language_edit.tpl"}]<br>
</td>
</tr>
[{if $oxid!=-1 && $thisvariantlist}]
<tr>
<td class="edittext">[{oxmultilang ident="ARTICLE_MAIN_GOTO"}]</td>
<td class="edittext">
[{include file="variantlist.tpl"}]
</td>
</tr>
[{/if}]
</table>
</td>
<!-- Anfang rechte Seite -->
<td valign="top" class="edittext" align="left" style="width:100%;height:99%;padding-left:5px;padding-bottom:30px;padding-top:10px;">
[{block name="admin_article_main_editor"}]
[{include file="include/editor.tpl"}]
[{/block}]
</td>
<!-- Ende rechte Seite -->
</tr>
</table>
</form>
[{include file="bottomnaviitem.tpl"}]
[{include file="bottomitem.tpl"}]
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pt-BR" original="../COMReference.xaml">
<body>
<trans-unit id="BoolProperty|CopyLocal|Description">
<source>Indicates whether the reference will be copied to the output directory.</source>
<target state="translated">Indica se a referência será copiada para o diretório de saída.</target>
<note />
</trans-unit>
<trans-unit id="BoolProperty|CopyLocal|DisplayName">
<source>Copy Local</source>
<target state="translated">Local da Cópia</target>
<note />
</trans-unit>
<trans-unit id="BoolProperty|EmbedInteropTypes|Description">
<source>Indicates whether types defined in this assembly will be embedded into the target assembly.</source>
<target state="translated">Indica se os tipos definidos neste assembly serão inseridos no assembly de destino.</target>
<note />
</trans-unit>
<trans-unit id="BoolProperty|EmbedInteropTypes|DisplayName">
<source>Embed Interop Types</source>
<target state="translated">Inserir Tipos Interop</target>
<note />
</trans-unit>
<trans-unit id="Rule|ComReference|DisplayName">
<source>COM Reference</source>
<target state="translated">Referência COM</target>
<note />
</trans-unit>
<trans-unit id="Rule|ComReference|Description">
<source>COM Reference Properties</source>
<target state="translated">Propriedades de Referência COM</target>
<note />
</trans-unit>
<trans-unit id="StringListProperty|Aliases|Description">
<source>A comma-delimited list of aliases to this reference.</source>
<target state="translated">Uma lista delimitada por vírgula de aliases para esta referência.</target>
<note />
</trans-unit>
<trans-unit id="StringListProperty|Aliases|DisplayName">
<source>Aliases</source>
<target state="translated">Aliases</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|Guid|DisplayName">
<source>CLSID</source>
<target state="translated">CLSID</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|Guid|Description">
<source>The GUID of the COM server.</source>
<target state="translated">O GUID do servidor COM.</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|Identity|Description">
<source>Security identity of the referenced assembly (see System.Reflection.Assembly.Evidence or System.Security.Policy.Evidence).</source>
<target state="translated">Identidade de segurança do assembly referenciado (veja System.Reflection.Assembly.Evidence ou System.Security.Policy.Evidence).</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|Identity|DisplayName">
<source>Identity</source>
<target state="translated">Identidade</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|Lcid|DisplayName">
<source>Locale</source>
<target state="translated">Localidade</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|Lcid|Description">
<source>The LCID of the COM server.</source>
<target state="translated">O LCID do servidor COM.</target>
<note />
</trans-unit>
<trans-unit id="IntProperty|VersionMajor|DisplayName">
<source>Major Version</source>
<target state="translated">Versão Principal</target>
<note />
</trans-unit>
<trans-unit id="IntProperty|VersionMinor|DisplayName">
<source>Minor Version</source>
<target state="translated">Versão Secundária </target>
<note />
</trans-unit>
<trans-unit id="StringProperty|ResolvedPath|Description">
<source>Location of the file being referenced.</source>
<target state="translated">Localização do arquivo que está sendo referenciado.</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|ResolvedPath|DisplayName">
<source>Path</source>
<target state="translated">Caminho</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|Version|Description">
<source>Version of reference.</source>
<target state="translated">Versão de referência.</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|Version|DisplayName">
<source>Version</source>
<target state="translated">Versão</target>
<note />
</trans-unit>
<trans-unit id="StringProperty|WrapperTool|DisplayName">
<source>Wrapper Tool</source>
<target state="translated">Ferramenta do Wrapper</target>
<note />
</trans-unit>
<trans-unit id="BoolProperty|Isolated|DisplayName">
<source>Isolated</source>
<target state="translated">Isolada</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | {
"pile_set_name": "Github"
} |
# Name:Draytek Vigor 2XXX/3XXX series config file decryption and decompression with password extraction
# File:vigor_config.py
# Author:Ján Trenčanský
# License: GNU GPL v3
# Created: 7.3.2014
# Last modified: 7.3.2014
# Shodan Dork:
# Description: Guess the state of config file and decrypt and decompress it, extract passwords
# Based on draytools work of Nikita Abdullin (AMMOnium) https://github.com/ammonium/draytools
# TODO: No sample of older cfg file, so not able to test properly.
# TODO: All cfgs use new encryption. Works with decrypted cfg
import core.Decryptor
import core.io
import core.compression.lzo
from interface.messages import print_success, print_green, print_yellow, print_warning, print_info
from collections import defaultdict
from struct import unpack, pack
import math
class Decryptor(core.Decryptor.RextDecryptor):
"""
Name:Draytek Vigor 2XXX/3XXX series config file decryption and decompression with password extraction
File:vigor_config.py
Author:Ján Trenčanský
License: GNU GPL v3
Created: 7.3.2014
Description: Guess the state of config file and decrypt and decompress it, extract passwords
Based on: draytools work of Nikita Abdullin (AMMOnium) https://github.com/ammonium/draytools
Options:
Name Description
file Input config file path
"""
CFG_RAW = 0
CFG_LZO = 1
CFG_ENC = 2
def __init__(self):
core.Decryptor.RextDecryptor.__init__(self)
def do_run(self, e):
f = open(self.input_file, 'rb')
data = f.read()
f.close()
g, outdata = self.de_cfg(data)
if g != self.CFG_RAW:
core.io.writefile(outdata, "config.out")
print_success("config file written to config.out, extracting credentials...")
creds = self.get_credentials(outdata)
print_green("Login :\t" + (creds[0] == b"" and b"admin" or creds[0]).decode())
print_green("Password :\t" + (creds[1] == b"" and b"admin" or creds[1]).decode())
def de_cfg(self, data):
"""Get raw config data from raw /compressed/encrypted & comressed"""
g = self.smart_guess(data)
if g == self.CFG_RAW:
print_warning('File is :\tnot compressed, not encrypted')
return g, data
elif g == self.CFG_LZO:
print_warning('File is :\tcompressed, not encrypted')
return g, self.decompress_cfg(data)
elif g == self.CFG_ENC:
print_warning('File is :\tcompressed, encrypted')
return g, self.decompress_cfg(self.decrypt_cfg(data))
def smart_guess(self, data):
"""Guess is the cfg block compressed or not"""
# Uncompressed block is large and has low entropy
if self.entropy(data) < 1.0 or len(data) > 0x10000:
return self.CFG_RAW
# Compressed block still has pieces of cleartext at the beginning
if b"Vigor" in data and (b"Series" in data or b"draytek" in data):
return self.CFG_LZO
return self.CFG_ENC
def entropy(self, data):
"""Calculate Shannon entropy (in bits per byte)"""
flist = defaultdict(int)
dlen = len(data)
data = map(int, data)
# count occurencies
for byte in data:
flist[byte] += 1
ent = 0.0
# convert count of occurencies into frequency
for freq in flist.values():
if freq > 0:
ffreq = float(freq) / dlen
# actual entropy calcualtion
ent -= ffreq * math.log(ffreq, 2)
return ent
def get_modelid(self, data):
"""Extract a model ID from config file header"""
modelid = data[0x0C:0x0E]
return modelid
def decompress_cfg(self, data):
"""Decompress a config file"""
modelstr = "V" + format(unpack(">H", self.get_modelid(data))[0], "04X")
print_info('Model is :\t' + modelstr)
rawcfgsize = 0x00100000
lzocfgsize = unpack(">L", data[0x24:0x28])[0]
raw = data[:0x2D] + b'\x00' + data[0x2E:0x100] + \
core.compression.lzo.pydelzo.decompress(b'\xF0' + pack(">L", rawcfgsize) + data[0x100:0x100 + lzocfgsize])
return raw
def decrypt_cfg(self, data):
"""Decrypt config, bruteforce if default key fails"""
modelstr = "V" + format(unpack(">H", self.get_modelid(data))[0], "04X")
print_info('Model is :\t' + modelstr)
ckey = self.make_key(modelstr)
rdata = self.decrypt(data[0x100:], ckey)
# if the decrypted data does not look good, bruteforce
if self.smart_guess(rdata) != self.CFG_LZO:
rdata = self.brute_cfg(data[0x100:])
print_success('Used key :\t[0x%02X]' % ckey)
return data[:0x2D] + b'\x01' + data[0x2E:0x100] + rdata
def make_key(self, modelstr):
"""Construct a key out of a model string (like 'V2710')"""
key_sum = 0
for c in modelstr:
key_sum += ord(c)
return 0xFF & key_sum
def enc(self, c, key):
c ^= key
c -= key
c = 0xFF & (c >> 5 | c << 3)
return c
def dec(self, c, key):
c = (c << 5 | c >> 3)
c += key
c ^= key
c &= 0xFF
return c
def decrypt(self, data, key):
"""Decrypt a block of data using given key"""
rdata = b''
for i in range(len(data)):
rdata += bytes(self.dec(data[i], key))
return rdata
# return ''.join(map(lambda od:chr(draytools.dec(ord(od),key)),data))
def brute_cfg(self, data):
"""Check all possible keys until data looks like decrypted"""
rdata = None
key = 0
for i in range(256):
rdata = self.decrypt(data, i)
if self.smart_guess(rdata) == self.CFG_LZO:
key = i
break
print_success('Found key:\t[0x%02X]' % key)
return rdata
def get_credentials(self, data):
"""Extract admin credentials from config"""
login = data[0x100 + 0x28:0x100 + 0x40].split(b'\x00')[0]
password = data[0x100 + 0x40:0x100 + 0x58].split(b'\x00')[0]
return [login, password]
Decryptor() | {
"pile_set_name": "Github"
} |
//
// SPPlaylistContainer.m
// CocoaLibSpotify
//
// Created by Daniel Kennett on 2/19/11.
/*
Copyright (c) 2011, Spotify AB
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Spotify AB nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL SPOTIFY AB 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.
*/
#import "SPPlaylistContainer.h"
#import "SPPlaylistFolder.h"
#import "SPUser.h"
#import "SPSession.h"
#import "SPPlaylist.h"
#import "SPErrorExtensions.h"
#import "SPPlaylistContainerInternal.h"
#import "SPPlaylistFolderInternal.h"
@interface SPPlaylistContainerCallbackProxy : NSObject
// SPPlaylistContainerCallbackProxy is here to bridge the gap between -dealloc and the
// playlist callbacks being unregistered, since that's done async.
@property (nonatomic, readwrite, assign) __unsafe_unretained SPPlaylistContainer *container;
@end
@implementation SPPlaylistContainerCallbackProxy
@synthesize container;
@end
@interface SPPlaylistContainer ()
-(NSArray *)createPlaylistTree;
@property (nonatomic, readwrite, strong) SPUser *owner;
@property (nonatomic, readwrite, assign) __unsafe_unretained SPSession *session;
@property (nonatomic, readwrite, getter=isLoaded) BOOL loaded;
@property (nonatomic, readwrite, strong) NSArray *playlists;
@property (nonatomic, readwrite, strong) NSMutableDictionary *folderCache;
@property (nonatomic, readwrite, strong) SPPlaylistContainerCallbackProxy *callbackProxy;
@property (nonatomic, readwrite, strong) NSMutableArray *playlistAddCallbackStack;
@property (nonatomic, readwrite, strong) NSMutableArray *playlistRemoveCallbackStack;
@property (nonatomic, readwrite) sp_playlistcontainer *container;
-(NSRange)rangeOfFolderInRootList:(SPPlaylistFolder *)folder;
-(NSInteger)indexInFlattenedListForIndex:(NSUInteger)virtualIndex inFolder:(SPPlaylistFolder *)parentFolder;
-(void)removeFolderFromTree:(SPPlaylistFolder *)aPlaylistOrFolderIndex callback:(SPErrorableOperationCallback)block;
-(void)removePlaylist:(SPPlaylist *)aPlaylist callback:(SPErrorableOperationCallback)block;
-(NSArray *)playlistsInFolder:(SPPlaylistFolder *)folder;
@end
static void playlist_added(sp_playlistcontainer *pc, sp_playlist *playlist, int position, void *userdata) {
// Find the object model container, add the playlist to it
SPPlaylistContainerCallbackProxy *proxy = (__bridge SPPlaylistContainerCallbackProxy *)userdata;
SPPlaylistContainer *container = proxy.container;
if (!container) return;
NSArray *newTree = [container createPlaylistTree];
SPPlaylist *newPlaylist = [SPPlaylist playlistWithPlaylistStruct:playlist inSession:container.session];
void (^callback)(SPPlaylist *) = nil;
if (container.playlistAddCallbackStack.count > 0) {
callback = [container.playlistAddCallbackStack objectAtIndex:0];
[container.playlistAddCallbackStack removeObjectAtIndex:0];
}
dispatch_async(dispatch_get_main_queue(), ^() {
container.playlists = newTree;
if (callback) callback(newPlaylist);
});
}
static void playlist_removed(sp_playlistcontainer *pc, sp_playlist *playlist, int position, void *userdata) {
SPPlaylistContainerCallbackProxy *proxy = (__bridge SPPlaylistContainerCallbackProxy *)userdata;
SPPlaylistContainer *container = proxy.container;
if (!container) return;
NSArray *newTree = [container createPlaylistTree];
SPErrorableOperationCallback callback = nil;
if (container.playlistRemoveCallbackStack.count > 0) {
callback = [container.playlistRemoveCallbackStack objectAtIndex:0];
[container.playlistRemoveCallbackStack removeObjectAtIndex:0];
}
dispatch_async(dispatch_get_main_queue(), ^() {
container.playlists = newTree;
if (callback) callback(nil);
});
}
static void playlist_moved(sp_playlistcontainer *pc, sp_playlist *playlist, int position, int new_position, void *userdata) {
// Find the old and new containers. If they're the same, move, otherwise remove from old and add to new
}
static void container_loaded(sp_playlistcontainer *pc, void *userdata) {
SPPlaylistContainerCallbackProxy *proxy = (__bridge SPPlaylistContainerCallbackProxy *)userdata;
SPPlaylistContainer *container = proxy.container;
if (!container) return;
SPUser *user = [SPUser userWithUserStruct:sp_playlistcontainer_owner(container.container) inSession:container.session];
NSArray *newTree = [container createPlaylistTree];
dispatch_async(dispatch_get_main_queue(), ^() {
container.owner = user;
container.playlists = newTree;
container.loaded = YES;
});
}
static sp_playlistcontainer_callbacks playlistcontainer_callbacks = {
&playlist_added,
&playlist_removed,
&playlist_moved,
&container_loaded
};
#pragma mark -
@implementation SPPlaylistContainer
-(NSString *)description {
return [NSString stringWithFormat:@"%@: %@", [super description], [self playlists]];
}
@synthesize owner;
@synthesize session;
@synthesize container = _container;
@synthesize loaded;
@synthesize folderCache;
@synthesize playlists;
@synthesize callbackProxy;
@synthesize playlistAddCallbackStack;
@synthesize playlistRemoveCallbackStack;
-(sp_playlistcontainer *)container {
#if DEBUG
SPAssertOnLibSpotifyThread();
#endif
return _container;
}
-(void)startLoading {
SPDispatchAsync(^{
if (self.callbackProxy != nil) return;
self.callbackProxy = [[SPPlaylistContainerCallbackProxy alloc] init];
self.callbackProxy.container = self;
sp_playlistcontainer_add_callbacks(self.container, &playlistcontainer_callbacks, (__bridge void *)(self.callbackProxy));
NSArray *newTree = [self createPlaylistTree];
SPUser *user = nil;
BOOL isLoaded = sp_playlistcontainer_is_loaded(self.container);
if (isLoaded)
user = [SPUser userWithUserStruct:sp_playlistcontainer_owner(self.container) inSession:self.session];
dispatch_async(dispatch_get_main_queue(), ^() {
self.owner = user;
self.playlists = newTree;
self.loaded = isLoaded;
});
});
}
-(NSArray *)createPlaylistTree {
SPAssertOnLibSpotifyThread();
NSInteger itemCount = sp_playlistcontainer_num_playlists(self.container);
if (itemCount == -1) return nil;
NSMutableArray *rootPlaylistList = [NSMutableArray arrayWithCapacity:itemCount];
SPPlaylistFolder *folderAtTopOfStack = nil;
for (int currentItem = 0; currentItem < itemCount; currentItem++) {
sp_playlist_type type = sp_playlistcontainer_playlist_type(self.container, currentItem);
if (type == SP_PLAYLIST_TYPE_START_FOLDER) {
sp_uint64 folderId = sp_playlistcontainer_playlist_folder_id(self.container, currentItem);
SPPlaylistFolder *folder = [self.session playlistFolderForFolderId:folderId inContainer:self];
[folder clearAllItems];
char nameChars[256];
sp_error nameError = sp_playlistcontainer_playlist_folder_name(self.container, currentItem, nameChars, sizeof(nameChars));
if (nameError == SP_ERROR_OK)
folder.name = [NSString stringWithUTF8String:nameChars];
if (folderAtTopOfStack) {
[folderAtTopOfStack addObject:folder];
folder.parentFolder = folderAtTopOfStack;
} else {
[rootPlaylistList addObject:folder];
folder.parentFolder = nil;
}
folderAtTopOfStack = folder;
} else if (type == SP_PLAYLIST_TYPE_END_FOLDER) {
sp_uint64 folderId = sp_playlistcontainer_playlist_folder_id(self.container, currentItem);
if (folderAtTopOfStack.folderId != folderId)
NSLog(@"[%@ %@]: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), @"WARNING: Root list is insane!");
folderAtTopOfStack = folderAtTopOfStack.parentFolder;
} else if (type == SP_PLAYLIST_TYPE_PLAYLIST) {
SPPlaylist *playlist = [SPPlaylist playlistWithPlaylistStruct:sp_playlistcontainer_playlist(self.container, currentItem)
inSession:self.session];
if (folderAtTopOfStack)
[folderAtTopOfStack addObject:playlist];
else
[rootPlaylistList addObject:playlist];
} else if (type == SP_PLAYLIST_TYPE_PLACEHOLDER) {
SPUnknownPlaylist *playlist = [self.session unknownPlaylistForPlaylistStruct:sp_playlistcontainer_playlist(self.container, currentItem)];
if (folderAtTopOfStack)
[folderAtTopOfStack addObject:playlist];
else
[rootPlaylistList addObject:playlist];
}
}
return [NSArray arrayWithArray:rootPlaylistList];
}
-(NSInteger)indexInFlattenedListForIndex:(NSUInteger)virtualIndex inFolder:(SPPlaylistFolder *)parentFolder {
SPAssertOnLibSpotifyThread();
NSMutableArray *indexes = [NSMutableArray arrayWithCapacity:self.playlists.count];
NSRange folderRangeInRootList = [self rangeOfFolderInRootList:parentFolder];
if (folderRangeInRootList.location == NSNotFound) return NSNotFound;
NSRange rangeOfPlaylists = parentFolder == nil ? folderRangeInRootList : NSMakeRange(folderRangeInRootList.location + 1, folderRangeInRootList.length - 2);
NSUInteger currentRootlistIndex = rangeOfPlaylists.location;
NSArray *playlistsOfParent = parentFolder == nil ? self.playlists : parentFolder.playlists;
for (NSUInteger currentIndex = 0; currentIndex < playlistsOfParent.count; currentIndex++) {
// For each index in our items, we want the rootlist index that'd replace it.
[indexes addObject:[NSNumber numberWithInteger:currentRootlistIndex]];
id item = [playlistsOfParent objectAtIndex:currentIndex];
if ([item isKindOfClass:[SPPlaylist class]])
currentRootlistIndex++;
else if ([item isKindOfClass:[SPPlaylistFolder class]])
currentRootlistIndex += [self rangeOfFolderInRootList:item].length;
}
// The indexes array now contains the root list index for the item at the virtual index
if (virtualIndex == playlistsOfParent.count)
return rangeOfPlaylists.location + rangeOfPlaylists.length; // Why did we just do that loop?
else if (virtualIndex > playlistsOfParent.count)
return NSNotFound;
else
return [[indexes objectAtIndex:virtualIndex] integerValue];
}
-(NSInteger)virtualIndexForFlattenedIndex:(NSUInteger)flattenedIndex parentFolder:(SPPlaylistFolder **)parent {
return NSNotFound;
}
-(NSRange)rangeOfFolderInRootList:(SPPlaylistFolder *)folder {
SPAssertOnLibSpotifyThread();
if (!folder) return NSMakeRange(0, sp_playlistcontainer_num_playlists(self.container));
NSRange folderRange = NSMakeRange(NSNotFound, 0);
NSInteger itemCount = sp_playlistcontainer_num_playlists(self.container);
for (int currentItem = 0; currentItem < itemCount; currentItem++) {
sp_playlist_type type = sp_playlistcontainer_playlist_type(self.container, currentItem);
if (type == SP_PLAYLIST_TYPE_START_FOLDER) {
sp_uint64 folderId = sp_playlistcontainer_playlist_folder_id(self.container, currentItem);
if (folderId == folder.folderId)
folderRange.location = currentItem;
} else if (type == SP_PLAYLIST_TYPE_END_FOLDER) {
sp_uint64 folderId = sp_playlistcontainer_playlist_folder_id(self.container, currentItem);
if (folderId == folder.folderId) {
folderRange.length = (currentItem - folderRange.location) + 1;
if (folderRange.location == NSNotFound)
NSLog(@"[%@ %@]: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), @"WARNING: Root list is insane!");
}
}
}
return folderRange;
}
#pragma mark -
-(NSArray *)flattenedPlaylists {
NSArray *tree = [self.playlists copy];
NSMutableArray *flatList = [NSMutableArray array];
for (id item in tree) {
if ([item isKindOfClass:[SPPlaylist class]])
[flatList addObject:item];
else if ([item isKindOfClass:[SPPlaylistFolder class]])
[flatList addObjectsFromArray:[self playlistsInFolder:item]];
}
return [NSArray arrayWithArray:flatList];
}
-(NSArray *)playlistsInFolder:(SPPlaylistFolder *)folder {
NSMutableArray *playlistsInFolder = [NSMutableArray array];
for (id item in folder.playlists) {
if ([item isKindOfClass:[SPPlaylist class]])
[playlistsInFolder addObject:item];
else if ([item isKindOfClass:[SPPlaylistFolder class]])
[playlistsInFolder addObjectsFromArray:[self playlistsInFolder:item]];
}
return [NSArray arrayWithArray:playlistsInFolder];
}
-(void)createPlaylistWithName:(NSString *)name callback:(void (^)(SPPlaylist *))block {
SPDispatchAsync(^{
if ([[name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0 ||
[name length] > 255) {
dispatch_async(dispatch_get_main_queue(), ^() { if (block) block(nil); });
return;
}
if (block)
[self.playlistAddCallbackStack addObject:block];
sp_playlist *newPlaylist = sp_playlistcontainer_add_new_playlist(self.container, [name UTF8String]);
if (newPlaylist == NULL && block) {
[self.playlistAddCallbackStack removeObject:block];
dispatch_async(dispatch_get_main_queue(), ^{ block(nil); });
}
});
}
-(void)createFolderWithName:(NSString *)name callback:(void (^)(SPPlaylistFolder *, NSError *))block {
SPDispatchAsync(^{
sp_error errorCode = sp_playlistcontainer_add_folder(self.container, 0, [name UTF8String]);
NSError *error = nil;
SPPlaylistFolder *folder = nil;
if (errorCode == SP_ERROR_OK)
folder = [[SPPlaylistFolder alloc] initWithPlaylistFolderId:sp_playlistcontainer_playlist_folder_id(self.container, 0)
container:self
inSession:self.session];
else if (error != NULL)
error = [NSError spotifyErrorWithCode:errorCode];
dispatch_async(dispatch_get_main_queue(), ^() { if (block) block(folder, error); });
});
}
-(void)removeItem:(id)playlistOrFolder callback:(SPErrorableOperationCallback)block {
if ([playlistOrFolder isKindOfClass:[SPPlaylistFolder class]])
[self removeFolderFromTree:playlistOrFolder callback:block];
else if ([playlistOrFolder isKindOfClass:[SPPlaylist class]])
[self removePlaylist:playlistOrFolder callback:block];
else if (block)
block([NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA]);
}
-(void)removePlaylist:(SPPlaylist *)aPlaylist callback:(SPErrorableOperationCallback)block {
if (aPlaylist == nil)
if (block) dispatch_async(dispatch_get_main_queue(), ^{ block([NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA]); });
SPDispatchAsync(^{
NSUInteger playlistCount = sp_playlistcontainer_num_playlists(self.container);
if (block)
[self.playlistRemoveCallbackStack addObject:block];
NSError *error = [NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA];
for (int currentIndex = 0; currentIndex < playlistCount; currentIndex++) {
sp_playlist *playlist = sp_playlistcontainer_playlist(self.container, currentIndex);
if (playlist == aPlaylist.playlist) {
sp_error errorCode = sp_playlistcontainer_remove_playlist(self.container, currentIndex);
if (errorCode != SP_ERROR_OK)
error = [NSError spotifyErrorWithCode:errorCode];
else
error = nil;
break;
}
}
if (error) {
[self.playlistRemoveCallbackStack removeObject:block];
dispatch_async(dispatch_get_main_queue(), ^{ block(error); });
}
});
}
-(void)removeFolderFromTree:(SPPlaylistFolder *)aFolder callback:(SPErrorableOperationCallback)block {
if (aFolder == nil)
if (block) dispatch_async(dispatch_get_main_queue(), ^{ block([NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA]); });
SPDispatchAsync(^{
// Remove callbacks, since we have to remove two playlists and reacting to list change notifications halfway through would be bad.
self.callbackProxy.container = nil;
sp_playlistcontainer_remove_callbacks(self.container, &playlistcontainer_callbacks, (__bridge void *)(self.callbackProxy));
self.callbackProxy = nil;
NSRange folderRange = [self rangeOfFolderInRootList:aFolder];
NSUInteger entriesToRemove = folderRange.length;
while (entriesToRemove > 0) {
sp_playlistcontainer_remove_playlist(self.container, (int)folderRange.location);
entriesToRemove--;
}
self.callbackProxy = [[SPPlaylistContainerCallbackProxy alloc] init];
self.callbackProxy.container = self;
sp_playlistcontainer_add_callbacks(self.container, &playlistcontainer_callbacks, (__bridge void *)(self.callbackProxy));
NSArray *newTree = [self createPlaylistTree];
dispatch_async(dispatch_get_main_queue(), ^{
self.playlists = newTree;
if (block) block(nil);
});
});
}
-(void)moveItem:(id)playlistOrFolder
toIndex:(NSUInteger)newIndex
ofNewParent:(SPPlaylistFolder *)aParentFolderOrNil
callback:(SPErrorableOperationCallback)block {
if ([playlistOrFolder isKindOfClass:[SPPlaylist class]]) {
SPDispatchAsync(^{
NSInteger sourceIndex = NSNotFound;
SPPlaylist *sourcePlaylist = playlistOrFolder;
NSUInteger playlistCount = sp_playlistcontainer_num_playlists(self.container);
for (int currentIndex = 0; currentIndex < playlistCount; currentIndex++) {
sp_playlist *playlist = sp_playlistcontainer_playlist(self.container, currentIndex);
if (playlist == sourcePlaylist.playlist) {
sourceIndex = currentIndex;
break;
}
}
if (sourceIndex == NSNotFound) {
dispatch_async(dispatch_get_main_queue(), ^{ if (block) block([NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA]); });
return;
}
NSInteger destinationIndex = [self indexInFlattenedListForIndex:newIndex inFolder:aParentFolderOrNil];
if (destinationIndex == NSNotFound) {
dispatch_async(dispatch_get_main_queue(), ^{ if (block) block([NSError spotifyErrorWithCode:SP_ERROR_INDEX_OUT_OF_RANGE]); });
return;
}
sp_error errorCode = sp_playlistcontainer_move_playlist(self.container, (int)sourceIndex, (int)destinationIndex, false);
if (errorCode != SP_ERROR_OK)
dispatch_async(dispatch_get_main_queue(), ^{ if (block) block([NSError spotifyErrorWithCode:errorCode]); });
else if (block)
dispatch_async(dispatch_get_main_queue(), ^{ block(nil); });
});
} else if ([playlistOrFolder isKindOfClass:[SPPlaylistFolder class]]) {
SPDispatchAsync(^{
self.callbackProxy.container = nil;
sp_playlistcontainer_remove_callbacks(self.container, &playlistcontainer_callbacks, (__bridge void *)(self.callbackProxy));
self.callbackProxy = nil;
NSInteger sourceIndex = NSNotFound;
SPPlaylistFolder *folder = playlistOrFolder;
NSRange folderRange = [self rangeOfFolderInRootList:folder];
sourceIndex = folderRange.location;
if (sourceIndex == NSNotFound) {
dispatch_async(dispatch_get_main_queue(), ^{ if (block) block([NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA]); });
return;
}
NSInteger destinationIndex = [self indexInFlattenedListForIndex:newIndex inFolder:aParentFolderOrNil];
if (destinationIndex == NSNotFound) {
dispatch_async(dispatch_get_main_queue(), ^{ if (block) block([NSError spotifyErrorWithCode:SP_ERROR_INDEX_OUT_OF_RANGE]); });
return;
}
for (NSUInteger entriesToMove = folderRange.length; entriesToMove > 0; entriesToMove--) {
sp_error errorCode = sp_playlistcontainer_move_playlist(self.container, (int)sourceIndex, (int)destinationIndex, false);
NSError *error = errorCode == SP_ERROR_OK ? nil : [NSError spotifyErrorWithCode:errorCode];
if (error) {
dispatch_async(dispatch_get_main_queue(), ^() { if (block) block(error); });
return;
}
if (destinationIndex < sourceIndex) {
destinationIndex++;
sourceIndex++;
}
}
self.callbackProxy = [[SPPlaylistContainerCallbackProxy alloc] init];
self.callbackProxy.container = self;
sp_playlistcontainer_add_callbacks(self.container, &playlistcontainer_callbacks, (__bridge void *)(self.callbackProxy));
if (sp_playlistcontainer_is_loaded(self.container))
container_loaded(self.container, (__bridge void *)(self.callbackProxy));
dispatch_async(dispatch_get_main_queue(), ^() { if (block) block(nil); });
});
} else if (block) {
block([NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA]);
}
}
-(void)subscribeToPlaylist:(SPPlaylist *)playlist callback:(SPErrorableOperationCallback)block {
if (playlist == nil ||
playlist.owner == self.session.user ||
[self.flattenedPlaylists containsObject:playlist]) {
if (block) block([NSError spotifyErrorWithCode:SP_ERROR_INVALID_INDATA]);
return;
}
SPDispatchAsync(^{
sp_link *link = sp_link_create_from_playlist(playlist.playlist);
sp_playlist *subbedPlaylist = sp_playlistcontainer_add_playlist(self.container, link);
sp_link_release(link);
link = NULL;
if (block)
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error = nil;
if (subbedPlaylist == NULL)
error = [NSError spotifyErrorWithCode:SP_ERROR_OTHER_PERMANENT];
block(error);
});
});
}
-(void)dealloc {
self.session = nil;
sp_playlistcontainer *outgoing_container = _container;
SPPlaylistContainerCallbackProxy *outgoingProxy = self.callbackProxy;
self.callbackProxy.container = nil;
self.callbackProxy = nil;
SPDispatchAsync(^() {
if (outgoing_container) sp_playlistcontainer_remove_callbacks(outgoing_container, &playlistcontainer_callbacks, (__bridge void *)outgoingProxy);
if (outgoing_container) sp_playlistcontainer_release(outgoing_container);
});
}
@end
@implementation SPPlaylistContainer (SPPlaylistContainerInternal)
-(id)initWithContainerStruct:(sp_playlistcontainer *)aContainer inSession:(SPSession *)aSession {
SPAssertOnLibSpotifyThread();
if ((self = [super init])) {
self.container = aContainer;
sp_playlistcontainer_add_ref(self.container);
self.session = aSession;
self.playlistAddCallbackStack = [NSMutableArray new];
self.playlistRemoveCallbackStack = [NSMutableArray new];
if (self.session.loadingPolicy == SPAsyncLoadingImmediate)
dispatch_async(dispatch_get_main_queue(), ^() { [self startLoading]; });
}
return self;
}
-(void)printRootList {
SPAssertOnLibSpotifyThread();
NSInteger itemCount = sp_playlistcontainer_num_playlists(self.container);
if (itemCount == -1) {
NSLog(@"Item count of container is -1.");
return;
}
for (int currentItem = 0; currentItem < itemCount; currentItem++) {
sp_playlist_type type = sp_playlistcontainer_playlist_type(self.container, currentItem);
if (type == SP_PLAYLIST_TYPE_START_FOLDER) {
sp_uint64 folderId = sp_playlistcontainer_playlist_folder_id(self.container, currentItem);
char nameChars[256];
NSString *folderName = nil;
sp_error nameError = sp_playlistcontainer_playlist_folder_name(self.container, currentItem, nameChars, sizeof(nameChars));
if (nameError == SP_ERROR_OK)
folderName = [NSString stringWithUTF8String:nameChars];
NSLog(@"%u: ---- Folder Start Marker: %llu ---- (%@)", currentItem, folderId, folderName);
} else if (type == SP_PLAYLIST_TYPE_END_FOLDER) {
sp_uint64 folderId = sp_playlistcontainer_playlist_folder_id(self.container, currentItem);
NSLog(@"%u: ---- Folder End Marker: %llu ----", currentItem, folderId);
} else if (type == SP_PLAYLIST_TYPE_PLAYLIST) {
sp_playlist *pl = sp_playlistcontainer_playlist(self.container, currentItem);
NSString *playlistName = [NSString stringWithUTF8String:sp_playlist_name(pl)];
sp_link *link = sp_link_create_from_playlist(pl);
char uriChars[256];
sp_link_as_string(link, (char *)&uriChars, sizeof(uriChars));
NSString *playlistUrl = [NSString stringWithUTF8String:uriChars];
free(link);
link = NULL;
NSLog(@"%u: Playlist: %@ (%@)", currentItem, playlistUrl, playlistName);
} else if (type == SP_PLAYLIST_TYPE_PLACEHOLDER) {
NSLog(@"%u: Placeholder Playlist", currentItem);
}
}
}
@end
| {
"pile_set_name": "Github"
} |
Optimizations for cloud based discovery stores
==============================================
Author: Bela Ban, 2014
JIRA: https://issues.jboss.org/browse/JGRP-1841
Goals
-----
- Reduce the number of discovery calls to the cloud store (HTTP/REST based, potentially slow and charged per call/volume)
- Use of a single file for all members rather than 1 file per member
- Reading a single file is faster than having to read N files
- We used ~35 bytes / member in Google Cloud Store, so for 1000 nodes this could be ~35-50 KB
- Optional fast startup via bootstrap file: contains UUIDs, logical names and IP addresses:ports of all members
- The members file should be user-readable (not binary); users should also be able to modify / generate it
Members file
------------
- Located under <location>/<clustername>
- Named after the coordinator: '<UUID of coord>.list'
- If we have multiple coordinators (e.g. on a partition), multiple x.list files may exist
- Structure: <Logical name> <UUID> <IP address>:<port> <coord>
- Entries are separated by white space (this accommodates IPv6 addresses, too)
- Example:
A 1 192.168.1.5:7800 T
B 0a6c59fc-7ee0-acd2-2d4b-cf7dd59adb97 192.168.1.5:4569 F
C 2 fe80::21b:21ff:fe07:a3b0:4500 F
(The last semicolon separates the IP address from the port, so the port is 4500)
- This is just an example; usually all addresses would either be IPv4 or IPv6, but not mixed.
Overview
--------
- When a new member starts, it reads the members list and adds all of the information to its local cache,
then sends a JOIN request to the coordinator (which is marked with a T in the file)
- When the coordinator A changes, the new coordinator B writes the B.list file, marking itself with a T.
The old coord removes its A.list file.
- When a member joins which is not listed, it multicasts its information (UUID, logical name and IP address:port) to
all members
- When the coord receives this message, it adds the new member to the members file. New joiners then have this info
available when reading the file
- When the information for a given member P is not available, the information is fetched from the coordinator (or
from the cloud store)
Scenarios:
----------
Initial start with bootstrap file
---------------------------------
- The idea is that all members that are going to be started are listed in a bootstap file (see above)
- The name of the bootstrap file would be the first coord's UUID, e.g. "1.list".
- Since all of the information for all members is listed, a new member doesn't need to run discovery as the
information of all members is already present in its local cache
- The bootstrap file can be generated: e.g. after starting 1000 hosts in a cloud, all IP addresses can be fetched
- Example (Google Compute Engine): gcutil listinstances
- Now members are started according to the order in the bootstrap file
- For each member,
- TP.bind_port is set
- The logical name is set: JChannel.name(String logical_name)
- The UUID is set
- This can be done via an AddressGenerator seeded with the *initial* UUID (e.g. 3)
- After setting the initial UUID, subsequent UUIDs are *random* as UUIDs cannot be reused (e.g. on channel
disconnect and subsequent reconnect)
- When a new joiner doesn't find its information in the file, it multicasts its information and the coord adds it to
the members file (see section below on new member not in members file)
- When a new joiner finds multiple members files (e.g. in a partition, see below), it reads all of them and picks a
random coordinator from all of the coordinators found. (Alternative: pick a random file and only add that info)
- When a new member starts up, reads the members file and finds that it itself is the coordinator, it adds the
information on the members to its local cache, but returns an empty Responses object so the node becomes
a singleton member (and therefore coordinator)
Initial start without bootstrap file
------------------------------------
- When a member P starts and doesn't find a members file, it turns out to become the coordinator,
it creates a new file P.list (where P is the UUID) and adds its own information
Coordinator change
------------------
- If we have {A,B,C,D}, and A crashes or leaves, and B becomes the new coordinator, then
- A removes A.list (including info on A,B,C,D) by means of a shutdown hook (kill -9 requires manual cleanup)
or handling of a graceful leave
- B creates B.list (including B,C,D) and marks itself as coordinator
- If a coordinator A ceases to be coordinator in a MergeView (someone else became coord, e.g. after a partition healed)
- A does *not* remove A.list (B will do this, see below in merge handling)
- This is different from a partition (split), see below (partition and merge)
Member leaves or crashes
------------------------
- When B leaves (B is not a coord, otherwise go to coordinator change above), the current coord (A)
writes a new A.list excluding B.
- CHANGED: we don't do anything (saving us a write when members leave). When the logical address cache fills up,
next time a member joins we'll write the cleaned cache anyway
New member P is not in members file
-----------------------------------
- P multicasts (IP multicast if UDP is used or N-1 unicasts if TCP is used) a GET_MBRS_RSP message containing its
UUID, logical name and IP address:port
Reception of GET_MBRS_RSP message from P
----------------------------------------
- Everyone adds P's information to their local caches
- If the current member A is the coord:
- If P was not in the local cache -> write A.list including P
Information for target P is not in local cache
----------------------------------------------
- When a message is to be sent to P and P is not in the local cache, the information for P is fetched from the
current coordinator (A).
- Alternative: read it from the members file? Advantage is that we can read the entire file and thus
possibly suppress further fetches from the coord for other missing members.
Partition and subsequent merge
------------------------------
- Say we have {A,B,C,X,Y,Z}. A is the coordinator and A.list contains information on A,B,C,X,Y,Z
- Then we have 2 partitions {A,B,C} and {X,Y,Z}
- A removes information on X,Y,Z from A.list. (Same as if X,Y,Z left, see above).
- X (the new coord of the {X,Y,Z} partition) creates X.list and adds information on X,Y,Z
- Both MERGE2 and MERGE3 need to read all *.list files, e.g. A.list and X.list to see if partitions exist
Merge of {A,B,C}, {M,N,O} and {X,Y,Z}
-------------------------------------
- A is the new coordinator of the merged group, M and X are the old coordinators
- A reads M.list and X.list and merges the contents back into A.list, then deletes M.list and X.list
- Everyone clears the 'removable' flag from their cache entries for all members in the merge-view
(done automatically by TP's view change handling)
- When target members are not in the local cache, they can be fetched either from the coord or via reading
the members file (see members not in member list above)
Issues
------
- Do we need to support subclasses of UUID (e.g. ExtendedUUID)?
--> Probably yes: we actually only need the UUIDs as *keys* for the physical addrs in the caches, so it doesn't matter
that we strip ExtendedUUIDs down to UUIDs as they're only used for lookup purposes anyway. The UUIDs sent with
the messages (e.g. sender) are not changed, so this should not have any adverse effect.
| {
"pile_set_name": "Github"
} |
AlgorithmType: MAC
Name: Two-Track-MAC
Source: NESSIE submission
Comment: Key for all test cases
Key: 00112233445566778899aabbccddeeff01234567
Comment: Test Case 1
Message: ""
MAC: 2dec8ed4a0fd712ed9fbf2ab466ec2df21215e4a
Test: Verify
Comment: Test Case 2
Message: "a"
MAC: 5893e3e6e306704dd77ad6e6ed432cde321a7756
Test: Verify
Comment: Test Case 3
Message: "abc"
MAC: 70bfd1029797a5c16da5b557a1f0b2779b78497e
Test: Verify
Comment: Test Case 4
Message: "message digest"
MAC: 8289f4f19ffe4f2af737de4bd71c829d93a972fa
Test: Verify
Comment: Test Case 5
Message: "abcdefghijklmnopqrstuvwxyz"
MAC: 2186ca09c5533198b7371f245273504ca92bae60
Test: Verify
Comment: Test Case 6
Message: "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
MAC: 8a7bf77aef62a2578497a27c0d6518a429e7c14d
Test: Verify
Comment: Test Case 7
Message: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
MAC: 54bac392a886806d169556fcbb6789b54fb364fb
Test: Verify
Comment: Test Case 8
Message: r8 "1234567890"
MAC: 0ced2c9f8f0d9d03981ab5c8184bac43dd54c484
Test: Verify
Comment: Test Case 9
Message: r15625 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
MAC: 27b3aedb5df8b629f0142194daa3846e1895f3d2
| {
"pile_set_name": "Github"
} |
{ add(a, b) { return a + b; } };
| {
"pile_set_name": "Github"
} |
File: FunVsCtorInDifferentFiles.test2.kt - 2a2e517a6a1d4f627cc2dbdd8f919707
packageHeader
importList
topLevelObject
declaration
functionDeclaration
FUN("fun")
simpleIdentifier
Identifier("A")
functionValueParameters
LPAREN("(")
RPAREN(")")
functionBody
block
LCURL("{")
statements
RCURL("}")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
simpleIdentifier
Identifier("B")
functionValueParameters
LPAREN("(")
functionValueParameter
parameter
simpleIdentifier
Identifier("x")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Int")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("x")
semis
NL("\n")
topLevelObject
declaration
functionDeclaration
FUN("fun")
simpleIdentifier
Identifier("B")
functionValueParameters
LPAREN("(")
functionValueParameter
parameter
simpleIdentifier
Identifier("x")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Int")
COMMA(",")
functionValueParameter
parameter
simpleIdentifier
Identifier("y")
COLON(":")
type
typeReference
userType
simpleUserType
simpleIdentifier
Identifier("Int")
RPAREN(")")
functionBody
ASSIGNMENT("=")
expression
disjunction
conjunction
equality
comparison
genericCallLikeComparison
infixOperation
elvisExpression
infixFunctionCall
rangeExpression
additiveExpression
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("x")
additiveOperator
ADD("+")
multiplicativeExpression
asExpression
prefixUnaryExpression
postfixUnaryExpression
primaryExpression
simpleIdentifier
Identifier("y")
semis
EOF("<EOF>")
EOF("<EOF>")
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2006 Ben Warren, Qstreams Networks Inc.
* With help from the common/soft_spi and cpu/mpc8260 drivers
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <malloc.h>
#include <spi.h>
#include <asm/mpc8xxx_spi.h>
#define SPI_EV_NE (0x80000000 >> 22) /* Receiver Not Empty */
#define SPI_EV_NF (0x80000000 >> 23) /* Transmitter Not Full */
#define SPI_MODE_LOOP (0x80000000 >> 1) /* Loopback mode */
#define SPI_MODE_REV (0x80000000 >> 5) /* Reverse mode - MSB first */
#define SPI_MODE_MS (0x80000000 >> 6) /* Always master */
#define SPI_MODE_EN (0x80000000 >> 7) /* Enable interface */
#define SPI_TIMEOUT 1000
struct spi_slave *spi_setup_slave(unsigned int bus, unsigned int cs,
unsigned int max_hz, unsigned int mode)
{
struct spi_slave *slave;
if (!spi_cs_is_valid(bus, cs))
return NULL;
slave = malloc(sizeof(struct spi_slave));
if (!slave)
return NULL;
slave->bus = bus;
slave->cs = cs;
/*
* TODO: Some of the code in spi_init() should probably move
* here, or into spi_claim_bus() below.
*/
return slave;
}
void spi_free_slave(struct spi_slave *slave)
{
free(slave);
}
void spi_init(void)
{
volatile spi8xxx_t *spi = &((immap_t *) (CONFIG_SYS_IMMR))->spi;
/*
* SPI pins on the MPC83xx are not muxed, so all we do is initialize
* some registers
*/
spi->mode = SPI_MODE_REV | SPI_MODE_MS | SPI_MODE_EN;
spi->mode = (spi->mode & 0xfff0ffff) | (1 << 16); /* Use SYSCLK / 8
(16.67MHz typ.) */
spi->event = 0xffffffff; /* Clear all SPI events */
spi->mask = 0x00000000; /* Mask all SPI interrupts */
spi->com = 0; /* LST bit doesn't do anything, so disregard */
}
int spi_claim_bus(struct spi_slave *slave)
{
return 0;
}
void spi_release_bus(struct spi_slave *slave)
{
}
int spi_xfer(struct spi_slave *slave, unsigned int bitlen, const void *dout,
void *din, unsigned long flags)
{
volatile spi8xxx_t *spi = &((immap_t *) (CONFIG_SYS_IMMR))->spi;
unsigned int tmpdout, tmpdin, event;
int numBlks = bitlen / 32 + (bitlen % 32 ? 1 : 0);
int tm, isRead = 0;
unsigned char charSize = 32;
debug("spi_xfer: slave %u:%u dout %08X din %08X bitlen %u\n",
slave->bus, slave->cs, *(uint *) dout, *(uint *) din, bitlen);
if (flags & SPI_XFER_BEGIN)
spi_cs_activate(slave);
spi->event = 0xffffffff; /* Clear all SPI events */
/* handle data in 32-bit chunks */
while (numBlks--) {
tmpdout = 0;
charSize = (bitlen >= 32 ? 32 : bitlen);
/* Shift data so it's msb-justified */
tmpdout = *(u32 *) dout >> (32 - charSize);
/* The LEN field of the SPMODE register is set as follows:
*
* Bit length setting
* len <= 4 3
* 4 < len <= 16 len - 1
* len > 16 0
*/
if (bitlen <= 16) {
if (bitlen <= 4)
spi->mode = (spi->mode & 0xff0fffff) |
(3 << 20);
else
spi->mode = (spi->mode & 0xff0fffff) |
((bitlen - 1) << 20);
} else {
spi->mode = (spi->mode & 0xff0fffff);
/* Set up the next iteration if sending > 32 bits */
bitlen -= 32;
dout += 4;
}
spi->tx = tmpdout; /* Write the data out */
debug("*** spi_xfer: ... %08x written\n", tmpdout);
/*
* Wait for SPI transmit to get out
* or time out (1 second = 1000 ms)
* The NE event must be read and cleared first
*/
for (tm = 0, isRead = 0; tm < SPI_TIMEOUT; ++tm) {
event = spi->event;
if (event & SPI_EV_NE) {
tmpdin = spi->rx;
spi->event |= SPI_EV_NE;
isRead = 1;
*(u32 *) din = (tmpdin << (32 - charSize));
if (charSize == 32) {
/* Advance output buffer by 32 bits */
din += 4;
}
}
/*
* Only bail when we've had both NE and NF events.
* This will cause timeouts on RO devices, so maybe
* in the future put an arbitrary delay after writing
* the device. Arbitrary delays suck, though...
*/
if (isRead && (event & SPI_EV_NF))
break;
}
if (tm >= SPI_TIMEOUT)
puts("*** spi_xfer: Time out during SPI transfer");
debug("*** spi_xfer: transfer ended. Value=%08x\n", tmpdin);
}
if (flags & SPI_XFER_END)
spi_cs_deactivate(slave);
return 0;
}
| {
"pile_set_name": "Github"
} |
package org.enso.projectmanager.service
import cats.MonadError
import cats.implicits._
import org.enso.projectmanager.service.ValidationFailure.{
EmptyName,
NameContainsForbiddenCharacter
}
/**
* MTL implementation of the project validator.
*/
class MonadicProjectValidator[F[_, _]](
implicit M: MonadError[F[ValidationFailure, *], ValidationFailure]
) extends ProjectValidator[F] {
import M._
private val validCharSpec: Char => Boolean = { char =>
char.isLetterOrDigit || char == '_' || char == '-'
}
/**
* Validates a project name.
*
* @param name the project name
* @return either validation failure or success
*/
override def validateName(name: String): F[ValidationFailure, Unit] =
checkIfNonEmptyName(name) *> checkCharacters(name)
private def checkIfNonEmptyName(name: String): F[ValidationFailure, Unit] =
if (name.trim.isEmpty) {
raiseError(EmptyName)
} else {
unit
}
private def checkCharacters(name: String): F[ValidationFailure, Unit] = {
val forbiddenChars = name.toCharArray.filterNot(validCharSpec).toSet
if (forbiddenChars.isEmpty) unit
else raiseError(NameContainsForbiddenCharacter(forbiddenChars))
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.X11;
import java.awt.*;
import java.awt.peer.ComponentPeer;
import java.awt.peer.TextAreaPeer;
import java.awt.event.*;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import javax.swing.JTextArea;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JScrollBar;
import javax.swing.plaf.ComponentUI;
import com.sun.java.swing.plaf.motif.MotifTextAreaUI;
import javax.swing.plaf.UIResource;
import javax.swing.UIDefaults;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.AbstractBorder;
import javax.swing.JButton;
import javax.swing.JViewport;
import javax.swing.InputMap;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicScrollBarUI;
import javax.swing.plaf.basic.BasicScrollPaneUI;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.text.Caret;
import javax.swing.text.DefaultCaret;
import javax.swing.text.JTextComponent;
import javax.swing.plaf.BorderUIResource;
import java.awt.im.InputMethodRequests;
import sun.awt.CausedFocusEvent;
import sun.awt.AWTAccessor;
import sun.awt.SunToolkit;
final class XTextAreaPeer extends XComponentPeer implements TextAreaPeer {
private final AWTTextPane textPane;
private final AWTTextArea jtext;
private final boolean firstChangeSkipped;
private final JavaMouseEventHandler javaMouseEventHandler =
new JavaMouseEventHandler(this);
/**
* Create a Text area.
*/
XTextAreaPeer(TextArea target) {
super(target);
// some initializations require that target be set even
// though init(target) has not been called
this.target = target;
//ComponentAccessor.enableEvents(target,AWTEvent.MOUSE_WHEEL_EVENT_MASK);
String text = target.getText();
jtext = new AWTTextArea(text, this);
jtext.setWrapStyleWord(true);
jtext.getDocument().addDocumentListener(jtext);
XToolkit.specialPeerMap.put(jtext,this);
textPane = new AWTTextPane(jtext,this, target.getParent());
setBounds(x, y, width, height, SET_BOUNDS);
textPane.setVisible(true);
textPane.validate();
AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
foreground = compAccessor.getForeground(target);
if (foreground == null) {
foreground = SystemColor.textText;
}
setForeground(foreground);
background = compAccessor.getBackground(target);
if (background == null) {
if (target.isEditable()) background = SystemColor.text;
else background = SystemColor.control;
}
setBackground(background);
if (!target.isBackgroundSet()) {
// This is a way to set the background color of the TextArea
// without calling setBackground - go through accessor
compAccessor.setBackground(target, background);
}
if (!target.isForegroundSet()) {
target.setForeground(SystemColor.textText);
}
setFont(font);
// set the text of this object to the text of its target
setTextImpl(target.getText()); //?? should this be setText
int start = target.getSelectionStart();
int end = target.getSelectionEnd();
// Fix for 5100200
// Restoring Motif behaviour
// Since the end position of the selected text can be greater then the length of the text,
// so we should set caret to max position of the text
setCaretPosition(Math.min(end, text.length()));
if (end > start) {
// Should be called after setText() and setCaretPosition()
select(start, end);
}
setEditable(target.isEditable());
setScrollBarVisibility();
// After this line we should not change the component's text
firstChangeSkipped = true;
}
@Override
public void dispose() {
XToolkit.specialPeerMap.remove(jtext);
// visible caret has a timer thread which must be stopped
jtext.getCaret().setVisible(false);
jtext.removeNotify();
textPane.removeNotify();
super.dispose();
}
/*
* The method overrides one from XComponentPeer
* If ignoreSubComponents=={@code true} it calls super.
* If ignoreSubComponents=={@code false} it uses the XTextArea machinery
* to change cursor appropriately. In particular it changes the cursor to
* default if over scrollbars.
*/
@Override
public void pSetCursor(Cursor cursor, boolean ignoreSubComponents) {
if (ignoreSubComponents ||
javaMouseEventHandler == null) {
super.pSetCursor(cursor, true);
return;
}
Point cursorPos = new Point();
((XGlobalCursorManager)XGlobalCursorManager.getCursorManager()).getCursorPos(cursorPos);
final Point onScreen = getLocationOnScreen();
Point localPoint = new Point(cursorPos.x - onScreen.x, cursorPos.y - onScreen.y );
javaMouseEventHandler.setPointerToUnderPoint(localPoint);
javaMouseEventHandler.setCursor();
}
private void setScrollBarVisibility() {
int visibility = ((TextArea)target).getScrollbarVisibility();
jtext.setLineWrap(false);
if (visibility == TextArea.SCROLLBARS_NONE) {
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
textPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
jtext.setLineWrap(true);
}
else if (visibility == TextArea.SCROLLBARS_BOTH) {
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
else if (visibility == TextArea.SCROLLBARS_VERTICAL_ONLY) {
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
textPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jtext.setLineWrap(true);
}
else if (visibility == TextArea.SCROLLBARS_HORIZONTAL_ONLY) {
textPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
}
/**
* Compute minimum size.
*/
@Override
public Dimension getMinimumSize() {
return getMinimumSize(10, 60);
}
@Override
public Dimension getPreferredSize(int rows, int cols) {
return getMinimumSize(rows, cols);
}
/**
* @see java.awt.peer.TextAreaPeer
*/
@Override
public Dimension getMinimumSize(int rows, int cols) {
/* Dimension d = null;
if (jtext != null) {
d = jtext.getMinimumSize(rows,cols);
}
return d;
*/
int vsbwidth=0;
int hsbheight=0;
JScrollBar vsb = textPane.getVerticalScrollBar();
if (vsb != null) {
vsbwidth = vsb.getMinimumSize().width;
}
JScrollBar hsb = textPane.getHorizontalScrollBar();
if (hsb != null) {
hsbheight = hsb.getMinimumSize().height;
}
Font f = jtext.getFont();
FontMetrics fm = jtext.getFontMetrics(f);
return new Dimension(fm.charWidth('0') * cols + /*2*XMARGIN +*/ vsbwidth,
fm.getHeight() * rows + /*2*YMARGIN +*/ hsbheight);
}
@Override
public boolean isFocusable() {
return true;
}
@Override
public void setVisible(boolean b) {
super.setVisible(b);
if (textPane != null)
textPane.setVisible(b);
}
void repaintText() {
jtext.repaintNow();
}
@Override
public void focusGained(FocusEvent e) {
super.focusGained(e);
jtext.forwardFocusGained(e);
}
@Override
public void focusLost(FocusEvent e) {
super.focusLost(e);
jtext.forwardFocusLost(e);
}
/**
* Paint the component
* this method is called when the repaint instruction has been used
*/
@Override
public void repaint() {
if (textPane != null) {
//textPane.validate();
textPane.repaint();
}
}
@Override
void paintPeer(final Graphics g) {
if (textPane != null) {
textPane.paint(g);
}
}
@Override
public void setBounds(int x, int y, int width, int height, int op) {
super.setBounds(x, y, width, height, op);
if (textPane != null) {
/*
* Fixed 6277332, 6198290:
* the coordinates is coming (to peer): relatively to closest HW parent
* the coordinates is setting (to textPane): relatively to closest ANY parent
* the parent of peer is target.getParent()
* the parent of textPane is the same
* see 6277332, 6198290 for more information
*/
int childX = x;
int childY = y;
Component parent = target.getParent();
// we up to heavyweight parent in order to be sure
// that the coordinates of the text pane is relatively to closest parent
while (parent.isLightweight()){
childX -= parent.getX();
childY -= parent.getY();
parent = parent.getParent();
}
textPane.setBounds(childX,childY,width,height);
textPane.validate();
}
}
@Override
void handleJavaKeyEvent(KeyEvent e) {
AWTAccessor.getComponentAccessor().processEvent(jtext,e);
}
@Override
public boolean handlesWheelScrolling() { return true; }
@Override
void handleJavaMouseWheelEvent(MouseWheelEvent e) {
AWTAccessor.getComponentAccessor().processEvent(textPane, e);
}
@Override
public void handleJavaMouseEvent( MouseEvent e ) {
super.handleJavaMouseEvent( e );
javaMouseEventHandler.handle( e );
}
@Override
void handleJavaInputMethodEvent(InputMethodEvent e) {
if (jtext != null)
jtext.processInputMethodEventPublic((InputMethodEvent)e);
}
/**
* @see java.awt.peer.TextComponentPeer
*/
@Override
public void select(int s, int e) {
jtext.select(s, e);
// Fixed 5100806
// We must take care that Swing components repainted correctly
jtext.repaint();
}
@Override
public void setBackground(Color c) {
super.setBackground(c);
// synchronized (getStateLock()) {
// background = c;
// }
if (jtext != null) {
jtext.setBackground(c);
jtext.setSelectedTextColor(c);
}
// repaintText();
}
@Override
public void setForeground(Color c) {
super.setForeground(c);
// synchronized (getStateLock()) {
// foreground = c;
// }
if (jtext != null) {
jtext.setForeground(foreground);
jtext.setSelectionColor(foreground);
jtext.setCaretColor(foreground);
}
// repaintText();
}
@Override
public void setFont(Font f) {
super.setFont(f);
// synchronized (getStateLock()) {
// font = f;
// }
if (jtext != null) {
jtext.setFont(font);
}
textPane.validate();
}
/**
* @see java.awt.peer.TextComponentPeer
*/
@Override
public void setEditable(boolean editable) {
if (jtext != null) jtext.setEditable(editable);
repaintText();
}
/**
* @see java.awt.peer.ComponentPeer
*/
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (jtext != null) {
jtext.setEnabled(enabled);
jtext.repaint();
}
}
/**
* @see java.awt.peer.TextComponentPeer
*/
@Override
public InputMethodRequests getInputMethodRequests() {
if (jtext != null) return jtext.getInputMethodRequests();
else return null;
}
/**
* @see java.awt.peer.TextComponentPeer
*/
@Override
public int getSelectionStart() {
return jtext.getSelectionStart();
}
/**
* @see java.awt.peer.TextComponentPeer
*/
@Override
public int getSelectionEnd() {
return jtext.getSelectionEnd();
}
/**
* @see java.awt.peer.TextComponentPeer
*/
@Override
public String getText() {
return jtext.getText();
}
/**
* @see java.awt.peer.TextComponentPeer
*/
@Override
public void setText(String text) {
setTextImpl(text);
repaintText();
}
private void setTextImpl(String txt) {
if (jtext != null) {
// JTextArea.setText() posts two different events (remove & insert).
// Since we make no differences between text events,
// the document listener has to be disabled while
// JTextArea.setText() is called.
jtext.getDocument().removeDocumentListener(jtext);
jtext.setText(txt);
if (firstChangeSkipped) {
postEvent(new TextEvent(target, TextEvent.TEXT_VALUE_CHANGED));
}
jtext.getDocument().addDocumentListener(jtext);
}
}
/**
* insert the text "txt on position "pos" in the array lines
* @see java.awt.peer.TextAreaPeer
*/
@Override
public void insert(String txt, int p) {
if (jtext != null) {
boolean doScroll = (p >= jtext.getDocument().getLength() && jtext.getDocument().getLength() != 0);
jtext.insert(txt,p);
textPane.validate();
if (doScroll) {
JScrollBar bar = textPane.getVerticalScrollBar();
if (bar != null) {
bar.setValue(bar.getMaximum()-bar.getVisibleAmount());
}
}
}
}
/**
* replace the text between the position "s" and "e" with "txt"
* @see java.awt.peer.TextAreaPeer
*/
@Override
public void replaceRange(String txt, int s, int e) {
if (jtext != null) {
// JTextArea.replaceRange() posts two different events.
// Since we make no differences between text events,
// the document listener has to be disabled while
// JTextArea.replaceRange() is called.
jtext.getDocument().removeDocumentListener(jtext);
jtext.replaceRange(txt, s, e);
postEvent(new TextEvent(target, TextEvent.TEXT_VALUE_CHANGED));
jtext.getDocument().addDocumentListener(jtext);
}
}
/**
* to be implemented.
* @see java.awt.peer.TextComponentPeer
*/
@Override
public void setCaretPosition(int position) {
jtext.setCaretPosition(position);
}
/**
* to be implemented.
* @see java.awt.peer.TextComponentPeer
*/
@Override
public int getCaretPosition() {
return jtext.getCaretPosition();
}
final class AWTTextAreaUI extends MotifTextAreaUI {
private JTextArea jta;
@Override
protected String getPropertyPrefix() { return "TextArea"; }
@Override
public void installUI(JComponent c) {
super.installUI(c);
jta = (JTextArea) c;
JTextArea editor = jta;
UIDefaults uidefaults = XToolkit.getUIDefaults();
String prefix = getPropertyPrefix();
Font f = editor.getFont();
if ((f == null) || (f instanceof UIResource)) {
editor.setFont(uidefaults.getFont(prefix + ".font"));
}
Color bg = editor.getBackground();
if ((bg == null) || (bg instanceof UIResource)) {
editor.setBackground(uidefaults.getColor(prefix + ".background"));
}
Color fg = editor.getForeground();
if ((fg == null) || (fg instanceof UIResource)) {
editor.setForeground(uidefaults.getColor(prefix + ".foreground"));
}
Color color = editor.getCaretColor();
if ((color == null) || (color instanceof UIResource)) {
editor.setCaretColor(uidefaults.getColor(prefix + ".caretForeground"));
}
Color s = editor.getSelectionColor();
if ((s == null) || (s instanceof UIResource)) {
editor.setSelectionColor(uidefaults.getColor(prefix + ".selectionBackground"));
}
Color sfg = editor.getSelectedTextColor();
if ((sfg == null) || (sfg instanceof UIResource)) {
editor.setSelectedTextColor(uidefaults.getColor(prefix + ".selectionForeground"));
}
Color dfg = editor.getDisabledTextColor();
if ((dfg == null) || (dfg instanceof UIResource)) {
editor.setDisabledTextColor(uidefaults.getColor(prefix + ".inactiveForeground"));
}
Border b = new BevelBorder(false,SystemColor.controlDkShadow,SystemColor.controlLtHighlight);
editor.setBorder(new BorderUIResource.CompoundBorderUIResource(
b,new EmptyBorder(2, 2, 2, 2)));
Insets margin = editor.getMargin();
if (margin == null || margin instanceof UIResource) {
editor.setMargin(uidefaults.getInsets(prefix + ".margin"));
}
}
@Override
protected void installKeyboardActions() {
super.installKeyboardActions();
JTextComponent comp = getComponent();
UIDefaults uidefaults = XToolkit.getUIDefaults();
String prefix = getPropertyPrefix();
InputMap map = (InputMap)uidefaults.get(prefix + ".focusInputMap");
if (map != null) {
SwingUtilities.replaceUIInputMap(comp, JComponent.WHEN_FOCUSED,
map);
}
}
@Override
protected Caret createCaret() {
return new XAWTCaret();
}
}
static final class XAWTCaret extends DefaultCaret {
@Override
public void focusGained(FocusEvent e) {
super.focusGained(e);
if (getComponent().isEnabled()){
// Make sure the cursor is visible in case of non-editable TextArea
super.setVisible(true);
}
getComponent().repaint();
}
@Override
public void focusLost(FocusEvent e) {
super.focusLost(e);
getComponent().repaint();
}
// Fix for 5100950: textarea.getSelectedText() returns the de-selected text, on XToolkit
// Restoring Motif behaviour
// If the text is unhighlighted then we should sets the selection range to zero
@Override
public void setSelectionVisible(boolean vis) {
if (vis){
super.setSelectionVisible(vis);
}else{
// In order to de-select the selection
setDot(getDot());
}
}
}
final class XAWTScrollBarButton extends BasicArrowButton {
private UIDefaults uidefaults = XToolkit.getUIDefaults();
private Color darkShadow = SystemColor.controlShadow;
private Color lightShadow = SystemColor.controlLtHighlight;
private Color buttonBack = uidefaults.getColor("ScrollBar.track");
XAWTScrollBarButton(int direction) {
super(direction);
switch (direction) {
case NORTH:
case SOUTH:
case EAST:
case WEST:
this.direction = direction;
break;
default:
throw new IllegalArgumentException("invalid direction");
}
setRequestFocusEnabled(false);
setOpaque(true);
setBackground(uidefaults.getColor("ScrollBar.thumb"));
setForeground(uidefaults.getColor("ScrollBar.foreground"));
}
@Override
public Dimension getPreferredSize() {
switch (direction) {
case NORTH:
case SOUTH:
return new Dimension(11, 12);
case EAST:
case WEST:
default:
return new Dimension(12, 11);
}
}
@Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
@Override
public Dimension getMaximumSize() {
return getPreferredSize();
}
@Override
public boolean isFocusTraversable() {
return false;
}
@Override
public void paint(Graphics g)
{
int w = getWidth();
int h = getHeight();
if (isOpaque()) {
g.setColor(buttonBack);
g.fillRect(0, 0, w, h);
}
boolean isPressed = getModel().isPressed();
Color lead = (isPressed) ? darkShadow : lightShadow;
Color trail = (isPressed) ? lightShadow : darkShadow;
Color fill = getBackground();
int cx = w / 2;
int cy = h / 2;
int s = Math.min(w, h);
switch (direction) {
case NORTH:
g.setColor(lead);
g.drawLine(cx, 0, cx, 0);
for (int x = cx - 1, y = 1, dx = 1; y <= s - 2; y += 2) {
g.setColor(lead);
g.drawLine(x, y, x, y);
if (y >= (s - 2)) {
g.drawLine(x, y + 1, x, y + 1);
}
g.setColor(fill);
g.drawLine(x + 1, y, x + dx, y);
if (y < (s - 2)) {
g.drawLine(x, y + 1, x + dx + 1, y + 1);
}
g.setColor(trail);
g.drawLine(x + dx + 1, y, x + dx + 1, y);
if (y >= (s - 2)) {
g.drawLine(x + 1, y + 1, x + dx + 1, y + 1);
}
dx += 2;
x -= 1;
}
break;
case SOUTH:
g.setColor(trail);
g.drawLine(cx, s, cx, s);
for (int x = cx - 1, y = s - 1, dx = 1; y >= 1; y -= 2) {
g.setColor(lead);
g.drawLine(x, y, x, y);
if (y <= 2) {
g.drawLine(x, y - 1, x + dx + 1, y - 1);
}
g.setColor(fill);
g.drawLine(x + 1, y, x + dx, y);
if (y > 2) {
g.drawLine(x, y - 1, x + dx + 1, y - 1);
}
g.setColor(trail);
g.drawLine(x + dx + 1, y, x + dx + 1, y);
dx += 2;
x -= 1;
}
break;
case EAST:
g.setColor(lead);
g.drawLine(s, cy, s, cy);
for (int y = cy - 1, x = s - 1, dy = 1; x >= 1; x -= 2) {
g.setColor(lead);
g.drawLine(x, y, x, y);
if (x <= 2) {
g.drawLine(x - 1, y, x - 1, y + dy + 1);
}
g.setColor(fill);
g.drawLine(x, y + 1, x, y + dy);
if (x > 2) {
g.drawLine(x - 1, y, x - 1, y + dy + 1);
}
g.setColor(trail);
g.drawLine(x, y + dy + 1, x, y + dy + 1);
dy += 2;
y -= 1;
}
break;
case WEST:
g.setColor(trail);
g.drawLine(0, cy, 0, cy);
for (int y = cy - 1, x = 1, dy = 1; x <= s - 2; x += 2) {
g.setColor(lead);
g.drawLine(x, y, x, y);
if (x >= (s - 2)) {
g.drawLine(x + 1, y, x + 1, y);
}
g.setColor(fill);
g.drawLine(x, y + 1, x, y + dy);
if (x < (s - 2)) {
g.drawLine(x + 1, y, x + 1, y + dy + 1);
}
g.setColor(trail);
g.drawLine(x, y + dy + 1, x, y + dy + 1);
if (x >= (s - 2)) {
g.drawLine(x + 1, y + 1, x + 1, y + dy + 1);
}
dy += 2;
y -= 1;
}
break;
}
}
}
final class XAWTScrollBarUI extends BasicScrollBarUI {
@Override
protected void installDefaults()
{
super.installDefaults();
scrollbar.setBorder(new BevelBorder(false,SystemColor.controlDkShadow,SystemColor.controlLtHighlight) );
}
@Override
protected void configureScrollBarColors() {
UIDefaults uidefaults = XToolkit.getUIDefaults();
Color bg = scrollbar.getBackground();
if (bg == null || bg instanceof UIResource) {
scrollbar.setBackground(uidefaults.getColor("ScrollBar.background"));
}
Color fg = scrollbar.getForeground();
if (fg == null || fg instanceof UIResource) {
scrollbar.setForeground(uidefaults.getColor("ScrollBar.foreground"));
}
thumbHighlightColor = uidefaults.getColor("ScrollBar.thumbHighlight");
thumbLightShadowColor = uidefaults.getColor("ScrollBar.thumbShadow");
thumbDarkShadowColor = uidefaults.getColor("ScrollBar.thumbDarkShadow");
thumbColor = uidefaults.getColor("ScrollBar.thumb");
trackColor = uidefaults.getColor("ScrollBar.track");
trackHighlightColor = uidefaults.getColor("ScrollBar.trackHighlight");
}
@Override
protected JButton createDecreaseButton(int orientation) {
JButton b = new XAWTScrollBarButton(orientation);
return b;
}
@Override
protected JButton createIncreaseButton(int orientation) {
JButton b = new XAWTScrollBarButton(orientation);
return b;
}
public JButton getDecreaseButton(){
return decrButton;
}
public JButton getIncreaseButton(){
return incrButton;
}
@Override
public void paint(Graphics g, JComponent c) {
paintTrack(g, c, getTrackBounds());
Rectangle thumbBounds = getThumbBounds();
paintThumb(g, c, thumbBounds);
}
@Override
public void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds)
{
if(!scrollbar.isEnabled()) {
return;
}
if (thumbBounds.isEmpty())
thumbBounds = getTrackBounds();
int w = thumbBounds.width;
int h = thumbBounds.height;
g.translate(thumbBounds.x, thumbBounds.y);
g.setColor(thumbColor);
g.fillRect(0, 0, w-1, h-1);
g.setColor(thumbHighlightColor);
g.drawLine(0, 0, 0, h-1);
g.drawLine(1, 0, w-1, 0);
g.setColor(thumbLightShadowColor);
g.drawLine(1, h-1, w-1, h-1);
g.drawLine(w-1, 1, w-1, h-2);
g.translate(-thumbBounds.x, -thumbBounds.y);
}
}
final class AWTTextArea extends JTextArea implements DocumentListener {
private boolean isFocused = false;
private final XTextAreaPeer peer;
AWTTextArea(String text, XTextAreaPeer peer) {
super(text);
setFocusable(false);
this.peer = peer;
}
@Override
public void insertUpdate(DocumentEvent e) {
if (peer != null) {
peer.postEvent(new TextEvent(peer.target,
TextEvent.TEXT_VALUE_CHANGED));
}
}
@Override
public void removeUpdate(DocumentEvent e) {
if (peer != null) {
peer.postEvent(new TextEvent(peer.target,
TextEvent.TEXT_VALUE_CHANGED));
}
}
@Override
public void changedUpdate(DocumentEvent e) {
if (peer != null) {
peer.postEvent(new TextEvent(peer.target,
TextEvent.TEXT_VALUE_CHANGED));
}
}
void forwardFocusGained( FocusEvent e) {
isFocused = true;
FocusEvent fe = CausedFocusEvent.retarget(e, this);
super.processFocusEvent(fe);
}
void forwardFocusLost( FocusEvent e) {
isFocused = false;
FocusEvent fe = CausedFocusEvent.retarget(e, this);
super.processFocusEvent(fe);
}
@Override
public boolean hasFocus() {
return isFocused;
}
public void repaintNow() {
paintImmediately(getBounds());
}
public void processMouseEventPublic(MouseEvent e) {
processMouseEvent(e);
}
public void processMouseMotionEventPublic(MouseEvent e) {
processMouseMotionEvent(e);
}
public void processInputMethodEventPublic(InputMethodEvent e) {
processInputMethodEvent(e);
}
@Override
public void updateUI() {
ComponentUI ui = new AWTTextAreaUI();
setUI(ui);
}
// Fix for 4915454 - override the default implementation to avoid
// loading SystemFlavorMap and associated classes.
@Override
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)
getClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER());
putClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER(),
newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
}
final class XAWTScrollPaneUI extends BasicScrollPaneUI {
private final Border vsbMarginBorderR = new EmptyBorder(0, 2, 0, 0);
private final Border vsbMarginBorderL = new EmptyBorder(0, 0, 0, 2);
private final Border hsbMarginBorder = new EmptyBorder(2, 0, 0, 0);
private Border vsbBorder;
private Border hsbBorder;
private PropertyChangeListener propertyChangeHandler;
@Override
protected void installListeners(JScrollPane scrollPane) {
super.installListeners(scrollPane);
propertyChangeHandler = createPropertyChangeHandler();
scrollPane.addPropertyChangeListener(propertyChangeHandler);
}
@Override
public void paint(Graphics g, JComponent c) {
Border vpBorder = scrollpane.getViewportBorder();
if (vpBorder != null) {
Rectangle r = scrollpane.getViewportBorderBounds();
vpBorder.paintBorder(scrollpane, g, r.x, r.y, r.width, r.height);
}
}
@Override
protected void uninstallListeners(JComponent scrollPane) {
super.uninstallListeners(scrollPane);
scrollPane.removePropertyChangeListener(propertyChangeHandler);
}
private PropertyChangeListener createPropertyChangeHandler() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if (propertyName.equals("componentOrientation")) {
JScrollPane pane = (JScrollPane)e.getSource();
JScrollBar vsb = pane.getVerticalScrollBar();
if (vsb != null) {
if (isLeftToRight(pane)) {
vsbBorder = new CompoundBorder(new EmptyBorder(0, 4, 0, -4),
vsb.getBorder());
} else {
vsbBorder = new CompoundBorder(new EmptyBorder(0, -4, 0, 4),
vsb.getBorder());
}
vsb.setBorder(vsbBorder);
}
}
}};
}
boolean isLeftToRight( Component c ) {
return c.getComponentOrientation().isLeftToRight();
}
@Override
protected void installDefaults(JScrollPane scrollpane) {
Border b = scrollpane.getBorder();
UIDefaults uidefaults = XToolkit.getUIDefaults();
scrollpane.setBorder(uidefaults.getBorder("ScrollPane.border"));
scrollpane.setBackground(uidefaults.getColor("ScrollPane.background"));
scrollpane.setViewportBorder(uidefaults.getBorder("TextField.border"));
JScrollBar vsb = scrollpane.getVerticalScrollBar();
if (vsb != null) {
if (isLeftToRight(scrollpane)) {
vsbBorder = new CompoundBorder(vsbMarginBorderR,
vsb.getBorder());
}
else {
vsbBorder = new CompoundBorder(vsbMarginBorderL,
vsb.getBorder());
}
vsb.setBorder(vsbBorder);
}
JScrollBar hsb = scrollpane.getHorizontalScrollBar();
if (hsb != null) {
hsbBorder = new CompoundBorder(hsbMarginBorder, hsb.getBorder());
hsb.setBorder(hsbBorder);
}
}
@Override
protected void uninstallDefaults(JScrollPane c) {
super.uninstallDefaults(c);
JScrollBar vsb = scrollpane.getVerticalScrollBar();
if (vsb != null) {
if (vsb.getBorder() == vsbBorder) {
vsb.setBorder(null);
}
vsbBorder = null;
}
JScrollBar hsb = scrollpane.getHorizontalScrollBar();
if (hsb != null) {
if (hsb.getBorder() == hsbBorder) {
hsb.setBorder(null);
}
hsbBorder = null;
}
}
}
private class AWTTextPane extends JScrollPane implements FocusListener {
private final JTextArea jtext;
private final XWindow xwin;
private final Color control = SystemColor.control;
private final Color focus = SystemColor.activeCaptionBorder;
AWTTextPane(JTextArea jt, XWindow xwin, Container parent) {
super(jt);
this.xwin = xwin;
setDoubleBuffered(true);
jt.addFocusListener(this);
AWTAccessor.getComponentAccessor().setParent(this,parent);
setViewportBorder(new BevelBorder(false,SystemColor.controlDkShadow,SystemColor.controlLtHighlight) );
this.jtext = jt;
setFocusable(false);
addNotify();
}
@Override
public void invalidate() {
synchronized (getTreeLock()) {
final Container parent = getParent();
AWTAccessor.getComponentAccessor().setParent(this, null);
try {
super.invalidate();
} finally {
AWTAccessor.getComponentAccessor().setParent(this, parent);
}
}
}
@Override
public void focusGained(FocusEvent e) {
Graphics g = getGraphics();
Rectangle r = getViewportBorderBounds();
g.setColor(focus);
g.drawRect(r.x,r.y,r.width,r.height);
g.dispose();
}
@Override
public void focusLost(FocusEvent e) {
Graphics g = getGraphics();
Rectangle r = getViewportBorderBounds();
g.setColor(control);
g.drawRect(r.x,r.y,r.width,r.height);
g.dispose();
}
public Window getRealParent() {
return (Window) xwin.target;
}
@Override
public ComponentPeer getPeer() {
return (ComponentPeer) (xwin);
}
@Override
public void updateUI() {
ComponentUI ui = new XAWTScrollPaneUI();
setUI(ui);
}
@Override
public JScrollBar createVerticalScrollBar() {
return new XAWTScrollBar(JScrollBar.VERTICAL);
}
@Override
public JScrollBar createHorizontalScrollBar() {
return new XAWTScrollBar(JScrollBar.HORIZONTAL);
}
public JTextArea getTextArea () {
return this.jtext;
}
@Override
public Graphics getGraphics() {
return xwin.getGraphics();
}
final class XAWTScrollBar extends ScrollBar {
XAWTScrollBar(int i) {
super(i);
setFocusable(false);
}
@Override
public void updateUI() {
ComponentUI ui = new XAWTScrollBarUI();
setUI(ui);
}
}
}
static class BevelBorder extends AbstractBorder implements UIResource {
private Color darkShadow = SystemColor.controlDkShadow;
private Color lightShadow = SystemColor.controlLtHighlight;
private Color control = SystemColor.controlShadow;
private boolean isRaised;
BevelBorder(boolean isRaised, Color darkShadow, Color lightShadow) {
this.isRaised = isRaised;
this.darkShadow = darkShadow;
this.lightShadow = lightShadow;
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
g.setColor((isRaised) ? lightShadow : darkShadow);
g.drawLine(x, y, x+w-1, y); // top
g.drawLine(x, y+h-1, x, y+1); // left
g.setColor(control);
g.drawLine(x+1, y+1, x+w-2, y+1); // top
g.drawLine(x+1, y+h-1, x+1, y+1); // left
g.setColor((isRaised) ? darkShadow : lightShadow);
g.drawLine(x+1, y+h-1, x+w-1, y+h-1); // bottom
g.drawLine(x+w-1, y+h-1, x+w-1, y+1); // right
g.setColor(control);
g.drawLine(x+1, y+h-2, x+w-2, y+h-2); // bottom
g.drawLine(x+w-2, y+h-2, x+w-2, y+1); // right
}
@Override
public Insets getBorderInsets(Component c) {
return getBorderInsets(c, new Insets(0,0,0,0));
}
@Override
public Insets getBorderInsets(Component c, Insets insets) {
insets.top = insets.left = insets.bottom = insets.right = 2;
return insets;
}
public boolean isOpaque(Component c) {
return true;
}
}
// This class dispatches 'MouseEvent's to 'XTextAreaPeer''s (hidden)
// subcomponents, and overrides mouse cursor, e.g. for scrollbars.
//
// However, current dispatching is a kind of fake, and is tuned to do only
// what is necessary/possible. E.g. no additional mouse-exited/entered
// events are generated, when mouse exits scrollbar and enters viewport
// with JTextArea inside. Actually, no events are ever generated here (for
// now). They are only dispatched as correctly as possible/neccessary.
//
// In future, it would be better to replace fake-emulation of grab-detection
// and event-dispatching here, by reusing some common implementation of this
// functionality. Mouse-cursor setting should also be freed of hacked
// overloading here.
private static final class JavaMouseEventHandler {
private final XTextAreaPeer outer;
private final Pointer current = new Pointer();
private boolean grabbed = false;
JavaMouseEventHandler( XTextAreaPeer outer ) {
this.outer = outer;
}
// 1. We can make grab-tracking emulation here more robust to variations in
// in mouse-events order and consistence. E.g. by using such code:
// if( grabbed && event.getID()==MouseEvent.MOUSE_MOVED ) grabbed = false;
// Or we can also use 'assert'ions.
// 2. WARNING: Currently, while grab-detection mechanism _here_ says, that
// grab is in progress, we do not update 'current'. In case 'current'
// is set to a scrollbar or to a scroll-button, then references to their
// 'Component'-instances are "remembered". And events are dispatched to
// these remembered components, without checking, if XTextAreaPeer has
// replaced these instances with another ones. This also aplies to
// mouse-drags-from-outside (see comment in 'grabbed_update' method).
void handle( MouseEvent event ) {
if ( ! grabbed ) {
// dispatch() needs up-to-date pointer in ungrabbed case.
setPointerToUnderPoint( event.getPoint() );
}
dispatch( event );
boolean wasGrabbed = grabbed;
grabbed_update( event );
if ( wasGrabbed && ! grabbed ) {
setPointerToUnderPoint( event.getPoint() );
}
setCursor();
}
// Following is internally private:
// Here dispatching is performed, of 'MouseEvent's to (some)
// 'XTextAreaPeer''s (hidden) subcomponents.
private void dispatch( MouseEvent event ) {
switch( current.getType() )
{
case TEXT:
Point point = toViewportChildLocalSpace(
outer.textPane.getViewport(), event.getPoint() );
XTextAreaPeer.AWTTextArea jtext = outer.jtext;
MouseEvent newEvent = newMouseEvent( jtext, point, event );
int id = newEvent.getID();
if ( id==MouseEvent.MOUSE_MOVED || id==MouseEvent.MOUSE_DRAGGED ) {
jtext.processMouseMotionEventPublic( newEvent );
} else {
jtext.processMouseEventPublic( newEvent );
}
break;
// We perform (additional) dispatching of events to buttons of
// scrollbar, instead of leaving it to JScrollbar. This is
// required, because of different listeners in Swing and AWT,
// which trigger scrolling (ArrowButtonListener vs. TrackListener,
// accordingly). So we dispatch events to scroll-buttons, to
// invoke a correct Swing button listener.
// See CR 6175401 for more information.
case BAR:
case BUTTON:
Component c = current.getBar();
Point p = toLocalSpace( c, event.getPoint() );
if ( current.getType()==Pointer.Type.BUTTON ) {
c = current.getButton();
p = toLocalSpace( c, p );
}
AWTAccessor.getComponentAccessor().processEvent( c, newMouseEvent( c, p, event ) );
break;
}
}
private static MouseEvent newMouseEvent(
Component source, Point point, MouseEvent template )
{
MouseEvent e = template;
MouseEvent nme = new MouseEvent(
source,
e.getID(), e.getWhen(),
e.getModifiersEx() | e.getModifiers(),
point.x, point.y,
e.getXOnScreen(), e.getYOnScreen(),
e.getClickCount(), e.isPopupTrigger(), e.getButton() );
// Because these MouseEvents are dispatched directly to
// their target, we need to mark them as being
// system-generated here
SunToolkit.setSystemGenerated(nme);
return nme;
}
private void setCursor() {
if ( current.getType()==Pointer.Type.TEXT ) {
// 'target.getCursor()' is also applied from elsewhere
// (at least now), but only when mouse "entered", and
// before 'XTextAreaPeer.handleJavaMouseEvent' is invoked.
outer.pSetCursor( outer.target.getCursor(), true );
}
else {
// We can write here a more intelligent cursor selection
// mechanism, like getting cursor from 'current' component.
// However, I see no point in doing so now. But if you feel
// like implementing it, you'll probably need to introduce
// 'Pointer.Type.PANEL'.
outer.pSetCursor( outer.textPane.getCursor(), true );
}
}
// Current way of grab-detection causes interesting (but harmless)
// side-effect. If mouse is draged from outside to inside of TextArea,
// we will then (in some cases) be asked to dispatch mouse-entered/exited
// events. But, as at least one mouse-button is down, we will detect
// grab-mode is on (though the grab isn't ours).
//
// Thus, we will not update 'current' (see 'handle' method), and will
// dispatch events to the last subcomponent, the 'current' was set to.
// As always, we set cursor in this case also. But, all this seems
// harmless, because mouse entered/exited events seem to have no effect
// here, and cursor setting is ignored in case of drags from outside.
//
// Grab-detection can be further improved, e.g. by taking into account
// current event-ID, but I see not point in doing it now.
private void grabbed_update( MouseEvent event ) {
final int allButtonsMask
= MouseEvent.BUTTON1_DOWN_MASK
| MouseEvent.BUTTON2_DOWN_MASK
| MouseEvent.BUTTON3_DOWN_MASK;
grabbed = ( (event.getModifiersEx() & allButtonsMask) != 0 );
}
// 'toLocalSpace' and 'toViewportChildLocalSpace' can be "optimized" to
// 'return' 'void' and use 'Point' input-argument also as output.
private static Point toLocalSpace( Component local, Point inParentSpace )
{
Point p = inParentSpace;
Point l = local.getLocation();
return new Point( p.x - l.x, p.y - l.y );
}
private static Point toViewportChildLocalSpace( JViewport v, Point inViewportParentSpace )
{
Point l = toLocalSpace(v, inViewportParentSpace);
Point p = v.getViewPosition();
l.x += p.x;
l.y += p.y;
return l;
}
private void setPointerToUnderPoint( Point point ) {
if ( outer.textPane.getViewport().getBounds().contains( point ) ) {
current.setText();
}
else if ( ! setPointerIfPointOverScrollbar(
outer.textPane.getVerticalScrollBar(), point ) )
{
if ( ! setPointerIfPointOverScrollbar(
outer.textPane.getHorizontalScrollBar(), point ) )
{
current.setNone();
}
}
}
private boolean setPointerIfPointOverScrollbar( JScrollBar bar, Point point ) {
if ( ! bar.getBounds().contains( point ) ) {
return false;
}
current.setBar( bar );
Point local = toLocalSpace( bar, point );
XTextAreaPeer.XAWTScrollBarUI ui =
(XTextAreaPeer.XAWTScrollBarUI) bar.getUI();
if ( ! setPointerIfPointOverButton( ui.getIncreaseButton(), local ) ) {
setPointerIfPointOverButton( ui.getDecreaseButton(), local );
}
return true;
}
private boolean setPointerIfPointOverButton( JButton button, Point point ) {
if ( ! button.getBounds().contains( point ) ) {
return false;
}
current.setButton( button );
return true;
}
private static final class Pointer {
static enum Type {
NONE, TEXT, BAR, BUTTON // , PANEL
}
Type getType() {
return type;
}
boolean isNone() {
return type==Type.NONE;
}
JScrollBar getBar() {
boolean ok = type==Type.BAR || type==Type.BUTTON;
assert ok;
return ok ? bar : null;
}
JButton getButton() {
boolean ok = type==Type.BUTTON;
assert ok;
return ok ? button : null;
}
void setNone() {
type = Type.NONE;
}
void setText() {
type = Type.TEXT;
}
void setBar( JScrollBar bar ) {
this.bar=bar;
type=Type.BAR;
}
void setButton( JButton button ) {
this.button=button;
type=Type.BUTTON;
}
private Type type;
private JScrollBar bar;
private JButton button;
}
}
}
| {
"pile_set_name": "Github"
} |
version: '3'
vars:
FILE: file.txt
CONTENT: default
tasks:
default:
cmds:
- echo "{{.CONTENT}}" > {{.FILE}}
| {
"pile_set_name": "Github"
} |
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
__global__ void AdaGradUpdate(int N, Dtype* g, Dtype* h, Dtype delta,
Dtype local_rate) {
CUDA_KERNEL_LOOP(i, N) {
float gi = g[i];
float hi = h[i] = h[i] + gi*gi;
g[i] = local_rate * gi / (sqrt(hi) + delta);
}
}
template <typename Dtype>
void adagrad_update_gpu(int N, Dtype* g, Dtype* h, Dtype delta,
Dtype local_rate) {
AdaGradUpdate<Dtype> // NOLINT_NEXT_LINE(whitespace/operators)
<<<CAFFE_GET_BLOCKS(N), CAFFE_CUDA_NUM_THREADS>>>(
N, g, h, delta, local_rate);
CUDA_POST_KERNEL_CHECK;
}
template void adagrad_update_gpu<float>(int, float*, float*, float, float);
template void adagrad_update_gpu<double>(int, double*, double*, double, double);
} // namespace caffe
| {
"pile_set_name": "Github"
} |
package org.matheclipse.core.doctools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import org.matheclipse.core.builtin.Arithmetic;
import org.matheclipse.core.convert.AST2Expr;
import org.matheclipse.core.eval.EvalEngine;
import org.matheclipse.core.interfaces.IExpr;
import org.matheclipse.core.parser.ExprParser;
import org.matheclipse.core.reflection.system.NIntegrate;
public class Github2 {
final static String BASE_POM_PATH = "..\\symja_android_library\\matheclipse-core\\";
final static String BASE_SRC_PATH = "src\\main\\java\\";
public static void main(final String[] args) {
String fileName=buildFileNameL(Arithmetic.Times.class);
File sourceLocation = new File(fileName);
// File sourceLocation = new File(
// "..\\symja_android_library\\matheclipse-core\\src\\main\\java\\org\\matheclipse\\core\\builtin\\Arithmetic.java");
int lineCounter = parseFileToList(sourceLocation, "Times");
System.out.println(lineCounter);
}
public static int parseFileToList(File file, String search) {
String s1 = "class " + search + " extends";
String s2 = "class " + search + " implements";
try {
final BufferedReader f = new BufferedReader(new FileReader(file));
String line;
int lineCounter = 0;
while ((line = f.readLine()) != null) {
lineCounter++;
int index = line.indexOf(search, 0);
if (index > 0) {
index = line.indexOf(s1, 0);
if (index > 0) {
f.close();
return lineCounter;
}
index = line.indexOf(s2, 0);
if (index > 0) {
f.close();
return lineCounter;
}
}
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public static String buildFileNameL(final Class<?> clazz) {
StringBuilder buf = new StringBuilder(512);
buf.append(BASE_POM_PATH);
buf.append(BASE_SRC_PATH);
String canonicalName = clazz.getCanonicalName();
String packageName = clazz.getPackage().getName();
String parentClass = canonicalName.substring(packageName.length() + 1);
int index = parentClass.indexOf('.');
if (index > 0) {
parentClass = parentClass.substring(0, index);
}
String packagePath = packageName.replace('.', '\\');
buf.append(packagePath);
buf.append('\\');
buf.append(parentClass);
buf.append(".java");
return buf.toString();
}
}
| {
"pile_set_name": "Github"
} |
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:sp="http://www.w3.org/ns/pim/space#"
xmlns:sched="http://www.w3.org/ns/pim/schedule#"
xmlns:rdf="http://www.w3.org/2000/01/rdf-schema#"
xmlns:ic="http://www.w3.org/2002/12/cal/ical#"
xmlns:n0="http://xmlns.com/foaf/0.1/">
<sched:SchedulableEvent rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#event">
<dc:author rdf:resource="https://www.w3.org/People/Berners-Lee/card#i"/>
<dc:created>2015-09-15T11:20:05Z</dc:created>
<sp:inspiration rdf:resource="http://linkeddata.github.io/app-schedule/details.ttl#event1"/>
</sched:SchedulableEvent>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#event1">
<dc:author rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316021316"/>
<dc:title>TAG 2016 Q1 Meeting </dc:title>
<rdf:comment>Three day meeting, starting date:</rdf:comment>
<ic:location>Melbourne Australia</ic:location>
<sched:availabilityOptions rdf:resource="http://www.w3.org/ns/pim/schedule#YesNoMaybe"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316021320"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316359855"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316381050"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316382860"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316551915"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316616585"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316618393"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316627647"/>
<sched:invitee rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316628781"/>
<sched:option rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316021318"/>
<sched:option rdf:resource="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316021319"/>
<sched:ready>2015-09-15T11:20:21Z</sched:ready>
<sched:results rdf:resource="https://timbl.com/2015/09/tagpoll/results.ttl"/>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316021316">
<n0:mbox>[email protected]</n0:mbox><n0:name>Tim BL</n0:name>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316021318">
<ic:dtstart>2016-01-13</ic:dtstart>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316021319">
<ic:dtstart>2016-01-20</ic:dtstart>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316021320">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316359855">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316382860">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316381050">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316551915">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316616585">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316618393">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316627647">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
<rdf:Description rdf:about="https://timbl.com/2015/09/tagpoll/details.ttl#id1442316628781">
<n0:mbox>[email protected]</n0:mbox>
</rdf:Description>
</rdf:RDF>
" | {
"pile_set_name": "Github"
} |
var baseIsMatch = require('./baseIsMatch'),
getMatchData = require('./getMatchData'),
toObject = require('./toObject');
/**
* The base implementation of `_.matches` which does not clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
var key = matchData[0][0],
value = matchData[0][1];
return function(object) {
if (object == null) {
return false;
}
return object[key] === value && (value !== undefined || (key in toObject(object)));
};
}
return function(object) {
return baseIsMatch(object, matchData);
};
}
module.exports = baseMatches;
| {
"pile_set_name": "Github"
} |
// setup theme configs and styles
@import "config";
@import "primitives";
// extend the __THEME_EXTENDS__ theme
@import "__THEME_EXTENDS__";
//@import "../__THEME_EXTENDS__/core";
// import helper functions
@import "helpers";
// finally initialize our custom components
@import "components";
| {
"pile_set_name": "Github"
} |
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
| {
"pile_set_name": "Github"
} |
//===-- JIT.h - Abstract Execution Engine Interface -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Common functionality for JITEventListener implementations
//
//===----------------------------------------------------------------------===//
#ifndef EVENT_LISTENER_COMMON_H
#define EVENT_LISTENER_COMMON_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/Path.h"
namespace llvm {
namespace jitprofiling {
class FilenameCache {
// Holds the filename of each Scope, so that we can pass a null-terminated
// string into oprofile.
DenseMap<const MDNode *, std::string> Filenames;
DenseMap<const MDNode *, std::string> Paths;
public:
const char *getFilename(MDNode *Scope) {
assert(Scope->isResolved() && "Expected Scope to be resolved");
std::string &Filename = Filenames[Scope];
if (Filename.empty()) {
DIScope DIScope(Scope);
Filename = DIScope.getFilename();
}
return Filename.c_str();
}
const char *getFullPath(MDNode *Scope) {
assert(Scope->isResolved() && "Expected Scope to be resolved");
std::string &P = Paths[Scope];
if (P.empty()) {
DIScope DIScope(Scope);
StringRef DirName = DIScope.getDirectory();
StringRef FileName = DIScope.getFilename();
SmallString<256> FullPath;
if (DirName != "." && DirName != "") {
FullPath = DirName;
}
if (FileName != "") {
sys::path::append(FullPath, FileName);
}
P = FullPath.str();
}
return P.c_str();
}
};
} // namespace jitprofiling
} // namespace llvm
#endif //EVENT_LISTENER_COMMON_H
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
*
* Contact: Ernest Borowski <[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
*
*
* @file Certificates.cs
* @author Ernest Borowski ([email protected])
* @version 1.0
* @brief This file contains class used in ListView grupping (UI)
*/
namespace SecureRepository
{
using System.Collections.Generic;
/// <summary>
/// Enumeration for item type.
/// </summary>
public enum AliasType
{
/// <summary>
/// Represents a data.
/// </summary>
Data,
/// <summary>
/// Represents a Key.
/// </summary>
Key,
/// <summary>
/// Represents a Certificate.
/// </summary>
Certificate
}
/// <summary>
/// class responsible for holding item list (UI).
/// </summary>
public class ListViewGroup : List<Item>
{
/// <summary>
/// Initializes a new instance of the ListViewGroup class.
/// </summary>
/// <param name="aliasType">item type.</param>
public ListViewGroup(AliasType aliasType)
{
switch (aliasType)
{
case AliasType.Certificate:
this.Title = "Certificate";
this.ShortName = "C";
break;
case AliasType.Key:
this.Title = "Key";
this.ShortName = "K";
break;
case AliasType.Data:
this.Title = "Data";
this.ShortName = "D";
break;
}
}
/// <summary>
/// Gets first letter of item type.
/// </summary>
public string ShortName { get; }
/// <summary>
/// Gets item alias.
/// </summary>
public string Title { get; }
}
}
| {
"pile_set_name": "Github"
} |
<menu>
<Services>
<DynamicDNS VisibleName="Dynamic DNS" url="/services_dyndns.php" cssClass="fa fa-tags fa-fw">
<Edit url="/services_dyndns_edit.php*" visibility="hidden"/>
</DynamicDNS>
</Services>
</menu>
| {
"pile_set_name": "Github"
} |
{-# LANGUAGE TemplateHaskell #-}
module Foo where
-- This is here just to trigger template haskell
blork = $([| 1 + 1 |])
| {
"pile_set_name": "Github"
} |
# AtomicCreateTableAsSelectExec
`AtomicCreateTableAsSelectExec` is...FIXME
| {
"pile_set_name": "Github"
} |
/****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCRENDERCOMMAND_H_
#define __CCRENDERCOMMAND_H_
#include <stdint.h>
#include "platform/CCPlatformMacros.h"
#include "base/ccTypes.h"
/**
* @addtogroup renderer
* @{
*/
NS_CC_BEGIN
/** Base class of the `RenderCommand` hierarchy.
*
The `Renderer` knows how to render `RenderCommands` objects.
*/
class CC_DLL RenderCommand
{
public:
/**Enum the type of render command. */
enum class Type
{
/** Reserved type.*/
UNKNOWN_COMMAND,
/** Quad command, used for draw quad.*/
QUAD_COMMAND,
/**Custom command, used for calling callback for rendering.*/
CUSTOM_COMMAND,
/**Batch command, used for draw batches in texture atlas.*/
BATCH_COMMAND,
/**Group command, which can group command in a tree hierarchy.*/
GROUP_COMMAND,
/**Mesh command, used to draw 3D meshes.*/
MESH_COMMAND,
/**Primitive command, used to draw primitives such as lines, points and triangles.*/
PRIMITIVE_COMMAND,
/**Triangles command, used to draw triangles.*/
TRIANGLES_COMMAND
};
/**
Init function, will be called by all the render commands.
@param globalZOrder The global order of command, used for rendercommand sorting.
@param modelViewTransform Modelview matrix when submitting the render command.
@param flags Flag used to indicate whether the command should be draw at 3D mode or not.
*/
void init(float globalZOrder, const Mat4& modelViewTransform, uint32_t flags);
/** Get global Z order. */
inline float getGlobalOrder() const { return _globalOrder; }
/** Returns the Command type. */
inline Type getType() const { return _type; }
/** Retruns whether is transparent. */
inline bool isTransparent() const { return _isTransparent; }
/** Set transparent flag. */
inline void setTransparent(bool isTransparent) { _isTransparent = isTransparent; }
/**
Get skip batching status, if a rendering is skip batching, it will be forced to be rendering separately.
*/
inline bool isSkipBatching() const { return _skipBatching; }
/**Set skip batching.*/
inline void setSkipBatching(bool value) { _skipBatching = value; }
/**Whether the command should be rendered at 3D mode.*/
inline bool is3D() const { return _is3D; }
/**Set the command rendered in 3D mode or not.*/
inline void set3D(bool value) { _is3D = value; }
/**Get the depth by current model view matrix.*/
inline float getDepth() const { return _depth; }
protected:
/**Constructor.*/
RenderCommand();
/**Desctructor.*/
virtual ~RenderCommand();
//used for debug but it is not implemented.
void printID();
/**Type used in order to avoid dynamic cast, faster. */
Type _type;
/** Commands are sort by global Z order. */
float _globalOrder;
/** Transparent flag. */
bool _isTransparent;
/**
QuadCommand and TrianglesCommand could be auto batched if there material ID is the same, however, if
a command is skip batching, it would be forced to draw in a separate function call, and break the batch.
*/
bool _skipBatching;
/** Is the command been rendered on 3D pass. */
bool _is3D;
/** Depth from the model view matrix.*/
float _depth;
};
NS_CC_END
/**
end of support group
@}
*/
#endif //__CCRENDERCOMMAND_H_
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.analysis.function;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.exception.NullArgumentException;
import org.apache.commons.math.exception.DimensionMismatchException;
import org.junit.Assert;
import org.junit.Test;
/**
* Test for class {@link Sigmoid}.
*/
public class SigmoidTest {
private final double EPS = Math.ulp(1d);
@Test
public void testSomeValues() {
final UnivariateRealFunction f = new Sigmoid();
Assert.assertEquals(0.5, f.value(0), EPS);
Assert.assertEquals(0, f.value(Double.NEGATIVE_INFINITY), EPS);
Assert.assertEquals(1, f.value(Double.POSITIVE_INFINITY), EPS);
}
@Test
public void testDerivative() {
final Sigmoid f = new Sigmoid();
final UnivariateRealFunction dfdx = f.derivative();
Assert.assertEquals(0.25, dfdx.value(0), 0);
}
@Test
public void testDerivativeLargeArguments() {
final Sigmoid f = new Sigmoid(1, 2);
final UnivariateRealFunction dfdx = f.derivative();
Assert.assertEquals(0, dfdx.value(Double.NEGATIVE_INFINITY), 0);
Assert.assertEquals(0, dfdx.value(-Double.MAX_VALUE), 0);
Assert.assertEquals(0, dfdx.value(-1e50), 0);
Assert.assertEquals(0, dfdx.value(-1e3), 0);
Assert.assertEquals(0, dfdx.value(1e3), 0);
Assert.assertEquals(0, dfdx.value(1e50), 0);
Assert.assertEquals(0, dfdx.value(Double.MAX_VALUE), 0);
Assert.assertEquals(0, dfdx.value(Double.POSITIVE_INFINITY), 0);
}
@Test(expected=NullArgumentException.class)
public void testParametricUsage1() {
final Sigmoid.Parametric g = new Sigmoid.Parametric();
g.value(0, null);
}
@Test(expected=DimensionMismatchException.class)
public void testParametricUsage2() {
final Sigmoid.Parametric g = new Sigmoid.Parametric();
g.value(0, new double[] {0});
}
@Test(expected=NullArgumentException.class)
public void testParametricUsage3() {
final Sigmoid.Parametric g = new Sigmoid.Parametric();
g.gradient(0, null);
}
@Test(expected=DimensionMismatchException.class)
public void testParametricUsage4() {
final Sigmoid.Parametric g = new Sigmoid.Parametric();
g.gradient(0, new double[] {0});
}
@Test
public void testParametricValue() {
final double lo = 2;
final double hi = 3;
final Sigmoid f = new Sigmoid(lo, hi);
final Sigmoid.Parametric g = new Sigmoid.Parametric();
Assert.assertEquals(f.value(-1), g.value(-1, new double[] {lo, hi}), 0);
Assert.assertEquals(f.value(0), g.value(0, new double[] {lo, hi}), 0);
Assert.assertEquals(f.value(2), g.value(2, new double[] {lo, hi}), 0);
}
}
| {
"pile_set_name": "Github"
} |
// leaf_node.hpp
// Copyright (c) 2007-2009 Ben Hanson (http://www.benhanson.net/)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file licence_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_LEXER_LEAF_NODE_HPP
#define BOOST_LEXER_LEAF_NODE_HPP
#include "../../consts.hpp" // null_token
#include "node.hpp"
#include "../../size_t.hpp"
namespace boost
{
namespace lexer
{
namespace detail
{
class leaf_node : public node
{
public:
leaf_node (const std::size_t token_, const bool greedy_) :
node (token_ == null_token),
_token (token_),
_set_greedy (!greedy_),
_greedy (greedy_)
{
if (!_nullable)
{
_firstpos.push_back (this);
_lastpos.push_back (this);
}
}
virtual ~leaf_node ()
{
}
virtual void append_followpos (const node_vector &followpos_)
{
for (node_vector::const_iterator iter_ = followpos_.begin (),
end_ = followpos_.end (); iter_ != end_; ++iter_)
{
_followpos.push_back (*iter_);
}
}
virtual type what_type () const
{
return LEAF;
}
virtual bool traverse (const_node_stack &/*node_stack_*/,
bool_stack &/*perform_op_stack_*/) const
{
return false;
}
virtual std::size_t token () const
{
return _token;
}
virtual void greedy (const bool greedy_)
{
if (!_set_greedy)
{
_greedy = greedy_;
_set_greedy = true;
}
}
virtual bool greedy () const
{
return _greedy;
}
virtual const node_vector &followpos () const
{
return _followpos;
}
virtual node_vector &followpos ()
{
return _followpos;
}
private:
std::size_t _token;
bool _set_greedy;
bool _greedy;
node_vector _followpos;
virtual void copy_node (node_ptr_vector &node_ptr_vector_,
node_stack &new_node_stack_, bool_stack &/*perform_op_stack_*/,
bool &/*down_*/) const
{
node_ptr_vector_->push_back (static_cast<leaf_node *>(0));
node_ptr_vector_->back () = new leaf_node (_token, _greedy);
new_node_stack_.push (node_ptr_vector_->back ());
}
};
}
}
}
#endif
| {
"pile_set_name": "Github"
} |
// Targeted by JavaCPP version 1.5.4: DO NOT EDIT THIS FILE
package org.bytedeco.tensorflow;
import org.bytedeco.tensorflow.Allocator;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.tensorflow.global.tensorflow.*;
/** Strip leading and trailing whitespaces from the Tensor.
*
* Arguments:
* * scope: A Scope object
* * input: A string {@code Tensor} of any shape.
*
* Returns:
* * {@code Output}: A string {@code Tensor} of the same shape as the input. */
@Namespace("tensorflow::ops") @NoOffset @Properties(inherit = org.bytedeco.tensorflow.presets.tensorflow.class)
public class StringStrip extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public StringStrip(Pointer p) { super(p); }
public StringStrip(@Const @ByRef Scope scope, @ByVal Input input) { super((Pointer)null); allocate(scope, input); }
private native void allocate(@Const @ByRef Scope scope, @ByVal Input input);
public native @ByVal @Name("operator tensorflow::Output") Output asOutput();
public native @ByVal @Name("operator tensorflow::Input") Input asInput();
public native Node node();
public native @ByRef Operation operation(); public native StringStrip operation(Operation setter);
public native @ByRef Output output(); public native StringStrip output(Output setter);
}
| {
"pile_set_name": "Github"
} |
#
# WiMAX LAN device configuration
#
menuconfig WIMAX
tristate "WiMAX Wireless Broadband support"
depends on RFKILL || !RFKILL
help
Select to configure support for devices that provide
wireless broadband connectivity using the WiMAX protocol
(IEEE 802.16).
Please note that most of these devices require signing up
for a service plan with a provider.
The different WiMAX drivers can be enabled in the menu entry
Device Drivers > Network device support > WiMAX Wireless
Broadband devices
If unsure, it is safe to select M (module).
config WIMAX_DEBUG_LEVEL
int "WiMAX debug level"
depends on WIMAX
default 8
help
Select the maximum debug verbosity level to be compiled into
the WiMAX stack code.
By default, debug messages are disabled at runtime and can
be selectively enabled for different parts of the code using
the sysfs debug-levels file.
If set at zero, this will compile out all the debug code.
It is recommended that it is left at 8.
| {
"pile_set_name": "Github"
} |
package crypto
import (
"crypto/md5"
"crypto/rand"
"io"
)
// DeriveKey derives a key from a string of password.
func DeriveKey(password string, length int) []byte {
var key, prev []byte
h := md5.New()
for len(key) < length {
h.Write(prev)
h.Write([]byte(password))
key = h.Sum(key)
prev = key[len(key)-h.Size():]
h.Reset()
}
return key[:length]
}
// GenerateIV generates a random IV of the given size.
func GenerateIV(size int) ([]byte, error) {
iv := make([]byte, size)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
return iv, nil
}
// GenerateNonce generates a random nonce of the given size.
func GenerateNonce(size int) ([]byte, error) {
nonce := make([]byte, size)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return nonce, nil
}
| {
"pile_set_name": "Github"
} |
#include <algorithm>
// bring on the public stuff
#include "Parsing.h"
#include "Private/Defines.h"
#include "Private/Skipper.h"
#include "Private/Userlist/Grammar/Grammar.h"
namespace boss { namespace parsing {
using std::istream;
using std::string;
bool Userlist::Parse(istream& in, IRulesManager& manager)
{
using std::ios;
using std::istream_iterator;
using std::copy;
using std::back_inserter;
string storage; // We will read the contents here.
in.unsetf(ios::skipws); // No white space skipping!
copy(
istream_iterator<char>(in),
istream_iterator<char>(),
back_inserter(storage));
return Parse(storage, manager);
}
bool Userlist::Parse(string& storage, IRulesManager& manager)
{
using std::count;
typedef detail::Skipper<string::const_iterator> Skipper;
typedef detail::Grammar<string::const_iterator, Skipper> Grammar;
Skipper skipper;
Grammar grammar(manager);
string::iterator iter = storage.begin();
string::iterator end = storage.end();
bool success = qi::phrase_parse(iter, end, grammar, skipper) && (iter == end);
if (!success) {
while (*iter == '\n') {
iter++;
}
string::difference_type lines = 1 + count(storage.begin(), iter, '\n');
manager.ParsingFailed(storage.begin(), end, iter, lines);
}
return success;
}
}} | {
"pile_set_name": "Github"
} |
package loon.build.tools;
import java.util.Locale;
public enum Language {
SIMPLECN(Locale.SIMPLIFIED_CHINESE), TRADITIONALCN(
Locale.TRADITIONAL_CHINESE), EN(Locale.ENGLISH), JP(Locale.JAPANESE), DEF();
private Locale locale;
Language(Locale locale) {
this.locale = locale;
}
Language() {
this(Locale.getDefault());
}
public Locale getLocale() {
return locale;
}
} | {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.VFX;
namespace UnityEditor.VFX
{
[VFXGizmo(typeof(Position))]
class VFXPositionGizmo : VFXSpaceableGizmo<Position>
{
IProperty<Position> m_Property;
public override void RegisterEditableMembers(IContext context)
{
m_Property = context.RegisterProperty<Position>("");
}
public override void OnDrawSpacedGizmo(Position position)
{
if (m_Property.isEditable && PositionGizmo(ref position.position, true))
{
m_Property.SetValue(position);
}
}
public override Bounds OnGetSpacedGizmoBounds(Position value)
{
return new Bounds(value.position, Vector3.one);
}
}
[VFXGizmo(typeof(DirectionType))]
class VFXDirectionGizmo : VFXSpaceableGizmo<DirectionType>
{
IProperty<DirectionType> m_Property;
public override void RegisterEditableMembers(IContext context)
{
m_Property = context.RegisterProperty<DirectionType>("");
}
public override void OnDrawSpacedGizmo(DirectionType direction)
{
direction.direction.Normalize();
if (direction.direction == Vector3.zero)
{
direction.direction = Vector3.up;
}
Quaternion normalQuat = Quaternion.FromToRotation(Vector3.forward, direction.direction);
Ray ray = HandleUtility.GUIPointToWorldRay(Vector2.one * 200);
var position = ray.origin + ray.direction * 2;
var mat = Handles.matrix;
mat.SetColumn(3, new Vector4(position.x, position.y, position.z, 1));
Handles.matrix = mat;
Handles.ArrowHandleCap(0, Vector3.zero, normalQuat, HandleUtility.GetHandleSize(Vector3.zero) * 1, Event.current.type);
if (m_Property.isEditable && NormalGizmo(Vector3.zero, ref direction.direction, true))
{
direction.direction.Normalize();
m_Property.SetValue(direction);
}
}
Quaternion m_PrevQuaternion;
public static void AngleHandleDrawFunction(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType)
{
Handles.DrawWireDisc(Vector3.zero, Vector3.forward, size * 10);
Handles.DrawLine(Vector3.zero, position);
}
public override Bounds OnGetSpacedGizmoBounds(DirectionType value)
{
return new Bounds(Vector3.zero, Vector3.zero);
}
}
[VFXGizmo(typeof(Vector))]
class VFXVectorGizmo : VFXSpaceableGizmo<Vector>
{
IProperty<Vector> m_Property;
public override void RegisterEditableMembers(IContext context)
{
m_Property = context.RegisterProperty<Vector>("");
}
public override void OnDrawSpacedGizmo(Vector vector)
{
if (vector.vector == Vector3.zero)
{
vector.vector = Vector3.up;
}
Quaternion normalQuat = Quaternion.FromToRotation(Vector3.forward, vector.vector);
float length = vector.vector.magnitude;
if (m_Property.isEditable && NormalGizmo(Vector3.zero, ref vector.vector, true))
{
m_Property.SetValue(vector);
}
if (m_Property.isEditable)
{
Handles.DrawLine(Vector3.zero, vector.vector);
EditorGUI.BeginChangeCheck();
Vector3 result = Handles.Slider(vector.vector, vector.vector, handleSize * 2 * HandleUtility.GetHandleSize(vector.vector), Handles.ConeHandleCap, 0);
if (EditorGUI.EndChangeCheck())
{
vector.vector = vector.vector.normalized * result.magnitude;
m_Property.SetValue(vector);
}
}
else
{
Handles.ArrowHandleCap(0, Vector3.zero, normalQuat, length, Event.current.type);
}
}
public override Bounds OnGetSpacedGizmoBounds(Vector value)
{
return new Bounds(Vector3.zero, Vector3.one * value.vector.magnitude * 2);
}
}
}
| {
"pile_set_name": "Github"
} |
include(QHexView/QHexView.pri)
QT += core gui widgets
TARGET = ApkStudio
TEMPLATE = app
CONFIG += c++11
HEADERS += \
Qt-Frameless-Window-DarkStyle/DarkStyle.h \
sources/adbinstallworker.h \
sources/apkdecompiledialog.h \
sources/apkdecompileworker.h \
sources/apkrecompileworker.h \
sources/apksignworker.h \
sources/appearancesettingswidget.h \
sources/binarysettingswidget.h \
sources/findreplacedialog.h \
sources/flickcharm.h \
sources/hexedit.h \
sources/imageviewerwidget.h \
sources/mainwindow.h \
sources/processutils.h \
sources/settingsdialog.h \
sources/signingconfigdialog.h \
sources/signingconfigwidget.h \
sources/sourcecodeedit.h \
sources/splashwindow.h \
sources/themedsyntaxhighlighter.h \
sources/versionresolveworker.h
SOURCES += \
Qt-Frameless-Window-DarkStyle/DarkStyle.cpp \
sources/flickcharm.cpp \
sources/hexedit.cpp \
sources/imageviewerwidget.cpp \
sources/main.cpp \
sources/adbinstallworker.cpp \
sources/apkdecompiledialog.cpp \
sources/apkdecompileworker.cpp \
sources/apkrecompileworker.cpp \
sources/apksignworker.cpp \
sources/appearancesettingswidget.cpp \
sources/binarysettingswidget.cpp \
sources/findreplacedialog.cpp \
sources/mainwindow.cpp \
sources/processutils.cpp \
sources/settingsdialog.cpp \
sources/signingconfigdialog.cpp \
sources/signingconfigwidget.cpp \
sources/sourcecodeedit.cpp \
sources/splashwindow.cpp \
sources/themedsyntaxhighlighter.cpp \
sources/versionresolveworker.cpp
RESOURCES += \
Qt-Frameless-Window-DarkStyle/darkstyle.qrc \
resources/all.qrc
OTHER_FILES += \
build/linux.sh \
build/osx.sh \
build/windows.bat \
docs/index.html \
resources/apkstudio.desktop \
.appveyor.yml \
.travis.yml \
README.md
mac:ICON = resources/icon.icns
unix {
isEmpty(PREFIX) {
PREFIX = /usr/local
}
target.path = $$PREFIX/bin
icons.files += resources/icon.png
icons.path = $$PREFIX/share/pixmaps/
shortcut.files = resources/apkstudio.desktop
shortcut.path = $$PREFIX/share/applications/
INSTALLS += target icons shortcut
TARGET = apkstudio
}
win32:RC_ICONS += resources/icon.ico
QMAKE_TARGET_COMPANY = Vaibhav Pandey -aka- VPZ
QMAKE_TARGET_COPYRIGHT = Vaibhav Pandey
QMAKE_TARGET_DESCRIPTION = Open-source, cross-platform Qt based IDE for reverse-engineering Android application packages.
QMAKE_TARGET_PRODUCT = APK Studio
win32 {
NULL_DEVICE = NUL
} else {
NULL_DEVICE = /dev/null
}
GIT_CMD_BASE = git --git-dir $$PWD/.git --work-tree $$PWD
GIT_BRANCH = $$system($$GIT_CMD_BASE rev-parse --abbrev-ref HEAD 2> $$NULL_DEVICE)
GIT_COMMIT_FULL = $$system($$GIT_CMD_BASE rev-parse HEAD 2> $$NULL_DEVICE)
GIT_COMMIT_NUMBER = $$system($$GIT_CMD_BASE rev-list HEAD --count 2> $$NULL_DEVICE)
GIT_COMMIT_SHORT = $$system($$GIT_CMD_BASE rev-parse --short HEAD 2> $$NULL_DEVICE)
GIT_TAG = $$system($$GIT_CMD_BASE tag -l --points-at HEAD 2> $$NULL_DEVICE)
DEFINES += GIT_BRANCH=\\\"$$GIT_BRANCH\\\" \
GIT_COMMIT_FULL=\\\"$$GIT_COMMIT_FULL\\\" \
GIT_COMMIT_NUMBER=\\\"$$GIT_COMMIT_NUMBER\\\" \
GIT_COMMIT_SHORT=\\\"$$GIT_COMMIT_SHORT\\\" \
GIT_TAG=\\\"$$GIT_TAG\\\"
!isEmpty(GIT_TAG) {
win32 {
VERSION = $${GIT_TAG}.$${GIT_COMMIT_NUMBER}
} else {
VERSION = $$GIT_TAG
}
macx {
INFO_PLIST_PATH = $$shell_quote($${OUT_PWD}/$${TARGET}.app/Contents/Info.plist)
QMAKE_POST_LINK += /usr/libexec/PlistBuddy -c \"Set :CFBundleShortVersionString $${VERSION}\" $${INFO_PLIST_PATH}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#ifndef _NGX_CYCLE_H_INCLUDED_
#define _NGX_CYCLE_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
#ifndef NGX_CYCLE_POOL_SIZE
#define NGX_CYCLE_POOL_SIZE NGX_DEFAULT_POOL_SIZE
#endif
#define NGX_DEBUG_POINTS_STOP 1
#define NGX_DEBUG_POINTS_ABORT 2
typedef struct ngx_shm_zone_s ngx_shm_zone_t;
typedef ngx_int_t (*ngx_shm_zone_init_pt) (ngx_shm_zone_t *zone, void *data);
struct ngx_shm_zone_s {
void *data;
ngx_shm_t shm;
ngx_shm_zone_init_pt init;
void *tag;
void *sync;
ngx_uint_t noreuse; /* unsigned noreuse:1; */
};
struct ngx_cycle_s {
void ****conf_ctx;
ngx_pool_t *pool;
ngx_log_t *log;
ngx_log_t new_log;
ngx_uint_t log_use_stderr; /* unsigned log_use_stderr:1; */
ngx_connection_t **files;
ngx_connection_t *free_connections;
ngx_uint_t free_connection_n;
ngx_module_t **modules;
ngx_uint_t modules_n;
ngx_uint_t modules_used; /* unsigned modules_used:1; */
ngx_queue_t reusable_connections_queue;
ngx_uint_t reusable_connections_n;
time_t connections_reuse_time;
ngx_array_t listening;
ngx_array_t paths;
ngx_array_t config_dump;
ngx_rbtree_t config_dump_rbtree;
ngx_rbtree_node_t config_dump_sentinel;
ngx_list_t open_files;
ngx_list_t shared_memory;
ngx_uint_t connection_n;
ngx_uint_t files_n;
ngx_connection_t *connections;
ngx_event_t *read_events;
ngx_event_t *write_events;
ngx_cycle_t *old_cycle;
ngx_str_t conf_file;
ngx_str_t conf_param;
ngx_str_t conf_prefix;
ngx_str_t prefix;
ngx_str_t lock_file;
ngx_str_t hostname;
};
typedef struct {
ngx_flag_t daemon;
ngx_flag_t master;
ngx_msec_t timer_resolution;
ngx_msec_t shutdown_timeout;
ngx_int_t worker_processes;
ngx_int_t debug_points;
ngx_int_t rlimit_nofile;
off_t rlimit_core;
int priority;
ngx_uint_t cpu_affinity_auto;
ngx_uint_t cpu_affinity_n;
ngx_cpuset_t *cpu_affinity;
char *username;
ngx_uid_t user;
ngx_gid_t group;
ngx_str_t working_directory;
ngx_str_t lock_file;
ngx_str_t pid;
ngx_str_t oldpid;
ngx_array_t env;
char **environment;
ngx_uint_t transparent; /* unsigned transparent:1; */
} ngx_core_conf_t;
#define ngx_is_init_cycle(cycle) (cycle->conf_ctx == NULL)
ngx_cycle_t *ngx_init_cycle(ngx_cycle_t *old_cycle);
ngx_int_t ngx_create_pidfile(ngx_str_t *name, ngx_log_t *log);
void ngx_delete_pidfile(ngx_cycle_t *cycle);
ngx_int_t ngx_signal_process(ngx_cycle_t *cycle, char *sig);
void ngx_reopen_files(ngx_cycle_t *cycle, ngx_uid_t user);
char **ngx_set_environment(ngx_cycle_t *cycle, ngx_uint_t *last);
ngx_pid_t ngx_exec_new_binary(ngx_cycle_t *cycle, char *const *argv);
ngx_cpuset_t *ngx_get_cpu_affinity(ngx_uint_t n);
ngx_shm_zone_t *ngx_shared_memory_add(ngx_conf_t *cf, ngx_str_t *name,
size_t size, void *tag);
void ngx_set_shutdown_timer(ngx_cycle_t *cycle);
extern volatile ngx_cycle_t *ngx_cycle;
extern ngx_array_t ngx_old_cycles;
extern ngx_module_t ngx_core_module;
extern ngx_uint_t ngx_test_config;
extern ngx_uint_t ngx_dump_config;
extern ngx_uint_t ngx_quiet_mode;
#endif /* _NGX_CYCLE_H_INCLUDED_ */
| {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Barcode
* @subpackage Renderer
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Image.php 20366 2010-01-18 03:56:52Z ralph $
*/
/** @see Zend_Barcode_Renderer_RendererAbstract*/
require_once 'Zend/Barcode/Renderer/RendererAbstract.php';
/**
* Class for rendering the barcode as svg
*
* @category Zend
* @package Zend_Barcode
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Barcode_Renderer_Svg extends Zend_Barcode_Renderer_RendererAbstract
{
/**
* Resource for the image
* @var DOMDocument
*/
protected $_resource = null;
/**
* Root element of the XML structure
* @var DOMElement
*/
protected $_rootElement = null;
/**
* Height of the rendered image wanted by user
* @var integer
*/
protected $_userHeight = 0;
/**
* Width of the rendered image wanted by user
* @var integer
*/
protected $_userWidth = 0;
/**
* Set height of the result image
* @param null|integer $value
* @return Zend_Image_Barcode_Abstract
* @throw Zend_Image_Barcode_Exception
*/
public function setHeight($value)
{
if (!is_numeric($value) || intval($value) < 0) {
require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Svg height must be greater than or equals 0'
);
}
$this->_userHeight = intval($value);
return $this;
}
/**
* Get barcode height
*
* @return int
*/
public function getHeight()
{
return $this->_userHeight;
}
/**
* Set barcode width
*
* @param mixed $value
* @return void
*/
public function setWidth($value)
{
if (!is_numeric($value) || intval($value) < 0) {
require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Svg width must be greater than or equals 0'
);
}
$this->_userWidth = intval($value);
return $this;
}
/**
* Get barcode width
*
* @return int
*/
public function getWidth()
{
return $this->_userWidth;
}
/**
* Set an image resource to draw the barcode inside
*
* @param DOMDocument $value
* @return Zend_Barcode_Renderer
* @throw Zend_Barcode_Renderer_Exception
*/
public function setResource($svg)
{
if (!$svg instanceof DOMDocument) {
require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Invalid DOMDocument resource provided to setResource()'
);
}
$this->_resource = $svg;
return $this;
}
/**
* Initialize the image resource
*
* @return void
*/
protected function _initRenderer()
{
$barcodeWidth = $this->_barcode->getWidth(true);
$barcodeHeight = $this->_barcode->getHeight(true);
$backgroundColor = $this->_barcode->getBackgroundColor();
$imageBackgroundColor = 'rgb(' . implode(', ', array(($backgroundColor & 0xFF0000) >> 16,
($backgroundColor & 0x00FF00) >> 8,
($backgroundColor & 0x0000FF))) . ')';
$width = $barcodeWidth;
$height = $barcodeHeight;
if ($this->_userWidth && $this->_barcode->getType() != 'error') {
$width = $this->_userWidth;
}
if ($this->_userHeight && $this->_barcode->getType() != 'error') {
$height = $this->_userHeight;
}
if ($this->_resource === null) {
$this->_resource = new DOMDocument('1.0', 'utf-8');
$this->_resource->formatOutput = true;
$this->_rootElement = $this->_resource->createElement('svg');
$this->_rootElement->setAttribute('xmlns', "http://www.w3.org/2000/svg");
$this->_rootElement->setAttribute('version', '1.1');
$this->_rootElement->setAttribute('width', $width);
$this->_rootElement->setAttribute('height', $height);
$this->_appendRootElement('title',
array(),
"Barcode " . strtoupper($this->_barcode->getType()) . " " . $this->_barcode->getText());
} else {
$this->_readRootElement();
$width = $this->_rootElement->getAttribute('width');
$height = $this->_rootElement->getAttribute('height');
}
$this->_adjustPosition($height, $width);
$this->_appendRootElement('rect',
array('x' => $this->_leftOffset,
'y' => $this->_topOffset,
'width' => ($this->_leftOffset + $barcodeWidth - 1),
'height' => ($this->_topOffset + $barcodeHeight - 1),
'fill' => $imageBackgroundColor));
}
protected function _readRootElement()
{
if ($this->_resource !== null) {
$this->_rootElement = $this->_resource->documentElement;
}
}
/**
* Append a new DOMElement to the root element
*
* @param string $tagName
* @param array $attributes
* @param string $textContent
*/
protected function _appendRootElement($tagName, $attributes = array(), $textContent = null)
{
$newElement = $this->_createElement($tagName, $attributes, $textContent);
$this->_rootElement->appendChild($newElement);
}
/**
* Create DOMElement
*
* @param string $tagName
* @param array $attributes
* @param string $textContent
* @return DOMElement
*/
protected function _createElement($tagName, $attributes = array(), $textContent = null)
{
$element = $this->_resource->createElement($tagName);
foreach ($attributes as $k =>$v) {
$element->setAttribute($k, $v);
}
if ($textContent !== null) {
$element->appendChild(new DOMText((string) $textContent));
}
return $element;
}
/**
* Check barcode parameters
*
* @return void
*/
protected function _checkParams()
{
$this->_checkDimensions();
}
/**
* Check barcode dimensions
*
* @return void
*/
protected function _checkDimensions()
{
if ($this->_resource !== null) {
$this->_readRootElement();
$height = (float) $this->_rootElement->getAttribute('height');
if ($height < $this->_barcode->getHeight(true)) {
require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Barcode is define outside the image (height)'
);
}
} else {
if ($this->_userHeight) {
$height = $this->_barcode->getHeight(true);
if ($this->_userHeight < $height) {
require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(sprintf(
"Barcode is define outside the image (calculated: '%d', provided: '%d')",
$height,
$this->_userHeight
));
}
}
}
if ($this->_resource !== null) {
$this->_readRootElement();
$width = $this->_rootElement->getAttribute('width');
if ($width < $this->_barcode->getWidth(true)) {
require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(
'Barcode is define outside the image (width)'
);
}
} else {
if ($this->_userWidth) {
$width = (float) $this->_barcode->getWidth(true);
if ($this->_userWidth < $width) {
require_once 'Zend/Barcode/Renderer/Exception.php';
throw new Zend_Barcode_Renderer_Exception(sprintf(
"Barcode is define outside the image (calculated: '%d', provided: '%d')",
$width,
$this->_userWidth
));
}
}
}
}
/**
* Draw the barcode in the rendering resource
* @return mixed
*/
public function draw()
{
parent::draw();
$this->_resource->appendChild($this->_rootElement);
return $this->_resource;
}
/**
* Draw and render the barcode with correct headers
*
* @return mixed
*/
public function render()
{
$this->draw();
header("Content-Type: image/svg+xml");
echo $this->_resource->saveXML();
}
/**
* Draw a polygon in the svg resource
*
* @param array $points
* @param integer $color
* @param boolean $filled
*/
protected function _drawPolygon($points, $color, $filled = true)
{
$color = 'rgb(' . implode(', ', array(($color & 0xFF0000) >> 16,
($color & 0x00FF00) >> 8,
($color & 0x0000FF))) . ')';
$orientation = $this->getBarcode()->getOrientation();
$newPoints = array(
$points[0][0] + $this->_leftOffset,
$points[0][1] + $this->_topOffset,
$points[1][0] + $this->_leftOffset,
$points[1][1] + $this->_topOffset,
$points[2][0] + $this->_leftOffset + cos(-$orientation),
$points[2][1] + $this->_topOffset - sin($orientation),
$points[3][0] + $this->_leftOffset + cos(-$orientation),
$points[3][1] + $this->_topOffset - sin($orientation),
);
$newPoints = implode(' ', $newPoints);
$attributes['points'] = $newPoints;
$attributes['fill'] = $color;
$this->_appendRootElement('polygon', $attributes);
}
/**
* Draw a polygon in the svg resource
*
* @param string $text
* @param float $size
* @param array $position
* @param string $font
* @param integer $color
* @param string $alignment
* @param float $orientation
*/
protected function _drawText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0)
{
$color = 'rgb(' . implode(', ', array(($color & 0xFF0000) >> 16,
($color & 0x00FF00) >> 8,
($color & 0x0000FF))) . ')';
$attributes['x'] = $position[0] + $this->_leftOffset;
$attributes['y'] = $position[1] + $this->_topOffset;
//$attributes['font-family'] = $font;
$attributes['color'] = $color;
$attributes['font-size'] = $size * 1.2;
switch ($alignment) {
case 'left':
$textAnchor = 'start';
break;
case 'right':
$textAnchor = 'end';
break;
case 'center':
default:
$textAnchor = 'middle';
}
$attributes['style'] = 'text-anchor: ' . $textAnchor;
$attributes['transform'] = 'rotate('
. (- $orientation)
. ', '
. ($position[0] + $this->_leftOffset)
. ', ' . ($position[1] + $this->_topOffset)
. ')';
$this->_appendRootElement('text', $attributes, $text);
}
}
| {
"pile_set_name": "Github"
} |
{
"ProviderId": "Microsoft.ApplicationInsights.ConnectedService.ConnectedServiceProvider",
"Version": "4.0.0.0",
"GettingStartedDocument": {
"Uri": "http://go.microsoft.com/fwlink/?LinkID=613413"
}
} | {
"pile_set_name": "Github"
} |
#include "qwindowsystem_qws.h"
| {
"pile_set_name": "Github"
} |
html, body {
height: 100%;
padding: 0;
margin: 0;
font-size: 12px;
}
#pano-outer {
position: relative;
top: 0;
left: 0;
min-width: 100%;
min-height: 100%;
}
#pano {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
} | {
"pile_set_name": "Github"
} |
<!-- SPDX-License-Identifier: Apache-2.0 -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../_static/css/styles.css">
</head>
<body>
<div class="container">
<input type="checkbox" id="hl_tx_count_per_hour">
<label for="hl_tx_count_per_hour">
<img src="../_static/images/hl_tx_count_per_hour.png">
</label>
</div>
<br>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* OCI specific temptables store. Needed because temporary tables
* in Oracle are global (to all sessions), so we need to rename them
* on the fly in order to get local (different for each session) table names.
* Also used to be able to retrieve temp table names included in the get_tables()
* method of the DB.
*
* @package core_dml
* @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__.'/moodle_temptables.php');
class oci_native_moodle_temptables extends moodle_temptables {
/** @var int To store unique_session_id. Needed for temp tables unique naming (upto 24cc) */
protected $unique_session_id; //
/** @var int To get incrementally different temptable names on each add_temptable() request */
protected $counter;
/**
* Creates new moodle_temptables instance
* @param object moodle_database instance
*/
public function __construct($mdb, $unique_session_id) {
$this->unique_session_id = $unique_session_id;
$this->counter = 1;
parent::__construct($mdb);
}
/**
* Add one temptable to the store.
*
* Overridden because OCI only support global temptables, so we need to change completely the name, based
* in unique session identifier, to get local-like temp tables support
* tables before the prefix.
*
* Given one moodle temptable name (without prefix), add it to the store, with the
* key being the original moodle name and the value being the real db temptable name
* already prefixed
*
* Override and use this *only* if the database requires modification in the table name.
*
* @param string $tablename name without prefix of the table created as temptable
*/
public function add_temptable($tablename) {
// TODO: throw exception if exists: if ($this->is_temptable...
$this->temptables[$tablename] = $this->prefix . $this->unique_session_id . $this->counter;
$this->counter++;
}
}
| {
"pile_set_name": "Github"
} |
/*
* 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.
*/
/*!
* Copyright (c) 2015 by Contributors
* \file crop-inl.h
* \brief
* \author Wei Wu
*/
#ifndef MXNET_OPERATOR_CROP_INL_H_
#define MXNET_OPERATOR_CROP_INL_H_
#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <mxnet/operator.h>
#include <cstring>
#include <map>
#include <string>
#include <vector>
#include <utility>
#include "./operator_common.h"
namespace mxnet {
namespace op {
namespace crop_enum {
enum CropOpInputs {kData, kCropLike};
enum CropOpOutputs {kOut};
} // namespace crop_enum
struct CropParam : public dmlc::Parameter<CropParam> {
int num_args;
TShape offset;
TShape h_w;
bool center_crop;
DMLC_DECLARE_PARAMETER(CropParam) {
DMLC_DECLARE_FIELD(num_args).set_range(1, 3)
.describe("Number of inputs for crop, if equals one, then we will use the h_w"
"for crop height and width, else if equals two, then we will use the height"
"and width of the second input symbol, we name crop_like here");
int shape[] = {0, 0};
DMLC_DECLARE_FIELD(offset).set_default(TShape(shape, shape + 2))
.describe("crop offset coordinate: (y, x)");
DMLC_DECLARE_FIELD(h_w).set_default(TShape(shape, shape + 2))
.describe("crop height and width: (h, w)");
DMLC_DECLARE_FIELD(center_crop).set_default(false)
.describe("If set to true, then it will use be the center_crop,"
"or it will crop using the shape of crop_like");
}
}; // struct CropParam
template<typename xpu>
class CropOp : public Operator {
public:
explicit CropOp(CropParam param) {
this->param_ = param;
}
virtual void Forward(const OpContext &ctx,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &out_data,
const std::vector<TBlob> &aux_args) {
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(static_cast<int>(in_data.size()), param_.num_args);
CHECK_EQ(out_data.size(), 1U);
CHECK_EQ(req[crop_enum::kOut], kWriteTo);
Stream<xpu> *s = ctx.get_stream<xpu>();
Tensor<xpu, 4> data = in_data[crop_enum::kData].get<xpu, 4, real_t>(s);
Tensor<xpu, 4> out = out_data[crop_enum::kOut].get<xpu, 4, real_t>(s);
offset_hw_ = InferCropOfferset(data.shape_, out.shape_);
out = crop(data, Shape2(out.size(2), out.size(3)), offset_hw_[0], offset_hw_[1]);
}
// because the crop_like input is only used with it's shape, so we should be
// careful setting its backwrd grad value to zeros, so that it will not hurt
// the connection of crop_like.
virtual void Backward(const OpContext &ctx,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &in_data,
const std::vector<TBlob> &out_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &in_grad,
const std::vector<TBlob> &aux_states) {
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(in_grad.size(), static_cast<size_t>(param_.num_args)) << in_grad.size();
CHECK_EQ(out_grad.size(), 1U) << out_grad.size();
Stream<xpu> *s = ctx.get_stream<xpu>();
Tensor<xpu, 4> grad = out_grad[crop_enum::kOut].get<xpu, 4, real_t>(s);
Tensor<xpu, 4> gdata = in_grad[crop_enum::kData].get<xpu, 4, real_t>(s);
if (param_.num_args > 1) {
// here backward grad is set to zero for crop_like
// however, this should only be done when num_args > 1, i.e., crop_like exists
Tensor<xpu, 4> gcrop_like = in_grad[crop_enum::kCropLike].get<xpu, 4, real_t>(s);
gcrop_like = (real_t)0.0f;
}
offset_hw_ = InferCropOfferset(gdata.shape_, grad.shape_);
gdata = (real_t)0.0f;
slice<3>(slice<2>(gdata, offset_hw_[0], offset_hw_[0]+grad.size(2)),
offset_hw_[1], offset_hw_[1]+grad.size(3)) = grad;
}
private:
CropParam param_;
std::vector<int> offset_hw_;
std::vector<int> InferCropOfferset(const mshadow::Shape<4> &data_shape,
const mshadow::Shape<4> &out_shape) {
std::vector<int> offset_hw;
CHECK_GE(data_shape[2], out_shape[2]) <<
"data_shape'height should be larger than that of out_shape";
CHECK_GE(data_shape[3], out_shape[3]) <<
"data_shape'weight should be larger than that of out_shape";
if (param_.center_crop) {
offset_hw.push_back(static_cast<int>((data_shape[2]-out_shape[2])/2));
offset_hw.push_back(static_cast<int>((data_shape[3]-out_shape[3])/2));
} else {
CHECK_GE(static_cast<int>(param_.offset[0]), 0) <<
"offset[0] should be larger than 0";
CHECK_LE(param_.offset[0], data_shape[2]-out_shape[2]) <<
"offset[0] should be less than the residual space of height";
CHECK_GE(static_cast<int>(param_.offset[1]), 0) <<
"offset[1] should be larger than 0";
CHECK_LE(param_.offset[1], data_shape[3]-out_shape[3]) <<
"offset[1] should be less than the residual space of width";
offset_hw.push_back(static_cast<int>(param_.offset[0]));
offset_hw.push_back(static_cast<int>(param_.offset[1]));
}
return offset_hw;
}
}; // class CropOp
template<typename xpu>
Operator *CreateOp(CropParam param);
#if DMLC_USE_CXX11
class CropProp : public OperatorProperty {
public:
void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) override {
param_.Init(kwargs);
}
std::map<std::string, std::string> GetParams() const override {
return param_.__DICT__();
}
std::vector<std::string> ListArguments() const override {
// return {"data", "crop_like"};
std::vector<std::string> ret;
for (int i = 0; i < param_.num_args; ++i) {
ret.push_back(std::string("arg") + std::to_string(i));
}
return ret;
}
bool InferShape(std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape,
std::vector<TShape> *aux_shape) const override {
using namespace mshadow;
CHECK_EQ(in_shape->size(), static_cast<size_t>(param_.num_args));
TShape data_shape = in_shape->at(crop_enum::kData);
if (data_shape.ndim() == 0) return false;
CHECK_EQ(data_shape.ndim(), 4U) << \
"Input data should be 4D in batch-num_filter-y-x";
std::vector<int> crop_shape;
if (param_.num_args == 1) {
CHECK_GE(static_cast<int>(param_.h_w[0]), 1) <<
"the crop height(h_w[0]) should be larger than 1";
CHECK_LE(static_cast<int>(param_.h_w[0]), static_cast<int>(data_shape[2])) <<
"the crop height(h_w[0]) should be less than the input data's height";
CHECK_GE(static_cast<int>(param_.h_w[1]), 1) <<
"the crop width(h_w[1]) should be larger than 1";
CHECK_LE(static_cast<int>(param_.h_w[1]), static_cast<int>(data_shape[3])) <<
"the crop width(h_w[1]) should be less than the input data's width";
crop_shape.push_back(param_.h_w[0]);
crop_shape.push_back(param_.h_w[1]);
} else if (param_.num_args == 2) {
TShape crop_like_shape = in_shape->at(crop_enum::kCropLike);
crop_shape.push_back(crop_like_shape[2]);
crop_shape.push_back(crop_like_shape[3]);
}
if (crop_shape.size() == 0) return false;
CHECK_EQ(crop_shape.size(), 2U) << \
"Input crop_like should be 2D in height-width";
out_shape->clear();
data_shape[2] = crop_shape[0];
data_shape[3] = crop_shape[1];
out_shape->push_back(data_shape);
return true;
}
OperatorProperty* Copy() const override {
auto ptr = new CropProp();
ptr->param_ = param_;
return ptr;
}
std::string TypeString() const override {
return "Crop";
}
std::vector<int> DeclareBackwardDependency(
const std::vector<int> &out_grad,
const std::vector<int> &in_data,
const std::vector<int> &out_data) const override {
return out_grad;
}
Operator* CreateOperator(Context ctx) const override;
private:
CropParam param_;
}; // class CropProp
#endif // DMLC_USE_CXX11
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_CROP_INL_H_
| {
"pile_set_name": "Github"
} |
Drop table O_Customer;
CREATE TABLE O_Customer (
c_id integer not null,
c_phone char(16)
);
| {
"pile_set_name": "Github"
} |
module Def where
what :: forall a b. a -> b -> a
what a _ = a
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* 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 org.hsqldb.persist;
import java.io.EOFException;
import org.hsqldb.Database;
import org.hsqldb.Error;
import org.hsqldb.ErrorCode;
import org.hsqldb.Session;
import org.hsqldb.lib.IntKeyHashMap;
import org.hsqldb.lib.SimpleLog;
import org.hsqldb.lib.StopWatch;
import org.hsqldb.result.Result;
import org.hsqldb.scriptio.ScriptReaderBase;
/**
* Restores the state of a Database instance from an SQL log file. <p>
*
* If there is an error, processing stops at that line and the message is
* logged to the application log. If memory runs out, an exception is thrown.
*
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.7.2
*/
public class ScriptRunner {
/**
* This is used to read the *.log file and manage any necessary
* transaction rollback.
*/
public static void runScript(Database database, String logFilename,
int logType) {
IntKeyHashMap sessionMap = new IntKeyHashMap();
Session current = null;
int currentId = 0;
database.setReferentialIntegrity(false);
ScriptReaderBase scr = null;
String statement;
int statementType;
try {
StopWatch sw = new StopWatch();
scr = ScriptReaderBase.newScriptReader(database, logFilename,
logType);
while (scr.readLoggedStatement(current)) {
int sessionId = scr.getSessionNumber();
if (current == null || currentId != sessionId) {
currentId = sessionId;
current = (Session) sessionMap.get(currentId);
if (current == null) {
current =
database.getSessionManager().newSession(database,
database.getUserManager().getSysUser(), false,
true, 0);
sessionMap.put(currentId, current);
}
}
if (current.isClosed()) {
sessionMap.remove(currentId);
continue;
}
Result result = null;
statementType = scr.getStatementType();
switch (statementType) {
case ScriptReaderBase.ANY_STATEMENT :
statement = scr.getLoggedStatement();
result = current.executeDirectStatement(statement);
if (result != null && result.isError()) {
if (result.getException() != null) {
throw result.getException();
}
throw Error.error(result);
}
break;
case ScriptReaderBase.SEQUENCE_STATEMENT :
scr.getCurrentSequence().reset(scr.getSequenceValue());
break;
case ScriptReaderBase.COMMIT_STATEMENT :
current.commit(false);
break;
case ScriptReaderBase.INSERT_STATEMENT : {
current.beginAction(null);
Object[] data = scr.getData();
scr.getCurrentTable().insertNoCheckFromLog(current,
data);
current.endAction(Result.updateOneResult);
break;
}
case ScriptReaderBase.DELETE_STATEMENT : {
current.beginAction(null);
Object[] data = scr.getData();
scr.getCurrentTable().deleteNoCheckFromLog(current,
data);
current.endAction(Result.updateOneResult);
break;
}
case ScriptReaderBase.SET_SCHEMA_STATEMENT : {
current.setSchema(scr.getCurrentSchema());
}
}
if (current.isClosed()) {
sessionMap.remove(currentId);
}
}
} catch (Throwable e) {
String message;
// catch out-of-memory errors and terminate
if (e instanceof EOFException) {
// end of file - normal end
} else if (e instanceof OutOfMemoryError) {
message = "out of memory processing " + logFilename
+ " line: " + scr.getLineNumber();
database.logger.appLog.logContext(SimpleLog.LOG_ERROR,
message);
throw Error.error(ErrorCode.OUT_OF_MEMORY);
} else {
// stop processing on bad log line
message = logFilename + " line: " + scr.getLineNumber() + " "
+ e.toString();
database.logger.appLog.logContext(SimpleLog.LOG_ERROR,
message);
}
} finally {
if (scr != null) {
scr.close();
}
database.getSessionManager().closeAllSessions();
database.setReferentialIntegrity(true);
}
}
}
| {
"pile_set_name": "Github"
} |
#import "WebServerIPhoneAppDelegate.h"
#import "WebServerIPhoneViewController.h"
#import <CocoaLumberjack/CocoaLumberjack.h>
#import "HTTPServer.h"
#import "MyHTTPConnection.h"
// Log levels: off, error, warn, info, verbose
static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
@implementation WebServerIPhoneAppDelegate
@synthesize fileLogger;
@synthesize window;
@synthesize viewController;
- (void)setupWebServer
{
// Create server using our custom MyHTTPServer class
httpServer = [[HTTPServer alloc] init];
// Configure it to use our connection class
[httpServer setConnectionClass:[MyHTTPConnection class]];
// Set the bonjour type of the http server.
// This allows the server to broadcast itself via bonjour.
// You can automatically discover the service in Safari's bonjour bookmarks section.
[httpServer setType:@"_http._tcp."];
// Normally there is no need to run our server on any specific port.
// Technologies like Bonjour allow clients to dynamically discover the server's port at runtime.
// However, for testing purposes, it may be much easier if the port doesn't change on every build-and-go.
[httpServer setPort:12345];
// Serve files from our embedded Web folder
NSString *webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Web"];
[httpServer setDocumentRoot:webPath];
// Start the server (and check for problems)
NSError *error = nil;
if (![httpServer start:&error])
{
DDLogError(@"Error starting HTTP Server: %@", error);
}
}
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// Direct log messages to the console.
// The log messages will look exactly like a normal NSLog statement.
//
// This is something we may not want to do in a shipping version of the application.
// [DDLog addLogger:[DDASLLogger sharedInstance]];
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// We also want to direct our log messages to a file.
// So we're going to setup file logging.
//
// We start by creating a file logger.
fileLogger = [[DDFileLogger alloc] init];
// Configure some sensible defaults for an iPhone application.
//
// Roll the file when it gets to be 512 KB or 24 Hours old (whichever comes first).
//
// Also, only keep up to 4 archived log files around at any given time.
// We don't want to take up too much disk space.
fileLogger.maximumFileSize = 1024 * 512; // 512 KB
fileLogger.rollingFrequency = 60 * 60 * 24; // 24 Hours
fileLogger.logFileManager.maximumNumberOfLogFiles = 4;
// Add our file logger to the logging system.
[DDLog addLogger:fileLogger];
// Now setup our web server.
//
// This will allow us to connect to the device from our web browser.
// We can then view log files, or view logging in real time as the application runs.
[self setupWebServer];
// This application, by itself, doesn't actually do anthing.
// It is just a proof of concept or demonstration.
// But we want to be able to see the application logging something.
// So we setup a timer to spit out a silly log message.
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(writeLogMessages:)
userInfo:nil
repeats:YES];
[window setRootViewController:viewController];
[window makeKeyAndVisible];
}
- (void)writeLogMessages:(NSTimer *)aTimer
{
// Log a message in verbose mode.
//
// Want to disable this log message?
// Try setting the log level (at the top of this file) to DDLogLevelWarning.
// After doing this you can leave the log statement below.
// It will automatically be compiled out (when compiling in release mode where compiler optimizations are enabled).
DDLogVerbose(@"I like cheese");
}
@end
| {
"pile_set_name": "Github"
} |
const app = require('../../../dadi/lib/')
const config = require('../../../config')
const help = require('../help')
const request = require('supertest')
const connectionString =
'http://' + config.get('server.host') + ':' + config.get('server.port')
let bearerToken
describe('Mixed Field', () => {
beforeEach(done => {
help.dropDatabase('library', 'misc', err => {
app.start(() => {
help
.createSchemas([
{
version: 'v1',
property: 'library',
name: 'misc',
fields: {
boolean: {
type: 'Boolean'
},
string: {
type: 'String'
},
mixed: {
type: 'Mixed'
},
object: {
type: 'Object'
},
multiReference: {
type: 'Reference'
}
},
settings: {
cache: false,
authenticate: false,
count: 40,
sort: 'string',
sortOrder: 1,
storeRevisions: false
}
}
])
.then(() => {
help.getBearerToken(function(err, token) {
bearerToken = token
done(err)
})
})
})
})
})
afterEach(done => {
help.dropSchemas().then(() => {
app.stop(done)
})
})
describe('String values', () => {
it('should create and retrieve', done => {
const client = request(connectionString)
const value = 'DADI #ftw'
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
res.body.results[0].mixed.should.eql(value)
client
.get(`/library/misc/${res.body.results[0]._id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
res.body.results[0].mixed.should.eql(value)
done()
})
})
})
it('should update', done => {
const client = request(connectionString)
const value = 'DADI #ftw'
const newValue = 'DADI #superftw'
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
const id = res.body.results[0]._id
res.body.results[0].mixed.should.eql(value)
client
.put(`/library/misc/${id}`)
.send({mixed: newValue})
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
client
.get(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
res.body.results[0].mixed.should.eql(newValue)
done()
})
})
})
})
it('should delete', done => {
const client = request(connectionString)
const value = 'DADI #ftw'
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
const id = res.body.results[0]._id
res.body.results[0].mixed.should.eql(value)
client
.delete(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
client
.get(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(404)
.end(done)
})
})
})
})
describe('Number values', () => {
it('should create and retrieve', done => {
const client = request(connectionString)
const value = 1337
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
res.body.results[0].mixed.should.eql(value)
client
.get(`/library/misc/${res.body.results[0]._id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
res.body.results[0].mixed.should.eql(value)
done()
})
})
})
it('should update', done => {
const client = request(connectionString)
const value = 1337
const newValue = 'DADI #superftw'
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
const id = res.body.results[0]._id
res.body.results[0].mixed.should.eql(value)
client
.put(`/library/misc/${id}`)
.send({mixed: newValue})
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
client
.get(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
res.body.results[0].mixed.should.eql(newValue)
done()
})
})
})
})
it('should delete', done => {
const client = request(connectionString)
const value = 1337
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
const id = res.body.results[0]._id
res.body.results[0].mixed.should.eql(value)
client
.delete(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
client
.get(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(404)
.end(done)
})
})
})
})
describe('Object values', () => {
it('should create and retrieve', done => {
const client = request(connectionString)
const value = {
name: 'GrandDADI',
child: {
name: 'DADI',
child: {
name: 'Grandson'
}
}
}
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
res.body.results[0].mixed.should.eql(value)
client
.get(`/library/misc/${res.body.results[0]._id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
res.body.results[0].mixed.should.eql(value)
done()
})
})
})
it('should retrieve by nested keys', done => {
const client = request(connectionString)
const value = {
name: 'GrandDADI',
child: {
name: 'DADI',
child: {
name: 'Grandson'
}
}
}
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
res.body.results[0].mixed.should.eql(value)
client
.get(
`/library/misc?filter={"mixed.child.name":"${value.child.name}"}`
)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
res.body.results[0].mixed.should.eql(value)
done()
})
})
})
it('should update by id', done => {
const client = request(connectionString)
const value = {
name: 'GrandDADI',
child: {
name: 'DADI',
child: {
name: 'Grandson'
}
}
}
const newValue = {
name: 'GrandDADI',
child: {
name: 'DADI'
}
}
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
const id = res.body.results[0]._id
res.body.results[0].mixed.should.eql(value)
client
.put(`/library/misc/${id}`)
.send({mixed: newValue})
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
client
.get(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
res.body.results[0].mixed.should.eql(newValue)
done()
})
})
})
})
it('should update by query for nested key', done => {
const client = request(connectionString)
const value = {
name: 'GrandDADI',
child: {
name: 'DADI',
child: {
name: 'Grandson'
}
}
}
const newValue = {
name: 'GrandDADI',
child: {
name: 'DADI'
}
}
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
const id = res.body.results[0]._id
res.body.results[0].mixed.should.eql(value)
client
.put(`/library/misc`)
.send({
query: {
'mixed.child.name': value.child.name
},
update: {
mixed: newValue
}
})
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
client
.get(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
res.body.results[0].mixed.should.eql(newValue)
done()
})
})
})
})
it('should delete', done => {
const client = request(connectionString)
const value = {
name: 'GrandDADI',
child: {
name: 'DADI',
child: {
name: 'Grandson'
}
}
}
client
.post('/library/misc')
.set('Authorization', 'Bearer ' + bearerToken)
.send({mixed: value})
.expect(200)
.end((err, res) => {
if (err) return done(err)
const id = res.body.results[0]._id
res.body.results[0].mixed.should.eql(value)
client
.delete(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(200)
.end((err, res) => {
client
.get(`/library/misc/${id}`)
.set('Authorization', 'Bearer ' + bearerToken)
.expect(404)
.end(done)
})
})
})
})
})
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2017 TOSHIBA Digital Solutions Corporation
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Copyright (c) 2008, Yubin Lim([email protected]).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Purewell nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@file
@brief Definition of Utility of common configuration, data types, and exceptions
*/
#ifndef UTIL_TYPE_H_
#define UTIL_TYPE_H_
#ifndef UTIL_MINOR_MODULE_ENABLED
#define UTIL_MINOR_MODULE_ENABLED 0
#endif
#ifndef UTIL_FAILURE_SIMULATION_ENABLED
#define UTIL_FAILURE_SIMULATION_ENABLED 0
#endif
#define UTIL_STACK_TRACE_ENABLED
#if UTIL_FAILURE_SIMULATION_ENABLED || \
defined(UTIL_MEMORY_ALLOCATE_INITIALIZE) || \
defined(UTIL_DUMP_OPERATOR_DELETE)
#define UTIL_PLACEMENT_NEW_ENABLED
#endif
#if (defined(_MSC_VER) && defined(_M_X64)) || \
(defined(__GNUC__) && defined(__x86_64__))
#define UTIL_POINTER_SIZE 8
#else
#define UTIL_POINTER_SIZE 4
#endif
#if __cplusplus >= 201103L
#define UTIL_CXX11_SUPPORTED_EXACT 1
#else
#define UTIL_CXX11_SUPPORTED_EXACT 0
#endif
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || UTIL_CXX11_SUPPORTED_EXACT
#define UTIL_CXX11_SUPPORTED 1
#else
#define UTIL_CXX11_SUPPORTED 0
#endif
#if __cplusplus >= 201402L
#define UTIL_CXX14_SUPPORTED 1
#else
#define UTIL_CXX14_SUPPORTED 0
#endif
#if defined(_MSC_VER) && defined(_M_X64) && !defined(_WIN64)
#error 0
#endif
#if UTIL_CXX14_SUPPORTED && defined(__has_cpp_attribute)
#define UTIL_HAS_FEATURE_MACRO 1
#else
#define UTIL_HAS_FEATURE_MACRO 0
#endif
#if UTIL_CXX11_SUPPORTED_EXACT
#define UTIL_HAS_ATTRIBUTE_NORETURN 1
#elif defined(__GNUC__) && \
(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
#define UTIL_HAS_ATTRIBUTE_NORETURN 1
#else
#define UTIL_HAS_ATTRIBUTE_NORETURN 0
#endif
#if UTIL_HAS_FEATURE_MACRO
#if __has_cpp_attribute(maybe_unused) >= 201603L
#define UTIL_HAS_ATTRIBUTE_MAYBE_UNUSED 1
#else
#define UTIL_HAS_ATTRIBUTE_MAYBE_UNUSED 0
#endif
#else
#define UTIL_HAS_ATTRIBUTE_MAYBE_UNUSED 0
#endif
#if UTIL_HAS_FEATURE_MACRO
#if __has_cpp_attribute(nodiscard) >= 201603L
#define UTIL_HAS_ATTRIBUTE_NODISCARD 1
#else
#define UTIL_HAS_ATTRIBUTE_NODISCARD 0
#endif
#else
#define UTIL_HAS_ATTRIBUTE_NODISCARD 0
#endif
#ifdef _WIN32
/* #undef UTIL_HAVE_BLKCNT_T */
/* #undef UTIL_HAVE_BLKSIZE_T */
/* #undef UTIL_HAVE_CLOCKID_T */
/* #undef UTIL_HAVE_DEV_T */
/* #undef UTIL_HAVE_DIRENT_H */
/* #undef UTIL_HAVE_DLFCN_H */
/* #undef UTIL_HAVE_EPOLL_CTL */
/* #undef UTIL_HAVE_FCNTL */
/* #undef UTIL_HAVE_FCNTL_H */
/* #undef UTIL_HAVE_FSBLKCNT_T */
/* #undef UTIL_HAVE_FSTAT */
/* #undef UTIL_HAVE_FSTATVFS */
#define UTIL_HAVE_GETSYSTEMTIMEASFILETIME 1
/* #undef UTIL_HAVE_GETTIMEOFDAY */
/* #undef UTIL_HAVE_GID_T */
/* #undef UTIL_HAVE_INO_T */
#define UTIL_HAVE_INTPTR_T UTIL_POINTER_SIZE
/* #undef UTIL_HAVE_INTTYPE_H */
/* #undef UTIL_HAVE_IOCTL */
/* #undef UTIL_HAVE_IOCTLSOCKET */
/* #undef UTIL_HAVE_IOCTL_H */
/* #undef UTIL_HAVE_LONG_LONG_T */
/* #undef UTIL_HAVE_LSTAT */
/* #undef UTIL_HAVE_MODE_T */
/* #undef UTIL_HAVE_MQUEUE_H */
/* #undef UTIL_HAVE_NLINK_T */
/* #undef UTIL_HAVE_OFF_T */
/* #undef UTIL_HAVE_OPENDIR */
/* #undef UTIL_HAVE_POINTER_T */
/* #undef UTIL_HAVE_POLL */
/* #undef UTIL_HAVE_POLL_H */
/* #undef UTIL_HAVE_POSIX_BARRIER */
/* #undef UTIL_HAVE_POSIX_CONDITION */
/* #undef UTIL_HAVE_POSIX_MUTEX */
/* #undef UTIL_HAVE_POSIX_RWLOCK */
/* #undef UTIL_HAVE_POSIX_SPIN */
/* #undef UTIL_HAVE_POSIX_SPIN_TIMEDLOCK */
/* #undef UTIL_HAVE_PTHREAD_CONDATTR_GETCLOCK */
/* #undef UTIL_HAVE_PTHREAD_CONDATTR_SETCLOCK */
/* #undef UTIL_HAVE_RESTRICT */
/* #undef UTIL_HAVE_RESTRICT_CPP */
/* #undef UTIL_HAVE_SEMAPHORE_H */
/* #undef UTIL_HAVE_SIGINFO_T */
/* #undef UTIL_HAVE_SIGNAL_H */
/* #undef UTIL_HAVE_SIGSET_T */
#define UTIL_HAVE_SIZE_T UTIL_POINTER_SIZE
/* #undef UTIL_HAVE_SOCKADDR_STORAGE_T */
/* #undef UTIL_HAVE_SOCKADDR_UN_T */
#define UTIL_HAVE_SOCKLEN_T 1
/* #undef UTIL_HAVE_SSIZE_T */
/* #undef UTIL_HAVE_STAT */
/* #undef UTIL_HAVE_STATVFS */
/* #undef UTIL_HAVE_STATVFS_H */
/* #undef UTIL_HAVE_STATVFS_T */
/* #undef UTIL_HAVE_STAT_H */
/* #undef UTIL_HAVE_STAT_T */
#define UTIL_HAVE_STDDEF_H 1
/* #undef UTIL_HAVE_STDINT_H */
/* #undef UTIL_HAVE_STRCASECMP */
#define UTIL_HAVE_STRICMP 1
/* #undef UTIL_HAVE_SYS_DIRENT_H */
/* #undef UTIL_HAVE_SYS_EPOLL_H */
/* #undef UTIL_HAVE_SYS_IOCTL_H */
/* #undef UTIL_HAVE_SYS_MMAN_H */
/* #undef UTIL_HAVE_SYS_POLL_H */
/* #undef UTIL_HAVE_SYS_RESOURCE_H */
/* #undef UTIL_HAVE_SYS_SELECT_H */
/* #undef UTIL_HAVE_SYS_SIGNAL_H */
/* #undef UTIL_HAVE_SYS_STATVFS_H */
/* #undef UTIL_HAVE_SYS_STAT_H */
/* #undef UTIL_HAVE_SYS_TIME_H */
/* #undef UTIL_HAVE_SYS_UN_H */
#define UTIL_HAVE_TIME_H 1
#define UTIL_HAVE_TIMEVAL_T 1
/* #undef UTIL_HAVE_UID_T */
/* #undef UTIL_HAVE_UINT8_T */
/* #undef UTIL_HAVE_UNISTD_H */
#define UTIL_HAVE_VSNPRINTF 1
/* #undef UTIL_HAVE___BLKSIZE_T */
/* #undef UTIL_HAVE___INT64_T */
/* #undef UTIL_HAVE_MEM_STAT_ST_BLKSIZE */
/* #undef UTIL_HAVE_MEM_STAT_ST_BLOCKS */
#else
#define UTIL_HAVE_BLKCNT_T 4
/* #undef UTIL_HAVE_BLKSIZE_T */
#define UTIL_HAVE_CLOCKID_T 4
#define UTIL_HAVE_DEV_T 8
#define UTIL_HAVE_DIRENT_H 1
#define UTIL_HAVE_DLFCN_H 1
#define UTIL_HAVE_EPOLL_CTL 1
#define UTIL_HAVE_FCNTL 1
#define UTIL_HAVE_FCNTL_H 1
#define UTIL_HAVE_FSBLKCNT_T 4
#define UTIL_HAVE_FSTAT 1
#define UTIL_HAVE_FSTATVFS 1
/* #undef UTIL_HAVE_GETSYSTEMTIMEASFILETIME */
#define UTIL_HAVE_GETTIMEOFDAY 1
#define UTIL_HAVE_GID_T 4
#define UTIL_HAVE_INO_T 4
#define UTIL_HAVE_INTPTR_T 4
/* #undef UTIL_HAVE_INTTYPE_H */
#define UTIL_HAVE_IOCTL 1
/* #undef UTIL_HAVE_IOCTLSOCKET */
/* #undef UTIL_HAVE_IOCTL_H */
#define UTIL_HAVE_LONG_LONG_T 8
#define UTIL_HAVE_LSTAT 1
#define UTIL_HAVE_MODE_T 4
#define UTIL_HAVE_MQUEUE_H 1
#define UTIL_HAVE_NLINK_T 4
#define UTIL_HAVE_OFF_T 4
#define UTIL_HAVE_OPENDIR 1
#define UTIL_HAVE_POINTER_T UTIL_POINTER_SIZE
#define UTIL_HAVE_POLL 1
#define UTIL_HAVE_POLL_H 1
#define UTIL_HAVE_POSIX_BARRIER 1
#define UTIL_HAVE_POSIX_CONDITION 1
#define UTIL_HAVE_POSIX_MUTEX 1
#define UTIL_HAVE_POSIX_RWLOCK 1
#define UTIL_HAVE_POSIX_SPIN 1
/* #undef UTIL_HAVE_POSIX_SPIN_TIMEDLOCK */
#define UTIL_HAVE_PTHREAD_CONDATTR_GETCLOCK 1
#define UTIL_HAVE_PTHREAD_CONDATTR_SETCLOCK 1
/* #undef UTIL_HAVE_RESTRICT */
#define UTIL_HAVE_RESTRICT_CPP 4
#define UTIL_HAVE_SEMAPHORE_H 1
#define UTIL_HAVE_SIGINFO_T 128
#define UTIL_HAVE_SIGNAL_H 1
#define UTIL_HAVE_SIGSET_T 128
#define UTIL_HAVE_SIZE_T UTIL_POINTER_SIZE
#define UTIL_HAVE_SOCKADDR_STORAGE_T 128
#define UTIL_HAVE_SOCKADDR_UN_T 110
#define UTIL_HAVE_SOCKLEN_T 4
#define UTIL_HAVE_SSIZE_T UTIL_POINTER_SIZE
#define UTIL_HAVE_STAT 1
#define UTIL_HAVE_STATVFS 1
/* #undef UTIL_HAVE_STATVFS_H */
#define UTIL_HAVE_STATVFS_T 72
/* #undef UTIL_HAVE_STAT_H */
#define UTIL_HAVE_STAT_T 88
#define UTIL_HAVE_STDDEF_H 1
#define UTIL_HAVE_STDINT_H 1
#define UTIL_HAVE_STRCASECMP 1
/* #undef UTIL_HAVE_STRICMP */
/* #undef UTIL_HAVE_SYS_DIRENT_H */
#define UTIL_HAVE_SYS_EPOLL_H 1
#define UTIL_HAVE_SYS_IOCTL_H 1
#define UTIL_HAVE_SYS_MMAN_H 1
#define UTIL_HAVE_SYS_POLL_H 1
#define UTIL_HAVE_SYS_RESOURCE_H 1
#define UTIL_HAVE_SYS_SELECT_H 1
#define UTIL_HAVE_SYS_SIGNAL_H 1
#define UTIL_HAVE_SYS_STATVFS_H 1
#define UTIL_HAVE_SYS_STAT_H 1
#define UTIL_HAVE_SYS_TIME_H 1
#define UTIL_HAVE_SYS_UN_H 1
#define UTIL_HAVE_TIME_H 1
#define UTIL_HAVE_TIMEVAL_T 8
#define UTIL_HAVE_UID_T 4
#define UTIL_HAVE_UINT8_T 1
#define UTIL_HAVE_UNISTD_H 1
#define UTIL_HAVE_VSNPRINTF 1
#define UTIL_HAVE___BLKSIZE_T 4
/* #undef UTIL_HAVE___INT64_T */
#define UTIL_HAVE_MEM_STAT_ST_BLKSIZE 1
#define UTIL_HAVE_MEM_STAT_ST_BLOCKS 1
#endif
#ifndef _WIN32
#ifdef __off_t_defined
#error "This header must be included before off_t declaration"
#endif
#define _FILE_OFFSET_BITS 64
#define LARGEFILE_SOURCE
#define LARGE_FILES
#endif
#define __STDC_CONSTANT_MACROS
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#if UTIL_CXX11_SUPPORTED
#include <cstdint>
#else
#ifdef _MSC_STDINT_H_
#error "Do not include stdint.h before this header is included"
#endif
#if defined(_MSC_VER) && (_MSC_VER <= 1500)
#include "util/stdint/stdint.h"
#else
#include <stdint.h>
#endif
#endif
#ifndef UINT64_MAX
#error "Integer limit macros are not defined"
#endif
#ifndef UINT64_C
#error "Integer constant macros are not defined"
#endif
#include <exception>
#include <sstream>
#ifndef _WIN32
#include <sys/types.h>
#endif
#ifdef UTIL_HAVE_STDDEF_H
#include <stddef.h>
#endif
#ifndef UTIL_HAVE_INTPTR_T
# if ( UTIL_HAVE_POINTER_T == 4 )
typedef int32_t intptr_t;
# elif ( UTIL_HAVE_POINTER_T == 8 )
typedef int64_t intptr_t;
# else
# error "Unknown pointer size"
# endif
#endif
#ifndef UTIL_HAVE_SSIZE_T
# if ( UTIL_HAVE_SIZE_T == 4 )
typedef int32_t ssize_t;
# elif ( UTIL_HAVE_SIZE_T == 8 )
typedef int64_t ssize_t;
# else
# error "Unknown size_t size"
# endif
#endif
#ifndef UTIL_UTF8_CHAR_DEFINED
typedef char char8_t;
#define UTIL_UTF8_CHAR_DEFINED
#endif
#ifndef UTIL_UTF8_STRING_DEFINED
typedef std::string u8string;
#define UTIL_UTF8_STRING_DEFINED
#endif
#if defined(__GNUC__) && !UTIL_CXX11_SUPPORTED || \
defined(_MSC_VER) && !( \
defined(_HAS_CHAR16_T_LANGUAGE_SUPPORT) && \
_HAS_CHAR16_T_LANGUAGE_SUPPORT ) && \
!defined(_CHAR16T)
#ifdef __GNUC__
typedef uint16_t char16_t;
#else
#define _CHAR16T
typedef wchar_t char16_t;
#endif
typedef uint32_t char32_t;
#endif
namespace util {
int stricmp(const char *x, const char *y);
typedef std::basic_string< char8_t, std::char_traits<char8_t> > NormalString;
}
#if UTIL_CXX11_SUPPORTED
#define UTIL_NOEXCEPT noexcept
#else
#define UTIL_NOEXCEPT throw()
#endif
#if UTIL_CXX11_SUPPORTED
#define UTIL_NULLPTR nullptr
#else
#define UTIL_NULLPTR NULL
#endif
#ifdef _MSC_VER
#define UTIL_FORCEINLINE __forceinline
#else
#define UTIL_FORCEINLINE inline
#endif
#ifdef _MSC_VER
#define UTIL_NORETURN(func) __declspec(noreturn) func
#elif defined(__GNUC__)
#define UTIL_NORETURN(func) func __attribute__((noreturn))
#else
#error 0
#endif
namespace util {
typedef const int UTIL_FLAG_TYPE;
#if !defined(UTIL_HAVE_OFF_T)
typedef uint64_t off_t;
#endif
#if !defined(UTIL_HAVE_DEV_T)
typedef size_t dev_t;
#endif
#if !defined(UTIL_HAVE_INO_T)
typedef size_t ino_t;
#endif
#if !defined(UTIL_HAVE_MODE_T)
typedef size_t mode_t;
#endif
#if !defined(UTIL_HAVE_NLINK_T)
typedef size_t nlink_t;
#endif
#if !defined(UTIL_HAVE_UID_T)
typedef size_t uid_t;
#endif
#if !defined(UTIL_HAVE_GID_T)
typedef size_t gid_t;
#endif
#if !defined(UTIL_HAVE_BLKSIZE_T)
#if defined (__USE_UNIX98) && !defined (__blksize_t_defined)
typedef __blksize_t blksize_t;
#elif defined(UTIL_HAVE___BLKSIZE_T)
typedef __blksize_t blksize_t;
#else
typedef size_t blksize_t;
#endif
#endif
#if !defined(UTIL_HAVE_BLKCNT_T)
typedef size_t blkcnt_t;
#endif
#if !defined(UTIL_HAVE_FSBLKCNT_T)
typedef size_t fsblkcnt_t;
#endif
}
const int32_t ERROR_UNDEF = 0;
namespace util {
#define UTIL_EXCEPTION_CONSTRUCTOR_ARGS_DECL \
const util::Exception::NamedErrorCode &namedErrorCode = \
util::Exception::NamedErrorCode(), \
const char8_t *message = NULL, \
const util::Exception::SourceSymbolChar *fileNameLiteral = NULL, \
const util::Exception::SourceSymbolChar *functionNameLiteral = NULL, \
int32_t lineNumber = 0, \
const std::exception *causeInHandling = NULL, \
const char8_t *typeNameLiteral = NULL, \
util::Exception::StackTraceMode stackTraceMode = \
util::Exception::STACK_TRACE_NONE, \
util::Exception::DuplicatedLiteralFlags literalFlags = \
util::Exception::LITERAL_NORMAL
#define UTIL_EXCEPTION_CONSTRUCTOR_ARGS_LIST \
const util::Exception::NamedErrorCode &namedErrorCode, \
const char8_t *message, \
const util::Exception::SourceSymbolChar *fileNameLiteral, \
const util::Exception::SourceSymbolChar *functionNameLiteral, \
int32_t lineNumber, \
const std::exception *causeInHandling, \
const char8_t *typeNameLiteral, \
util::Exception::StackTraceMode stackTraceMode, \
util::Exception::DuplicatedLiteralFlags literalFlags
#define UTIL_EXCEPTION_CONSTRUCTOR_ARGS_SET \
namedErrorCode, \
message, \
fileNameLiteral, \
functionNameLiteral, \
lineNumber, \
causeInHandling, \
typeNameLiteral, \
stackTraceMode, \
literalFlags
/*!
@brief Basic exception handling error messages and place caused the error.
*/
class Exception : public std::exception {
friend class ExceptionInitializer;
public:
typedef char8_t SourceSymbolChar;
typedef uint8_t DuplicatedLiteralFlags;
class Field;
template<typename Alloc> struct NoThrowString;
struct NamedErrorCode {
public:
NamedErrorCode(
int32_t code = 0,
const SourceSymbolChar *nameLiteral = NULL) throw();
bool isEmpty() const throw() { return code_ == 0; }
int32_t getCode() const throw() { return code_; }
const SourceSymbolChar* getName() const throw() { return name_; }
private:
int32_t code_;
const SourceSymbolChar *name_;
};
enum StackTraceMode {
STACK_TRACE_NONE,
STACK_TRACE_TOP
};
enum FieldType {
FIELD_ERROR_CODE,
FIELD_ERROR_CODE_NAME,
FIELD_MESSAGE,
FIELD_FILE_NAME,
FIELD_FUNCTION_NAME,
FIELD_LINE_NUMBER,
FIELD_STACK_TRACE,
FIELD_TYPE_NAME
};
static const DuplicatedLiteralFlags LITERAL_NORMAL;
static const DuplicatedLiteralFlags LITERAL_ALL_DUPLICATED;
explicit Exception(UTIL_EXCEPTION_CONSTRUCTOR_ARGS_DECL) throw();
virtual ~Exception() throw();
Exception(const Exception &another) throw();
Exception& operator=(const Exception &another) throw();
void assign(const Exception &another, size_t startDepth = 0) throw();
void append(const Exception &another, size_t startDepth = 0) throw();
virtual bool isEmpty() const throw();
size_t getMaxDepth() const throw();
virtual void format(std::ostream &stream) const;
virtual void formatField(
std::ostream &stream, FieldType fieldType, size_t depth = 0) const;
Field getField(FieldType fieldType, size_t depth = 0) const throw();
virtual int32_t getErrorCode(size_t depth = 0) const throw();
virtual NamedErrorCode getNamedErrorCode(size_t depth = 0) const throw();
virtual void formatEntry(
std::ostream &stream, size_t depth = 0) const;
virtual void formatErrorCodeName(
std::ostream &stream, size_t depth = 0) const;
virtual void formatMessage(
std::ostream &stream, size_t depth = 0) const;
#ifdef UTIL_STACK_TRACE_ENABLED
virtual void formatStackTrace(
std::ostream &stream, size_t depth = 0) const;
#endif
virtual void formatTypeName(
std::ostream &stream, size_t depth = 0) const;
virtual void formatFileName(
std::ostream &stream, size_t depth = 0) const;
virtual void formatFunctionName(
std::ostream &stream, size_t depth = 0) const;
virtual int32_t getLineNumber(size_t depth = 0) const throw();
virtual bool hasErrorCode(size_t depth = 0) const throw();
virtual bool hasErrorCodeName(size_t depth = 0) const throw();
virtual bool hasMessage(size_t depth = 0) const throw();
#ifdef UTIL_STACK_TRACE_ENABLED
virtual bool hasStackTrace(size_t depth = 0) const throw();
#endif
virtual bool hasTypeName(size_t depth = 0) const throw();
virtual bool hasFileName(size_t depth = 0) const throw();
virtual bool hasFunctionName(size_t depth = 0) const throw();
virtual bool hasLineNumber(size_t depth = 0) const throw();
virtual DuplicatedLiteralFlags inheritLiteralFlags(
DuplicatedLiteralFlags baseFlags = LITERAL_ALL_DUPLICATED,
size_t depth = 0) const throw();
virtual const char* what() const throw();
static void enableWhat(bool enabled) throw();
static NamedErrorCode makeNamedErrorCode(
int32_t code,
const SourceSymbolChar *nameLiteral,
const SourceSymbolChar *nameLiteralPrefix) throw();
protected:
void* allocate(size_t size) throw();
void deallocate(void *ptr) throw();
void deallocateLiteral(const char8_t *literalStr,
FieldType fieldType, DuplicatedLiteralFlags literalFlags) throw();
char8_t* tryCopyString(const char8_t *str) throw();
const char8_t* tryCopyLiteral(const char8_t *literalStr,
FieldType fieldType, DuplicatedLiteralFlags literalFlags) throw();
NamedErrorCode tryCopyNamedErrorCode(const NamedErrorCode &src,
DuplicatedLiteralFlags literalFlags) throw();
virtual void clear() throw();
private:
struct Entry {
Entry() throw();
bool isEmpty(bool typeNameIgnorable) const throw();
NamedErrorCode namedErrorCode_;
char8_t *message_;
#ifdef UTIL_STACK_TRACE_ENABLED
char8_t *stackTrace_;
#endif
const char8_t *typeName_;
const SourceSymbolChar *fileName_;
const SourceSymbolChar *functionName_;
int32_t lineNumber_;
DuplicatedLiteralFlags literalFlags_;
};
static const size_t BUFFER_SIZE = 512;
const Entry* getEntryAt(size_t depth) const throw();
static const char8_t* resolveException(
Exception **fullEx, std::exception **stdEx) throw();
static const char8_t* resolveTypeName(const char8_t *customName) throw();
void fillWhat() throw();
void setEntry(Entry &dest, const Entry &src) throw();
void setEntry(Entry &entry,
const NamedErrorCode &namedErrorCode,
const char8_t *message,
const char8_t *stackTrace,
const char8_t *typeNameLiteral,
const SourceSymbolChar *fileNameLiteral,
const SourceSymbolChar *functionNameLiteral,
int32_t lineNumber,
DuplicatedLiteralFlags literalFlags) throw();
void clearEntry(Entry &entry) throw();
static bool whatEnabled_;
uint8_t buffer_[BUFFER_SIZE];
size_t bufferOffset_;
Entry *subEntries_;
size_t maxDepth_;
Entry topEntry_;
char8_t *what_;
};
/*!
@brief String for exception without throwing.
*/
template<typename Alloc>
struct Exception::NoThrowString {
public:
typedef std::basic_ostringstream<
char8_t, std::char_traits<char8_t>, Alloc> Stream;
typedef std::basic_string<
char8_t, std::char_traits<char8_t>, Alloc> String;
explicit NoThrowString(Stream &stream) throw();
~NoThrowString() throw();
const char8_t* get() const throw();
private:
NoThrowString(const NoThrowString&);
NoThrowString& operator=(NoThrowString&);
String *str_;
uint64_t storage_[
(sizeof(String) + sizeof(uint64_t) - 1) / sizeof(uint64_t)];
};
class Exception::Field {
public:
explicit Field(const Exception &exception, FieldType fieldType,
size_t depth = 0) throw();
void format(std::ostream &s) const;
private:
friend class Exception;
Field(const Field&);
Field& operator=(const Field&);
const Exception &exception_;
FieldType fieldType_;
size_t depth_;
};
std::ostream& operator<<(std::ostream &s, const Exception::Field &field);
/*!
@brief Exception handling an error number of a system call.
*/
class PlatformException : public Exception {
public:
explicit PlatformException(UTIL_EXCEPTION_CONSTRUCTOR_ARGS_DECL) throw();
virtual ~PlatformException() throw();
};
class UtilityException : public Exception {
public:
explicit UtilityException(UTIL_EXCEPTION_CONSTRUCTOR_ARGS_DECL) throw();
virtual ~UtilityException() throw();
static UtilityException inherit(
UTIL_EXCEPTION_CONSTRUCTOR_ARGS_DECL) throw();
enum Code {
CODE_DEFAULT = 0,
CODE_ILLEGAL_OPERATION,
CODE_ILLEGAL_ARGUMENT,
CODE_INVALID_STATUS,
CODE_INVALID_PARAMETER,
CODE_NO_MEMORY,
CODE_MEMORY_LIMIT_EXCEEDED,
CODE_SIZE_LIMIT_EXCEEDED,
CODE_DECODE_FAILED,
CODE_VALUE_OVERFLOW
};
};
class LocaleUtils {
public:
inline static const std::locale& getCLocale() throw() {
return *cLocale_;
}
class CLocaleScope {
public:
inline explicit CLocaleScope(std::ios_base &baseStream) :
baseStream_(NULL),
orgLocale_(NULL) {
if (baseStream.getloc() != getCLocale()) {
set(baseStream);
}
}
inline ~CLocaleScope() {
if (orgLocale_ != NULL) {
unset();
}
}
private:
void set(std::ios_base &baseStream);
void unset() throw();
std::ios_base *baseStream_;
std::locale *orgLocale_;
uint8_t orgLocaleStorage_[sizeof(std::locale)];
};
class Initializer {
public:
Initializer();
~Initializer();
};
private:
LocaleUtils();
static const std::locale *cLocale_;
};
namespace detail {
static LocaleUtils::Initializer g_localeUtilsInitializer;
}
class NormalOStringStream : public std::ostringstream {
public:
inline explicit NormalOStringStream(
std::ios_base::openmode mode = ios_base::out) :
std::ostringstream(mode) {
if (getloc() != LocaleUtils::getCLocale()) {
imbue(LocaleUtils::getCLocale());
}
}
inline explicit NormalOStringStream(
const std::string &str,
std::ios_base::openmode mode = ios_base::out) :
std::ostringstream(str, mode) {
}
virtual ~NormalOStringStream();
};
class NormalIStringStream : public std::istringstream {
public:
inline explicit NormalIStringStream(
std::ios_base::openmode mode = ios_base::in) :
std::istringstream(mode) {
if (getloc() != LocaleUtils::getCLocale()) {
imbue(LocaleUtils::getCLocale());
}
}
inline explicit NormalIStringStream(
const std::string &str,
std::ios_base::openmode mode = ios_base::in) :
std::istringstream(str, mode) {
}
virtual ~NormalIStringStream();
};
}
#define ostringstream ostringstream_is_disabled_because_of_locale_dependency
#define istringstream istringstream_is_disabled_because_of_locale_dependency
#define stringstream stringstream_is_disabled_because_of_locale_dependency
#ifdef __GNUC__
#define UTIL_EXCEPTION_THROWN_FUNCTION __PRETTY_FUNCTION__
#else
#define UTIL_EXCEPTION_THROWN_FUNCTION __FUNCTION__
#endif
#define UTIL_EXCEPTION_POSITION_ARGS \
__FILE__, UTIL_EXCEPTION_THROWN_FUNCTION, __LINE__
#define UTIL_EXCEPTION_CREATE_MESSAGE_STREAM \
util::NormalOStringStream().write("", 0)
#define UTIL_EXCEPTION_CREATE_MESSAGE_CHARS(message) \
util::Exception::NoThrowString<util::NormalOStringStream::allocator_type>( \
static_cast<util::NormalOStringStream&>( \
UTIL_EXCEPTION_CREATE_MESSAGE_STREAM << message)).get()
#define UTIL_EXCEPTION_CREATE_CUSTOM_DETAIL( \
type, errorCode, cause, message, stackTraceMode) \
type((errorCode), UTIL_EXCEPTION_CREATE_MESSAGE_CHARS(message), \
UTIL_EXCEPTION_POSITION_ARGS, (cause), #type, \
stackTraceMode)
#define UTIL_EXCEPTION_CREATE_DETAIL(type, errorCode, cause, message) \
UTIL_EXCEPTION_CREATE_CUSTOM_DETAIL( \
type, errorCode, cause, message, util::Exception::STACK_TRACE_NONE)
#define UTIL_EXCEPTION_CREATE_DETAIL_TRACE(type, errorCode, cause, message) \
UTIL_EXCEPTION_CREATE_CUSTOM_DETAIL( \
type, errorCode, cause, message, util::Exception::STACK_TRACE_TOP)
#define UTIL_EXCEPTION_UTIL_NAMED_CODE(codeSymbol) \
util::Exception::makeNamedErrorCode( \
util::UtilityException::codeSymbol, #codeSymbol, "CODE_")
#define UTIL_THROW_UTIL_ERROR(codeSymbol, message) \
throw UTIL_EXCEPTION_CREATE_DETAIL_TRACE(util::UtilityException, \
UTIL_EXCEPTION_UTIL_NAMED_CODE(codeSymbol), NULL, message)
#define UTIL_THROW_UTIL_ERROR_CODED(codeSymbol) \
UTIL_THROW_UTIL_ERROR(codeSymbol, "Utility error occurred (code=" << \
UTIL_EXCEPTION_UTIL_NAMED_CODE(codeSymbol).getName() << ")")
#define UTIL_RETHROW_UTIL_ERROR(codeSymbol, cause, message) \
throw util::UtilityException::inherit( \
UTIL_EXCEPTION_UTIL_NAMED_CODE(codeSymbol), \
UTIL_EXCEPTION_CREATE_MESSAGE_CHARS(message), \
UTIL_EXCEPTION_POSITION_ARGS, &(cause), \
"util::UtilityException", util::Exception::STACK_TRACE_NONE)
#define UTIL_THROW_NOIMPL_UTIL() \
UTIL_THROW_UTIL_ERROR(CODE_ILLEGAL_OPERATION, "Not implemented")
#define UTIL_THROW_ERROR(errorCode, message) \
throw UTIL_EXCEPTION_CREATE_DETAIL_TRACE( \
util::Exception, errorCode, NULL, message)
#define UTIL_RETHROW(errorCode, cause, message) \
throw UTIL_EXCEPTION_CREATE_DETAIL( \
util::Exception, errorCode, &(cause), message)
#define UTIL_THROW_NOIMPL() UTIL_THROW_ERROR(0, "Not implemented")
namespace util {
class PlatformExceptionBuilder {
public:
enum Type {
TYPE_NORMAL,
TYPE_ADDRINFO_LINUX
};
PlatformException operator()(
const char8_t *message,
const Exception::SourceSymbolChar *fileNameLiteral,
const Exception::SourceSymbolChar *functionNameLiteral,
int32_t lineNumber,
Type type = TYPE_NORMAL,
int32_t specialErrorCode = 0);
};
}
#define UTIL_THROW_PLATFORM_ERROR(message) \
throw util::PlatformExceptionBuilder()(message, UTIL_EXCEPTION_POSITION_ARGS);
#define UTIL_THROW_PLATFORM_ERROR_WITH_CODE(type, errorCode, message) \
throw util::PlatformExceptionBuilder()( \
message, UTIL_EXCEPTION_POSITION_ARGS, \
util::PlatformExceptionBuilder::type, errorCode);
namespace util {
/*!
@brief Structure template for only assert macros during compile.
*/
template<bool>
struct StaticAssertChecker {
public:
enum {
ASSERTION_FAILED
};
};
template<>
struct StaticAssertChecker<false> {
private:
enum {
ASSERTION_FAILED
};
};
}
#define UTIL_STATIC_ASSERT(expression) \
static_cast<void>( \
util::StaticAssertChecker<(expression)>::ASSERTION_FAILED)
namespace util {
struct TrueType { enum Value { VALUE = 1 }; };
struct FalseType { enum Value { VALUE = 0 }; };
template<bool> struct BoolType;
template<> struct BoolType<false> { typedef FalseType Result; };
template<> struct BoolType<true> { typedef TrueType Result; };
template<typename Base, typename Sub>
class BaseOf {
private:
typedef int T;
struct F { T i, j; };
static T check(const Base*);
static F check(...);
public:
typedef typename BoolType<
sizeof(check(static_cast<Sub*>(NULL))) == sizeof(T)>::Result Result;
};
template<bool, typename T = void> struct EnableIf {
};
template<typename T> struct EnableIf<true, T> {
typedef T Type;
};
template<bool Cond, typename T, typename F>
struct Conditional {
typedef T Type;
};
template<typename T, typename F>
struct Conditional<false, T, F> {
typedef F Type;
};
template<typename T, typename U> struct IsSame {
typedef FalseType Type;
enum Value { VALUE = Type::VALUE };
};
template<typename T> struct IsSame<T, T> {
typedef TrueType Type;
enum Value { VALUE = Type::VALUE };
};
template<typename>
struct IsPointer {
typedef FalseType Type;
enum Value { VALUE = Type::VALUE };
};
template<typename E>
struct IsPointer<E*> {
typedef TrueType Type;
enum Value { VALUE = Type::VALUE };
};
}
namespace util {
namespace detail {
class RawNumberFormatter {
public:
const char8_t* operator()(uint64_t value);
const char8_t* operator()(int64_t value);
const char8_t* operator()(uint32_t value);
const char8_t* operator()(int32_t value);
private:
char8_t result_[100];
};
}
}
namespace util {
namespace detail {
class LocalString {
public:
LocalString(char8_t *localBuf, size_t capacity) throw();
~LocalString();
bool tryAppend(const char8_t *value) throw();
bool tryAppend(const char8_t *begin, const char8_t *end) throw();
const char8_t* tryGet(const char8_t *alternative = "") throw();
private:
size_t size_;
size_t capacity_;
char8_t *localBuf_;
char8_t *dynamicBuf_;
};
}
}
#ifdef UTIL_STACK_TRACE_ENABLED
namespace util {
class StackTraceHandler {
public:
virtual void operator()(const char8_t *name, int32_t line) = 0;
};
class StackTraceUtils {
public:
static void getStackTrace(StackTraceHandler &handler);
static std::ostream& getStackTrace(std::ostream &stream);
class Initializer {
public:
Initializer();
~Initializer();
private:
static size_t counter_;
};
private:
struct Impl;
StackTraceUtils();
static Impl *impl_;
};
namespace detail {
static StackTraceUtils::Initializer g_stackTraceUtilsInitializer;
class StackTraceStringHandler : public StackTraceHandler {
public:
explicit StackTraceStringHandler(
detail::LocalString &str,
size_t maxDepth = 0, bool ignoreLibs = false);
virtual ~StackTraceStringHandler();
virtual void operator()(const char8_t *name, int32_t line);
private:
detail::LocalString &str_;
size_t maxDepth_;
bool ignoreLibs_;
size_t lastDepth_;
};
}
}
#endif
namespace util {
/*!
@brief Utility for debugging.
*/
class DebugUtils {
public:
static bool isDebuggerAttached();
static void interrupt();
private:
DebugUtils();
DebugUtils(const DebugUtils&);
DebugUtils& operator=(const DebugUtils&);
};
}
namespace util {
namespace detail {
struct DirectAllocationUtils {
static void* allocate(size_t size);
static void deallocate(void *ptr);
};
}
}
#define UTIL_MALLOC(size) util::detail::DirectAllocationUtils::allocate(size)
#define UTIL_FREE(ptr) util::detail::DirectAllocationUtils::deallocate(ptr)
#if UTIL_CXX11_SUPPORTED
#define UTIL_UNIQUE_PTR std::unique_ptr
#else
#define UTIL_UNIQUE_PTR std::auto_ptr
#endif
#if UTIL_FAILURE_SIMULATION_ENABLED
namespace util {
class AllocationFailureSimulator {
public:
enum Target {
TARGET_NEW,
TARGET_STACK_ALLOCATION,
};
static void set(int32_t targetType, uint64_t startCount, uint64_t endCount);
static void checkOperation(int32_t targetType, size_t size);
static uint64_t getLastOperationCount() { return lastOperationCount_; }
private:
AllocationFailureSimulator();
~AllocationFailureSimulator();
static volatile bool enabled_;
static volatile int32_t targetType_;
static volatile uint64_t startCount_;
static volatile uint64_t endCount_;
static volatile uint64_t lastOperationCount_;
};
}
void* operator new(size_t size);
void* operator new[](size_t size);
void operator delete(void *p);
void operator delete[](void *p);
#else
#ifdef UTIL_PLACEMENT_NEW_ENABLED
void* operator new(size_t size);
void* operator new[](size_t size);
void operator delete(void *p);
void operator delete[](void *p);
#endif
#endif
#define UTIL_NEW new
#endif
| {
"pile_set_name": "Github"
} |
import {join} from "path";
import {expect} from "chai";
import {BeaconState} from "@chainsafe/lodestar-types";
import {config} from "@chainsafe/lodestar-config/lib/presets/mainnet";
import {processBlockHeader} from "@chainsafe/lodestar-beacon-state-transition";
import {describeDirectorySpecTest} from "@chainsafe/lodestar-spec-test-util/lib/single";
import {IProcessBlockHeader} from "./type";
import {SPEC_TEST_LOCATION} from "../../../utils/specTestCases";
describeDirectorySpecTest<IProcessBlockHeader, BeaconState>(
"process block header mainnet",
join(SPEC_TEST_LOCATION, "/tests/mainnet/phase0/operations/block_header/pyspec_tests"),
(testcase) => {
const state = testcase.pre;
processBlockHeader(config, state, testcase.block);
return state;
},
{
sszTypes: {
pre: config.types.BeaconState,
post: config.types.BeaconState,
block: config.types.BeaconBlock,
},
timeout: 100000000,
shouldError: (testCase) => !testCase.post,
getExpected: (testCase) => testCase.post,
expectFunc: (testCase, expected, actual) => {
expect(config.types.BeaconState.equals(actual, expected)).to.be.true;
},
}
);
| {
"pile_set_name": "Github"
} |
- hosts: master
tasks:
- name: Upgrade kubeadm
apt:
name: ['kubeadm']
state: latest
force: yes
update_cache: yes
autoclean: yes
autoremove: yes
- name: Determine latest stable version of Kubernetes
shell: curl -sSL https://dl.k8s.io/release/stable.txt
register: stable_ver
args:
warn: False
- name: Upgrade cluster with kubeadm
shell: "kubeadm upgrade apply -y {{ stable_ver.stdout }}"
async: 600
poll: 5
- name: Cordon Hosts
shell: "kubectl cordon {{ item }}"
with_items:
- "{{ groups['all'] }}"
tags: cordon
- name: Drain Hosts
shell: "kubectl drain {{ item }} --ignore-daemonsets"
with_items:
- "{{ groups['all'] }}"
ignore_errors: yes
tags: drain
- hosts: all
tasks:
- name: Upgrade Y'all
apt:
name: ['kubelet', 'kubectl']
state: latest
force: yes
update_cache: yes
autoclean: yes
autoremove: yes
tags:
- kubelet
- kubectl
- hosts: master
tasks:
- name: Uncordon Hosts
shell: "kubectl uncordon {{ item }}"
with_items:
- "{{ groups['all'] }}"
tags: uncordon
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.adapter.pig;
import org.apache.calcite.adapter.enumerable.EnumerableRules;
import org.apache.calcite.jdbc.CalciteSchema;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.core.TableScan;
import org.apache.calcite.rel.rules.CoreRules;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.pig.data.DataType;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
/** Implementation of {@link org.apache.calcite.rel.core.TableScan} in
* {@link PigRel#CONVENTION Pig calling convention}. */
public class PigTableScan extends TableScan implements PigRel {
/** Creates a PigTableScan. */
public PigTableScan(RelOptCluster cluster, RelTraitSet traitSet, RelOptTable table) {
super(cluster, traitSet, ImmutableList.of(), table);
assert getConvention() == PigRel.CONVENTION;
}
@Override public void implement(Implementor implementor) {
final PigTable pigTable = getPigTable(implementor.getTableName(this));
final String alias = implementor.getPigRelationAlias(this);
final String schema = '(' + getSchemaForPigStatement(implementor)
+ ')';
final String statement = alias + " = LOAD '" + pigTable.getFilePath()
+ "' USING PigStorage() AS " + schema + ';';
implementor.addStatement(statement);
}
private PigTable getPigTable(String name) {
final CalciteSchema schema = getTable().unwrap(org.apache.calcite.jdbc.CalciteSchema.class);
return (PigTable) schema.getTable(name, false).getTable();
}
private String getSchemaForPigStatement(Implementor implementor) {
final List<String> fieldNamesAndTypes = new ArrayList<>(
getTable().getRowType().getFieldList().size());
for (RelDataTypeField f : getTable().getRowType().getFieldList()) {
fieldNamesAndTypes.add(getConcatenatedFieldNameAndTypeForPigSchema(implementor, f));
}
return String.join(", ", fieldNamesAndTypes);
}
private String getConcatenatedFieldNameAndTypeForPigSchema(Implementor implementor,
RelDataTypeField field) {
final PigDataType pigDataType = PigDataType.valueOf(field.getType().getSqlTypeName());
final String fieldName = implementor.getFieldName(this, field.getIndex());
return fieldName + ':' + DataType.findTypeName(pigDataType.getPigType());
}
@Override public void register(RelOptPlanner planner) {
planner.addRule(PigToEnumerableConverterRule.INSTANCE);
for (RelOptRule rule : PigRules.ALL_PIG_OPT_RULES) {
planner.addRule(rule);
}
// Don't move Aggregates around, otherwise PigAggregate.implement() won't
// know how to correctly procuce Pig Latin
planner.removeRule(CoreRules.AGGREGATE_EXPAND_DISTINCT_AGGREGATES);
// Make sure planner picks PigJoin over EnumerableHashJoin. Should there be
// a rule for this instead for removing ENUMERABLE_JOIN_RULE here?
planner.removeRule(EnumerableRules.ENUMERABLE_JOIN_RULE);
}
}
| {
"pile_set_name": "Github"
} |
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', './tooltip'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('./tooltip'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.Tooltip);
global.popover = mod.exports;
}
})(this, function (exports, module, _tooltip) {
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _Tooltip2 = _interopRequireDefault(_tooltip);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): popover.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Popover = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'popover';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.popover';
var EVENT_KEY = '.' + DATA_KEY;
var JQUERY_NO_CONFLICT = $.fn[NAME];
var Default = $.extend({}, _Tooltip2['default'].Default, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip">' + '<div class="popover-arrow"></div>' + '<h3 class="popover-title"></h3>' + '<div class="popover-content"></div></div>'
});
var DefaultType = $.extend({}, _Tooltip2['default'].DefaultType, {
content: '(string|function)'
});
var ClassName = {
FADE: 'fade',
IN: 'in'
};
var Selector = {
TITLE: '.popover-title',
CONTENT: '.popover-content',
ARROW: '.popover-arrow'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
INSERTED: 'inserted' + EVENT_KEY,
CLICK: 'click' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
FOCUSOUT: 'focusout' + EVENT_KEY,
MOUSEENTER: 'mouseenter' + EVENT_KEY,
MOUSELEAVE: 'mouseleave' + EVENT_KEY
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Popover = (function (_Tooltip) {
_inherits(Popover, _Tooltip);
function Popover() {
_classCallCheck(this, Popover);
_get(Object.getPrototypeOf(Popover.prototype), 'constructor', this).apply(this, arguments);
}
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
_createClass(Popover, [{
key: 'isWithContent',
// overrides
value: function isWithContent() {
return this.getTitle() || this._getContent();
}
}, {
key: 'getTipElement',
value: function getTipElement() {
return this.tip = this.tip || $(this.config.template)[0];
}
}, {
key: 'setContent',
value: function setContent() {
var tip = this.getTipElement();
var title = this.getTitle();
var content = this._getContent();
var titleElement = $(tip).find(Selector.TITLE)[0];
if (titleElement) {
titleElement[this.config.html ? 'innerHTML' : 'innerText'] = title;
}
// we use append for html objects to maintain js events
$(tip).find(Selector.CONTENT).children().detach().end()[this.config.html ? typeof content === 'string' ? 'html' : 'append' : 'text'](content);
$(tip).removeClass(ClassName.FADE).removeClass(ClassName.IN);
this.cleanupTether();
}
// private
}, {
key: '_getContent',
value: function _getContent() {
return this.element.getAttribute('data-content') || (typeof this.config.content === 'function' ? this.config.content.call(this.element) : this.config.content);
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = typeof config === 'object' ? config : null;
if (!data && /destroy|hide/.test(config)) {
return;
}
if (!data) {
data = new Popover(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
data[config]();
}
});
}
}, {
key: 'VERSION',
// getters
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}, {
key: 'NAME',
get: function get() {
return NAME;
}
}, {
key: 'DATA_KEY',
get: function get() {
return DATA_KEY;
}
}, {
key: 'Event',
get: function get() {
return Event;
}
}, {
key: 'EVENT_KEY',
get: function get() {
return EVENT_KEY;
}
}, {
key: 'DefaultType',
get: function get() {
return DefaultType;
}
}]);
return Popover;
})(_Tooltip2['default']);
$.fn[NAME] = Popover._jQueryInterface;
$.fn[NAME].Constructor = Popover;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Popover._jQueryInterface;
};
return Popover;
})(jQuery);
module.exports = Popover;
});
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2010-2011 ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained from Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "mali_kernel_common.h"
#include "mali_kernel_core.h"
#include "mali_kernel_memory_engine.h"
#include "mali_block_allocator.h"
#include "mali_osk.h"
#define MALI_BLOCK_SIZE (256UL * 1024UL) /* 256 kB, remember to keep the ()s */
typedef struct block_info
{
struct block_info * next;
} block_info;
/* The structure used as the handle produced by block_allocator_allocate,
* and removed by block_allocator_release */
typedef struct block_allocator_allocation
{
/* The list will be released in reverse order */
block_info *last_allocated;
mali_allocation_engine * engine;
mali_memory_allocation * descriptor;
u32 start_offset;
u32 mapping_length;
} block_allocator_allocation;
typedef struct block_allocator
{
_mali_osk_lock_t *mutex;
block_info * all_blocks;
block_info * first_free;
u32 base;
u32 cpu_usage_adjust;
u32 num_blocks;
} block_allocator;
MALI_STATIC_INLINE u32 get_phys(block_allocator * info, block_info * block);
static mali_physical_memory_allocation_result block_allocator_allocate(void* ctx, mali_allocation_engine * engine, mali_memory_allocation * descriptor, u32* offset, mali_physical_memory_allocation * alloc_info);
static void block_allocator_release(void * ctx, void * handle);
static mali_physical_memory_allocation_result block_allocator_allocate_page_table_block(void * ctx, mali_page_table_block * block);
static void block_allocator_release_page_table_block( mali_page_table_block *page_table_block );
static void block_allocator_destroy(mali_physical_memory_allocator * allocator);
static u32 block_allocator_stat(mali_physical_memory_allocator * allocator);
mali_physical_memory_allocator * mali_block_allocator_create(u32 base_address, u32 cpu_usage_adjust, u32 size, const char *name)
{
mali_physical_memory_allocator * allocator;
block_allocator * info;
u32 usable_size;
u32 num_blocks;
usable_size = size & ~(MALI_BLOCK_SIZE - 1);
MALI_DEBUG_PRINT(3, ("Mali block allocator create for region starting at 0x%08X length 0x%08X\n", base_address, size));
MALI_DEBUG_PRINT(4, ("%d usable bytes\n", usable_size));
num_blocks = usable_size / MALI_BLOCK_SIZE;
MALI_DEBUG_PRINT(4, ("which becomes %d blocks\n", num_blocks));
if (usable_size == 0)
{
MALI_DEBUG_PRINT(1, ("Memory block of size %d is unusable\n", size));
return NULL;
}
allocator = _mali_osk_malloc(sizeof(mali_physical_memory_allocator));
if (NULL != allocator)
{
info = _mali_osk_malloc(sizeof(block_allocator));
if (NULL != info)
{
info->mutex = _mali_osk_lock_init( _MALI_OSK_LOCKFLAG_ORDERED, 0, 105);
if (NULL != info->mutex)
{
info->all_blocks = _mali_osk_malloc(sizeof(block_info) * num_blocks);
if (NULL != info->all_blocks)
{
u32 i;
info->first_free = NULL;
info->num_blocks = num_blocks;
info->base = base_address;
info->cpu_usage_adjust = cpu_usage_adjust;
for ( i = 0; i < num_blocks; i++)
{
info->all_blocks[i].next = info->first_free;
info->first_free = &info->all_blocks[i];
}
allocator->allocate = block_allocator_allocate;
allocator->allocate_page_table_block = block_allocator_allocate_page_table_block;
allocator->destroy = block_allocator_destroy;
allocator->stat = block_allocator_stat;
allocator->ctx = info;
allocator->name = name;
return allocator;
}
_mali_osk_lock_term(info->mutex);
}
_mali_osk_free(info);
}
_mali_osk_free(allocator);
}
return NULL;
}
static void block_allocator_destroy(mali_physical_memory_allocator * allocator)
{
block_allocator * info;
MALI_DEBUG_ASSERT_POINTER(allocator);
MALI_DEBUG_ASSERT_POINTER(allocator->ctx);
info = (block_allocator*)allocator->ctx;
_mali_osk_free(info->all_blocks);
_mali_osk_lock_term(info->mutex);
_mali_osk_free(info);
_mali_osk_free(allocator);
}
MALI_STATIC_INLINE u32 get_phys(block_allocator * info, block_info * block)
{
return info->base + ((block - info->all_blocks) * MALI_BLOCK_SIZE);
}
static mali_physical_memory_allocation_result block_allocator_allocate(void* ctx, mali_allocation_engine * engine, mali_memory_allocation * descriptor, u32* offset, mali_physical_memory_allocation * alloc_info)
{
block_allocator * info;
u32 left;
block_info * last_allocated = NULL;
mali_physical_memory_allocation_result result = MALI_MEM_ALLOC_NONE;
block_allocator_allocation *ret_allocation;
MALI_DEBUG_ASSERT_POINTER(ctx);
MALI_DEBUG_ASSERT_POINTER(descriptor);
MALI_DEBUG_ASSERT_POINTER(offset);
MALI_DEBUG_ASSERT_POINTER(alloc_info);
info = (block_allocator*)ctx;
left = descriptor->size - *offset;
MALI_DEBUG_ASSERT(0 != left);
if (_MALI_OSK_ERR_OK != _mali_osk_lock_wait(info->mutex, _MALI_OSK_LOCKMODE_RW)) return MALI_MEM_ALLOC_INTERNAL_FAILURE;
ret_allocation = _mali_osk_malloc( sizeof(block_allocator_allocation) );
if ( NULL == ret_allocation )
{
/* Failure; try another allocator by returning MALI_MEM_ALLOC_NONE */
_mali_osk_lock_signal(info->mutex, _MALI_OSK_LOCKMODE_RW);
return result;
}
ret_allocation->start_offset = *offset;
ret_allocation->mapping_length = 0;
while ((left > 0) && (info->first_free))
{
block_info * block;
u32 phys_addr;
u32 padding;
u32 current_mapping_size;
block = info->first_free;
info->first_free = info->first_free->next;
block->next = last_allocated;
last_allocated = block;
phys_addr = get_phys(info, block);
padding = *offset & (MALI_BLOCK_SIZE-1);
if (MALI_BLOCK_SIZE - padding < left)
{
current_mapping_size = MALI_BLOCK_SIZE - padding;
}
else
{
current_mapping_size = left;
}
if (_MALI_OSK_ERR_OK != mali_allocation_engine_map_physical(engine, descriptor, *offset, phys_addr + padding, info->cpu_usage_adjust, current_mapping_size))
{
MALI_DEBUG_PRINT(1, ("Mapping of physical memory failed\n"));
result = MALI_MEM_ALLOC_INTERNAL_FAILURE;
mali_allocation_engine_unmap_physical(engine, descriptor, ret_allocation->start_offset, ret_allocation->mapping_length, (_mali_osk_mem_mapregion_flags_t)0);
/* release all memory back to the pool */
while (last_allocated)
{
/* This relinks every block we've just allocated back into the free-list */
block = last_allocated->next;
last_allocated->next = info->first_free;
info->first_free = last_allocated;
last_allocated = block;
}
break;
}
*offset += current_mapping_size;
left -= current_mapping_size;
ret_allocation->mapping_length += current_mapping_size;
}
_mali_osk_lock_signal(info->mutex, _MALI_OSK_LOCKMODE_RW);
if (last_allocated)
{
if (left) result = MALI_MEM_ALLOC_PARTIAL;
else result = MALI_MEM_ALLOC_FINISHED;
/* Record all the information about this allocation */
ret_allocation->last_allocated = last_allocated;
ret_allocation->engine = engine;
ret_allocation->descriptor = descriptor;
alloc_info->ctx = info;
alloc_info->handle = ret_allocation;
alloc_info->release = block_allocator_release;
}
else
{
/* Free the allocation information - nothing to be passed back */
_mali_osk_free( ret_allocation );
}
return result;
}
static void block_allocator_release(void * ctx, void * handle)
{
block_allocator * info;
block_info * block, * next;
block_allocator_allocation *allocation;
MALI_DEBUG_ASSERT_POINTER(ctx);
MALI_DEBUG_ASSERT_POINTER(handle);
info = (block_allocator*)ctx;
allocation = (block_allocator_allocation*)handle;
block = allocation->last_allocated;
MALI_DEBUG_ASSERT_POINTER(block);
if (_MALI_OSK_ERR_OK != _mali_osk_lock_wait(info->mutex, _MALI_OSK_LOCKMODE_RW))
{
MALI_DEBUG_PRINT(1, ("allocator release: Failed to get mutex\n"));
return;
}
/* unmap */
mali_allocation_engine_unmap_physical(allocation->engine, allocation->descriptor, allocation->start_offset, allocation->mapping_length, (_mali_osk_mem_mapregion_flags_t)0);
while (block)
{
MALI_DEBUG_ASSERT(!((block < info->all_blocks) || (block > (info->all_blocks + info->num_blocks))));
next = block->next;
/* relink into free-list */
block->next = info->first_free;
info->first_free = block;
/* advance the loop */
block = next;
}
_mali_osk_lock_signal(info->mutex, _MALI_OSK_LOCKMODE_RW);
_mali_osk_free( allocation );
}
static mali_physical_memory_allocation_result block_allocator_allocate_page_table_block(void * ctx, mali_page_table_block * block)
{
block_allocator * info;
mali_physical_memory_allocation_result result = MALI_MEM_ALLOC_INTERNAL_FAILURE;
MALI_DEBUG_ASSERT_POINTER(ctx);
MALI_DEBUG_ASSERT_POINTER(block);
info = (block_allocator*)ctx;
if (_MALI_OSK_ERR_OK != _mali_osk_lock_wait(info->mutex, _MALI_OSK_LOCKMODE_RW)) return MALI_MEM_ALLOC_INTERNAL_FAILURE;
if (NULL != info->first_free)
{
void * virt;
u32 phys;
u32 size;
block_info * alloc;
alloc = info->first_free;
phys = get_phys(info, alloc); /* Does not modify info or alloc */
size = MALI_BLOCK_SIZE; /* Must be multiple of MALI_MMU_PAGE_SIZE */
virt = _mali_osk_mem_mapioregion( phys, size, "Mali block allocator page tables" );
/* Failure of _mali_osk_mem_mapioregion will result in MALI_MEM_ALLOC_INTERNAL_FAILURE,
* because it's unlikely another allocator will be able to map in. */
if ( NULL != virt )
{
block->ctx = info; /* same as incoming ctx */
block->handle = alloc;
block->phys_base = phys;
block->size = size;
block->release = block_allocator_release_page_table_block;
block->mapping = virt;
info->first_free = alloc->next;
alloc->next = NULL; /* Could potentially link many blocks together instead */
result = MALI_MEM_ALLOC_FINISHED;
}
}
else result = MALI_MEM_ALLOC_NONE;
_mali_osk_lock_signal(info->mutex, _MALI_OSK_LOCKMODE_RW);
return result;
}
static void block_allocator_release_page_table_block( mali_page_table_block *page_table_block )
{
block_allocator * info;
block_info * block, * next;
MALI_DEBUG_ASSERT_POINTER( page_table_block );
info = (block_allocator*)page_table_block->ctx;
block = (block_info*)page_table_block->handle;
MALI_DEBUG_ASSERT_POINTER(info);
MALI_DEBUG_ASSERT_POINTER(block);
if (_MALI_OSK_ERR_OK != _mali_osk_lock_wait(info->mutex, _MALI_OSK_LOCKMODE_RW))
{
MALI_DEBUG_PRINT(1, ("allocator release: Failed to get mutex\n"));
return;
}
/* Unmap all the physical memory at once */
_mali_osk_mem_unmapioregion( page_table_block->phys_base, page_table_block->size, page_table_block->mapping );
/** @note This loop handles the case where more than one block_info was linked.
* Probably unnecssary for page table block releasing. */
while (block)
{
next = block->next;
MALI_DEBUG_ASSERT(!((block < info->all_blocks) || (block > (info->all_blocks + info->num_blocks))));
block->next = info->first_free;
info->first_free = block;
block = next;
}
_mali_osk_lock_signal(info->mutex, _MALI_OSK_LOCKMODE_RW);
}
static u32 block_allocator_stat(mali_physical_memory_allocator * allocator)
{
block_allocator * info;
block_info *block;
u32 free_blocks = 0;
MALI_DEBUG_ASSERT_POINTER(allocator);
info = (block_allocator*)allocator->ctx;
block = info->first_free;
while(block)
{
free_blocks++;
block = block->next;
}
return (info->num_blocks - free_blocks) * MALI_BLOCK_SIZE;
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2005 - 2017 Settlers Freaks (sf-team at siedler25.org)
//
// This file is part of Return To The Roots.
//
// Return To The Roots is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Return To The Roots 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 Return To The Roots. If not, see <http://www.gnu.org/licenses/>.
#include "world/TerritoryRegion.h"
#include "GamePlayer.h"
#include "MapGeometry.h"
#include "buildings/noBaseBuilding.h"
#include "buildings/nobMilitary.h"
#include "helpers/EnumRange.h"
#include "world/GameWorldBase.h"
#include <stdexcept>
TerritoryRegion::TerritoryRegion(const Position& startPt, const Extent& size, const GameWorldBase& gwb)
: startPt(startPt), size(size), world(gwb)
{
if(size.x > gwb.GetWidth() || size.y > gwb.GetHeight())
throw std::runtime_error("Size to big for TerritoryRegion");
// Feld erzeugen
nodes.resize(size.x * size.y);
}
TerritoryRegion::~TerritoryRegion() = default;
bool TerritoryRegion::IsPointInPolygon(const std::vector<Position>& polygon, const Position& pt)
{
// Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
// The site contains a lot of details and information.
bool inside = false;
auto it = polygon.begin();
auto prev = polygon.end() - 1;
// Check each edge if a ray from the point to the right crosses the edge
for(; it != polygon.end(); prev = it, ++it)
{
// Check if the edge crosses the horizontal line at height pt.y
// Includes edge point at lower coord and excludes the one at higher coord
if((it->y > pt.y) == (prev->y > pt.y))
continue;
// Check if the intersection point in X is right of our point
// Original formula for (signed) floating point:
// if (pt.x < (prev->x - it->x) * (pt.y - it->y) / (prev->y - it->y) + it->x)
// ==>(pt.x - it->x < (prev->x - it->x) * (pt.y - it->y) / (prev->y - it->y))
const int dy = prev->y - it->y;
const int lhs = (pt.x - it->x) * dy;
const int rhs = (prev->x - it->x) * (pt.y - it->y);
if((dy < 0 && lhs > rhs) || (dy > 0 && lhs < rhs))
inside = !inside;
}
return (inside);
}
bool TerritoryRegion::IsPointValid(const MapExtent& mapSize, const std::vector<MapPoint>& polygon, const MapPoint pt)
{
// This is for specifying polyons that wrap around corners:
// - e.g. w=64, h=64, polygon = {(40,40), (40,80), (80,80), (80,40)}
Position pt2(pt.x + mapSize.x, pt.y), pt3(pt.x, pt.y + mapSize.y), pt4(pt + mapSize);
const std::vector<Position> polygonInt(polygon.begin(), polygon.end());
return (polygon.empty() || IsPointInPolygon(polygonInt, Position(pt)) || IsPointInPolygon(polygonInt, pt2)
|| IsPointInPolygon(polygonInt, pt3) || IsPointInPolygon(polygonInt, pt4));
}
void TerritoryRegion::AdjustNode(MapPoint pt, uint8_t player, uint16_t radius, const std::vector<MapPoint>* allowedArea)
{
TRNode* node = TryGetNode(pt);
// Not in our region -> Out
if(!node)
return;
// check whether this node is within the area we may have territory in
if(allowedArea && !IsPointValid(world.GetSize(), *allowedArea, pt))
return;
/// If the new distance is less then the old, then we claim this point.
/// If the node did not had an owner, we still claim it
if(radius < node->radius || !node->owner)
{
node->owner = player + 1;
node->radius = radius;
}
}
TerritoryRegion::TRNode* TerritoryRegion::TryGetNode(const MapPoint& pt)
{
return TryGetNode(GetPosFromMapPos(pt));
}
TerritoryRegion::TRNode* TerritoryRegion::TryGetNode(Position realPt)
{
if(!AdjustCoords(realPt))
return nullptr;
return &GetNode(realPt);
}
const TerritoryRegion::TRNode* TerritoryRegion::TryGetNode(Position realPt) const
{
if(!AdjustCoords(realPt))
return nullptr;
return &GetNode(realPt);
}
bool TerritoryRegion::AdjustCoords(Position& pt) const
{
// The region might wrap around world boundaries. So we have to adjust the point so it will still be inside this
// region even if it is on "the other side" of the world wrap Note: Only 1 time wrapping around is allowed which is
// ensured by the assertion, that this size is at most the world size
// Check if this point is inside this region
// Apply wrap-around if on either side
if(pt.x < 0)
pt.x += world.GetWidth();
else if(static_cast<unsigned>(pt.x) >= size.x)
pt.x -= world.GetWidth();
// Check the (possibly) adjusted point
if(pt.x < 0 || static_cast<unsigned>(pt.x) >= size.x)
return false;
// Apply wrap-around if on either side
if(pt.y < 0)
pt.y += world.GetHeight();
else if(static_cast<unsigned>(pt.y) >= size.y)
pt.y -= world.GetHeight();
// Check the (possibly) adjusted point
if(pt.y < 0 || static_cast<unsigned>(pt.y) >= size.y)
return false;
return true;
}
namespace {
struct GetMapPointWithRadius
{
using result_type = std::pair<MapPoint, unsigned>;
result_type operator()(const MapPoint pt, unsigned r) { return std::make_pair(pt, r); }
};
} // namespace
void TerritoryRegion::CalcTerritoryOfBuilding(const noBaseBuilding& building)
{
unsigned radius = building.GetMilitaryRadius();
// Does not hold territory? -> Out
if(radius == 0u)
return;
// Also ignore non-occupied military buildings
if(building.GetGOT() == GOT_NOB_MILITARY && static_cast<const nobMilitary&>(building).IsNewBuilt())
return;
const std::vector<MapPoint>* allowedArea = &world.GetPlayer(building.GetPlayer()).GetRestrictedArea();
if(allowedArea->empty())
allowedArea = nullptr;
// Punkt, auf dem das Militärgebäude steht
MapPoint bldPos = building.GetPos();
AdjustNode(bldPos, building.GetPlayer(), 0,
nullptr); // no need to check barriers here. this point is on our territory.
std::vector<GetMapPointWithRadius::result_type> pts =
world.GetPointsInRadius(bldPos, radius, GetMapPointWithRadius());
for(const auto& ptWithRadius : pts)
AdjustNode(ptWithRadius.first, building.GetPlayer(), ptWithRadius.second, allowedArea);
}
uint8_t TerritoryRegion::SafeGetOwner(const Position& pt) const
{
const TRNode* node = TryGetNode(pt);
if(!node)
return world.GetNode(world.MakeMapPoint(pt + startPt)).owner;
return node->owner;
}
bool TerritoryRegion::WillBePlayerTerritory(const Position& mapPos, uint8_t owner, Direction exceptDir)
{
for(const auto d : helpers::EnumRange<Direction>{})
{
if(d == exceptDir)
continue;
if(SafeGetOwner(::GetNeighbour(mapPos, d) - startPt) != owner)
return false;
}
return true;
}
| {
"pile_set_name": "Github"
} |
<?php
namespace WhichBrowser\Data;
DeviceModels::$KDDI_MODELS = [
'KC3Q' => [ 'iida', 'misora' ], // KYX02 by Kyocera
'KC3S' => [ 'iida', 'PRISMOID' ], // KYX03 by Kyocera
'KC3V' => [ 'iida', 'lotta' ], // KYX04 by Kyocera
'ST22' => [ 'iida', 'INFOBAR' ], // A5307ST by Sanyo
'ST33' => [ 'iida', 'INFOBAR 2' ], // W55SA by Sanyo
'SN3K' => [ 'iida', 'G9' ], // SOX01 by Sony Ericsson
'SN3T' => [ 'iida', 'G11' ], // SOX02 by Sony Ericsson
'TS3Q' => [ 'iida', 'PLY' ], // TSX04 by Toshiba
'TS3U' => [ 'iida', 'LIGHT POOL' ], // by Toshiba
'TS3W' => [ 'iida', 'X-RAY' ], // by Toshiba
'CA11' => [ 'Casio', 'C303CA' ],
'CA12' => [ 'Casio', 'C311CA' ],
'CA13' => [ 'Casio', 'C409CA' ],
'CA14' => [ 'Casio', 'C452CA' ],
'CA21' => [ 'Casio', 'A3012CA' ],
'CA22' => [ 'Casio', 'A5302CA' ],
'CA23' => [ 'Casio', 'A5401CA' ],
'CA24' => [ 'Casio', 'A5403CA' ],
'CA25' => [ 'Casio', 'A5406CA' ],
'CA26' => [ 'Casio', 'A5407CA' ],
'CA27' => [ 'Casio', 'A5512CA' ],
'CA28' => [ 'Casio', 'GzOne Type-R A5513CA' ],
'CA31' => [ 'Casio', 'W21CA' ],
'CA32' => [ 'Casio', 'W31CA' ],
'CA33' => [ 'Casio', 'W41CA' ],
'CA34' => [ 'Casio', 'W42CA' ],
'CA35' => [ 'Casio', 'W43CA' ],
'CA36' => [ 'Casio', 'E03CA' ],
'CA37' => [ 'Casio', 'W51CA' ],
'CA38' => [ 'Casio', 'W52CA' ],
'CA39' => [ 'Casio', 'W53CA' ],
'CA3A' => [ 'Casio', 'W61CA' ],
'CA3B' => [ 'Casio', 'W62CA' ],
'CA3C' => [ 'Casio', 'W63CA' ],
'CA3D' => [ 'Casio', 'CA001' ],
'CA3E' => [ 'Casio', 'CA002' ],
'CA3F' => [ 'Casio', 'CA003' ],
'CA3G' => [ 'Casio', 'CA004' ],
'CA3H' => [ 'Casio', 'CA005' ],
'CA3I' => [ 'Casio', 'GzOne Type-X CAY01' ],
'CA3J' => [ 'Casio', 'CA006' ],
'CA3K' => [ 'Casio', 'CA007' ],
'DN01' => [ 'Denso', 'C202DE' ],
'DN11' => [ 'Denso', 'C402DE' ],
'ERK0' => [ 'Ericsson', 'R280' ],
'FJ31' => [ 'Fujitsu', 'F001' ],
'HI01' => [ 'Hitachi', 'C201H' ],
'HI02' => [ 'Hitachi', 'C201H' ],
'HI11' => [ 'Hitachi', 'C302H' ],
'HI12' => [ 'Hitachi', 'C309H' ],
'HI13' => [ 'Hitachi', 'C407H' ],
'HI14' => [ 'Hitachi', 'C451H' ],
'HI21' => [ 'Hitachi', 'C3001H' ],
'HI23' => [ 'Hitachi', 'A5303H' ],
'HI24' => [ 'Hitachi', 'A5303H II' ],
'HI31' => [ 'Hitachi', 'W11H' ],
'HI32' => [ 'Hitachi', 'W21H' ],
'HI33' => [ 'Hitachi', 'W22H' ],
'HI34' => [ 'Hitachi', 'PENCK W31H' ],
'HI35' => [ 'Hitachi', 'W32H' ],
'HI36' => [ 'Hitachi', 'W41H' ],
'HI37' => [ 'Hitachi', 'W42H' ],
'HI38' => [ 'Hitachi', 'W43H' ],
'HI39' => [ 'Hitachi', 'W51H' ],
'HI3A' => [ 'Hitachi', 'W52H' ],
'HI3B' => [ 'Hitachi', 'W53H' ],
'HI3C' => [ 'Hitachi', 'W61H' ],
'HI3D' => [ 'Hitachi', 'W62H' ],
'HI3E' => [ 'Hitachi', 'W63H' ],
'HI3F' => [ 'Hitachi', 'H001' ], // HI001
'HI3G' => [ 'Hitachi', 'Mobile Hi-Vision CAM Wooo HIY01' ],
'HI3H' => [ 'Hitachi', 'beskey HIY02' ],
'KC11' => [ 'Kyocera', 'C307K' ],
'KC12' => [ 'Kyocera', 'C313K' ],
'KC13' => [ 'Kyocera', 'C414K' ],
'KC14' => [ 'Kyocera', 'A1012K' ],
'KC15' => [ 'Kyocera', 'A1013K' ],
'KC21' => [ 'Kyocera', 'C3002K' ],
'KC22' => [ 'Kyocera', 'A5305K' ],
'KC23' => [ 'Kyocera', 'A1401K' ],
'KC24' => [ 'Kyocera', 'A5502K' ],
'KC25' => [ 'Kyocera', 'A5502K' ],
'KC26' => [ 'Kyocera', 'A1403K' ],
'KC27' => [ 'Kyocera', 'A5515K' ],
'KC28' => [ 'Kyocera', 'A5521K' ],
'KC29' => [ 'Kyocera', 'A5526K' ],
'KC2A' => [ 'Kyocera', 'A5528K' ],
'KC31' => [ 'Kyocera', 'W11K' ],
'KC32' => [ 'Kyocera', 'W21K' ],
'KC33' => [ 'Kyocera', 'W31K' ],
'KC34' => [ 'Kyocera', 'W32K' ],
'KC35' => [ 'Kyocera', 'W41K' ],
'KC36' => [ 'Kyocera', 'W42K' ],
'KC37' => [ 'Kyocera', 'W43K' ],
'KC38' => [ 'Kyocera', 'W44K' ],
'KC39' => [ 'Kyocera', 'W51K' ],
'KC3A' => [ 'Kyocera', 'MEDIA SKIN W52K' ],
'KC3B' => [ 'Kyocera', 'W53K/W64K' ],
'KC3D' => [ 'Kyocera', 'W61K' ],
'KC3E' => [ 'Kyocera', 'W44K II' ],
'KC3G' => [ 'Kyocera', 'W62K' ],
'KC3H' => [ 'Kyocera', 'W63K' ],
'KC3I' => [ 'Kyocera', 'W65K' ],
'KC3K' => [ 'Kyocera', 'W63K' ],
'KC3M' => [ 'Kyocera', 'K001' ], // KY001
'KC3N' => [ 'Kyocera', 'NS01' ], // KYX01
'KC3O' => [ 'Kyocera', 'K002' ], // KY002
'KC3P' => [ 'Kyocera', 'K003' ], // KY003
'KC3R' => [ 'Kyocera', 'SA001' ],
'KC3T' => [ 'Kyocera', 'E07K' ],
'KC3U' => [ 'Kyocera', 'K004' ], // KY004
'KC3W' => [ 'Kyocera', 'mamorino' ], // KYY01
'KC3X' => [ 'Kyocera', 'SA002' ],
'KC3Y' => [ 'Kyocera', 'K005' ], // KY005
'KC3Z' => [ 'Kyocera', 'K006' ], // KY006
'KC41' => [ 'Kyocera', 'K006' ],
'KC42' => [ 'Kyocera', 'K007' ], // KY007
'KC43' => [ 'Kyocera', 'K008' ], // KY008
'KC44' => [ 'Kyocera', 'mamorino 2' ], // KYY02
'KC45' => [ 'Kyocera', 'K010' ], // KY010
'KC46' => [ 'Kyocera', 'K009' ], // KY009
'KC47' => [ 'Kyocera', 'Mi-Look' ],
'KC48' => [ 'Kyocera', 'E10K' ],
'KC4A' => [ 'Kyocera', 'K011' ],
'KCC1' => [ 'Kyocera', 'D303K' ],
'KCC2' => [ 'Kyocera', 'D304K' ],
'KCI1' => [ 'Kyocera', '703G' ],
'KCI2' => [ 'Kyocera', '702G' ],
'KCT1' => [ 'Kyocera', 'TK01' ],
'KCT2' => [ 'Kyocera', 'TK02' ],
'KCT3' => [ 'Kyocera', 'TK02' ],
'KCT4' => [ 'Kyocera', 'TK03' ],
'KCT5' => [ 'Kyocera', 'TK04' ],
'KCT6' => [ 'Kyocera', 'TK05' ],
'KCT7' => [ 'Kyocera', 'TK11' ],
'KCT8' => [ 'Kyocera', 'TK12' ],
'KCT9' => [ 'Kyocera', 'TK21' ],
'KCTA' => [ 'Kyocera', 'TK22' ],
'KCTB' => [ 'Kyocera', 'TK23' ],
'KCTC' => [ 'Kyocera', 'TK31' ],
'MA11' => [ 'Panasonic', 'C308P' ],
'MA12' => [ 'Panasonic', 'C308P' ],
'MA13' => [ 'Panasonic', 'C408P' ],
'MA21' => [ 'Panasonic', 'C3003P' ],
'MA31' => [ 'Panasonic', 'W51P' ],
'MA32' => [ 'Panasonic', 'W52P' ],
'MA33' => [ 'Panasonic', 'W61P' ],
'MA34' => [ 'Panasonic', 'W62P' ],
'MA35' => [ 'Panasonic', 'P001' ],
'MAC1' => [ 'Panasonic', 'D305P' ],
'MAC2' => [ 'Panasonic', 'D305P' ],
'MAI1' => [ 'Panasonic', '704G' ],
'MAI2' => [ 'Panasonic', '704G' ],
'MAT1' => [ 'Panasonic', 'TP01' ],
'MAT2' => [ 'Panasonic', 'TP01' ],
'MAT3' => [ 'Panasonic', 'TP11' ],
'MIT1' => [ 'Mitsubishi', 'TD11' ],
'PT21' => [ 'Pantech', 'A1405PT' ],
'PT23' => [ 'Pantech', 'A1407PT' ],
'PT33' => [ 'Pantech', 'W61PT' ],
'PT34' => [ 'Pantech', 'W62PT' ],
'PT35' => [ 'Pantech', 'NS02' ],
'PT36' => [ 'Pantech', 'PT002' ],
'SA21' => [ 'Sanyo', 'A3011SA' ],
'SA22' => [ 'Sanyo', 'A3015SA' ],
'SA24' => [ 'Sanyo', 'A1302SA' ],
'SA25' => [ 'Sanyo', 'A1303SA' ],
'SA26' => [ 'Sanyo', 'A5503SA' ],
'SA27' => [ 'Sanyo', 'A5505SA' ],
'SA28' => [ 'Sanyo', 'A1305SA' ],
'SA29' => [ 'Sanyo', 'A5522SA' ],
'SA2A' => [ 'Sanyo', 'A5527SA' ],
'SA31' => [ 'Sanyo', 'W21SA' ],
'SA32' => [ 'Sanyo', 'W22SA' ],
'SA33' => [ 'Sanyo', 'W31SA' ],
'SA34' => [ 'Sanyo', 'W32SA' ],
'SA35' => [ 'Sanyo', 'W33SA' ],
'SA36' => [ 'Sanyo', 'W41SA' ],
'SA37' => [ 'Sanyo', 'E02SA' ],
'SA38' => [ 'Sanyo', 'W43SA' ],
'SA39' => [ 'Sanyo', 'W51SA' ],
'SA3A' => [ 'Sanyo', 'W52SA' ],
'SA3B' => [ 'Sanyo', 'W54SA' ],
'SA3C' => [ 'Sanyo', 'W61SA' ],
'SA3D' => [ 'Sanyo', 'W63SA' ],
'SA3E' => [ 'Sanyo', 'W64SA' ],
'SY12' => [ 'Sanyo', 'C401SA' ],
'SY13' => [ 'Sanyo', 'C405SA' ],
'SY14' => [ 'Sanyo', 'C412SA' ],
'SY15' => [ 'Sanyo', 'C1001SA' ],
'SYC1' => [ 'Sanyo', 'D301SA' ],
'SYT1' => [ 'Sanyo', 'TS01' ],
'SYT2' => [ 'Sanyo', 'TS02' ],
'SYT3' => [ 'Sanyo', 'TS11' ],
'SYT4' => [ 'Sanyo', 'TS31' ],
'SH31' => [ 'Sharp', 'W41SH' ],
'SH32' => [ 'Sharp', 'W51SH' ],
'SH33' => [ 'Sharp', 'W52SH' ],
'SH34' => [ 'Sharp', 'W61SH' ],
'SH35' => [ 'Sharp', 'W62SH' ],
'SH36' => [ 'Sharp', 'URBANO W63SH' ],
'SH37' => [ 'Sharp', 'W64SH' ],
'SH38' => [ 'Sharp', 'SH001' ],
'SH39' => [ 'Sharp', 'E05SH' ],
'SH3A' => [ 'Sharp', 'E06SH' ],
'SH3B' => [ 'Sharp', 'SH002' ],
'SH3C' => [ 'Sharp', 'Sportio water beat SHY01' ],
'SH3D' => [ 'Sharp', 'SH003' ],
'SH3E' => [ 'Sharp', 'SH004' ],
'SH3F' => [ 'Sharp', 'SH005' ],
'SH3G' => [ 'Sharp', 'SH006' ],
'SH3H' => [ 'Sharp', 'SH007' ],
'SH3I' => [ 'Sharp', 'SH008' ],
'SH3J' => [ 'Sharp', 'SH009' ],
'SH3K' => [ 'Sharp', 'SH010' ],
'SH3L' => [ 'Sharp', 'SH011' ],
'SN11' => [ 'Sony', 'C305S' ],
'SN13' => [ 'Sony', 'C406S' ],
'SN14' => [ 'Sony', 'C404S' ],
'SN15' => [ 'Sony', 'C413S' ],
'SN16' => [ 'Sony', 'C413S' ],
'SN17' => [ 'Sony Ericsson', 'C1002S' ],
'SN21' => [ 'Sony Ericsson', 'A3014S' ],
'SN22' => [ 'Sony Ericsson', 'A1101S' ],
'SN23' => [ 'Sony Ericsson', 'A1301S' ],
'SN24' => [ 'Sony Ericsson', 'A5402S' ],
'SN25' => [ 'Sony Ericsson', 'A5404S' ],
'SN26' => [ 'Sony Ericsson', 'A1402S' ],
'SN27' => [ 'Sony Ericsson', 'A1402S II' ],
'SN28' => [ 'Sony Ericsson', 'A1402S II' ],
'SN29' => [ 'Sony Ericsson', 'A1404S' ],
'SN31' => [ 'Sony Ericsson', 'W21S' ],
'SN32' => [ 'Sony Ericsson', 'W31S' ],
'SN33' => [ 'Sony Ericsson', 'W32S' ],
'SN34' => [ 'Sony Ericsson', 'W41S' ],
'SN35' => [ 'Sony Ericsson', 'EZ FeliCa W32S' ],
'SN36' => [ 'Sony Ericsson', 'W42S' ],
'SN37' => [ 'Sony Ericsson', 'W43S' ],
'SN38' => [ 'Sony Ericsson', 'W44S' ],
'SN39' => [ 'Sony Ericsson', 'W51S' ],
'SN3A' => [ 'Sony Ericsson', 'W52S' ],
'SN3B' => [ 'Sony Ericsson', 'W53S' ],
'SN3C' => [ 'Sony Ericsson', 'W54S' ],
'SN3D' => [ 'Sony Ericsson', 'W61S' ],
'SN3E' => [ 'Sony Ericsson', 'W62S' ],
'SN3F' => [ 'Sony Ericsson', 're W63S' ],
'SN3G' => [ 'Sony Ericsson', 'W64S' ],
'SN3H' => [ 'Sony Ericsson', 'Xmini W65S' ],
'SN3I' => [ 'Sony Ericsson', 'Premier3 SOY01' ],
'SN3J' => [ 'Sony Ericsson', 'S001' ],
'SN3L' => [ 'Sony Ericsson', 'BRAVIA Phone U1 SOY02' ],
'SN3M' => [ 'Sony Ericsson', 'S002' ],
'SN3N' => [ 'Sony Ericsson', 'URBANO BARONE SOY03' ],
'SN3O' => [ 'Sony Ericsson', 'S003' ],
'SN3P' => [ 'Sony Ericsson', 'S004' ],
'SN3Q' => [ 'Sony Ericsson', 'S005' ],
'SN3R' => [ 'Sony Ericsson', 'URBANO MOND SOY04' ],
'SN3S' => [ 'Sony Ericsson', 'S006' ],
'SN3U' => [ 'Sony Ericsson', 'S007' ],
'SN3V' => [ 'Sony Ericsson', 'URBANO AFFARE SOY05' ],
'ST11' => [ 'Sanyo', 'C403ST' ],
'ST12' => [ 'Sanyo', 'C411ST' ],
'ST13' => [ 'Sanyo', 'A1011ST' ],
'ST14' => [ 'Sanyo', 'A1014ST' ],
'ST21' => [ 'Sanyo', 'A5306ST' ],
'ST23' => [ 'Sanyo', 'A5405SA' ],
'ST24' => [ 'Sanyo', 'A5507SA' ],
'ST25' => [ 'Sanyo', 'talby A5508SA' ],
'ST26' => [ 'Sanyo', 'Sweets A5510SA' ],
'ST27' => [ 'Sanyo', 'A5514SA' ],
'ST28' => [ 'Sanyo', 'A5518SA' ],
'ST29' => [ 'Sanyo', 'Sweets pure A5519SA' ],
'ST2A' => [ 'Sanyo', 'A5520SA' ],
'ST2C' => [ 'Sanyo', 'Sweets cute A5524SA' ],
'ST2D' => [ 'Sanyo', 'A5525SA' ],
'ST31' => [ 'Sanyo', 'W42SA' ],
'ST32' => [ 'Sanyo', 'W53SA' ],
'ST34' => [ 'Sanyo', 'W62SA' ],
'SY01' => [ 'Sanyo', 'SCP-4000' ],
'SY02' => [ 'Sanyo', 'SCP-4500' ],
'SY03' => [ 'Sanyo', 'SCP-5000' ],
'SY11' => [ 'Sanyo', 'C304SA' ],
'SY12' => [ 'Sanyo', 'C401SA' ],
'SY13' => [ 'Sanyo', 'C405SA' ],
'SY14' => [ 'Sanyo', 'C412SA' ],
'SY15' => [ 'Sanyo', 'C1001SA' ],
'TS01' => [ 'Toshiba', 'IS02' ],
'TS11' => [ 'Toshiba', 'C301T' ],
'TS12' => [ 'Toshiba', 'C310T' ],
'TS13' => [ 'Toshiba', 'C410T' ],
'TS14' => [ 'Toshiba', 'C415T' ],
'TS21' => [ 'Toshiba', 'C5001T' ],
'TS22' => [ 'Toshiba', 'A3013T' ],
'TS23' => [ 'Toshiba', 'A5301T' ],
'TS24' => [ 'Toshiba', 'A5304T' ],
'TS25' => [ 'Toshiba', 'A1304T' ],
'TS26' => [ 'Toshiba', 'A5501T' ],
'TS27' => [ 'Toshiba', 'A5504T' ],
'TS28' => [ 'Toshiba', 'A5506T' ],
'TS29' => [ 'Toshiba', 'A5509T' ],
'TS2A' => [ 'Toshiba', 'A5511T' ],
'TS2B' => [ 'Toshiba', 'A5516T' ],
'TS2C' => [ 'Toshiba', 'A5517T' ],
'TS2D' => [ 'Toshiba', 'A5523T' ],
'TS2E' => [ 'Toshiba', 'A5529T' ],
'TS31' => [ 'Toshiba', 'W21T' ],
'TS32' => [ 'Toshiba', 'W31T' ],
'TS33' => [ 'Toshiba', 'W32T' ],
'TS34' => [ 'Toshiba', 'W41T' ],
'TS35' => [ 'Toshiba', 'neon W42T' ],
'TS36' => [ 'Toshiba', 'W43T' ],
'TS37' => [ 'Toshiba', 'W44T' ],
'TS38' => [ 'Toshiba', 'W45T' ],
'TS39' => [ 'Toshiba', 'DRAPE W46T' ],
'TS3A' => [ 'Toshiba', 'W47T' ],
'TS3B' => [ 'Toshiba', 'W51T' ],
'TS3C' => [ 'Toshiba', 'W52T' ],
'TS3D' => [ 'Toshiba', 'W53T' ],
'TS3E' => [ 'Toshiba', 'W54T' ],
'TS3G' => [ 'Toshiba', 'W55T' ],
'TS3H' => [ 'Toshiba', 'W56T' ],
'TS3I' => [ 'Toshiba', 'W61T' ],
'TS3J' => [ 'Toshiba', 'W62T' ],
'TS3K' => [ 'Toshiba', 'Sportio W63T' ],
'TS3L' => [ 'Toshiba', 'W64T' ],
'TS3M' => [ 'Toshiba', 'W65T' ],
'TS3N' => [ 'Toshiba', 'T001' ],
'TS3O' => [ 'Toshiba', 'biblio TSY01' ],
'TS3P' => [ 'Toshiba', 'T002' ],
'TS3R' => [ 'Toshiba', 'T003' ],
'TS3S' => [ 'Toshiba', 'T004' ],
'TS3T' => [ 'Toshiba', 'E08T' ],
'TS3V' => [ 'Toshiba', 'T005' ],
'TS3X' => [ 'Toshiba', 'T006' ],
'TS3Y' => [ 'Toshiba', 'T008' ],
'TS3Z' => [ 'Toshiba', 'T007' ],
'TS41' => [ 'Toshiba', 'E09F' ],
'TSC1' => [ 'Toshiba', 'D302T' ],
'TSI1' => [ 'Toshiba', '701G' ],
'TST1' => [ 'Toshiba', 'TT01' ],
'TST2' => [ 'Toshiba', 'TT02' ],
'TST3' => [ 'Toshiba', 'TT03' ],
'TST4' => [ 'Toshiba', 'TT11' ],
'TST5' => [ 'Toshiba', 'TT21' ],
'TST6' => [ 'Toshiba', 'TT22' ],
'TST7' => [ 'Toshiba', 'TT31' ],
];
| {
"pile_set_name": "Github"
} |
#include "glfw-app.hpp"
#include "util.hpp"
#include "math-spatial.hpp"
#include "gl-api.hpp"
#include "stb/stb_image_write.h"
#include "human_time.hpp"
using namespace avl;
static InputEvent generate_input_event(GLFWwindow * window, InputEvent::Type type, const float2 & cursor, int action)
{
InputEvent e;
e.window = window;
e.type = type;
e.cursor = cursor;
e.action = action;
e.mods = 0;
glfwGetWindowSize(window, &e.windowSize.x, &e.windowSize.y);
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) | glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT)) e.mods |= GLFW_MOD_SHIFT;
if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) | glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL)) e.mods |= GLFW_MOD_CONTROL;
if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) | glfwGetKey(window, GLFW_KEY_RIGHT_ALT)) e.mods |= GLFW_MOD_ALT;
if (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) | glfwGetKey(window, GLFW_KEY_RIGHT_SUPER)) e.mods |= GLFW_MOD_SUPER;
return e;
}
static void s_error_callback(int error, const char * description)
{
std::cerr << description << std::endl;
}
#define CATCH_CURRENT app->exceptions.push_back(std::current_exception())
GLFWApp::GLFWApp(int width, int height, const std::string title, int glfwSamples, bool usingImgui)
{
if (!glfwInit())
::exit(EXIT_FAILURE);
glfwWindowHint(GLFW_DEPTH_BITS, 24);
glfwWindowHint(GLFW_STENCIL_BITS, 8);
glfwWindowHint(GLFW_SAMPLES, glfwSamples);
glfwWindowHint(GLFW_SRGB_CAPABLE, true);
#if defined(ANVIL_PLATFORM_OSX)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
#ifdef _DEBUG
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif
glfwSetErrorCallback(s_error_callback);
window = glfwCreateWindow(width, height, title.c_str(), NULL, NULL);
if (!window)
{
ANVIL_ERROR("Failed to open GLFW window");
glfwTerminate();
::exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
ANVIL_INFO("GL_VERSION = " << (char *)glGetString(GL_VERSION));
ANVIL_INFO("GL_VENDOR = " << (char *)glGetString(GL_VENDOR));
ANVIL_INFO("GL_RENDERER = " << (char *)glGetString(GL_RENDERER));
#if defined(ANVIL_PLATFORM_WINDOWS)
glewExperimental = GL_TRUE;
if (GLenum err = glewInit())
throw std::runtime_error(std::string("glewInit() failed - ") + (const char *)glewGetErrorString(err));
ANVIL_INFO("GLEW_VERSION = " << (char *)glewGetString(GLEW_VERSION));
#endif
std::vector<std::pair<std::string, bool>> extensions{
{ "GL_EXT_direct_state_access", false },
{ "GL_KHR_debug", false },
{ "GL_EXT_blend_equation_separate", false },
{ "GL_EXT_framebuffer_sRGB", false },
{ "GL_EXT_pixel_buffer_object", false },
};
has_gl_extension(extensions);
std::ostringstream ss;
ss << "Unsupported extensions: ";
bool anyUnsupported = false;
for (auto & e : extensions)
{
if (!e.second)
{
ss << ' ' << e.first;
anyUnsupported = true;
}
}
if (anyUnsupported) { throw std::runtime_error(ss.str()); }
#ifdef _DEBUG
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(&gl_debug_callback, nullptr);
#endif
glfwSetWindowUserPointer(window, this);
glfwSetWindowFocusCallback (window, [](GLFWwindow * window, int focused)
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window)); try { app->on_window_focus(!!focused);} catch(...) { CATCH_CURRENT; }
});
glfwSetWindowSizeCallback (window, [](GLFWwindow * window, int width, int height)
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window)); try { app->on_window_resize({width, height});} catch(...) { CATCH_CURRENT; }
});
glfwSetCharCallback (window, [](GLFWwindow * window, unsigned int codepoint)
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window)); try { app->consume_character(codepoint);} catch(...) { CATCH_CURRENT; }
});
glfwSetKeyCallback (window, [](GLFWwindow * window, int key, int, int action, int)
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window)); try { app->consume_key(key, action);} catch(...) { CATCH_CURRENT; }
});
glfwSetMouseButtonCallback (window, [](GLFWwindow * window, int button, int action, int)
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window)); try { app->consume_mousebtn(button, action);} catch(...) { CATCH_CURRENT; }
});
glfwSetCursorPosCallback (window, [](GLFWwindow * window, double xpos, double ypos)
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window)); try { app->consume_cursor(xpos, ypos);} catch(...) { CATCH_CURRENT; }
});
glfwSetScrollCallback (window, [](GLFWwindow * window, double deltaX, double deltaY)
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window)); try { app->consume_scroll(deltaX, deltaY); }
catch (...) { CATCH_CURRENT; }
});
glfwSetDropCallback (window, [](GLFWwindow * window, int count, const char * names[])
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window)); try { app->on_drop({names, names+count});} catch(...) { CATCH_CURRENT; }
});
/*
glfwSetWindowIconifyCallback(window, [](GLFWwindow * window, int)
{
auto app = (GLFWApp *)(glfwGetWindowUserPointer(window));
try
{
glfwMakeContextCurrent(window);
}
catch (...) { CATCH_CURRENT; }
});
*/
}
GLFWApp::~GLFWApp()
{
if (window) glfwDestroyWindow(window);
}
void GLFWApp::preprocess_input(InputEvent & event)
{
if (event.type == InputEvent::MOUSE)
{
if (event.is_down()) isDragging = true;
else if (event.is_up()) isDragging = false;
}
event.drag = isDragging;
on_input(event);
}
void GLFWApp::set_window_title(const std::string & str)
{
glfwSetWindowTitle(window, str.c_str());
}
void GLFWApp::consume_character(uint32_t codepoint)
{
auto e = generate_input_event(window, InputEvent::CHAR, get_cursor_position(), 0);
e.value[0] = codepoint;
preprocess_input(e);
}
void GLFWApp::consume_key(int key, int action)
{
auto e = generate_input_event(window, InputEvent::KEY, get_cursor_position(), action);
e.value[0] = key;
preprocess_input(e);
}
void GLFWApp::consume_mousebtn(int button, int action)
{
auto e = generate_input_event(window, InputEvent::MOUSE, get_cursor_position(), action);
e.value[0] = button;
preprocess_input(e);
}
void GLFWApp::consume_cursor(double xpos, double ypos)
{
auto e = generate_input_event(window, InputEvent::CURSOR, {(float)xpos, (float)ypos}, 0);
preprocess_input(e);
}
void GLFWApp::consume_scroll(double deltaX, double deltaY)
{
auto e = generate_input_event(window, InputEvent::SCROLL, get_cursor_position(), 0);
e.value[0] = (float) deltaX;
e.value[1] = (float) deltaY;
preprocess_input(e);
}
void GLFWApp::take_screenshot(const std::string & filename)
{
screenshotPath = filename;
}
void GLFWApp::take_screenshot_impl()
{
int width, height;
glfwGetWindowSize(window, &width, &height);
int2 size(width, height);
HumanTime t;
auto timestamp = t.make_timestamp();
std::vector<uint8_t> screenShot(size.x * size.y * 4);
glReadPixels(0, 0, size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, screenShot.data());
auto flipped = screenShot;
for (int y = 0; y < size.y; ++y) memcpy(flipped.data() + y * size.x * 4, screenShot.data() + (size.y - y - 1)*size.x * 4, size.x * 4);
stbi_write_png(std::string(screenshotPath + "-" + timestamp + ".png").c_str(), size.x, size.y, 4, flipped.data(), 4 * size.x);
screenshotPath.clear();
}
void GLFWApp::main_loop()
{
auto t0 = std::chrono::high_resolution_clock::now();
while (!glfwWindowShouldClose(window))
{
for (auto & e : exceptions) on_uncaught_exception(e);
try
{
auto t1 = std::chrono::high_resolution_clock::now();
auto timestep = std::chrono::duration<float>(t1 - t0).count();
t0 = t1;
elapsedFrames++;
fpsTime += timestep;
if (fpsTime > 0.5f)
{
fps = elapsedFrames / fpsTime;
elapsedFrames = 0;
fpsTime = 0;
}
UpdateEvent e;
e.elapsed_s = glfwGetTime();
e.timestep_ms = timestep;
e.framesPerSecond = fps;
e.elapsedFrames = elapsedFrames;
on_update(e);
on_draw();
if (screenshotPath.size() > 0)take_screenshot_impl();
glfwPollEvents();
}
catch(...)
{
on_uncaught_exception(std::current_exception());
}
}
}
void GLFWApp::on_uncaught_exception(std::exception_ptr e)
{
rethrow_exception(e);
}
float2 GLFWApp::get_cursor_position() const
{
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
return {(float)xpos, (float)ypos};
}
void GLFWApp::exit()
{
glfwSetWindowShouldClose(window, 1);
}
int GLFWApp::get_mods() const
{
int mods = 0;
if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) || glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL)) mods |= GLFW_MOD_CONTROL;
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT)) mods |= GLFW_MOD_SHIFT;
if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) || glfwGetKey(window, GLFW_KEY_RIGHT_ALT)) mods |= GLFW_MOD_ALT;
return mods;
}
namespace avl
{
int main(int argc, char * argv[])
{
int returnCode = EXIT_FAILURE;
try
{
if (!glfwInit())
throw std::runtime_error("glfwInit() failed.");
returnCode = main(argc, argv);
}
catch (const std::exception & e)
{
ANVIL_ERROR("[Fatal] Caught exception: \n" << e.what());
}
catch (...)
{
ANVIL_ERROR("[Fatal] Caught unknown exception.");
}
glfwTerminate();
return returnCode;
}
}
int get_current_monitor(GLFWwindow * window)
{
int numberOfMonitors;
GLFWmonitor** monitors = glfwGetMonitors(&numberOfMonitors);
int xW, yW;
glfwGetWindowPos(window, &xW, &yW);
for (int iC = 0; iC < numberOfMonitors; iC++)
{
int xM, yM;
glfwGetMonitorPos(monitors[iC], &xM, &yM);
const GLFWvidmode * desktopMode = glfwGetVideoMode(monitors[iC]);
Bounds2D monitorRect {(float) xM, (float) yM, (float)xM + desktopMode->width, (float)yM + desktopMode->height};
if (monitorRect.contains((float) xW, (float) yW))
return iC;
}
return 0;
}
int2 get_screen_size(GLFWwindow * window)
{
int numMonitors;
GLFWmonitor** monitors = glfwGetMonitors(&numMonitors);
if (numMonitors > 0)
{
int currentMonitor = get_current_monitor(window);
const GLFWvidmode * desktopMode = glfwGetVideoMode(monitors[currentMonitor]);
if (desktopMode)
return {desktopMode->width, desktopMode->height};
else
return {0, 0};
}
return {0, 0};
}
#if defined (ANVIL_PLATFORM_WINDOWS)
#undef APIENTRY
#define GLFW_EXPOSE_NATIVE_WIN32
#define GLFW_EXPOSE_NATIVE_WGL
#include <GLFW/glfw3native.h>
#include <shellapi.h>
void GLFWApp::enter_fullscreen(GLFWwindow * window, int2 & windowedSize, int2 & windowedPos)
{
glfwGetWindowSize(window, &windowedSize.x, &windowedSize.y);
glfwGetWindowPos(window, &windowedPos.x, &windowedPos.y);
HWND hwnd = glfwGetWin32Window(window);
SetWindowLong(hwnd, GWL_EXSTYLE, 0);
SetWindowLong(hwnd, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED | SWP_SHOWWINDOW);
int32_t newScreenWidth = get_screen_size(window).x;
int32_t newScreenHeight = get_screen_size(window).y;
int monitorCount;
GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
int currentMonitor = get_current_monitor(window);
int xpos, ypos;
glfwGetMonitorPos(monitors[currentMonitor], &xpos, &ypos);
SetWindowPos(hwnd, HWND_TOPMOST, xpos, ypos, (int) newScreenWidth, (int) newScreenHeight, SWP_SHOWWINDOW);
}
void GLFWApp::exit_fullscreen(GLFWwindow * window, const int2 & windowedSize, const int2 & windowedPos)
{
HWND hwnd = glfwGetWin32Window(window);
DWORD EX_STYLE = WS_EX_OVERLAPPEDWINDOW;
DWORD STYLE = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_SIZEBOX;
ChangeDisplaySettings(0, 0);
SetWindowLong(hwnd, GWL_EXSTYLE, EX_STYLE);
SetWindowLong(hwnd, GWL_STYLE, STYLE);
SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED | SWP_SHOWWINDOW);
// glfw/os bug: window shrinks by 4 pixels in x and y
glfwSetWindowPos(window, windowedPos.x - 2, windowedPos.y - 2);
glfwSetWindowSize(window, windowedSize.x + 4, windowedSize.y + 4);
}
#elif defined(ANVIL_PLATFORM_OSX)
#define GLFW_EXPOSE_NATIVE_COCOA
#define GLFW_EXPOSE_NATIVE_NSGL
#include "GLFW/glfw3native.h"
void GLFWApp::enter_fullscreen(GLFWwindow * window, int2 & windowedSize, int2 & windowedPos)
{
glfwGetWindowSize(window, &windowedSize.x, &windowedSize.y);
glfwGetWindowPos(window, &windowedPos.x, &windowedPos.y);
[NSApp setPresentationOptions:NSApplicationPresentationHideMenuBar | NSApplicationPresentationHideDock];
NSWindow * cocoaWindow = glfwGetCocoaWindow(window);
[cocoaWindow setStyleMask:NSBorderlessWindowMask];
int32_t newScreenWidth = get_screen_size(window).x;
int32_t newScreenHeight = get_screen_size(window).y;
int monitorCount;
GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
int currentMonitor = get_current_monitor(window);
int xpos, ypos;
glfwGetMonitorPos(monitors[currentMonitor], &xpos, &ypos);
glfwSetWindowSize(window, newScreenWidth, newScreenHeight);
glfwSetWindowPos(window, windowedPos.x, windowedPos.y);
[cocoaWindow makeFirstResponder:cocoaWindow.contentView];
}
void GLFWApp::exit_fullscreen(GLFWwindow * window, const int2 & windowedSize, const int2 & windowedPos)
{
[NSApp setPresentationOptions:NSApplicationPresentationDefault];
NSWindow * cocoaWindow = glfwGetCocoaWindow(window);
[cocoaWindow setStyleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask];
[cocoaWindow makeFirstResponder:cocoaWindow.contentView];
glfwSetWindowPos(window, windowedPos.x, windowedPos.y);
glfwSetWindowSize(window, windowedSize.x, windowedSize.y);
}
#endif // end platform specific | {
"pile_set_name": "Github"
} |
version https://git-lfs.github.com/spec/v1
oid sha256:c536e679ee4db86511a04e0330a87edae69e41350d356a80d982c4f1888c1aba
size 196608000
| {
"pile_set_name": "Github"
} |
/* Find the correct compiler.
Copyright (C) 2014-2019 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef CC1_PLUGIN_FINDCOMP_HH
#define CC1_PLUGIN_FINDCOMP_HH
extern bool find_compiler (const regex_t ®exp, std::string *result);
#endif // CC1_PLUGIN_FINDCOMP_HH
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>4.1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
import pytest
def test_private_test(get_contract_with_gas_estimation):
private_test_code = """
@internal
def a() -> int128:
return 5
@external
def returnten() -> int128:
return self.a() * 2
"""
c = get_contract_with_gas_estimation(private_test_code)
assert c.returnten() == 10
def test_private_with_more_vars(get_contract):
private_test_code = """
@internal
def afunc() -> int128:
a: int128 = 4
b: int128 = 40
c: int128 = 400
return a + b + c
@external
def return_it() -> int128:
a: int128 = 111
b: int128 = 222
c: int128 = self.afunc()
assert a == 111
assert b == 222
assert c == 444
return a + b + c
"""
c = get_contract(private_test_code)
assert c.return_it() == 777
def test_private_with_more_vars_nested(get_contract_with_gas_estimation):
private_test_code = """
@internal
def more() -> int128:
a: int128 = 50
b: int128 = 50
c: int128 = 11
return a + b + c
@internal
def afunc() -> int128:
a: int128 = 444
a += self.more()
assert a == 555
return a + self.more()
@external
def return_it() -> int128:
a: int128 = 222
b: int128 = 111
c: int128 = self.afunc()
assert a == 222
assert b == 111
return a + b + c
"""
c = get_contract_with_gas_estimation(private_test_code)
assert c.return_it() == 999
def test_private_with_args(get_contract_with_gas_estimation):
private_test_code = """
@internal
def add_times2(a: uint256, b: uint256) -> uint256:
assert a == 100
assert b == 11
return 2 * (a + b)
@external
def return_it() -> uint256:
a: uint256 = 111
b: uint256 = 222
c: uint256 = self.add_times2(100, 11)
return a + b + c
"""
c = get_contract_with_gas_estimation(private_test_code)
assert c.return_it() == 555
def test_private_with_args_nested(get_contract_with_gas_estimation):
private_test_code = """
@internal
def multiply(a: uint256, b: uint256) -> uint256:
c: uint256 = 7
d: uint256 = 8
e: uint256 = 9
return a * b
@internal
def add_times2(a: uint256, b: uint256) -> uint256:
return self.multiply(3, (a + b))
@external
def return_it() -> uint256:
a: uint256 = 111
b: uint256 = 222
c: uint256 = self.add_times2(0, a)
return a + b + c
"""
c = get_contract_with_gas_estimation(private_test_code)
assert c.return_it() == 666
def test_private_bytes(get_contract_with_gas_estimation):
private_test_code = """
greeting: public(Bytes[100])
@external
def __init__():
self.greeting = b"Hello "
@internal
def construct(greet: Bytes[100]) -> Bytes[200]:
return concat(self.greeting, greet)
@external
def hithere(name: Bytes[100]) -> Bytes[200]:
d: Bytes[200] = self.construct(name)
return d
"""
c = get_contract_with_gas_estimation(private_test_code)
assert c.hithere(b"bob") == b"Hello bob"
assert c.hithere(b"alice") == b"Hello alice"
def test_private_statement(get_contract_with_gas_estimation):
private_test_code = """
greeting: public(Bytes[20])
@external
def __init__():
self.greeting = b"Hello "
@internal
def set_greeting(_greeting: Bytes[20]):
a: uint256 = 332
b: uint256 = 333
c: uint256 = 334
d: uint256 = 335
if a + b + c + d + 3 == 1337:
self.greeting = _greeting
@internal
@view
def construct(greet: Bytes[20]) -> Bytes[40]:
return concat(self.greeting, greet)
@external
def iprefer(_greeting: Bytes[20]):
a: uint256 = 112
b: uint256 = 211
self.set_greeting(_greeting)
assert a == 112
assert b == 211
@external
def hithere(name: Bytes[20]) -> Bytes[40]:
d: Bytes[40] = self.construct(name)
return d
"""
c = get_contract_with_gas_estimation(private_test_code)
assert c.greeting() == b"Hello "
assert c.hithere(b"Bob") == b"Hello Bob"
c.iprefer(b"Hi there, ", transact={})
assert c.hithere(b"Alice") == b"Hi there, Alice"
def test_private_default_parameter(get_contract_with_gas_estimation):
private_test_code = """
@internal
def addition(a: uint256, b: uint256 = 1) -> uint256:
return a + b
@external
def add_one(a: uint256) -> uint256:
return self.addition(a)
@external
def added(a: uint256, b: uint256) -> uint256:
a_before: uint256 = a
b_before: uint256 = b
c: int128 = 333
d: uint256 = self.addition(a, b)
assert c == 333
assert a_before == a
assert b_before == b
return d
"""
c = get_contract_with_gas_estimation(private_test_code)
assert c.add_one(20) == 21
assert c.added(10, 20) == 30
def test_private_return_bytes(get_contract_with_gas_estimation):
code = """
a_message: Bytes[50]
@internal
def _test() -> (Bytes[100]):
b: Bytes[50] = b"hello 1 2"
return b
@internal
def _test_b(a: Bytes[100]) -> (Bytes[100]):
b: Bytes[50] = b"hello there"
if len(a) > 1:
return a
else:
return b
@internal
def get_msg() -> (Bytes[100]):
return self.a_message
@external
def test() -> (Bytes[100]):
d: Bytes[100] = b""
d = self._test()
return d
@external
def test2() -> (Bytes[100]):
d: Bytes[100] = b'xyzxyzxyzxyz'
return self._test()
@external
def test3(a: Bytes[50]) -> (Bytes[100]):
d: Bytes[100] = b'xyzxyzxyzxyz'
return self._test_b(a)
@external
def set(a: Bytes[50]):
self.a_message = a
@external
def test4() -> (Bytes[100]):
d: Bytes[100] = b'xyzxyzxyzxyz'
return self.get_msg()
"""
c = get_contract_with_gas_estimation(code)
test_str = b" 1 2"
assert c.test() == b"hello" + test_str
assert c.test2() == b"hello" + test_str
assert c.test3(b"alice") == b"alice"
c.set(b"hello daar", transact={})
assert c.test4() == b"hello daar"
def test_private_bytes_as_args(get_contract_with_gas_estimation):
code = """
@internal
def _test(a: Bytes[40]) -> (Bytes[100]):
b: Bytes[40] = b"hello "
return concat(b, a)
@external
def test(a: Bytes[10]) -> Bytes[100]:
b: Bytes[40] = concat(a, b", jack attack")
out: Bytes[100] = self._test(b)
return out
@external
def test2() -> Bytes[100]:
c: Bytes[10] = b"alice"
return self._test(c)
"""
c = get_contract_with_gas_estimation(code)
assert c.test(b"bob") == b"hello bob, jack attack"
assert c.test2() == b"hello alice"
def test_private_return_tuple_base_types(get_contract_with_gas_estimation):
code = """
@internal
def _test(a: bytes32) -> (bytes32, uint256, int128):
b: uint256 = 1000
return a, b, -1200
@external
def test(a: bytes32) -> (bytes32, uint256, int128):
b: uint256 = 1
c: int128 = 1
d: int128 = 123
f: bytes32 = EMPTY_BYTES32
f, b, c = self._test(a)
assert d == 123
return f, b, c
@external
def test2(a: bytes32) -> (bytes32, uint256, int128):
return self._test(a)
"""
c = get_contract_with_gas_estimation(code)
assert c.test(b"test") == [b"test" + 28 * b"\x00", 1000, -1200]
assert c.test2(b"test") == [b"test" + 28 * b"\x00", 1000, -1200]
def test_private_return_tuple_bytes(get_contract_with_gas_estimation):
code = """
@internal
def _test(a: int128, b: Bytes[50]) -> (int128, Bytes[100]):
return a + 2, concat(b"badabing:", b)
@internal
def _test_combined(a: Bytes[50], x: int128, c:Bytes[50]) -> (int128, Bytes[100], Bytes[100]):
assert x == 8
return x + 2, a, concat(c, b'_two')
@external
def test(a: int128, b: Bytes[40]) -> (int128, Bytes[100], Bytes[50]):
c: int128 = 1
x: Bytes[50] = concat(b, b"_one")
d: Bytes[100] = b""
c, d = self._test(a + c, x)
return c, d, x
@external
def test2(b: Bytes[40]) -> (int128, Bytes[100]):
a: int128 = 4
x: Bytes[50] = concat(b, b"_one")
d: Bytes[100] = b""
return self._test(a, x)
@external
def test3(a: Bytes[32]) -> (int128, Bytes[100], Bytes[100]):
q: Bytes[100] = b"random data1"
w: Bytes[100] = b"random data2"
x: int128 = 8
b: Bytes[32] = a
x, q, w = self._test_combined(a, x, b)
return x, q, w
@external
def test4(a: Bytes[40]) -> (int128, Bytes[100], Bytes[100]):
b: Bytes[50] = concat(a, b"_one")
return self._test_combined(a, 8, b)
"""
c = get_contract_with_gas_estimation(code)
assert c.test(11, b"jill") == [14, b"badabing:jill_one", b"jill_one"]
assert c.test2(b"jack") == [6, b"badabing:jack_one"]
assert c.test3(b"hill") == [10, b"hill", b"hill_two"]
assert c.test4(b"bucket") == [10, b"bucket", b"bucket_one_two"]
def test_private_return_list_types(get_contract_with_gas_estimation):
code = """
@internal
def _test(b: int128[4]) -> int128[4]:
assert b[1] == 2
assert b[2] == 3
assert b[3] == 4
return [0, 1, 0, 1]
@external
def test() -> int128[4]:
b: int128[4] = [1, 2, 3, 4]
c: int128[2] = [11, 22]
return self._test(b)
"""
c = get_contract_with_gas_estimation(code)
assert c.test() == [0, 1, 0, 1]
def test_private_payable(w3, get_contract_with_gas_estimation):
code = """
@internal
def _send_it(a: address, _value: uint256):
send(a, _value)
@payable
@external
def test(doit: bool, a: address, _value: uint256):
self._send_it(a, _value)
@external
@payable
def __default__():
pass
"""
c = get_contract_with_gas_estimation(code)
w3.eth.sendTransaction({"to": c.address, "value": w3.toWei(1, "ether")})
assert w3.eth.getBalance(c.address) == w3.toWei(1, "ether")
a3 = w3.eth.accounts[2]
assert w3.eth.getBalance(a3) == w3.toWei(1000000, "ether")
c.test(True, a3, w3.toWei(0.05, "ether"), transact={})
assert w3.eth.getBalance(a3) == w3.toWei(1000000.05, "ether")
assert w3.eth.getBalance(c.address) == w3.toWei(0.95, "ether")
def test_private_msg_sender(get_contract, assert_compile_failed):
code = """
@internal
def _whoami() -> address:
return msg.sender
"""
assert_compile_failed(lambda: get_contract(code))
def test_nested_static_params_only(get_contract, assert_tx_failed):
code1 = """
@internal
@view
def c() -> bool:
return True
@internal
@view
def b(sender: address) -> address:
assert self.c()
return sender
@external
def a() -> bool:
assert self.b(msg.sender) == msg.sender
return True
"""
code2 = """
@internal
@view
def c(sender: address) -> address:
return sender
@internal
@view
def b(sender: address) -> address:
return self.c(sender)
@external
def a() -> bool:
assert self.b(msg.sender) == msg.sender
return True
"""
c1 = get_contract(code1)
c2 = get_contract(code2)
assert c1.a() is True
assert c2.a() is True
def test_private_nested_if_return(get_contract):
code = """
@internal
def _test(z: int128) -> bool:
y: int128 = 1
if (z <= 0):
return True
else:
y = 2
return False
@external
def test(z: int128) -> bool:
return self._test(z)
"""
c = get_contract(code)
assert c.test(-1) is True
assert c.test(0) is True
assert c.test(1) is False
def test_private_call_expr(get_contract):
code = """
test: public(bool)
@internal
def foo():
self.test = True
@external
def start():
if True:
self.foo()
"""
c = get_contract(code)
assert c.test() is False
c.start(transact={})
assert c.test() is True
def test_private_array_param(get_contract):
code = """
@internal
def change_arr(arr: int128[2]):
pass
@external
def call_arr() -> int128:
a: int128[2] = [0, 0] # test with zeroed arg
self.change_arr(a)
return 42
"""
c = get_contract(code)
assert c.call_arr() == 42
def test_private_zero_bytearray(get_contract):
private_test_code = """
@internal
def inner(xs: Bytes[256]):
pass
@external
def outer(xs: Bytes[256] = b"") -> bool:
self.inner(xs)
return True
"""
c = get_contract(private_test_code)
assert c.outer()
tuple_return_sources = [
(
"""
@internal
def _test(a: int128) -> (int128, int128):
return a + 2, 2
@external
def foo(a: int128) -> (int128, int128):
return self._test(a)
""",
(11,),
[13, 2],
),
(
"""
struct A:
many: uint256[4]
one: uint256
@internal
def _foo(_many: uint256[4], _one: uint256) -> A:
return A({many: _many, one: _one})
@external
def foo() -> A:
return self._foo([1, 2, 3, 4], 5)
""",
(),
[[1, 2, 3, 4], 5],
),
(
"""
struct A:
many: uint256[4]
one: uint256
@internal
def _foo(_many: uint256[4], _one: uint256) -> A:
return A({many: _many, one: _one})
@external
def foo() -> (uint256[4], uint256):
out: A = self._foo([1, 2, 3, 4], 5)
return out.many, out.one
""",
(),
[[1, 2, 3, 4], 5],
),
(
"""
@internal
def _foo() -> (uint256[2], uint256[2]):
return [1, 2], [5, 6]
@external
def foo() -> (uint256[2], uint256[2], uint256[2]):
return self._foo()[0], [3, 4], self._foo()[1]
""",
(),
[[1, 2], [3, 4], [5, 6]],
),
(
"""
@internal
def _foo(a: int128, b: int128[3], c: int128[3]) -> (int128[3], int128, int128[3]):
return c, 4, [b[1], a, b[0]]
@external
def foo(a: int128, b: int128[3], c: int128[3]) -> (int128[3], int128, int128[3]):
return self._foo(a, b, c)
""",
(6, [7, 5, 8], [1, 2, 3]),
[[1, 2, 3], 4, [5, 6, 7]],
),
(
"""
@internal
def _foo(a: int128, b: int128[3], c: int128[3]) -> (int128[3], int128, int128[3]):
return c, 4, [b[1], a, b[0]]
@external
def foo(a: int128, b: int128[3], c: int128[3]) -> (int128[3], int128, int128[3]):
return c, 4, self._foo(a, b, c)[2]
""",
(6, [7, 5, 8], [1, 2, 3]),
[[1, 2, 3], 4, [5, 6, 7]],
),
]
@pytest.mark.parametrize("source_code,args,expected", tuple_return_sources)
def test_tuple_return_types(get_contract, source_code, args, expected):
c = get_contract(source_code)
assert c.foo(*args) == expected
| {
"pile_set_name": "Github"
} |
---
title: Ansible Operator Watches
linkTitle: Watches
weight: 20
---
The Watches file contains a list of mappings from custom resources, identified
by it's Group, Version, and Kind, to an Ansible Role or Playbook. The Operator
expects this mapping file in a predefined location: `/opt/ansible/watches.yaml`
These resources, as well as child resources (determined by owner references) will
be monitored for updates and cached.
* **group**: The group of the Custom Resource that you will be watching.
* **version**: The version of the Custom Resource that you will be watching.
* **kind**: The kind of the Custom Resource that you will be watching.
* **role** (default): Specifies a role to be executed. This field is mutually exclusive with the
"playbook" field. This field can be:
* an absolute path to a role directory.
* a relative path within one of the directories specified by `ANSIBLE_ROLES_PATH` environment variable or `ansible-roles-path` flag.
* a relative path within the current working directory, which defaults to `/opt/ansible/roles`.
* a fully qualified collection name of an installed Ansible collection. Ansible collections are installed to
`~/.ansible/collections` or `/usr/share/ansible/collections` by default. If they are installed elsewhere,
use the `ANSIBLE_COLLECTIONS_PATH` environment variable or the `ansible-collections-path` flag
* **playbook**: This is the playbook name that you have added to the
container. This playbook is expected to be simply a way to call roles. This
field is mutually exclusive with the "role" field. When running locally, the playbook is expected to be in the
current project directory.
* **vars**: This is an arbitrary map of key-value pairs. The contents will be
passed as `extra_vars` to the playbook or role specified for this watch.
* **reconcilePeriod** (optional): The maximum interval in seconds that the operator will wait before beginning another reconcile, even if no watched events are received. When an operator watches many resources, each reconcile can become expensive, and a low value here can actually reduce performance. Typically, this option should only be used in advanced use cases where `watchDependentResources` is set to `False` and when is not possible to use the watch feature. E.g To managing external resources that don’t raise Kubernetes events.
* **manageStatus** (optional): When true (default), the operator will manage
the status of the CR generically. Set to false, the status of the CR is
managed elsewhere, by the specified role/playbook or in a separate controller.
* **blacklist**: A list of child resources (by GVK) that will not be watched or cached.
An example Watches file:
```yaml
---
# Simple example mapping Foo to the Foo role
- version: v1alpha1
group: foo.example.com
kind: Foo
role: Foo
# Simple example mapping Bar to a playbook
- version: v1alpha1
group: bar.example.com
kind: Bar
playbook: playbook.yml
# More complex example for our Baz kind
# Here we will disable requeuing and be managing the CR status in the playbook,
# and specify additional variables.
- version: v1alpha1
group: baz.example.com
kind: Baz
playbook: baz.yml
reconcilePeriod: 0
manageStatus: False
vars:
foo: bar
# ConfigMaps owned by a Memcached CR will not be watched or cached.
- version: v1alpha1
group: cache.example.com
kind: Memcached
role: /opt/ansible/roles/memcached
blacklist:
- group: ""
version: v1
kind: ConfigMap
# Example usage with a role from an installed Ansible collection
- version: v1alpha1
group: bar.example.com
kind: Bar
role: myNamespace.myCollection.myRole
# Example filtering of resources with specific labels
- version: v1alpha1
group: bar.example.com
kind: Bar
playbook: playbook.yml
selector:
matchLabels:
foo: bar
matchExpressions:
- {key: foo, operator: In, values: [bar]}
- {key: baz, operator: Exists, values: []}
```
The advanced features can be enabled by adding them to your watches file per GVK.
They can go below the `group`, `version`, `kind` and `playbook` or `role`.
Some features can be overridden per resource via an annotation on that CR. The options that are overridable will have the annotation specified below.
| Feature | Yaml Key | Description| Annotation for override | default | Documentation |
|---------|----------|------------|-------------------------|---------|---------------|
| Reconcile Period | `reconcilePeriod` | time between reconcile runs for a particular CR | ansible.sdk.operatorframework.io/reconcile-period | 1m | |
| Manage Status | `manageStatus` | Allows the ansible operator to manage the conditions section of each resource's status section. | | true | |
| Watching Dependent Resources | `watchDependentResources` | Allows the ansible operator to dynamically watch resources that are created by ansible | | true | [dependent watches](../dependent-watches) |
| Watching Cluster-Scoped Resources | `watchClusterScopedResources` | Allows the ansible operator to watch cluster-scoped resources that are created by ansible | | false | |
| Max Runner Artifacts | `maxRunnerArtifacts` | Manages the number of [artifact directories](https://ansible-runner.readthedocs.io/en/latest/intro.html#runner-artifacts-directory-hierarchy) that ansible runner will keep in the operator container for each individual resource. | ansible.sdk.operatorframework.io/max-runner-artifacts | 20 | |
| Finalizer | `finalizer` | Sets a finalizer on the CR and maps a deletion event to a playbook or role | | | [finalizers](../finalizers)|
| Selector | `selector` | Identifies a set of objects based on their labels | | None Applied | [Labels and Selectors](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/)|
| Automatic Case Conversion | `snakeCaseParameters` | Determines whether to convert the CR spec from camelCase to snake_case before passing the contents to Ansible as extra_vars| | true | |
#### Example
```YaML
---
- version: v1alpha1
group: app.example.com
kind: AppService
playbook: playbook.yml
maxRunnerArtifacts: 30
reconcilePeriod: 5s
manageStatus: False
watchDependentResources: False
snakeCaseParameters: False
finalizer:
name: finalizer.app.example.com
vars:
state: absent
```
**Note:** By using the command `operator-sdk add api` you are able to add additional CRDs to the project API, which can aid in designing your solution using concepts such as encapsulation, single responsibility principle, and cohesion, which could make the project easier to read, debug, and maintain. With this approach, you are able to customize and optimize the configurations more specifically per GKV via the `watches.yaml` file.
**Example:**
```YaML
---
- version: v1alpha1
group: app.example.com
kind: AppService
playbook: playbook.yml
maxRunnerArtifacts: 30
reconcilePeriod: 5s
manageStatus: False
watchDependentResources: False
finalizer:
name: finalizer.app.example.com
vars:
state: absent
- version: v1alpha1
group: app.example.com
kind: Database
playbook: playbook.yml
watchDependentResources: True
manageStatus: True
```
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015-2019 Alexandr Evstigneev
*
* 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.perl5.lang.perl.psi.mro;
public enum PerlMroType {
DFS,
C3
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 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.
*/
/*
* Do not modify this file. This file is generated from the imagebuilder-2019-12-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Imagebuilder.Model
{
/// <summary>
/// Container for the parameters to the ImportComponent operation.
/// Imports a component and transforms its data into a component document.
/// </summary>
public partial class ImportComponentRequest : AmazonImagebuilderRequest
{
private string _changeDescription;
private string _clientToken;
private string _data;
private string _description;
private ComponentFormat _format;
private string _kmsKeyId;
private string _name;
private Platform _platform;
private string _semanticVersion;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
private ComponentType _type;
private string _uri;
/// <summary>
/// Gets and sets the property ChangeDescription.
/// <para>
/// The change description of the component. Describes what change has been made in this
/// version, or what makes this version different from other versions of this component.
///
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string ChangeDescription
{
get { return this._changeDescription; }
set { this._changeDescription = value; }
}
// Check to see if ChangeDescription property is set
internal bool IsSetChangeDescription()
{
return this._changeDescription != null;
}
/// <summary>
/// Gets and sets the property ClientToken.
/// <para>
/// The idempotency token of the component.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=36)]
public string ClientToken
{
get { return this._clientToken; }
set { this._clientToken = value; }
}
// Check to see if ClientToken property is set
internal bool IsSetClientToken()
{
return this._clientToken != null;
}
/// <summary>
/// Gets and sets the property Data.
/// <para>
/// The data of the component. Used to specify the data inline. Either <code>data</code>
/// or <code>uri</code> can be used to specify the data within the component.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string Data
{
get { return this._data; }
set { this._data = value; }
}
// Check to see if Data property is set
internal bool IsSetData()
{
return this._data != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the component. Describes the contents of the component.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property Format.
/// <para>
/// The format of the resource that you want to import as a component.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public ComponentFormat Format
{
get { return this._format; }
set { this._format = value; }
}
// Check to see if Format property is set
internal bool IsSetFormat()
{
return this._format != null;
}
/// <summary>
/// Gets and sets the property KmsKeyId.
/// <para>
/// The ID of the KMS key that should be used to encrypt this component.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string KmsKeyId
{
get { return this._kmsKeyId; }
set { this._kmsKeyId = value; }
}
// Check to see if KmsKeyId property is set
internal bool IsSetKmsKeyId()
{
return this._kmsKeyId != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the component.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Platform.
/// <para>
/// The platform of the component.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public Platform Platform
{
get { return this._platform; }
set { this._platform = value; }
}
// Check to see if Platform property is set
internal bool IsSetPlatform()
{
return this._platform != null;
}
/// <summary>
/// Gets and sets the property SemanticVersion.
/// <para>
/// The semantic version of the component. This version follows the semantic version syntax.
/// For example, major.minor.patch. This could be versioned like software (2.0.1) or like
/// a date (2019.12.01).
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string SemanticVersion
{
get { return this._semanticVersion; }
set { this._semanticVersion = value; }
}
// Check to see if SemanticVersion property is set
internal bool IsSetSemanticVersion()
{
return this._semanticVersion != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// The tags of the component.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=50)]
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property Type.
/// <para>
/// The type of the component denotes whether the component is used to build the image
/// or only to test it.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public ComponentType Type
{
get { return this._type; }
set { this._type = value; }
}
// Check to see if Type property is set
internal bool IsSetType()
{
return this._type != null;
}
/// <summary>
/// Gets and sets the property Uri.
/// <para>
/// The uri of the component. Must be an S3 URL and the requester must have permission
/// to access the S3 bucket. If you use S3, you can specify component content up to your
/// service quota. Either <code>data</code> or <code>uri</code> can be used to specify
/// the data within the component.
/// </para>
/// </summary>
public string Uri
{
get { return this._uri; }
set { this._uri = value; }
}
// Check to see if Uri property is set
internal bool IsSetUri()
{
return this._uri != null;
}
}
} | {
"pile_set_name": "Github"
} |
import React from 'react';
import TodoItem from '../TodoItem';
import { storiesOf, action } from '@kadira/storybook';
storiesOf('TodoItem', module)
.add('not completed', () => {
const todo = {
id: 'the-id',
text: 'Hello Todo',
completed: false
};
return getItem(todo);
})
.add('completed', () => {
const todo = {
id: 'the-id',
text: 'Hello Todo',
completed: true
};
return getItem(todo);
});
function getItem(todo) {
return (
<div className="todoapp">
<div className="todo-list">
<TodoItem
todo={todo}
editTodo={action('editTodo')}
deleteTodo={action('deleteTodo')}
completeTodo={action('completeTodo')}/>
</div>
</div>
);
}
| {
"pile_set_name": "Github"
} |
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"github.com/folbricht/desync"
"github.com/spf13/cobra"
)
type untarOptions struct {
cmdStoreOptions
desync.LocalFSOptions
stores []string
cache string
readIndex bool
outFormat string
}
func newUntarCommand(ctx context.Context) *cobra.Command {
var opt untarOptions
cmd := &cobra.Command{
Use: "untar <catar|index> <target>",
Short: "Extract directory tree from a catar archive or index",
Long: `Extracts a directory tree from a catar file or an index. Use '-' to read the
index from STDIN.
The input is either a catar archive, or a caidx index file (with -i and -s).
By default, the catar archive is extracted to local disk. Using --output-format=gnu-tar,
the output can be set to GNU tar, either an archive or STDOUT with '-'.
`,
Example: ` desync untar docs.catar /tmp/documents
desync untar -s http://192.168.1.1/ -c /path/to/local -i docs.caidx /tmp/documents`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return runUntar(ctx, opt, args)
},
SilenceUsage: true,
}
flags := cmd.Flags()
flags.StringSliceVarP(&opt.stores, "store", "s", nil, "source store(s), used with -i")
flags.StringVarP(&opt.cache, "cache", "c", "", "store to be used as cache")
flags.BoolVarP(&opt.readIndex, "index", "i", false, "read index file (caidx), not catar")
flags.BoolVar(&opt.NoSameOwner, "no-same-owner", false, "extract files as current user")
flags.BoolVar(&opt.NoSamePermissions, "no-same-permissions", false, "use current user's umask instead of what is in the archive")
flags.StringVar(&opt.outFormat, "output-format", "disk", "output format, 'disk' or 'gnu-tar'")
addStoreOptions(&opt.cmdStoreOptions, flags)
return cmd
}
func runUntar(ctx context.Context, opt untarOptions, args []string) error {
if err := opt.cmdStoreOptions.validate(); err != nil {
return err
}
if opt.readIndex && len(opt.stores) == 0 {
return errors.New("-i requires at least one store (-s <location>)")
}
input := args[0]
target := args[1]
// Prepare output
var (
fs desync.FilesystemWriter
err error
)
switch opt.outFormat {
case "disk": // Local filesystem
fs = desync.NewLocalFS(target, opt.LocalFSOptions)
case "gnu-tar": // GNU tar, either file or STDOUT
var w *os.File
if target == "-" {
w = os.Stdout
} else {
w, err = os.Create(target)
if err != nil {
return err
}
defer w.Close()
}
gtar := desync.NewTarWriter(w)
defer gtar.Close()
fs = gtar
default:
return fmt.Errorf("invalid output format '%s'", opt.outFormat)
}
// If we got a catar file unpack that and exit
if !opt.readIndex {
f, err := os.Open(input)
if err != nil {
return err
}
defer f.Close()
var r io.Reader = f
pb := NewProgressBar("Unpacking ")
if pb != nil {
// Get the file size to initialize the progress bar
info, err := f.Stat()
if err != nil {
return err
}
pb.Start()
defer pb.Finish()
pb.SetTotal(int(info.Size()))
r = io.TeeReader(f, pb)
}
return desync.UnTar(ctx, r, fs)
}
s, err := MultiStoreWithCache(opt.cmdStoreOptions, opt.cache, opt.stores...)
if err != nil {
return err
}
defer s.Close()
// Apparently the input must be an index, read it whole
index, err := readCaibxFile(input, opt.cmdStoreOptions)
if err != nil {
return err
}
return desync.UnTarIndex(ctx, fs, index, s, opt.n, NewProgressBar("Unpacking "))
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <objc/NSObject.h>
__attribute__((visibility("hidden")))
@interface VTKColor : NSObject
{
}
+ (id)colorWithRed:(double)arg1 green:(double)arg2 blue:(double)arg3 alpha:(double)arg4;
@end
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the `liip/LiipImagineBundle` project.
*
* (c) https://github.com/liip/LiipImagineBundle/graphs/contributors
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
namespace Liip\ImagineBundle\Imagine\Filter\Loader;
use Imagine\Image\ImageInterface;
class InterlaceFilterLoader implements LoaderInterface
{
/**
* {@inheritdoc}
*/
public function load(ImageInterface $image, array $options = [])
{
$mode = ImageInterface::INTERLACE_LINE;
if (!empty($options['mode'])) {
$mode = $options['mode'];
}
$image->interlace($mode);
return $image;
}
}
| {
"pile_set_name": "Github"
} |
body {
padding: 20px 0 0 20px;
cursor: pointer;
}
#field {
overflow: hidden;
width: 200px;
height: 150px;
border-top: 10px solid black;
border-right: 10px solid gray;
border-bottom: 10px solid gray;
border-left: 10px solid black;
background-color: #00FF00;
font: 10px/1.2 monospace;
}
.triangle-right {
position: relative;
width: 0;
height: 0;
border-top: 6px solid transparent;
border-bottom: 6px solid transparent;
border-left: 20px solid red;
text-indent: -20px;
font: 12px/1 monospace;
} | {
"pile_set_name": "Github"
} |
/*
* Copyright 2017-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.dataflow.server.service.impl;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.cloud.dataflow.audit.service.AuditRecordService;
import org.springframework.cloud.dataflow.configuration.metadata.BootApplicationConfigurationMetadataResolver;
import org.springframework.cloud.dataflow.configuration.metadata.container.ContainerImageMetadataResolver;
import org.springframework.cloud.dataflow.core.ApplicationType;
import org.springframework.cloud.dataflow.core.AuditActionType;
import org.springframework.cloud.dataflow.core.AuditOperationType;
import org.springframework.cloud.dataflow.core.DefaultStreamDefinitionService;
import org.springframework.cloud.dataflow.core.StreamDefinition;
import org.springframework.cloud.dataflow.core.StreamDeployment;
import org.springframework.cloud.dataflow.registry.service.AppRegistryService;
import org.springframework.cloud.dataflow.rest.SkipperStream;
import org.springframework.cloud.dataflow.server.config.apps.CommonApplicationProperties;
import org.springframework.cloud.dataflow.server.controller.support.InvalidStreamDefinitionException;
import org.springframework.cloud.dataflow.server.repository.StreamDefinitionRepository;
import org.springframework.cloud.dataflow.server.service.impl.validation.DefaultStreamValidationService;
import org.springframework.cloud.dataflow.server.stream.SkipperStreamDeployer;
import org.springframework.cloud.dataflow.server.stream.StreamDeploymentRequest;
import org.springframework.cloud.dataflow.server.support.TestResourceUtils;
import org.springframework.cloud.deployer.spi.app.DeploymentState;
import org.springframework.cloud.deployer.spi.core.AppDeploymentRequest;
import org.springframework.cloud.skipper.domain.Deployer;
import org.springframework.cloud.skipper.domain.Manifest;
import org.springframework.cloud.skipper.domain.Release;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StreamUtils;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* @author Ilayaperumal Gopinathan
* @author Eric Bottard
* @author Christian Tzolov
* @author Gunnar Hillert
* @author Chris Schaefer
*/
@RunWith(SpringRunner.class)
public class DefaultStreamServiceTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
private StreamDefinition streamDefinition1 = new StreamDefinition("test1", "time | log");
private StreamDefinition streamDefinition2 = new StreamDefinition("test2", "time | log");
private StreamDefinitionRepository streamDefinitionRepository;
private SkipperStreamDeployer skipperStreamDeployer;
private AppDeploymentRequestCreator appDeploymentRequestCreator;
private DefaultStreamService defaultStreamService;
private AppRegistryService appRegistryService;
private AuditRecordService auditRecordService;
private DefaultStreamValidationService streamValidationService;
@Before
public void setupMock() {
this.streamDefinitionRepository = mock(StreamDefinitionRepository.class);
this.skipperStreamDeployer = mock(SkipperStreamDeployer.class);
this.appRegistryService = mock(AppRegistryService.class);
this.auditRecordService = mock(AuditRecordService.class); // FIXME
this.appDeploymentRequestCreator = new AppDeploymentRequestCreator(this.appRegistryService,
mock(CommonApplicationProperties.class),
new BootApplicationConfigurationMetadataResolver(mock(ContainerImageMetadataResolver.class)),
new DefaultStreamDefinitionService());
this.streamValidationService = mock(DefaultStreamValidationService.class);
this.defaultStreamService = new DefaultStreamService(streamDefinitionRepository,
this.skipperStreamDeployer, this.appDeploymentRequestCreator, this.streamValidationService,
this.auditRecordService, new DefaultStreamDefinitionService());
when(streamDefinitionRepository.findById("test2")).thenReturn(Optional.of(streamDefinition2));
}
@Test
public void createStream() {
when(this.streamValidationService.isRegistered("time", ApplicationType.source)).thenReturn(true);
when(this.streamValidationService.isRegistered("log", ApplicationType.sink)).thenReturn(true);
final StreamDefinition expectedStreamDefinition = new StreamDefinition("testStream", "time | log");
when(streamDefinitionRepository.save(expectedStreamDefinition)).thenReturn(expectedStreamDefinition);
this.defaultStreamService.createStream("testStream", "time | log", "demo stream", false);
verify(this.streamValidationService).isRegistered("time", ApplicationType.source);
verify(this.streamValidationService).isRegistered("log", ApplicationType.sink);
verify(this.streamDefinitionRepository).save(expectedStreamDefinition);
verify(this.auditRecordService).populateAndSaveAuditRecord(
AuditOperationType.STREAM, AuditActionType.CREATE, "testStream", "time | log", null);
verifyNoMoreInteractions(this.skipperStreamDeployer);
verifyNoMoreInteractions(this.appRegistryService);
verifyNoMoreInteractions(this.skipperStreamDeployer);
verifyNoMoreInteractions(this.auditRecordService);
}
@Test
public void createStreamWithMissingApps() {
when(this.appRegistryService.appExist("time", ApplicationType.source)).thenReturn(false);
when(this.appRegistryService.appExist("log", ApplicationType.sink)).thenReturn(false);
thrown.expect(InvalidStreamDefinitionException.class);
thrown.expectMessage("Application name 'time' with type 'source' does not exist in the app registry.\n" +
"Application name 'log' with type 'sink' does not exist in the app registry.");
this.defaultStreamService.createStream("testStream", "time | log", "demo stream", false);
}
@Test
public void createStreamInvalidDsl() {
when(this.appRegistryService.appExist("time", ApplicationType.source)).thenReturn(true);
when(this.appRegistryService.appExist("log", ApplicationType.sink)).thenReturn(true);
thrown.expect(InvalidStreamDefinitionException.class);
thrown.expectMessage("Application name 'koza' with type 'app' does not exist in the app registry.");
this.defaultStreamService.createStream("testStream", "koza", "demo stream", false);
}
@Test
public void verifyUndeployStream() {
StreamDefinition streamDefinition2 = new StreamDefinition("test2", "time | log");
this.defaultStreamService.undeployStream(streamDefinition2.getName());
verify(this.skipperStreamDeployer, times(1)).undeployStream(streamDefinition2.getName());
verify(this.auditRecordService).populateAndSaveAuditRecord(
AuditOperationType.STREAM, AuditActionType.UNDEPLOY, "test2", "time | log", null);
verifyNoMoreInteractions(this.skipperStreamDeployer);
verifyNoMoreInteractions(this.auditRecordService);
}
@Test
public void verifyRollbackStream() throws Exception {
StreamDefinition streamDefinition2 = new StreamDefinition("test2", "time | log");
verifyNoMoreInteractions(this.skipperStreamDeployer);
Release release = new Release();
Manifest manifest = new Manifest();
String rollbackReleaseManifestData = StreamUtils.copyToString(
TestResourceUtils.qualifiedResource(getClass(), "rollbackManifest.yml").getInputStream(),
Charset.defaultCharset());
manifest.setData(rollbackReleaseManifestData);
release.setManifest(manifest);
when(this.skipperStreamDeployer.rollbackStream(streamDefinition2.getName(), 0)).thenReturn(release);
this.defaultStreamService.rollbackStream(streamDefinition2.getName(), 0);
verify(this.skipperStreamDeployer, times(1)).rollbackStream(streamDefinition2.getName(), 0);
}
@Test
public void verifyStreamInfo() {
StreamDefinition streamDefinition1 = new StreamDefinition("test1", "time | log");
Map<String, String> deploymentProperties1 = new HashMap<>();
deploymentProperties1.put("test1", "value1");
Map<String, String> deploymentProperties2 = new HashMap<>();
deploymentProperties2.put("test2", "value2");
Map<String, Map<String, String>> streamDeploymentProperties = new HashMap<>();
streamDeploymentProperties.put("time", deploymentProperties1);
streamDeploymentProperties.put("log", deploymentProperties2);
StreamDeployment streamDeployment1 = new StreamDeployment(streamDefinition1.getName(),
new JSONObject(streamDeploymentProperties).toString());
when(this.skipperStreamDeployer.getStreamInfo(streamDeployment1.getStreamName())).thenReturn(streamDeployment1);
StreamDeployment streamDeployment = this.defaultStreamService.info("test1");
Assert.assertEquals(streamDeployment.getStreamName(), streamDefinition1.getName());
Assert.assertEquals("{\"log\":{\"test2\":\"value2\"},\"time\":{\"test1\":\"value1\"}}",
streamDeployment.getDeploymentProperties());
}
@Test
public void verifyStreamState() {
StreamDefinition streamDefinition = new StreamDefinition("myStream", "time|log");
Map<StreamDefinition, DeploymentState> streamSates = new HashMap<>();
streamSates.put(streamDefinition, DeploymentState.deployed);
when(this.skipperStreamDeployer.streamsStates(eq(Arrays.asList(streamDefinition)))).thenReturn(streamSates);
Map<StreamDefinition, DeploymentState> resultStates = this.defaultStreamService
.state(Arrays.asList(streamDefinition));
verify(this.skipperStreamDeployer, times(1)).streamsStates(any());
Assert.assertNotNull(resultStates);
Assert.assertEquals(1, resultStates.size());
Assert.assertEquals(DeploymentState.deployed, resultStates.get(streamDefinition));
}
@Test
public void verifyStreamHistory() {
Release release = new Release();
release.setName("RELEASE666");
when(this.skipperStreamDeployer.history(eq("myStream"))).thenReturn(Arrays.asList(release));
Collection<Release> releases = this.defaultStreamService.history("myStream");
verify(this.skipperStreamDeployer, times(1)).history(eq("myStream"));
Assert.assertNotNull(releases);
Assert.assertEquals(1, releases.size());
Assert.assertEquals("RELEASE666", releases.iterator().next().getName());
}
@Test
public void verifyStreamPlatformList() {
Deployer deployer = new Deployer("testDeployer", "testType", null);
when(this.skipperStreamDeployer.platformList()).thenReturn(Arrays.asList(deployer));
Collection<Deployer> deployers = this.defaultStreamService.platformList();
verify(this.skipperStreamDeployer, times(1)).platformList();
Assert.assertNotNull(deployers);
Assert.assertEquals(1, deployers.size());
Assert.assertEquals("testDeployer", deployers.iterator().next().getName());
}
@Test
public void verifyStreamManifest() {
when(this.skipperStreamDeployer.manifest(eq("myManifest"), eq(666))).thenReturn("MANIFEST666");
String manifest = this.defaultStreamService.manifest("myManifest", 666);
verify(this.skipperStreamDeployer, times(1)).manifest(anyString(), anyInt());
Assert.assertEquals("MANIFEST666", manifest);
}
@Test
public void testStreamDeployWithDefaultPackageVersion() {
Map<String, String> deploymentProperties = new HashMap<>();
ArgumentCaptor<StreamDeploymentRequest> argumentCaptor = this.testStreamDeploy(deploymentProperties);
Assert.assertEquals(DefaultStreamService.DEFAULT_SKIPPER_PACKAGE_VERSION,
argumentCaptor.getValue().getStreamDeployerProperties().get(SkipperStream.SKIPPER_PACKAGE_VERSION));
}
@Test
public void testStreamDeployWithPreDefinedPackageVersion() {
Map<String, String> deploymentProperties = new HashMap<>();
deploymentProperties.put(SkipperStream.SKIPPER_PACKAGE_VERSION, "2.0.0");
ArgumentCaptor<StreamDeploymentRequest> argumentCaptor = this.testStreamDeploy(deploymentProperties);
Assert.assertEquals("2.0.0",
argumentCaptor.getValue().getStreamDeployerProperties().get(SkipperStream.SKIPPER_PACKAGE_VERSION));
}
@Test
public void testInvalidStreamName() {
when(this.streamValidationService.isRegistered("time", ApplicationType.source)).thenReturn(true);
when(this.streamValidationService.isRegistered("log", ApplicationType.sink)).thenReturn(true);
String[] streamNames = { "$stream", "stream$", "st_ream" };
for (String streamName : streamNames) {
try {
final StreamDefinition expectedStreamDefinition = new StreamDefinition(streamName, "time | log");
when(streamDefinitionRepository.save(expectedStreamDefinition)).thenReturn(expectedStreamDefinition);
this.defaultStreamService.createStream(streamName, "time | log", "demo stream", false);
} catch (Exception e) {
Assert.assertTrue(e instanceof InvalidStreamDefinitionException);
Assert.assertEquals(e.getMessage(), "Stream name must consist of alphanumeric characters or '-', " +
"start with an alphabetic character, and end with an alphanumeric character (e.g. 'my-name', " +
"or 'abc-123')");
}
}
}
public ArgumentCaptor<StreamDeploymentRequest> testStreamDeploy(Map<String, String> deploymentProperties) {
appDeploymentRequestCreator = mock(AppDeploymentRequestCreator.class);
skipperStreamDeployer = mock(SkipperStreamDeployer.class);
streamDefinitionRepository = mock(StreamDefinitionRepository.class);
this.defaultStreamService = new DefaultStreamService(streamDefinitionRepository,
this.skipperStreamDeployer, this.appDeploymentRequestCreator,
this.streamValidationService, this.auditRecordService, new DefaultStreamDefinitionService());
StreamDefinition streamDefinition = new StreamDefinition("test1", "time | log");
when(streamDefinitionRepository.findById(streamDefinition.getName())).thenReturn(Optional.of(streamDefinition));
List<AppDeploymentRequest> appDeploymentRequests = Arrays.asList(mock(AppDeploymentRequest.class));
when(appDeploymentRequestCreator.createRequests(streamDefinition, new HashMap<>()))
.thenReturn(appDeploymentRequests);
this.defaultStreamService.deployStream(streamDefinition1.getName(), deploymentProperties);
ArgumentCaptor<StreamDeploymentRequest> argumentCaptor = ArgumentCaptor.forClass(StreamDeploymentRequest.class);
verify(skipperStreamDeployer, times(1)).deployStream(argumentCaptor.capture());
return argumentCaptor;
}
}
| {
"pile_set_name": "Github"
} |
2 0 2
']' expected near end of file
| {
"pile_set_name": "Github"
} |
---
layout: default
title: gokrazy platforms
aliases:
- /platforms.html
menu:
main:
title: "Platforms"
weight: 10
---
<div class="row">
<div class="col-lg-12">
<h1>Supported platforms</h1>
<p>
<strong>bold</strong> appliances are tested in the CI setup on real
hardware and gate new kernel and firmware versions, and hence can be
considered supported.
</p>
<p>
Regular appliances are supported in a best-effort way, i.e. they
might be temporarily broken at HEAD.
</p>
<p>
The leading <code>github.com</code> in front of package import paths has been omitted for space reasons.
</p>
<table width="100%" class="table table-striped">
<thead>
<tr>
<th scope="col">Target</th>
<th scope="col">Hardware</th>
<th scope="col">GOARCH</th>
<th scope="col">Kernel package</th>
<th scope="col">Firmware package</th>
<th scope="col">Appliances</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">apu2c4</td>
<td>apu2c4</td>
<td>amd64</td>
<td><code><a href="https://github.com/rtr7/kernel">rtr7/kernel</a></code></td>
<td><code><a href="https://github.com/rtr7/kernel">rtr7/kernel</a></code></td>
<td>
<strong><code><a href="https://github.com/gokrazy/bakery">gokrazy/bakery/cmd/bake</a></code></strong><br>
<code><a href="https://github.com/rtr7/router7">rtr7/router7</a></code>
</td>
</tr>
<tr>
<td scope="row">x86-64</td>
<td>qemu</td>
<td>amd64</td>
<td><code><a href="https://github.com/rtr7/kernel">rtr7/kernel</a></code></td>
<td><code><a href="https://github.com/rtr7/kernel">rtr7/kernel</a></code></td>
<td><strong><code><a href="https://github.com/gokrazy/bakery">gokrazy/bakery/cmd/bake</a></code></strong></td>
</tr>
<tr>
<td scope="row">rpi4b</td>
<td>raspi4b</td>
<td>arm64</td>
<td><code><a href="https://github.com/gokrazy/kernel">gokrazy/kernel</a></code></td>
<td><code><a href="https://github.com/gokrazy/firmware">gokrazy/firmware</a></code></td>
<td>
<strong><code><a href="https://github.com/gokrazy/bakery">gokrazy/bakery/cmd/bake</a></code></strong><br>
<code><a href="https://github.com/stapelberg/zkj-nas-tools">stapelberg/avr-x1100w</a></code><br>
<code><a href="https://github.com/stapelberg/zkj-nas-tools">stapelberg/dornröschen</a></code><br>
<code><a href="https://github.com/stapelberg/hmgo">stapelberg/hmgo</a></code><br>
<code><a href="https://github.com/stapelberg/scan2drive">stapelberg/scan2drive</a></code>
</td>
</tr>
<tr>
<td scope="row">rpi3b</td>
<td>raspi3b</td>
<td>arm64</td>
<td><code><a href="https://github.com/gokrazy/kernel">gokrazy/kernel</a></code></td>
<td><code><a href="https://github.com/gokrazy/firmware">gokrazy/firmware</a></code></td>
<td><strong><code><a href="https://github.com/gokrazy/bakery">gokrazy/bakery/cmd/bake</a></code></strong></td>
</tr>
<tr>
<td scope="row">rpi3b+</td>
<td>raspi3b+</td>
<td>arm64</td>
<td><code><a href="https://github.com/gokrazy/kernel">gokrazy/kernel</a></code></td>
<td><code><a href="https://github.com/gokrazy/firmware">gokrazy/firmware</a></code></td>
<td><strong><code><a href="https://github.com/gokrazy/bakery">gokrazy/bakery/cmd/bake</a></code></strong></td>
</tr>
</tbody>
</table>
</div>
</div>
| {
"pile_set_name": "Github"
} |
map "http://hl7.org/fhir/StructureMap/Resource4to3" = "R3 to R2 Conversion for Resource"
uses "http://hl7.org/fhir/StructureDefinition/Resource" alias Resource as source
uses "http://hl7.org/fhir/3.0/StructureDefinition/Resource" alias ResourceR3 as target
imports "http://hl7.org/fhir/StructureMap/primitives4to3"
imports "http://hl7.org/fhir/StructureMap/Meta4to3"
group Resource(source src : Resource, target tgt : ResourceR3) <<type+>> {
src.id -> tgt.id "Resource-id";
src.meta -> tgt.meta "Resource-meta";
src.implicitRules -> tgt.implicitRules "Resource-implicitRules";
src.language -> tgt.language "Resource-language";
}
| {
"pile_set_name": "Github"
} |
package com.ronakmanglani.watchlist.ui.fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ronakmanglani.watchlist.R;
import com.ronakmanglani.watchlist.WatchlistApp;
import com.ronakmanglani.watchlist.ui.activity.MovieActivity;
import com.ronakmanglani.watchlist.ui.activity.MovieDetailActivity;
import com.ronakmanglani.watchlist.ui.adapter.MovieAdapter;
import com.ronakmanglani.watchlist.model.Movie;
import com.ronakmanglani.watchlist.api.ApiHelper;
import com.ronakmanglani.watchlist.util.TextUtil;
import com.ronakmanglani.watchlist.api.VolleySingleton;
import com.ronakmanglani.watchlist.ui.view.PaddingDecorationView;
import org.json.JSONArray;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.BindBool;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class MovieListFragment extends Fragment implements MovieAdapter.OnMovieClickListener {
private Context context;
private Unbinder unbinder;
private MovieAdapter adapter;
private GridLayoutManager layoutManager;
private int pageToDownload;
private static final int TOTAL_PAGES = 999;
private int viewType;
private boolean isLoading;
private boolean isLoadingLocked;
@BindBool(R.bool.is_tablet) boolean isTablet;
@BindView(R.id.error_message) View errorMessage;
@BindView(R.id.progress_circle) View progressCircle;
@BindView(R.id.loading_more) View loadingMore;
@BindView(R.id.swipe_refresh) SwipeRefreshLayout swipeRefreshLayout;
@BindView(R.id.movie_grid) RecyclerView recyclerView;
// Fragment lifecycle
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_movie_list,container,false);
context = getContext();
unbinder = ButterKnife.bind(this, v);
// Initialize variables
pageToDownload = 1;
viewType = getArguments().getInt(WatchlistApp.VIEW_TYPE);
// Setup RecyclerView
adapter = new MovieAdapter(context, this);
layoutManager = new GridLayoutManager(context, getNumberOfColumns());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new PaddingDecorationView(context, R.dimen.recycler_item_padding));
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// Load more if RecyclerView has reached the end and isn't already loading
if (layoutManager.findLastVisibleItemPosition() == adapter.movieList.size() - 1 && !isLoadingLocked && !isLoading) {
if (pageToDownload < TOTAL_PAGES) {
loadingMore.setVisibility(View.VISIBLE);
downloadMoviesList();
}
}
}
});
// Setup swipe refresh
swipeRefreshLayout.setColorSchemeResources(R.color.accent);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// Toggle visibility
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
// Remove cache
VolleySingleton.getInstance().requestQueue.getCache().remove(getUrlToDownload(1));
// Download again
pageToDownload = 1;
adapter = null;
downloadMoviesList();
}
});
// Get the movies list
if (savedInstanceState == null || !savedInstanceState.containsKey(WatchlistApp.MOVIE_LIST)) {
downloadMoviesList();
} else {
adapter.movieList = savedInstanceState.getParcelableArrayList(WatchlistApp.MOVIE_LIST);
pageToDownload = savedInstanceState.getInt(WatchlistApp.PAGE_TO_DOWNLOAD);
isLoadingLocked = savedInstanceState.getBoolean(WatchlistApp.IS_LOCKED);
isLoading = savedInstanceState.getBoolean(WatchlistApp.IS_LOADING);
// Download again if stopped, else show list
if (isLoading) {
if (pageToDownload == 1) {
progressCircle.setVisibility(View.VISIBLE);
loadingMore.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
swipeRefreshLayout.setVisibility(View.GONE);
} else {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setVisibility(View.VISIBLE);
}
downloadMoviesList();
} else {
onDownloadSuccessful();
}
}
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (layoutManager != null && adapter != null) {
outState.putBoolean(WatchlistApp.IS_LOADING, isLoading);
outState.putBoolean(WatchlistApp.IS_LOCKED, isLoadingLocked);
outState.putInt(WatchlistApp.PAGE_TO_DOWNLOAD, pageToDownload);
outState.putParcelableArrayList(WatchlistApp.MOVIE_LIST, adapter.movieList);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
VolleySingleton.getInstance().requestQueue.cancelAll(this.getClass().getName());
unbinder.unbind();
}
// JSON parsing and display
public String getUrlToDownload(int page) {
if (viewType == WatchlistApp.VIEW_TYPE_POPULAR) {
return ApiHelper.getMostPopularMoviesLink(getActivity(), page);
} else if (viewType == WatchlistApp.VIEW_TYPE_RATED) {
return ApiHelper.getHighestRatedMoviesLink(getActivity(), page);
} else if (viewType == WatchlistApp.VIEW_TYPE_UPCOMING) {
return ApiHelper.getUpcomingMoviesLink(getActivity(), page);
} else if (viewType == WatchlistApp.VIEW_TYPE_PLAYING) {
return ApiHelper.getNowPlayingMoviesLink(getActivity(), page);
}
return null;
}
private void downloadMoviesList() {
if (adapter == null) {
adapter = new MovieAdapter(context, this);
recyclerView.setAdapter(adapter);
}
String urlToDownload = getUrlToDownload(pageToDownload);
final JsonObjectRequest request = new JsonObjectRequest (
Request.Method.GET, urlToDownload, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
try {
JSONArray result = jsonObject.getJSONArray("results");
for (int i = 0; i < result.length(); i++) {
JSONObject movie = (JSONObject) result.get(i);
String poster = movie.getString("poster_path");
String overview = movie.getString("overview");
String year = movie.getString("release_date");
if (!TextUtil.isNullOrEmpty(year)) {
year = year.substring(0, 4);
}
String id = movie.getString("id");
String title = movie.getString("title");
String backdrop = movie.getString("backdrop_path");
String rating = movie.getString("vote_average");
Movie thumb = new Movie(id, title, year, overview, rating, poster, backdrop);
adapter.movieList.add(thumb);
}
// Load detail fragment if in tablet mode
if (isTablet && pageToDownload == 1 && adapter.movieList.size() > 0) {
((MovieActivity)getActivity()).loadDetailFragmentWith(adapter.movieList.get(0).id);
}
pageToDownload++;
onDownloadSuccessful();
} catch (Exception ex) {
// JSON parsing error
onDownloadFailed();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// Network error
onDownloadFailed();
}
});
isLoading = true;
request.setTag(this.getClass().getName());
VolleySingleton.getInstance().requestQueue.add(request);
}
private void onDownloadSuccessful() {
isLoading = false;
errorMessage.setVisibility(View.GONE);
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setEnabled(true);
adapter.notifyDataSetChanged();
}
private void onDownloadFailed() {
isLoading = false;
if (pageToDownload == 1) {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setVisibility(View.GONE);
errorMessage.setVisibility(View.VISIBLE);
} else {
progressCircle.setVisibility(View.GONE);
loadingMore.setVisibility(View.GONE);
errorMessage.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
swipeRefreshLayout.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setEnabled(true);
isLoadingLocked = true;
}
}
// Helper methods
public void refreshLayout() {
Parcelable state = layoutManager.onSaveInstanceState();
layoutManager = new GridLayoutManager(getContext(), getNumberOfColumns());
recyclerView.setLayoutManager(layoutManager);
layoutManager.onRestoreInstanceState(state);
}
public int getNumberOfColumns() {
// Get screen width
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float widthPx = displayMetrics.widthPixels;
if (isTablet) {
widthPx = widthPx / 3;
}
// Calculate desired width
SharedPreferences preferences = context.getSharedPreferences(WatchlistApp.TABLE_USER, Context.MODE_PRIVATE);
if (preferences.getInt(WatchlistApp.VIEW_MODE, WatchlistApp.VIEW_MODE_GRID) == WatchlistApp.VIEW_MODE_GRID) {
float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_card_width);
int columns = Math.round(widthPx / desiredPx);
return columns > 2 ? columns : 2;
} else {
float desiredPx = getResources().getDimensionPixelSize(R.dimen.movie_list_card_width);
int columns = Math.round(widthPx / desiredPx);
return columns > 1 ? columns : 1;
}
}
// Click events
@OnClick(R.id.try_again)
public void onTryAgainClicked() {
// Hide all views
errorMessage.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
swipeRefreshLayout.setVisibility(View.GONE);
// Show progress circle
progressCircle.setVisibility(View.VISIBLE);
// Try to download the data again
pageToDownload = 1;
adapter = null;
downloadMoviesList();
}
@Override
public void onMovieClicked(int position) {
if (isTablet) {
((MovieActivity)getActivity()).loadDetailFragmentWith(adapter.movieList.get(position).id);
} else {
Intent intent = new Intent(context, MovieDetailActivity.class);
intent.putExtra(WatchlistApp.MOVIE_ID, adapter.movieList.get(position).id);
startActivity(intent);
}
}
}
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import "NSObject-Protocol.h"
@class CKShareMetadata, NSApplication, NSArray, NSCoder, NSData, NSDictionary, NSError, NSMenu, NSNotification, NSString, NSUserActivity;
@protocol NSApplicationDelegate <NSObject>
@optional
- (void)applicationDidChangeOcclusionState:(NSNotification *)arg1;
- (void)applicationDidChangeScreenParameters:(NSNotification *)arg1;
- (void)applicationWillTerminate:(NSNotification *)arg1;
- (void)applicationDidUpdate:(NSNotification *)arg1;
- (void)applicationWillUpdate:(NSNotification *)arg1;
- (void)applicationDidResignActive:(NSNotification *)arg1;
- (void)applicationWillResignActive:(NSNotification *)arg1;
- (void)applicationDidBecomeActive:(NSNotification *)arg1;
- (void)applicationWillBecomeActive:(NSNotification *)arg1;
- (void)applicationDidUnhide:(NSNotification *)arg1;
- (void)applicationWillUnhide:(NSNotification *)arg1;
- (void)applicationDidHide:(NSNotification *)arg1;
- (void)applicationWillHide:(NSNotification *)arg1;
- (void)applicationDidFinishLaunching:(NSNotification *)arg1;
- (void)applicationWillFinishLaunching:(NSNotification *)arg1;
- (BOOL)application:(NSApplication *)arg1 delegateHandlesKey:(NSString *)arg2;
- (void)application:(NSApplication *)arg1 userDidAcceptCloudKitShareWithMetadata:(CKShareMetadata *)arg2;
- (void)application:(NSApplication *)arg1 didUpdateUserActivity:(NSUserActivity *)arg2;
- (void)application:(NSApplication *)arg1 didFailToContinueUserActivityWithType:(NSString *)arg2 error:(NSError *)arg3;
- (BOOL)application:(NSApplication *)arg1 continueUserActivity:(NSUserActivity *)arg2 restorationHandler:(void (^)(NSArray *))arg3;
- (BOOL)application:(NSApplication *)arg1 willContinueUserActivityWithType:(NSString *)arg2;
- (void)application:(NSApplication *)arg1 didDecodeRestorableState:(NSCoder *)arg2;
- (void)application:(NSApplication *)arg1 willEncodeRestorableState:(NSCoder *)arg2;
- (void)application:(NSApplication *)arg1 didReceiveRemoteNotification:(NSDictionary *)arg2;
- (void)application:(NSApplication *)arg1 didFailToRegisterForRemoteNotificationsWithError:(NSError *)arg2;
- (void)application:(NSApplication *)arg1 didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)arg2;
- (NSError *)application:(NSApplication *)arg1 willPresentError:(NSError *)arg2;
- (NSMenu *)applicationDockMenu:(NSApplication *)arg1;
- (BOOL)applicationShouldHandleReopen:(NSApplication *)arg1 hasVisibleWindows:(BOOL)arg2;
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)arg1;
- (unsigned long long)application:(NSApplication *)arg1 printFiles:(NSArray *)arg2 withSettings:(NSDictionary *)arg3 showPrintPanels:(BOOL)arg4;
- (BOOL)application:(NSApplication *)arg1 printFile:(NSString *)arg2;
- (BOOL)application:(id)arg1 openFileWithoutUI:(NSString *)arg2;
- (BOOL)applicationOpenUntitledFile:(NSApplication *)arg1;
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)arg1;
- (BOOL)application:(NSApplication *)arg1 openTempFile:(NSString *)arg2;
- (void)application:(NSApplication *)arg1 openFiles:(NSArray *)arg2;
- (BOOL)application:(NSApplication *)arg1 openFile:(NSString *)arg2;
- (void)application:(NSApplication *)arg1 openURLs:(NSArray *)arg2;
- (unsigned long long)applicationShouldTerminate:(NSApplication *)arg1;
@end
| {
"pile_set_name": "Github"
} |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2009-2012 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.admingui.plugin.jms;
import com.sun.appserv.connectors.internal.api.ConnectorRuntimeException;
import com.sun.enterprise.config.serverbeans.Cluster;
import com.sun.enterprise.config.serverbeans.Domain;
import com.sun.enterprise.config.serverbeans.Server;
import com.sun.enterprise.connectors.ConnectorRuntime;
import com.sun.enterprise.connectors.jms.system.JmsProviderLifecycle;
import com.sun.jsftemplating.annotation.Handler;
import com.sun.jsftemplating.annotation.HandlerInput;
import com.sun.jsftemplating.annotation.HandlerOutput;
import com.sun.jsftemplating.layout.descriptors.handler.HandlerContext;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import org.glassfish.admingui.common.util.GuiUtil;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.internal.api.ServerContext;
import org.glassfish.jms.admin.cli.JMSDestination;
import org.glassfish.jms.admin.cli.MQJMXConnectorInfo;
import org.glassfish.resourcebase.resources.api.PoolInfo;
/**
*
* @author jasonlee
*/
public class JmsHandlers {
protected static final String OBJECT_DEST_MGR = "com.sun.messaging.jms.server:type=DestinationManager,subtype=Config";
protected static final String OBJECT_DEST_BASE = "com.sun.messaging.jms.server:type=Destination";
protected static final String SUBTYPE_CONFIG = "Config";
protected static final String SUBTYPE_MONITOR = "Monitor";
protected static final String OP_LIST_DESTINATIONS = "getDestinations";
protected static final String OP_CREATE = "create";
protected static final String OP_DESTROY = "destroy";
protected static final String OP_PURGE = "purge";
// Config attributes
protected static final String ATTR_CONSUMER_FLOW_LIMIT = "ConsumerFlowLimit";
protected static final String ATTR_LIMIT_BEHAVIOR = "LimitBehavior";
protected static final String ATTR_LOCAL_DELIVERY_PREFERRED = "LocalDeliveryPreferred";
protected static final String ATTR_MAX_BYTES_PER_MSG = "MaxBytesPerMsg";
protected static final String ATTR_MAX_NUM_ACTIVE_CONSUMERS = "MaxNumActiveConsumers";
protected static final String ATTR_MAX_NUM_BACKUP_CONSUMERS = "MaxNumBackupConsumers";
protected static final String ATTR_MAX_NUM_PRODUCERS = "MaxNumProducers";
protected static final String ATTR_USE_DMQ = "UseDMQ";
protected static final String ATTR_MAX_NUM_MSGS = "MaxNumMsgs";
protected static final String ATTR_MAX_TOTAL_MSG_BYTES = "MaxTotalMsgBytes";
protected static final String ATTR_VALIDATE_XML_SCHEMA_ENABLED = "ValidateXMLSchemaEnabled";
protected static final String ATTR_XML_SCHEMA_URI_LIST = "XMLSchemaURIList";
// Monitoring attributes
protected static final String ATTR_CREATED_BY_ADMIN = "CreatedByAdmin";
protected static final String ATTR_TEMPORARY = "Temporary";
protected static final String ATTR_CONNECTION_ID = "ConnectionID";
protected static final String ATTR_STATE = "State";
protected static final String ATTR_STATE_LABEL = "StateLabel";
protected static final String ATTR_NUM_PRODUCERS = "NumProducers";
protected static final String ATTR_NUM_CONSUMERS = "NumConsumers";
protected static final String ATTR_NUM_WILDCARD_PRODUCERS = "NumWildcardProducers";
protected static final String ATTR_NUM_WILDCARD_CONSUMERS = "NumWildcardConsumers";
protected static final String ATTR_NUM_WILDCARDS = "NumWildcards";
protected static final String ATTR_PEAK_NUM_CONSUMERS = "PeakNumConsumers";
protected static final String ATTR_AVG_NUM_CONSUMERS = "AvgNumConsumers";
protected static final String ATTR_NUM_ACTIVE_CONSUMERS = "NumActiveConsumers";
protected static final String ATTR_PEAK_NUM_ACTIVE_CONSUMERS = "PeakNumActiveConsumers";
protected static final String ATTR_AVG_NUM_ACTIVE_CONSUMERS = "AvgNumActiveConsumers";
protected static final String ATTR_NUM_BACKUP_CONSUMERS = "NumBackupConsumers";
protected static final String ATTR_PEAK_NUM_BACKUP_CONSUMERS = "PeakNumBackupConsumers";
protected static final String ATTR_AVG_NUM_BACKUP_CONSUMERS = "AvgNumBackupConsumers";
protected static final String ATTR_NUM_MSGS = "NumMsgs";
protected static final String ATTR_NUM_MSGS_REMOTE = "NumMsgsRemote";
protected static final String ATTR_NUM_MSGS_PENDING_ACKS = "NumMsgsPendingAcks";
protected static final String ATTR_NUM_MSGS_HELD_IN_TRANSACTION = "NumMsgsHeldInTransaction";
protected static final String ATTR_NEXT_MESSAGE_ID = "NextMessageID";
protected static final String ATTR_PEAK_NUM_MSGS = "PeakNumMsgs";
protected static final String ATTR_AVG_NUM_MSGS = "AvgNumMsgs";
protected static final String ATTR_NUM_MSGS_IN = "NumMsgsIn";
protected static final String ATTR_NUM_MSGS_OUT = "NumMsgsOut";
protected static final String ATTR_MSG_BYTES_IN = "MsgBytesIn";
protected static final String ATTR_MSG_BYTES_OUT = "MsgBytesOut";
protected static final String ATTR_PEAK_MSG_BYTES = "PeakMsgBytes";
protected static final String ATTR_TOTAL_MSG_BYTES = "TotalMsgBytes";
protected static final String ATTR_TOTAL_MSG_BYTES_REMOTE = "TotalMsgBytesRemote";
protected static final String ATTR_TOTAL_MSG_BYTES_HELD_IN_TRANSACTION = "TotalMsgBytesHeldInTransaction";
protected static final String ATTR_PEAK_TOTAL_MSG_BYTES = "PeakTotalMsgBytes";
protected static final String ATTR_AVG_TOTAL_MSG_BYTES = "AvgTotalMsgBytes";
protected static final String ATTR_DISK_RESERVED = "DiskReserved";
protected static final String ATTR_DISK_USED = "DiskUsed";
protected static final String ATTR_DISK_UTILIZATION_RATIO = "DiskUtilizationRatio";
private static final String[] ATTRS_CONFIG = new String[]{ATTR_MAX_NUM_MSGS, ATTR_MAX_BYTES_PER_MSG, ATTR_MAX_TOTAL_MSG_BYTES, ATTR_LIMIT_BEHAVIOR,
ATTR_MAX_NUM_PRODUCERS, ATTR_MAX_NUM_ACTIVE_CONSUMERS, ATTR_MAX_NUM_BACKUP_CONSUMERS, ATTR_CONSUMER_FLOW_LIMIT,
ATTR_LOCAL_DELIVERY_PREFERRED, ATTR_USE_DMQ, ATTR_VALIDATE_XML_SCHEMA_ENABLED, ATTR_XML_SCHEMA_URI_LIST};
private static final String[] ATTRS_MONITOR = new String[]{ATTR_CREATED_BY_ADMIN, ATTR_TEMPORARY, ATTR_CONNECTION_ID, ATTR_STATE, ATTR_STATE_LABEL,
ATTR_NUM_PRODUCERS, ATTR_NUM_CONSUMERS, ATTR_NUM_WILDCARD_PRODUCERS, ATTR_NUM_WILDCARD_CONSUMERS, ATTR_NUM_WILDCARDS, ATTR_PEAK_NUM_CONSUMERS,
ATTR_AVG_NUM_CONSUMERS, ATTR_NUM_ACTIVE_CONSUMERS, ATTR_PEAK_NUM_ACTIVE_CONSUMERS, ATTR_AVG_NUM_ACTIVE_CONSUMERS,
ATTR_NUM_BACKUP_CONSUMERS, ATTR_PEAK_NUM_BACKUP_CONSUMERS, ATTR_AVG_NUM_BACKUP_CONSUMERS, ATTR_NUM_MSGS, ATTR_NUM_MSGS_REMOTE,
ATTR_NUM_MSGS_PENDING_ACKS, ATTR_NUM_MSGS_HELD_IN_TRANSACTION, ATTR_NEXT_MESSAGE_ID, ATTR_PEAK_NUM_MSGS, ATTR_AVG_NUM_MSGS,
ATTR_NUM_MSGS_IN, ATTR_NUM_MSGS_OUT, ATTR_MSG_BYTES_IN, ATTR_MSG_BYTES_OUT, ATTR_PEAK_MSG_BYTES, ATTR_TOTAL_MSG_BYTES, ATTR_TOTAL_MSG_BYTES_REMOTE,
ATTR_TOTAL_MSG_BYTES_HELD_IN_TRANSACTION, ATTR_PEAK_TOTAL_MSG_BYTES, ATTR_AVG_TOTAL_MSG_BYTES, ATTR_DISK_RESERVED, ATTR_DISK_USED,
ATTR_DISK_UTILIZATION_RATIO};
protected static final String PROP_NAME = "name";
protected static final String PROP_DEST_TYPE = "desttype";
@Handler(id = "getPhysicalDestination",
input = {
@HandlerInput(name = "name", type = String.class, required = true),
@HandlerInput(name = "type", type = String.class, required = true)},
output = {
@HandlerOutput(name = "destData", type = java.util.Map.class)})
public static void getPhysicalDestination(HandlerContext handlerCtx) {
String name = (String) handlerCtx.getInputValue("name");
String type = (String) handlerCtx.getInputValue("type");
Map valueMap = new HashMap();
try {
String objectName = getJmsDestinationObjectName(SUBTYPE_CONFIG, name, type);
AttributeList attributes = (AttributeList) JMXUtil.getMBeanServer().getAttributes(new ObjectName(objectName), ATTRS_CONFIG);
for (Attribute attribute : attributes.asList()) {
valueMap.put(attribute.getName(), (attribute.getValue() != null) ? attribute.getValue().toString() : null);
}
handlerCtx.setOutputValue("destData", valueMap);
} catch (Exception ex) {
GuiUtil.handleException(handlerCtx, ex);
}
handlerCtx.setOutputValue("destData", valueMap);
}
@Handler(id = "getPhysicalDestinationStats",
input = {
@HandlerInput(name = "name", type = String.class, required = true),
@HandlerInput(name = "type", type = String.class, required = true),
@HandlerInput(name = "target", type = String.class, required = true)},
output = {
@HandlerOutput(name = "statsData", type = java.util.List.class)})
public static void getPhysicalDestinationStats(HandlerContext handlerCtx) {
String name = (String) handlerCtx.getInputValue("name");
String type = (String) handlerCtx.getInputValue("type");
String target = (String) handlerCtx.getInputValue("target");
List statsList = new ArrayList();
try {
insureJmsBrokerIsRunning();
String objectName = getJmsDestinationObjectName(SUBTYPE_MONITOR, name, type);
AttributeList attributes = (AttributeList) getMBeanServerConnection(target).getAttributes(new ObjectName(objectName), ATTRS_MONITOR);
ResourceBundle bundle = GuiUtil.getBundle("org.glassfish.jms.admingui.Strings");
statsList.add(createRow("Name", name, ""));
statsList.add(createRow("Type", type.substring(0, 1).toUpperCase(GuiUtil.guiLocale) + type.substring(1), ""));
for (Attribute attribute : attributes.asList()) {
statsList.add(
createRow(
GuiUtil.getMessage(bundle, "jmsPhysDestinations." + attribute.getName()),
attribute.getValue(),
GuiUtil.getMessage(bundle, "jmsPhysDestinations." + attribute.getName() + "Help")));
}
} catch (Exception ex) {
GuiUtil.handleException(handlerCtx, ex);
}
handlerCtx.setOutputValue("statsData", statsList);
}
@Handler(id = "getPhysicalDestinations",
input = {
@HandlerInput(name = "selectedRows", type = List.class)},
output = {
@HandlerOutput(name = "result", type = java.util.List.class)})
public static void getPhysicalDestinations(HandlerContext handlerCtx) {
ObjectName[] objectNames = null;
List result = new ArrayList();
try {
insureJmsBrokerIsRunning();
//com.sun.messaging.jms.server:type=Destination,subtype=Config,desttype=q,name="mq.sys.dmq"
objectNames = (ObjectName[]) JMXUtil.invoke(OBJECT_DEST_MGR, OP_LIST_DESTINATIONS);
if (objectNames == null) {
handlerCtx.setOutputValue("result", result);
return; //nothing to load..
}
List<Map> selectedList = (List) handlerCtx.getInputValue("selectedRows");
boolean hasOrig = (selectedList == null || selectedList.size() == 0) ? false : true;
for (int i = 0; i < objectNames.length; i++) {
// getAttributes for the given objectName...
HashMap oneRow = new HashMap();
oneRow.put("name", objectNames[i].getKeyProperty(PROP_NAME).replaceAll("\"", ""));
oneRow.put("type", "t".equals(objectNames[i].getKeyProperty(PROP_DEST_TYPE)) ? "topic" : "queue");
oneRow.put("selected", (hasOrig) ? isSelected(objectNames[i].getKeyProperty(PROP_NAME), selectedList) : false);
result.add(oneRow);
}
} catch (Exception ex) {
System.out.println("invoke: " + OBJECT_DEST_MGR + ", method = " + OP_LIST_DESTINATIONS);
GuiUtil.handleException(handlerCtx, ex);
}
handlerCtx.setOutputValue("result", result);
}
/**
* <p>This handler creates a physical destination.</p>
* @param context The HandlerContext.
*/
@Handler(id = "createPhysicalDestination",
input = {
@HandlerInput(name = "name", type = String.class, required = true),
@HandlerInput(name = "attributes", type = Map.class, required = true),
@HandlerInput(name = "type", type = String.class)})
public static void createPhysicalDestination(HandlerContext handlerCtx) {
try {
final String type = (String) handlerCtx.getInputValue("type");
final String name = (String) handlerCtx.getInputValue("name");
AttributeList list = new AttributeList();
// Copy attributes to the AttributeList.
// Make it work, then make it right. :|
Map attrMap = (Map) handlerCtx.getInputValue("attributes");
buildAttributeList(list, attrMap, type);
String[] types = new String[]{"java.lang.String", "java.lang.String", "javax.management.AttributeList"};
Object[] params = new Object[]{type, name, list};
JMXUtil.invoke(OBJECT_DEST_MGR, OP_CREATE, params, types);
} catch (Exception ex) {
GuiUtil.handleException(handlerCtx, ex);
}
}
/**
* <p>This handler updates a physical destination.</p>
* @param context The HandlerContext.
*/
@Handler(id = "updatePhysicalDestination",
input = {
@HandlerInput(name = "name", type = String.class, required = true),
@HandlerInput(name = "attributes", type = Map.class, required = true),
@HandlerInput(name = "type", type = String.class)})
public static void updatePhysicalDestination(HandlerContext handlerCtx) {
try {
final String type = (String) handlerCtx.getInputValue("type");
final String name = (String) handlerCtx.getInputValue("name");
AttributeList list = new AttributeList();
// Copy attributes to the AttributeList.
// Make it work, then make it right. :|
Map attrMap = (Map) handlerCtx.getInputValue("attributes");
buildAttributeList(list, attrMap, type);
String objectName = getJmsDestinationObjectName(SUBTYPE_CONFIG, name, type);
JMXUtil.getMBeanServer().setAttributes(new ObjectName(objectName), list);
} catch (Exception ex) {
GuiUtil.handleException(handlerCtx, ex);
}
}
@Handler(id = "deleteJMSDest",
input = {
@HandlerInput(name = "selectedRows", type = List.class, required = true)}
)
public static void deleteJMSDest(HandlerContext handlerCtx) {
// String configName = ((String) handlerCtx.getInputValue("targetName"));
List obj = (List) handlerCtx.getInputValue("selectedRows");
List<Map> selectedRows = (List) obj;
try {
for (Map oneRow : selectedRows) {
String name = (String) oneRow.get("name");
String type = ((String) oneRow.get("type")).substring(0, 1).toLowerCase(GuiUtil.guiLocale);
Object[] params = new Object[]{type, name};
String[] types = new String[]{"java.lang.String", "java.lang.String"};
JMXUtil.invoke(OBJECT_DEST_MGR, OP_DESTROY, params, types);
}
} catch (Exception ex) {
GuiUtil.handleException(handlerCtx, ex);
}
}
/**
* <p> This handler takes in selected rows, and removes selected config
* @param context The HandlerContext.
*/
@Handler(id = "flushJMSDestination",
input = {
@HandlerInput(name = "selectedRows", type = List.class, required = true)})
public static void flushJMSDestination(HandlerContext handlerCtx) {
List<Map> selectedRows = (List) handlerCtx.getInputValue("selectedRows");
try {
for (Map oneRow : selectedRows) {
String name = (String) oneRow.get("name");
String type = ((String) oneRow.get("type"));
JMXUtil.invoke(getJmsDestinationObjectName(SUBTYPE_CONFIG, name, type), OP_PURGE);
}
} catch (Exception ex) {
GuiUtil.handleException(handlerCtx, ex);
}
}
/**
* <p> This handler returns a map populated with the default values for a
* destination. Currently, this is all hard-coded, based on data from the MQ
* documentation. When/if they expose an API for determining this programmatically,
* the implementation will be updated.</p>
* If an orig map is passed in, the default value will be set to this orig map instead
* of creating a new one. This is used for restoring back to the default value during edit.
* @param context The HandlerContext.
*/
@Handler(id = "getDefaultPhysicalDestinationValues",
input = {
@HandlerInput(name = "orig", type = Map.class)},
output = {
@HandlerOutput(name = "map", type = Map.class)
})
public static void getDefaultPhysicalDestinationValues(HandlerContext handlerCtx) {
Map orig = (Map) handlerCtx.getInputValue("orig");
Map map = new HashMap();
if (orig != null) {
map = orig;
}
map.put(ATTR_MAX_NUM_MSGS, "-1");
map.put(ATTR_MAX_BYTES_PER_MSG, "-1");
map.put(ATTR_MAX_TOTAL_MSG_BYTES, "-1");
map.put(ATTR_LIMIT_BEHAVIOR, "REJECT_NEWEST");
map.put(ATTR_MAX_NUM_PRODUCERS, "100");
map.put(ATTR_MAX_NUM_ACTIVE_CONSUMERS, "-1");
map.put(ATTR_MAX_NUM_BACKUP_CONSUMERS, "0");
map.put(ATTR_CONSUMER_FLOW_LIMIT, "1000");
map.put(ATTR_LOCAL_DELIVERY_PREFERRED, "false");
map.put(ATTR_USE_DMQ, "true");
map.put(ATTR_VALIDATE_XML_SCHEMA_ENABLED, "false");
map.put(ATTR_XML_SCHEMA_URI_LIST, "");
handlerCtx.setOutputValue("map", map);
}
@Handler(id = "pingJms",
input = {
@HandlerInput(name = "poolName", type = String.class, required = true)})
public static void pingJms(HandlerContext handlerCtx) {
try {
String poolName = (String) handlerCtx.getInputValue("poolName");
ConnectorRuntime connectorRuntime = GuiUtil.getHabitat().getService(ConnectorRuntime.class);
PoolInfo poolInfo = new PoolInfo(poolName);
connectorRuntime.pingConnectionPool(poolInfo);
GuiUtil.prepareAlert("success", GuiUtil.getMessage("msg.PingSucceed"), null);
} catch (Exception ex) {
GuiUtil.prepareAlert("error", GuiUtil.getMessage("msg.Error"), ex.getMessage());
}
}
public static void getDestinations(HandlerContext handlerCtx) {
//String result = (String)JMXUtil.invoke(JMS_OBJECT_NAME, OP_LIST_DESTINATIONS, null, null);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
mbs.invoke(new ObjectName(OBJECT_DEST_MGR), OP_LIST_DESTINATIONS, new Object[]{}, new String[]{});
} catch (Exception ex) {
Logger.getLogger(JmsHandlers.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static boolean isSelected(String name, List<Map> selectedList) {
if (selectedList == null || name == null) {
return false;
}
for (Map oneRow : selectedList) {
if (name.equals(oneRow.get("name"))) {
return true;
}
}
return false;
}
protected static String getJmsDestinationObjectName(String objectType, String name, String destType) {
return OBJECT_DEST_BASE + ",subtype=" + objectType + ",desttype=" + destType.substring(0, 1).toLowerCase(GuiUtil.guiLocale) + ",name=\"" + name + "\"";
}
protected static void buildAttributeList(AttributeList list, Map attrMap, String type) {
list.add(new Attribute(ATTR_MAX_NUM_MSGS, Long.parseLong((String) attrMap.get(ATTR_MAX_NUM_MSGS))));
list.add(new Attribute(ATTR_MAX_BYTES_PER_MSG, Long.parseLong((String) attrMap.get(ATTR_MAX_BYTES_PER_MSG))));
list.add(new Attribute(ATTR_MAX_TOTAL_MSG_BYTES, Long.parseLong((String) attrMap.get(ATTR_MAX_TOTAL_MSG_BYTES))));
list.add(new Attribute(ATTR_LIMIT_BEHAVIOR, (String) attrMap.get(ATTR_LIMIT_BEHAVIOR)));
list.add(new Attribute(ATTR_MAX_NUM_PRODUCERS, Integer.parseInt((String) attrMap.get(ATTR_MAX_NUM_PRODUCERS))));
if ("queue".equals(type)) {
list.add(new Attribute(ATTR_MAX_NUM_ACTIVE_CONSUMERS, Integer.parseInt((String) attrMap.get(ATTR_MAX_NUM_ACTIVE_CONSUMERS))));
list.add(new Attribute(ATTR_MAX_NUM_BACKUP_CONSUMERS, Integer.parseInt((String) attrMap.get(ATTR_MAX_NUM_BACKUP_CONSUMERS))));
list.add(new Attribute(ATTR_LOCAL_DELIVERY_PREFERRED, Boolean.valueOf((String) attrMap.get(ATTR_LOCAL_DELIVERY_PREFERRED))));
}
list.add(new Attribute(ATTR_CONSUMER_FLOW_LIMIT, Long.parseLong((String) attrMap.get(ATTR_CONSUMER_FLOW_LIMIT))));
list.add(new Attribute(ATTR_USE_DMQ, Boolean.valueOf((String) attrMap.get(ATTR_USE_DMQ))));
list.add(new Attribute(ATTR_VALIDATE_XML_SCHEMA_ENABLED, Boolean.valueOf((String) attrMap.get(ATTR_VALIDATE_XML_SCHEMA_ENABLED))));
list.add(new Attribute(ATTR_XML_SCHEMA_URI_LIST, (String) attrMap.get(ATTR_XML_SCHEMA_URI_LIST)));
}
protected static void insureJmsBrokerIsRunning() throws ConnectorRuntimeException {
// FIXME: This @Service needs to be wrapped in an MBean so that we can have the console out of process
JmsProviderLifecycle jpl = GuiUtil.getHabitat().getService(JmsProviderLifecycle.class);
jpl.initializeBroker();
}
private static Map createRow(String label, Object value, String helpText) {
Map map = new HashMap();
map.put("label", label);
map.put("value", (value != null) ? value.toString() : null);
map.put("help", helpText);
return map;
}
private static MBeanServerConnection getMBeanServerConnection(String target) throws ConnectorRuntimeException, Exception {
ServiceLocator habitat = GuiUtil.getHabitat();
Domain domain = habitat.getService(Domain.class);
Cluster cluster = domain.getClusterNamed(target);
String configRef = null;
if (cluster == null) {
Server server = domain.getServerNamed(target);
configRef = server.getConfigRef();
} else {
configRef = cluster.getConfigRef();
}
PhysicalDestinations pd = new PhysicalDestinations();
MQJMXConnectorInfo mqInfo = pd.getConnectorInfo(target, configRef, habitat, domain);
return mqInfo.getMQMBeanServerConnection();
}
private static class PhysicalDestinations extends JMSDestination {
public MQJMXConnectorInfo getConnectorInfo(String target, String configName, ServiceLocator habitat, Domain domain) throws Exception {
return getMQJMXConnectorInfo(target, domain.getConfigNamed(configName), habitat.<ServerContext>getService(ServerContext.class),
domain, habitat.<ConnectorRuntime>getService(ConnectorRuntime.class));
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* uriparser - RFC 3986 URI parsing library
*
* Copyright (C) 2018, Sebastian Pipping <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of
* its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <uriparser/Uri.h>
int main() {
char toUnescape[] = "one%20two";
printf("original: \"%s\"\n", toUnescape);
uriUnescapeInPlaceA(toUnescape);
printf("unescaped: \"%s\"\n", toUnescape);
return 0;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>7-Zip 出口代码</TITLE>
<LINK href="../style.css" rel="stylesheet" type="text/css">
</HEAD>
<BODY>
<H1>7-Zip 出口代码</H1>
<P>7-Zip 会返回下列出口代码:</P>
<TABLE>
<TR><TH width=30>代码</TH><TH>含义</TH></TR>
<TR><TD>0</TH><TD>无错误</TD></TR>
<TR><TD>1</TH><TD>警告 (非致命错误),例如一个或多个文件被其它应用程序锁定,无法添加到压缩档案中</TD></TR>
<TR><TD>2</TH><TD>致命错误</TD></TR>
<TR><TD>7</TH><TD>命令行错误</TD></TR>
<TR><TD>8</TH><TD>内存不足</TD></TR>
<TR><TD>255</TH><TD>用户取消操作</TD></TR>
</TABLE>
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
{
"name": "@tanker/file-ponyfill",
"version": "0.0.1",
"description": "A cross-browser ponyfill for File with a working constructor",
"author": "Tanker Team",
"license": "Apache-2.0",
"homepage": "https://tanker.io/",
"repository": {
"type": "git",
"url": "git+https://github.com/TankerHQ/sdk-js.git"
},
"bugs": {
"url": "https://github.com/TankerHQ/sdk-js/issues"
},
"keywords": [
"file",
"browser",
"dom",
"constructor",
"ponyfill",
"polyfill"
],
"main": "src/index.js",
"dependencies": {
"@babel/runtime-corejs3": "^7.6.0",
"@tanker/global-this": "0.0.1"
},
"devDependencies": {
"@tanker/test-utils": "0.0.1"
}
}
| {
"pile_set_name": "Github"
} |
青葉ゆうな最新番号
【KK-225】ブルマー娘SEXベストセレクション4時間
【KK-219】あの女優の初SEX特集盤!
【ALD-222】小柄16人の美少女ハメまくり!
【AZRD-008】flow… 妹の部屋 青葉ゆうな
【AZRD-004】quel cul! 青葉ゆうな
【AZRD-001】jolie petite fille 青葉ゆうな
【RBNR-060】アイドル女優とSEXしませんか?
【AOBD-005】FAKE FINAL 迷いこんだ心 青葉ゆうな
【TNKD-027】THE LOVE STORIES 青葉ゆうな
【AOBD-004】FAKE4 とまどう素顔 青葉ゆうな
【AOBD-003】FAKE3 おしゃべりな唇 青葉ゆうな
【AOBD-002】FAKE2 ロマンティックな狂気 青葉ゆうな
【AOBD-001】FAKE 作られしもの 青葉ゆうな
【VIP-221】アイドル宅配便 青葉ゆうなをお届けします。
【MDL-225】男喰い痴女病棟 ~淫乳女医と変態ナースの秘密痴療~
【MDL-212】僕のお姉ちゃん達は女教師
【LLD-008】僕の女教師ペット 青葉ゆうな</a>2004-11-12プレステージ$$$LOVERs LOCK119分钟 | {
"pile_set_name": "Github"
} |
package org.bukkit.craftbukkit.v1_12_R1.entity;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSet.Builder;
import java.util.Set;
import net.minecraft.entity.MultiPartEntityPart;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.dragon.phase.PhaseList;
import org.bukkit.craftbukkit.v1_12_R1.CraftServer;
import org.bukkit.entity.ComplexEntityPart;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.EntityType;
public class CraftEnderDragon extends CraftComplexLivingEntity implements EnderDragon {
public CraftEnderDragon(CraftServer server, EntityDragon entity) {
super(server, entity);
}
public Set<ComplexEntityPart> getParts() {
Builder<ComplexEntityPart> builder = ImmutableSet.builder();
for (MultiPartEntityPart part : getHandle().dragonPartArray) {
builder.add((ComplexEntityPart) part.getBukkitEntity());
}
return builder.build();
}
@Override
public EntityDragon getHandle() {
return (EntityDragon) entity;
}
@Override
public String toString() {
return "CraftEnderDragon";
}
public EntityType getType() {
return EntityType.ENDER_DRAGON;
}
@Override
public Phase getPhase() {
return Phase.values()[getHandle().getDataManager().get(EntityDragon.PHASE)];
}
@Override
public void setPhase(Phase phase) {
getHandle().getPhaseManager().setPhase(getMinecraftPhase(phase));
}
public static Phase getBukkitPhase(PhaseList phase) {
return Phase.values()[phase.getId()];
}
public static PhaseList getMinecraftPhase(Phase phase) {
return PhaseList.getById(phase.ordinal());
}
}
| {
"pile_set_name": "Github"
} |
\input texinfo @c -*- texinfo -*-
@settitle ffplay Documentation
@titlepage
@center @titlefont{ffplay Documentation}
@end titlepage
@top
@contents
@chapter Synopsis
@example
@c man begin SYNOPSIS
ffplay [options] [@file{input_file}]
@c man end
@end example
@chapter Description
@c man begin DESCRIPTION
FFplay is a very simple and portable media player using the FFmpeg
libraries and the SDL library. It is mostly used as a testbed for the
various FFmpeg APIs.
@c man end
@chapter Options
@c man begin OPTIONS
@include avtools-common-opts.texi
@section Main options
@table @option
@item -x @var{width}
Force displayed width.
@item -y @var{height}
Force displayed height.
@item -s @var{size}
Set frame size (WxH or abbreviation), needed for videos which do
not contain a header with the frame size like raw YUV. This option
has been deprecated in favor of private options, try -video_size.
@item -an
Disable audio.
@item -vn
Disable video.
@item -ss @var{pos}
Seek to a given position in seconds.
@item -t @var{duration}
play <duration> seconds of audio/video
@item -bytes
Seek by bytes.
@item -nodisp
Disable graphical display.
@item -f @var{fmt}
Force format.
@item -window_title @var{title}
Set window title (default is the input filename).
@item -loop @var{number}
Loops movie playback <number> times. 0 means forever.
@item -showmode @var{mode}
Set the show mode to use.
Available values for @var{mode} are:
@table @samp
@item 0, video
show video
@item 1, waves
show audio waves
@item 2, rdft
show audio frequency band using RDFT ((Inverse) Real Discrete Fourier Transform)
@end table
Default value is "video", if video is not present or cannot be played
"rdft" is automatically selected.
You can interactively cycle through the available show modes by
pressing the key @key{w}.
@item -vf @var{filter_graph}
@var{filter_graph} is a description of the filter graph to apply to
the input video.
Use the option "-filters" to show all the available filters (including
also sources and sinks).
@item -i @var{input_file}
Read @var{input_file}.
@end table
@section Advanced options
@table @option
@item -pix_fmt @var{format}
Set pixel format.
This option has been deprecated in favor of private options, try -pixel_format.
@item -stats
Show the stream duration, the codec parameters, the current position in
the stream and the audio/video synchronisation drift.
@item -bug
Work around bugs.
@item -fast
Non-spec-compliant optimizations.
@item -genpts
Generate pts.
@item -rtp_tcp
Force RTP/TCP protocol usage instead of RTP/UDP. It is only meaningful
if you are streaming with the RTSP protocol.
@item -sync @var{type}
Set the master clock to audio (@code{type=audio}), video
(@code{type=video}) or external (@code{type=ext}). Default is audio. The
master clock is used to control audio-video synchronization. Most media
players use audio as master clock, but in some cases (streaming or high
quality broadcast) it is necessary to change that. This option is mainly
used for debugging purposes.
@item -threads @var{count}
Set the thread count.
@item -ast @var{audio_stream_number}
Select the desired audio stream number, counting from 0. The number
refers to the list of all the input audio streams. If it is greater
than the number of audio streams minus one, then the last one is
selected, if it is negative the audio playback is disabled.
@item -vst @var{video_stream_number}
Select the desired video stream number, counting from 0. The number
refers to the list of all the input video streams. If it is greater
than the number of video streams minus one, then the last one is
selected, if it is negative the video playback is disabled.
@item -sst @var{subtitle_stream_number}
Select the desired subtitle stream number, counting from 0. The number
refers to the list of all the input subtitle streams. If it is greater
than the number of subtitle streams minus one, then the last one is
selected, if it is negative the subtitle rendering is disabled.
@item -autoexit
Exit when video is done playing.
@item -exitonkeydown
Exit if any key is pressed.
@item -exitonmousedown
Exit if any mouse button is pressed.
@item -codec:@var{stream_type}
Force a specific decoder implementation
@end table
@section While playing
@table @key
@item q, ESC
Quit.
@item f
Toggle full screen.
@item p, SPC
Pause.
@item a
Cycle audio channel.
@item v
Cycle video channel.
@item t
Cycle subtitle channel.
@item w
Show audio waves.
@item left/right
Seek backward/forward 10 seconds.
@item down/up
Seek backward/forward 1 minute.
@item page down/page up
Seek backward/forward 10 minutes.
@item mouse click
Seek to percentage in file corresponding to fraction of width.
@end table
@c man end
@include eval.texi
@include decoders.texi
@include demuxers.texi
@include muxers.texi
@include indevs.texi
@include outdevs.texi
@include protocols.texi
@include filters.texi
@ignore
@setfilename ffplay
@settitle FFplay media player
@c man begin SEEALSO
ffmpeg(1), ffprobe(1), ffserver(1) and the FFmpeg HTML documentation
@c man end
@c man begin AUTHORS
The FFmpeg developers
@c man end
@end ignore
@bye
| {
"pile_set_name": "Github"
} |
submit=\u63d0\u51fa
cancel=\u30ad\u30e3\u30f3\u30bb\u30eb
askQuestion=\u8cea\u554f\u3059\u308b
firstname=\u540d
lastname=\u59d3
emailAddress=\u96fb\u5b50\u30e1\u30fc\u30eb\u30a2\u30c9\u30ec\u30b9
username=\u30e6\u30fc\u30b6\u30fc\u540d
subject=\u4ef6\u540d
content=\u8cea\u554f\u3092\u5165\u529b\u3059\u308b\u304b\u3001\u554f\u984c\u3092\u8a18\u8ff0\u3057\u3066\u304f\u3060\u3055\u3044
description=\u5fc5\u8981\u306a\u56de\u7b54\u304c\u898b\u3064\u304b\u3089\u306a\u304b\u3063\u305f\u5834\u5408\u306f\u3001\u30b5\u30dd\u30fc\u30c8\u30b3\u30f3\u30b5\u30eb\u30bf\u30f3\u30c8\u306b\u8cea\u554f\u3092\u9001\u4fe1\u3067\u304d\u307e\u3059\u3002 \u6b21\u306e\u60c5\u5831\u3092\u3067\u304d\u308b\u3060\u3051\u6b63\u78ba\u306b\u3059\u3079\u3066\u5165\u529b\u3057\u3066\u304f\u3060\u3055\u3044\u3002
confirmaton=\u8cea\u554f\u3092\u3054\u63d0\u51fa\u3044\u305f\u3060\u304d\u3001\u3042\u308a\u304c\u3068\u3046\u3054\u3056\u3044\u307e\u3057\u305f\u3002
reset=\u4ed6\u306e\u8cea\u554f\u3092\u63d0\u51fa
search=\u30d8\u30eb\u30d7\u3092\u691c\u7d22
search_button=\u691c\u7d22
search_result=\u691c\u7d22\u7d50\u679c
search_result_summary=\u691c\u7d22\u7d50\u679c\u306e\u4e00\u89a7\u3067\u3059\u3002 \u5217 1 \u306f\u8a18\u4e8b\u3078\u306e\u30ea\u30f3\u30af\u3001\u5217 2 \u306f\u91cd\u8981\u5ea6\u3067\u3059\u3002
back=< \u623b\u308b
forward=\u6b21\u3078 >
closeHelp=\u30d8\u30eb\u30d7\u3092\u9589\u3058\u308b
ask_more_help=\u3055\u3089\u306b\u30d8\u30eb\u30d7\u304c\u5fc5\u8981\u306a\u5834\u5408\u306f\u3053\u3053\u3092\u30af\u30ea\u30c3\u30af
table_of_contents=\u76ee\u6b21
contact_info = \u9023\u7d61\u5148\u60c5\u5831
searching = \u691c\u7d22\u3057\u3066\u3044\u307e\u3059.....\u3057\u3070\u3089\u304f\u304a\u5f85\u3061\u304f\u3060\u3055\u3044
search_term = \u691c\u7d22\u8a9e\u3092\u5165\u529b\u3057\u307e\u3059
no_results = \u691c\u7d22\u6761\u4ef6\u306b\u4e00\u81f4\u3059\u308b\u7d50\u679c\u304c\u898b\u3064\u304b\u308a\u307e\u305b\u3093\u3067\u3057\u305f
results_found = \u4ef6\u306e\u7d50\u679c\u304c\u898b\u3064\u304b\u308a\u307e\u3057\u305f
title_edit = \u7de8\u96c6
help = \u30d8\u30eb\u30d7
| {
"pile_set_name": "Github"
} |
*> \brief \b SSYTRI_3X
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download SSYTRI_3X + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/ssytri_3x.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/ssytri_3x.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/ssytri_3x.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE SSYTRI_3X( UPLO, N, A, LDA, E, IPIV, WORK, NB, INFO )
*
* .. Scalar Arguments ..
* CHARACTER UPLO
* INTEGER INFO, LDA, N, NB
* ..
* .. Array Arguments ..
* INTEGER IPIV( * )
* REAL A( LDA, * ), E( * ), WORK( N+NB+1, * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*> SSYTRI_3X computes the inverse of a real symmetric indefinite
*> matrix A using the factorization computed by SSYTRF_RK or SSYTRF_BK:
*>
*> A = P*U*D*(U**T)*(P**T) or A = P*L*D*(L**T)*(P**T),
*>
*> where U (or L) is unit upper (or lower) triangular matrix,
*> U**T (or L**T) is the transpose of U (or L), P is a permutation
*> matrix, P**T is the transpose of P, and D is symmetric and block
*> diagonal with 1-by-1 and 2-by-2 diagonal blocks.
*>
*> This is the blocked version of the algorithm, calling Level 3 BLAS.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] UPLO
*> \verbatim
*> UPLO is CHARACTER*1
*> Specifies whether the details of the factorization are
*> stored as an upper or lower triangular matrix.
*> = 'U': Upper triangle of A is stored;
*> = 'L': Lower triangle of A is stored.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The order of the matrix A. N >= 0.
*> \endverbatim
*>
*> \param[in,out] A
*> \verbatim
*> A is REAL array, dimension (LDA,N)
*> On entry, diagonal of the block diagonal matrix D and
*> factors U or L as computed by SYTRF_RK and SSYTRF_BK:
*> a) ONLY diagonal elements of the symmetric block diagonal
*> matrix D on the diagonal of A, i.e. D(k,k) = A(k,k);
*> (superdiagonal (or subdiagonal) elements of D
*> should be provided on entry in array E), and
*> b) If UPLO = 'U': factor U in the superdiagonal part of A.
*> If UPLO = 'L': factor L in the subdiagonal part of A.
*>
*> On exit, if INFO = 0, the symmetric inverse of the original
*> matrix.
*> If UPLO = 'U': the upper triangular part of the inverse
*> is formed and the part of A below the diagonal is not
*> referenced;
*> If UPLO = 'L': the lower triangular part of the inverse
*> is formed and the part of A above the diagonal is not
*> referenced.
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*> LDA is INTEGER
*> The leading dimension of the array A. LDA >= max(1,N).
*> \endverbatim
*>
*> \param[in] E
*> \verbatim
*> E is REAL array, dimension (N)
*> On entry, contains the superdiagonal (or subdiagonal)
*> elements of the symmetric block diagonal matrix D
*> with 1-by-1 or 2-by-2 diagonal blocks, where
*> If UPLO = 'U': E(i) = D(i-1,i), i=2:N, E(1) not referenced;
*> If UPLO = 'L': E(i) = D(i+1,i), i=1:N-1, E(N) not referenced.
*>
*> NOTE: For 1-by-1 diagonal block D(k), where
*> 1 <= k <= N, the element E(k) is not referenced in both
*> UPLO = 'U' or UPLO = 'L' cases.
*> \endverbatim
*>
*> \param[in] IPIV
*> \verbatim
*> IPIV is INTEGER array, dimension (N)
*> Details of the interchanges and the block structure of D
*> as determined by SSYTRF_RK or SSYTRF_BK.
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*> WORK is REAL array, dimension (N+NB+1,NB+3).
*> \endverbatim
*>
*> \param[in] NB
*> \verbatim
*> NB is INTEGER
*> Block size.
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0: successful exit
*> < 0: if INFO = -i, the i-th argument had an illegal value
*> > 0: if INFO = i, D(i,i) = 0; the matrix is singular and its
*> inverse could not be computed.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date June 2017
*
*> \ingroup singleSYcomputational
*
*> \par Contributors:
* ==================
*> \verbatim
*>
*> June 2017, Igor Kozachenko,
*> Computer Science Division,
*> University of California, Berkeley
*>
*> \endverbatim
*
* =====================================================================
SUBROUTINE SSYTRI_3X( UPLO, N, A, LDA, E, IPIV, WORK, NB, INFO )
*
* -- LAPACK computational routine (version 3.7.1) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* June 2017
*
* .. Scalar Arguments ..
CHARACTER UPLO
INTEGER INFO, LDA, N, NB
* ..
* .. Array Arguments ..
INTEGER IPIV( * )
REAL A( LDA, * ), E( * ), WORK( N+NB+1, * )
* ..
*
* =====================================================================
*
* .. Parameters ..
REAL ONE, ZERO
PARAMETER ( ONE = 1.0E+0, ZERO = 0.0E+0 )
* ..
* .. Local Scalars ..
LOGICAL UPPER
INTEGER CUT, I, ICOUNT, INVD, IP, K, NNB, J, U11
REAL AK, AKKP1, AKP1, D, T, U01_I_J, U01_IP1_J,
$ U11_I_J, U11_IP1_J
* ..
* .. External Functions ..
LOGICAL LSAME
EXTERNAL LSAME
* ..
* .. External Subroutines ..
EXTERNAL SGEMM, SSYSWAPR, STRTRI, STRMM, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC ABS, MAX, MOD
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
UPPER = LSAME( UPLO, 'U' )
IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN
INFO = -1
ELSE IF( N.LT.0 ) THEN
INFO = -2
ELSE IF( LDA.LT.MAX( 1, N ) ) THEN
INFO = -4
END IF
*
* Quick return if possible
*
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'SSYTRI_3X', -INFO )
RETURN
END IF
IF( N.EQ.0 )
$ RETURN
*
* Workspace got Non-diag elements of D
*
DO K = 1, N
WORK( K, 1 ) = E( K )
END DO
*
* Check that the diagonal matrix D is nonsingular.
*
IF( UPPER ) THEN
*
* Upper triangular storage: examine D from bottom to top
*
DO INFO = N, 1, -1
IF( IPIV( INFO ).GT.0 .AND. A( INFO, INFO ).EQ.ZERO )
$ RETURN
END DO
ELSE
*
* Lower triangular storage: examine D from top to bottom.
*
DO INFO = 1, N
IF( IPIV( INFO ).GT.0 .AND. A( INFO, INFO ).EQ.ZERO )
$ RETURN
END DO
END IF
*
INFO = 0
*
* Splitting Workspace
* U01 is a block ( N, NB+1 )
* The first element of U01 is in WORK( 1, 1 )
* U11 is a block ( NB+1, NB+1 )
* The first element of U11 is in WORK( N+1, 1 )
*
U11 = N
*
* INVD is a block ( N, 2 )
* The first element of INVD is in WORK( 1, INVD )
*
INVD = NB + 2
IF( UPPER ) THEN
*
* Begin Upper
*
* invA = P * inv(U**T) * inv(D) * inv(U) * P**T.
*
CALL STRTRI( UPLO, 'U', N, A, LDA, INFO )
*
* inv(D) and inv(D) * inv(U)
*
K = 1
DO WHILE( K.LE.N )
IF( IPIV( K ).GT.0 ) THEN
* 1 x 1 diagonal NNB
WORK( K, INVD ) = ONE / A( K, K )
WORK( K, INVD+1 ) = ZERO
ELSE
* 2 x 2 diagonal NNB
T = WORK( K+1, 1 )
AK = A( K, K ) / T
AKP1 = A( K+1, K+1 ) / T
AKKP1 = WORK( K+1, 1 ) / T
D = T*( AK*AKP1-ONE )
WORK( K, INVD ) = AKP1 / D
WORK( K+1, INVD+1 ) = AK / D
WORK( K, INVD+1 ) = -AKKP1 / D
WORK( K+1, INVD ) = WORK( K, INVD+1 )
K = K + 1
END IF
K = K + 1
END DO
*
* inv(U**T) = (inv(U))**T
*
* inv(U**T) * inv(D) * inv(U)
*
CUT = N
DO WHILE( CUT.GT.0 )
NNB = NB
IF( CUT.LE.NNB ) THEN
NNB = CUT
ELSE
ICOUNT = 0
* count negative elements,
DO I = CUT+1-NNB, CUT
IF( IPIV( I ).LT.0 ) ICOUNT = ICOUNT + 1
END DO
* need a even number for a clear cut
IF( MOD( ICOUNT, 2 ).EQ.1 ) NNB = NNB + 1
END IF
CUT = CUT - NNB
*
* U01 Block
*
DO I = 1, CUT
DO J = 1, NNB
WORK( I, J ) = A( I, CUT+J )
END DO
END DO
*
* U11 Block
*
DO I = 1, NNB
WORK( U11+I, I ) = ONE
DO J = 1, I-1
WORK( U11+I, J ) = ZERO
END DO
DO J = I+1, NNB
WORK( U11+I, J ) = A( CUT+I, CUT+J )
END DO
END DO
*
* invD * U01
*
I = 1
DO WHILE( I.LE.CUT )
IF( IPIV( I ).GT.0 ) THEN
DO J = 1, NNB
WORK( I, J ) = WORK( I, INVD ) * WORK( I, J )
END DO
ELSE
DO J = 1, NNB
U01_I_J = WORK( I, J )
U01_IP1_J = WORK( I+1, J )
WORK( I, J ) = WORK( I, INVD ) * U01_I_J
$ + WORK( I, INVD+1 ) * U01_IP1_J
WORK( I+1, J ) = WORK( I+1, INVD ) * U01_I_J
$ + WORK( I+1, INVD+1 ) * U01_IP1_J
END DO
I = I + 1
END IF
I = I + 1
END DO
*
* invD1 * U11
*
I = 1
DO WHILE ( I.LE.NNB )
IF( IPIV( CUT+I ).GT.0 ) THEN
DO J = I, NNB
WORK( U11+I, J ) = WORK(CUT+I,INVD) * WORK(U11+I,J)
END DO
ELSE
DO J = I, NNB
U11_I_J = WORK(U11+I,J)
U11_IP1_J = WORK(U11+I+1,J)
WORK( U11+I, J ) = WORK(CUT+I,INVD) * WORK(U11+I,J)
$ + WORK(CUT+I,INVD+1) * WORK(U11+I+1,J)
WORK( U11+I+1, J ) = WORK(CUT+I+1,INVD) * U11_I_J
$ + WORK(CUT+I+1,INVD+1) * U11_IP1_J
END DO
I = I + 1
END IF
I = I + 1
END DO
*
* U11**T * invD1 * U11 -> U11
*
CALL STRMM( 'L', 'U', 'T', 'U', NNB, NNB,
$ ONE, A( CUT+1, CUT+1 ), LDA, WORK( U11+1, 1 ),
$ N+NB+1 )
*
DO I = 1, NNB
DO J = I, NNB
A( CUT+I, CUT+J ) = WORK( U11+I, J )
END DO
END DO
*
* U01**T * invD * U01 -> A( CUT+I, CUT+J )
*
CALL SGEMM( 'T', 'N', NNB, NNB, CUT, ONE, A( 1, CUT+1 ),
$ LDA, WORK, N+NB+1, ZERO, WORK(U11+1,1), N+NB+1 )
*
* U11 = U11**T * invD1 * U11 + U01**T * invD * U01
*
DO I = 1, NNB
DO J = I, NNB
A( CUT+I, CUT+J ) = A( CUT+I, CUT+J ) + WORK(U11+I,J)
END DO
END DO
*
* U01 = U00**T * invD0 * U01
*
CALL STRMM( 'L', UPLO, 'T', 'U', CUT, NNB,
$ ONE, A, LDA, WORK, N+NB+1 )
*
* Update U01
*
DO I = 1, CUT
DO J = 1, NNB
A( I, CUT+J ) = WORK( I, J )
END DO
END DO
*
* Next Block
*
END DO
*
* Apply PERMUTATIONS P and P**T:
* P * inv(U**T) * inv(D) * inv(U) * P**T.
* Interchange rows and columns I and IPIV(I) in reverse order
* from the formation order of IPIV vector for Upper case.
*
* ( We can use a loop over IPIV with increment 1,
* since the ABS value of IPIV(I) represents the row (column)
* index of the interchange with row (column) i in both 1x1
* and 2x2 pivot cases, i.e. we don't need separate code branches
* for 1x1 and 2x2 pivot cases )
*
DO I = 1, N
IP = ABS( IPIV( I ) )
IF( IP.NE.I ) THEN
IF (I .LT. IP) CALL SSYSWAPR( UPLO, N, A, LDA, I ,IP )
IF (I .GT. IP) CALL SSYSWAPR( UPLO, N, A, LDA, IP ,I )
END IF
END DO
*
ELSE
*
* Begin Lower
*
* inv A = P * inv(L**T) * inv(D) * inv(L) * P**T.
*
CALL STRTRI( UPLO, 'U', N, A, LDA, INFO )
*
* inv(D) and inv(D) * inv(L)
*
K = N
DO WHILE ( K .GE. 1 )
IF( IPIV( K ).GT.0 ) THEN
* 1 x 1 diagonal NNB
WORK( K, INVD ) = ONE / A( K, K )
WORK( K, INVD+1 ) = ZERO
ELSE
* 2 x 2 diagonal NNB
T = WORK( K-1, 1 )
AK = A( K-1, K-1 ) / T
AKP1 = A( K, K ) / T
AKKP1 = WORK( K-1, 1 ) / T
D = T*( AK*AKP1-ONE )
WORK( K-1, INVD ) = AKP1 / D
WORK( K, INVD ) = AK / D
WORK( K, INVD+1 ) = -AKKP1 / D
WORK( K-1, INVD+1 ) = WORK( K, INVD+1 )
K = K - 1
END IF
K = K - 1
END DO
*
* inv(L**T) = (inv(L))**T
*
* inv(L**T) * inv(D) * inv(L)
*
CUT = 0
DO WHILE( CUT.LT.N )
NNB = NB
IF( (CUT + NNB).GT.N ) THEN
NNB = N - CUT
ELSE
ICOUNT = 0
* count negative elements,
DO I = CUT + 1, CUT+NNB
IF ( IPIV( I ).LT.0 ) ICOUNT = ICOUNT + 1
END DO
* need a even number for a clear cut
IF( MOD( ICOUNT, 2 ).EQ.1 ) NNB = NNB + 1
END IF
*
* L21 Block
*
DO I = 1, N-CUT-NNB
DO J = 1, NNB
WORK( I, J ) = A( CUT+NNB+I, CUT+J )
END DO
END DO
*
* L11 Block
*
DO I = 1, NNB
WORK( U11+I, I) = ONE
DO J = I+1, NNB
WORK( U11+I, J ) = ZERO
END DO
DO J = 1, I-1
WORK( U11+I, J ) = A( CUT+I, CUT+J )
END DO
END DO
*
* invD*L21
*
I = N-CUT-NNB
DO WHILE( I.GE.1 )
IF( IPIV( CUT+NNB+I ).GT.0 ) THEN
DO J = 1, NNB
WORK( I, J ) = WORK( CUT+NNB+I, INVD) * WORK( I, J)
END DO
ELSE
DO J = 1, NNB
U01_I_J = WORK(I,J)
U01_IP1_J = WORK(I-1,J)
WORK(I,J)=WORK(CUT+NNB+I,INVD)*U01_I_J+
$ WORK(CUT+NNB+I,INVD+1)*U01_IP1_J
WORK(I-1,J)=WORK(CUT+NNB+I-1,INVD+1)*U01_I_J+
$ WORK(CUT+NNB+I-1,INVD)*U01_IP1_J
END DO
I = I - 1
END IF
I = I - 1
END DO
*
* invD1*L11
*
I = NNB
DO WHILE( I.GE.1 )
IF( IPIV( CUT+I ).GT.0 ) THEN
DO J = 1, NNB
WORK( U11+I, J ) = WORK( CUT+I, INVD)*WORK(U11+I,J)
END DO
ELSE
DO J = 1, NNB
U11_I_J = WORK( U11+I, J )
U11_IP1_J = WORK( U11+I-1, J )
WORK( U11+I, J ) = WORK(CUT+I,INVD) * WORK(U11+I,J)
$ + WORK(CUT+I,INVD+1) * U11_IP1_J
WORK( U11+I-1, J ) = WORK(CUT+I-1,INVD+1) * U11_I_J
$ + WORK(CUT+I-1,INVD) * U11_IP1_J
END DO
I = I - 1
END IF
I = I - 1
END DO
*
* L11**T * invD1 * L11 -> L11
*
CALL STRMM( 'L', UPLO, 'T', 'U', NNB, NNB, ONE,
$ A( CUT+1, CUT+1 ), LDA, WORK( U11+1, 1 ),
$ N+NB+1 )
*
DO I = 1, NNB
DO J = 1, I
A( CUT+I, CUT+J ) = WORK( U11+I, J )
END DO
END DO
*
IF( (CUT+NNB).LT.N ) THEN
*
* L21**T * invD2*L21 -> A( CUT+I, CUT+J )
*
CALL SGEMM( 'T', 'N', NNB, NNB, N-NNB-CUT, ONE,
$ A( CUT+NNB+1, CUT+1 ), LDA, WORK, N+NB+1,
$ ZERO, WORK( U11+1, 1 ), N+NB+1 )
*
* L11 = L11**T * invD1 * L11 + U01**T * invD * U01
*
DO I = 1, NNB
DO J = 1, I
A( CUT+I, CUT+J ) = A( CUT+I, CUT+J )+WORK(U11+I,J)
END DO
END DO
*
* L01 = L22**T * invD2 * L21
*
CALL STRMM( 'L', UPLO, 'T', 'U', N-NNB-CUT, NNB, ONE,
$ A( CUT+NNB+1, CUT+NNB+1 ), LDA, WORK,
$ N+NB+1 )
*
* Update L21
*
DO I = 1, N-CUT-NNB
DO J = 1, NNB
A( CUT+NNB+I, CUT+J ) = WORK( I, J )
END DO
END DO
*
ELSE
*
* L11 = L11**T * invD1 * L11
*
DO I = 1, NNB
DO J = 1, I
A( CUT+I, CUT+J ) = WORK( U11+I, J )
END DO
END DO
END IF
*
* Next Block
*
CUT = CUT + NNB
*
END DO
*
* Apply PERMUTATIONS P and P**T:
* P * inv(L**T) * inv(D) * inv(L) * P**T.
* Interchange rows and columns I and IPIV(I) in reverse order
* from the formation order of IPIV vector for Lower case.
*
* ( We can use a loop over IPIV with increment -1,
* since the ABS value of IPIV(I) represents the row (column)
* index of the interchange with row (column) i in both 1x1
* and 2x2 pivot cases, i.e. we don't need separate code branches
* for 1x1 and 2x2 pivot cases )
*
DO I = N, 1, -1
IP = ABS( IPIV( I ) )
IF( IP.NE.I ) THEN
IF (I .LT. IP) CALL SSYSWAPR( UPLO, N, A, LDA, I ,IP )
IF (I .GT. IP) CALL SSYSWAPR( UPLO, N, A, LDA, IP ,I )
END IF
END DO
*
END IF
*
RETURN
*
* End of SSYTRI_3X
*
END
| {
"pile_set_name": "Github"
} |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Graphics.Printing.PrintTicket
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class PrintTicketParameterInitializer
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.Graphics.Printing.PrintTicket.PrintTicketValue Value
{
get
{
throw new global::System.NotImplementedException("The member PrintTicketValue PrintTicketParameterInitializer.Value is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Graphics.Printing.PrintTicket.PrintTicketParameterInitializer", "PrintTicketValue PrintTicketParameterInitializer.Value");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public string Name
{
get
{
throw new global::System.NotImplementedException("The member string PrintTicketParameterInitializer.Name is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public string XmlNamespace
{
get
{
throw new global::System.NotImplementedException("The member string PrintTicketParameterInitializer.XmlNamespace is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.Data.Xml.Dom.IXmlNode XmlNode
{
get
{
throw new global::System.NotImplementedException("The member IXmlNode PrintTicketParameterInitializer.XmlNode is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.Graphics.Printing.PrintTicket.PrintTicketParameterInitializer.Name.get
// Forced skipping of method Windows.Graphics.Printing.PrintTicket.PrintTicketParameterInitializer.XmlNamespace.get
// Forced skipping of method Windows.Graphics.Printing.PrintTicket.PrintTicketParameterInitializer.XmlNode.get
// Forced skipping of method Windows.Graphics.Printing.PrintTicket.PrintTicketParameterInitializer.Value.set
// Forced skipping of method Windows.Graphics.Printing.PrintTicket.PrintTicketParameterInitializer.Value.get
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 15005d98f1ec8a14f8fba753a3bdc521
timeCreated: 1485259006
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
//
// SoftDebuggerEngine.cs
//
// Author:
// Lluis Sanchez Gual <[email protected]>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using Mono.Debugging.Soft;
using Mono.Debugging.Client;
using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core.Assemblies;
using System.Threading.Tasks;
namespace MonoDevelop.Debugger.Soft
{
public class SoftDebuggerEngine: DebuggerEngineBackend
{
static SoftDebuggerEngine ()
{
DebuggerLoggingService.CustomLogger = new MDLogger ();
}
public override bool CanDebugCommand (ExecutionCommand cmd)
{
var netCmd = cmd as DotNetExecutionCommand;
if (netCmd == null)
return false;
return CanDebugRuntime (netCmd.TargetRuntime);
}
public override bool IsDefaultDebugger (ExecutionCommand cmd)
{
return true;
}
public static bool CanDebugRuntime (TargetRuntime runtime)
{
var mrun = runtime as MonoTargetRuntime;
if (mrun == null)
return false;
return mrun.AssemblyContext.GetAssemblyLocation ("Mono.Debugger.Soft", null) != null;
}
public override DebuggerStartInfo CreateDebuggerStartInfo (ExecutionCommand c)
{
var cmd = (DotNetExecutionCommand) c;
var runtime = (MonoTargetRuntime)cmd.TargetRuntime;
var dsi = new SoftDebuggerStartInfo (null, runtime.EnvironmentVariables) {
Command = cmd.Command,
Arguments = cmd.Arguments,
RuntimeArguments = cmd.RuntimeArguments,
WorkingDirectory = cmd.WorkingDirectory,
};
((SoftDebuggerLaunchArgs)dsi.StartArgs).MonoExecutableFileName = runtime.GetMonoExecutableForAssembly (cmd.Command);
SetUserAssemblyNames (dsi, cmd.UserAssemblyPaths);
foreach (KeyValuePair<string,string> var in cmd.EnvironmentVariables)
dsi.EnvironmentVariables [var.Key] = var.Value;
var varsCopy = new Dictionary<string, string> (cmd.EnvironmentVariables);
var startArgs = (SoftDebuggerLaunchArgs) dsi.StartArgs;
startArgs.ExternalConsoleLauncher = delegate (System.Diagnostics.ProcessStartInfo info) {
ProcessAsyncOperation oper;
oper = Runtime.ProcessService.StartConsoleProcess (info.FileName, info.Arguments, info.WorkingDirectory,
ExternalConsoleFactory.Instance.CreateConsole (dsi.CloseExternalConsoleOnExit), varsCopy);
return new ProcessAdapter (oper, Path.GetFileName (info.FileName));
};
return dsi;
}
public override DebuggerSession CreateSession ()
{
return new SoftDebuggerSession ();
}
public static void SetUserAssemblyNames (SoftDebuggerStartInfo dsi, IList<string> files)
{
if (files == null || files.Count == 0)
return;
var pathMap = new Dictionary<string, string> ();
var names = new List<AssemblyName> ();
foreach (var file in files) {
if (!File.Exists (file)) {
dsi.LogMessage = GettextCatalog.GetString ("User assembly '{0}' is missing. " +
"Debugger will now debug all code, not just user code.", file);
continue;
}
try {
using (var asm = Mono.Cecil.AssemblyDefinition.ReadAssembly (file)) {
if (string.IsNullOrEmpty (asm.Name.Name))
throw new InvalidOperationException ("Assembly has no assembly name");
AssemblyName name = new AssemblyName (asm.Name.FullName);
if (!pathMap.ContainsKey (asm.Name.FullName))
pathMap.Add (asm.Name.FullName, file);
names.Add (name);
}
} catch (Exception ex) {
dsi.LogMessage = GettextCatalog.GetString ("Could not get assembly name for user assembly '{0}'. " +
"Debugger will now debug all code, not just user code.", file);
LoggingService.LogError ("Error getting assembly name for user assembly '" + file + "'", ex);
continue;
}
}
dsi.UserAssemblyNames = names;
dsi.AssemblyPathMap = pathMap;
}
class MDLogger : ICustomLogger
{
public string GetNewDebuggerLogFilename ()
{
if (PropertyService.Get ("MonoDevelop.Debugger.DebuggingService.DebuggerLogging", false)) {
string filename;
var logWriter = LoggingService.CreateLogFile ("Debugger", out filename);
logWriter.Dispose ();
return filename;
} else {
return null;
}
}
public void LogError (string message, Exception ex)
{
LoggingService.LogError (message, ex);
}
public void LogAndShowException (string message, Exception ex)
{
MonoDevelop.Ide.MessageService.ShowError (message, ex);
}
public void LogMessage (string messageFormat, params object[] args)
{
LoggingService.LogInfo (messageFormat, args);
}
}
}
class ProcessAdapter: Mono.Debugger.Soft.ITargetProcess
{
ProcessAsyncOperation oper;
string name;
public ProcessAdapter (ProcessAsyncOperation oper, string name)
{
this.oper = oper;
this.name = name;
oper.Task.ContinueWith (t => {
if (Exited != null)
Exited (this, EventArgs.Empty);
}, Runtime.MainTaskScheduler);
}
#region IProcess implementation
public event EventHandler Exited;
public void Kill ()
{
oper.Cancel ();
}
public StreamReader StandardOutput {
get {
// Not supported in external console
throw new System.NotSupportedException ();
}
}
public StreamReader StandardError {
get {
// Not supported in external console
throw new System.NotSupportedException ();
}
}
public bool HasExited {
get {
return oper.IsCompleted;
}
}
public int Id {
get {
return oper.ProcessId;
}
}
public string ProcessName {
get {
return name;
}
}
#endregion
}
}
| {
"pile_set_name": "Github"
} |
package zhan.pull.delegate
import android.view.MotionEvent
import android.view.View
import zhan.pull.ScrollState
import zhan.pull.listener.OnStateChangeListener
class ScrollBodyDelegate(private val mTargetView: View) : ScrollerDelegate(mTargetView) {
private var mMaxOffset: Int = 0
private var mLastY: Float = 0.toFloat()
private var mMoveY: Int = 0
var state = ScrollState.SHOW
private var mOnStateChangeListener: OnStateChangeListener? = null
fun setMaxOffset(offset: Int) {
mMaxOffset = offset
}
fun onTouchEvent(event: MotionEvent): Boolean {
if (state === ScrollState.HIDE) {
return false
}
val y = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> mLastY = y
MotionEvent.ACTION_MOVE -> {
val moveY = (y - mLastY).toInt()
if (mTargetView.scrollY <= 0 && moveY > 0) {
val offset = moveY / 2
move(offset)
}
mLastY = y
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> changeState()
}
return true
}
private fun move(offset: Int) {
state = ScrollState.MOVE
if (mOnStateChangeListener != null) {
mOnStateChangeListener!!.pullViewMove(state, -offset)
}
mTargetView.scrollBy(0, -offset)
}
private fun hide() {
state = ScrollState.HIDE
if (mOnStateChangeListener != null) {
mOnStateChangeListener!!.pullViewHide(state)
}
mMoveY = mTargetView.measuredHeight + Math.abs(mTargetView.scrollY)
smoothScrollTo(0, mTargetView.scrollY, 0, -mMoveY, NORMAL_TIME * 3)
}
fun hide(time: Int) {
state = ScrollState.HIDE
if (mOnStateChangeListener != null) {
mOnStateChangeListener!!.pullViewHide(state)
}
mMoveY = mTargetView.measuredHeight + Math.abs(mTargetView.scrollY)
smoothScrollTo(0, mTargetView.scrollY, 0, -mMoveY, time)
}
private fun show() {
state = ScrollState.SHOW
if (mOnStateChangeListener != null) {
mOnStateChangeListener!!.pullViewShow(state)
}
smoothScrollTo(0, mTargetView.scrollY, 0, -mTargetView.scrollY,
mTargetView.scrollY)
}
private fun changeState() {
if (Math.abs(mTargetView.scrollY) > mMaxOffset + 50) {
hide()
} else {
show()
}
}
fun open() {
state = ScrollState.OPEN_START
if (mOnStateChangeListener != null) {
mOnStateChangeListener!!.pullViewOpenStart()
}
smoothScrollTo(0, -mMoveY, 0, mMoveY, NORMAL_TIME)
mTargetView.postDelayed({
state = ScrollState.OPEN_FINISH
if (mOnStateChangeListener != null) {
mOnStateChangeListener!!.pullViewOpenFinish()
}
}, NORMAL_TIME.toLong())
}
fun setOnStateChangeListener(listener: OnStateChangeListener) {
mOnStateChangeListener = listener
}
companion object {
private val NORMAL_TIME = 600
}
}
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='utf-8'?>
<section xmlns="https://code.dccouncil.us/schemas/dc-library" xmlns:codified="https://code.dccouncil.us/schemas/codified" xmlns:codify="https://code.dccouncil.us/schemas/codify" xmlns:xi="http://www.w3.org/2001/XInclude" containing-doc="D.C. Code">
<num>29-402.05</num>
<heading>Organization of corporation.</heading>
<para>
<num>(a)</num>
<text>After incorporation:</text>
<para>
<num>(1)</num>
<text>If initial directors or members of a designated body are named in the articles of incorporation, those persons shall hold an organizational meeting, as appropriate, at the call of a majority of them, to complete the organization of the nonprofit corporation by electing directors, when the organization of the corporation is to be completed by a designated body, appointing officers, adopting bylaws, and carrying on any other business brought before the meeting;</text>
</para>
<para>
<num>(2)</num>
<text>If initial directors or members of a designated body are not named in the articles, the incorporator or incorporators shall hold an organizational meeting at the call of a majority of the incorporators to elect:</text>
<para>
<num>(A)</num>
<text>Directors and complete the organization of the nonprofit corporation; or</text>
</para>
<para>
<num>(B)</num>
<text>A board of directors who shall complete the organization of the corporation.</text>
</para>
</para>
</para>
<para>
<num>(b)</num>
<text>Action required or permitted by this chapter to be taken by incorporators at an organizational meeting may be taken without a meeting if the action taken is evidenced by one or more consents in the form of a record describing the action taken and signed by each incorporator.</text>
</para>
<para>
<num>(c)</num>
<text>An organizational meeting may be held in or outside of the District.</text>
</para>
<annotations>
<annotation doc="D.C. Law 18-378" type="History">July 2, 2011, D.C. Law 18-378, § 2, 58 DCR 1720</annotation>
</annotations>
</section>
| {
"pile_set_name": "Github"
} |
{
"version": "0.1.0",
"command": "dotnet",
"isShellCommand": true,
"args": [],
"tasks": [
{
"taskName": "build",
"args": [
"${workspaceRoot}\\dotnet-retire\\dotnet-retire.csproj"
],
"isBuildCommand": true,
"problemMatcher": "$msCompile"
}
]
} | {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.