repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
pfhello/v-shop
v-model/src/main/java/cn/itcast/shop/pojo/User.java
<gh_stars>0 package cn.itcast.shop.pojo; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class User implements Serializable{ /* `uid` varchar(32) NOT NULL, `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, `name` varchar(20) DEFAULT NULL, `email` varchar(30) DEFAULT NULL, `telephone` varchar(20) DEFAULT NULL, `birthday` date DEFAULT NULL, `sex` varchar(10) DEFAULT NULL, `state` int(11) DEFAULT NULL, `code` varchar(64) DEFAULT NULL,*/ private String uid; private String username; private String password; private String name; private String email; private String telephone; private Date birthday; private String sex; private Integer state;//是否激活 private String code;//激活码 }
lxhlzq/metasfresh
backend/de.metas.business/src/main/java/de/metas/security/permissions/bpartner_hierarchy/handlers/BPartnerDependentDocumentHandlersMap.java
package de.metas.security.permissions.bpartner_hierarchy.handlers; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.util.lang.impl.TableRecordReference; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import de.metas.bpartner.BPartnerId; import lombok.NonNull; import lombok.ToString; /* * #%L * de.metas.business * %% * Copyright (C) 2019 metas GmbH * %% * 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, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @ToString(of = "handlersByTableName") public class BPartnerDependentDocumentHandlersMap { public static BPartnerDependentDocumentHandlersMap of(@NonNull final List<BPartnerDependentDocumentHandler> handlers) { return new BPartnerDependentDocumentHandlersMap(handlers); } private final ImmutableMap<String, BPartnerDependentDocumentHandler> handlersByTableName; private BPartnerDependentDocumentHandlersMap(@NonNull final List<BPartnerDependentDocumentHandler> handlers) { handlersByTableName = Maps.uniqueIndex(handlers, BPartnerDependentDocumentHandler::getDocumentTableName); } public ImmutableSet<String> getTableNames() { return handlersByTableName.keySet(); } public Stream<TableRecordReference> streamBPartnerRelatedRecords(@NonNull final BPartnerId bpartnerId) { return handlersByTableName.values() .stream() .flatMap(handler -> handler.streamRelatedDocumentsByBPartnerId(bpartnerId)); } public Optional<BPartnerDependentDocument> extractBPartnerDependentDocumentFromDocumentObj(final Object documentObj) { final String documentTableName = InterfaceWrapperHelper.getModelTableName(documentObj); final BPartnerDependentDocumentHandler handler = handlersByTableName.get(documentTableName); if (handler == null) { return Optional.empty(); } final BPartnerDependentDocument doc = handler.extractBPartnerDependentDocumentFromDocumentObj(documentObj); return Optional.of(doc); } }
wb14123/bard
bard-basic/src/main/java/com/bardframework/bard/basic/injector/DocInjector.java
package com.bardframework.bard.basic.injector; import com.bardframework.bard.basic.marker.Doc; import com.bardframework.bard.core.BindTo; import com.bardframework.bard.core.Injector; @BindTo(Doc.class) public class DocInjector extends Injector<Doc> { @Override public void generateDoc() { docParameter.description = annotation.value(); } }
Mavennix/eltaj
src/data/footer-menu.js
<filename>src/data/footer-menu.js const footerMenu = [ { title: "ELTAJ", menuItems: [ { text: "About us", to: "/about", }, { text: "Career", to: "/career", }, { text: "Blog", to: "", }, { text: "Partners", to: "/partners", }, { text: "Terms and Condition", to: "/about-us", }, { text: "Privacy Policy", to: "/about-us", }, ], }, { title: "Solutions", menuItems: [ { text: "Queue Management", to: "/queue-management", }, { text: "Customer Journey Management", to: "/customer-journey-management", }, { text: "Customer Feedback", to: "/customer-feedback", }, { text: "Business Intelligence", to: "/business-intelligence", }, { text: "Virtual Queuing System", to: "/virtual-queuing-system", }, { text: "Distributed Operations", to: "/distributed-operations", }, { text: "Online Appointment Booking", to: "/online-appointment-booking", }, ], }, { title: "Industries", menuItems: [ { text: "Finance", to: "/finance", }, { text: "Healthcare", to: "/healthcare", }, { text: "Telecom", to: "/telecom", }, { text: "Public Sector", to: "/public-sector", }, ], }, ] export default footerMenu
ViseEngine/dhtmlx_web
assets/lib/dhtmlx/v403_pro/sources/dhtmlxPopup/codebase/dhtmlxpopup.js
/* Product Name: dhtmlxSuite Version: 4.0.3 Edition: Professional License: content of this file is covered by DHTMLX Commercial or Enterprise license. Usage without proper license is prohibited. To obtain it contact <EMAIL> Copyright <NAME> http://www.dhtmlx.com */ function dhtmlXPopup(conf) { var that = this; this.conf = conf||{}; conf = null; this.mode = (this.conf.mode||"bottom"); // popup position related to caller element this.conf.zi = window.dhx4.newId(); this.conf.isIE = (navigator.userAgent.indexOf("MSIE")>=0); this.p = document.createElement("DIV"); this.p.style.display = "none"; this.p.innerHTML = "<div class='dhx_popup_area"+(this.conf.isIE?" dhx_popup_area_ie":"")+"'>"+ "<table cellspacing='0' cellpadding='0' border='0' class='dhx_popup_table'><tbody></tbody></table>"+ "</div>"+ "<div class='dhx_popup_arrow dhx_popup_arrow_"+this.mode+"'></div>"; document.body.appendChild(this.p); this.skinParams = { dhx_terrace: { t0: 19, // minimal top offset for polygon, i.e. space between polygon top and arrow top t1: 9, // if no more space at top, and "t0 allowed" - move top polygon position a bit to bottom, t1 = offset for empty space at top t2: 19, // same as t0, for width t3: 9 // same as t1, for width }, dhx_skyblue: {t0: 12, t1: 9, t2: 12, t3: 9}, dhx_web: {t0: 12, t1: 9, t2: 12, t3: 9} }; this.p.onclick = function(e) { e = e||event; that._clearClick = true; if (that._nodeObj != null) { that.callEvent("onContentClick",[]); return true; } var t = (e.target||e.srcElement); var id = null; while (t != that.p && t != null) { if (typeof(t._idd) != "undefined" && !t._isSeparator) { id = t._idd; t = null; } else { t = t.parentNode; } } t = null; if (id != null) { that.callEvent("onClick",[id]); if (that != null && that.isVisible != null && that.isVisible() && that.callEvent("onBeforeHide",["select",e,id]) === true) { e.cancelBubble = true; that.hide(); } } } this.separator = "DHXSEP_"+window.dhx4.newId(); this.tpl = []; this._setTemplate = function(t) { this.tpl = t.split(","); } this.show = function(id) { // 4 coords for custom object, x, y, width, height var p = null; if (arguments.length == 1) { // if id not specified show on first if (!id) { id = this.conf.id[0]; } else { if (!this._idExists(id)) return; } if (this.conf.toolbar) { p = this.conf.toolbar._getItemDim(id); } if (this.conf.ribbon) { p = this.conf.ribbon._getItemDim(id); } if (this.conf.form) { p = this.conf.form._getItemDim(id); } } else if (arguments.length == 4) { this._clearClick = true; // show for custom object, 4 coords p = { left: arguments[0], top: arguments[1], width: arguments[2], height: arguments[3] } id = null; } if (!p) return; this.p.style.visibility = "hidden"; this.p.style.display = ""; this._setPos(p); this.p.style.zIndex = window.dhx4.zim.reserve(this.conf.zi); this.p.style.visibility = "visible"; this._lastId = id; this.callEvent("onShow",[id]); } this._setPos = function(p, state) { var x = p.left; var y = p.top; var w = p.width; var h = p.height; this._posData = { left: x, top: y, width: w, height: h }; var d = window.dhx4.screenDim(); var mode = state||this.mode; if (typeof(state) == "undefined") state = false; // avail space form each side, negative value = no-space var availSpace = { top: (y-this.p.offsetHeight)-d.top, bottom: d.bottom-(y+h+this.p.offsetHeight), left: x-this.p.offsetWidth-d.left, right: d.right-(x+w+this.p.offsetWidth) }; if (!state && availSpace[mode] < 0) { var k = this._getAvailPos(mode, availSpace); if (k !== false) { this._setPos(p, k); return; } } if (mode == "top" || mode == "bottom") { var t0 = this.skinParams[this.conf.skin].t2; var t1 = this.skinParams[this.conf.skin].t3; var pw2 = Math.round(this.p.offsetWidth/2); // 1/2 polygon width var aw2 = Math.round(this.p.lastChild.offsetWidth/2); // 1/2 arrow width // define max left and right position of input including rendering [d.left..d.right] area if (x < d.left) { var x1 = Math.min(x+w, d.left); w = x+w-x1; x = x1; } // left if (x+w > d.right) w = d.right-x; // right // arrow position var ta = Math.round(x+w/2); // polygon top var left = ta - pw2; var maxLeft = ta - t0 - aw2; var maxLeftRight = ta+aw2+t0-this.p.offsetWidth; if (left < d.left-t1) { // left left = Math.min(d.left-t1, maxLeft); } else if (left+this.p.offsetWidth > d.right+t1) { // right left = Math.max(maxLeftRight, d.right+t1-this.p.offsetWidth); // -scrollWidth here? } // draw polygon this.p.style.left = left+"px"; this.p.style.top = (mode=="top"?y-this.p.offsetHeight:y+h)+"px"; // fix arrow offset (it inside polygon) ta = ta-left-aw2; // draw arrow this.p.lastChild.className = "dhx_popup_arrow dhx_popup_arrow_"+mode; this.p.lastChild.style.top = (mode=="top"?this.p.offsetHeight-this.p.lastChild.offsetHeight:0)+"px"; this.p.lastChild.style.left = ta+"px"; } if (mode == "left" || mode == "right") { var t0 = this.skinParams[this.conf.skin].t0; var t1 = this.skinParams[this.conf.skin].t1; var ph2 = Math.round(this.p.offsetHeight/2); // 1/2 polygon height var ah2 = Math.round(this.p.lastChild.offsetHeight/2); // 1/2 arrow height // define max top and bottom position of input including rendering [d.top..d.bottom] area if (y < d.top) { var y1 = Math.min(y+h, d.top); h = y+h-y1; y = y1; } // top if (y+h > d.bottom) h = d.bottom-y; // bottom // arrow position var ta = Math.round(y+h/2); // polygon top var top = ta - ph2; var maxTop = ta - t0 - ah2; var maxTopBottom = ta+ah2+t0-this.p.offsetHeight; if (top < d.top-t1) { // top top = Math.min(d.top-t1, maxTop); } else if (top+this.p.offsetHeight > d.bottom+t1) { // bottom top = Math.max(maxTopBottom, d.bottom+t1-this.p.offsetHeight); } // draw polygon this.p.style.left = (mode=="left"?x-this.p.offsetWidth:x+w)+"px"; this.p.style.top = top+"px"; // fix arrow offset (it inside polygon) ta = ta-top-ah2; // draw arrow this.p.lastChild.className = "dhx_popup_arrow dhx_popup_arrow_"+mode; this.p.lastChild.style.left = (mode=="left"?this.p.offsetWidth-this.p.lastChild.offsetWidth:0)+"px"; this.p.lastChild.style.top = ta+"px"; } if (this._IEDisp && this._nodeId != null) { var t = document.getElementById(this._nodeId); //t.style.visibility = "hidden"; window.setTimeout(function(){ t.style.visibility = "visible"; t = null; },1); } } this._getAvailPos = function(mode, data) { var seq = { top: ["bottom","right","left"], bottom: ["top","right","left"], left: ["right", "bottom", "top"], right: ["left", "bottom", "top"] }; var dir = null; // check "next" with avail space for (var q=0; q<seq[mode].length; q++) { if (dir == null && data[seq[mode][q]] > 0) dir = seq[mode][q]; } // define which side have more space if (dir == null) { dir = "bottom"; for (var a in data) if (data[a] > data[dir]) dir = a; } if (dir == mode) return false; return dir; } this._repaint = function() { if (this.isVisible()) this._setPos(this._posData); } this.clear = function() { if (this._nodeObj) { if (this.conf.isIE && typeof(dhtmlXLayoutObject) != "undefined" && this._nodeObj instanceof dhtmlXLayoutObject) { this.p.onmousedown = null; } if (this._nodeObj.unload) { this._nodeObj.unload(); } else if (this._nodeObj.destruct) { this._nodeObj.destruct(); } this._nodeObj = this._nodeId = null; // events if any if (this._nodeObjEv != null) { for (var q=0; q<this._nodeObjEv.length; q++) this.detachEvent(this._nodeObjEv[q]); this._nodeObjEv = null; } } if (this._IEHoverInited) this._IEHoverClear(); var r = this.p.firstChild.firstChild.firstChild; // table->tbody while (r.childNodes.length > 0) r.removeChild(r.lastChild); r = null; this.itemData = {}; } this.hide = function() { if (this.p.style.display != "none") { this.p.style.display = "none"; window.dhx4.zim.clear(this.conf.zi); var id = this._lastId; this._lastId = null; this.callEvent("onHide",[id]); } } this.isVisible = function() { return (this.p.style.display == ""); } this.itemData = {}; this.getItemData = function(id) { if (!id) return this.itemData; if (this.itemData[id]) return this.itemData[id]; return {}; } this.setSkin = function(skin) { this.conf.skin = skin; this.p.className = "dhx_popup_"+this.conf.skin; if (this._nodeObj != null && typeof(this._nodeObj.setSkin) == "function") this._nodeObj.setSkin(this.conf.skin); this._repaint(); } this.attachList = function(template, data) { this._setTemplate(template); this.clear(); var r = this.p.firstChild.firstChild.firstChild; // table->tbody for (var q=0; q<data.length; q++) { var tr = document.createElement("TR"); if (data[q] != this.separator) { if (typeof(data[q].id) == "undefined" || data[q].id == null) { tr._idd = window.dhx4.newId(); while (this.itemData[tr._idd] != null) tr._idd = window.dhx4.newId(); } else { tr._idd = data[q].id; } this.itemData[tr._idd] = data[q]; } r.appendChild(tr); if (data[q] == this.separator) { tr.className = "dhx_popup_sep"; tr._isSeparator = true; var td = document.createElement("TD"); td.className = "dhx_popup_sep"; td.colSpan = this.tpl.length; td.innerHTML = "<div class='dhx_popup_sep'>&nbsp;</div>"; tr.appendChild(td); td = null; } else { for (var w=0; w<this.tpl.length; w++) { var css = "dhx_popup_td"; if (this._IEFirstLast && (this.tpl.length==1||w==0||w==this.tpl.length-1)) { if (this.tpl.length==1) css += " dhx_popup_td_single"; else css += (w==0?" dhx_popup_td_first":" dhx_popup_td_last"); } var td = document.createElement("TD"); td.className = css; td.innerHTML = data[q][this.tpl[w]]||"&nbsp;"; tr.appendChild(td); td = null; } // IE6 hover functionality if (this._IEHover) { tr._IEHover = true; if (!this._IEHoverInited) this._IEHoverInit(); } } tr = null; } r = null; this._repaint(); } this._attachNode = function(mode, data) { this.clear(); this._nodeId = "dhxpopup_node_"+window.dhx4.newId(); var r = this.p.firstChild.firstChild.firstChild; // table->tbody var tr = document.createElement("TR"); tr.className = "dhxnode"; r.appendChild(tr); var td = document.createElement("TD"); td.className = "dhx_popup_td"; td.innerHTML = "<div id='"+this._nodeId+"' style='position:relative;'></div>"; if (data.width) td.firstChild.style.width = data.width+"px"; if (data.height) td.firstChild.style.height = data.height+"px"; tr.appendChild(td); td = tr = r = null; if (typeof(this["_attach_init_"+mode]) == "function") { this["_attach_init_"+mode](data); this._enableIEVFix(); } this._repaint(); return this._nodeObj; } this.unload = function() { if (typeof(window.addEventListener) == "function") { window.removeEventListener("click", this._doOnClick, false); window.removeEventListener("keyup", this._doOnKeyUp, false); window.removeEventListener("unload", this._doOnUnload, false); } else { document.body.detachEvent("onclick", this._doOnClick, false); document.body.detachEvent("onkeyup", this._doOnKeyUp, false); document.body.detachEvent("onunload", this._doOnUnload, false); } this.clear(); this._doOnClick = null; this._doOnUnload = null; this._doOnKeyUp = null; if (this.conf.toolbarEvent != null && this.conf.toolbar != null) { if (this.conf.toolbar.detachEvent != null) { // make sure toolbar wasn't unloaded this.conf.toolbar.detachEvent(this.conf.toolbarEvent); } else { this.conf.toolbar._getItemDim = null; } } if (this.conf.ribbonEvent != null && this.conf.ribbon != null) { if (this.conf.ribbon.detachEvent != null) { this.conf.ribbon.detachEvent(this.conf.ribbonEvent); } else { this.conf.ribbon._getItemDim = null; } } if (this.conf.slider) { for (var q=0; q<this.conf.slider_events.length; q++) { this.conf.slider.detachEvent(this.conf.slider_events[q]); } this.conf.slider_events = null; this._sliderShow = this._sliderHide = null; this.conf.slider = null; } window.dhx4._eventable(this, "clear"); this.attachList = this.attachAccordion = this.attachCalendar = this.attachForm = this.attachGrid = this.attachLayout = this.attachTabbar = this.attachTree = this.attachHTML = this.attachObject = this._attachNode = null; this.show = this.hide = this.isVisible = this._setTemplate = this._repaint = this._setPos = this.getItemData = this.clear = this._idExists = this._doOnToolbarClick = this._doOnRibbonClick = this.setSkin = null; this.tpl = this.itemData = this.separator = this.mode = null; this._clearClick = this._lastId = this._posData = this.skinParams = this.skinParent = null; this.p.onclick = null; this.p.parentNode.removeChild(this.p); this.p = null; this.conf.toolbar = this.conf.toolbarEvent = this.conf.ribbon = this.conf.ribbonEvent = this.conf.form = this.conf.id = null; this.conf = null; this._IEHover = this._IEHoverTM = this._IEHoverInit = this._IEHoverClear = this._IEHoverRender = this._IEHoverInited = null; this._IEDisp = null; this.unload = null; that = null; } window.dhx4._eventable(this); this._doOnClick = function(e) { e = e||event; if (that._clearClick) { that._clearClick = false; return; } if (that.conf.form != null) { var id; var t = (e.target||e.srcElement); if ((t.tagName||"").toLowerCase() == "option") t = t.parentNode; if (t.className != null && t.className.search("dhxform") >= 0) { if (t.parentNode != null && t.parentNode.parentNode != null && t.parentNode.parentNode._idd != null) { id = t.parentNode.parentNode._idd; if (t.parentNode.parentNode._type == "ra") id = [t.parentNode.parentNode._group, t.parentNode.parentNode._value]; } } else { // check if button, editor or combo var k = true; var f = false; while (k && !f) { var p = (t.className||"").toLowerCase(); if (p.length > 0) f = (p == "dhxform_btn" || p.search(/dhxeditor_inside/gi) >= 0 || p == "dhxcombo_input" || p.search(/dhxcombolist/gi) >=0); t = t.parentNode; k = (t != null); } if (f) return; } t = null; if (id != null && that._idExists(id)) return; } if (that.isVisible() && that.callEvent("onBeforeHide",["click",e]) === true) { that.hide(); } } this._doOnKeyUp = function(e) { e = e||event; if (e.keyCode == 27) { if (that.isVisible() && that.callEvent("onBeforeHide",["esc",e]) === true) { that.hide(); } } } this._doOnUnload = function() { that.unload(); } if (typeof(window.addEventListener) == "function") { window.addEventListener("click", this._doOnClick, false); window.addEventListener("keyup", this._doOnKeyUp, false); window.addEventListener("unload", this._doOnUnload, false); } else { document.body.attachEvent("onclick", this._doOnClick, false); document.body.attachEvent("onkeyup", this._doOnKeyUp, false); document.body.attachEvent("onunload", this._doOnUnload, false); } this._idExists = function(id) { var r = false; for (var q=0; q<this.conf.id.length; q++) { if (this.conf.id[q] instanceof Array) { // radiobutton r = r||(this.conf.id[q][0]==id[0]&&this.conf.id[q][1]==id[1]); } else { r = r||this.conf.id[q]==id; } } return r; } // IE6/Quircks Display fix this._IEDisp = (this.conf.isIE && (navigator.userAgent.search("MSIE 6.0")>=0 || document.compatMode != "CSS1Compat")); // IE6 hover functionality this._IEHover = (this.conf.isIE && navigator.userAgent.search("MSIE 6.0")>=0); if (this._IEHover) { this._IEHoverInit = function() { this.p.onmouseover = function() { var t = event.srcElement; while (t != this && t._IEHover != true) t = t.parentNode; if (t._IEHover) { if (that._IEHoverTM) window.clearTimeout(that._IEHoverTM); if (that._lastIEHover == t) return; that._IEHoverRender(t); t = null; } } this.p.onmouseout = function() { if (that._IEHoverTM) window.clearTimeout(that._IEHoverTM); that._IEHoverTM = window.setTimeout(function(){that._IEHoverRender(null);},1); } this._IEHoverRender = function(t) { if (this._lastIEHover != null) { if (this._lastIEHover.className.search(/tr_hover/gi) >= 0) { this._lastIEHover.className = this._lastIEHover.className.replace(/\s{0,}tr_hover/gi, ""); this._lastIEHover = null; } } if (t != null && t.className.search(/tr_hover/gi) < 0) { t.className += " tr_hover"; that._lastIEHover = t; } } this._IEHoverInited = true; } this._IEHoverClear = function() { this.p.onmouseover = null; this.p.onmouseout = null; this._IEHoverInited = false; } } // IE6/7/8 first/last-child this._IEFirstLast = (this.conf.isIE && navigator.userAgent.search(/MSIE [6,7,8]\.0/i)>=0); // IE6 visibility fix this._enableIEVFix = function() { if (this.conf.isIE && navigator.userAgent.search("MSIE 6.0") >= 0) { var e1 = this.attachEvent("onHide", function(){ document.getElementById(this._nodeId).style.visibility = "hidden"; }); var e2 = this.attachEvent("onShow", function(){ document.getElementById(this._nodeId).style.visibility = "visible"; }); if (this._nodeObjEv == null) this._nodeObjEv = []; this._nodeObjEv.push(e1,e2); } } // auto-init, toolbar mode if (typeof(window.dhtmlXToolbarObject) != "undefined" && this.conf.toolbar != null && this.conf.toolbar instanceof window.dhtmlXToolbarObject && this.conf.id != null) { if (!(this.conf.id instanceof Array)) this.conf.id = [this.conf.id]; this.skinParent = this.conf.toolbar.conf.skin; this._doOnToolbarClick = function(id) { for (var q=0; q<that.conf.id.length; q++) { if (id == that.conf.id[q]) { if (id != that._lastId) { that.show(id); that._clearClick = true; } } } } // extension for toolbar, return pos/dim for specified button if (typeof(dhtmlXToolbarObject.prototype._getItemDim) == "undefined") { dhtmlXToolbarObject.prototype._getItemDim = function(id) { var t = this.objPull[this.idPrefix+id]; var p = { left: window.dhx4.absLeft(t.obj), top: window.dhx4.absTop(t.obj), width: t.obj.offsetWidth+(t.arw?t.arw.offsetWidth:0), height: t.obj.offsetHeight }; t = null; return p; } } this.conf.toolbarEvent = this.conf.toolbar.attachEvent("onClick", this._doOnToolbarClick); } // auto-init, ribbon mode if (typeof(window.dhtmlXRibbon) != "undefined" && this.conf.ribbon != null && this.conf.ribbon instanceof window.dhtmlXRibbon && this.conf.id != null) { if (!(this.conf.id instanceof Array)) this.conf.id = [this.conf.id]; this.skinParent = this.conf.ribbon.conf.skin; this._doOnRibbonClick = function(id) { for (var q=0; q<that.conf.id.length; q++) { if (id == that.conf.id[q]) { if (id != that._lastId) { that.show(id); that._clearClick = true; } } } } // extension for toolbar, return pos/dim for specified button if (typeof(dhtmlXRibbon.prototype._getItemDim) == "undefined") { dhtmlXRibbon.prototype._getItemDim = function(id) { var t = this._items[id].base; var p = { left: window.dhx4.absLeft(t), top: window.dhx4.absTop(t), width: t.offsetWidth, height: t.offsetHeight }; t = null; return p; } } this.conf.ribbonEvent = this.conf.ribbon.attachEvent("_showPopup", this._doOnRibbonClick); } // auto-init, form mode if (typeof(window.dhtmlXForm) != "undefined" && this.conf.form != null && this.conf.form instanceof window.dhtmlXForm && this.conf.id != null) { if (!(this.conf.id instanceof Array)) this.conf.id = [this.conf.id]; if (!this.conf.mode) this.mode = "right"; // default mode for form this.skinParent = this.conf.form.skin; if (typeof(dhtmlXForm.prototype._getItemDim) == "undefined") { dhtmlXForm.prototype._getItemDim = function(name, value) { return this.doWithItem(name, "_getDim"); }; // file - ?? for (var a in {input: 1, password: 1, select: 1, multiselect: 1, checkbox: 1, radio: 1, button: 1, combo: 1, btn2state: 1, calendar: 1, colorpicker: 1, editor: 1}) { if (dhtmlXForm.prototype.items[a] != null) { dhtmlXForm.prototype.items[a]._getDim = function(item) { var t = item; //console.log(item._type) if ({"ta":true,"pw":true,"se":true,"calendar":true,"colorpicker":1,"editor":true}[item._type]) { t = item.childNodes[item._ll?1:0].childNodes[0]; } if ({"ch":true,"ra":true,"btn2state":true}[item._type]) { t = item.childNodes[item._ll?1:0].childNodes[1]; } if ({"bt":true}[item._type]){ t = item.firstChild; } if ({"combo":true}[item._type]){ t = item._combo.DOMParent.firstChild; } var p = { left: window.dhx4.absLeft(t), top: window.dhx4.absTop(t), width: t.offsetWidth, height: t.offsetHeight }; t = null; return p; }; } } } } // auto-init, slider mode if (typeof(window.dhtmlXSlider) != "undefined" && this.conf.slider != null && this.conf.slider instanceof window.dhtmlXSlider) { if (!this.conf.mode) this.mode = "top"; // default mode for slider this.conf.slider_tm = null; this._sliderShow = function() { if (that.conf.slider_tm) window.clearTimeout(that.conf.slider_tm); var t = that.conf.slider._nodes.runner; var p = { left: window.dhx4.absLeft(t), top: window.dhx4.absTop(t), width: t.offsetWidth, height: t.offsetHeight }; that.show(p.left, p.top, p.width, p.height); } this._sliderHide = function() { that.conf.slider_tm = window.setTimeout(function(){ that.hide(); }, 200); //that.hide(); } this.conf.slider_events = [ this.conf.slider.attachEvent("_onRunnerMouseDown", this._sliderShow), this.conf.slider.attachEvent("_onRunnerMouseUp", this._sliderHide), this.conf.slider.attachEvent("onChange", this._sliderShow) ]; } // define skin this.setSkin(this.skinParent||this.conf.skin||window.dhx4.skin||(typeof(dhtmlx)!="undefined"?dhtmlx.skin:null)||window.dhx4.skinDetect("dhx_popup")||"dhx_skyblue"); return this; }; // object dhtmlXPopup.prototype.attachObject = function(obj) { return this._attachNode("object", {obj: obj}); }; dhtmlXPopup.prototype._attach_init_object = function(data) { this._nodeObj = (typeof(data.obj)=="string"?document.getElementById(data.obj):data.obj); data.obj = null; document.getElementById(this._nodeId).appendChild(this._nodeObj); this._nodeObj.style.display = ""; this._nodeObj.style.visibility = "visible"; }; // html dhtmlXPopup.prototype.attachHTML = function(html) { return this._attachNode("html", {html: html}); }; dhtmlXPopup.prototype._attach_init_html = function(data) { document.getElementById(this._nodeId).innerHTML = data.html; this._nodeObj = {text: data.html}; }; // form dhtmlXPopup.prototype.attachForm = function(struct) { return this._attachNode("form", {struct: struct}); }; dhtmlXPopup.prototype._attach_init_form = function(data) { var that = this; this._nodeObj = new dhtmlXForm(this._nodeId, data.struct); this._nodeObj.setSkin(this.conf.skin); this._nodeObj.attachEvent("_onBeforeEditorAccess", function(){ // prevent popup autohide, editor will trigger body/click that._clearClick = true; }); }; // calendar dhtmlXPopup.prototype.attachCalendar = function() { return this._attachNode("calendar", {}); }; dhtmlXPopup.prototype._attach_init_calendar = function(data) { this._nodeObj = new dhtmlXCalendarObject(this._nodeId); this._nodeObj.setSkin(this.conf.skin); this._nodeObj.show(); }; // grid dhtmlXPopup.prototype.attachGrid = function(width, height) { return this._attachNode("grid", {width: width||400, height: height||200}); }; dhtmlXPopup.prototype._attach_init_grid = function() { this._nodeObj = new dhtmlXGridObject(this._nodeId); this._nodeObj.setSkin(this.conf.skin); }; // tree dhtmlXPopup.prototype.attachTree = function(width, height, rootId) { return this._attachNode("tree", {width: width||400, height: height||200, rootId: rootId||0}); }; dhtmlXPopup.prototype._attach_init_tree = function(data) { this._nodeObj = new dhtmlXTreeObject(this._nodeId, "100%", "100%", (data.rootId)) }; // layout dhtmlXPopup.prototype.attachLayout = function(width, height, pattern) { return this._attachNode("layout", {width: width||400, height: height||200, pattern: pattern||"3L"}); }; dhtmlXPopup.prototype._attach_init_layout = function(data) { this._nodeObj = new dhtmlXLayoutObject(this._nodeId, data.pattern, this.conf.skin) }; // accordion dhtmlXPopup.prototype.attachAccordion = function(width, height, conf) { return this._attachNode("accordion", {width: width||400, height: height||200, conf:conf||{}}); }; dhtmlXPopup.prototype._attach_init_accordion = function(conf) { conf.conf.parent = this._nodeId; conf.conf.skin = this.conf.skin; this._nodeObj = new dhtmlXAccordion(conf.conf); }; // tabbar dhtmlXPopup.prototype.attachTabbar = function(width, height, conf) { if (typeof(conf) == "string") { conf = {mode:conf}; // 3.6 compat } else if (typeof(conf) != "object" || conf == null) { conf = {}; } return this._attachNode("tabbar", {width: width||400, height: height||200, conf:conf}); }; dhtmlXPopup.prototype._attach_init_tabbar = function(conf) { conf.conf.parent = this._nodeId; conf.conf.skin = this.conf.skin; this._nodeObj = new dhtmlXTabBar(conf.conf); }; // editor dhtmlXPopup.prototype.attachEditor = function(width, height, conf) { return this._attachNode("editor", {width: width||400, height: height||200, conf: conf||{}}); }; dhtmlXPopup.prototype._attach_init_editor = function(data) { document.getElementById(this._nodeId).className = "dhxeditor_"+this.conf.skin; data.conf.parent = this._nodeId; if (data.conf.skin == null) data.conf.skin = this.conf.skin; this._nodeObj = new dhtmlXEditor(data.conf); var evId = this.attachEvent("onShow", function(){ if (this._nodeObj instanceof window.dhtmlXEditor) this._nodeObj.setSizes(); }); if (this._nodeObjEv == null) this._nodeObjEv = []; this._nodeObjEv.push(evId); }; // color picker dhtmlXPopup.prototype.attachColorPicker = function(conf) { if (typeof(conf) != "object" || conf == null) conf = {}; return this._attachNode("colorpicker", {conf:conf}); }; dhtmlXPopup.prototype._attach_init_colorpicker = function(conf) { conf.conf.skin = this.conf.skin; conf.conf.parent = this._nodeId; this._nodeObj = new dhtmlXColorPicker(conf.conf); };
bbargstaedt/conflowgen
conflowgen/domain_models/data_types/container_length.py
from __future__ import annotations import enum import enum_tools.documentation @enum_tools.documentation.document_enum class ContainerLength(enum.Enum): """ The container length is one of the most important factors of how much space a container occupies. Here, the most common container sizes (neglecting height) are represented. """ twenty_feet = 20 # doc: A twenty-foot container forty_feet = 40 # doc: A forty-foot container forty_five_feet = 45 # doc: A forty-five-foot container other = -1 # doc: Any other length usually does not fit into the standardized slots and handling processes. @classmethod def get_factor(cls, container_length: ContainerLength) -> float: """ Args: container_length: The length of the sea container Returns: The TEU factor of that container """ return { cls.twenty_feet: 1, cls.forty_feet: 2, cls.forty_five_feet: 2.25, cls.other: 2.5 # This is assumed to be a bad shape taking a lot of capacity. }[container_length] def __str__(self): """ The representation is e.g. '20 foot' instead of '<ContainerLength.twenty_feet>' and thus nicer for the logs. """ if self.value > 0: return f"{self.value} feet" return "other"
chuyiting/tp
src/main/java/seedu/studybananas/logic/commands/commandresults/QuizErrorCommandResult.java
<filename>src/main/java/seedu/studybananas/logic/commands/commandresults/QuizErrorCommandResult.java package seedu.studybananas.logic.commands.commandresults; import static seedu.studybananas.logic.commands.commandresults.QuizCommandResultType.ERROR; public class QuizErrorCommandResult extends QuizCommandResult { public QuizErrorCommandResult(String feedbackToUser) { super(feedbackToUser, ERROR); } }
uqlibrary/homepage-react
src/modules/SharedComponents/Toolbox/HelpDrawer/actions.js
<filename>src/modules/SharedComponents/Toolbox/HelpDrawer/actions.js // Types export const SHOW = 'HELP_DRAWER_SHOW'; export const HIDE = 'HELP_DRAWER_HIDE'; // Actions export function show(title, text, buttonLabel) { return { type: SHOW, payload: { title, text, buttonLabel }, }; } export function hide() { return { type: HIDE, }; }
samahAbujwaied/data-structures-and-algorithms401
C28_401js/index.js
'use strict' function quickSort(array, left, right) { //[8,4,23,42,16,15]; let index; if (array.length > 1) { index = partition(array, left, right); if (left < index - 1) { quickSort(array, left, index - 1); } if (index < right) { quickSort(array, index, right); } } return array; } function swap(array, leftIndex, rightIndex){ let temp = array[leftIndex]; array[leftIndex] = array[rightIndex]; array[rightIndex] = temp; } function partition(array, left, right) { let pivot = array[Math.floor((right + left) / 2)], i = left, j = right; while (i <= j) { while (array[i] < pivot) { i++; } while (array[j] > pivot) { j--; } if (i <= j) { swap(array, i, j); //sawpping two elements i++; j--; } } return i; } let array = [8,4,23,42,16,15]; let sortedArray = quickSort(array, 0, array.length - 1); console.log(sortedArray); module.exports = quickSort;
yangbiny/imp
imp-rpc/imp-rpc-api/src/main/java/com/impassive/rpc/invocation/Invocation.java
package com.impassive.rpc.invocation; /** * @author impassivey */ public interface Invocation { /** * 返回执行对象的接口全路径名 * * @return 执行对象的接口全路径名 */ String getServiceName(); /** * 获取待执行方法的方法名称 * * @return 方法名称 */ String getMethodName(); /** * 获取执行方法的参数类型 * * @return 参数类型 */ Class<?>[] getParamTypes(); /** * 参数的实际类型。例如:如果参数是list,则 paramType是list,该值可能是ArrayList,也可能是LinkedList * * @return 参数的实际类型 */ Class<?>[] argumentsType(); /** * 获取执行方法的参数信息 * * @return 参数信息 */ Object[] getParams(); }
webispy/nugu-linux
src/core/session_manager.hh
<reponame>webispy/nugu-linux<filename>src/core/session_manager.hh /* * Copyright (c) 2019 SK Telecom Co., Ltd. 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. * 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. */ #ifndef __NUGU_SESSION_MANAGER_H__ #define __NUGU_SESSION_MANAGER_H__ #include <map> #include <vector> #include "clientkit/session_manager_interface.hh" namespace NuguCore { using namespace NuguClientKit; class SessionManager : public ISessionManager { public: using ActiveDialogs = std::vector<std::pair<std::string, int>>; using Sessions = std::map<std::string, Session>; public: SessionManager() = default; virtual ~SessionManager(); void reset(); void addListener(ISessionManagerListener* listener) override; void removeListener(ISessionManagerListener* listener) override; int getListenerCount(); void set(const std::string& dialog_id, Session&& session) override; void activate(const std::string& dialog_id) override; void deactivate(const std::string& dialog_id) override; Json::Value getActiveSessionInfo() override; void clear() override; const ActiveDialogs& getActiveList(); const Sessions& getAllSessions(); private: void notifyActiveState(const std::string& dialog_id, bool is_active = true); void clearContainer(); std::vector<ISessionManagerListener*> listeners; ActiveDialogs active_list; Sessions session_map; }; } // NuguCore #endif /* __NUGU_SESSION_MANAGER_H__ */
azerothcore/lib-ace
ace/Mutex.inl
// -*- C++ -*- #include "ace/OS_NS_sys_mman.h" ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE int ACE_Mutex::acquire_read (void) { // ACE_TRACE ("ACE_Mutex::acquire_read"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_lock (this->process_lock_); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return ACE_OS::mutex_lock (&this->lock_); } ACE_INLINE int ACE_Mutex::acquire_write (void) { // ACE_TRACE ("ACE_Mutex::acquire_write"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_lock (this->process_lock_); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return ACE_OS::mutex_lock (&this->lock_); } ACE_INLINE int ACE_Mutex::tryacquire_read (void) { // ACE_TRACE ("ACE_Mutex::tryacquire_read"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_trylock (this->process_lock_); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return ACE_OS::mutex_trylock (&this->lock_); } ACE_INLINE const ACE_mutex_t & ACE_Mutex::lock (void) const { // ACE_TRACE ("ACE_Mutex::lock"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return *this->process_lock_; #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return this->lock_; } ACE_INLINE ACE_mutex_t & ACE_Mutex::lock (void) { // ACE_TRACE ("ACE_Mutex::lock"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return *this->process_lock_; #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return this->lock_; } ACE_INLINE int ACE_Mutex::tryacquire_write (void) { // ACE_TRACE ("ACE_Mutex::tryacquire_write"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_trylock (this->process_lock_); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return ACE_OS::mutex_trylock (&this->lock_); } ACE_INLINE int ACE_Mutex::tryacquire_write_upgrade (void) { // ACE_TRACE ("ACE_Mutex::tryacquire_write_upgrade"); return 0; } ACE_INLINE int ACE_Mutex::acquire (void) { // ACE_TRACE ("ACE_Mutex::acquire"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_lock (this->process_lock_); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return ACE_OS::mutex_lock (&this->lock_); } ACE_INLINE int ACE_Mutex::acquire (ACE_Time_Value &tv) { // ACE_TRACE ("ACE_Mutex::acquire"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_lock (this->process_lock_, tv); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS*/ return ACE_OS::mutex_lock (&this->lock_, tv); } ACE_INLINE int ACE_Mutex::acquire (ACE_Time_Value *tv) { #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_lock (this->process_lock_, tv); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS*/ return ACE_OS::mutex_lock (&this->lock_, tv); } ACE_INLINE int ACE_Mutex::tryacquire (void) { // ACE_TRACE ("ACE_Mutex::tryacquire"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_trylock (this->process_lock_); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return ACE_OS::mutex_trylock (&this->lock_); } ACE_INLINE int ACE_Mutex::release (void) { // ACE_TRACE ("ACE_Mutex::release"); #if defined (ACE_HAS_PTHREADS) || defined(ACE_HAS_STHREADS) if (this->process_lock_) return ACE_OS::mutex_unlock (this->process_lock_); #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return ACE_OS::mutex_unlock (&this->lock_); } ACE_INLINE int ACE_Mutex::remove (void) { // ACE_TRACE ("ACE_Mutex::remove"); int result = 0; #if defined (ACE_HAS_PTHREADS) || defined (ACE_HAS_STHREADS) // In the case of a interprocess mutex, the owner is the first // process that created the shared memory object. In this case, the // lockname_ pointer will be non-zero (points to allocated memory // for the name). Owner or not, the memory needs to be unmapped // from the process. If we are the owner, the file used for // shm_open needs to be deleted as well. if (this->process_lock_) { if (this->removed_ == false) { this->removed_ = true; // Only destroy the lock if we're the ones who initialized // it. if (!this->lockname_) ACE_OS::munmap ((void *) this->process_lock_, sizeof (ACE_mutex_t)); else { result = ACE_OS::mutex_destroy (this->process_lock_); ACE_OS::munmap ((void *) this->process_lock_, sizeof (ACE_mutex_t)); ACE_OS::shm_unlink (this->lockname_); ACE_OS::free ( static_cast<void *> ( const_cast<ACE_TCHAR *> (this->lockname_))); } } } else { #else /* !ACE_HAS_PTHREADS && !ACE_HAS_STHREADS */ if (this->removed_ == false) { this->removed_ = true; result = ACE_OS::mutex_destroy (&this->lock_); } #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ #if defined (ACE_HAS_PTHREADS) || defined (ACE_HAS_STHREADS) } #endif /* ACE_HAS_PTHREADS || ACE_HAS_STHREADS */ return result; } ACE_END_VERSIONED_NAMESPACE_DECL
rjfpeters-iefbr14/mod1-energy-guard-system
mod1-agm-service/src/main/java/tld/yggdrasill/services/agm/core/delegate/CreateFulFillmentProcessDelegate.java
package tld.yggdrasill.services.agm.core.delegate; import lombok.extern.slf4j.Slf4j; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.springframework.stereotype.Component; import tld.yggdrasill.services.agm.client.safetydossier.SafetyDossierClient; import javax.inject.Named; import static net.logstash.logback.argument.StructuredArguments.kv; @Slf4j @Component @Named("createFulFillmentProcessDelegate") public class CreateFulFillmentProcessDelegate implements JavaDelegate { private final SafetyDossierClient safetyDossierClient; public CreateFulFillmentProcessDelegate(SafetyDossierClient safetyDossierClient) { this.safetyDossierClient = safetyDossierClient; } public void execute(DelegateExecution execution) throws Exception { log.info("... CreateFulFillmentProcessDelegate invoked by " + "processDefinitionId=" + execution.getProcessDefinitionId() + ", activityId=" + execution.getCurrentActivityId() + ", activityName='" + execution.getCurrentActivityName() + "'" + ", processInstanceId=" + execution.getProcessInstanceId() + ", businessKey=" + execution.getProcessBusinessKey() + ", executionId=" + execution.getId()); // ContingencyResponse contingency = safetyDossierClient.getSafetyDossierById(contingencyId); // log.info("SafetyDossiers: {} -> {}", kv("contingencyId", contingencyId), contingency.toString()); } }
ivanceras/orm
src/main/java/com/ivanceras/db/api/ColumnDataType.java
<reponame>ivanceras/orm package com.ivanceras.db.api; public class ColumnDataType{ private String[] columns = null; private String[] dataTypes = null; private String[] comments = null; public void setDataTypes(String[] dataTypes) { this.dataTypes = dataTypes; } public String[] getDataTypes() { return dataTypes; } public void setColumns(String[] columns) { this.columns = columns; } public String[] getColumns() { return columns; } public String[] getComments() { return comments; } public void setComments(String[] comments) { this.comments = comments; } }
rknop/amuse
src/amuse/test/suite/core_tests/test_scaling_converter.py
from amuse.units import scaling_converter from amuse.units import nbody_system from amuse.test import amusetest class TestScalingConverter(amusetest.TestCase): def test1(self): converter = scaling_converter.ScalingConverter( length = 0.2, time = 0.1, ) input = 1 | nbody_system.time output = converter.convert(input) self.assertAlmostRelativeEquals(output, 0.1 | nbody_system.time) def test2(self): converter = scaling_converter.ScalingConverter( length = 0.2, time = 0.1, ) input = 1 | nbody_system.length ** 2 output = converter.convert(input) self.assertAlmostRelativeEquals(output, 0.2 * 0.2 | nbody_system.length ** 2)
hyu-iot/gem5
mibench/office/ghostscript/src/zdevice2.c
/* Copyright (C) 1993, 1995, 1997 Aladdin Enterprises. All rights reserved. This file is part of Aladdin Ghostscript. Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND. No author or distributor accepts any responsibility for the consequences of using it, or for whether it serves any particular purpose or works at all, unless he or she says so in writing. Refer to the Aladdin Ghostscript Free Public License (the "License") for full details. Every copy of Aladdin Ghostscript must include a copy of the License, normally in a plain ASCII text file named PUBLIC. The License grants you the right to copy, modify and redistribute Aladdin Ghostscript, but only under certain conditions described in the License. Among other things, the License requires that the copyright notice and this notice be preserved on all copies. */ /* zdevice2.c */ /* Level 2 device operators */ #include "math_.h" #include "memory_.h" #include "ghost.h" #include "errors.h" #include "oper.h" #include "dstack.h" /* for dict_find_name */ #include "estack.h" #include "idict.h" #include "idparam.h" #include "igstate.h" #include "iname.h" #include "store.h" #include "gxdevice.h" #include "gsstate.h" /* Imported data */ extern op_proc_p zcopy_procs[t_next_index]; /* Forward references */ private int z2copy_gstate(P1(os_ptr)); private int near push_callout(P1(const char _ds *)); /* Initialize by adding changing the `copy' operator for gstates. */ /* This is a hack -- we know that gstates are the only */ /* t_astruct subtype that implements copy. */ private void zdevice2_init(void) { zcopy_procs[t_astruct] = z2copy_gstate; } /* - .currentshowpagecount <count> true */ /* - .currentshowpagecount false */ private int zcurrentshowpagecount(register os_ptr op) { gx_device *dev = gs_currentdevice(igs); if ( (*dev_proc(dev, get_page_device))(dev) == 0 ) { push(1); make_false(op); } else { push(2); make_int(op - 1, dev->ShowpageCount); make_true(op); } return 0; } /* - .doneshowpage - */ private int zdoneshowpage(register os_ptr op) { gx_device *dev = gs_currentdevice(igs); if ( (*dev_proc(dev, get_page_device))(dev) != 0 ) dev->ShowpageCount++; return 0; } /* - .currentpagedevice <dict> <bool> */ private int zcurrentpagedevice(register os_ptr op) { gx_device *dev = gs_currentdevice(igs); push(2); if ( (*dev_proc(dev, get_page_device))(dev) != 0 ) { op[-1] = istate->pagedevice; make_true(op); } else { op[-1] = i_null_pagedevice; make_false(op); } return 0; } /* <dict> .setpagedevice - */ private int zsetpagedevice(register os_ptr op) { int code; /****** if ( igs->in_cachedevice ) return_error(e_undefined); ******/ check_type(*op, t_dictionary); check_dict_read(*op); /* Make the dictionary read-only. */ code = zreadonly(op); if ( code < 0 ) return code; istate->pagedevice = *op; pop(1); return 0; } /* Default Install/BeginPage/EndPage procedures */ /* that just call the procedure in the device. */ /* - .callinstall - */ private int zcallinstall(os_ptr op) { gx_device *dev = gs_currentdevice(igs); if ( (dev = (*dev_proc(dev, get_page_device))(dev)) != 0 ) { int code = (*dev->page_procs.install)(dev, igs); if ( code < 0 ) return code; } return 0; } /* <showpage_count> .callbeginpage - */ private int zcallbeginpage(os_ptr op) { gx_device *dev = gs_currentdevice(igs); check_type(*op, t_integer); if ( (dev = (*dev_proc(dev, get_page_device))(dev)) != 0 ) { int code = (*dev->page_procs.begin_page)(dev, igs); if ( code < 0 ) return code; } pop(1); return 0; } /* <showpage_count> <reason_int> .callendpage <flush_bool> */ private int zcallendpage(os_ptr op) { gx_device *dev = gs_currentdevice(igs); int code; check_type(op[-1], t_integer); check_type(*op, t_integer); if ( (dev = (*dev_proc(dev, get_page_device))(dev)) != 0 ) { code = (*dev->page_procs.end_page)(dev, (int)op->value.intval, igs); if ( code < 0 ) return code; if ( code > 1 ) return_error(e_rangecheck); } else { code = (op->value.intval == 2 ? 0 : 1); } make_bool(op - 1, code); pop(1); return 0; } /* ------ Wrappers for operators that save the graphics state. ------ */ /* When saving the state with the current device a page device, */ /* we need to make sure that the page device dictionary exists */ /* so that grestore can use it to reset the device parameters. */ /* This may have significant performance consequences, but we don't see */ /* any way around it. */ /* Check whether we need to call out to create the page device dictionary. */ #define save_page_device(pgs)\ (gs_int_gstate(pgs)->pagedevice.value.pdict ==\ i_null_pagedevice.value.pdict &&\ (*dev_proc(gs_currentdevice(pgs), get_page_device))(gs_currentdevice(pgs))\ != 0) /* - gsave - */ private int z2gsave(os_ptr op) { if ( !save_page_device(igs) ) return gs_gsave(igs); return push_callout("%gsavepagedevice"); } /* - save - */ private int z2save(os_ptr op) { if ( !save_page_device(igs) ) return zsave(op); return push_callout("%savepagedevice"); } /* - gstate <gstate> */ private int z2gstate(os_ptr op) { if ( !save_page_device(igs) ) return zgstate(op); return push_callout("%gstatepagedevice"); } /* <gstate1> <gstate2> copy <gstate2> */ private int z2copy_gstate(os_ptr op) { if ( !save_page_device(igs) ) return zcopy_gstate(op); return push_callout("%copygstatepagedevice"); } /* <gstate1> <gstate2> currentgstate <gstate2> */ private int z2currentgstate(os_ptr op) { if ( !save_page_device(igs) ) return zcurrentgstate(op); return push_callout("%currentgstatepagedevice"); } /* ------ Wrappers for operators that reset the graphics state. ------ */ /* Check whether we need to call out to restore the page device. */ private bool near restore_page_device(const gs_state *pgs_old, const gs_state *pgs_new) { gx_device *dev_old = gs_currentdevice(pgs_old); gx_device *dev_new; gx_device *dev_t1; gx_device *dev_t2; if ( (dev_t1 = (*dev_proc(dev_old, get_page_device))(dev_old)) == 0 ) return false; dev_new = gs_currentdevice(pgs_new); if ( dev_old != dev_new ) { if ( (dev_t2 = (*dev_proc(dev_new, get_page_device))(dev_new)) == 0 ) return false; if ( dev_t1 != dev_t2 ) return true; } /* The current implementation of setpagedevice just sets new */ /* parameters in the same device object, so we have to check */ /* whether the page device dictionaries are the same. */ { const ref *pdict1 = &gs_int_gstate(pgs_old)->pagedevice; const ref *pdict2 = &gs_int_gstate(pgs_new)->pagedevice; return pdict1->value.pdict != pdict2->value.pdict; } } /* - grestore - */ private int z2grestore(os_ptr op) { if ( !restore_page_device(igs, gs_state_saved(igs)) ) return gs_grestore(igs); return push_callout("%grestorepagedevice"); } /* - grestoreall - */ private int z2grestoreall(os_ptr op) { for ( ; ; ) { if ( !restore_page_device(igs, gs_state_saved(igs)) ) { bool done = !gs_state_saved(gs_state_saved(igs)); gs_grestore(igs); if ( done ) break; } else return push_callout("%grestoreallpagedevice"); } return 0; } /* <save> restore - */ private int z2restore(os_ptr op) { for ( ; ; ) { if ( !restore_page_device(igs, gs_state_saved(igs)) ) { zgrestore(op); if ( !gs_state_saved(gs_state_saved(igs)) ) break; } else return push_callout("%restorepagedevice"); } return zrestore(op); } /* <gstate> setgstate - */ private int z2setgstate(os_ptr op) { check_stype(*op, st_igstate_obj); if ( !restore_page_device(igs, igstate_ptr(op)) ) return zsetgstate(op); return push_callout("%setgstatepagedevice"); } /* ------ Initialization procedure ------ */ BEGIN_OP_DEFS(zdevice2_l2_op_defs) { op_def_begin_level2(), {"0.currentshowpagecount", zcurrentshowpagecount}, {"0.currentpagedevice", zcurrentpagedevice}, {"0.doneshowpage", zdoneshowpage}, {"1.setpagedevice", zsetpagedevice}, /* Note that the following replace prior definitions */ /* in the indicated files: */ {"0gsave", z2gsave}, /* zgstate.c */ {"0save", z2save}, /* zvmem.c */ {"0gstate", z2gstate}, /* zdps1.c */ {"1currentgstate", z2currentgstate}, /* zdps1.c */ {"0grestore", z2grestore}, /* zgstate.c */ {"0grestoreall", z2grestoreall}, /* zgstate.c */ {"1restore", z2restore}, /* zvmem.c */ {"1setgstate", z2setgstate}, /* zdps1.c */ /* Default Install/BeginPage/EndPage procedures */ /* that just call the procedure in the device. */ {"0.callinstall", zcallinstall}, {"1.callbeginpage", zcallbeginpage}, {"2.callendpage", zcallendpage}, END_OP_DEFS(zdevice2_init) } /* ------ Internal routines ------ */ /* Call out to a PostScript procedure. */ private int near push_callout(const char _ds *callout_name) { int code; check_estack(1); code = name_enter_string(callout_name, esp + 1); if ( code < 0 ) return code; ++esp; r_set_attrs(esp, a_executable); return o_push_estack; }
evemonk/evemonk
spec/controllers/admin/settings_controller_spec.rb
<filename>spec/controllers/admin/settings_controller_spec.rb # frozen_string_literal: true require "rails_helper" describe Admin::SettingsController do it { should be_an(Admin::ApplicationController) } end
aparo/zio-elasticsearch
elasticsearch-admin/shared/src/main/scala/elasticsearch/managers/IndicesManager.scala
/* * Copyright 2019 <NAME> * * 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 elasticsearch.managers import elasticsearch._ import elasticsearch.client.IndicesActionResolver import zio.circe.CirceUtils import elasticsearch.mappings._ import elasticsearch.requests.indices._ import elasticsearch.responses.indices._ import io.circe._ import io.circe.syntax._ class IndicesManager(client: IndicesActionResolver) { /* * Performs the analysis process on a text and return the tokens breakdown of the text. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-analyze.html * * @param body body the body of the call * @param index The name of the index to scope the operation */ def analyze(body: JsonObject, index: Option[String] = None): ZioResponse[IndicesAnalyzeResponse] = { val request = IndicesAnalyzeRequest(body = body, index = index) analyze(request) } def analyze(request: IndicesAnalyzeRequest): ZioResponse[IndicesAnalyzeResponse] = client.execute(request) /* * Clears all or specific caches for one or more indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-clearcache.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param fielddata Clear field data * @param fields A comma-separated list of fields to clear when using the `fielddata` parameter (default: all) * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param index A comma-separated list of index name to limit the operation * @param indices A comma-separated list of index name to limit the operation * @param query Clear query caches * @param request Clear request cache */ def clearCache( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, fielddata: Option[Boolean] = None, fields: Seq[String] = Nil, ignoreUnavailable: Option[Boolean] = None, index: Seq[String] = Nil, indices: Seq[String] = Nil, query: Option[Boolean] = None, request: Option[Boolean] = None ): ZioResponse[IndicesClearCacheResponse] = { val requestI = IndicesClearCacheRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, fielddata = fielddata, fields = fields, ignoreUnavailable = ignoreUnavailable, index = index, indices = indices, query = query, request = request ) clearCache(requestI) } def clearCache(request: IndicesClearCacheRequest): ZioResponse[IndicesClearCacheResponse] = client.execute(request) /* * Clones an index * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-clone-index.html * * @param index The name of the source index to clone * @param target The name of the target index to clone into * @param body body the body of the call * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout * @param waitForActiveShards Set the number of active shards to wait for on the cloned index before the operation returns. */ def clone( index: String, target: String, body: Option[JsonObject] = None, masterTimeout: Option[String] = None, timeout: Option[String] = None, waitForActiveShards: Option[String] = None ): ZioResponse[IndicesCloneResponse] = { val request = IndicesCloneRequest( index = index, target = target, body = body, masterTimeout = masterTimeout, timeout = timeout, waitForActiveShards = waitForActiveShards ) clone(request) } def clone(request: IndicesCloneRequest): ZioResponse[IndicesCloneResponse] = client.execute(request) /* * Closes an index. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-open-close.html * * @param index A comma separated list of indices to close * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout * @param waitForActiveShards Sets the number of active shards to wait for before the operation returns. */ def close( index: String, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, masterTimeout: Option[String] = None, timeout: Option[String] = None, waitForActiveShards: Option[String] = None ): ZioResponse[IndicesCloseResponse] = { val request = IndicesCloseRequest( index = index, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, masterTimeout = masterTimeout, timeout = timeout, waitForActiveShards = waitForActiveShards ) close(request) } def close(request: IndicesCloseRequest): ZioResponse[IndicesCloseResponse] = client.execute(request) /* * Creates an index with optional settings and mappings. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-create-index.html * * @param index The name of the index * @param body body the body of the call * @param includeTypeName Whether a type should be expected in the body of the mappings. * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout * @param waitForActiveShards Set the number of active shards to wait for before the operation returns. */ def createIfNotExists( index: String, body: JsonObject = JsonObject.empty, waitForActiveShards: Option[Int] = None, timeout: Option[String] = None, masterTimeout: Option[String] = None ): ZioResponse[Unit] = for { existsRes <- exists(index) _ <- create( IndicesCreateRequest( index = index, body = CirceUtils.cleanValue(body), // we remove null waitForActiveShards = waitForActiveShards, timeout = timeout, masterTimeout = masterTimeout ) ).when(existsRes.exists) } yield () def create( index: String, body: JsonObject = JsonObject.empty, includeTypeName: Option[Boolean] = None, masterTimeout: Option[String] = None, timeout: Option[String] = None, waitForActiveShards: Option[Int] = None ): ZioResponse[IndicesCreateResponse] = { val request = IndicesCreateRequest( index = index, body = body, includeTypeName = includeTypeName, masterTimeout = masterTimeout, timeout = timeout, waitForActiveShards = waitForActiveShards ) create(request) } def create(request: IndicesCreateRequest): ZioResponse[IndicesCreateResponse] = client.execute(request) /* * Deletes an index. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-delete-index.html * * @param indices A comma-separated list of indices to delete; use `_all` or `*` string to delete all indices * @param allowNoIndices Ignore if a wildcard expression resolves to no concrete indices (default: false) * @param expandWildcards Whether wildcard expressions should get expanded to open or closed indices (default: open) * @param ignoreUnavailable Ignore unavailable indexes (default: false) * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout */ def delete( indices: Seq[String] = Nil, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, masterTimeout: Option[String] = None, timeout: Option[String] = None ): ZioResponse[IndicesDeleteResponse] = { val request = IndicesDeleteRequest( indices = indices, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, masterTimeout = masterTimeout, timeout = timeout ) delete(request) } def delete(request: IndicesDeleteRequest): ZioResponse[IndicesDeleteResponse] = client.execute(request) /* * Deletes an alias. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-aliases.html * * @param indices A comma-separated list of index names (supports wildcards); use `_all` for all indices * @param name A comma-separated list of aliases to delete (supports wildcards); use `_all` to delete all aliases for the specified indices. * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit timestamp for the document */ def deleteAlias( names: Seq[String] = Nil, indices: Seq[String] = Nil, timeout: Option[String] = None, masterTimeout: Option[String] = None ): ZioResponse[IndicesDeleteAliasResponse] = { val request = IndicesDeleteAliasRequest( name = names, indices = indices, timeout = timeout, masterTimeout = masterTimeout ) deleteAlias(request) } def deleteAlias( request: IndicesDeleteAliasRequest ): ZioResponse[IndicesDeleteAliasResponse] = client.execute(request) def addAlias( alias: String, indices: List[String] ): ZioResponse[IndicesPutAliasResponse] = putAlias(indices = indices, name = alias) /* * Deletes an index template. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-templates.html * * @param name The name of the template * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout */ def deleteTemplate( name: String, masterTimeout: Option[String] = None, timeout: Option[String] = None ): ZioResponse[IndicesDeleteTemplateResponse] = { val request = IndicesDeleteTemplateRequest(name = name, masterTimeout = masterTimeout, timeout = timeout) deleteTemplate(request) } def deleteTemplate(request: IndicesDeleteTemplateRequest): ZioResponse[IndicesDeleteTemplateResponse] = client.execute(request) def exists( index: String ): ZioResponse[IndicesExistsResponse] = exists(Seq(index)) def existsAsBoolean( index: String ): ZioResponse[Boolean] = exists(Seq(index)).map(_.exists) /* * Returns information about whether a particular index exists. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-exists.html * * @param indices A comma-separated list of index names * @param allowNoIndices Ignore if a wildcard expression resolves to no concrete indices (default: false) * @param expandWildcards Whether wildcard expressions should get expanded to open or closed indices (default: open) * @param flatSettings Return settings in flat format (default: false) * @param ignoreUnavailable Ignore unavailable indexes (default: false) * @param includeDefaults Whether to return all default setting for each of the indices. * @param local Return local information, do not retrieve the state from master node (default: false) */ def exists( indices: Seq[String] = Nil, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, flatSettings: Option[Boolean] = None, ignoreUnavailable: Option[Boolean] = None, includeDefaults: Boolean = false, local: Option[Boolean] = None ): ZioResponse[IndicesExistsResponse] = { val request = IndicesExistsRequest( indices = indices, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, flatSettings = flatSettings, ignoreUnavailable = ignoreUnavailable, includeDefaults = includeDefaults, local = local ) exists(request) } def exists(request: IndicesExistsRequest): ZioResponse[IndicesExistsResponse] = client.execute(request) /* * Returns information about whether a particular alias exists. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-aliases.html * * @param name A comma-separated list of alias names to return * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names to filter aliases * @param local Return local information, do not retrieve the state from master node (default: false) */ def existsAlias( name: Seq[String] = Nil, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, local: Option[Boolean] = None ): ZioResponse[IndicesExistsAliasResponse] = { val request = IndicesExistsAliasRequest( name = name, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices, local = local ) existsAlias(request) } def existsAlias(request: IndicesExistsAliasRequest): ZioResponse[IndicesExistsAliasResponse] = client.execute(request) /* * Returns information about whether a particular index template exists. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-templates.html * * @param name The comma separated names of the index templates * @param flatSettings Return settings in flat format (default: false) * @param local Return local information, do not retrieve the state from master node (default: false) * @param masterTimeout Explicit operation timeout for connection to master node */ def existsTemplate( name: String, flatSettings: Option[Boolean] = None, local: Option[Boolean] = None, masterTimeout: Option[String] = None ): ZioResponse[Boolean] = { val request = IndicesExistsTemplateRequest( name = name, flatSettings = flatSettings, local = local, masterTimeout = masterTimeout ) existsTemplate(request).map(_.contains(name)) } def existsTemplate( request: IndicesExistsTemplateRequest ): ZioResponse[IndicesExistsTemplateResponse] = client.execute(request) /* * Performs the flush operation on one or more indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-flush.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param force Whether a flush should be forced even if it is not necessarily needed ie. if no changes will be committed to the index. This is useful if transaction log IDs should be incremented even if no uncommitted changes are present. (This setting can be considered as internal) * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string for all indices * @param waitIfOngoing If set to true the flush operation will block until the flush can be executed if another flush operation is already executing. The default is true. If set to false the flush will be skipped iff if another flush operation is already running. */ def flush( indices: Seq[String] = Nil, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, force: Option[Boolean] = None, ignoreUnavailable: Option[Boolean] = None, waitIfOngoing: Option[Boolean] = None ): ZioResponse[IndicesFlushResponse] = { val request = IndicesFlushRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, force = force, ignoreUnavailable = ignoreUnavailable, indices = indices, waitIfOngoing = waitIfOngoing ) flush(request) } def flush( request: IndicesFlushRequest ): ZioResponse[IndicesFlushResponse] = client.execute(request) /* * Performs a synced flush operation on one or more indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-synced-flush-api.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string for all indices */ def flushSynced( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil ): ZioResponse[IndicesFlushSyncedResponse] = { val request = IndicesFlushSyncedRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices ) flushSynced(request) } def flushSynced(request: IndicesFlushSyncedRequest): ZioResponse[IndicesFlushSyncedResponse] = client.execute(request) /* * Performs the force merge operation on one or more indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-forcemerge.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param flush Specify whether the index should be flushed after performing the operation (default: true) * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param maxNumSegments The number of segments the index should be merged into (default: dynamic) * @param onlyExpungeDeletes Specify whether the operation should only expunge deleted documents */ def forcemerge( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, flush: Option[Boolean] = None, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, maxNumSegments: Option[Double] = None, onlyExpungeDeletes: Option[Boolean] = None ): ZioResponse[IndicesForcemergeResponse] = { val request = IndicesForcemergeRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, flush = flush, ignoreUnavailable = ignoreUnavailable, indices = indices, maxNumSegments = maxNumSegments, onlyExpungeDeletes = onlyExpungeDeletes ) forcemerge(request) } def forcemerge( request: IndicesForcemergeRequest ): ZioResponse[IndicesForcemergeResponse] = client.execute(request) /* * Returns information about one or more indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-get-index.html * * @param indices A comma-separated list of index names * @param allowNoIndices Ignore if a wildcard expression resolves to no concrete indices (default: false) * @param expandWildcards Whether wildcard expressions should get expanded to open or closed indices (default: open) * @param flatSettings Return settings in flat format (default: false) * @param ignoreUnavailable Ignore unavailable indexes (default: false) * @param includeDefaults Whether to return all default setting for each of the indices. * @param includeTypeName Whether to add the type name to the response (default: false) * @param local Return local information, do not retrieve the state from master node (default: false) * @param masterTimeout Specify timeout for connection to master */ def get( indices: Seq[String] = Nil, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, flatSettings: Option[Boolean] = None, ignoreUnavailable: Option[Boolean] = None, includeDefaults: Boolean = false, includeTypeName: Option[Boolean] = None, local: Option[Boolean] = None, masterTimeout: Option[String] = None ): ZioResponse[IndicesGetResponse] = { val request = IndicesGetRequest( indices = indices, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, flatSettings = flatSettings, ignoreUnavailable = ignoreUnavailable, includeDefaults = includeDefaults, includeTypeName = includeTypeName, local = local, masterTimeout = masterTimeout ) get(request) } def get( request: IndicesGetRequest ): ZioResponse[IndicesGetResponse] = client.execute(request) /* * Returns an alias. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-aliases.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names to filter aliases * @param local Return local information, do not retrieve the state from master node (default: false) * @param name A comma-separated list of alias names to return */ def getAlias( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, local: Option[Boolean] = None, name: Seq[String] = Nil ): ZioResponse[IndicesGetAliasResponse] = { val request = IndicesGetAliasRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices, local = local, name = name ) getAlias(request) } def getAlias(request: IndicesGetAliasRequest): ZioResponse[IndicesGetAliasResponse] = client.execute(request) /* * Returns mapping for one or more fields. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-get-field-mapping.html * * @param fields A comma-separated list of fields * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param includeDefaults Whether the default mapping values should be returned as well * @param includeTypeName Whether a type should be returned in the body of the mappings. * @param indices A comma-separated list of index names * @param local Return local information, do not retrieve the state from master node (default: false) */ def getFieldMapping( fields: Seq[String] = Nil, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, includeDefaults: Option[Boolean] = None, includeTypeName: Option[Boolean] = None, indices: Seq[String] = Nil, local: Option[Boolean] = None ): ZioResponse[IndicesGetFieldMappingResponse] = { val request = IndicesGetFieldMappingRequest( fields = fields, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, includeDefaults = includeDefaults, includeTypeName = includeTypeName, indices = indices, local = local ) getFieldMapping(request) } def getFieldMapping( request: IndicesGetFieldMappingRequest ): ZioResponse[IndicesGetFieldMappingResponse] = client.execute(request) /* * Returns mappings for one or more indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-get-mapping.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names * @param local Return local information, do not retrieve the state from master node (default: false) * @param masterTimeout Specify timeout for connection to master */ def getMapping( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, local: Option[Boolean] = None, masterTimeout: Option[String] = None ): ZioResponse[IndicesGetMappingResponse] = { val request = IndicesGetMappingRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices, local = local, masterTimeout = masterTimeout ) getMapping(request) } def getMapping(request: IndicesGetMappingRequest): ZioResponse[IndicesGetMappingResponse] = client.execute(request) /* * Returns settings for one or more indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-get-settings.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param flatSettings Return settings in flat format (default: false) * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param includeDefaults Whether to return all default setting for each of the indices. * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param local Return local information, do not retrieve the state from master node (default: false) * @param masterTimeout Specify timeout for connection to master * @param name The name of the settings that should be included */ def getSettings( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, flatSettings: Option[Boolean] = None, ignoreUnavailable: Option[Boolean] = None, includeDefaults: Boolean = false, indices: Seq[String] = Nil, local: Option[Boolean] = None, masterTimeout: Option[String] = None, name: Option[String] = None ): ZioResponse[IndicesGetSettingsResponse] = { val request = IndicesGetSettingsRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, flatSettings = flatSettings, ignoreUnavailable = ignoreUnavailable, includeDefaults = includeDefaults, indices = indices, local = local, masterTimeout = masterTimeout, name = name ) getSettings(request) } def getSettings(request: IndicesGetSettingsRequest): ZioResponse[IndicesGetSettingsResponse] = client.execute(request) /* * Returns an index template. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-templates.html * * @param flatSettings Return settings in flat format (default: false) * @param includeTypeName Whether a type should be returned in the body of the mappings. * @param local Return local information, do not retrieve the state from master node (default: false) * @param masterTimeout Explicit operation timeout for connection to master node * @param name The comma separated names of the index templates */ def getTemplate( flatSettings: Option[Boolean] = None, includeTypeName: Option[Boolean] = None, local: Option[Boolean] = None, masterTimeout: Option[String] = None, name: Option[String] = None ): ZioResponse[IndicesGetTemplateResponse] = { val request = IndicesGetTemplateRequest( flatSettings = flatSettings, includeTypeName = includeTypeName, local = local, masterTimeout = masterTimeout, name = name ) getTemplate(request) } def getTemplate(request: IndicesGetTemplateRequest): ZioResponse[IndicesGetTemplateResponse] = client.execute(request) /* * Shortcut to return all the templates */ def getTemplates(): ZioResponse[IndicesGetTemplateResponse] = { val request = IndicesGetTemplateRequest( name = None, flatSettings = Some(false), masterTimeout = None, local = Some(true) ) getTemplate(request) } /* * The _upgrade API is no longer useful and will be removed. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-upgrade.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ def getUpgrade( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil ): ZioResponse[IndicesGetUpgradeResponse] = { val request = IndicesGetUpgradeRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices ) getUpgrade(request) } def getUpgrade(request: IndicesGetUpgradeRequest): ZioResponse[IndicesGetUpgradeResponse] = client.execute(request) /* * Opens an index. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-open-close.html * * @param index A comma separated list of indices to open * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout * @param waitForActiveShards Sets the number of active shards to wait for before the operation returns. */ def open( indices: Seq[String], allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, masterTimeout: Option[String] = None, timeout: Option[String] = None, waitForActiveShards: Option[String] = None ): ZioResponse[IndicesOpenResponse] = { val request = IndicesOpenRequest( indices = indices, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, masterTimeout = masterTimeout, timeout = timeout, waitForActiveShards = waitForActiveShards ) open(request) } def open(request: IndicesOpenRequest): ZioResponse[IndicesOpenResponse] = client.execute(request) def open( index: String ): ZioResponse[IndicesOpenResponse] = client.execute(new IndicesOpenRequest(Seq(index))) /* * http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-aliases.html * * @param indices A list of index names the alias should point to (supports wildcards); use `_all` or omit to perform the operation on all indices. * @param name The name of the alias to be created or updated * @param body body the body of the call * @param timeout Explicit timestamp for the document * @param masterTimeout Specify timeout for connection to master */ def putAlias( indices: Seq[String] = Nil, name: String, body: JsonObject = JsonObject.empty, timeout: Option[String] = None, masterTimeout: Option[String] = None ): ZioResponse[IndicesPutAliasResponse] = { val request = IndicesPutAliasRequest( indices = indices, name = name, timeout = timeout, masterTimeout = masterTimeout ) putAlias(request) } def putAlias( request: IndicesPutAliasRequest ): ZioResponse[IndicesPutAliasResponse] = client.execute(request) def putMapping( index: String, docType: String, mapping: RootDocumentMapping ): ZioResponse[IndicesPutMappingResponse] = putMapping(indices = Seq(index), body = mapping.asJsonObject) /* * Updates the index mappings. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html * * @param indices A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices. * @param body body the body of the call * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout */ def putMapping( indices: Seq[String] = Nil, body: JsonObject, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, masterTimeout: Option[String] = None, timeout: Option[String] = None ): ZioResponse[IndicesPutMappingResponse] = { val request = IndicesPutMappingRequest( indices = indices, body = body, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, masterTimeout = masterTimeout, timeout = timeout ) putMapping(request) } def putMapping( request: IndicesPutMappingRequest ): ZioResponse[IndicesPutMappingResponse] = client.execute(request) /* * Updates the index settings. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-update-settings.html * * @param body body the body of the call * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param flatSettings Return settings in flat format (default: false) * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param masterTimeout Specify timeout for connection to master * @param preserveExisting Whether to update existing settings. If set to `true` existing settings on an index remain unchanged, the default is `false` * @param timeout Explicit operation timeout */ def putSettings( body: JsonObject, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, flatSettings: Option[Boolean] = None, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, masterTimeout: Option[String] = None, preserveExisting: Option[Boolean] = None, timeout: Option[String] = None ): ZioResponse[IndicesPutSettingsResponse] = { val request = IndicesPutSettingsRequest( body = body, allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, flatSettings = flatSettings, ignoreUnavailable = ignoreUnavailable, indices = indices, masterTimeout = masterTimeout, preserveExisting = preserveExisting, timeout = timeout ) putSettings(request) } def putSettings( request: IndicesPutSettingsRequest ): ZioResponse[IndicesPutSettingsResponse] = client.execute(request) /* * Creates or updates an index template. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-templates.html * * @param name The name of the template * @param body body the body of the call * @param create Whether the index template should only be added if new or can also replace an existing one * @param flatSettings Return settings in flat format (default: false) * @param includeTypeName Whether a type should be returned in the body of the mappings. * @param masterTimeout Specify timeout for connection to master * @param order The order for this template when merging multiple matching ones (higher numbers are merged later, overriding the lower numbers) * @param timeout Explicit operation timeout */ def putTemplate( name: String, body: JsonObject, create: Boolean = false, flatSettings: Option[Boolean] = None, includeTypeName: Option[Boolean] = None, masterTimeout: Option[String] = None, order: Option[Double] = None, timeout: Option[String] = None ): ZioResponse[IndicesPutTemplateResponse] = { val request = IndicesPutTemplateRequest( name = name, body = body, create = create, flatSettings = flatSettings, includeTypeName = includeTypeName, masterTimeout = masterTimeout, order = order, timeout = timeout ) putTemplate(request) putTemplate(request) } def putTemplate( request: IndicesPutTemplateRequest ): ZioResponse[IndicesPutTemplateResponse] = client.execute(request) /* * Returns information about ongoing index shard recoveries. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-recovery.html * * @param activeOnly Display only those recoveries that are currently on-going * @param detailed Whether to display detailed information about shard recovery * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ def recovery( activeOnly: Boolean = false, detailed: Boolean = false, indices: Seq[String] = Nil ): ZioResponse[IndicesRecoveryResponse] = { val request = IndicesRecoveryRequest(activeOnly = activeOnly, detailed = detailed, indices = indices) recovery(request) } def recovery( request: IndicesRecoveryRequest ): ZioResponse[IndicesRecoveryResponse] = client.execute(request) /* * Performs the refresh operation in one or more indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-refresh.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices */ def refresh( indices: Seq[String] = Nil, allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None ): ZioResponse[IndicesRefreshResponse] = { val request = IndicesRefreshRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices ) refresh(request) } def refresh(request: IndicesRefreshRequest): ZioResponse[IndicesRefreshResponse] = client.execute(request) /* * Updates an alias to point to a new index when the existing index is considered to be too large or too old. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-rollover-index.html * * @param alias The name of the alias to rollover * @param body body the body of the call * @param dryRun If set to true the rollover action will only be validated but not actually performed even if a condition matches. The default is false * @param includeTypeName Whether a type should be included in the body of the mappings. * @param masterTimeout Specify timeout for connection to master * @param newIndex The name of the rollover index * @param timeout Explicit operation timeout * @param waitForActiveShards Set the number of active shards to wait for on the newly created rollover index before the operation returns. */ def rollover( alias: String, body: Option[JsonObject] = None, dryRun: Option[Boolean] = None, includeTypeName: Option[Boolean] = None, masterTimeout: Option[String] = None, newIndex: Option[String] = None, timeout: Option[String] = None, waitForActiveShards: Option[String] = None ): ZioResponse[IndicesRolloverResponse] = { val request = IndicesRolloverRequest( alias = alias, body = body, dryRun = dryRun, includeTypeName = includeTypeName, masterTimeout = masterTimeout, newIndex = newIndex, timeout = timeout, waitForActiveShards = waitForActiveShards ) rollover(request) } def rollover( request: IndicesRolloverRequest ): ZioResponse[IndicesRolloverResponse] = client.execute(request) /* * Provides low-level information about segments in a Lucene index. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-segments.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param verbose Includes detailed memory usage by Lucene. */ def segments( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, verbose: Boolean = false ): ZioResponse[IndicesSegmentsResponse] = { val request = IndicesSegmentsRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices, verbose = verbose ) segments(request) } def segments(request: IndicesSegmentsRequest): ZioResponse[IndicesSegmentsResponse] = client.execute(request) /* * Provides store information for shard copies of indices. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shards-stores.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param status A comma-separated list of statuses used to filter on shards to get store information for */ def shardStores( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, status: Seq[String] = Nil ): ZioResponse[IndicesShardStoresResponse] = { val request = IndicesShardStoresRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices, status = status ) shardStores(request) } def shardStores(request: IndicesShardStoresRequest): ZioResponse[IndicesShardStoresResponse] = client.execute(request) /* * Allow to shrink an existing index into a new index with fewer primary shards. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-shrink-index.html * * @param index The name of the source index to shrink * @param target The name of the target index to shrink into * @param body body the body of the call * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout * @param waitForActiveShards Set the number of active shards to wait for on the shrunken index before the operation returns. */ def shrink( index: String, target: String, body: Option[JsonObject] = None, masterTimeout: Option[String] = None, timeout: Option[String] = None, waitForActiveShards: Option[String] = None ): ZioResponse[IndicesShrinkResponse] = { val request = IndicesShrinkRequest( index = index, target = target, body = body, masterTimeout = masterTimeout, timeout = timeout, waitForActiveShards = waitForActiveShards ) shrink(request) } def shrink(request: IndicesShrinkRequest): ZioResponse[IndicesShrinkResponse] = client.execute(request) /* * Allows you to split an existing index into a new index with more primary shards. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-split-index.html * * @param index The name of the source index to split * @param target The name of the target index to split into * @param body body the body of the call * @param masterTimeout Specify timeout for connection to master * @param timeout Explicit operation timeout * @param waitForActiveShards Set the number of active shards to wait for on the shrunken index before the operation returns. */ def split( index: String, target: String, body: Option[JsonObject] = None, masterTimeout: Option[String] = None, timeout: Option[String] = None, waitForActiveShards: Option[String] = None ): ZioResponse[IndicesSplitResponse] = { val request = IndicesSplitRequest( index = index, target = target, body = body, masterTimeout = masterTimeout, timeout = timeout, waitForActiveShards = waitForActiveShards ) split(request) } def split(request: IndicesSplitRequest): ZioResponse[IndicesSplitResponse] = client.execute(request) /* * Provides statistics on operations happening in an index. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-stats.html * * @param completionFields A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param fielddataFields A comma-separated list of fields for `fielddata` index metric (supports wildcards) * @param fields A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards) * @param forbidClosedIndices If set to false stats will also collected from closed indices if explicitly specified or if expand_wildcards expands to closed indices * @param groups A comma-separated list of search groups for `search` index metric * @param includeSegmentFileSizes Whether to report the aggregated disk usage of each one of the Lucene index files (only applies if segment stats are requested) * @param includeUnloadedSegments If set to true segment stats will include stats for segments that are not currently loaded into memory * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param level Return stats aggregated at cluster, index or shard level * @param metric Limit the information returned the specific metrics. * @param types A comma-separated list of document types for the `indexing` index metric */ def stats( indices: Seq[String] = Nil, completionFields: Seq[String] = Nil, expandWildcards: Seq[ExpandWildcards] = Nil, fielddataFields: Seq[String] = Nil, fields: Seq[String] = Nil, forbidClosedIndices: Boolean = true, groups: Seq[String] = Nil, includeSegmentFileSizes: Boolean = false, includeUnloadedSegments: Boolean = false, level: Level = Level.indices, metric: Option[String] = None, types: Seq[String] = Nil ): ZioResponse[IndicesStatsResponse] = { val request = IndicesStatsRequest( completionFields = completionFields, expandWildcards = expandWildcards, fielddataFields = fielddataFields, fields = fields, forbidClosedIndices = forbidClosedIndices, groups = groups, includeSegmentFileSizes = includeSegmentFileSizes, includeUnloadedSegments = includeUnloadedSegments, indices = indices, level = level, metric = metric, types = types ) stats(request) } def stats(request: IndicesStatsRequest): ZioResponse[IndicesStatsResponse] = client.execute(request) /* * Updates index aliases. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-aliases.html * * @param body body the body of the call * @param masterTimeout Specify timeout for connection to master * @param timeout Request timeout */ def updateAliases( body: JsonObject, masterTimeout: Option[String] = None, timeout: Option[String] = None ): ZioResponse[IndicesUpdateAliasesResponse] = { val request = IndicesUpdateAliasesRequest(body = body, masterTimeout = masterTimeout, timeout = timeout) updateAliases(request) } def updateAliases(request: IndicesUpdateAliasesRequest): ZioResponse[IndicesUpdateAliasesResponse] = client.execute(request) /* * The _upgrade API is no longer useful and will be removed. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-upgrade.html * * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names; use `_all` or empty string to perform the operation on all indices * @param onlyAncientSegments If true, only ancient (an older Lucene major release) segments will be upgraded * @param waitForCompletion Specify whether the request should block until the all segments are upgraded (default: false) */ def upgrade( allowNoIndices: Option[Boolean] = None, expandWildcards: Seq[ExpandWildcards] = Nil, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, onlyAncientSegments: Option[Boolean] = None, waitForCompletion: Option[Boolean] = None ): ZioResponse[IndicesUpgradeResponse] = { val request = IndicesUpgradeRequest( allowNoIndices = allowNoIndices, expandWildcards = expandWildcards, ignoreUnavailable = ignoreUnavailable, indices = indices, onlyAncientSegments = onlyAncientSegments, waitForCompletion = waitForCompletion ) upgrade(request) } def upgrade(request: IndicesUpgradeRequest): ZioResponse[IndicesUpgradeResponse] = client.execute(request) /* * Allows a user to validate a potentially expensive query without executing it. * For more info refers to https://www.elastic.co/guide/en/elasticsearch/reference/master/search-validate.html * * @param allShards Execute validation on all shards instead of one random shard per index * @param allowNoIndices Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified) * @param analyzeWildcard Specify whether wildcard and prefix queries should be analyzed (default: false) * @param analyzer The analyzer to use for the query string * @param body body the body of the call * @param defaultOperator The default operator for query string query (AND or OR) * @param df The field to use as default where no field prefix is given in the query string * @param docTypes A comma-separated list of document types to restrict the operation; leave empty to perform the operation on all types * @param expandWildcards Whether to expand wildcard expression to concrete indices that are open, closed or both. * @param explain Return detailed information about the error * @param ignoreUnavailable Whether specified concrete indices should be ignored when unavailable (missing or closed) * @param indices A comma-separated list of index names to restrict the operation; use `_all` or empty string to perform the operation on all indices * @param lenient Specify whether format-based query failures (such as providing text to a numeric field) should be ignored * @param q Query in the Lucene query string syntax * @param rewrite Provide a more detailed explanation showing the actual Lucene query that will be executed. */ def validateQuery( body: JsonObject, allShards: Option[Boolean] = None, allowNoIndices: Option[Boolean] = None, analyzeWildcard: Option[Boolean] = None, analyzer: Option[String] = None, defaultOperator: DefaultOperator = DefaultOperator.OR, df: Option[String] = None, docTypes: Seq[String] = Nil, expandWildcards: Seq[ExpandWildcards] = Nil, explain: Option[Boolean] = None, ignoreUnavailable: Option[Boolean] = None, indices: Seq[String] = Nil, lenient: Option[Boolean] = None, q: Option[String] = None, rewrite: Option[Boolean] = None ): ZioResponse[IndicesValidateQueryResponse] = { val request = IndicesValidateQueryRequest( allShards = allShards, allowNoIndices = allowNoIndices, analyzeWildcard = analyzeWildcard, analyzer = analyzer, body = body, defaultOperator = defaultOperator, df = df, expandWildcards = expandWildcards, explain = explain, ignoreUnavailable = ignoreUnavailable, indices = indices, lenient = lenient, q = q, rewrite = rewrite ) validateQuery(request) } def validateQuery(request: IndicesValidateQueryRequest): ZioResponse[IndicesValidateQueryResponse] = client.execute(request) def createWithSettingsAndMappings( index: String, settings: Settings = Settings(), mappings: Map[String, RootDocumentMapping] = Map.empty[String, RootDocumentMapping] ): ZioResponse[IndicesCreateResponse] = { /* Creates an index with optional settings. :ref:`qdb-guide-reference-api-admin-indices-create-index` :param index: the name of the index :keyword settings: a settings object or a dict containing settings */ val request = IndicesCreateRequest( index, body = CirceUtils.cleanValue( JsonObject.fromMap( Map("settings" -> settings.asJson, "mappings" -> mappings.asJson) ) ) ) client.execute(request) } def putMapping( indices: Seq[String], docType: String, mapping: RootDocumentMapping ): ZioResponse[IndicesPutMappingResponse] = putMapping( indices = indices, body = CirceUtils.cleanValue(mapping.asJsonObject) ) // def ensureIndex(index: String, // settings: org.qdb.common.settings.Settings, // mappings: Map[String, MappingMetaData]): Unit = { // val existsValue = client.awaitResult(this.exists(Seq(index))) // if (!existsValue.isExists) { // val request = new CreateIndexRequest(index).settings(settings) // mappings.foreach { // case (name, mapping) => // request.mapping(name, mapping.getSourceAsMap) // } // client.awaitResult(client.indices.create(request)) // } else { // val currMappings = client.mappings.get(index) // val toAdd = mappings.keySet -- currMappings.map(_.field).toSet // //TODO aparo: implement diff for mappings // toAdd.foreach { name => // mappings.find(_._1 == name).foreach { mapping => // val request = new PutMappingRequest(index).`type`(name).source(mapping._2.getSourceAsMap) // client.indices.putMapping(request) // } // } // // val res = client.cluster.health(waitForStatus=Some(WaitForStatus.yellow)) //TODO restore // val res = client.cluster.health() // client.awaitResult(res) // // } // } }
haroldl/rest.li
gradle-plugins/src/main/java/com/linkedin/pegasus/gradle/tasks/ChangedFileReportTask.java
package com.linkedin.pegasus.gradle.tasks; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import org.gradle.api.DefaultTask; import org.gradle.api.file.FileCollection; import org.gradle.api.specs.Specs; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.incremental.IncrementalTaskInputs; public class ChangedFileReportTask extends DefaultTask { private final Collection<String> _needCheckinFiles = new ArrayList<>(); private FileCollection _idlFiles = getProject().files(); private FileCollection _snapshotFiles = getProject().files(); public ChangedFileReportTask() { //with Gradle 6.0, Declaring an incremental task without outputs is not allowed. getOutputs().upToDateWhen(Specs.satisfyNone()); } @TaskAction public void checkFilesForChanges(IncrementalTaskInputs inputs) { getLogger().lifecycle("Checking idl and snapshot files for changes..."); getLogger().info("idlFiles: " + _idlFiles.getAsPath()); getLogger().info("snapshotFiles: " + _snapshotFiles.getAsPath()); Set<String> filesRemoved = new HashSet<>(); Set<String> filesAdded = new HashSet<>(); Set<String> filesChanged = new HashSet<>(); if (inputs.isIncremental()) { inputs.outOfDate(inputFileDetails -> { if (inputFileDetails.isAdded()) { filesAdded.add(inputFileDetails.getFile().getAbsolutePath()); } if (inputFileDetails.isRemoved()) { filesRemoved.add(inputFileDetails.getFile().getAbsolutePath()); } if (inputFileDetails.isModified()) { filesChanged.add(inputFileDetails.getFile().getAbsolutePath()); } }); inputs.removed(inputFileDetails -> filesRemoved.add(inputFileDetails.getFile().getAbsolutePath())); if (!filesRemoved.isEmpty()) { String files = joinByComma(filesRemoved); _needCheckinFiles.add(files); getLogger().lifecycle( "The following files have been removed, be sure to remove them from source control: {}", files); } if (!filesAdded.isEmpty()) { String files = joinByComma(filesAdded); _needCheckinFiles.add(files); getLogger().lifecycle("The following files have been added, be sure to add them to source control: {}", files); } if (!filesChanged.isEmpty()) { String files = joinByComma(filesChanged); _needCheckinFiles.add(files); getLogger().lifecycle( "The following files have been changed, be sure to commit the changes to source control: {}", files); } } } private String joinByComma(Set<String> files) { return files.stream().collect(Collectors.joining(", ")); } @InputFiles @SkipWhenEmpty public FileCollection getSnapshotFiles() { return _snapshotFiles; } public void setSnapshotFiles(FileCollection snapshotFiles) { _snapshotFiles = snapshotFiles; } @InputFiles @SkipWhenEmpty public FileCollection getIdlFiles() { return _idlFiles; } public void setIdlFiles(FileCollection idlFiles) { _idlFiles = idlFiles; } @Internal public Collection<String> getNeedCheckinFiles() { return _needCheckinFiles; } }
kathy32/code-front-end
algorithm/path.js
/** * 有一个 m 行 n 列的矩阵地图,起点位于左上角,终点位于右下角。 * * 一个机器人要从起点走到终点,而且每一步只能往前走(往右或往下),不能往回走。 * * 实现一个算法,输入 m 和 n,输出机器人从起点走到终点有多少条不同的路径。 * * 比如: * 输入: m = 2, n = 3 输出 3 * 解释: * 1. 右 -> 右 -> 下 * 2. 右 -> 下 -> 右 * 3. 下 -> 右 -> 右 * * 输入:m = 3, n = 6 输出 21 */ // 思路:https://leetcode-cn.com/problems/unique-paths/solution/ // 重要图示:https://leetcode-cn.com/problems/unique-paths/solution/tu-jie-bu-tong-lu-jing-shu-c-by-vin-18/ /** * @param {number} m 行数 * @param {number} n 列数 * @return {number} 路径条数 */ var paths = function(m, n) { // 重难点:创建二维数组,值为0 let dp = Array.from({length:m}, () => Array.from({length:n}, () => 0)) // 注意,对于第一行 dp[0][j],或者第一列 dp[i][0],由于都是在边界,所以只能为 1 for (let i=0; i<n; i++) dp[0][i] = 1 // 将第一行初始为1 for (let j=0; j<m; j++) dp[j][0] = 1 // 将第一列初始为1 for (let i=1; i<m; i++) { // 从第二行第二列开始遍历,记录到达每一个格子的不同路径数 for (let j=1; j<n; j++) { // 右下格子:右 -> 下 || 下 -> 右 dp[i][j] = dp[i-1][j] + dp[i][j-1] // 相邻并且已遍历格子 的路径数之和 } } return dp[m-1][n-1] }; console.log(paths(3, 7)) // 28
MXDTeam/zsrc
src/main/java/scripting/PortalScript.java
<gh_stars>1-10 package scripting; public interface PortalScript { void enter(PortalPlayerInteraction ppi); }
bridennis/leetcode-on-go
problems/easy/implement-strstr/main_test.go
package easy_implement_strstr import "testing" func Test_strStr(t *testing.T) { type args struct { haystack string needle string } tests := []struct { name string args args want int }{ { name: "strStr #1", args: struct { haystack string needle string }{haystack: "hello", needle: "ll"}, want: 2, }, { name: "strStr #2", args: struct { haystack string needle string }{haystack: "aaaaa", needle: "bba"}, want: -1, }, { name: "strStr #3", args: struct { haystack string needle string }{haystack: "", needle: ""}, want: 0, }, { name: "strStr #4", args: struct { haystack string needle string }{haystack: "abc", needle: "c"}, want: 2, }, { name: "strStr #5", args: struct { haystack string needle string }{haystack: "", needle: "a"}, want: -1, }, { name: "strStr #6", args: struct { haystack string needle string }{haystack: "a", needle: ""}, want: 0, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := strStr(tt.args.haystack, tt.args.needle); got != tt.want { t.Errorf("strStr() = %v, want %v", got, tt.want) } }) } } func BenchmarkStrStr(b *testing.B) { for i := 0; i < b.N; i++ { _ = strStr("hello", "ll") } }
KnpLabs/server-side-renderer
src/worker/index.js
export { default } from './initWorker'
dpkristensen/bfdm
pkg/BfsdlTests/source/CommonTypesTest.cpp
<reponame>dpkristensen/bfdm /** Tests for BFDP Common Types Copyright 2016-2019, <NAME>, Garmin Ltd, or its subsidiaries. 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 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 "gtest/gtest.h" #include "Bfdp/Common.hpp" #include "Bfdp/String.hpp" namespace BfsdlTests { using namespace Bfdp; class CommonTypesTest : public ::testing::Test { }; TEST_F( CommonTypesTest, IsWithinRange ) { ASSERT_FALSE( IsWithinRange< uint8_t >( 1U, 0U, 3U ) ); ASSERT_TRUE( IsWithinRange< uint8_t >( 1U, 1U, 3U ) ); ASSERT_TRUE( IsWithinRange< uint8_t >( 1U, 2U, 3U ) ); ASSERT_TRUE( IsWithinRange< uint8_t >( 1U, 3U, 3U ) ); ASSERT_FALSE( IsWithinRange< uint8_t >( 1U, 4U, 3U ) ); ASSERT_FALSE( IsWithinRange< int8_t >( -1, -2, 1 ) ); ASSERT_TRUE( IsWithinRange< int8_t >( -1, -1, 1 ) ); ASSERT_TRUE( IsWithinRange< int8_t >( -1, 0, 1 ) ); ASSERT_TRUE( IsWithinRange< int8_t >( -1, 1, 1 ) ); ASSERT_FALSE( IsWithinRange< int8_t >( -1, 2, 1 ) ); } TEST_F( CommonTypesTest, MemoryTypes ) { // Verify assumptions about memory types ASSERT_EQ( sizeof( std::size_t ), sizeof( size_t ) ); ASSERT_EQ( 1U, sizeof( Byte ) ); } TEST_F( CommonTypesTest, NumericTypes ) { // Verify assumptions about sized numeric types ASSERT_EQ( 1U, sizeof( uint8_t ) ); ASSERT_EQ( 2U, sizeof( uint16_t ) ); ASSERT_EQ( 4U, sizeof( uint32_t ) ); ASSERT_EQ( 8U, sizeof( uint64_t ) ); ASSERT_EQ( 1U, sizeof( int8_t ) ); ASSERT_EQ( 2U, sizeof( int16_t ) ); ASSERT_EQ( 4U, sizeof( int32_t ) ); ASSERT_EQ( 8U, sizeof( int64_t ) ); // Compare min/max values as LL and ULL to catch size errors for types < 64-bits ASSERT_EQ( -128LL, INT8_MIN ); ASSERT_EQ( 127LL, INT8_MAX ); ASSERT_EQ( 0ULL, UINT8_MIN ); ASSERT_EQ( 255ULL, UINT8_MAX ); ASSERT_EQ( -32768LL, INT16_MIN ); ASSERT_EQ( 32767LL, INT16_MAX ); ASSERT_EQ( 0ULL, UINT16_MIN ); ASSERT_EQ( 65535ULL, UINT16_MAX ); ASSERT_EQ( -2147483648LL, INT32_MIN ); ASSERT_EQ( 2147483647LL, INT32_MAX ); ASSERT_EQ( 0ULL, UINT32_MIN ); ASSERT_EQ( 4294967295ULL, UINT32_MAX ); ASSERT_EQ( -9223372036854775808LL, INT64_MIN ); ASSERT_EQ( 9223372036854775807LL, INT64_MAX ); ASSERT_EQ( 0ULL, UINT64_MIN ); ASSERT_EQ( 18446744073709551615ULL, UINT64_MAX ); } TEST_F( CommonTypesTest, StrContains ) { Byte const helloBytes[] = { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; Byte const hiBytes[] = { 0x48, 0x69 }; std::string const helloStr = String( helloBytes, sizeof( helloBytes ) ); std::string const hiStr = String( hiBytes, sizeof( hiBytes ) ); ASSERT_STREQ( "Hello", helloStr.c_str() ); ASSERT_STREQ( "Hi", hiStr.c_str() ); ASSERT_FALSE( StrContains( helloStr, hiBytes, sizeof( hiBytes ) ) ); ASSERT_FALSE( StrContains( hiStr, helloBytes, sizeof( helloBytes ) ) ); ASSERT_TRUE( StrContains( helloStr, helloBytes, sizeof( helloBytes ) ) ); ASSERT_TRUE( StrContains( hiStr, hiBytes, sizeof( hiBytes ) ) ); Byte const loBytes[] = { 0x6c, 0x6f }; ASSERT_TRUE( StrContains( helloStr, loBytes, sizeof( loBytes ) ) ); ASSERT_FALSE( StrContains( hiStr, loBytes, sizeof( loBytes ) ) ); Byte const elBytes[] = { 0x65, 0x6c }; ASSERT_TRUE( StrContains( helloStr, elBytes, sizeof( elBytes ) ) ); ASSERT_FALSE( StrContains( hiStr, elBytes, sizeof( elBytes ) ) ); } } // namespace BfsdlTests
er5bus/sm
src/containers/admin/containers/assessment-tool/components/menu/AssessmentToolEdit.js
import React, { useEffect } from "react" import { injectIntl } from "react-intl" import { isEmpty } from "lodash" import { shallowEqual, useSelector, useDispatch } from "react-redux" import { fetchAssessmentTool } from "./../../store/actions" import menuItems from "./items/edit" import {Menu} from "../../../../../../components/partials" import AssessmentToolInformation from "./AssessmentToolInformation" const EditAssessmentTool = ({ param, intl }) => { const dispatch = useDispatch() // const layoutDispatch = useContext(LayoutContext.Dispatch) const { assessmentTool } = useSelector( (state) => ({ refresh: state.admin.assessmentTool.refresh, isFetching: state.admin.assessmentTool.isFetching, assessmentTool: state.admin.assessmentTool.assessmentTool }), shallowEqual ) useEffect(() => { if (isEmpty(assessmentTool) || assessmentTool.id !== param) { dispatch(fetchAssessmentTool({ param })) } // eslint-disable-next-line }, []) const items = menuItems({ intl, param }) return (<Menu items={items}> <AssessmentToolInformation assessmentTool={assessmentTool} param={param} /> </Menu> ) } export default injectIntl(EditAssessmentTool)
nithinkumar030/bigmuddy-network-telemetry-pipeline
vendor/github.com/cisco/bigmuddy-network-telemetry-proto/proto_go/cisco_ios_xr_ipv4_ospf_oper/ospf/processes/process/default_vrf/mpls_te/mpls_te_fragments/mpls_te_fragment/a.go
<gh_stars>1-10 //go:generate protoc --go_out=plugins=grpc:. ospf_sh_mpls.proto // Cisco-IOS-XR-ipv4-ospf-oper:ospf/processes/process/default-vrf/mpls-te/mpls-te-fragments/mpls-te-fragment package cisco_ios_xr_ipv4_ospf_oper_ospf_processes_process_default_vrf_mpls_te_mpls_te_fragments_mpls_te_fragment
ciremoussadia/finitio-rb
lib/finitio/syntax/import.rb
module Finitio module Syntax module Import include Node capture :import_url def compile(system) file = system.resolve_url(import_url) imported = Finitio.send(:_system, file) system.add_import(imported) system end def to_ast [:import, import_url] end end # module Import end # module Syntax end # module Finitio
femmebot/shape
__tests__/ui/global/MainMenuDropdown.unit.test.js
import MainMenuDropdown, { CONTEXT_USER, CONTEXT_ORG, } from '~/ui/global/MainMenuDropdown' import { fakeOrganization } from '#/mocks/data' import fakeUiStore from '#/mocks/fakeUiStore' import fakeApiStore from '#/mocks/fakeApiStore' import fakeRoutingStore from '#/mocks/fakeRoutingStore' window.IdeoSSO = { profileUrl: 'https://profile.url' } describe('MainMenuDropdown', () => { let component, wrapper, props, otherFakeOrg, itemNames beforeEach(() => { const apiStore = fakeApiStore() otherFakeOrg = { ...fakeOrganization, id: 999, name: 'new', primary_group: { name: 'new' }, } apiStore.currentUserOrganization = fakeOrganization fakeOrganization.primary_group.can_edit = true apiStore.currentUser.organizations = [fakeOrganization, otherFakeOrg] props = { open: true, onItemClick: jest.fn(), apiStore, routingStore: fakeRoutingStore, uiStore: fakeUiStore, showCurrentOrg: false, } itemNames = [ 'People & Groups', 'New Organization', 'Settings', 'Contact Support', 'Billing', 'Terms of Use', 'Privacy Policy', 'Do not Sell My Info', 'CA User Rights', ] props.uiStore.alert.mockClear() props.uiStore.confirm.mockClear() render = () => { wrapper = shallow(<MainMenuDropdown.wrappedComponent {...props} />) component = wrapper.instance() } render() }) describe('menuItems', () => { it('should add organizations to the list of items', () => { expect(component.menuItems.organizations[0].name).toEqual( otherFakeOrg.primary_group.name ) expect(component.menuItems.organizations[0].iconLeft).toBeTruthy() }) it('should not add your current organization to list of items', () => { const orgNames = component.menuItems.organizations.map(o => o.name) expect(orgNames.indexOf(fakeOrganization.primary_group.name)).toEqual(-1) }) it('should have all other menu items', () => { const items = component.menuItems.top.concat(component.menuItems.bottom) expect(items.map(i => i.name)).toEqual(itemNames) }) describe('if current user is not an org admin', () => { beforeEach(() => { fakeOrganization.primary_group.can_edit = false }) it('should not show the settings link', () => { expect( component.menuItems.bottom.find(item => item.name === 'Settings') ).toBeFalsy() }) it('should not show the billing link', () => { expect( component.menuItems.bottom.find(item => item.name === 'Billing') ).toBeFalsy() }) }) describe('if displaying the user menu', () => { beforeEach(() => { props.context = CONTEXT_USER render() }) it('has a main group', () => { expect(component.menuItems.main).toBeDefined() }) it('does not have a top group', () => { expect(component.menuItems.top).toBeUndefined() }) it('has user settings option', () => { const link = component.menuItems.main.find( item => item.name === 'Account Settings' ) expect(link).toBeDefined() expect(link.onClick).toBeInstanceOf(Function) }) it('has notifications option', () => { const link = component.menuItems.main.find( item => item.name === 'User Settings' ) expect(link).toBeDefined() expect(link.onClick).toBeInstanceOf(Function) }) it('has logout option', () => { const link = component.menuItems.main.find( item => item.name === 'Logout' ) expect(link).toBeDefined() expect(link.onClick).toBeInstanceOf(Function) }) }) describe('if displaying the org menu', () => { beforeEach(() => { props.context = CONTEXT_ORG render() }) it('has the correct groups', () => { expect(component.menuItems.top).toBeDefined() expect(component.menuItems.organizations).toBeDefined() expect(component.menuItems.bottom).toBeDefined() }) it('does not have a main group', () => { expect(component.menuItems.main).toBeUndefined() }) it('has a People & Groups option', () => { const link = component.menuItems.top.find( item => item.name === 'People & Groups' ) expect(link).toBeDefined() expect(link.onClick).toBeInstanceOf(Function) }) it('has a New Organization option', () => { const link = component.menuItems.bottom.find( item => item.name === 'New Organization' ) expect(link).toBeDefined() expect(link.onClick).toBeInstanceOf(Function) }) }) }) describe('openOrgMenu', () => { beforeEach(() => { component.handleOrgPeople() }) it('sets organization page to passed in page name', () => { expect(props.uiStore.update).toHaveBeenCalledWith( 'organizationMenuPage', 'organizationPeople' ) }) }) describe('handleSwitchOrg', () => { const fakeEv = { preventDefault: () => null } it('should route you to the organization', () => { component.handleSwitchOrg(fakeOrganization)(fakeEv) expect(fakeRoutingStore.routeTo).toHaveBeenCalledWith( `/${fakeOrganization.slug}` ) }) it('should call uiStore.confirm if trying to move cards between orgs', () => { props.uiStore.isMovingCards = true wrapper.setProps(props) component.handleSwitchOrg(fakeOrganization)(fakeEv) // findOrganizationById to lookup the name for the confirm dialog expect(props.apiStore.findOrganizationById).toHaveBeenCalledWith( fakeOrganization.id ) expect(props.uiStore.confirm).toHaveBeenCalled() }) }) describe('handleZendesk', () => { const zEBackup = global.zE beforeEach(() => { global.zE = { activate: jest.fn() } component.handleZendesk() }) it('should activate the Zendesk widget', () => { expect(global.zE.activate).toHaveBeenCalledWith({ hideOnClose: true }) }) afterEach(() => { global.zE = zEBackup }) }) describe('handleBilling', () => { beforeEach(() => { component.handleBilling() }) it('should route to the billing page', () => { expect(props.routingStore.routeTo).toHaveBeenCalledWith('/billing') }) }) describe('handleTerms', () => { beforeEach(() => { component.handleTerms() }) it('should route to the terms page', () => { expect(props.routingStore.routeTo).toHaveBeenCalledWith('/terms') }) }) describe('handleExternalLink', () => { const url = 'https://www.ideo.com/privacy' beforeEach(() => { window.open = jest.fn() const handler = component.handleExternalLink(url) handler() }) it('should route to the external page', () => { expect(window.open).toHaveBeenCalledWith(url, '_blank') }) }) describe('with showCurrentOrg = true', () => { beforeEach(() => { props.showCurrentOrg = true render() }) it('should still show the current organization in the dropdown', () => { const orgNames = component.menuItems.organizations.map(o => o.name) expect(orgNames.indexOf(fakeOrganization.primary_group.name)).not.toEqual( -1 ) }) }) })
Andreas237/AndroidPolicyAutomation
ExtractedJars/Health_com.huawei.health/javafiles/cn/com/fmsh/nfcos/client/service/huawei/NfcosActivity.java
<gh_stars>1-10 // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package cn.com.fmsh.nfcos.client.service.huawei; import android.os.Parcel; import android.os.Parcelable; public class NfcosActivity implements Parcelable { public NfcosActivity() { // 0 0:aload_0 // 1 1:invokespecial #31 <Method void Object()> // 2 4:return } public int describeContents() { return 0; // 0 0:iconst_0 // 1 1:ireturn } public void readFromParcel(Parcel parcel) { name = parcel.readString(); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokevirtual #41 <Method String Parcel.readString()> // 3 5:putfield #43 <Field String name> code = parcel.readString(); // 4 8:aload_0 // 5 9:aload_1 // 6 10:invokevirtual #41 <Method String Parcel.readString()> // 7 13:putfield #45 <Field String code> start = parcel.readString(); // 8 16:aload_0 // 9 17:aload_1 // 10 18:invokevirtual #41 <Method String Parcel.readString()> // 11 21:putfield #47 <Field String start> end = parcel.readString(); // 12 24:aload_0 // 13 25:aload_1 // 14 26:invokevirtual #41 <Method String Parcel.readString()> // 15 29:putfield #49 <Field String end> total = parcel.readInt(); // 16 32:aload_0 // 17 33:aload_1 // 18 34:invokevirtual #52 <Method int Parcel.readInt()> // 19 37:putfield #54 <Field int total> remainder = parcel.readInt(); // 20 40:aload_0 // 21 41:aload_1 // 22 42:invokevirtual #52 <Method int Parcel.readInt()> // 23 45:putfield #56 <Field int remainder> definition = parcel.readString(); // 24 48:aload_0 // 25 49:aload_1 // 26 50:invokevirtual #41 <Method String Parcel.readString()> // 27 53:putfield #58 <Field String definition> payChannel = parcel.readString(); // 28 56:aload_0 // 29 57:aload_1 // 30 58:invokevirtual #41 <Method String Parcel.readString()> // 31 61:putfield #60 <Field String payChannel> payMin = parcel.readInt(); // 32 64:aload_0 // 33 65:aload_1 // 34 66:invokevirtual #52 <Method int Parcel.readInt()> // 35 69:putfield #62 <Field int payMin> // 36 72:return } public void writeToParcel(Parcel parcel, int i) { parcel.writeString(name); // 0 0:aload_1 // 1 1:aload_0 // 2 2:getfield #43 <Field String name> // 3 5:invokevirtual #68 <Method void Parcel.writeString(String)> parcel.writeString(code); // 4 8:aload_1 // 5 9:aload_0 // 6 10:getfield #45 <Field String code> // 7 13:invokevirtual #68 <Method void Parcel.writeString(String)> parcel.writeString(start); // 8 16:aload_1 // 9 17:aload_0 // 10 18:getfield #47 <Field String start> // 11 21:invokevirtual #68 <Method void Parcel.writeString(String)> parcel.writeString(end); // 12 24:aload_1 // 13 25:aload_0 // 14 26:getfield #49 <Field String end> // 15 29:invokevirtual #68 <Method void Parcel.writeString(String)> parcel.writeInt(total); // 16 32:aload_1 // 17 33:aload_0 // 18 34:getfield #54 <Field int total> // 19 37:invokevirtual #72 <Method void Parcel.writeInt(int)> parcel.writeInt(remainder); // 20 40:aload_1 // 21 41:aload_0 // 22 42:getfield #56 <Field int remainder> // 23 45:invokevirtual #72 <Method void Parcel.writeInt(int)> parcel.writeString(definition); // 24 48:aload_1 // 25 49:aload_0 // 26 50:getfield #58 <Field String definition> // 27 53:invokevirtual #68 <Method void Parcel.writeString(String)> parcel.writeString(payChannel); // 28 56:aload_1 // 29 57:aload_0 // 30 58:getfield #60 <Field String payChannel> // 31 61:invokevirtual #68 <Method void Parcel.writeString(String)> parcel.writeInt(payMin); // 32 64:aload_1 // 33 65:aload_0 // 34 66:getfield #62 <Field int payMin> // 35 69:invokevirtual #72 <Method void Parcel.writeInt(int)> // 36 72:return } public static final android.os.Parcelable.Creator CREATOR = new android.os.Parcelable.Creator() { public NfcosActivity createFromParcel(Parcel parcel) { NfcosActivity nfcosactivity = new NfcosActivity(); // 0 0:new #9 <Class NfcosActivity> // 1 3:dup // 2 4:invokespecial #17 <Method void NfcosActivity()> // 3 7:astore_2 nfcosactivity.name = parcel.readString(); // 4 8:aload_2 // 5 9:aload_1 // 6 10:invokevirtual #23 <Method String Parcel.readString()> // 7 13:putfield #27 <Field String NfcosActivity.name> nfcosactivity.code = parcel.readString(); // 8 16:aload_2 // 9 17:aload_1 // 10 18:invokevirtual #23 <Method String Parcel.readString()> // 11 21:putfield #30 <Field String NfcosActivity.code> nfcosactivity.start = parcel.readString(); // 12 24:aload_2 // 13 25:aload_1 // 14 26:invokevirtual #23 <Method String Parcel.readString()> // 15 29:putfield #33 <Field String NfcosActivity.start> nfcosactivity.end = parcel.readString(); // 16 32:aload_2 // 17 33:aload_1 // 18 34:invokevirtual #23 <Method String Parcel.readString()> // 19 37:putfield #36 <Field String NfcosActivity.end> nfcosactivity.total = parcel.readInt(); // 20 40:aload_2 // 21 41:aload_1 // 22 42:invokevirtual #40 <Method int Parcel.readInt()> // 23 45:putfield #44 <Field int NfcosActivity.total> nfcosactivity.remainder = parcel.readInt(); // 24 48:aload_2 // 25 49:aload_1 // 26 50:invokevirtual #40 <Method int Parcel.readInt()> // 27 53:putfield #47 <Field int NfcosActivity.remainder> nfcosactivity.definition = parcel.readString(); // 28 56:aload_2 // 29 57:aload_1 // 30 58:invokevirtual #23 <Method String Parcel.readString()> // 31 61:putfield #50 <Field String NfcosActivity.definition> nfcosactivity.payChannel = parcel.readString(); // 32 64:aload_2 // 33 65:aload_1 // 34 66:invokevirtual #23 <Method String Parcel.readString()> // 35 69:putfield #53 <Field String NfcosActivity.payChannel> nfcosactivity.payMin = parcel.readInt(); // 36 72:aload_2 // 37 73:aload_1 // 38 74:invokevirtual #40 <Method int Parcel.readInt()> // 39 77:putfield #56 <Field int NfcosActivity.payMin> return nfcosactivity; // 40 80:aload_2 // 41 81:areturn } public volatile Object createFromParcel(Parcel parcel) { return ((Object) (createFromParcel(parcel))); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokevirtual #59 <Method NfcosActivity createFromParcel(Parcel)> // 3 5:areturn } public NfcosActivity[] newArray(int i) { return new NfcosActivity[i]; // 0 0:iload_1 // 1 1:anewarray NfcosActivity[] // 2 4:areturn } public volatile Object[] newArray(int i) { return ((Object []) (newArray(i))); // 0 0:aload_0 // 1 1:iload_1 // 2 2:invokevirtual #64 <Method NfcosActivity[] newArray(int)> // 3 5:areturn } } ; public String code; public String definition; public String end; public String name; public String payChannel; public int payMin; public int remainder; public String start; public int total; static { // 0 0:new #8 <Class NfcosActivity$1> // 1 3:dup // 2 4:invokespecial #27 <Method void NfcosActivity$1()> // 3 7:putstatic #29 <Field android.os.Parcelable$Creator CREATOR> //* 4 10:return } }
uagg/SoftwareUniversity
3. Professional Module/Java Web Developer/1. Java Fundamentals/1. Java Advanced/04. Data Representation And Manipulation/Lab/1. Sorting/src/Main.java
<reponame>uagg/SoftwareUniversity /* Implement the following sorting algorithms: • Bubble Sort • Selection Sort Read a sequence of numbers from the console, sort them and print them back. */ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] arr = input.nextLine().split(" "); int[] parsedArr = new int[arr.length]; for (int i = 0; i < arr.length; i++) { parsedArr[i] = Integer.parseInt(arr[i]); } for (int i = 0; i < parsedArr.length - 1; i++) { int index = i; for (int j = i + 1; j < parsedArr.length; j++) { if (parsedArr[j] < parsedArr[index]) { index = j; } } int smallerNumber = parsedArr[index]; parsedArr[index] = parsedArr[i]; parsedArr[i] = smallerNumber; } for (int element : parsedArr) { System.out.print(element + " "); } } } //import java.util.Scanner; // //public class Main { // // public static void main(String[] args) { // Scanner input = new Scanner(System.in); // String[] arr = input.nextLine().split(" "); // int[] parsedArr = new int[arr.length]; // // for (int i = 0; i < arr.length; i++) { // parsedArr[i] = Integer.parseInt(arr[i]); // } // // boolean isSwapped = true; // // while (isSwapped) { // isSwapped = false; // for (int i = 0; i < parsedArr.length - 1; i++) { // if (parsedArr[i] > parsedArr[i + 1]) { // int temp = parsedArr[i + 1]; // parsedArr[i + 1] = parsedArr[i]; // parsedArr[i] = temp; // isSwapped = true; // } // } // } // // for (int element : parsedArr) { // System.out.print(element + " "); // } // } //}
bobperonga/way4u
src/components/contact-component/contact-form.js
<filename>src/components/contact-component/contact-form.js import styled from "styled-components" export const ContactForm = styled.form` background: white; padding: 30px; color: #5d5d5d; display: flex; flex-direction: column; h3 { font-size: 1.8rem; line-height: 1.8rem; } input[type="button"] { border: none; background: #e20e2d; font-size: 1.4rem; color: white; width: 16.6rem; height: 3.2rem; align-self: flex-end; margin-top: 20px; outline: none; transition: box-shadow .2s; cursor: pointer; :hover{ box-shadow: 0 0 0.5rem 0 black; } } ` export const FormContent = styled.div` display: flex; flex-direction: column; p { font-size: 1.4rem; line-height: 1.4rem; font-weight: 700; } input { height: 3.2rem; } textarea{ resize: none; height: 6.6rem; } `
yath/restic
cmd/restic/cmd_list.go
package main import ( "errors" "fmt" "github.com/restic/restic/backend" ) type CmdList struct{} func init() { _, err := parser.AddCommand("list", "lists data", "The list command lists structures or data of a repository", &CmdList{}) if err != nil { panic(err) } } func (cmd CmdList) Usage() string { return "[data|trees|snapshots|keys|locks]" } func (cmd CmdList) Execute(args []string) error { if len(args) != 1 { return fmt.Errorf("type not specified, Usage: %s", cmd.Usage()) } s, err := OpenRepo() if err != nil { return err } var ( t backend.Type each func(backend.Type, func(backend.ID, []byte, error)) error = s.Each ) switch args[0] { case "data": t = backend.Data each = s.EachDecrypted case "trees": t = backend.Tree each = s.EachDecrypted case "snapshots": t = backend.Snapshot case "maps": t = backend.Map case "keys": t = backend.Key case "locks": t = backend.Lock default: return errors.New("invalid type") } return each(t, func(id backend.ID, data []byte, err error) { if t == backend.Data || t == backend.Tree { fmt.Printf("%s %s\n", id, backend.Hash(data)) } else { fmt.Printf("%s\n", id) } }) }
WillTong/mybatis-helper
mybatis-helper-datascope/src/main/java/com/github/mybatis/helper/datascope/annotation/DataScopeSettings.java
package com.github.mybatis.helper.datascope.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD}) public @interface DataScopeSettings { boolean onlyUseSmallScope() default true; /** * 自定义dataScope生效的字段 * @return activeScopeFields */ ActiveScopeField[] activeScopeFields() default {}; /** * sql风格 * @return dataScopeSqlStyle */ DataScopeSqlStyle dataScopeSqlStyle() default DataScopeSqlStyle.OUTER; /** * 外部sql配置 * @return outerSqlStyleSettings */ OuterSqlStyleSettings outerSqlStyleSettings() default @OuterSqlStyleSettings; /** * 内部sql配置 * @return innerSqlStyleSettings */ InnerSqlStyleSettings innerSqlStyleSettings() default @InnerSqlStyleSettings; }
NellyD3v/GitHub-Defreshed
src/fixers/repository/edit-details-fixer.js
import { isRepoRoot, isRepoSetup } from "../../tools/path-detector"; import { waitUntilElementsReady, checkIfElementsReady } from "../../tools/wait-until-ready"; import Fixer from "../fixer"; /** * Moves repository's details editor to the top section. */ export default class EditDetailsFixer extends Fixer { /** @inheritdoc */ isApplieble(location) { return isRepoRoot(location) && !isRepoSetup(location); } /** @inheritdoc */ async waitUntilFixerReady() { return (await waitUntilElementsReady("main:nth-child(1) .repository-content .BorderGrid-row")) && (await checkIfElementsReady("main:nth-child(1) .repository-content .BorderGrid-row:nth-child(1) details")); } /** @inheritdoc */ apply() { let details = document.querySelector("main .repository-content .BorderGrid-row:nth-child(1) details"); if (details) document.querySelector("main .repository-content").prepend(details); } }
eugeneilyin/mdi-norm
es/OutlineSignalWifiOff.js
import React from 'react'; import { Icon } from './Icon'; export var OutlineSignalWifiOff = /*#__PURE__*/ function OutlineSignalWifiOff(props) { return React.createElement(Icon, props, React.createElement("path", { d: "M23.64 7c-.45-.34-4.93-4-11.64-4-1.32 0-2.55.14-3.69.38L18.43 13.5 23.64 7zM3.41 1.31L2 2.72l2.05 2.05C1.91 5.76.59 6.82.36 7L12 21.5l3.91-4.87 3.32 3.32 1.41-1.41z" })); };
shmarovfedor/esbmc
regression/esbmc-cpp/cpp/ch4_17/main.cpp
// Fig. 4.17: fig04_17.cpp // This program introduces the topic of survey data analysis. // It computes the mean, median, and mode of the data. #include <iostream> using std::cout; using std::endl; using std::fixed; #include <iomanip> using std::setw; using std::setprecision; void mean( const int [], int ); void median( int [], int ); void mode( int [], int [], int ); void bubbleSort( int[], int ); void printArray( const int[], int ); int main() { const int responseSize = 99; // size of array responses int frequency[ 10 ] = { 0 }; // initialize array frequency // initialize array responses int response[ responseSize ] = { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 7, 8, 9, 5, 9, 8, 7, 8, 7, 8, 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 4, 5, 6, 1, 6, 5, 7, 8, 7 }; // process responses mean( response, responseSize ); median( response, responseSize ); mode( frequency, response, responseSize ); return 0; // indicates successful termination } // end main // calculate average of all response values void mean( const int answer[], int arraySize ) { int total = 0; cout << "********\n Mean\n********\n"; // total response values for ( int i = 0; i < arraySize; i++ ) total += answer[ i ]; // format and output results cout << fixed << setprecision( 4 ); cout << "The mean is the average value of the data\n" << "items. The mean is equal to the total of\n" << "all the data items divided by the number\n" << "of data items (" << arraySize << "). The mean value for\nthis run is: " << total << " / " << arraySize << " = " << static_cast< double >( total ) / arraySize << "\n\n"; } // end function mean // sort array and determine median element's value void median( int answer[], int size ) { cout << "\n********\n Median\n********\n" << "The unsorted array of responses is"; printArray( answer, size ); // output unsorted array bubbleSort( answer, size ); // sort array cout << "\n\nThe sorted array is"; printArray( answer, size ); // output sorted array // display median element cout << "\n\nThe median is element " << size / 2 << " of\nthe sorted " << size << " element array.\nFor this run the median is " << answer[ size / 2 ] << "\n\n"; } // end function median // determine most frequent response void mode( int freq[], int answer[], int size ) { int largest = 0; // represents largest frequency int modeValue = 0; // represents most frequent response cout << "\n********\n Mode\n********\n"; // initialize frequencies to 0 for ( int i = 1; i <= 9; i++ ) freq[ i ] = 0; // summarize frequencies for ( int j = 0; j < size; j++ ) ++freq[ answer[ j ] ]; // output headers for result columns cout << "Response" << setw( 11 ) << "Frequency" << setw( 19 ) << "Histogram\n\n" << setw( 55 ) << "1 1 2 2\n" << setw( 56 ) << "5 0 5 0 5\n\n"; // output results for ( int rating = 1; rating <= 9; rating++ ) { cout << setw( 8 ) << rating << setw( 11 ) << freq[ rating ] << " "; // keep track of mode value and largest fequency value if ( freq[ rating ] > largest ) { largest = freq[ rating ]; modeValue = rating; } // end if // output histogram bar representing frequency value for ( int k = 1; k <= freq[ rating ]; k++ ) cout << '*'; cout << '\n'; // begin new line of output } // end outer for // display the mode value cout << "The mode is the most frequent value.\n" << "For this run the mode is " << modeValue << " which occurred " << largest << " times." << endl; } // end function mode // function that sorts an array with bubble sort algorithm void bubbleSort( int a[], int size ) { int hold; // temporary location used to swap elements // loop to control number of passes for ( int pass = 1; pass < size; pass++ ) // loop to control number of comparisons per pass for ( int j = 0; j < size - 1; j++ ) // swap elements if out of order if ( a[ j ] > a[ j + 1 ] ) { hold = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = hold; } // end if } // end function bubbleSort // output array contents (20 values per row) void printArray( const int a[], int size ) { for ( int i = 0; i < size; i++ ) { if ( i % 20 == 0 ) // begin new line every 20 values cout << endl; cout << setw( 2 ) << a[ i ]; } // end for } // end function printArray /************************************************************************** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and Prentice * * Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
meherwan/ProjectFirst
node_modules/babel-npm-module-example/example.js
'use strict'; /* global require */ var Developer = require('./dist/developer.js').default; var developer = new Developer('Alex', '??'); developer.sayWhoAmI();
PhysShell/inexplicable_engine
inex/render/api.h
//////////////////////////////////////////////////////////////////////////// // Created : 04.01.2019 // Author : <NAME> //////////////////////////////////////////////////////////////////////////// #ifndef INEX_RENDER_API_H_INCLUDED # define INEX_RENDER_API_H_INCLUDED # ifndef INEX_RENDER_API # include <inex/macro_compiler.h> //# ifdef INEX_STATIC_LIBRARIES //# define INEX_CORE_API //# else # ifdef INEX_RENDER_EXPORTS # define INEX_RENDER_API INEX_DLL_EXPORT # else // #ifdef IECORE_EXPORTS # define INEX_RENDER_API INEX_DLL_IMPORT # endif // #ifdef IECORE_EXPORTS //# endif // #ifndef INEX_STATIC_LIBRARIES # endif // #ifdef INEX_CORE_API namespace inex { namespace render { struct world; namespace engine { struct wrapper; } // namespace engine INEX_RENDER_API world* create_world ( render::engine::wrapper& engine, HWND window_handle ); INEX_RENDER_API void destroy_world ( world*& world ); } // namespace render } // namespace inex #endif // #ifndef INEX_RENDER_API_H_INCLUDED
chromium/chromium
chrome/browser/ash/arc/sharesheet/arc_sharesheet_bridge.h
<filename>chrome/browser/ash/arc/sharesheet/arc_sharesheet_bridge.h // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ASH_ARC_SHARESHEET_ARC_SHARESHEET_BRIDGE_H_ #define CHROME_BROWSER_ASH_ARC_SHARESHEET_ARC_SHARESHEET_BRIDGE_H_ #include "ash/components/arc/mojom/sharesheet.mojom.h" #include "base/memory/weak_ptr.h" #include "components/keyed_service/core/keyed_service.h" class Profile; namespace content { class BrowserContext; } // namespace content namespace arc { class ArcBridgeService; // This class handles sharesheet related IPC from ARC++ and allows sharesheet // to be displayed and managed in Chrome preview instead of the Android // sharesheet activity. class ArcSharesheetBridge : public KeyedService, public mojom::SharesheetHost { public: // Returns singleton instance for the given BrowserContext, // or nullptr if the browser |context| is not allowed to use ARC. static ArcSharesheetBridge* GetForBrowserContext( content::BrowserContext* context); static ArcSharesheetBridge* GetForBrowserContextForTesting( content::BrowserContext* context); ArcSharesheetBridge(content::BrowserContext* context, ArcBridgeService* bridge_service); ArcSharesheetBridge(const ArcSharesheetBridge&) = delete; ArcSharesheetBridge& operator=(const ArcSharesheetBridge&) = delete; ~ArcSharesheetBridge() override; // mojom::SharesheetHost overrides: // TODO(phshah): Add overrides. private: ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. Profile* const profile_; base::WeakPtrFactory<ArcSharesheetBridge> weak_ptr_factory_{this}; }; } // namespace arc #endif // CHROME_BROWSER_ASH_ARC_SHARESHEET_ARC_SHARESHEET_BRIDGE_H_
java-tools/awe
awe-framework/awe-client-angular/src/main/resources/js/lib/highcharts/i18n/highcharts-lang.js
/** * General highcharts lang object * @author <NAME> */ global.HighchartsLocale = {};
SETTER2000/sailsinaction
assets/js/controllers/tutorialsDetailNewPageController.js
angular.module('brushfire').controller('tutorialsDetailNewPageController', ['$scope', '$http', 'toastr', function($scope, $http, toastr){ /* ____ _____ _ / __ \ | __ \ | | | | | |_ __ | |__) |___ _ __ __| | ___ _ __ | | | | '_ \ | _ // _ \ '_ \ / _` |/ _ \ '__| | |__| | | | | | | \ \ __/ | | | (_| | __/ | \____/|_| |_| |_| \_\___|_| |_|\__,_|\___|_| */ // set-up loading state $scope.tutorialDetailsNew = { loading: false }; $scope.me = window.SAILS_LOCALS.me; /* _____ ____ __ __ ______ _ | __ \ / __ \| \/ | | ____| | | | | | | | | | \ / | | |____ _____ _ __ | |_ ___ | | | | | | | |\/| | | __\ \ / / _ \ '_ \| __/ __| | |__| | |__| | | | | | |___\ V / __/ | | | |_\__ \ |_____/ \____/|_| |_| |______\_/ \___|_| |_|\__|___/ */ $scope.createTutorial = function() { $scope.tutorialDetailsNew.loading = true; $http.post('/tutorials', { title: $scope.tutorialDetailsNew.title, description: $scope.tutorialDetailsNew.description }) .then(function onSuccess(sailsResponse){ window.location='/tutorials/'+sailsResponse.data.id; }) .catch(function onError(sailsResponse){ console.error(sailsResponse); }) .finally(function eitherWay(){ $scope.tutorialDetailsNew.loading = false; }); }; }]);
mulesoft/amf
amf-cli/shared/src/test/scala/amf/resolution/ExtensionResolutionTest.scala
package amf.resolution import amf.core.client.scala.config.RenderOptions import amf.core.internal.remote.{AmfJsonHint, Raml10, Raml10YamlHint} import scala.concurrent.ExecutionContext class ExtensionResolutionTest extends ResolutionTest { override implicit val executionContext: ExecutionContext = ExecutionContext.Implicits.global val basePath = "amf-cli/shared/src/test/resources/resolution/extension/" test("Extension with annotations to Raml") { cycle("input.raml", "output.raml", Raml10YamlHint, target = Raml10YamlHint, directory = s"${basePath}annotations/") } test("Extension basic to Raml") { cycle("input.raml", "output.raml", Raml10YamlHint, target = Raml10YamlHint, directory = s"${basePath}basic/") } test("Extension with traits to Raml") { cycle("input.raml", "output.raml", Raml10YamlHint, target = Raml10YamlHint, directory = s"${basePath}traits/") } multiGoldenTest("Extension with traits to Amf", "output.%s") { config => cycle( "input.raml", config.golden, Raml10YamlHint, target = AmfJsonHint, directory = s"${basePath}traits/", renderOptions = Some(config.renderOptions), transformWith = Some(Raml10) ) } test("Extension chain to Raml") { cycle("input.raml", "output.raml", Raml10YamlHint, target = Raml10YamlHint, directory = s"${basePath}chain/") } test("Extension with example to Raml") { cycle("input.raml", "output.raml", Raml10YamlHint, target = Raml10YamlHint, directory = s"${basePath}example/") } multiGoldenTest("Trait should be applied to all operations that inherit from it", "output.%s") { config => cycle( "extension.raml", config.golden, Raml10YamlHint, target = AmfJsonHint, directory = s"${basePath}operation/", renderOptions = Some(config.renderOptions), transformWith = Some(Raml10) ) } override def defaultRenderOptions: RenderOptions = RenderOptions().withSourceMaps.withPrettyPrint }
mikolajgucki/ae-engine
studio/plugins/file/src/main/java/com/andcreations/ae/studio/plugins/file/FileAdapter.java
package com.andcreations.ae.studio.plugins.file; import java.io.File; import java.util.List; /** * The abstract file listener which does nothing. * * @author <NAME> */ public abstract class FileAdapter implements FileListener { /** */ @Override public void fileCreated(File file) { } /** */ @Override public void fileChanged(File file) { } /** */ @Override public void fileIssuesChanged(File file,List<FileIssue> issues) { } /** */ @Override public void fileDeleted(File file) { } /** */ @Override public void dirCreated(File dir) { } /** */ @Override public void dirDeleted(File dir) { } /** */ @Override public void fileRenamed(File src,File dst) { } }
aitoehigie/britecore_flask
venv/lib/python3.6/site-packages/pylint/test/functional/too_many_ancestors.py
<reponame>aitoehigie/britecore_flask # pylint: disable=missing-docstring, too-few-public-methods, useless-object-inheritance class Aaaa(object): pass class Bbbb(object): pass class Cccc(object): pass class Dddd(object): pass class Eeee(object): pass class Ffff(object): pass class Gggg(object): pass class Hhhh(object): pass class Iiii(Aaaa, Bbbb, Cccc, Dddd, Eeee, Ffff, Gggg, Hhhh): # [too-many-ancestors] pass class Jjjj(Iiii): # [too-many-ancestors] pass
NCAR/sage-gateway-archive
src/main/java/sgf/gateway/web/controllers/security/ConfirmAccountController.java
package sgf.gateway.web.controllers.security; import org.safehaus.uuid.UUID; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import sgf.gateway.service.security.AccountService; @Controller public class ConfirmAccountController { private final AccountService accountService; private String loginForm; public ConfirmAccountController(final AccountService accountService) { this.accountService = accountService; } @ModelAttribute("command") public ConfirmAccountCommand setupCommand() { //Create form backing object ConfirmAccountCommand command = new ConfirmAccountCommand(); return command; } @RequestMapping(value = "/ac/guest/secure/confirmAccount") protected ModelAndView handle(@ModelAttribute("command") ConfirmAccountCommand command) throws Exception { UUID identifier = command.getIdentifier(); accountService.confirmRegistration(identifier); ModelAndView modelAndView = new ModelAndView("/ac/guest/secure/registration/confirmAccount"); modelAndView.addObject("loginForm", this.loginForm); return modelAndView; } public void setLoginForm(String loginForm) { this.loginForm = loginForm; } }
anhtu1197/WebSocketProject
src/main/java/com/myself/nettychat/common/ssl/StreamReader.java
package com.myself.nettychat.common.ssl; import java.io.InputStream; public class StreamReader { public String toByteArray(InputStream fin) { int i = -1; StringBuilder buf = new StringBuilder(); try{ while((i=fin.read())!=-1){ if(buf.length()>0) buf.append(","); buf.append("(byte)"); buf.append(i); } }catch(Throwable e){ ; } return buf.toString(); } }
sdace/United-I-Stand
src/Events/upgrade_unlocked_event.hpp
<filename>src/Events/upgrade_unlocked_event.hpp<gh_stars>0 #pragma once #include "ECS/Components/upgrade_component.hpp" class UpgradeUnlockedEvent { public: UpgradeUnlockedEvent(UpgradeType upgrade_type) : upgrade_type(upgrade_type) {} UpgradeType upgrade_type; };
LLcat1217/arangodb
tests/Replication2/Helper/ModelChecker/Actors.h
<gh_stars>0 //////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2021-2021 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author <NAME> //////////////////////////////////////////////////////////////////////////////// #pragma once #include <boost/container_hash/hash.hpp> #include "Replication2/ReplicatedLog/LogCommon.h" #include "Replication2/ReplicatedState/AgencySpecification.h" #include "Replication2/ReplicatedLog/SupervisionAction.h" #include "Replication2/ReplicatedState/SupervisionAction.h" #include "Replication2/ReplicatedLog/ParticipantsHealth.h" #include "Replication2/Helper/ModelChecker/AgencyState.h" #include "Replication2/Helper/ModelChecker/AgencyTransitions.h" namespace arangodb::test { struct EmptyInternalState { friend auto operator==(EmptyInternalState const& lhs, EmptyInternalState const& rhs) noexcept -> bool { return true; } friend auto operator<<(std::ostream& os, EmptyInternalState const&) noexcept -> std::ostream& { return os; } friend auto hash_value(EmptyInternalState const& i) noexcept -> std::size_t { return 0; } }; template<typename Derived, typename InternalStateType = EmptyInternalState> struct ActorBase { using InternalState = InternalStateType; auto expand(AgencyState const& s, InternalState const& i) -> std::vector<std::tuple<AgencyTransition, AgencyState, InternalState>> { auto result = std::vector<std::tuple<AgencyTransition, AgencyState, InternalState>>{}; auto actions = reinterpret_cast<Derived const&>(*this).step(s); for (auto& action : actions) { auto newState = s; std::visit([&](auto& action) { action.apply(newState); }, action); result.emplace_back(std::move(action), std::move(newState), InternalState{}); } return result; } }; struct OnceInternalState { bool wasTriggered = false; friend auto operator==(OnceInternalState const& lhs, OnceInternalState const& rhs) noexcept -> bool = default; friend auto operator<<(std::ostream& os, OnceInternalState const& s) noexcept -> std::ostream& { return os << "was triggered = " << std::boolalpha << s.wasTriggered; } friend auto hash_value(OnceInternalState const& i) noexcept -> std::size_t { return boost::hash_value(i.wasTriggered); } }; template<typename Derived> struct OnceActorBase { using InternalState = OnceInternalState; auto expand(AgencyState const& s, InternalState const& i) -> std::vector<std::tuple<AgencyTransition, AgencyState, InternalState>> { if (i.wasTriggered) { return {}; } auto result = std::vector<std::tuple<AgencyTransition, AgencyState, InternalState>>{}; auto actions = reinterpret_cast<Derived const&>(*this).step(s); for (auto& action : actions) { auto newState = s; std::visit([&](auto& action) { action.apply(newState); }, action); result.emplace_back(std::move(action), std::move(newState), InternalState{.wasTriggered = true}); } return result; } }; struct SupervisionActor : ActorBase<SupervisionActor> { static auto stepReplicatedState(AgencyState const& agency) -> std::optional<AgencyTransition>; static auto stepReplicatedLog(AgencyState const& agency) -> std::optional<AgencyTransition>; auto step(AgencyState const& agency) const -> std::vector<AgencyTransition>; }; struct DBServerActor : ActorBase<DBServerActor> { explicit DBServerActor(replication2::ParticipantId name); [[nodiscard]] auto stepReplicatedState(AgencyState const& agency) const -> std::optional<AgencyTransition>; auto stepReplicatedLogReportTerm(AgencyState const& agency) const -> std::optional<AgencyTransition>; auto stepReplicatedLogLeaderCommit(AgencyState const& agency) const -> std::optional<AgencyTransition>; auto step(AgencyState const& agency) const -> std::vector<AgencyTransition>; replication2::ParticipantId name; }; struct KillLeaderActor : ActorBase<KillLeaderActor> { auto step(AgencyState const& agency) const -> std::vector<AgencyTransition>; }; struct KillServerActor : ActorBase<KillServerActor> { explicit KillServerActor(replication2::ParticipantId name); auto step(AgencyState const& agency) const -> std::vector<AgencyTransition>; replication2::ParticipantId name; }; struct KillAnyServerActor { struct InternalState { bool wasKilled = false; friend auto operator==(InternalState const& lhs, InternalState const& rhs) noexcept -> bool = default; friend auto operator<<(std::ostream& os, InternalState const& s) noexcept -> std::ostream& { return os << "was killed = " << std::boolalpha << s.wasKilled; } friend auto hash_value(InternalState const& i) noexcept -> std::size_t { return boost::hash_value(i.wasKilled); } }; auto expand(AgencyState const& s, InternalState const& i) -> std::vector<std::tuple<AgencyTransition, AgencyState, InternalState>>; }; struct ReplaceAnyServerActor : OnceActorBase<ReplaceAnyServerActor> { explicit ReplaceAnyServerActor(replication2::ParticipantId newServer); auto step(AgencyState const& agency) const -> std::vector<AgencyTransition>; replication2::ParticipantId newServer; }; struct ReplaceSpecificServerActor : OnceActorBase<ReplaceSpecificServerActor> { explicit ReplaceSpecificServerActor(replication2::ParticipantId oldServer, replication2::ParticipantId newServer); auto step(AgencyState const& agency) const -> std::vector<AgencyTransition>; replication2::ParticipantId oldServer; replication2::ParticipantId newServer; }; } // namespace arangodb::test
travisbrown/dotty-experiments
dotty-cats/kernel-laws/src/main/scala/io/circe/cats/kernel/laws/SemilatticeLaws.scala
<reponame>travisbrown/dotty-experiments<filename>dotty-cats/kernel-laws/src/main/scala/io/circe/cats/kernel/laws/SemilatticeLaws.scala package io.circe.cats.kernel.laws import io.circe.cats.kernel.Semilattice trait SemilatticeLaws[A] given Semilattice[A] extends CommutativeSemigroupLaws[A] with BandLaws[A] object SemilatticeLaws { def apply[A] given (A: Semilattice[A]): SemilatticeLaws[A] = new SemilatticeLaws[A] with CommutativeSemigroupLaws[A] with BandLaws[A] with SemigroupLaws[A] }
Files-com/files-sdk-python
tests/test_invoice_line_item.py
import unittest import inspect import files_sdk from tests.base import TestBase from files_sdk.models import InvoiceLineItem from files_sdk import invoice_line_item class InvoiceLineItemTest(TestBase): pass # Instance Methods # Static Methods if __name__ == '__main__': unittest.main()
ita-social-projects/horondi_client_fe
src/redux/cart/tests/cart.sagas.test.js
import { expectSaga } from 'redux-saga-test-plan'; import * as matchers from 'redux-saga-test-plan/matchers'; import { handleCartLoad, handleAddCartItem, handleRemoveCartItem } from '../cart.sagas'; import { SET_CART } from '../cart.types'; import { getFromLocalStorage, setToLocalStorage } from '../../../services/local-storage.service'; import { addItemToCart, removeItemFromCart } from '../cart.actions'; import { cartKey } from '../../../configs'; describe('Cart saga', () => { let products; let product; beforeEach(() => { product = { _id: 3, name: 'Orange', selectedSize: 'L' }; products = [ { _id: 1, name: 'Pumpkin', selectedSize: 'M' }, { _id: 2, name: 'Cherry', selectedSize: 'S' } ]; setToLocalStorage(cartKey, products); }); it.skip('fetching cart items from local storage and set to redux store', () => expectSaga(handleCartLoad) .provide([[matchers.call.fn(getFromLocalStorage), products]]) .put({ type: SET_CART, payload: products }) .run()); it.skip('fetching cart items from local storage and add new one', () => { const productToCart = addItemToCart(product); return expectSaga(handleAddCartItem, productToCart) .provide([[matchers.call.fn(getFromLocalStorage), products]]) .put({ type: SET_CART, payload: [...products, product] }) .run(); }); it.skip('if product already in cart nothing changes', () => { const productToCart = addItemToCart(products[0]); return expectSaga(handleAddCartItem, productToCart) .provide([[matchers.call.fn(getFromLocalStorage), products]]) .put({ type: SET_CART, payload: products }) .run(); }); it.skip('should to remove product from cart by id', () => { const productToRemove = removeItemFromCart(products[0]); return expectSaga(handleRemoveCartItem, productToRemove) .provide([[matchers.call.fn(getFromLocalStorage), products]]) .put({ type: SET_CART, payload: [products[1]] }) .run(); }); it.skip('also checks the size of products before removal', () => { const fakeItems = [ { _id: 1, name: 'Pumpkin', selectedSize: 'M' }, { _id: 1, name: 'Pumpkin', selectedSize: 'L' } ]; setToLocalStorage(cartKey, fakeItems); const productToRemove = removeItemFromCart(fakeItems[0]); return expectSaga(handleRemoveCartItem, productToRemove) .provide([[matchers.call.fn(getFromLocalStorage), fakeItems]]) .put({ type: SET_CART, payload: [fakeItems[1]] }) .run(); }); });
zjukiita/projectElectron
src/components/ModalDev/index.js
import React, { useEffect, useState } from 'react'; import MoviesInfo from '../MoviesInfo'; import api from '../../services/api'; import { useFormik } from 'formik'; import * as Yup from 'yup'; import { Modaal, Container, Close, Button, Box, Label, Buttoon } from './styles'; const Modal = ({ id = 'mod', onClose = () => { }, selectedMovie, onUpdate = () => { } }) => { const [edit, setEdit] = useState(false); const [movie, setMovie] = useState(selectedMovie); useEffect(() => { setMovie(selectedMovie); }, [selectedMovie]); const handleOutsideClick = (e) => { if (e.target.id === id) onClose(); }; const formik = useFormik({ initialValues: { nome: movie.nome || '', imagem: movie.imagem || '', sinopse: movie.sinopse || '', duracao: movie.duracao || '', link: movie.link || '', trailer: movie.trailer || '', avaliacao: movie.avaliacao || '', anoDeLancamento: movie.anoDeLancamento || '', categoria: movie.categoria || '', classificacao: movie.classificacao || '', }, enableReinitialize: true, validationSchema: Yup.object({ nome: Yup.string().required('Obrigatório'), imagem: Yup.string().required('Obrigatório'), sinopse: Yup.string().required('Obrigatório'), duracao: Yup.string().required('Obrigatório'), link: Yup.string().required('Obrigatório'), trailer: Yup.string().required('Obrigatório'), avaliacao: Yup.string().required('Obrigatório'), anoDeLancamento: Yup.string().required('Obrigatório'), categoria: Yup.string().required('Obrigatório'), classificacao: Yup.string().required('Obrigatório'), }), onSubmit: async (values) => { try { await api.put(`/filmes/${selectedMovie.id}`, values); setMovie({ id: selectedMovie.id, ...values }); onUpdate(); onClose(); // alert(JSON.stringify(values, null, 2)); } catch (error) { console.log('erro') } setEdit(false); } }) return ( <div> <Modaal id={id} className="mod" onClick={handleOutsideClick} > <Container> <Close onClick={onClose} /> {!edit ? ( <div> <MoviesInfo movie={movie} /> <Button onClick={() => { setEdit(true) }} >Editar</Button> </div> ) : ( <div style={{ display: "flex", color: "#fff", justifyContent: "center", }} > <form onSubmit={formik.handleSubmit}> <div style={{ display: "flex", flexDirection: "column", }}> <Label htmlFor="nome">Nome</Label> <Box id="nome" type="text" {...formik.getFieldProps('nome')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="imagem">Imagem</Label> <Box id="imagem" type="text" {...formik.getFieldProps('imagem')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="sinopse">Sinopse</Label> <Box id="sinopse" type="text" {...formik.getFieldProps('sinopse')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="duracao">Duração</Label> <Box id="duracao" type="text" {...formik.getFieldProps('duracao')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="link">Link</Label> <Box id="link" type="text" {...formik.getFieldProps('link')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="trailer">Trailer</Label> <Box id="trailer" type="text" {...formik.getFieldProps('trailer')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="avaliacao">Avaliação</Label> <Box id="avaliacao" type="text" {...formik.getFieldProps('avaliacao')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="anoDeLancamento">Lançamento</Label> <Box id="anoDeLancamento" type="text" {...formik.getFieldProps('anoDeLancamento')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="categoria">Categoria</Label> <Box id="categoria" type="text" {...formik.getFieldProps('categoria')} /> </div> <div style={{ display: "flex", flexDirection: "column" }}> <Label htmlFor="classificacao">Classificação</Label> <Box id="classificacao" type="text" {...formik.getFieldProps('classificacao')} /> </div> <Buttoon type="submit" >Enviar</Buttoon> </form> </div> )} </Container> </Modaal> </div> ); }; export default Modal;
quinnrong94/HugeCTR
HugeCTR/pybind/metrics_wrapper.hpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <HugeCTR/include/metrics.hpp> namespace HugeCTR { namespace python_lib { void MetricsPybind(pybind11::module& m) { pybind11::enum_<HugeCTR::metrics::RawType>(m, "MetricsRawType") .value("Loss", HugeCTR::metrics::RawType::Loss) .value("Pred", HugeCTR::metrics::RawType::Pred) .value("Label", HugeCTR::metrics::RawType::Label) .export_values(); pybind11::enum_<HugeCTR::metrics::Type>(m, "MetricsType") .value("AUC", HugeCTR::metrics::Type::AUC) .value("AverageLoss", HugeCTR::metrics::Type::AverageLoss) .export_values(); } } // namespace python_lib } // namespace HugeCTR
umts/screaming-dinosaur
spec/controllers/assignments_controller_spec.rb
<reponame>umts/screaming-dinosaur<filename>spec/controllers/assignments_controller_spec.rb # frozen_string_literal: true RSpec.describe AssignmentsController do let(:roster) { create :roster } describe 'POST #create' do subject :submit do post :create, params: { roster_id: roster, assignment: attributes } end let(:user) { roster_user(roster) } let :attributes do { start_date: Time.zone.today, end_date: Date.tomorrow, user_id: user.id, roster_id: roster.id } end context 'when you are an admin in roster' do before { when_current_user_is roster_admin(roster) } context 'when there are no errors' do it 'creates an assignment' do submit expect(Assignment.count).to be 1 end it 'sends an email to the new owner of the assignment' do assignment = build :assignment allow(Assignment).to receive(:new).and_return(assignment) allow(assignment).to receive(:notify) submit expect(assignment).to have_received(:notify) end end context 'when there are errors' do before do # Guaranteed to not be a user with this ID, # but will pass param validation in the controller. attributes[:user_id] = User.maximum(:id) + 1 end it 'does not create assignment' do submit expect(Assignment.all).to be_empty end it 'gives errors' do submit expect(flash[:errors]).not_to be_empty end it 'redirects back' do expect { submit }.to redirect_back end end end context 'when you are not admin' do before { when_current_user_is user } context 'when creating assignment belonging to self' do it 'creates the assignment' do expect { submit }.to change(Assignment, :count).by 1 end end context 'when creating assignment not belonging to self' do before { attributes[:user_id] = user.id + 1 } it 'does not create the assignment' do expect { submit }.not_to change(Assignment, :count) end it 'gives errors' do expect { submit }.to redirect_back end it 'redirects back' do submit expect(flash[:errors]).not_to be_empty end end end end describe 'DELETE #destroy' do subject :submit do delete :destroy, params: { roster_id: assignment.roster.id, id: assignment.id } end let(:assignment) { create :assignment } before do when_current_user_is :whoever end it 'finds the correct assignment' do submit expect(assigns.fetch(:assignment)).to eql assignment end it 'destroys the assignment' do allow(Assignment).to receive(:includes).and_return(Assignment) allow(Assignment).to receive(:find).and_return(assignment) allow(assignment).to receive(:destroy) submit expect(assignment).to have_received(:destroy) end it 'sends a notification to the owner of the assignment' do allow(Assignment).to receive(:includes).and_return(Assignment) allow(Assignment).to receive(:find).and_return(assignment) allow(assignment).to receive(:notify) submit expect(assignment).to have_received(:notify) end end describe 'GET #edit' do subject :submit do get :edit, params: { roster_id: roster.id, id: assignment.id } end let(:assignment) { create :assignment } before do when_current_user_is :whoever end it 'finds the correct assignment' do submit expect(assigns.fetch(:assignment)).to eql assignment end it 'populates a users variable of all users' do user1 = roster_user roster user2 = roster_user roster user3 = roster_user roster submit expect(assigns.fetch(:users)).to include user1, user2, user3 end it 'renders the edit template' do submit expect(response).to render_template :edit end end describe 'POST #generate_rotation' do subject :submit do post :generate_rotation, params: { roster_id: roster.id, start_date: Time.zone.today.to_s(:db), end_date: Date.tomorrow.to_s(:db), user_ids: user_ids, starting_user_id: starting_user_id } end let(:user_ids) { Array.new(3) { roster_user(roster).id.to_s } } let(:starting_user_id) { user_ids[1] } let(:assignment) { create(:assignment) } before do when_current_user_is :whoever end context 'when you are an admin in roster' do before { when_current_user_is roster_admin(roster) } it 'calls Roster#generate_assignments with the given arguments' do allow(Roster).to receive(:find_by).and_return(roster) allow(roster).to receive(:generate_assignments).and_return [] submit expect(roster).to have_received(:generate_assignments) .with(user_ids, Time.zone.today, Date.tomorrow, starting_user_id) end it 'notifies the new assignment holders' do allow(Roster).to receive(:find_by).and_return(roster) allow(roster).to receive(:generate_assignments).and_return [assignment] allow(assignment).to receive :notify submit expect(assignment).to have_received :notify end it 'has a flash message' do submit expect(flash[:message]).not_to be_empty end it 'redirects to the calendar with the start date given' do submit expect(response) .to redirect_to roster_assignments_path(date: Time.zone.today) end context 'when the starting user is not in the selected users' do let(:starting_user_id) { roster_user(roster).id } it 'warns that the starting user is not in the selected users' do submit expect(flash[:errors]).not_to be_empty end it 'redirects back' do expect { submit }.to redirect_back end end end context 'when you are an admin, but not in roster' do before { when_current_user_is roster_admin } it 'returns a 401' do submit expect(response).to have_http_status :unauthorized end end context 'when you are not admin' do before { when_current_user_is :whoever } it 'returns a 401' do submit expect(response).to have_http_status :unauthorized end end end describe 'GET #index' do subject :submit do get :index, params: { roster_id: roster.id } end context 'with a user_id in session' do let(:user) { roster_user(roster) } let! :old_assignment do create :assignment, user: user, roster: roster, start_date: 1.month.ago.to_date, end_date: 3.weeks.ago.to_date end let! :new_assignment do create :assignment, user: user, roster: roster, start_date: 1.month.since.to_date, end_date: 5.weeks.since.to_date end before { when_current_user_is user } it 'assigns the correct current user' do submit expect(assigns.fetch(:current_user)).to eql user end it 'populates assignments including upcoming assignments' do submit expect(assigns.fetch(:assignments)).to include new_assignment end it 'populates assignments excluding upcoming assignments' do submit expect(assigns.fetch(:assignments)).not_to include old_assignment end it 'populates the current assignment' do assignment = create :assignment allow(Assignment).to receive(:current).and_return assignment submit expect(assigns.fetch(:current_assignment)).to eql assignment end it 'uses Assignment.current to populate the current assignment' do allow(Assignment).to receive(:current) submit expect(Assignment).to have_received(:current) end it 'includes the switchover hour as a variable' do stub_const('CONFIG', { switchover_hour: 12 }) submit expect(assigns.fetch(:switchover_hour)).to be 12 end it 'includes a variable of the fallback user' do fallback = create :user roster.update(fallback_user_id: fallback.id) submit expect(assigns.fetch(:fallback_user)).to eql fallback end it 'renders the correct template' do submit expect(response).to render_template :index end end context 'with fcIdNumber in the request' do before { request.env['fcIdNumber'] = '<EMAIL>' } context 'when that user exists' do let(:user) { create :user } before { request.env['fcIdNumber'] = user.spire } it 'assigns the correct current user' do submit expect(assigns.fetch(:current_user)).to eql user end it 'renders the correct template' do submit expect(response).to render_template :index end end context 'when that user does not exist' do it 'redirects to unauthenticated sessions path' do submit expect(response).to redirect_to unauthenticated_session_path end end end end describe 'GET #new' do subject :submit do get :new, params: { roster_id: roster.id, date: date } end let(:date) { Time.zone.today } before { when_current_user_is :whoever } it 'passes the date parameter through as a start_date variable' do submit expect(assigns.fetch(:start_date)).to eql date end it 'populates an end_date instance variable 6 days after start_date' do submit expect(assigns.fetch(:end_date)).to eql(date + 6.days) end it 'populates a users variable containing all the users' do user1 = roster_user roster user2 = roster_user roster user3 = roster_user roster submit expect(assigns.fetch(:users)).to include user1, user2, user3 end it 'renders the new template' do submit expect(response).to render_template :new end end describe 'GET #rotation_generator' do subject :submit do get :rotation_generator, params: { roster_id: roster.id } end context 'when you are an admin in roster' do before { when_current_user_is roster_admin(roster) } it 'sets the users instance variable' do submit expect(assigns.fetch(:users)).to include(*roster.users) end it 'uses the next rotation start date' do allow(Assignment).to receive(:next_rotation_start_date) submit expect(Assignment).to have_received(:next_rotation_start_date) end it 'sets the start date instance variable' do allow(Assignment).to receive(:next_rotation_start_date).and_return 'whatever' submit expect(assigns.fetch(:start_date)).to eql 'whatever' end it 'renders the rotation_generator template' do submit expect(response).to render_template :rotation_generator end end context 'when you are an admin, but not in the roster' do before { when_current_user_is roster_admin } it 'returns a 401' do submit expect(response).to have_http_status :unauthorized end end context 'when you are not an admin' do before { when_current_user_is :whoever } it 'returns a 401' do submit expect(response).to have_http_status :unauthorized end end end describe 'POST #update' do subject :submit do post :update, params: { id: assignment.id, assignment: changes, roster_id: assignment.roster.id } end let(:assignment) { create :assignment } let(:user) { roster_user(assignment.roster) } let(:changes) { { user_id: user.id } } context 'when you are an admin in the roster' do let(:admin) { roster_admin(assignment.roster) } before { when_current_user_is admin } it 'updates the assignment' do submit expect(assignment.reload.user).to eql user end context 'when the owner is being changed' do before do allow(Assignment).to receive(:includes).and_return(Assignment) allow(Assignment).to receive(:find).and_return(assignment) allow(assignment).to receive(:notify) end it 'notifies the owner of the new assignment' do submit expect(assignment).to have_received(:notify) .with(:owner, of: :new_assignment, by: admin) end it 'notifies the owner of the deleted assignment' do previous_user = assignment.user submit expect(assignment).to have_received(:notify) .with(previous_user, of: :deleted_assignment, by: admin) end end context 'when the owner is not being changed' do let(:changes) { { user_id: assignment.user_id } } before do allow(Assignment).to receive(:includes).and_return(Assignment) allow(Assignment).to receive(:find).and_return(assignment) allow(assignment).to receive(:notify) end it 'notifies the owner of the changed assignment' do submit expect(assignment).to have_received(:notify) .with(:owner, of: :changed_assignment, by: admin) end end context 'with errors' do let(:changes) { { user_id: User.maximum(:id) + 1 } } it 'does not update the assignment' do submit expect(assignment.reload.user).not_to eql user end it 'displays errors' do submit expect(flash[:errors]).not_to be_empty end it ' redirects back' do expect { submit }.to redirect_back end end end context 'when you are updating your own assignment' do before { when_current_user_is user } context 'when the updated assignment will belong to you' do it 'updates the assignment' do submit expect(assignment.reload.user).to eql user end end context 'when the updated assignment will not belong to you' do let(:changes) { { user_id: user.id + 1 } } it 'does not update the assignment' do submit expect(assignment.reload.user).not_to eql user end it 'displays errors' do submit expect(flash[:errors]).not_to be_empty end it 'redirects back' do expect { submit }.to redirect_back end end end end describe 'GET #feed' do let(:roster) { create :roster } let(:user) { create :user, rosters: [roster] } context 'when the user has a valid access token' do let :submit do get :feed, params: { format: 'ics', token: user.calendar_access_token, roster: roster.name } end it 'allows the request' do submit expect(response).to have_http_status :ok end it 'is a calendar file' do submit expect(response.media_type).to eq('text/calendar') end end context 'when the user does not belong to roster' do let :submit do new_roster = create :roster get :feed, params: { format: 'ics', token: user.calendar_access_token, roster: new_roster.name } end it 'returns a 401' do submit expect(response).to have_http_status :unauthorized end end context 'when the user does not have a valid access token' do let :submit do get :feed, params: { format: 'ics', token: SecureRandom.hex, roster: roster.name } end it 'returns a 404' do submit expect(response).to have_http_status :not_found end end end end
qioalice/devola
core/view/id.go
<filename>core/view/id.go // Copyright © 2019. All rights reserved. // Author: <NAME>. // Contacts: <<EMAIL>>. // License: https://opensource.org/licenses/MIT package view // ID represents a RAW identifier of View. // // This type used only for readable format View ID representation. // In internal SDK parts View ID represents by its encoded format using // IDEnc type and IDConv to encode/decode operations. // // More info: IDEnc, IDConv type ID string // Predefined constants. const ( // Represents a nil View ID and an indicator of some error. CIDNil ID = "" ) // IsValid returns true only if vid is valid ID value. // // Valid readable View ID must contain more than 2 chars and don't starts // from double underscore (reserved for internal parts). func (id ID) IsValid() bool { return id != CIDNil && len(id) > 2 && id[:2] != "__" }
derrickbeining/codesplit-SSR-reduxRouter-app-boiler
src/components/pages/AboutPage.js
import React from 'react' const AboutPage = props => ( <h1>About Our Thing</h1> ) export default AboutPage
lyonsrob/gistofit
steroids-composer/GistOfIt/app/controllers/Feed.js
'use strict' function toArrayObj(array) { for (var i = 0; i < array.length; ++i) array[i] = {link: array[i]}; return array; } angular.module('gistOfItApp').controller('FeedCtrl', ['$scope', '$q', 'GistofitService', 'embedlyService', 'FeedService', function ($scope, $q, Gistofit, Embedly, Feed) { // Create a view var myView = new steroids.views.WebView("http://localhost/views/Article/article.html"); myView.preload(); // Prelaod for faster view transitions var createGistView = new steroids.views.WebView("views/Gist/add.html"); createGistView.preload(); // Prelaod for faster view transitions var feedURLs = [ 'http://feeds2.feedburner.com/Mashable', 'http://www.tmz.com/rss.xml', 'http://feeds.gawker.com/deadspin/full', 'http://feeds.gawker.com/gizmodo/full', 'http://feeds2.feedburner.com/businessinsider', 'http://feeds.feedburner.com/TechCrunch', 'http://rss.cnn.com/rss/cnn_topstories.rss', 'http://sports.espn.go.com/espn/rss/news' ]; $scope.setExtract = function(feed) { var url = feed.link; Gistofit.getExtract(url).then(function (response) { if (response.data == undefined || response.data == '') { Embedly.extract(url) .then(function(e){ Gistofit.setExtract(url, e.data); feed.extract = e.data; }, function(error) { console.log(error); }); } else { feed.extract = response.data; } feed.extract.video = feed.extract.embeds[0].html; }); } $scope.loadFeed=function(e){ Feed.parseFeed($scope.feedSrc).then(function(res){ $scope.loadButonText=angular.element(e.target).text(); $scope.feeds=res.data.responseData.feed.entries; }); } $scope.loadSearchFeed=function(){ Gistofit.searchTopUrls($scope.searchText).then(function(res){ $scope.loadButonText=angular.element().text(); $scope.feeds=toArrayObj(res.data); }); } $scope.loadAllFeeds=function(e){ $scope.feeds = []; var promises = []; for (var i = 0, len = feedURLs.length; i < len; i++) { Feed.parseFeed(feedURLs[i]).then(function(res){ //$scope.loadButonText=angular.element(e.target).text(); $scope.feeds.push.apply($scope.feeds, res.data.responseData.feed.entries); angular.forEach($scope.feeds,function(feed){ promises.push($scope.setExtract(feed)); }); $q.all(promises).then(function success(data){ //console.log($scope.feeds); // Should all be here }, function failure(err){ // Can handle this is we want }); }); } //shuffle($scope.feeds); } $scope.showArticle = function(article) { var message = { recipient: "articleView", article: article, } window.postMessage(message); var fastSlide = new steroids.Animation({ transition: "slideFromRight", duration: .2}); // Navigate to your view steroids.layers.push( { view: myView, animation: fastSlide , }); } $scope.showGistPrompt = function(feed) { var message = { recipient: "gistModalView", feed: feed } window.postMessage(message); steroids.modal.show(createGistView); } $scope.loadAllFeeds(); steroids.view.navigationBar.show("Feed"); }]); angular.module('gistOfItApp').factory('FeedService',['$http',function($http){ return { parseFeed : function(url){ return $http.jsonp('https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1&callback=JSON_CALLBACK&q=' + encodeURIComponent(url)); } } }]);
wiarlawd/google-enterprise-connector-manager
projects/connector-manager/source/javatests/com/google/enterprise/connector/instantiator/MockTraversalStateStore.java
// Copyright 2009 Google Inc. 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. // 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.google.enterprise.connector.instantiator; import com.google.enterprise.connector.persist.PersistentStore; import com.google.enterprise.connector.persist.StoreContext; import com.google.enterprise.connector.traversal.TraversalStateStore; class MockTraversalStateStore implements TraversalStateStore { private final PersistentStore stateStore; private final StoreContext storeContext; MockTraversalStateStore(PersistentStore stateStore, StoreContext storeContext) { this.stateStore = stateStore; this.storeContext = storeContext; } /** * Store traversal state. * * @param state a String representation of the state to store. * If null, any previous stored state is discarded. */ public void storeTraversalState(String state) { if (state == null) { stateStore.removeConnectorState(storeContext); } else { stateStore.storeConnectorState(storeContext, state); } } /** * Return a stored traversal state. * * @returns String representation of the stored state, or * null if no state is stored. */ public String getTraversalState() { return stateStore.getConnectorState(storeContext); } }
techlib/adminator
util/leases2csv.py
<gh_stars>1-10 #!/usr/bin/python3 -tt # -*- coding: utf-8 -*- import re from sys import argv, stdin, stdout, stderr, exit from datetime import datetime from getopt import gnu_getopt from ipaddress import ip_address, ip_network from struct import unpack from json import load def parse_leases(data): leases = {} data = data.replace('\n', '\v') for address, section in re.findall(r'lease ([0-9.]+) {(.*?)}', data): fields = dict([tuple(re.split('\s+', row.strip(' ;'), 1)) \ for row in section.split('\v') if len(row.strip()) > 0]) if 'uid' in fields: del fields['uid'] if 'starts' not in fields or 'ends' not in fields or 'hardware' not in fields: continue if fields.get('binding') != 'state active': continue hwaddr = fields['hardware'].split(' ')[1] ends = datetime.strptime(fields['ends'], '%w %Y/%m/%d %H:%M:%S') leases[address] = { 'address': address, 'hwaddr': hwaddr, 'expire': ends.strftime('%Y-%m-%d %H:%M:%S+00'), } return leases if __name__ == '__main__': import csv def do_convert(kea_conf, leases, postgres, **kwargs): with open(leases) as fp: leases = parse_leases(fp.read()) with open(kea_conf) as fp: kea = load(fp) subnets = [] for subnet in kea['Dhcp4']['subnet4']: subnets.append((subnet['id'], ip_network(subnet['subnet']))) def find_subnet_id(address): for subnet_id, subnet in subnets: if address in subnet: return str(subnet_id) print('No subnet for {}'.format(address), file=stderr) exit(1) for lease in leases.values(): lease['subnet_id'] = find_subnet_id(ip_address(lease['address'])) if postgres: for lease in leases.values(): address = ip_address(lease['address']).packed hwaddr = lease['hwaddr'].replace(':', '') lease.update({ 'address': unpack('!I', address)[0], 'hwaddr': r'\x' + hwaddr, }) w = csv.DictWriter(stdout, ['address', 'hwaddr', 'expire', 'subnet_id']) w.writerows(leases.values()) def do_help(*args, **kwargs): print('Usage: leases2csv.py [--kea-conf=kea.conf] [--leases=dhcpd.leases]') print('Generate CSV from the lease file with network numbers from kea.conf.') print('') print('OPTIONS:') print(' --help, -h Display this help.') print(' --version, -V Display version info.') print('') print(' --kea-conf, -k path Path to the KEA configuration file.') print(' --leases, -l path Path to the ISC DHCPd lease file.') print('') print(' --postgres, -P Use PostgreSQL-compatible output.') print('') print('Report bugs at <http://github.com/techlib/adminator>.') def do_version(*args, **kwargs): print('leases2csv.py (NTK) 1') # Parse command line arguments. opts, args = gnu_getopt(argv, 'hVk:l:P', ['help', 'version', 'kea-conf=', 'leases=', 'postgres']) action = do_convert kea_conf = 'kea.conf' leases = 'dhcpd.leases' postgres = False for k, v in opts: if k in ('--help', '-h'): action = do_help elif k in ('--version', '-V'): action = do_version elif k in ('--kea-conf', '-k'): kea_conf = v elif k in ('--leases', '-l'): leases = v elif k in ('--postgres', '-P'): postgres = True # Perform the selected action. action(kea_conf, leases, postgres) # vim:set sw=4 ts=4 et:
Zilig/GraDesignTest
src/main/java/completion/CompareModel/Sentence.java
<filename>src/main/java/completion/CompareModel/Sentence.java package completion.CompareModel; import java.io.File; /** * @authorE <NAME> * @authorC 关哲林 * @date 2022/4/25 20:17 * @Description TODO **/ public class Sentence { private final File file; private final String entityCode; private final String fileName; private final String headName; private int headIndex; private final String tailName; private final String entityName; private int entityIndex; private final int sort; //网页的排名[1,50] private final String value; public Sentence(File file, String entityCode, String fileName, String headName, int headIndex, String tailName, String entityName, int entityIndex, int sort, String value) { this.file = file; this.entityCode = entityCode; this.fileName = fileName; this.headName = headName; this.headIndex = headIndex; this.tailName = tailName; this.entityName = entityName; this.entityIndex = entityIndex; this.value = value; this.sort = sort; } }
chriskim06/go-sdk
profanity/option_test.go
/* Copyright (c) 2021 - Present. Blend Labs, Inc. All rights reserved Use of this source code is governed by a MIT license that can be found in the LICENSE file. */ package profanity import ( "testing" "github.com/blend/go-sdk/assert" ) func TestConfigOptions(t *testing.T) { assert := assert.New(t) p := &Profanity{} assert.False(p.Config.VerboseOrDefault()) OptVerbose(true)(p) assert.True(p.Config.VerboseOrDefault()) assert.False(p.Config.DebugOrDefault()) OptDebug(true)(p) assert.True(p.Config.DebugOrDefault()) assert.False(p.Config.ExitFirstOrDefault()) OptExitFirst(true)(p) assert.True(p.Config.ExitFirstOrDefault()) assert.Empty(p.Config.Root) OptRoot("../foo")(p) assert.Equal("../foo", p.Config.Root) assert.Equal(DefaultRulesFile, p.Config.RulesFileOrDefault()) OptRulesFile("my_rules.yml")(p) assert.Empty(p.Config.Files.Include) OptIncludeFiles("foo", "bar", "baz")(p) assert.Equal([]string{"foo", "bar", "baz"}, p.Config.Files.Include) assert.Empty(p.Config.Files.Exclude) OptExcludeFiles("foo", "bar", "baz")(p) assert.Equal([]string{"foo", "bar", "baz"}, p.Config.Files.Exclude) }
hancer/boa
packages/components/src/Label/parseFontSize.test.js
import { assert } from 'chai'; import parseFontSize from './parseFontSize'; describe('parseFontSize', () => { it('should parse number', () => { const result = parseFontSize(10); assert.strictEqual(result, 10); }); it('should parse string', () => { const result = parseFontSize('10.2'); assert.strictEqual(result, 10.2); }); it('should not parse anouther type', () => { const result = parseFontSize({ fontSize: 10 }); assert.strictEqual(result, undefined); }); });
vinayakpokharkar/aws-sdk-java
aws-java-sdk-gluedatabrew/src/main/java/com/amazonaws/services/gluedatabrew/model/PathOptions.java
<gh_stars>1-10 /* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.gluedatabrew.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Represents a set of options that define how DataBrew selects files for a given Amazon S3 path in a dataset. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/PathOptions" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PathOptions implements Serializable, Cloneable, StructuredPojo { /** * <p> * If provided, this structure defines a date range for matching Amazon S3 objects based on their LastModifiedDate * attribute in Amazon S3. * </p> */ private FilterExpression lastModifiedDateCondition; /** * <p> * If provided, this structure imposes a limit on a number of files that should be selected. * </p> */ private FilesLimit filesLimit; /** * <p> * A structure that maps names of parameters used in the Amazon S3 path of a dataset to their definitions. * </p> */ private java.util.Map<String, DatasetParameter> parameters; /** * <p> * If provided, this structure defines a date range for matching Amazon S3 objects based on their LastModifiedDate * attribute in Amazon S3. * </p> * * @param lastModifiedDateCondition * If provided, this structure defines a date range for matching Amazon S3 objects based on their * LastModifiedDate attribute in Amazon S3. */ public void setLastModifiedDateCondition(FilterExpression lastModifiedDateCondition) { this.lastModifiedDateCondition = lastModifiedDateCondition; } /** * <p> * If provided, this structure defines a date range for matching Amazon S3 objects based on their LastModifiedDate * attribute in Amazon S3. * </p> * * @return If provided, this structure defines a date range for matching Amazon S3 objects based on their * LastModifiedDate attribute in Amazon S3. */ public FilterExpression getLastModifiedDateCondition() { return this.lastModifiedDateCondition; } /** * <p> * If provided, this structure defines a date range for matching Amazon S3 objects based on their LastModifiedDate * attribute in Amazon S3. * </p> * * @param lastModifiedDateCondition * If provided, this structure defines a date range for matching Amazon S3 objects based on their * LastModifiedDate attribute in Amazon S3. * @return Returns a reference to this object so that method calls can be chained together. */ public PathOptions withLastModifiedDateCondition(FilterExpression lastModifiedDateCondition) { setLastModifiedDateCondition(lastModifiedDateCondition); return this; } /** * <p> * If provided, this structure imposes a limit on a number of files that should be selected. * </p> * * @param filesLimit * If provided, this structure imposes a limit on a number of files that should be selected. */ public void setFilesLimit(FilesLimit filesLimit) { this.filesLimit = filesLimit; } /** * <p> * If provided, this structure imposes a limit on a number of files that should be selected. * </p> * * @return If provided, this structure imposes a limit on a number of files that should be selected. */ public FilesLimit getFilesLimit() { return this.filesLimit; } /** * <p> * If provided, this structure imposes a limit on a number of files that should be selected. * </p> * * @param filesLimit * If provided, this structure imposes a limit on a number of files that should be selected. * @return Returns a reference to this object so that method calls can be chained together. */ public PathOptions withFilesLimit(FilesLimit filesLimit) { setFilesLimit(filesLimit); return this; } /** * <p> * A structure that maps names of parameters used in the Amazon S3 path of a dataset to their definitions. * </p> * * @return A structure that maps names of parameters used in the Amazon S3 path of a dataset to their definitions. */ public java.util.Map<String, DatasetParameter> getParameters() { return parameters; } /** * <p> * A structure that maps names of parameters used in the Amazon S3 path of a dataset to their definitions. * </p> * * @param parameters * A structure that maps names of parameters used in the Amazon S3 path of a dataset to their definitions. */ public void setParameters(java.util.Map<String, DatasetParameter> parameters) { this.parameters = parameters; } /** * <p> * A structure that maps names of parameters used in the Amazon S3 path of a dataset to their definitions. * </p> * * @param parameters * A structure that maps names of parameters used in the Amazon S3 path of a dataset to their definitions. * @return Returns a reference to this object so that method calls can be chained together. */ public PathOptions withParameters(java.util.Map<String, DatasetParameter> parameters) { setParameters(parameters); return this; } /** * Add a single Parameters entry * * @see PathOptions#withParameters * @returns a reference to this object so that method calls can be chained together. */ public PathOptions addParametersEntry(String key, DatasetParameter value) { if (null == this.parameters) { this.parameters = new java.util.HashMap<String, DatasetParameter>(); } if (this.parameters.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.parameters.put(key, value); return this; } /** * Removes all the entries added into Parameters. * * @return Returns a reference to this object so that method calls can be chained together. */ public PathOptions clearParametersEntries() { this.parameters = null; return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getLastModifiedDateCondition() != null) sb.append("LastModifiedDateCondition: ").append(getLastModifiedDateCondition()).append(","); if (getFilesLimit() != null) sb.append("FilesLimit: ").append(getFilesLimit()).append(","); if (getParameters() != null) sb.append("Parameters: ").append(getParameters()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PathOptions == false) return false; PathOptions other = (PathOptions) obj; if (other.getLastModifiedDateCondition() == null ^ this.getLastModifiedDateCondition() == null) return false; if (other.getLastModifiedDateCondition() != null && other.getLastModifiedDateCondition().equals(this.getLastModifiedDateCondition()) == false) return false; if (other.getFilesLimit() == null ^ this.getFilesLimit() == null) return false; if (other.getFilesLimit() != null && other.getFilesLimit().equals(this.getFilesLimit()) == false) return false; if (other.getParameters() == null ^ this.getParameters() == null) return false; if (other.getParameters() != null && other.getParameters().equals(this.getParameters()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getLastModifiedDateCondition() == null) ? 0 : getLastModifiedDateCondition().hashCode()); hashCode = prime * hashCode + ((getFilesLimit() == null) ? 0 : getFilesLimit().hashCode()); hashCode = prime * hashCode + ((getParameters() == null) ? 0 : getParameters().hashCode()); return hashCode; } @Override public PathOptions clone() { try { return (PathOptions) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.gluedatabrew.model.transform.PathOptionsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
MOUDDENEHamza/ENSEEIHT
1A/S6/TOB/E24/src/customer/DessertSwing.java
package customer; import javax.swing.*; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import general.GUI; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * La version swing des desserts proposés * @author <NAME> * */ public class DessertSwing { public MenuSwing menuSwing; public JFrame fenetre; private JLabel logo, footerLabel, dish1Label, dish2Label, dish3Label, dish4Label; private JPanel headLeft, headCenter, headRight, footer, dish1, dish2, dish3, dish4, desc1, desc2, desc3, desc4; private JButton bChoisir1, bChoisir2, bChoisir3, bChoisir4, bBack; public DessertSwing(MenuSwing menuSwing) { GUI MenuModel = new GUI(); this.menuSwing = menuSwing; String backmenu=""; String dess1=null, dess2=null, dess3="", dess4="", choose ="", dessert =""; String lg = menuSwing.getLangue(); String file = "data/langueEn.json"; JSONParser parser = new JSONParser(); try { if (lg.equals("fr")) { file = "data/langueFr.json"; } JSONArray lang = (JSONArray) parser.parse(new FileReader(file)); for (Object word : lang) { JSONObject msg = (JSONObject) word; backmenu = (String) msg.get("back_menu"); dess1 = (String) msg.get("dessert1"); dess2 = (String) msg.get("dessert2"); dess3 = (String) msg.get("dessert3"); dess4 = (String) msg.get("dessert4"); choose = (String) msg.get("choose"); dessert = (String) msg.get("menu3"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (NumberFormatException e) { System.out.print(true); } catch (Exception e) { } this.fenetre = MenuModel.createWindow("Menu", 1000, 800); this.fenetre.setExtendedState(this.fenetre.getExtendedState() | JFrame.MAXIMIZED_BOTH); //Maximiser automatiquement la fen�tre Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int width = screenSize.width; //1536 (delete later) int height = screenSize.height;//864 (delete later) int actual_height = height - 40 - 75; //La vraie hauteur de la fen�tre (ayant soustrait l'ent�te et le bas de page) //ENTETE this.headLeft = MenuModel.createPanel(0, 0, width * 176 / 1536, 40, new Color(211, 211, 211)); this.logo = MenuModel.createLabel("E24 Restaurant 2020", 10, 10, 120, 40); this.headLeft.add(logo); this.bBack = MenuModel.createButton(backmenu, 580, 5, 200, 30, Color.RED, Color.WHITE); this.bBack.addActionListener(new ActionBack()); this.fenetre.add(this.bBack); this.fenetre.add(this.headLeft); this.headCenter = MenuModel.createPanel(width * 176 / 1536, 0, width * 1024 / 1536, 40, new Color(211, 211, 211)); this.fenetre.add(this.headCenter); this.headRight = MenuModel.createPanel(width * 176 / 1536 + width * 1024 / 1536, 0, width * 336 / 1536, 40, new Color(211, 211, 211)); JLabel text = MenuModel.createLabel(dessert, 10, 10, 200, 40); this.headRight.add(text); this.fenetre.add(this.headRight); //BAS DE PAGE this.footer = MenuModel.createPanel(0, height * 725 / 864, width, 75, new Color(211, 211, 211)); this.footer.setLayout(new BorderLayout()); this.footerLabel = MenuModel.createLabel("E24 Restaurant 2020 ", 0, 0, 100, 50); // this.footer.add(this.SignOut, BorderLayout.NORTH); this.footer.add(this.footerLabel, BorderLayout.CENTER); this.fenetre.add(this.footer); int bWidth = width / 4 - width * 100 / 1536 + width * 65 / 1366; int bHeight = actual_height / 2 - height * 25 / 768; int widthDiff = width - width * 750 / 1366; this.bChoisir1 = MenuModel.createButton(choose, bWidth, bHeight, 100, 30, new Color(9, 128, 67), Color.WHITE); this.bChoisir1.addActionListener(new ActionChoose1()); this.fenetre.add(this.bChoisir1); this.bChoisir2 = MenuModel.createButton(choose, bWidth + widthDiff, bHeight, 100, 30, new Color(9, 128, 67), Color.WHITE); this.bChoisir2.addActionListener(new ActionChoose2()); this.fenetre.add(this.bChoisir2); this.bChoisir3 = MenuModel.createButton(choose, bWidth, bHeight + height * 290 / 768, 100, 30, new Color(9, 128, 67), Color.WHITE); this.bChoisir3.addActionListener(new ActionChoose3()); this.fenetre.add(this.bChoisir3); this.bChoisir4 = MenuModel.createButton(choose, bWidth + widthDiff, bHeight + height * 290 / 768, 100, 30, new Color(9, 128, 67), Color.WHITE); this.bChoisir4.addActionListener(new ActionChoose4()); this.fenetre.add(this.bChoisir4); //Ajouter le priemier DISH this.dish1 = MenuModel.createPanel(width * 250 / 1366, height * 50 / 768, 250, 220, null); //Lire,Redimonsionner puis ajouter une image � la premi�re partie ImageIcon image1 = new ImageIcon("pics/Le Fraisier.jpeg"); Image newImage1 = MenuModel.scaleImage(image1.getImage(), 250, 220); JLabel icon1 = new JLabel(new ImageIcon(newImage1), JLabel.CENTER); this.dish1.add(icon1); this.fenetre.add(this.dish1); this.desc1 = MenuModel.createPanel(width * 270 / 1366, height * 270 / 768, 200, 20, null); this.dish1Label = MenuModel.createLabel(dess1 +"("+this.menuSwing.getMenu().getMenuDessert().get(0).getPrixPlat()+"\u20AC)", width * 200 / 1366, height * 265 / 768, 100, 250); this.desc1.add(this.dish1Label); this.fenetre.add(this.desc1); this.dish2 = MenuModel.createPanel(width - width * 500 / 1366, height * 50 / 768, 250, 220, null); //Lire,Redimonsionner puis ajouter une image � la premi�re partie ImageIcon image2 = new ImageIcon("pics/Tiramisu.jpg"); Image newImage2 = MenuModel.scaleImage(image2.getImage(), 250, 220); JLabel icon2 = new JLabel(new ImageIcon(newImage2), JLabel.CENTER); this.dish2.add(icon2); this.fenetre.add(this.dish2); this.desc2 = MenuModel.createPanel(width * 260 / 1366 + widthDiff, height * 270 / 768, 200, 20, null); this.dish2Label = MenuModel.createLabel(dess2 +"("+this.menuSwing.getMenu().getMenuDessert().get(1).getPrixPlat()+"\u20AC)", width * 200 / 1366, height * 265 / 768, 100, 250); this.desc2.add(this.dish2Label); this.fenetre.add(this.desc2); this.dish3 = MenuModel.createPanel(width * 250 / 1366, height * 340 / 768, 250, 220, null); //Lire,Redimonsionner puis ajouter une image � la premi�re partie ImageIcon image3 = new ImageIcon("pics/Tarte Chocolat.jpg"); Image newImage3 = MenuModel.scaleImage(image3.getImage(), 250, 220); JLabel icon3 = new JLabel(new ImageIcon(newImage3), JLabel.CENTER); this.dish3.add(icon3); this.fenetre.add(this.dish3); this.desc3 = MenuModel.createPanel(width * 270 / 1366, height * 560 / 768, 200, 20, null); this.dish3Label = MenuModel.createLabel(dess3 +"("+this.menuSwing.getMenu().getMenuDessert().get(2).getPrixPlat()+"\u20AC)", width * 200 / 1366, height * 265 / 768, 100, 250); this.desc3.add(this.dish3Label); this.fenetre.add(this.desc3); this.dish4 = MenuModel.createPanel(width - width * 500 / 1366, height * 340 / 768, 250, 220, null); //Lire,Redimonsionner puis ajouter une image � la premi�re partie ImageIcon image4 = new ImageIcon("pics/Tarte Orange.jpg"); Image newImage4 = MenuModel.scaleImage(image4.getImage(), 250, 220); JLabel icon4 = new JLabel(new ImageIcon(newImage4), JLabel.CENTER); this.dish4.add(icon4); this.fenetre.add(this.dish4); this.desc4 = MenuModel.createPanel(width * 270 / 1366 + widthDiff, height * 560 / 768, 200, 20, null); this.dish4Label = MenuModel.createLabel(dess4 +"("+this.menuSwing.getMenu().getMenuDessert().get(3).getPrixPlat()+"\u20AC)", width * 200 / 1366, height * 265 / 768, 100, 250); this.desc4.add(this.dish4Label); this.fenetre.add(this.desc4); fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fenetre.setVisible(true); } public class ActionBack implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { fenetre.dispose(); JFrame previous = menuSwing.getFenetre(); previous.setVisible(true); } } public class ActionChoose1 implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { PlatResto plat1 = menuSwing.getMenu().getMenuDessert().get(0); menuSwing.listChoixDessert.add(plat1); menuSwing.getChoix().ajouterDessert(menuSwing.listChoixDessert); } } public class ActionChoose2 implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { PlatResto plat2 = menuSwing.getMenu().getMenuDessert().get(1); menuSwing.listChoixDessert.add(plat2); menuSwing.getChoix().ajouterDessert(menuSwing.listChoixDessert); } } public class ActionChoose3 implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { PlatResto plat3 = menuSwing.getMenu().getMenuDessert().get(2); menuSwing.listChoixDessert.add(plat3); menuSwing.getChoix().ajouterDessert(menuSwing.listChoixDessert); } } public class ActionChoose4 implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { PlatResto plat4 = menuSwing.getMenu().getMenuDessert().get(3); menuSwing.listChoixDessert.add(plat4); menuSwing.getChoix().ajouterDessert(menuSwing.listChoixDessert); } } }
ikajic/nengolib
nengolib/monkeypatch.py
import nengo from nengolib.network import Network from nengolib.connection import Connection from nengo import Network as NengoNetwork, Connection as NengoConnection __all__ = ['patch', 'unpatch'] def patch(network=True, connection=True): """Monkey-patches nengolib.Network and/or nengolib.Connection.""" if network: nengo.Network = Network if connection: nengo.Connection = Connection def unpatch(): """Resets the effect of patch().""" nengo.Network = NengoNetwork nengo.Connection = NengoConnection
harshp8l/deep-learning-lang-detection
data/train/scala/2f685898354f069cb7b6e0df7ebdebd1783961cbcont.scala
<gh_stars>10-100 package scala.lms.black import eval._ import repl._ import org.scalatest.BeforeAndAfter class TestCont extends TestSuite with BeforeAndAfter { val under = "cont_" before { clean() } def resume = """(begin (EM (EM (begin (define pending-thunks '()) (define old-base-apply base-apply) (set! base-apply (lambda (fa r k) (if (continuation? (car fa)) (let ((v (old-base-apply fa r (lambda (x) x)))) (set! pending-thunks (cons (lambda () (k v)) pending-thunks)) v) (old-base-apply fa r k)))) ))) (define resume! (lambda () (if (null? (EM (EM pending-thunks))) 'done (EM (EM (let ((thunk (car pending-thunks))) (set! pending-thunks (cdr pending-thunks)) (thunk))))))) )""" def pushy = """(EM (EM (begin (define old-base-apply base-apply) (set! base-apply (lambda (fa r k) (if (continuation? (car fa)) (k (old-base-apply fa r (lambda (x) x))) (old-base-apply fa r k)))) )))""" def dummy = """(EM (begin (define old-eval-var eval-var) (set! eval-var (lambda (e r k) (if (eq? 'dummy e) (begin (k 1) (k 2) (k 3)) (old-eval-var e r k)))) ))""" def make_ev(c: Boolean) = if (c) {s: String => ev(s.replace("lambda", "clambda"))} else ev(_) def test_resume(c: Boolean) = { val mev = make_ev(c) mev(resume) mev(dummy) assertResult(I(1)){ev("dummy")} assertResult(I(2)){ev("(resume!)")} assertResult(I(3)){ev("(resume!)")} assertResult(I(3)){ev("(resume!)")} // id_cont :( assertResult(S("done")){ev("(resume!)")} } test("resume continuations") { test_resume(false) } test("resume continuations (all compiled)") { test_resume(true) } def test_pushy(c: Boolean) = { val mev = make_ev(c) mev(pushy) mev(dummy) assertResult(I(3)){ev("dummy")} } test("pushy continuations") { test_pushy(false) } test("pushy continuations (all compiled)") { test_pushy(true) } }
Miridescen/BWT
Pods/Headers/Public/Meiqia/MQBotMenuAnswerCellModel.h
// // MQBotMenuAnswerCellModel.h // Meiqia-SDK-Demo // // Created by <NAME> on 16/8/24. // Copyright © 2016年 Meiqia. All rights reserved. // #import <Foundation/Foundation.h> #import "MQCellModelProtocol.h" @class MQBotAnswerMessage; @interface MQBotMenuAnswerCellModel : NSObject <MQCellModelProtocol> @property (nonatomic, strong) NSArray *menus; @property (nonatomic, copy) NSString *menuTitle; @property (nonatomic, copy) NSString *menuFootnote; @property (nonatomic, copy) NSString *content; @property (nonatomic, assign) BOOL isEvaluated; @property (nonatomic, copy) NSString *messageId; @property (nonatomic, strong) UIImage *avatarImage; @property (nonatomic, copy) CGFloat(^provoideCellHeight)(void); @property (nonatomic, copy) void(^avatarLoaded)(UIImage *); - (instancetype)initCellModelWithMessage:(MQBotAnswerMessage *)message cellWidth:(CGFloat)cellWidth delegate:(id<MQCellModelDelegate>)delegator; @end
ilan-pinto/mercury
sd-base/customer-credit-rating/model/src/main/java/com/redhat/mercury/customercreditrating/model/BQAlertsRetrieveOutputModel.java
<gh_stars>0 /* * Customer Credit Rating * This service domain maintains and administers the bank's credit assessment for customers. * * OpenAPI spec version: 2.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.redhat.mercury.customercreditrating.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.v3.oas.annotations.media.Schema; import java.io.IOException; /** * BQAlertsRetrieveOutputModel */ @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2021-06-03T16:36:13.702891+02:00[Europe/Madrid]") public class BQAlertsRetrieveOutputModel { @SerializedName("customerCreditRatingStateInstanceRecord") private Object customerCreditRatingStateInstanceRecord = null; @SerializedName("alertsInstanceRecord") private Object alertsInstanceRecord = null; @SerializedName("alertsRetrieveActionTaskReference") private String alertsRetrieveActionTaskReference = null; @SerializedName("alertsRetrieveActionTaskRecord") private Object alertsRetrieveActionTaskRecord = null; @SerializedName("alertsRetrieveActionResponse") private String alertsRetrieveActionResponse = null; @SerializedName("alertsInstanceReport") private Object alertsInstanceReport = null; @SerializedName("alertsInstanceAnalysis") private Object alertsInstanceAnalysis = null; public BQAlertsRetrieveOutputModel customerCreditRatingStateInstanceRecord(Object customerCreditRatingStateInstanceRecord) { this.customerCreditRatingStateInstanceRecord = customerCreditRatingStateInstanceRecord; return this; } /** * Get customerCreditRatingStateInstanceRecord * @return customerCreditRatingStateInstanceRecord **/ @Schema(description = "") public Object getCustomerCreditRatingStateInstanceRecord() { return customerCreditRatingStateInstanceRecord; } public void setCustomerCreditRatingStateInstanceRecord(Object customerCreditRatingStateInstanceRecord) { this.customerCreditRatingStateInstanceRecord = customerCreditRatingStateInstanceRecord; } public BQAlertsRetrieveOutputModel alertsInstanceRecord(Object alertsInstanceRecord) { this.alertsInstanceRecord = alertsInstanceRecord; return this; } /** * Get alertsInstanceRecord * @return alertsInstanceRecord **/ @Schema(description = "") public Object getAlertsInstanceRecord() { return alertsInstanceRecord; } public void setAlertsInstanceRecord(Object alertsInstanceRecord) { this.alertsInstanceRecord = alertsInstanceRecord; } public BQAlertsRetrieveOutputModel alertsRetrieveActionTaskReference(String alertsRetrieveActionTaskReference) { this.alertsRetrieveActionTaskReference = alertsRetrieveActionTaskReference; return this; } /** * &#x60;status: Not Mapped&#x60; core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a Alerts instance retrieve service call * @return alertsRetrieveActionTaskReference **/ @Schema(example = "ARATR744841", description = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a Alerts instance retrieve service call ") public String getAlertsRetrieveActionTaskReference() { return alertsRetrieveActionTaskReference; } public void setAlertsRetrieveActionTaskReference(String alertsRetrieveActionTaskReference) { this.alertsRetrieveActionTaskReference = alertsRetrieveActionTaskReference; } public BQAlertsRetrieveOutputModel alertsRetrieveActionTaskRecord(Object alertsRetrieveActionTaskRecord) { this.alertsRetrieveActionTaskRecord = alertsRetrieveActionTaskRecord; return this; } /** * &#x60;status: Not Mapped&#x60; core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record * @return alertsRetrieveActionTaskRecord **/ @Schema(description = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record ") public Object getAlertsRetrieveActionTaskRecord() { return alertsRetrieveActionTaskRecord; } public void setAlertsRetrieveActionTaskRecord(Object alertsRetrieveActionTaskRecord) { this.alertsRetrieveActionTaskRecord = alertsRetrieveActionTaskRecord; } public BQAlertsRetrieveOutputModel alertsRetrieveActionResponse(String alertsRetrieveActionResponse) { this.alertsRetrieveActionResponse = alertsRetrieveActionResponse; return this; } /** * &#x60;status: Not Mapped&#x60; core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service response (lists returned reports) * @return alertsRetrieveActionResponse **/ @Schema(description = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service response (lists returned reports) ") public String getAlertsRetrieveActionResponse() { return alertsRetrieveActionResponse; } public void setAlertsRetrieveActionResponse(String alertsRetrieveActionResponse) { this.alertsRetrieveActionResponse = alertsRetrieveActionResponse; } public BQAlertsRetrieveOutputModel alertsInstanceReport(Object alertsInstanceReport) { this.alertsInstanceReport = alertsInstanceReport; return this; } /** * Get alertsInstanceReport * @return alertsInstanceReport **/ @Schema(description = "") public Object getAlertsInstanceReport() { return alertsInstanceReport; } public void setAlertsInstanceReport(Object alertsInstanceReport) { this.alertsInstanceReport = alertsInstanceReport; } public BQAlertsRetrieveOutputModel alertsInstanceAnalysis(Object alertsInstanceAnalysis) { this.alertsInstanceAnalysis = alertsInstanceAnalysis; return this; } /** * Get alertsInstanceAnalysis * @return alertsInstanceAnalysis **/ @Schema(description = "") public Object getAlertsInstanceAnalysis() { return alertsInstanceAnalysis; } public void setAlertsInstanceAnalysis(Object alertsInstanceAnalysis) { this.alertsInstanceAnalysis = alertsInstanceAnalysis; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BQAlertsRetrieveOutputModel bqAlertsRetrieveOutputModel = (BQAlertsRetrieveOutputModel) o; return Objects.equals(this.customerCreditRatingStateInstanceRecord, bqAlertsRetrieveOutputModel.customerCreditRatingStateInstanceRecord) && Objects.equals(this.alertsInstanceRecord, bqAlertsRetrieveOutputModel.alertsInstanceRecord) && Objects.equals(this.alertsRetrieveActionTaskReference, bqAlertsRetrieveOutputModel.alertsRetrieveActionTaskReference) && Objects.equals(this.alertsRetrieveActionTaskRecord, bqAlertsRetrieveOutputModel.alertsRetrieveActionTaskRecord) && Objects.equals(this.alertsRetrieveActionResponse, bqAlertsRetrieveOutputModel.alertsRetrieveActionResponse) && Objects.equals(this.alertsInstanceReport, bqAlertsRetrieveOutputModel.alertsInstanceReport) && Objects.equals(this.alertsInstanceAnalysis, bqAlertsRetrieveOutputModel.alertsInstanceAnalysis); } @Override public int hashCode() { return Objects.hash(customerCreditRatingStateInstanceRecord, alertsInstanceRecord, alertsRetrieveActionTaskReference, alertsRetrieveActionTaskRecord, alertsRetrieveActionResponse, alertsInstanceReport, alertsInstanceAnalysis); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BQAlertsRetrieveOutputModel {\n"); sb.append(" customerCreditRatingStateInstanceRecord: ").append(toIndentedString(customerCreditRatingStateInstanceRecord)).append("\n"); sb.append(" alertsInstanceRecord: ").append(toIndentedString(alertsInstanceRecord)).append("\n"); sb.append(" alertsRetrieveActionTaskReference: ").append(toIndentedString(alertsRetrieveActionTaskReference)).append("\n"); sb.append(" alertsRetrieveActionTaskRecord: ").append(toIndentedString(alertsRetrieveActionTaskRecord)).append("\n"); sb.append(" alertsRetrieveActionResponse: ").append(toIndentedString(alertsRetrieveActionResponse)).append("\n"); sb.append(" alertsInstanceReport: ").append(toIndentedString(alertsInstanceReport)).append("\n"); sb.append(" alertsInstanceAnalysis: ").append(toIndentedString(alertsInstanceAnalysis)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
NDPH-ARTS/mts-services
role-service-client/src/main/java/uk/ac/ox/ndph/mts/roleserviceclient/configuration/WebClientConfig.java
package uk.ac.ox.ndph.mts.roleserviceclient.configuration; import io.netty.channel.ChannelOption; import io.netty.handler.timeout.ReadTimeoutHandler; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.reactive.ClientHttpConnector; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.client.WebClient; import reactor.netty.http.client.HttpClient; import reactor.util.retry.Retry; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; @Configuration @ConfigurationProperties(prefix = "http-client") public class WebClientConfig { @Value("${http-client.connectTimeOutMs:3000}") private int connectTimeOutMs; @Value("${http-client.readTimeOutMs:30000}") private long readTimeOutMs; @Value("${http-client.maxRetryAttempts:9}") private int maxRetryAttempts; @Value("${http-client.initialRetryDurationMs:6000}") private long initialRetryDurationMs; @Value("${http-client.maxRetryDurationMs:30000}") private long maxRetryDurationMs; public ClientHttpConnector connectorWithConnectAndReadTimeOuts() { return new ReactorClientHttpConnector(HttpClient.create() .tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeOutMs()) .doOnConnected(conn -> conn .addHandlerLast(new ReadTimeoutHandler(getReadTimeOutMs(), TimeUnit.MILLISECONDS))))); } @Bean @LoadBalanced public WebClient.Builder webClientBuilder() { return WebClient.builder().clientConnector(connectorWithConnectAndReadTimeOuts()); } @Bean public Supplier<Retry> retryPolicy() { return () -> Retry.backoff(getMaxRetryAttempts(), Duration.ofMillis(getInitialRetryDurationMs())) .maxBackoff(Duration.ofMillis(getMaxRetryDurationMs())); } public int getConnectTimeOutMs() { return connectTimeOutMs; } public void setConnectTimeOutMs(int connectTimeOutMs) { this.connectTimeOutMs = connectTimeOutMs; } public long getReadTimeOutMs() { return readTimeOutMs; } public void setReadTimeOutMs(long readTimeOutMs) { this.readTimeOutMs = readTimeOutMs; } public int getMaxRetryAttempts() { return maxRetryAttempts; } public void setMaxRetryAttempts(int maxRetryAttempts) { this.maxRetryAttempts = maxRetryAttempts; } public long getInitialRetryDurationMs() { return initialRetryDurationMs; } public void setInitialRetryDurationMs(long initialRetryDurationMs) { this.initialRetryDurationMs = initialRetryDurationMs; } public long getMaxRetryDurationMs() { return maxRetryDurationMs; } public void setMaxRetryDurationMs(long maxRetryDurationMs) { this.maxRetryDurationMs = maxRetryDurationMs; } }
lmonkiewicz/commutee
routes-service/src/main/java/com/lmonkiewicz/commutee/routes/domain/model/BusStopData.java
package com.lmonkiewicz.commutee.routes.domain.model; import lombok.*; /** * Created by lmonkiewicz on 11.04.2017. */ @Builder @Getter @EqualsAndHashCode(exclude = {"valid"}) @ToString public class BusStopData { @NonNull private final String id; @NonNull private final String name; @NonNull private final String direction; private final double posX; private final double posY; @Setter @Builder.Default private boolean valid = true; }
JigarkumarPatel/clubhouse-android
Houseclub/src/main/java/me/grishka/appkit/imageloader/ImageLoaderThreadPool.java
<reponame>JigarkumarPatel/clubhouse-android package me.grishka.appkit.imageloader; import android.os.Process; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import me.grishka.appkit.utils.WorkerThread; /** * Created by grishka on 17.12.14. */ public class ImageLoaderThreadPool { private static final int THREAD_COUNT = 4; private static ThreadPoolExecutor networkExecutor = new ThreadPoolExecutor(THREAD_COUNT, THREAD_COUNT, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new LoaderThreadFactory()); private static ThreadPoolExecutor cacheExecutor = new ThreadPoolExecutor(THREAD_COUNT, THREAD_COUNT, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new LoaderThreadFactory()); private static WorkerThread canceler; static { canceler = new WorkerThread("ImageLoader canceler"); canceler.start(); } /*package*/ static void enqueueTask(Runnable task) { networkExecutor.execute(task); } /*package*/ static void enqueueCachedTask(Runnable task) { cacheExecutor.execute(task); } /*package*/ static void enqueueCancellation(Runnable task) { canceler.postRunnable(task, 0); } private static class LoaderThreadFactory implements ThreadFactory { private int num = 0; @Override public Thread newThread(Runnable r) { return new Thread(r) { @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); setName("ImageLoaderThread #" + (++num)); super.run(); } }; } } }
OlafKolditz/ogs
ThirdParty/logog/src/topic.cpp
/* * \file topic.cpp */ #include "logog.hpp" namespace logog { void SetDefaultLevel( LOGOG_LEVEL_TYPE level ) { Filter *pDefaultFilter = &GetDefaultFilter(); pDefaultFilter->Level( level ); } Topic::Topic( const LOGOG_LEVEL_TYPE level , const LOGOG_CHAR *sFileName , const int nLineNumber , const LOGOG_CHAR *sGroup , const LOGOG_CHAR *sCategory , const LOGOG_CHAR *sMessage , const double dTimestamp ) { m_TopicFlags = 0; if ( sFileName != NULL ) { m_vStringProps[ TOPIC_FILE_NAME ] = sFileName; m_TopicFlags |= TOPIC_FILE_NAME_FLAG; } if ( sGroup != NULL ) { m_vStringProps[ TOPIC_GROUP ] = sGroup; m_TopicFlags |= TOPIC_GROUP_FLAG; } if ( sCategory != NULL ) { m_vStringProps[ TOPIC_CATEGORY ] = sCategory; m_TopicFlags |= TOPIC_CATEGORY_FLAG; } if ( sMessage != NULL ) { m_vStringProps[ TOPIC_MESSAGE ] = sMessage; m_TopicFlags |= TOPIC_MESSAGE_FLAG; } m_vIntProps[ TOPIC_LEVEL ] = level; if ( level != LOGOG_LEVEL_ALL ) { m_TopicFlags |= TOPIC_LEVEL_FLAG; } m_vIntProps[ TOPIC_LINE_NUMBER ] = nLineNumber; if ( nLineNumber != 0 ) { m_TopicFlags |= TOPIC_LINE_NUMBER_FLAG; } m_tTime = dTimestamp; if ( dTimestamp != 0.0f ) //-V550 m_TopicFlags |= TOPIC_TIMESTAMP_FLAG; } bool Topic::IsTopic() const { return true; } int Topic::Send( const Topic &node ) { LockableNodesType::iterator it; { ScopedLock sl( m_Subscribers ); it = m_Subscribers.begin(); } /* Iterate over the subscribers, but only addressing the subscribers group while locking it */ Topic *pCurrentTopic; Node *pCurrentNode; m_Subscribers.MutexLock(); int nError = 0; while ( it != m_Subscribers.end() ) { pCurrentNode = *it; if ( pCurrentNode->IsTopic() == false ) continue; pCurrentTopic = ( Topic * )pCurrentNode; if ( pCurrentTopic ) nError += pCurrentTopic->Receive( node ); it++; } m_Subscribers.MutexUnlock(); return nError; } int Topic::Transmit() { return Send( *this ); } int Topic::Receive( const Topic &node ) { /* Default implementation -- send it on to all children */ return Send( node ); } bool Topic::CanSubscribeTo( const Node &otherNode ) { if ( CanSubscribe() == false ) return false; if ( otherNode.IsTopic() == false ) return false; Topic *pTopic = ( Topic * )&otherNode; /* This function will change from topic class to topic class. */ return CanSubscribeCheckTopic( *pTopic ); } bool Topic::CanSubscribeCheckTopic( const Topic &other ) { /* This is the generic comparison case. We'll want to optimize this function for other types * of topics. */ /* Check topics in likely order of disinterest */ if ( m_TopicFlags & TOPIC_LEVEL_FLAG ) { /* Topic levels are less interesting the larger the numbers are. */ if ( other.m_vIntProps[ TOPIC_LEVEL ] > m_vIntProps[ TOPIC_LEVEL ] ) return false; } if ( m_TopicFlags & TOPIC_GROUP_FLAG ) { /* If our topic is not a substring of the publisher's topic, ignore this */ if (( other.m_vStringProps[ TOPIC_GROUP ] ).find( m_vStringProps[ TOPIC_GROUP ] ) == LOGOG_STRING::npos ) return false; } if ( m_TopicFlags & TOPIC_CATEGORY_FLAG ) { /* If our topic is not a substring of the publisher's topic, ignore this */ if (( other.m_vStringProps[ TOPIC_CATEGORY ] ).find( m_vStringProps[ TOPIC_CATEGORY ] ) == LOGOG_STRING::npos ) return false; } if ( m_TopicFlags & TOPIC_FILE_NAME_FLAG ) { /* If our topic is not a substring of the publisher's file name, ignore this. */ if (( other.m_vStringProps[ TOPIC_FILE_NAME ] ).find( m_vStringProps[ TOPIC_FILE_NAME ] ) == LOGOG_STRING::npos ) return false; } if ( m_TopicFlags & TOPIC_LINE_NUMBER_FLAG ) { /* If our line number doesn't equal theirs, ignore this */ if ( other.m_vIntProps[ TOPIC_LINE_NUMBER ] != m_vIntProps[ TOPIC_LINE_NUMBER ] ) return false; } if ( m_TopicFlags & TOPIC_MESSAGE_FLAG ) { /* If our topic is not a substring of the publisher's file name, ignore this. */ if (( other.m_vStringProps[ TOPIC_MESSAGE ] ).find( m_vStringProps[ TOPIC_MESSAGE ] ) == LOGOG_STRING::npos ) return false; } if ( m_TopicFlags & TOPIC_TIMESTAMP_FLAG ) { /* Timestamps are only interesting if they're greater than or equal to ours. */ if ( other.m_tTime < m_tTime ) return false; } /* all tests passed */ return true; } bool Topic::PublishTo( Node &subscriber ) { #ifdef LOGOG_INTERNAL_DEBUGGING if ( &subscriber == this ) LOGOG_INTERNAL_FAILURE; #endif bool bWasInserted; /** Additional checking may be required first -- can the subscriber handle this publishing? */ if ( subscriber.IsTopic() ) { Topic *pSubscriber = (Topic *)&subscriber; if ( pSubscriber->CanSubscribeTo( *this ) == false ) return false; } { ScopedLock sl( m_Subscribers ); bWasInserted = ( m_Subscribers.insert( &subscriber ) ).second; } if ( bWasInserted ) subscriber.SubscribeTo( *this ); return bWasInserted; } void Topic::Format( const LOGOG_CHAR *cFormatMessage, ... ) { va_list args; va_start( args, cFormatMessage ); m_vStringProps[ TOPIC_MESSAGE ].format_va( cFormatMessage, args ); va_end( args ); m_TopicFlags |= TOPIC_MESSAGE_FLAG; } const LOGOG_STRING & Topic::FileName() const { return m_vStringProps[ TOPIC_FILE_NAME ]; } void Topic::FileName( const LOGOG_STRING &s ) { m_vStringProps[ TOPIC_FILE_NAME ] = s; m_TopicFlags |= TOPIC_FILE_NAME_FLAG; } const LOGOG_STRING & Topic::Message() const { return m_vStringProps[ TOPIC_MESSAGE ]; } void Topic::Message( const LOGOG_STRING &s ) { m_vStringProps[ TOPIC_MESSAGE ] = s; m_TopicFlags |= TOPIC_MESSAGE_FLAG; } const LOGOG_STRING & Topic::Category() const { return m_vStringProps[ TOPIC_CATEGORY ]; } void Topic::Category( const LOGOG_STRING &s ) { m_vStringProps[ TOPIC_CATEGORY ] = s; m_TopicFlags |= TOPIC_CATEGORY_FLAG; } const LOGOG_STRING & Topic::Group() const { return m_vStringProps[ TOPIC_GROUP ]; } void Topic::Group( const LOGOG_STRING &s ) { m_vStringProps[ TOPIC_GROUP ] = s; m_TopicFlags |= TOPIC_GROUP_FLAG; } int Topic::LineNumber() const { return m_vIntProps[ TOPIC_LINE_NUMBER ]; } void Topic::LineNumber( const int num ) { m_vIntProps[ TOPIC_LINE_NUMBER ] = num; m_TopicFlags |= TOPIC_LINE_NUMBER_FLAG; } LOGOG_LEVEL_TYPE Topic::Level() const { return ( LOGOG_LEVEL_TYPE )m_vIntProps[ TOPIC_LEVEL ]; } void Topic::Level( LOGOG_LEVEL_TYPE level ) { m_vIntProps[ TOPIC_LEVEL ] = level; m_TopicFlags |= TOPIC_LEVEL_FLAG; } logog::LOGOG_TIME Topic::Timestamp() const { return m_tTime; } void Topic::Timestamp( const LOGOG_TIME t ) { m_tTime = t; m_TopicFlags |= TOPIC_TIMESTAMP_FLAG; } TOPIC_FLAGS Topic::GetTopicFlags() const { return m_TopicFlags; } /********************************************************/ Filter::Filter( const LOGOG_LEVEL_TYPE level , const LOGOG_CHAR *sFileName , const int nLineNumber , const LOGOG_CHAR *sGroup , const LOGOG_CHAR *sCategory , const LOGOG_CHAR *sMessage , const double dTimestamp ) : Topic( level, sFileName, nLineNumber, sGroup, sCategory, sMessage, dTimestamp ) { Statics *pStatic = &Static(); #ifdef LOGOG_INTERNAL_DEBUGGING if ( pStatic == NULL ) LOGOG_INTERNAL_FAILURE; #endif if ( pStatic->s_pDefaultFilter == NULL ) pStatic->s_pDefaultFilter = this; PublishToMultiple( AllTargets() ); LockableNodesType *pFilterNodes = &AllFilters(); { ScopedLock sl( *pFilterNodes ); pFilterNodes->insert( this ); } } Filter &GetDefaultFilter() { Statics *pStatic = &Static(); #ifdef LOGOG_INTERNAL_DEBUGGING if ( pStatic == NULL ) LOGOG_INTERNAL_FAILURE; #endif if ( pStatic->s_pDefaultFilter == NULL ) { pStatic->s_pDefaultFilter = new Filter( LOGOG_LEVEL ); } return *((Filter *)(pStatic->s_pDefaultFilter)); } TopicGroup::TopicGroup( const LOGOG_CHAR *sGroup ) : Topic( LOGOG_LEVEL_ALL, NULL, 0, sGroup ) { } bool TopicGroup::CanSubscribeCheckTopic( const Topic &other ) { if ( m_TopicFlags & TOPIC_LEVEL_FLAG ) { /* Topic levels are less interesting the larger the numbers are. */ if ( other.m_vIntProps[ TOPIC_LEVEL ] > m_vIntProps[ TOPIC_LEVEL ] ) return false; } return true; } TopicLevel::TopicLevel( const LOGOG_LEVEL_TYPE level ) : Topic( level ) { } bool TopicLevel::CanSubscribeCheckTopic( const Topic &other ) { /* Check topics in likely order of disinterest */ if ( m_TopicFlags & TOPIC_LEVEL_FLAG ) { /* Topic levels are less interesting the larger the numbers are. */ if ( other.m_vIntProps[ TOPIC_LEVEL ] > m_vIntProps[ TOPIC_LEVEL ] ) return false; } /* all tests passed */ return true; } TopicSource::TopicSource( const LOGOG_LEVEL_TYPE level , const LOGOG_CHAR *sFileName, const int nLineNumber, const LOGOG_CHAR *sGroup, const LOGOG_CHAR *sCategory, const LOGOG_CHAR *sMessage, const double dTimestamp ) : Topic( level, sFileName, nLineNumber, sGroup, sCategory, sMessage, dTimestamp ) { } bool TopicSource::SubscribeTo( Node & ) { return false; } bool TopicSource::UnsubscribeTo( Node & ) { return false; } bool TopicSource::CanSubscribe() const { return false; } bool TopicSink::IsTopic() const { return true; } void TopicSink::Initialize() { } bool TopicSink::PublishTo( Node & ) { return false; } bool TopicSink::UnpublishTo( Node & ) { return false; } bool TopicSink::CanPublish() const { return false; } }
Xrenya/algorithms
Algoprog/Level_1/Real/A.py
<reponame>Xrenya/algorithms def equal(a, b, c): eps = 1e-10 if abs(a + b - c) < eps: return "YES" else: return "NO" a = float(input()) b = float(input()) c = float(input()) equal(a, b, c)
johnwonder/SpringSrc
springdebug/src/main/java/com/john/innerbean/Customer.java
package com.john.innerbean; /** * @Description: SpringSrc * @Author: johnwonder * @Date: 2020/8/31 */ public class Customer { private Person person; // public Customer(Person person) { // this.person = person; // } public Customer(){ } // public Customer(Person person) { // this.person = person; // } // public void setPerson(Person person) { this.person = person; } @Override public String toString() { return "Customer [person=" + person + "]"; } }
zhyon404/kubeflow
testing/kfctl/kfctl_go_test.py
<gh_stars>1000+ import logging import os import pytest from kubeflow.kubeflow.ci import kfctl_go_test_utils as kfctl_util from kubeflow.testing import util def test_build_kfctl_go(record_xml_attribute, app_path, project, use_basic_auth, use_istio, config_path, build_and_apply, cluster_creation_script): """Test building and deploying Kubeflow. Args: app_path: The path to the Kubeflow app. project: The GCP project to use. use_basic_auth: Whether to use basic_auth. use_istio: Whether to use Istio or not config_path: Path to the KFDef spec file. cluster_creation_script: script invoked to create a new cluster build_and_apply: whether to build and apply or apply """ util.set_pytest_junit(record_xml_attribute, "test_build_kfctl_go") # Need to activate account for scopes. if os.getenv("GOOGLE_APPLICATION_CREDENTIALS"): util.run([ "gcloud", "auth", "activate-service-account", "--key-file=" + os.environ["GOOGLE_APPLICATION_CREDENTIALS"] ]) # TODO(yanniszark): split this into a separate workflow step if cluster_creation_script: logging.info("Cluster creation script specified: %s", cluster_creation_script) util.run(["/bin/bash", "-c", cluster_creation_script]) kfctl_path = kfctl_util.build_kfctl_go() app_path = kfctl_util.kfctl_deploy_kubeflow( app_path, project, use_basic_auth, use_istio, config_path, kfctl_path, build_and_apply) if not cluster_creation_script: kfctl_util.verify_kubeconfig(app_path) if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format=('%(levelname)s|%(asctime)s' '|%(pathname)s|%(lineno)d| %(message)s'), datefmt='%Y-%m-%dT%H:%M:%S', ) logging.getLogger().setLevel(logging.INFO) pytest.main()
deadsy/gooz
ggm/src/module/pm/breath.c
/****************************************************************************** * Copyright (c) 2019 <NAME>. (<EMAIL>) * * SPDX-License-Identifier: Apache-2.0 * * Module to generate breath excitation for wind instruments. */ #include "ggm.h" #include "osc/osc.h" /****************************************************************************** * private state */ struct breath { struct module *noise; /* noise module */ struct module *adsr; /* adsr module */ float kn; /* noise scale */ float ka; /* amplitude scale */ float kd; /* derived scale */ }; /****************************************************************************** * breath functions */ static void breath_set_scale(struct module *m, float kn, float ka) { struct breath *this = (struct breath *)m->priv; this->kn = kn; this->ka = ka; this->kd = ka / (1.f + kn); } /****************************************************************************** * module port functions */ /* breath_port_reset resets the state of the envelope */ static void breath_port_reset(struct module *m, const struct event *e) { struct breath *this = (struct breath *)m->priv; event_in(this->adsr, "reset", e, NULL); } /* breath_port_gate is the envelope gate control, attack(>0) or release(=0) */ static void breath_port_gate(struct module *m, const struct event *e) { struct breath *this = (struct breath *)m->priv; event_in(this->adsr, "gate", e, NULL); } /* breath_port_attack sets the attack time (secs) */ static void breath_port_attack(struct module *m, const struct event *e) { struct breath *this = (struct breath *)m->priv; event_in(this->adsr, "attack", e, NULL); } /* breath_port_decay sets the decay time (secs) */ static void breath_port_decay(struct module *m, const struct event *e) { struct breath *this = (struct breath *)m->priv; event_in(this->adsr, "decay", e, NULL); } /* breath_port_sustain sets the sustain level 0..1 */ static void breath_port_sustain(struct module *m, const struct event *e) { struct breath *this = (struct breath *)m->priv; event_in(this->adsr, "sustain", e, NULL); } /* breath_port_release sets the release time (secs) */ static void breath_port_release(struct module *m, const struct event *e) { struct breath *this = (struct breath *)m->priv; event_in(this->adsr, "release", e, NULL); } /* breath_port_kn sets the scale for the breath noise */ static void breath_port_kn(struct module *m, const struct event *e) { struct breath *this = (struct breath *)m->priv; float kn = clampf_lo(event_get_float(e), 0.f); LOG_DBG("%s set kn %f", m->name, kn); breath_set_scale(m, kn, this->ka); } /* breath_port_ka sets the overall breath excitation amplitude */ static void breath_port_ka(struct module *m, const struct event *e) { struct breath *this = (struct breath *)m->priv; float ka = clampf_lo(event_get_float(e), 0.f); LOG_DBG("%s set ka %f", m->name, ka); breath_set_scale(m, this->kn, ka); } /****************************************************************************** * module functions */ static int breath_alloc(struct module *m, va_list vargs) { struct module *noise = NULL; struct module *adsr = NULL; /* allocate the private data */ struct breath *this = ggm_calloc(1, sizeof(struct breath)); if (this == NULL) { return -1; } m->priv = (void *)this; /* set some defaults */ breath_set_scale(m, 0.5f, 1.f); /* noise */ noise = module_new(m, "osc/noise", -1, NOISE_TYPE_WHITE); if (noise == NULL) { goto error; } this->noise = noise; /* adsr */ adsr = module_new(m, "env/adsr", -1); if (adsr == NULL) { goto error; } event_in_float(adsr, "attack", 0.1f, NULL); event_in_float(adsr, "decay", 0.5f, NULL); event_in_float(adsr, "sustain", 0.85f, NULL); event_in_float(adsr, "release", 1.f, NULL); this->adsr = adsr; return 0; error: module_del(noise); module_del(adsr); ggm_free(m->priv); return -1; } static void breath_free(struct module *m) { struct breath *this = (struct breath *)m->priv; module_del(this->noise); module_del(this->adsr); ggm_free(this); } static bool breath_process(struct module *m, float *bufs[]) { struct breath *this = (struct breath *)m->priv; struct module *adsr = this->adsr; float env[AudioBufferSize]; bool active = adsr->info->process(adsr, (float *[]) { env, }); if (active) { struct module *noise = this->noise; float *out = bufs[0]; /* out = ((noise * env * kn) + env) * kd */ noise->info->process(noise, (float *[]) { out, }); block_mul(out, env); block_mul_k(out, this->kn); block_add(out, env); block_mul_k(out, this->kd); } return active; } /****************************************************************************** * module information */ static const struct port_info in_ports[] = { {.name = "reset",.type = PORT_TYPE_BOOL,.pf = breath_port_reset}, {.name = "gate",.type = PORT_TYPE_FLOAT,.pf = breath_port_gate}, {.name = "attack",.type = PORT_TYPE_FLOAT,.pf = breath_port_attack}, {.name = "decay",.type = PORT_TYPE_FLOAT,.pf = breath_port_decay}, {.name = "sustain",.type = PORT_TYPE_FLOAT,.pf = breath_port_sustain}, {.name = "release",.type = PORT_TYPE_FLOAT,.pf = breath_port_release}, {.name = "kn",.type = PORT_TYPE_FLOAT,.pf = breath_port_kn}, {.name = "ka",.type = PORT_TYPE_FLOAT,.pf = breath_port_ka}, PORT_EOL, }; static const struct port_info out_ports[] = { {.name = "out",.type = PORT_TYPE_AUDIO,}, PORT_EOL, }; const struct module_info pm_breath_module = { .mname = "pm/breath", .iname = "breath", .in = in_ports, .out = out_ports, .alloc = breath_alloc, .free = breath_free, .process = breath_process, }; MODULE_REGISTER(pm_breath_module); /*****************************************************************************/
sarang-apps/darshan_browser
content/renderer/renderer_main_platform_delegate_fuchsia.cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/renderer_main_platform_delegate.h" namespace content { RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) {} RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {} void RendererMainPlatformDelegate::PlatformInitialize() { fuchsia_audio_device_factory_ = std::make_unique<FuchsiaAudioDeviceFactory>(); } void RendererMainPlatformDelegate::PlatformUninitialize() { fuchsia_audio_device_factory_.reset(); } bool RendererMainPlatformDelegate::EnableSandbox() { return true; } } // namespace content
TimSchneider42/mbpo
gym_modular/sensors/robot/gripper_joint_velocity_sensor.py
from assembly_gym.environment.generic import RobotComponent from .joint_velocity_sensor import JointVelocitySensor class GripperJointVelocitySensor(JointVelocitySensor): def __init__(self, robot_name: str = "ur10"): super(GripperJointVelocitySensor, self).__init__(name_prefix="gripper") self.__robot_name = robot_name def _get_observed_robot_component(self) -> RobotComponent: return self.task.environment.robots[self.__robot_name].gripper
Yoichi-KIKUCHI/vis
src/main/java/com/yo1000/vis/model/service/ChartService.java
package com.yo1000.vis.model.service; import com.yo1000.vis.component.aop.Cache; import com.yo1000.vis.model.data.Query; import com.yo1000.vis.model.repository.chart.ChartRepository; import com.yo1000.vis.model.repository.system.QueryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; /** * Created by yoichi.kikuchi on 15/06/09. */ @Service public class ChartService { @Autowired private ChartRepository chartRepository; @Autowired private QueryRepository queryRepository; @Cache public List<Map<String, Object>> getItems(String key) { Query query = this.getQueryRepository().findByKey(key); List<Map<String, Object>> items = this.getChartRepository().getItems(query.getSql()); return items; } @Cache public List<Map<String, Object>> getItemsForSummary(String key) { Query query = this.getQueryRepository().findByKey(key); List<Map<String, Object>> items = this.getChartRepository().getItems(query.getSql()); for (int i = 1; i < items.size(); i++) { for (Map.Entry<String, Object> data : items.get(i).entrySet()) { if (Number.class.isAssignableFrom(data.getValue().getClass())) { data.setValue(((Number) data.getValue()).doubleValue() + ((Number) items.get(i - 1).get(data.getKey())).doubleValue()); } } } return items; } @Cache public List<List<Object>> getItemsForSnowCover(String key, Date start, Date end) { Query query = this.getQueryRepository().findByKey(key); List<List<Object>> items = new ArrayList<List<Object>>(); Date work = new Date(start.getTime()); Calendar calendar = Calendar.getInstance(); while (!work.after(end)) { items.add(this.getChartRepository().getItemsForSnowCover(query.getSql(), work)); calendar.setTime(work); calendar.add(Calendar.MONTH, 1); work = calendar.getTime(); } int maxSize = 0; for (int i = 0; i < items.size(); i++) { if (items.get(i).size() > maxSize) { maxSize = items.get(i).size(); } } for (List<Object> item : items) { while (item.size() < maxSize) { item.add(1, 0); } } return items; } protected ChartRepository getChartRepository() { return chartRepository; } protected QueryRepository getQueryRepository() { return queryRepository; } }
kxepal/couchdb-fauxton
app/addons/databases/tests/nightwatch/zeroclipboard.js
// 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. var os = require('os'); module.exports = { 'ZeroClipboard copies' : function (client) { var waitTime = client.globals.maxWaitTime, newDatabaseName = client.globals.testDatabaseName, baseUrl = client.globals.test_settings.launch_url; var controlOrCommandKey = client.Keys.CONTROL; if (os.type() === 'Darwin') { controlOrCommandKey = client.Keys.COMMAND; } client .loginToGUI() .deleteDatabase(newDatabaseName) //need to delete the automatic database 'fauxton-selenium-tests' that has been set up before each test .url(baseUrl) .clickWhenVisible('.control-toggle-api-url') .waitForElementVisible('.copy-button', waitTime, false) .moveTo('.copy-button') .click('.copy-button') .mouseButtonDown('left') .mouseButtonUp('left') .closeNotification() .clickWhenVisible('.search-autocomplete', waitTime, false) .setValue('.search-autocomplete', '') .keys([controlOrCommandKey, 'v']) .assert.value('.search-autocomplete', 'http://localhost:8000/_all_dbs') .end(); } };
AndreaVoltan/MyKratos7.0
applications/FluidDynamicsApplication/python_scripts/apply_distance_modification_process.py
import KratosMultiphysics import KratosMultiphysics.FluidDynamicsApplication as KratosFluid import math def Factory(settings, Model): if(type(settings) != KratosMultiphysics.Parameters): raise Exception("expected input shall be a Parameters object, encapsulating a json string") return ApplyDistanceModificationProcess(Model, settings["Parameters"]) class ApplyDistanceModificationProcess(KratosMultiphysics.Process): def __init__(self, Model, settings): KratosMultiphysics.Process.__init__(self) default_parameters = KratosMultiphysics.Parameters( """ { "model_part_name" : "CHOOSE_FLUID_MODELPART_NAME", "distance_factor" : 2.0, "distance_threshold" : 0.01, "continuous_distance" : true, "check_at_each_time_step" : false, "avoid_almost_empty_elements" : true, "deactivate_full_negative_elements" : true, "recover_original_distance_at_each_step" : false } """ ) settings.ValidateAndAssignDefaults(default_parameters); self.fluid_model_part = Model[settings["model_part_name"].GetString()] self.DistanceModificationProcess = KratosFluid.DistanceModificationProcess(self.fluid_model_part, settings) def ExecuteInitialize(self): self.DistanceModificationProcess.ExecuteInitialize() def ExecuteBeforeSolutionLoop(self): self.DistanceModificationProcess.ExecuteBeforeSolutionLoop() def ExecuteInitializeSolutionStep(self): self.DistanceModificationProcess.ExecuteInitializeSolutionStep() def ExecuteFinalizeSolutionStep(self): self.DistanceModificationProcess.ExecuteFinalizeSolutionStep()
stevedekorte/ConnectionMachine
client/apps/CellularAutomata/CA.js
"use strict" getGlobalThis().CA = class CA extends Base { constructor() { super() // interesting rules sets // 00111110 // 10100001 // 00001111 // 01001001 // 01111100 // 10010010 // 01101010 // 00011110 // keep history so we can reset if loop detected this.newSlot("hashHistory", []) this.newSlot("maxHistory", 100000) this.newSlot("hadLoop", false) this.newSlot("width", 32) // rules // first 3 bits is are state of previous left, middle, and right bits // last bit is for new state this.newSlot("rules", [ [0, 0, 0, 1], // 0 [0, 0, 1, 1], // 1 // mirrors 4 [0, 1, 0, 1], // 2 [0, 1, 1, 0], // 3 // mirrors 6 [1, 0, 0, 0], // 4 // mirrors 1 [1, 0, 1, 0], // 5 [1, 1, 0, 1], // 6 // mirrors 3 [1, 1, 1, 0] // 7 ]) this.newSlot("doesEnforceSymmetry", true) /* this.newSlot("symmetries", [ [1, 4], [3, 6] ]) */ this.newSlot("generation", 0) this.randomizeRules() this.newSlot("cells", new Array(this.width())) this.restart() } checkForLoop () { const hash = this.cells().join("").hashCode() const matches = this.hashHistory().filter((h) => h == hash) const isInLoop = matches.length != 0 this.hashHistory().push(hash) while (this.hashHistory().length > this.maxHistory()) { this.hashHistory().shift() } return isInLoop } clearHistory () { this.setHashHistory([]) this.setHadLoop(false) return this } enforceRuleSymmetries () { const rules = this.rules() rules[4][3] = rules[1][3] rules[6][3] = rules[3][3] /* this.symmetries().forEach((sym) => { const i1 = sym[0] const v = this.cells()[i1] for (let ri = 1; ri < this. rules[ }) */ } ruleString() { let s = "" for (let i = 0; i < this._rules.length; i++) { s += this._rules[i][3] } return s } enforceCellStateSymmetry () { const cells = this.cells() for (let i = 0; i < cells.length - 1; i++) { cells[cells.length - 1 - i] = cells[i] } return this } randomizeRules() { for (let i = 0; i < this._rules.length; i++) { const rule = this._rules[i] rule[3] = Math.round(Math.random()) } this.genRuleDict() } mutateRules() { const i = Math.floor(Math.random() * this._rules.length) const rule = this._rules[i] if (rule[3] == 1) { rule[3] = 0 } else { rule[3] = 1 } if (this.doesEnforceSymmetry()) { this.enforceRuleSymmetries() } this.genRuleDict() } flipCellAt (i) { if (this._cells[i] == 1) { this._cells[i] = 0 } else { this._cells[i] = 1 } return this } flipOneCell () { const i = Math.floor(Math.random() * this.cells().length) this.flipCellAt(i) return this } genRuleDict() { this._rulesDict = {} for (let i = 0; i < this._rules.length; i++) { const rule = this._rules[i] const key = this.keyForSet(rule) const v = rule[3] this._rulesDict[key] = v //print("rule ", rule, " key ", key, " value ", v) } //print("ruleSet: ", this.ruleString()) } keyForSet(set) { //return str(set[0:3]) //str(set[0]) + str(set[1]) + str(set[2]) // for debugging return set[0] + set[1] * 2 + set[2] * 4 } restart() { this._generation = 0 this._cells = new Array(this._width) this.randomizeCells() } randomizeCells() { for (let i = 0; i < this._width; i++) { this._cells[i] = Math.round(Math.random()) //this._cells[i] = Math.round(Math.random() * Math.random()) } this.clearHistory() } mutateCells() { for (let i = 0; i < this._width; i++) { const r = Math.round(Math.random() * Math.random() * Math.random()) if (r) { this.flipCellAt(i) } } } cellValueAt (i) { let xmax = this._cells.length if (i < 0) { i = xmax + 1 + i } if (i > xmax - 1) { i = i % xmax } return this._cells[i] ? 1 : 0 } generate() { let xmax = this._cells.length const nextgen = new Array(xmax) for (let i = 0; i < xmax; i++) { const left = this.cellValueAt(i - 1) const me = this.cellValueAt(i + 0) const right = this.cellValueAt(i + 1) const set = [left, me, right] const key = this.keyForSet(set) const v = this._rulesDict[key] //print("set ", set, " key ", key, " value ", v) nextgen[i] = v } this._cells = nextgen this._generation += 1 if (this.checkForLoop()) { this.setHadLoop(true) } } }
christophe-gouel/dolo
dolo/tests/test_states_perturbation.py
import unittest class StatesPerturbationsTestCase(unittest.TestCase): def test_second_order_accuracy(self): # This solves the optimal growth example at second order # and computes the second order correction to the steady-state # We test that both the statefree method and the perturbation to states # yield the same result. from dolo.misc.yamlfile import yaml_import model = yaml_import('examples/global_models/rbc.yaml', compiler=None) from dolo.numeric.perturbations import solve_decision_rule from dolo.numeric.perturbations_to_states import approximate_controls coeffs = approximate_controls(model,order=2, return_dr=False) state_perturb = coeffs[0] dr = solve_decision_rule(model) statefree_perturb = dr['ys'] + dr['g_ss']/2.0 ctls = model.symbols_s['controls'] ctls_ind = [model.variables.index(v) for v in ctls] # the two methods should yield exactly the same result from numpy.testing import assert_almost_equal A = statefree_perturb[ctls_ind] B = state_perturb assert_almost_equal(A, B) # we compare the risk-adjusted constants # def test_third_order_accuracy(self): def test_perturbation_1(self): from dolo.misc.yamlfile import yaml_import model = yaml_import('examples/global_models/rbc.yaml') from dolo.numeric.perturbations_to_states import approximate_controls dr = approximate_controls(model,order=1) def test_perturbation_2(self): from dolo.misc.yamlfile import yaml_import from dolo.numeric.perturbations_to_states import approximate_controls model = yaml_import('examples/global_models/rbc.yaml') dr = approximate_controls(model,order=2) def test_perturbation_3(self): from dolo.misc.yamlfile import yaml_import from dolo.numeric.perturbations_to_states import approximate_controls model = yaml_import('examples/global_models/rbc.yaml') dr = approximate_controls(model,order=3) if __name__ == '__main__': unittest.main()
bakasoft/framboyan
src/main/java/org/bakasoft/framboyan/inspect/Inspectable.java
package org.bakasoft.framboyan.inspect; public interface Inspectable { void inspectWith(Inspector output); default String inspect() { StringBuilder output = new StringBuilder(); Inspector inspector = new Inspector(output); inspectWith(inspector); return output.toString(); } }
yiou362/spring-boot-2.2.9.RELEASE
spring-boot-project/spring-boot-cli/src/it/java/org/springframework/boot/cli/CommandLineIT.java
/* * Copyright 2012-2019 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.boot.cli; import java.io.File; import java.io.IOException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.cli.infrastructure.CommandLineInvoker; import org.springframework.boot.cli.infrastructure.CommandLineInvoker.Invocation; import static org.assertj.core.api.Assertions.assertThat; /** * Integration Tests for the command line application. * * @author <NAME> * @author <NAME> */ class CommandLineIT { private CommandLineInvoker cli; @BeforeEach void setup(@TempDir File tempDir) { this.cli = new CommandLineInvoker(tempDir); } @Test void hintProducesListOfValidCommands() throws IOException, InterruptedException { Invocation cli = this.cli.invoke("hint"); assertThat(cli.await()).isEqualTo(0); assertThat(cli.getErrorOutput()).isEmpty(); assertThat(cli.getStandardOutputLines()).hasSize(11); } @Test void invokingWithNoArgumentsDisplaysHelp() throws IOException, InterruptedException { Invocation cli = this.cli.invoke(); assertThat(cli.await()).isEqualTo(1); assertThat(cli.getErrorOutput()).isEmpty(); assertThat(cli.getStandardOutput()).startsWith("usage:"); } @Test void unrecognizedCommandsAreHandledGracefully() throws IOException, InterruptedException { Invocation cli = this.cli.invoke("not-a-real-command"); assertThat(cli.await()).isEqualTo(1); assertThat(cli.getErrorOutput()) .contains("'not-a-real-command' is not a valid command"); assertThat(cli.getStandardOutput()).isEmpty(); } @Test void version() throws IOException, InterruptedException { Invocation cli = this.cli.invoke("version"); assertThat(cli.await()).isEqualTo(0); assertThat(cli.getErrorOutput()).isEmpty(); assertThat(cli.getStandardOutput()).startsWith("Spring CLI v"); } @Test void help() throws IOException, InterruptedException { Invocation cli = this.cli.invoke("help"); assertThat(cli.await()).isEqualTo(1); assertThat(cli.getErrorOutput()).isEmpty(); assertThat(cli.getStandardOutput()).startsWith("usage:"); } }
johandoornenbal/TurnToinez-Customer-System
dom/src/main/java/domainapp/dom/klanten/Klant.java
<gh_stars>0 package domainapp.dom.klanten; import java.util.Arrays; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.UUID; import javax.inject.Inject; import javax.jdo.annotations.Column; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.VersionStrategy; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.BookmarkPolicy; import org.apache.isis.applib.annotation.CollectionLayout; import org.apache.isis.applib.annotation.Contributed; import org.apache.isis.applib.annotation.DomainObject; import org.apache.isis.applib.annotation.DomainObjectLayout; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.Optionality; import org.apache.isis.applib.annotation.Parameter; import org.apache.isis.applib.annotation.ParameterLayout; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.PropertyLayout; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.isisaddons.wicket.gmap3.cpt.applib.Locatable; import org.isisaddons.wicket.gmap3.cpt.applib.Location; import org.isisaddons.wicket.gmap3.cpt.service.LocationLookupService; import org.incode.module.base.dom.utils.TitleBuilder; import domainapp.dom.bestellingen.Bestelling; import domainapp.dom.bestellingen.BestellingRepository; import domainapp.dom.bestellingen.Postuur; import domainapp.dom.communicatie.Communicatie; import domainapp.dom.communicatie.CommunicatieRepository; import domainapp.dom.facturen.Factuur; import domainapp.dom.facturen.FactuurRepository; import domainapp.dom.instellingen.InstellingenRepository; import domainapp.dom.mailchimpintegration.module.api.IMailChimpParty; import domainapp.dom.utils.StringUtils; import lombok.Getter; import lombok.Setter; @javax.jdo.annotations.PersistenceCapable( identityType= IdentityType.DATASTORE, schema = "tti" ) @javax.jdo.annotations.DatastoreIdentity( strategy=javax.jdo.annotations.IdGeneratorStrategy.IDENTITY, column="id") @javax.jdo.annotations.Version( strategy= VersionStrategy.VERSION_NUMBER, column="version") @javax.jdo.annotations.Queries({ @javax.jdo.annotations.Query( name = "findByNaamContains", language = "JDOQL", value = "SELECT " + "FROM domainapp.dom.klanten.Klant " + "WHERE naam.toLowerCase().indexOf(:naam.toLowerCase()) >= 0 "), @javax.jdo.annotations.Query( name = "findByEmailContains", language = "JDOQL", value = "SELECT " + "FROM domainapp.dom.klanten.Klant " + "WHERE email.toLowerCase().indexOf(:email.toLowerCase()) >= 0 "), @javax.jdo.annotations.Query( name = "findUnique", language = "JDOQL", value = "SELECT " + "FROM domainapp.dom.klanten.Klant " + "WHERE uniqueId == :uniqueId.toLowerCase() "), @javax.jdo.annotations.Query( name = "findByUniqueHistoricId", language = "JDOQL", value = "SELECT " + "FROM domainapp.dom.klanten.Klant " + "WHERE historicId == :historicId "), @javax.jdo.annotations.Query( name = "findByMogelijkDubbel", language = "JDOQL", value = "SELECT " + "FROM domainapp.dom.klanten.Klant " + "WHERE mogelijkDubbel == :mogelijkDubbel "), @javax.jdo.annotations.Query( name = "findByPlaatsContains", language = "JDOQL", value = "SELECT " + "FROM domainapp.dom.klanten.Klant " + "WHERE plaats.toLowerCase().indexOf(:plaats.toLowerCase()) >= 0 "), @javax.jdo.annotations.Query( name = "findByKlantObjectContains", language = "JDOQL", value = "SELECT " + "FROM domainapp.dom.klanten.Klant " + "WHERE plaats.toLowerCase().indexOf(:searchString.toLowerCase()) >= 0 " + "|| postcode.toLowerCase().indexOf(:searchString.toLowerCase()) >= 0 " + "|| naam.toLowerCase().indexOf(:searchString.toLowerCase()) >= 0 " + "|| email.toLowerCase().indexOf(:searchString.toLowerCase()) >= 0 " + "|| aantekeningen.toLowerCase().indexOf(:searchString.toLowerCase()) >= 0 ") }) @javax.jdo.annotations.Unique(name="Klant_UNQ", members = {"uniqueId"}) @DomainObject( editing = Editing.DISABLED, autoCompleteRepository = KlantRepository.class ) @DomainObjectLayout( bookmarking = BookmarkPolicy.AS_ROOT ) public class Klant implements Locatable, Comparable<Klant>, IMailChimpParty { public Klant(){} public Klant( final String naam, final String straat, final String postcode, final String plaats, final String email, final String telefoon1, final String telefoon2, final String aantekeningen ) { this.naam = naam; this.straat = straat; this.postcode = postcode; this.plaats = plaats; this.email = email; this.telefoon1 = telefoon1; this.telefoon2 = telefoon2; this.aantekeningen = aantekeningen; } public String title(){ return TitleBuilder.start() .withName(getNaam()) .toString(); } @Getter @Setter @Column(allowsNull = "false") private String naam; @Getter @Setter @Column(allowsNull = "true") private String straat; @Getter @Setter @Column(allowsNull = "true") private String postcode; @Getter @Setter @Column(allowsNull = "true") private String plaats; @Getter @Setter @Column(allowsNull = "true") private String email; @Getter @Setter @Column(allowsNull = "true") private String telefoon1; @Getter @Setter @Column(allowsNull = "true") private String telefoon2; @Getter @Setter @Column(allowsNull = "true", length = 2048) @PropertyLayout(multiLine = 5) private String aantekeningen; @Persistent @Getter @Setter @Property(optionality = Optionality.OPTIONAL, hidden = Where.ALL_TABLES) private Location location; @Action(semantics = SemanticsOf.SAFE) @ActionLayout(contributed = Contributed.AS_ASSOCIATION) public List<Klant> getOpDeKaart(){ return Arrays.asList(this,this); // hack to force a collection layout ... 2x same obj } @Getter @Setter @Column(allowsNull = "false") private String uniqueId; @Getter @Setter @Column(allowsNull = "true") @Property(hidden = Where.ALL_TABLES) private Integer historicId; @Getter @Setter @Column(allowsNull = "true") @Property(hidden = Where.ALL_TABLES) private Boolean mogelijkDubbel; @Getter @Setter @Column(allowsNull = "true") @Property(hidden = Where.ALL_TABLES) private Boolean stuurGeenMailing; @Action(semantics = SemanticsOf.IDEMPOTENT) public Klant aanUit(){ setStuurGeenMailing(getStuurGeenMailing()==null || !getStuurGeenMailing() ? true : false); return this; } @Getter @Setter @Persistent(mappedBy = "klant", dependentElement = "true") private SortedSet<Bestelling> bestellingen = new TreeSet<>(); @Getter @Setter @Persistent(mappedBy = "klant", dependentElement = "true") @CollectionLayout(sortedBy = Communicatie.CommunicatieComparator.class) private SortedSet<Communicatie> communicaties = new TreeSet<>(); @Action(semantics = SemanticsOf.NON_IDEMPOTENT) public Bestelling nieuweBestelling( final String naamTurnster, @Parameter(optionality = Optionality.OPTIONAL) final String leeftijd, @Parameter(optionality = Optionality.OPTIONAL) final String kledingmaat, @Parameter(optionality = Optionality.OPTIONAL) final String lengte, @Parameter(optionality = Optionality.OPTIONAL) final Postuur postuur ){ return bestellingRepository.nieuweBestelling( this, naamTurnster, leeftijd, kledingmaat, lengte, postuur); } @Action(semantics = SemanticsOf.SAFE) @ActionLayout(contributed = Contributed.AS_ASSOCIATION) public List<Factuur> getFacturen(){ return factuurRepository.findByKlant(this); } @Action(semantics = SemanticsOf.IDEMPOTENT) public Klant wijzigKlant( final String naam, @Parameter(optionality = Optionality.OPTIONAL) final String email ){ setNaam(naam); setEmail(email); if (email!=null && !email.equals("")){ setUniqueId(getEmail().toLowerCase()); } else { setUniqueId(UUID.randomUUID().toString()); } return this; } public String default0WijzigKlant(){ return getNaam(); } public String default1WijzigKlant(){ return getEmail(); } public String validateWijzigKlant(final String naam, final String email){ if (email!=null) { Klant found = klantRepository.findUnique(email); if (email != null && found != null) { if (!found.equals(this)) { return "Er is al een klant met dit email adres"; } } } return null; } @Action(semantics = SemanticsOf.IDEMPOTENT) public Klant wijzigTelefoon( @Parameter(optionality = Optionality.OPTIONAL) final String telefoon1, @Parameter(optionality = Optionality.OPTIONAL) final String telefoon2 ){ setTelefoon1(telefoon1); setTelefoon2(telefoon2); return this; } public String default0WijzigTelefoon(){ return getTelefoon1(); } public String default1WijzigTelefoon(){ return getTelefoon2(); } @Action(semantics = SemanticsOf.IDEMPOTENT) public Klant wijzigAdres( @Parameter(optionality = Optionality.OPTIONAL) final String straat, @Parameter(optionality = Optionality.OPTIONAL) final String postcode, @Parameter(optionality = Optionality.OPTIONAL) final String plaats ){ setStraat(straat); setPostcode(postcode); setPlaats(plaats); zetPinOpGoogleMaps(); return this; } public String default0WijzigAdres(){ return getStraat(); } public String default1WijzigAdres(){ return getPostcode(); } public String default2WijzigAdres(){ return getPlaats(); } @Action(semantics = SemanticsOf.IDEMPOTENT) public Klant wijzigAantekening( @Parameter(optionality = Optionality.OPTIONAL) @ParameterLayout(multiLine = 5) final String aantekeningen ){ setAantekeningen(aantekeningen); return this; } public String default0WijzigAantekening(){ return getAantekeningen(); } @Programmatic public Klant zetPinOpGoogleMaps() { if (locationLookupService != null) { String zoekstring = new String(""); if (getStraat()!=null){ zoekstring = zoekstring.concat(getStraat()); } if (getPostcode()!=null){ zoekstring = zoekstring.concat(", ").concat(getPostcode()); } if (getPlaats()!=null){ zoekstring = zoekstring.concat(", ").concat(getPlaats()); } setLocation(locationLookupService.lookup(zoekstring)); } return this; } @Action(semantics = SemanticsOf.IDEMPOTENT) public MapsView zetPinOpGoogleMaps(final String adresgegevens){ setLocation(locationLookupService.lookup(adresgegevens)); return mapsViewRepository.nieuweMapsView(this); } public String default0ZetPinOpGoogleMaps(){ String zoekstring = new String(""); if (getStraat()!=null){ zoekstring = zoekstring.concat(getStraat()); } if (getPostcode()!=null){ zoekstring = zoekstring.concat(", ").concat(getPostcode()); } if (getPlaats()!=null){ zoekstring = zoekstring.concat(", ").concat(getPlaats()); } return zoekstring; } @Action(semantics = SemanticsOf.NON_IDEMPOTENT_ARE_YOU_SURE) public void verwijder(){ klantRepository.remove(this); } public boolean hideVerwijder(){ if (getBestellingen().size()<1 && getFacturen().size()<1){ return false; } return true; } @Override public int compareTo(final Klant other) { return org.apache.isis.applib.util.ObjectContracts .compare(this, other, "uniqueId"); } // Voor MailChimp integratie @Programmatic @Override public String getFirstName() { return StringUtils.firstNameOf(getNaam()); } @Programmatic @Override public String getLastName() { return StringUtils.lastNameOf(getNaam()); } @Programmatic @Override public String getEmailAddress() { return getEmail(); } @Programmatic @Override public Boolean excludeFromLists() { return getStuurGeenMailing(); } @Getter @Setter public static class KlantDto { public KlantDto(final Klant klant){ this.naam = klant.getNaam(); this.email = klant.getEmail(); this.straat = klant.getStraat(); this.postcode = klant.getPostcode(); this.plaats = klant.getPlaats(); } private String naam; private String email; private String straat; private String postcode; private String plaats; } @Inject BestellingRepository bestellingRepository; @Inject FactuurRepository factuurRepository; @Inject KlantRepository klantRepository; @Inject LocationLookupService locationLookupService; @Inject MapsViewRepository mapsViewRepository; @Inject CommunicatieRepository communicatieRepository; @Inject private InstellingenRepository instellingenRepository; }
williamclot/MemoryVisualizer
volatility/volatility/plugins/mac/machine_info.py
<filename>volatility/volatility/plugins/mac/machine_info.py # Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility 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. # # Volatility 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 Volatility. If not, see <http://www.gnu.org/licenses/>. # """ @author: <NAME> @license: GNU General Public License 2.0 @contact: <EMAIL> @organization: """ import volatility.obj as obj import volatility.plugins.mac.common as common class mac_machine_info(common.AbstractMacCommand): """ Prints machine information about the sample """ def calculate(self): common.set_plugin_members(self) machine_info = obj.Object("machine_info", offset = self.addr_space.profile.get_symbol("_machine_info"), vm = self.addr_space) yield machine_info def render_text(self, outfd, data): for machine_info in data: info = (("Major Version:", machine_info.major_version), ("Minor Version:", machine_info.minor_version), ("Memory Size:", machine_info.max_mem), ("Max CPUs:", machine_info.max_cpus), ("Physical CPUs:", machine_info.physical_cpu), ("Logical CPUs:", machine_info.logical_cpu), ) for i in info: outfd.write("{0:15} {1}\n".format(i[0], i[1]))
asanoviskhak/Outtalent
Leetcode/1114. Print in Order/solution2.py
class Foo: def __init__(self): self.flag2 = False self.flag3 = False def first(self, printFirst: 'Callable[[], None]') -> None: # printFirst() outputs "first". Do not change or remove this line. printFirst() self.flag2 = True def second(self, printSecond: 'Callable[[], None]') -> None: while self.flag2 == False: time.sleep(0.01) # printSecond() outputs "second". Do not change or remove this line. printSecond() self.flag3 = True def third(self, printThird: 'Callable[[], None]') -> None: while self.flag3 == False: time.sleep(0.01) # printThird() outputs "third". Do not change or remove this line. printThird()
rpachauri/connect4
connect_four/evaluation/incremental_victor/graph/graph_manager_test_6x6.py
<gh_stars>0 import unittest import gym import numpy as np from connect_four.envs import ConnectFourEnv from connect_four.evaluation.incremental_victor.graph.graph_manager import GraphManager from connect_four.evaluation.victor.rules import Claimeven, Vertical, Baseinverse, Before from connect_four.evaluation.incremental_victor.solution.victor_solution_manager import VictorSolutionManager from connect_four.evaluation.incremental_victor.solution import victor_solution from connect_four.evaluation.incremental_victor.solution.fake_solution_manager import FakeSolutionManager from connect_four.game import Square from connect_four.problem import Group as Problem, ConnectFourGroupManager @unittest.skip("deprecated") class TestGraphManager6x6(unittest.TestCase): def setUp(self) -> None: self.env = gym.make('connect_four-v0') ConnectFourEnv.M = 6 ConnectFourEnv.N = 6 self.env.reset() def test_find_chosen_set_6x6(self): # This test case is based on the example given in Section 10.1. self.env.state = np.array([ [ [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], ], [ [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], ], ]) # Define Rules that will be used as part of other Rules. claimeven_a1_a2 = Claimeven(lower=Square(row=5, col=0), upper=Square(row=4, col=0)) claimeven_b1_b2 = Claimeven(lower=Square(row=5, col=1), upper=Square(row=4, col=1)) vertical_c2_c3 = Vertical(lower=Square(row=4, col=2), upper=Square(row=3, col=2)) vertical_d2_d3 = Vertical(lower=Square(row=4, col=3), upper=Square(row=3, col=3)) claimeven_a3_a4 = Claimeven(lower=Square(row=3, col=0), upper=Square(row=2, col=0)) claimeven_b3_b4 = Claimeven(lower=Square(row=3, col=1), upper=Square(row=2, col=1)) vertical_c4_c5 = Vertical(lower=Square(row=2, col=2), upper=Square(row=1, col=2)) vertical_d4_d5 = Vertical(lower=Square(row=2, col=3), upper=Square(row=1, col=3)) claimeven_e1_e2 = Claimeven(lower=Square(row=5, col=4), upper=Square(row=4, col=4)) claimeven_e3_e4 = Claimeven(lower=Square(row=3, col=4), upper=Square(row=2, col=4)) claimeven_f1_f2 = Claimeven(lower=Square(row=5, col=5), upper=Square(row=4, col=5)) claimeven_f3_f4 = Claimeven(lower=Square(row=3, col=5), upper=Square(row=2, col=5)) # Define Rules that will be converted into Solutions. before_a1_a2_b1_b2_c2_c3_d2_d3 = victor_solution.from_before( Before( group=Problem(player=1, start=Square(row=4, col=0), end=Square(row=4, col=3)), # a2-d2 verticals=[vertical_c2_c3, vertical_d2_d3], claimevens=[claimeven_a1_a2, claimeven_b1_b2], ), ) before_a3_a4_b3_b4_c4_c5_d4_d5 = victor_solution.from_before( Before( group=Problem(player=1, start=Square(row=2, col=0), end=Square(row=2, col=3)), # a4-d4 verticals=[vertical_c4_c5, vertical_d4_d5], claimevens=[claimeven_a3_a4, claimeven_b3_b4], ), ) before_b1_b2_c2_c3_d2_d3_e1_e2 = victor_solution.from_before( Before( group=Problem(player=1, start=Square(row=4, col=1), end=Square(row=4, col=4)), # b2-e2 verticals=[vertical_c2_c3, vertical_d2_d3], claimevens=[claimeven_b1_b2, claimeven_e1_e2], ), ) before_b3_b4_c4_c5_d4_d5_e3_e4 = victor_solution.from_before( Before( group=Problem(player=1, start=Square(row=2, col=1), end=Square(row=2, col=4)), # b4-e4 verticals=[vertical_c4_c5, vertical_d4_d5], claimevens=[claimeven_b3_b4, claimeven_e3_e4], ), ) before_c2_c3_d2_d3_e1_e2_f1_f2 = victor_solution.from_before( Before( group=Problem(player=1, start=Square(row=4, col=2), end=Square(row=4, col=5)), # c2-f2 verticals=[vertical_c2_c3, vertical_d2_d3], claimevens=[claimeven_e1_e2, claimeven_f1_f2], ), ) before_c4_c5_d4_d5_e3_e4_f3_f4 = victor_solution.from_before( Before( group=Problem(player=1, start=Square(row=2, col=2), end=Square(row=2, col=5)), # c4-f4 verticals=[vertical_c4_c5, vertical_d4_d5], claimevens=[claimeven_e3_e4, claimeven_f3_f4], ), ) baseinverse_c1_d1 = victor_solution.from_baseinverse( Baseinverse( playable1=Square(row=5, col=2), # c1 playable2=Square(row=5, col=3), # d1 ), ) claimeven_a5_a6 = victor_solution.from_claimeven( Claimeven(lower=Square(row=1, col=0), upper=Square(row=0, col=0)), ) claimeven_b5_b6 = victor_solution.from_claimeven( Claimeven(lower=Square(row=1, col=1), upper=Square(row=0, col=1)), ) claimeven_e5_e6 = victor_solution.from_claimeven( Claimeven(lower=Square(row=1, col=4), upper=Square(row=0, col=4)), ) claimeven_f5_f6 = victor_solution.from_claimeven( Claimeven(lower=Square(row=1, col=5), upper=Square(row=0, col=5)), ) # Note that typically, for a given set of Solutions, there may be multiple subsets of Solutions that # solve all groups. # In this test case, the given VictorSolution set is the desired set so there is exactly one subset. solutions = { before_a1_a2_b1_b2_c2_c3_d2_d3, before_a3_a4_b3_b4_c4_c5_d4_d5, before_b1_b2_c2_c3_d2_d3_e1_e2, before_b3_b4_c4_c5_d4_d5_e3_e4, before_c2_c3_d2_d3_e1_e2_f1_f2, before_c4_c5_d4_d5_e3_e4_f3_f4, baseinverse_c1_d1, claimeven_a5_a6, claimeven_b5_b6, claimeven_e5_e6, claimeven_f5_f6, } problem_manager = ConnectFourGroupManager(env_variables=self.env.env_variables) fake_solution_manager = FakeSolutionManager(solutions=solutions) gm = GraphManager(player=0, problem_manager=problem_manager, solution_manager=fake_solution_manager) got_solutions = gm.evaluate() self.assertEqual(solutions, got_solutions) def test_evaluate_6x6(self): self.env.state = np.array([ [ [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], ], [ [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, ], ], ]) problem_manager = ConnectFourGroupManager(env_variables=self.env.env_variables) solution_manager = VictorSolutionManager(env_variables=self.env.env_variables) gm = GraphManager(player=0, problem_manager=problem_manager, solution_manager=solution_manager) got_evaluation = gm.evaluate() self.assertIsNotNone(got_evaluation) def test_evaluate_6x5_diagram_8_7_inverted(self): # This test case is based on an inverted version of Diagram 8.7. # White is to move and Black is trying to refute all of White's threats. self.env.state = np.array([ [ [0, 0, 0, 0, 0, 1, ], [0, 0, 0, 0, 1, 0, ], [0, 0, 0, 1, 0, 1, ], [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 1, 1, ], [0, 0, 1, 0, 1, 1, ], ], [ [0, 0, 0, 0, 0, 0, ], [0, 0, 0, 1, 0, 1, ], [0, 0, 0, 0, 1, 0, ], [0, 0, 0, 1, 1, 1, ], [0, 0, 0, 1, 0, 0, ], [0, 0, 0, 1, 0, 0, ], ], ]) problem_manager = ConnectFourGroupManager(env_variables=self.env.env_variables) solution_manager = VictorSolutionManager(env_variables=self.env.env_variables) gm = GraphManager(player=0, problem_manager=problem_manager, solution_manager=solution_manager) got_evaluation = gm.evaluate() self.assertIsNotNone(got_evaluation) if __name__ == '__main__': unittest.main()
Fillo7/KTT
Source/Api/Output/ComputationResult.cpp
<gh_stars>10-100 #include <limits> #include <Api/Output/ComputationResult.h> #include <Api/KttException.h> namespace ktt { ComputationResult::ComputationResult() : m_Duration(InvalidDuration), m_Overhead(InvalidDuration) {} ComputationResult::ComputationResult(const std::string& kernelFunction) : m_KernelFunction(kernelFunction), m_Duration(InvalidDuration), m_Overhead(InvalidDuration) {} ComputationResult::ComputationResult(const ComputationResult& other) : m_KernelFunction(other.m_KernelFunction), m_GlobalSize(other.m_GlobalSize), m_LocalSize(other.m_LocalSize), m_Duration(other.m_Duration), m_Overhead(other.m_Overhead) { if (other.HasCompilationData()) { m_CompilationData = std::make_unique<KernelCompilationData>(*other.m_CompilationData); } if (other.HasProfilingData()) { m_ProfilingData = std::make_unique<KernelProfilingData>(*other.m_ProfilingData); } } void ComputationResult::SetDurationData(const Nanoseconds duration, const Nanoseconds overhead) { m_Duration = duration; m_Overhead = overhead; } void ComputationResult::SetSizeData(const DimensionVector& globalSize, const DimensionVector& localSize) { m_GlobalSize = globalSize; m_LocalSize = localSize; } void ComputationResult::SetCompilationData(std::unique_ptr<KernelCompilationData> data) { m_CompilationData = std::move(data); } void ComputationResult::SetProfilingData(std::unique_ptr<KernelProfilingData> data) { m_ProfilingData = std::move(data); } const std::string& ComputationResult::GetKernelFunction() const { return m_KernelFunction; } const DimensionVector& ComputationResult::GetGlobalSize() const { return m_GlobalSize; } const DimensionVector& ComputationResult::GetLocalSize() const { return m_LocalSize; } Nanoseconds ComputationResult::GetDuration() const { return m_Duration; } Nanoseconds ComputationResult::GetOverhead() const { return m_Overhead; } bool ComputationResult::HasCompilationData() const { return m_CompilationData != nullptr; } const KernelCompilationData& ComputationResult::GetCompilationData() const { if (!HasCompilationData()) { throw KttException("Kernel compilation data can only be retrieved after prior check that it exists"); } return *m_CompilationData; } bool ComputationResult::HasProfilingData() const { return m_ProfilingData != nullptr; } const KernelProfilingData& ComputationResult::GetProfilingData() const { if (!HasProfilingData()) { throw KttException("Kernel profiling data can only be retrieved after prior check that it exists"); } return *m_ProfilingData; } bool ComputationResult::HasRemainingProfilingRuns() const { if (!HasProfilingData()) { return false; } return GetProfilingData().HasRemainingProfilingRuns(); } ComputationResult& ComputationResult::operator=(const ComputationResult& other) { m_KernelFunction = other.m_KernelFunction; m_Duration = other.m_Duration; m_Overhead = other.m_Overhead; m_GlobalSize = other.m_GlobalSize; m_LocalSize = other.m_LocalSize; if (other.HasCompilationData()) { m_CompilationData = std::make_unique<KernelCompilationData>(*other.m_CompilationData); } if (other.HasProfilingData()) { m_ProfilingData = std::make_unique<KernelProfilingData>(*other.m_ProfilingData); } return *this; } } // namespace ktt
pfinashx/openvino
src/inference/include/ie/vpu/hddl_config.hpp
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /** * @brief A header that defines advanced related properties for HDDL plugin. * These properties should be used in SetConfig() and LoadNetwork() methods of plugins * * @file hddl_config.hpp */ #pragma once #include "vpu_config.hpp" namespace InferenceEngine { namespace Metrics { /** * @brief Metric to get a int of the device number, String value is METRIC_HDDL_DEVICE_NUM */ DECLARE_METRIC_KEY(HDDL_DEVICE_NUM, int); /** * @brief Metric to get a std::vector<std::string> of device names, String value is METRIC_HDDL_DEVICE_NAME */ DECLARE_METRIC_KEY(HDDL_DEVICE_NAME, std::vector<std::string>); /** * @brief Metric to get a std::vector<float> of device thermal, String value is METRIC_HDDL_DEVICE_THERMAL */ DECLARE_METRIC_KEY(HDDL_DEVICE_THERMAL, std::vector<float>); /** * @brief Metric to get a std::vector<uint32> of device ids, String value is METRIC_HDDL_DEVICE_ID */ DECLARE_METRIC_KEY(HDDL_DEVICE_ID, std::vector<unsigned int>); /** * @brief Metric to get a std::vector<int> of device subclasses, String value is METRIC_HDDL_DEVICE_SUBCLASS */ DECLARE_METRIC_KEY(HDDL_DEVICE_SUBCLASS, std::vector<int>); /** * @brief Metric to get a std::vector<uint32> of device total memory, String value is METRIC_HDDL_MEMORY_TOTAL */ DECLARE_METRIC_KEY(HDDL_DEVICE_MEMORY_TOTAL, std::vector<unsigned int>); /** * @brief Metric to get a std::vector<uint32> of device used memory, String value is METRIC_HDDL_DEVICE_MEMORY_USED */ DECLARE_METRIC_KEY(HDDL_DEVICE_MEMORY_USED, std::vector<unsigned int>); /** * @brief Metric to get a std::vector<float> of device utilization, String value is METRIC_HDDL_DEVICE_UTILIZATION */ DECLARE_METRIC_KEY(HDDL_DEVICE_UTILIZATION, std::vector<float>); /** * @brief Metric to get a std::vector<std::string> of stream ids, String value is METRIC_HDDL_DEVICE_STREAM_ID */ DECLARE_METRIC_KEY(HDDL_STREAM_ID, std::vector<std::string>); /** * @brief Metric to get a std::vector<std::string> of device tags, String value is METRIC_HDDL_DEVICE_TAG */ DECLARE_METRIC_KEY(HDDL_DEVICE_TAG, std::vector<std::string>); /** * @brief Metric to get a std::vector<int> of group ids, String value is METRIC_HDDL_GROUP_ID */ DECLARE_METRIC_KEY(HDDL_GROUP_ID, std::vector<int>); /** * @brief Metric to get a int number of device be using for group, String value is METRIC_HDDL_DEVICE_GROUP_USING_NUM */ DECLARE_METRIC_KEY(HDDL_DEVICE_GROUP_USING_NUM, int); /** * @brief Metric to get a int number of total device, String value is METRIC_HDDL_DEVICE_TOTAL_NUM */ DECLARE_METRIC_KEY(HDDL_DEVICE_TOTAL_NUM, int); } // namespace Metrics /** * @brief [Only for HDDLPlugin] * Type: Arbitrary non-empty string. If empty (""), equals no set, default: ""; * This option allows to specify the number of MYX devices used for inference a specific Executable network. * Note: Only one network would be allocated to one device. * The number of devices for the tag is specified in the hddl_service.config file. * Example: * "service_settings": * { * "graph_tag_map": * { * "tagA":3 * } * } * It means that an executable network marked with tagA will be executed on 3 devices */ DECLARE_VPU_CONFIG(HDDL_GRAPH_TAG); /** * @brief [Only for HDDLPlugin] * Type: Arbitrary non-empty string. If empty (""), equals no set, default: ""; * This config makes the executable networks to be allocated on one certain device (instead of multiple devices). * And all inference through this executable network, will be done on this device. * Note: Only one network would be allocated to one device. * The number of devices which will be used for stream-affinity must be specified in hddl_service.config file. * Example: * "service_settings": * { * "stream_device_number":5 * } * It means that 5 device will be used for stream-affinity */ DECLARE_VPU_CONFIG(HDDL_STREAM_ID); /** * @brief [Only for HDDLPlugin] * Type: Arbitrary non-empty string. If empty (""), equals no set, default: ""; * This config allows user to control device flexibly. This config gives a "tag" for a certain device while * allocating a network to it. Afterward, user can allocating/deallocating networks to this device with this "tag". * Devices used for such use case is controlled by a so-called "Bypass Scheduler" in HDDL backend, and the number * of such device need to be specified in hddl_service.config file. * Example: * "service_settings": * { * "bypass_device_number": 5 * } * It means that 5 device will be used for Bypass scheduler. */ DECLARE_VPU_CONFIG(HDDL_DEVICE_TAG); /** * @brief [Only for HDDLPlugin] * Type: "YES/NO", default is "NO". * This config is a sub-config of DEVICE_TAG, and only available when "DEVICE_TAG" is set. After a user load a * network, the user got a handle for the network. * If "YES", the network allocated is bind to the device (with the specified "DEVICE_TAG"), which means all afterwards * inference through this network handle will be executed on this device only. * If "NO", the network allocated is not bind to the device (with the specified "DEVICE_TAG"). If the same network * is allocated on multiple other devices (also set BIND_DEVICE to "False"), then inference through any handle of these * networks may be executed on any of these devices those have the network loaded. */ DECLARE_VPU_CONFIG(HDDL_BIND_DEVICE); /** * @brief [Only for HDDLPlugin] * Type: A signed int wrapped in a string, default is "0". * This config is a sub-config of DEVICE_TAG, and only available when "DEVICE_TAG" is set and "BIND_DEVICE" is "False". * When there are multiple devices running a certain network (a same network running on multiple devices in Bypass * Scheduler), the device with a larger number has a higher priority, and more inference tasks will be fed to it with * priority. */ DECLARE_VPU_CONFIG(HDDL_RUNTIME_PRIORITY); /** * @brief [Only for HDDLPlugin] * Type: "YES/NO", default is "NO". * SGAD is short for "Single Graph All Device". With this scheduler, once application allocates 1 network, all devices * (managed by SGAD scheduler) will be loaded with this graph. The number of network that can be loaded to one device * can exceed one. Once application deallocates 1 network from device, all devices will unload the network from them. */ DECLARE_VPU_CONFIG(HDDL_USE_SGAD); /** * @brief [Only for HDDLPlugin] * Type: A signed int wrapped in a string, default is "0". * This config gives a "group id" for a certain device when this device has been reserved for certain client, client * can use this device grouped by calling this group id while other client can't use this device * Each device has their own group id. Device in one group shares same group id. */ DECLARE_VPU_CONFIG(HDDL_GROUP_DEVICE); } // namespace InferenceEngine
SolidRun/edk2-platforms
Silicon/NXP/Include/Library/Dpaa2McInterfaceLib/fsl_dpmac.h
/* Copyright 2017 NXP * * 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 above-listed copyright holders nor the * names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") as published by the Free Software * Foundation, either version 2 of that License or (at your option) any * later version. * * 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 HOLDERS 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. */ #ifndef __FSL_DPMAC_H #define __FSL_DPMAC_H /* Data Path MAC API * Contains initialization APIs and runtime control APIs for DPMAC */ struct fsl_mc_io; /** * dpmac_open() - Open a control session for the specified object. * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @dpmac_id: DPMAC unique ID * @token: Returned token; use in subsequent API calls * * This function can be used to open a control session for an * already created object; an object may have been declared in * the DPL or by calling the dpmac_create function. * This function returns a unique authentication token, * associated with the specific object ID and the specific MC * portal; this token must be used in all subsequent commands for * this specific object * * Return: '0' on Success; Error code otherwise. */ int dpmac_open(struct fsl_mc_io *mc_io, uint32_t cmd_flags, int dpmac_id, uint16_t *token); /** * dpmac_close() - Close the control session of the object * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * * After this function is called, no further operations are * allowed on the object without opening a new control session. * * Return: '0' on Success; Error code otherwise. */ int dpmac_close(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token); /** * enum dpmac_link_type - DPMAC link type * @DPMAC_LINK_TYPE_NONE: No link * @DPMAC_LINK_TYPE_FIXED: Link is fixed type * @DPMAC_LINK_TYPE_PHY: Link by PHY ID * @DPMAC_LINK_TYPE_BACKPLANE: Backplane link type */ enum dpmac_link_type { DPMAC_LINK_TYPE_NONE, DPMAC_LINK_TYPE_FIXED, DPMAC_LINK_TYPE_PHY, DPMAC_LINK_TYPE_BACKPLANE }; /** * enum dpmac_eth_if - DPMAC Ethrnet interface * @DPMAC_ETH_IF_MII: MII interface * @DPMAC_ETH_IF_RMII: RMII interface * @DPMAC_ETH_IF_SMII: SMII interface * @DPMAC_ETH_IF_GMII: GMII interface * @DPMAC_ETH_IF_RGMII: RGMII interface * @DPMAC_ETH_IF_SGMII: SGMII interface * @DPMAC_ETH_IF_QSGMII: QSGMII interface * @DPMAC_ETH_IF_XAUI: XAUI interface * @DPMAC_ETH_IF_XFI: XFI interface */ enum dpmac_eth_if { DPMAC_ETH_IF_MII, DPMAC_ETH_IF_RMII, DPMAC_ETH_IF_SMII, DPMAC_ETH_IF_GMII, DPMAC_ETH_IF_RGMII, DPMAC_ETH_IF_SGMII, DPMAC_ETH_IF_QSGMII, DPMAC_ETH_IF_XAUI, DPMAC_ETH_IF_XFI }; /** * struct dpmac_cfg - Structure representing DPMAC configuration * @mac_id: Represents the Hardware MAC ID; in case of multiple WRIOP, * the MAC IDs are continuous. * For example: 2 WRIOPs, 16 MACs in each: * MAC IDs for the 1st WRIOP: 1-16, * MAC IDs for the 2nd WRIOP: 17-32. */ struct dpmac_cfg { int mac_id; }; /** * dpmac_create() - Create the DPMAC object. * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @cfg: Configuration structure * @token: Returned token; use in subsequent API calls * * Create the DPMAC object, allocate required resources and * perform required initialization. * * The object can be created either by declaring it in the * DPL file, or by calling this function. * This function returns a unique authentication token, * associated with the specific object ID and the specific MC * portal; this token must be used in all subsequent calls to * this specific object. For objects that are created using the * DPL file, call dpmac_open function to get an authentication * token first. * * Return: '0' on Success; Error code otherwise. */ int dpmac_create(struct fsl_mc_io *mc_io, uint32_t cmd_flags, const struct dpmac_cfg *cfg, uint16_t *token); /** * dpmac_destroy() - Destroy the DPMAC object and release all its resources. * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * * Return: '0' on Success; error code otherwise. */ int dpmac_destroy(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token); /** * DPMAC IRQ Index and Events */ /** * IRQ index */ #define DPMAC_IRQ_INDEX 0 /** * IRQ event - indicates a change in link state */ #define DPMAC_IRQ_EVENT_LINK_CFG_REQ 0x00000001 /** * IRQ event - Indicates that the link state changed */ #define DPMAC_IRQ_EVENT_LINK_CHANGED 0x00000002 /** * struct dpmac_irq_cfg - IRQ configuration * @addr: Address that must be written to signal a message-based interrupt * @val: Value to write into irq_addr address * @irq_num: A user defined number associated with this IRQ */ struct dpmac_irq_cfg { uint64_t addr; uint32_t val; int irq_num; }; /** * dpmac_set_irq() - Set IRQ information for the DPMAC to trigger an interrupt. * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @irq_index: Identifies the interrupt index to configure * @irq_cfg: IRQ configuration * * Return: '0' on Success; Error code otherwise. */ int dpmac_set_irq(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, uint8_t irq_index, struct dpmac_irq_cfg *irq_cfg); /** * dpmac_get_irq() - Get IRQ information from the DPMAC. * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @irq_index: The interrupt index to configure * @type: Interrupt type: 0 represents message interrupt * type (both irq_addr and irq_val are valid) * @irq_cfg: IRQ attributes * * Return: '0' on Success; Error code otherwise. */ int dpmac_get_irq(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, uint8_t irq_index, int *type, struct dpmac_irq_cfg *irq_cfg); /** * dpmac_set_irq_enable() - Set overall interrupt state. * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @irq_index: The interrupt index to configure * @en: Interrupt state - enable = 1, disable = 0 * * Allows GPP software to control when interrupts are generated. * Each interrupt can have up to 32 causes. The enable/disable control's the * overall interrupt state. if the interrupt is disabled no causes will cause * an interrupt. * * Return: '0' on Success; Error code otherwise. */ int dpmac_set_irq_enable(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, uint8_t irq_index, uint8_t en); /** * dpmac_get_irq_enable() - Get overall interrupt state * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of D<PASSWORD> object * @irq_index: The interrupt index to configure * @en: Returned interrupt state - enable = 1, disable = 0 * * Return: '0' on Success; Error code otherwise. */ int dpmac_get_irq_enable(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, uint8_t irq_index, uint8_t *en); /** * dpmac_set_irq_mask() - Set interrupt mask. * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of D<PASSWORD> object * @irq_index: The interrupt index to configure * @mask: Event mask to trigger interrupt; * each bit: * 0 = ignore event * 1 = consider event for asserting IRQ * * Every interrupt can have up to 32 causes and the interrupt model supports * masking/unmasking each cause independently * * Return: '0' on Success; Error code otherwise. */ int dpmac_set_irq_mask(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, uint8_t irq_index, uint32_t mask); /** * dpmac_get_irq_mask() - Get interrupt mask. * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @irq_index: The interrupt index to configure * @mask: Returned event mask to trigger interrupt * * Every interrupt can have up to 32 causes and the interrupt model supports * masking/unmasking each cause independently * * Return: '0' on Success; Error code otherwise. */ int dpmac_get_irq_mask(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, uint8_t irq_index, uint32_t *mask); /** * dpmac_get_irq_status() - Get the current status of any pending interrupts. * * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @irq_index: The interrupt index to configure * @status: Returned interrupts status - one bit per cause: * 0 = no interrupt pending * 1 = interrupt pending * * Return: '0' on Success; Error code otherwise. */ int dpmac_get_irq_status(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, uint8_t irq_index, uint32_t *status); /** * dpmac_clear_irq_status() - Clear a pending interrupt's status * * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @irq_index: The interrupt index to configure * @status: Bits to clear (W1C) - one bit per cause: * 0 = don't change * 1 = clear status bit * * Return: '0' on Success; Error code otherwise. */ int dpmac_clear_irq_status(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, uint8_t irq_index, uint32_t status); /** * struct dpmac_attr - Structure representing DPMAC attributes * @id: DPMAC object ID * @phy_id: PHY ID * @link_type: link type * @eth_if: Ethernet interface * @max_rate: Maximum supported rate - in Mbps * @version: DPMAC version */ struct dpmac_attr { int id; int phy_id; enum dpmac_link_type link_type; enum dpmac_eth_if eth_if; uint32_t max_rate; /** * struct version - Structure representing DPMAC version * @major: DPMAC major version * @minor: DPMAC minor version */ struct { uint16_t major; uint16_t minor; } version; }; /** * dpmac_get_attributes - Retrieve DPMAC attributes. * * @mc_io: Pointer to MC portal's I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @attr: Returned object's attributes * * Return: '0' on Success; Error code otherwise. */ int dpmac_get_attributes(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, struct dpmac_attr *attr); /** * struct dpmac_mdio_cfg - DPMAC MDIO read/write parameters * @phy_addr: MDIO device address * @reg: Address of the register within the Clause 45 PHY device from which data * is to be read * @data: Data read/write from/to MDIO */ struct dpmac_mdio_cfg { uint8_t phy_addr; uint8_t reg; uint16_t data; }; /** * dpmac_mdio_read() - Perform MDIO read transaction * @mc_io: Pointer to opaque I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @cfg: Structure with MDIO transaction parameters * * Return: '0' on Success; Error code otherwise. */ int dpmac_mdio_read(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, struct dpmac_mdio_cfg *cfg); /** * dpmac_mdio_write() - Perform MDIO write transaction * @mc_io: Pointer to opaque I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @cfg: Structure with MDIO transaction parameters * * Return: '0' on Success; Error code otherwise. */ int dpmac_mdio_write(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, struct dpmac_mdio_cfg *cfg); /** * DPMAC link configuration/state options */ /** * Enable auto-negotiation */ #define DPMAC_LINK_OPT_AUTONEG 0x0000000000000001ULL /** * Enable half-duplex mode */ #define DPMAC_LINK_OPT_HALF_DUPLEX 0x0000000000000002ULL /** * Enable pause frames */ #define DPMAC_LINK_OPT_PAUSE 0x0000000000000004ULL /** * Enable a-symmetric pause frames */ #define DPMAC_LINK_OPT_ASYM_PAUSE 0x0000000000000008ULL /** * struct dpmac_link_cfg - Structure representing DPMAC link configuration * @rate: Link's rate - in Mbps * @options: Enable/Disable DPMAC link cfg features (bitmap) */ struct dpmac_link_cfg { uint32_t rate; uint64_t options; }; /** * dpmac_get_link_cfg() - Get Ethernet link configuration * @mc_io: Pointer to opaque I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @cfg: Returned structure with the link configuration * * Return: '0' on Success; Error code otherwise. */ int dpmac_get_link_cfg(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, struct dpmac_link_cfg *cfg); /** * struct dpmac_link_state - DPMAC link configuration request * @rate: Rate in Mbps * @options: Enable/Disable DPMAC link cfg features (bitmap) * @up: Link state */ struct dpmac_link_state { uint32_t rate; uint64_t options; int up; }; /** * dpmac_set_link_state() - Set the Ethernet link status * @mc_io: Pointer to opaque I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @link_state: Link state configuration * * Return: '0' on Success; Error code otherwise. */ int dpmac_set_link_state(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, struct dpmac_link_state *link_state); /** * enum dpmac_counter - DPMAC counter types * @DPMAC_CNT_ING_FRAME_64: counts 64-bytes frames, good or bad. * @DPMAC_CNT_ING_FRAME_127: counts 65- to 127-bytes frames, good or bad. * @DPMAC_CNT_ING_FRAME_255: counts 128- to 255-bytes frames, good or bad. * @DPMAC_CNT_ING_FRAME_511: counts 256- to 511-bytes frames, good or bad. * @DPMAC_CNT_ING_FRAME_1023: counts 512- to 1023-bytes frames, good or bad. * @DPMAC_CNT_ING_FRAME_1518: counts 1024- to 1518-bytes frames, good or bad. * @DPMAC_CNT_ING_FRAME_1519_MAX: counts 1519-bytes frames and larger * (up to max frame length specified), * good or bad. * @DPMAC_CNT_ING_FRAG: counts frames which are shorter than 64 bytes received * with a wrong CRC * @DPMAC_CNT_ING_JABBER: counts frames longer than the maximum frame length * specified, with a bad frame check sequence. * @DPMAC_CNT_ING_FRAME_DISCARD: counts dropped frames due to internal errors. * Occurs when a receive FIFO overflows. * Includes also frames truncated as a result of * the receive FIFO overflow. * @DPMAC_CNT_ING_ALIGN_ERR: counts frames with an alignment error * (optional used for wrong SFD). * @DPMAC_CNT_EGR_UNDERSIZED: counts frames transmitted that was less than 64 * bytes long with a good CRC. * @DPMAC_CNT_ING_OVERSIZED: counts frames longer than the maximum frame length * specified, with a good frame check sequence. * @DPMAC_CNT_ING_VALID_PAUSE_FRAME: counts valid pause frames (regular and PFC) * @DPMAC_CNT_EGR_VALID_PAUSE_FRAME: counts valid pause frames transmitted * (regular and PFC). * @DPMAC_CNT_ING_BYTE: counts bytes received except preamble for all valid * frames and valid pause frames. * @DPMAC_CNT_ING_MCAST_FRAME: counts received multicast frames. * @DPMAC_CNT_ING_BCAST_FRAME: counts received broadcast frames. * @DPMAC_CNT_ING_ALL_FRAME: counts each good or bad frames received. * @DPMAC_CNT_ING_UCAST_FRAME: counts received unicast frames. * @DPMAC_CNT_ING_ERR_FRAME: counts frames received with an error * (except for undersized/fragment frame). * @DPMAC_CNT_EGR_BYTE: counts bytes transmitted except preamble for all valid * frames and valid pause frames transmitted. * @DPMAC_CNT_EGR_MCAST_FRAME: counts transmitted multicast frames. * @DPMAC_CNT_EGR_BCAST_FRAME: counts transmitted broadcast frames. * @DPMAC_CNT_EGR_UCAST_FRAME: counts transmitted unicast frames. * @DPMAC_CNT_EGR_ERR_FRAME: counts frames transmitted with an error. * @DPMAC_CNT_ING_GOOD_FRAME: counts frames received without error, including * pause frames. * @DPMAC_CNT_ENG_GOOD_FRAME: counts frames transmitted without error, including * pause frames. */ enum dpmac_counter { DPMAC_CNT_ING_FRAME_64, DPMAC_CNT_ING_FRAME_127, DPMAC_CNT_ING_FRAME_255, DPMAC_CNT_ING_FRAME_511, DPMAC_CNT_ING_FRAME_1023, DPMAC_CNT_ING_FRAME_1518, DPMAC_CNT_ING_FRAME_1519_MAX, DPMAC_CNT_ING_FRAG, DPMAC_CNT_ING_JABBER, DPMAC_CNT_ING_FRAME_DISCARD, DPMAC_CNT_ING_ALIGN_ERR, DPMAC_CNT_EGR_UNDERSIZED, DPMAC_CNT_ING_OVERSIZED, DPMAC_CNT_ING_VALID_PAUSE_FRAME, DPMAC_CNT_EGR_VALID_PAUSE_FRAME, DPMAC_CNT_ING_BYTE, DPMAC_CNT_ING_MCAST_FRAME, DPMAC_CNT_ING_BCAST_FRAME, DPMAC_CNT_ING_ALL_FRAME, DPMAC_CNT_ING_UCAST_FRAME, DPMAC_CNT_ING_ERR_FRAME, DPMAC_CNT_EGR_BYTE, DPMAC_CNT_EGR_MCAST_FRAME, DPMAC_CNT_EGR_BCAST_FRAME, DPMAC_CNT_EGR_UCAST_FRAME, DPMAC_CNT_EGR_ERR_FRAME, DPMAC_CNT_ING_GOOD_FRAME, DPMAC_CNT_ENG_GOOD_FRAME }; /** * dpmac_get_counter() - Read a specific DPMAC counter * @mc_io: Pointer to opaque I/O object * @cmd_flags: Command flags; one or more of 'MC_CMD_FLAG_' * @token: Token of DPMAC object * @type: The requested counter * @counter: Returned counter value * * Return: The requested counter; '0' otherwise. */ int dpmac_get_counter(struct fsl_mc_io *mc_io, uint32_t cmd_flags, uint16_t token, enum dpmac_counter type, uint64_t *counter); #endif /* __FSL_DPMAC_H */
SergeyKrivohatskiy/tiny_database
src/ru/spbau/tinydb/btree/Node.java
package ru.spbau.tinydb.btree; import java.util.Iterator; import ru.spbau.tinydb.bufferManager.BufferManager; import ru.spbau.tinydb.bufferManager.BufferView; public abstract class Node { // View: // 0b | 4b | 8b | 12b // Type | Size | link(next leaf or right subtree) | (key, data(left subtree or value)) private static final int DATA_OFFSET = 12; private static final int DATA_SIZE = (int) (BufferManager.PAGE_SIZE - DATA_OFFSET); protected static final int N = Node.DATA_SIZE / 8; protected final int pageIndex; protected final BufferManager bm; public Node(int pageIndex, BufferManager bm) { this.pageIndex = pageIndex; this.bm = bm; } protected BufferView getDataView() { BufferView pageView = bm.getPage(pageIndex); BufferView dataVIew = pageView.getSubView(DATA_OFFSET, DATA_SIZE); pageView.close(); return dataVIew; } abstract public Iterator<BxTreeEntry> find(int key, boolean includeKey); // returns null if no split, otherwise returns split info abstract public Split insert(int key, int value); protected int getSize() { return getInt(pageIndex, bm, 4); } protected void setSize(int size) { setInt(pageIndex, bm, 4, size); } protected int getLink() { return getInt(pageIndex, bm, 8); } protected void setLink(int value) { setInt(pageIndex, bm, 8, value); } protected int getType() { return getType(pageIndex, bm); } /** * * @param key * @param include * @return index of first elem >(or >=) key or Size if not found */ protected int findKey(int key, boolean include) { int index = 0; int size = getSize(); BufferView dataView = getDataView(); for(; index < size; index ++) { int current = dataView.getInt(8 * index); if((include && current >= key) || (!include && current > key)) { break; } } dataView.close(); return index; } protected int getKey(int index) { return getInt(pageIndex, bm, DATA_OFFSET + 8 * index); } protected int getData(int index) { return getInt(pageIndex, bm, DATA_OFFSET + 8 * index + 4); } protected void setData(int index, int value) { setInt(pageIndex, bm, DATA_OFFSET + 8 * index + 4, value); } protected void insert(int index, int key, int data) { int size = getSize(); if(size == N) { throw new IllegalStateException(); } BufferView dataView = getDataView(); // |...|...|.| => |...|.|...| for(int i = size; i > index; i --) { dataView.setInt(8 * i, dataView.getInt(8 * (i - 1))); dataView.setInt(8 * i + 4, dataView.getInt(8 * (i - 1) + 4)); } dataView.setInt(8 * index, key); dataView.setInt(8 * index + 4, data); dataView.setChanged(); dataView.close(); setSize(size + 1); } protected void setIndexType() { setInt(pageIndex, bm, 0, 1); } public int getPageIndex() { return pageIndex; } /** * * @param pageIndex * @param bm * @return 0 if leafNode */ protected static int getType(int pageIndex, BufferManager bm) { return getInt(pageIndex, bm, 0); } private static int getInt(int pageIndex, BufferManager bm, int offset) { BufferView pageView = bm.getPage(pageIndex); int value = pageView.getInt(offset); pageView.close(); return value; } private static void setInt(int pageIndex, BufferManager bm, int offset, int value) { BufferView pageView = bm.getPage(pageIndex); pageView.setInt(offset, value); pageView.setChanged(); pageView.close(); } public static Node loadNode(int pageIndex, BufferManager bm) { if(getType(pageIndex, bm) == 0) { return new LeafNode(pageIndex, bm); } else { return new IndexNode(pageIndex, bm); } } }
lucasportella/learning_repo
python-codes/m2_curso_em_video_estruturas_de_controle/ex051.1.py
a1=int(input('Primeiro termo: ')) r=int(input('Razão: ')) print('Os 10 primeiros termos da PA são: \n{}->'.format(a1),end=' ') for c in range(a1,(a1+9*r),r): a1 = a1 + r print(a1, end=' -> ') print('FIM')
CUITCHE/CHE.Network.cpp
CHE/io/HByteConvert.cpp
#include "HByteConvert.h" #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <cassert> CHE_NAMESPACE_BEGIN DATATYPESET HByteConvert::_convertDataTypeCollection; string HByteConvert::ws2s(const wstring &ws) { string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C"; setlocale(LC_ALL, "chs"); const wchar_t* _Source = ws.c_str(); size_t _Dsize = 2 * ws.size() + 1; char *_Dest = new char[_Dsize]; assert(_Dest != NULL); CheZeroMemory(_Dest, _Dsize); uint32 returnValue(0); wcstombs_s(&returnValue, _Dest, _Dsize, _Source, _TRUNCATE); string result = _Dest; delete[]_Dest; setlocale(LC_ALL, curLocale.c_str()); return (result); } wstring HByteConvert::s2ws(const string &s) { setlocale(LC_ALL, "chs"); const char* _Source = s.c_str(); size_t _Dsize = s.size() + 1; wchar_t *_Dest = new wchar_t[_Dsize]; assert(_Dest != NULL); CheZeroMemory(_Dest, _Dsize); uint32 returnValue(0); mbstowcs_s(&returnValue, _Dest, _Dsize, _Source, _TRUNCATE); std::wstring result = _Dest; delete[] _Dest; setlocale(LC_ALL, "C"); return (result); } /* const byte* HByteConvert::shortToByte(const short data) { // // byte *pBuf = new byte[2]; // assert(pBuf != NULL); // // pBuf[0] = (byte)((data & 0xff00) >> 8); // pBuf[1] = (byte)(data & 0x00ff); _convertDataTypeCollection = data; return _convertDataTypeCollection; } void HByteConvert::shortToByte(const short data, byte *pBuf) { assert(pBuf != NULL); // // pBuf[0] = (byte)((data & 0xff00) >> 8); // pBuf[1] = (byte)(data & 0x00ff); _convertDataTypeCollection = data; memcpy2(pBuf, _convertDataTypeCollection); } short HByteConvert::byteToShort(const byte *pBuf) { assert(pBuf != NULL); // // short high = (short)((pBuf[0] << 8) & 0xff00); // short low = (short)(pBuf[1] & 0xff); // short t = high | low; _convertDataTypeCollection.memcpy2(pBuf); return _convertDataTypeCollection; } byte* HByteConvert::intToByte(const int data) { // // byte *pBuf = new byte[4]; // assert(pBuf != NULL); // // pBuf[3] = (byte)((data & 0xff)); // pBuf[2] = (byte)((data & 0xff00) >> 8); // pBuf[1] = (byte)((data & 0xff0000) >> 16); // pBuf[0] = (byte)((data & 0xff000000) >> 24); _convertDataTypeCollection = data; return _convertDataTypeCollection; } void HByteConvert::intToByte(const int data, byte *pBuf) { assert(pBuf != NULL); // pBuf[3] = (byte)((data & 0xff)); // pBuf[2] = (byte)((data & 0xff00) >> 8); // pBuf[1] = (byte)((data & 0xff0000) >> 16); // pBuf[0] = (byte)((data & 0xff000000) >> 24); _convertDataTypeCollection = data; memcpy4(pBuf, _convertDataTypeCollection); } int HByteConvert::byteToInt(const byte *pBuf) { assert(pBuf != NULL); // // int h24 = pBuf[0] << 24 & 0xff000000; // int h16 = pBuf[1] << 16 & 0xff0000; // int l8 = pBuf[2] << 8 & 0xff00; // int l = pBuf[3] & 0xff; // // int t = h24 | h16 | l8 | l; _convertDataTypeCollection.memcpy4(pBuf); return _convertDataTypeCollection; } byte* HByteConvert::long64ToByte(const long long &data) { // byte *pBuf = new byte[8]; // assert(pBuf != NULL); // // pBuf[7] = (byte)(data & 0xffL); // pBuf[6] = (byte)((data & 0xff00L) >> 8); // pBuf[5] = (byte)((data & 0xff0000L) >> 16); // pBuf[4] = (byte)((data & 0xff000000L) >> 24); // pBuf[3] = (byte)((data & 0xff00000000L) >> 32); // pBuf[2] = (byte)((data & 0xff0000000000L) >> 40); // pBuf[1] = (byte)((data & 0xff000000000000L) >> 48); // pBuf[0] = (byte)((data & 0xff00000000000000L) >> 56); _convertDataTypeCollection = data; return _convertDataTypeCollection; } void HByteConvert::long64ToByte(const long long &data, byte *pBuf) { assert(pBuf != NULL); // pBuf[7] = (byte)(data & 0xffL); // pBuf[6] = (byte)((data & 0xff00L) >> 8); // pBuf[5] = (byte)((data & 0xff0000L) >> 16); // pBuf[4] = (byte)((data & 0xff000000L) >> 24); // pBuf[3] = (byte)((data & 0xff00000000L) >> 32); // pBuf[2] = (byte)((data & 0xff0000000000L) >> 40); // pBuf[1] = (byte)((data & 0xff000000000000L) >> 48); // pBuf[0] = (byte)((data & 0xff00000000000000L) >> 56); _convertDataTypeCollection = data; memcpy8(pBuf, _convertDataTypeCollection); } long long HByteConvert::byteToLong64(const byte *pBuf) { assert(pBuf != NULL); // long long h56 = (long long)pBuf[0] << 56 & 0xff00000000000000L; // long long h48 = (long long)pBuf[1] << 48 & 0xff000000000000L; // long long h40 = (long long)pBuf[2] << 40 & 0xff0000000000L; // long long h32 = (long long)pBuf[3] << 32 & 0xff00000000L; // long long l24 = (long long)pBuf[4] << 24 & 0xff000000L; // long long l16 = (long long)pBuf[5] << 16 & 0xff0000L; // long long l08 = (long long)pBuf[6] << 8 & 0xff00L; // long long l00 = (long long)pBuf[7] & 0xffL; // // long long t = h32 | h40 | h48 | h56 | l00 | l08 | l16 | l24; _convertDataTypeCollection.memcpy8(pBuf); return _convertDataTypeCollection; } */ /* byte* HByteConvert::stringToByte(const string &data) { QString str = QString::fromStdString(data); QByteArray array = str.toLocal8Bit(); char *pchar = new char[array.size() + 1]; pchar[array.size()] = 0; memcpy_s(pchar, array.size(), array.constData(), array.size()); return (byte *)pchar; // wstring wstr = s2ws(data); // wchar_t *wchar = const_cast<wchar_t *>(wstr.c_str()); // assert(wchar != NULL); // int size = WideCharToMultiByte(CP_ACP, 0, wchar, -1, NULL, 0, NULL, NULL); // char *pchar = new char[size + 1]; // if (!WideCharToMultiByte(CP_ACP, 0, wchar, -1, pchar, size, NULL, NULL)) // { // delete[]pchar; // } // return (byte *)pchar; } void HByteConvert::stringToByte(const string &data, byte *pBuf) { assert(pBuf == NULL); QString str = QString::fromStdString(data); QByteArray array = str.toLocal8Bit(); pBuf = new byte[array.size() + 1]; memcpy_s(pBuf, array.size(), array.constData(), array.size()); // assert(pBuf == NULL); // wstring wstr = s2ws(data); // wchar_t *wchar = const_cast<wchar_t *>(wstr.c_str()); // assert(wchar != NULL); // int size = WideCharToMultiByte(CP_ACP, 0, wchar, -1, NULL, 0, NULL, NULL); // char *pchar = new char[size + 1]; // if (!WideCharToMultiByte(CP_ACP, 0, wchar, -1, pchar, size, NULL, NULL)) // { // delete[]pchar; // } // // pBuf = (byte *)pchar; } void HByteConvert::byteToString(string &data, const byte *pBuf) { data = utf8((const char *)pBuf).toStdString(); // char *pchar = (char *)pBuf; // int size = MultiByteToWideChar(CP_ACP, 0, pchar, -1, NULL, 0); // wchar_t *wchar = new wchar_t[size + 1]; // assert(wchar != NULL); // if (!MultiByteToWideChar(CP_ACP, 0, pchar, -1, wchar, size)) // { // delete[]wchar; // } // wstring wstr = wchar; // data = ws2s(wstr); // wchar != NULL ? delete[]wchar, wchar = NULL : 0; } byte* HByteConvert::stringToByte(const QString &data) { QByteArray array = data.toLocal8Bit(); char *pchar = new char[array.size() + 1]; pchar[array.size()] = 0; memcpy_s(pchar, array.size(), array.constData(), array.size()); return (byte *)pchar; } void HByteConvert::stringToByte(const QString &data, byte *pBuf) { QByteArray array = data.toLocal8Bit(); char *pchar = new char[array.size() + 1]; pchar[array.size()] = 0; memcpy_s(pchar, array.size(), array.constData(), array.size()); } void HByteConvert::byteToString(QString &data, const byte *pBuf) { data = utf8((const char *)pBuf); } */ /* byte* HByteConvert::doubleToByte(const double &data) { // byte *pBuf = new byte[9]; // memcpy_s(pBuf, 8, &data, 8); _convertDataTypeCollection = data; return _convertDataTypeCollection; } void HByteConvert::doubleToByte(const double &data, byte *&pBuf) { // memcpy_s(pBuf, 8, &data, 8); _convertDataTypeCollection = data; memcpy8(pBuf, _convertDataTypeCollection); } double HByteConvert::byteToDouble(const byte *pBuf) { _convertDataTypeCollection.memcpy8(pBuf); return _convertDataTypeCollection; } byte* HByteConvert::floatToByte(const float data) { // byte *pBuf = new byte[4]; // memcpy_s(pBuf, 4, &data, 4); // return pBuf; _convertDataTypeCollection = data; return _convertDataTypeCollection; } void HByteConvert::floatToByte(const float data, byte *pBuf) { // memcpy_s(pBuf, 4, &data, 4); _convertDataTypeCollection = data; memcpy4(pBuf, _convertDataTypeCollection); } float HByteConvert::byteToFloat(const byte *pBuf) { // float value = 0; // memcpy_s(&value, 4, pBuf, 4); // return value; _convertDataTypeCollection.memcpy4(pBuf); return _convertDataTypeCollection; } */ /* void HByteConvert::writeByte(HDataBuffer &buf, byte data) { buf.putBytes(&data, 1); } byte HByteConvert::readByte(HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(1); return *pBuf; } void HByteConvert::writeBytes(HDataBuffer &buf, byte *data, INT length) { byte *pBuf = intToByte(length); buf.putBytes(pBuf,4); //先写入长度 buf.putBytes(data,length); //再写入bytes 数据 } //返回bytes的长度 const byte* HByteConvert::readBytes(HDataBuffer &buf, int &size) { const byte *pBuf = buf.fetchBytes(4); //得到长度数据 size = byteToInt(pBuf); return buf.fetchBytes(size); } void HByteConvert::writeShort(HDataBuffer &buf, short data) { byte *pBuf = shortToByte(data); buf.putBytes(pBuf, 2); } short HByteConvert::readShort(HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(2); short t = byteToShort(pBuf); return t; } void HByteConvert::writeInt(HDataBuffer &buf, int data) { byte *pBuf = intToByte(data); buf.putBytes(pBuf, 4); } int HByteConvert::readInt(HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(4); int t = byteToInt(pBuf); return t; } void HByteConvert::writeDouble(HDataBuffer &buf, double &data) { const byte *pBuf = doubleToByte(data); // int16 len = strlen((char *)pBuf); // // byte *pBuf_ = shortToByte(len);//写入长度 // buf.putBytes(pBuf_, 2); // delete[]pBuf_; buf.putBytes(pBuf, 8);//写入数据 } double HByteConvert::readDouble(HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(8); // uint16 len = byteToShort(pBuf);//获取长度 // delete []pBuf; // // if (len == 0) return 0; // // pBuf = buf.fetchBytes(len); double ret = byteToDouble(pBuf); return ret; } void HByteConvert::writeLong64(HDataBuffer &buf, long long data) { byte *pBuf = long64ToByte(data); buf.putBytes(pBuf, 8); } long long HByteConvert::readLong64(HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(8); long long t = byteToLong64(pBuf); return t; } */ /* void HByteConvert::write256String(HDataBuffer &buf, string &data) { int16 len = data.length(); len >= 255 ? len = 255 : 0; byte l = (byte)len; buf.putBytes(&l,1);//写入string长度 byte *pBuf = stringToByte(data); buf.putBytes(pBuf, len); delete[]pBuf; } void HByteConvert::write256String(HDataBuffer &buf, QString &data) { int16 len = data.size(); len >= 255 ? len = 255 : 0; byte l = (byte)len; buf.putBytes(&l, 1); byte *pBuf = stringToByte(data); buf.putBytes(pBuf, len); delete[]pBuf; } void HByteConvert::read256String(string &_256String, HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(1);//得到长度 int len = pBuf[0]; if (len == 0) { _256String = ""; return; } pBuf = buf.fetchBytes(len); byteToString(_256String, pBuf); } void HByteConvert::read256String(QString &_256String, HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(1);//得到长度 int len = pBuf[0]; if (len == 0) { _256String = ""; return; } pBuf = buf.fetchBytes(len); byteToString(_256String, pBuf); } void HByteConvert::writeShortString(HDataBuffer &buf, string &data) { int32 len = data.length(); len > 65535 ? len = 65535 : 0; const byte *pBuf = shortToByte((uint16)len); buf.putBytes(pBuf, 2); pBuf = stringToByte(data); buf.putBytes(pBuf, (uint16)len); delete[]pBuf; } void HByteConvert::writeShortString(HDataBuffer &buf, QString &data) { int32 len = data.length(); len > 65535 ? len = 65535 : 0; byte *pBuf = shortToByte((uint16)len); buf.putBytes(pBuf, 2); pBuf = stringToByte(data); buf.putBytes(pBuf, (uint16)len); delete[]pBuf; } void HByteConvert::readShortString(string &_shortString, HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(2);//得到长度 uint16 len = byteToShort(pBuf); if (len == 0) { _shortString = ""; return; } pBuf = buf.fetchBytes(len); byteToString(_shortString, pBuf); } void HByteConvert::readShortString(QString &_shortString, HDataBuffer &buf) { const byte *pBuf = buf.fetchBytes(2);//得到长度 uint16 len = byteToShort(pBuf); if (len == 0) { _shortString = ""; return; } pBuf = buf.fetchBytes(len); byteToString(_shortString, pBuf); } void HByteConvert::writeVectorString(HDataBuffer &buf, vector<string> &arry) { int num = arry.size(); const byte *pBuf = shortToByte((uint16)num); buf.putBytes(pBuf, 2); vector<string>::iterator iter = arry.begin(); while (iter != arry.end()) { writeShortString(buf,*iter); ++iter; } } void HByteConvert::readVectorString(HDataBuffer &buf, vector<string> &result) { const byte *pBuf = buf.fetchBytes(2);//得到vector的个数 uint16 len = byteToShort(pBuf); for (uint16 i = 0; i < len; i++) { string str; readShortString(str, buf); result.push_back(str); } } */ CHE_NAMESPACE_END
tricot-inc/errros-gmops
errors/PS_CT0055.go
// Code generated from gen-error/main.go; DO NOT EDIT package errors type PS_CT0055 struct { } func (e *PS_CT0055) Error() string { return "決済種別の文字数が1文字でない" } func (e *PS_CT0055) Message() string { return "決済種別の文字数が異なります。" } func (e *PS_CT0055) Code() string { return "CT0055" } func (e *PS_CT0055) CanRetry() bool { return false }
mtaghiza/tinyos-main-1
tos/chips/msp430/x2xxx/usci/msp430usci.h
/* * Copyright (c) 2010-2011 <NAME> * Copyright (c) 2009-2010 DEXMA SENSORS SL * All rights reserved. * * Copyright (c) 2004-2006, Technische Universitaet Berlin * 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 copyright holders nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * 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. * * @author <NAME> <<EMAIL>> * @author <NAME> <huppertz@tkn.tu-berlin.de> * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> * * Support the x2 version of the USCI for the TI MSPx2xx (see TI MSP430x2xx * Users guide slau144e). */ #ifndef _H_MSP430USCI_H #define _H_MSP430USCI_H /* * The MSP430X architecture at least the msp430f2618 family * has a total of four ports that can be used independently * usciA0, A1 (uart, spi) and usciB0, B1 (i2c, spi only). * * We set the resources up so multiple use of a given port * can be arbritrated. * * UART0 -> usciA0 SPI2 -> usciA0 * UART1 -> usciA1 SPI3 -> usciA1 * SPI0 -> usciB0 I2C0 * SPI1 -> usciB1 I2C1 * * spi2,3 are mapped to usciA0,A1 because the typical * configuration is to use dual uarts and dual spis * so the less used configuration maps as 2 and 3. */ //USCI A0, A1: UART, SPI #define MSP430_HPLUSCIA0_RESOURCE "Msp430UsciA0.Resource" #define MSP430_HPLUSCIA1_RESOURCE "Msp430UsciA1.Resource" #define MSP430_UART0_BUS MSP430_HPLUSCIA0_RESOURCE #define MSP430_UART1_BUS MSP430_HPLUSCIA1_RESOURCE #define MSP430_SPI2_BUS MSP430_HPLUSCIA0_RESOURCE #define MSP430_SPI3_BUS MSP430_HPLUSCIA1_RESOURCE //USCI B0, B1: SPI, I2C #define MSP430_HPLUSCIB0_RESOURCE "Msp430UsciB0.Resource" #define MSP430_HPLUSCIB1_RESOURCE "Msp430UsciB1.Resource" #define MSP430_SPI0_BUS MSP430_HPLUSCIB0_RESOURCE #define MSP430_SPI1_BUS MSP430_HPLUSCIB1_RESOURCE #define MSP430_I2C0_BUS MSP430_HPLUSCIB0_RESOURCE #define MSP430_I2C1_BUS MSP430_HPLUSCIB1_RESOURCE typedef enum { USCI_NONE = 0, USCI_UART = 1, USCI_SPI = 2, USCI_I2C = 3 } msp430_uscimode_t; /************************************************************************************************************ * * UART mode definitions * */ /* * UCAxCTL0, UART control 0, uart mode */ typedef struct { unsigned int ucsync : 1; // Synchronous mode enable (0=Asynchronous; 1:Synchronous) unsigned int ucmode : 2; // USCI Mode (00=UART Mode; 01=Idle-Line; 10=Addres-Bit; 11=UART Mode, auto baud rate detection) unsigned int ucspb : 1; // Stop bit select. Number of stop bits (0=One stop bit; 1=Two stop bits) unsigned int uc7bit : 1; // Charactaer lenght, (0=8-bit data; 1=7-bit data) unsigned int ucmsb : 1; // endian. Direction of the rx and tx shift (0=LSB first, 1=MSB first) unsigned int ucpar : 1; // Parity Select (0=odd parity; 1=Even parity) unsigned int ucpen : 1; // Parity enable (0=Parity disable; 1=Parity enabled) } __attribute__ ((packed)) msp430_uctl0_t ; /* * UCAxCTL1, UART control 1, uart mode */ typedef struct { unsigned int ucswrst : 1; //Software reset enable (0=disabled; 1=enabled) unsigned int uctxbrk : 1; //Transmit break. (0 = no brk; 1 = tx break next frame unsigned int uctxaddr : 1; //Transmit address. (0=next frame transmitted is data; 1=next frame transmitted is an address) unsigned int ucdorm : 1; //Dormant. (0 = not dormant; 1 = Dormant, only some chars will set UCAxRXIFG) unsigned int ucbrkie : 1; //rx break interrupt -enable, 1 = enabled unsigned int ucrxeie : 1; //rx error interrupt-enable unsigned int ucssel : 2; //USCI clock source select: (00=UCKL; 01=ACLK; 10=SMCLK; 11=SMCLK } __attribute__ ((packed)) msp430_uctl1_t ; //converts from typedefstructs to uint8_t DEFINE_UNION_CAST(uctl02int,uint8_t,msp430_uctl0_t) DEFINE_UNION_CAST(int2uctl0,msp430_uctl0_t,uint8_t) DEFINE_UNION_CAST(uctl12int,uint8_t,msp430_uctl1_t) DEFINE_UNION_CAST(int2uctl1,msp430_uctl1_t,uint8_t) /* * The usci/uart baud rate mechanism is significantly different * than the msp430 usart uart. See section 15.3.9 of the TI * MSP430x2xx Family User's Guide, slau144e for details. * * For 32768Hz and 1048576Hz, we use UCOS16=0. * For higher cpu dco speeds we use oversampling, UCOS16=1. */ typedef enum { UBR_32KHZ_1200=0x001B, UMCTL_32KHZ_1200=0x04, UBR_32KHZ_2400=0x000D, UMCTL_32KHZ_2400=0x0c, UBR_32KHZ_4800=0x0006, UMCTL_32KHZ_4800=0x0e, UBR_32KHZ_9600=0x0003, UMCTL_32KHZ_9600=0x06, UBR_1048MHZ_9600=0x006D, UMCTL_1048MHZ_9600=0x04, UBR_1048MHZ_19200=0x0036, UMCTL_1048MHZ_19200=0x0a, UBR_1048MHZ_38400=0x001B, UMCTL_1048MHZ_38400=0x04, UBR_1048MHZ_57600=0x0012, UMCTL_1048MHZ_57600=0x0c, UBR_1048MHZ_115200=0x0009, UMCTL_1048MHZ_115200=0x02, UBR_1048MHZ_128000=0x0008, UMCTL_1048MHZ_128000=0x02, UBR_1048MHZ_256000=0x0004, UMCTL_1048MHZ_230400=0x02, /* 1MHz = 1000000 Hz, 4MHz 4000000, 8MHz 8000000 * 16MHz 16000000. use UCOS16 for oversampling, * use both UCBRF and UCBRS. * * Settings for 1MHz, 8Mhz, and 16MHz are taken from * a table on page 15-22 of slau144e. */ UBR_1MHZ_9600=0x6, UMCTL_1MHZ_9600=0x81, UBR_1MHZ_19200=0x3, UMCTL_1MHZ_19200=0x41, UBR_1MHZ_57600=0x1, UMCTL_1MHZ_57600=0x0F, UBR_4MHZ_9600=0x1A, UMCTL_4MHZ_9600=0x11, UBR_4MHZ_19200=0x0D, UMCTL_4MHZ_19200=0x01, UBR_4MHZ_38400=0x06, UMCTL_4MHZ_38400=0x81, UBR_4MHZ_57600=0x04, UMCTL_4MHZ_57600=0x3B, UBR_4MHZ_115200=0x02, UMCTL_4MHZ_115200=0x27, UBR_4MHZ_230400=0x01, UMCTL_4MHZ_230400=0x0F, UBR_8MHZ_4800=0x68, UMCTL_8MHZ_4800=0x31, UBR_8MHZ_9600=0x34, UMCTL_8MHZ_9600=0x11, UBR_8MHZ_19200=0x1A, UMCTL_8MHZ_19200=0x11, UBR_8MHZ_38400=0x0D, UMCTL_8MHZ_38400=0x01, UBR_8MHZ_57600=0x08, UMCTL_8MHZ_57600=0xB1, UBR_8MHZ_115200=0x04, UMCTL_8MHZ_115200=0x3B, UBR_8MHZ_230400=0x02, UMCTL_8MHZ_230400=0x27, UBR_16MHZ_4800=0xD0, UMCTL_16MHZ_4800=0x51, UBR_16MHZ_9600=0x68, UMCTL_16MHZ_9600=0x31, UBR_16MHZ_19200=0x34, UMCTL_16MHZ_19200=0x11, UBR_16MHZ_38400=0x1A, UMCTL_16MHZ_38400=0x11, UBR_16MHZ_57600=0x11, UMCTL_16MHZ_57600=0x61, UBR_16MHZ_115200=0x8, UMCTL_16MHZ_115200=0xB1, UBR_16MHZ_230400=0x4, UMCTL_16MHZ_230400=0x3B, } msp430_uart_rate_t; typedef struct { unsigned int ubr: 16; // Baud rate (use enum msp430_uart_rate_t for predefined rates) unsigned int umctl: 8; // Modulation (use enum msp430_uart_rate_t for predefined rates) /* start of ctl0 */ unsigned int : 1; // ucsync, should be 0 for uart unsigned int ucmode: 2; // mode: 00 - uart, 01 - Idle, 10 - addr bit, 11 - auto baud. unsigned int ucspb: 1; // stop: 0 - one, 1 - two unsigned int uc7bit: 1; // 7 or 8 bit unsigned int : 1; // msb or lsb first, 0 says lsb, uart should be 0 unsigned int ucpar: 1; // par, 0 odd, 1 even unsigned int ucpen: 1; // par enable, 0 disabled /* start of ctl1 */ unsigned int : 5; // not specified, defaults to 0. unsigned int ucrxeie: 1; // rx err int enable unsigned int ucssel: 2; // clock select, 00 uclk, 01 aclk, 10/11 smclk /* ume, not a control register, backward compatible with usart? * should be okay to nuke. Is this actually used? */ unsigned int utxe:1; // 1:enable tx module unsigned int urxe:1; // 1:enable rx module } msp430_uart_config_t; typedef struct { uint16_t ubr; uint8_t umctl; uint8_t uctl0; uint8_t uctl1; uint8_t ume; } msp430_uart_registers_t; typedef union { msp430_uart_config_t uartConfig; msp430_uart_registers_t uartRegisters; } msp430_uart_union_config_t; const msp430_uart_union_config_t msp430_uart_default_config = { { ubr : UBR_8MHZ_115200, umctl : UMCTL_8MHZ_115200, ucmode : 0, // uart ucspb : 0, // one stop uc7bit : 0, // 8 bit ucpar : 0, // odd parity (but no parity) ucpen : 0, // parity disabled ucrxeie : 0, // err int off ucssel : 2, // smclk utxe : 1, // enable tx urxe : 1, // enable rx } }; /************************************************************************************************************ * * SPI mode definitions * */ typedef struct { unsigned int ubr : 16; // Clock division factor (> = 1) /* ctl0 */ unsigned int : 1; // ucsync, forced to 1 by initilization code. unsigned int ucmode : 2; // 00 3pin spi, 01 4pin ste ah, 10 ste al, 11 i2c unsigned int ucmst : 1; // 0 slave, 1 master unsigned int uc7bit : 1; // 0 8 bit, 1 7 bit. unsigned int ucmsb : 1; // 0 lsb first, 1 msb first unsigned int ucckpl : 1; // 0 inactive low, 1 inactive high unsigned int ucckph : 1; // 0 tx rising uclk, captured falling // 1 captured rising, sent falling edge. /* ctl1 */ unsigned int : 1; // ucswrst, forced to 1 on init unsigned int : 5; // unused. unsigned int ucssel : 2; // BRCLK src, 00 NA, 01 ACLK, 10/11 SMCLK } msp430_spi_config_t; typedef struct { uint16_t ubr; uint8_t uctl0; uint8_t uctl1; } msp430_spi_registers_t; typedef union { msp430_spi_config_t spiConfig; msp430_spi_registers_t spiRegisters; } msp430_spi_union_config_t; const msp430_spi_union_config_t msp430_spi_default_config = { { ubr : 2, /* smclk/2 */ ucmode : 0, /* 3 pin, no ste */ ucmst : 1, /* master */ uc7bit : 0, /* 8 bit */ ucmsb : 1, /* msb first, compatible with msp430 usart */ ucckpl : 0, /* inactive state low */ ucckph : 1, /* data captured on rising, changed falling */ ucssel : 2, /* smclk */ } }; /************************************************************************************************************ * * I2C mode definitions * */ typedef struct { unsigned int : 1; // Sync mode enable, 1 = sync, must be 1 for i2c unsigned int ucmode : 2; // 11 for i2c unsigned int ucmst : 1; // 0 slave, 1 master unsigned int : 1; // unused unsigned int ucmm : 1; // multi master mode unsigned int ucsla10 : 1; // slave addr 7 or 10 bit unsigned int uca10 : 1; // own addr 7 or 10 bit } __attribute__ ((packed)) msp430_i2cctl0_t ; DEFINE_UNION_CAST(i2cctl02int,uint8_t,msp430_i2cctl0_t) DEFINE_UNION_CAST(int2i2cctl0,msp430_i2cctl0_t,uint8_t) typedef struct { unsigned int ucswrst : 1; // Software reset (1 = reset) unsigned int uctxstt : 1; // Transmit start in master. unsigned int uctxstp : 1; // Transmit stop in master. unsigned int uctxnack : 1; // transmit nack unsigned int uctr : 1; // 0 rx, 1 tx unsigned int : 1; // unused unsigned int ucssel : 2; // USCI clock source: (00 UCLKI; 01 ACLK; 10/11 SMCLK } __attribute__ ((packed)) msp430_i2cctl1_t ; typedef struct { uint16_t ubr : 16; /* baud rate divisor */ /* ctl0 */ uint8_t : 1; /* ucsync, forced to 1 by init code */ uint8_t ucmode : 2; /* mode, must be 3 for i2c */ uint8_t ucmst : 1; /* master if 1 */ uint8_t : 1; /* unused */ uint8_t ucmm : 1; /* mult-master mode */ uint8_t ucsla10 : 1; /* slave addr 10 bits vs. 7 */ uint8_t uca10 : 1; /* own addressing mode 10 bits vs. 7 */ /* ctl1 */ uint8_t : 1; /* software reset */ uint8_t : 1; /* gen tx start */ uint8_t : 1; /* gen tx stop */ uint8_t : 1; /* gen nack */ uint8_t uctr : 1; /* tx/rx mode, 1 = tx */ uint8_t : 1; /* unused */ uint8_t ucssel : 2; /* clock src, 00 uclk, 01 aclk, 10/11 smclk */ /* own addr */ uint16_t i2coa : 10; /* own address */ uint8_t : 5; /* unused */ uint8_t ucgcen : 1; /* general call response enable */ } msp430_i2c_config_t; typedef struct { uint16_t ubr; /* 16 bit baud rate */ uint8_t uctl0; /* control word 0 */ uint8_t uctl1; /* control word 1 */ uint16_t ui2coa; /* own address, ucgcen */ } msp430_i2c_registers_t; typedef union { msp430_i2c_config_t i2cConfig; msp430_i2c_registers_t i2cRegisters; } msp430_i2c_union_config_t; const msp430_i2c_union_config_t msp430_i2c_default_config = { { ubr : 2, /* smclk/2 */ ucmode : 3, /* i2c mode */ ucmst : 1, /* master */ ucmm : 0, /* single master */ ucsla10 : 1, /* 10 bit slave */ uca10 : 1, /* 10 bit us */ uctr : 1, /* tx mode to start */ ucssel : 2, /* smclk */ i2coa : 1, /* our address is 1 */ ucgcen : 1, /* respond to general call */ } }; #endif /* _H_MSP430USCI_H */
dbrennand/azure-intelligent-edge-patterns
factory-ai-vision/EdgeSolution/modules/WebModule/backend/vision_on_edge/azure_parts/tests/test_model_part.py
<reponame>dbrennand/azure-intelligent-edge-patterns """ Part Model and method unittest """ from django.core.exceptions import MultipleObjectsReturned from rest_framework.test import APITransactionTestCase from ..models import Part from .test_special_strings import special_strings class PartTestCase(APITransactionTestCase): """ Part Model and method unittest """ def setUp(self): Part.objects.create(name="Part1", description="Description1", is_demo=True) Part.objects.create(name="Part2", description="Description2", is_demo=True) Part.objects.create(name="Part1", description="SELECT * FROM 'LOCATION'", is_demo=False) Part.objects.create(name="Part2", description="python apps.py", is_demo=False) for special_string in special_strings: Part.objects.create(name=special_string, description=special_string, is_demo=False) self.exist_num = 4 + len(special_strings) def test_setup_is_valid(self): """ Make sure setup is valid """ self.assertEqual(Part.objects.count(), self.exist_num) self.assertRaises(MultipleObjectsReturned, Part.objects.get, name='Part1') part_1 = Part.objects.filter(name='Part1').last() self.assertFalse(part_1.is_demo) part_2 = Part.objects.filter(name='Part2').last() self.assertFalse(part_2.is_demo) demo_part_1 = Part.objects.filter(name='Part1').first() self.assertTrue(demo_part_1.is_demo) demo_part_2 = Part.objects.filter(name='Part2').first() self.assertTrue(demo_part_2.is_demo) def test_create_without_description(self): """ @Type Positive @Description Create parts without description assigned Description column is now not mandatory @Expected Results Object created. Description is '' """ part_name = "Part without Desb" Part.objects.create(name=part_name, is_demo=False) part_obj = Part.objects.get(name=part_name) self.assertEqual(part_obj.description, '')
maxim5/webby
webby-core/src/main/java/io/webby/url/convert/StringConstraint.java
<filename>webby-core/src/main/java/io/webby/url/convert/StringConstraint.java package io.webby.url.convert; import io.routekit.util.CharArray; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class StringConstraint extends LengthConstraint implements Constraint<String> { public static final StringConstraint UNLIMITED = new StringConstraint(Integer.MAX_VALUE); public static final StringConstraint MAX_256 = new StringConstraint(256); public StringConstraint(int maxLength) { super(maxLength); } @Override public String apply(@Nullable CharArray value) throws ConversionError { validateString(null, value); return String.valueOf(value); } @Override public String applyWithName(@NotNull String name, @Nullable CharArray value) throws ConversionError { validateString(name, value); return String.valueOf(value); } }
ppanditsaaksshaat/goHrUI
src/app/pages/leave/masters/masters.module.js
/** * @author v.lugovsky * created on 16.12.2015 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.leave.masters', []) .config(routeConfig); /** @ngInject */ function routeConfig($stateProvider,$urlRouterProvider) { $stateProvider .state('leave.masters', { url: '/masters', abstract: true, templateUrl: 'app/pages/leave/masters/masters.html', controller: "LeaveMastersController1", controllerAs: "tabCtrl", title: 'Master', sidebarMeta: { order: 0, }, }).state('leave.masters.list', { url: '/:name/:pageId', templateUrl: 'app/pages/leave/masters/list/mastersList.html', title: 'leave Masters', controller: "LeaveMastersListController1", controllerAs: "listCtrl" }).state('leave.masters.detail', { url: '/:pageId/:id', templateUrl: 'app/pages/leave/masters/detail/mastersDetail.html', title: 'leave Masters', controller: "leaveMastersDetailController", controllerAs: "detailCtrl" }).state('leave.masters.add', { url: '/:name/:action/:pageId/', templateUrl: 'app/pages/leave/masters/add/add.html', title: 'leave Masters', controller: "LeaveMastersAddController1", controllerAs: "addCtrl" }).state('leave.masters.edit', { url: '/:name/:action/:pageId/:pkId/', templateUrl: 'app/pages/leave/masters/add/add.html', title: 'leave Masters', controller: "LeaveMastersAddController1", controllerAs: "addCtrl" }); $urlRouterProvider.when('/leave/masters','/leave/masters/leavetype/260'); } })();