repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
abhishek-12355/netshell-libraries
utilities/src/main/java/com/netshell/libraries/utilities/strategy/Strategy.java
<reponame>abhishek-12355/netshell-libraries package com.netshell.libraries.utilities.strategy; /** * Created by Abhishek * on 5/22/2016. */ public interface Strategy { /** * It is recommended to override this method as empty name can cause issues. * * @return name of the validation strategy */ String getName(); }
RackHD/smi-lib-wiseman
src/main/java/com/sun/ws/management/server/reflective/ReflectiveRequestDispatcher.java
<gh_stars>0 /* * Copyright 2005 Sun Microsystems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ** Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P. ** ** Authors: <NAME> (<EMAIL>), <NAME> (<EMAIL>), ** <NAME> (<EMAIL>), <NAME> ** **$Log: ReflectiveRequestDispatcher.java,v $ **Revision 1.2 2007/05/31 19:47:46 nbeers **Add HP copyright header ** ** * $Id: ReflectiveRequestDispatcher.java,v 1.2 2007/05/31 19:47:46 nbeers Exp $ */ package com.sun.ws.management.server.reflective; import com.sun.ws.management.AccessDeniedFault; import com.sun.ws.management.InternalErrorFault; import com.sun.ws.management.Management; import com.sun.ws.management.addressing.DestinationUnreachableFault; import com.sun.ws.management.server.Handler; import com.sun.ws.management.server.HandlerContext; import com.sun.ws.management.server.RequestDispatcher; import com.sun.ws.management.server.WSManAgent; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.WeakHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBException; import javax.xml.soap.SOAPException; public final class ReflectiveRequestDispatcher extends RequestDispatcher { private static final Logger LOG = Logger .getLogger(ReflectiveRequestDispatcher.class.getName()); private static final Class<Handler> HANDLER_INTERFACE = Handler.class; private static final Class[] HANDLER_PARAMS = { String.class, String.class, HandlerContext.class, Management.class, Management.class }; private static final String HANDLER_PREFIX = RequestDispatcher.class .getPackage().getName() + ".handler"; static final class HandlerEntry { private final Object instance; private final Method method; HandlerEntry(final Object instance, final Method method) { this.instance = instance; this.method = method; } Object getInstance() { return instance; } Method getMethod() { return method; } } private static WSManAgent dispatchingAgent = null; private static final Map<String, HandlerEntry> cache = new WeakHashMap<String, HandlerEntry>(); private final RequestDispatcherConfig config; public ReflectiveRequestDispatcher(final Management req, final HandlerContext context) throws JAXBException, SOAPException { super(req, context); config = new RequestDispatcherConfig(context); } public Management call() throws Exception { final String resource = request.getResourceURI(); if (resource == null) { throw new DestinationUnreachableFault("Missing the " + Management.RESOURCE_URI.getLocalPart(), DestinationUnreachableFault.Detail.INVALID_RESOURCE_URI); } HandlerEntry he = getHandlerEntry(resource); final String action = request.getAction(); try { he.getMethod().invoke(he.getInstance(), action, resource, context, request, response); } catch (InvocationTargetException itex) { // the cause might be FaultException if a Fault is being indicated // by the handler final Throwable cause = itex.getCause(); if (cause instanceof Exception) { throw (Exception) cause; } else { throw new Exception(cause); } } return response; } private HandlerEntry getHandlerEntry(String resource) { HandlerEntry he = null; synchronized (cache) { he = cache.get(resource); if (he == null) { // Handler not yet cached. Check config. String handlerClassName = config.getHandlerName(resource); if ((handlerClassName == null) || (handlerClassName.length() == 0)) { // Handler not configured. Create default classname handlerClassName = createHandlerClassName(resource); } // Load the handler. if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, resource + " -> " + handlerClassName); } final Class handlerClass; try { handlerClass = Class.forName(handlerClassName, true, Thread .currentThread().getContextClassLoader()); } catch (ClassNotFoundException cnfex) { throw new DestinationUnreachableFault( "Handler not found for resource " + resource, DestinationUnreachableFault.Detail.INVALID_RESOURCE_URI); } catch (Throwable e) { throw new InternalErrorFault(e.getMessage()); } // verify that handlerClass implements the Handler interface if (!HANDLER_INTERFACE.isAssignableFrom(handlerClass)) { throw new DestinationUnreachableFault( "Handler " + handlerClassName + " does not implement the Handler interface for resource " + resource, DestinationUnreachableFault.Detail.INVALID_RESOURCE_URI); } final Method method; try { method = handlerClass.getMethod("handle", HANDLER_PARAMS); } catch (NoSuchMethodException nsmex) { throw new DestinationUnreachableFault( "handle method not found in Handler " + handlerClassName + " for resource " + resource, DestinationUnreachableFault.Detail.INVALID_RESOURCE_URI); } final Object handler; try { handler = handlerClass.newInstance(); } catch (InstantiationException iex) { throw new DestinationUnreachableFault( "Could not instantiate handler " + handlerClassName + " for resource " + resource, DestinationUnreachableFault.Detail.INVALID_RESOURCE_URI); } catch (IllegalAccessException iaex) { throw new AccessDeniedFault(); } he = new HandlerEntry(handler, method); cache.put(resource, he); } } return he; } private String createHandlerClassName(final String resource) { Class<?> converter = null; try { converter = Class.forName("com.sun.xml.internal.bind.api.impl." + "NameConverter"); }catch(ClassNotFoundException cnfe) { // XXX OK } if(converter == null) { try { converter = Class.forName("com.sun.xml.bind.api.impl." + "NameConverter"); }catch(ClassNotFoundException cnfe) { throw new IllegalStateException(cnfe); } } final String pkg; try { Field f = converter.getField("standard"); Object obj = f.get(null); Method m = converter.getMethod("toPackageName", String.class); pkg = (String) m.invoke(obj, resource); }catch(Exception ex) { throw new IllegalStateException(ex); } // final String pkg = //com.sun.xml.internal.bind.api.impl. // com.sun.xml.internal.bind.api.impl.*;NameConverter.standard.toPackageName(resource); final StringBuilder sb = new StringBuilder(); if (HANDLER_PREFIX != null) { sb.append(HANDLER_PREFIX); sb.append("."); } sb.append(pkg); sb.append("_Handler"); return sb.toString(); } }
TetrisIsCool/lightblocks
core/src/de/golfgl/lightblocks/backend/RankedPlayerDetails.java
package de.golfgl.lightblocks.backend; import com.badlogic.gdx.utils.JsonValue; public class RankedPlayerDetails extends PlayerDetails { public final int rank; RankedPlayerDetails(JsonValue fromJson) { super(fromJson); rank = fromJson.getInt("rank", 0); } }
godinj/EntityMod
src/main/java/entity/cards/Disturb.java
<gh_stars>0 package entity.cards; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.common.DamageAction; import com.megacrit.cardcrawl.actions.common.GainBlockAction; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.powers.VulnerablePower; import com.megacrit.cardcrawl.powers.WeakPower; import entity.EntityMod; import entity.characters.Entity; import static entity.EntityMod.makeCardPath; //disturb common skill 1 8(11) block. apply 2(1) weak to yourself and 1 weak to target enemy public class Disturb extends AbstractDynamicCard { public static final String ID = EntityMod.makeID(Disturb.class.getSimpleName()); public static final String IMG = makeCardPath("VoidBlast.png"); private static final CardRarity RARITY = CardRarity.COMMON; private static final CardTarget TARGET = CardTarget.SELF_AND_ENEMY; private static final CardType TYPE = CardType.SKILL; public static final CardColor COLOR = Entity.Enums.COLOR_TEAL; private static final int COST = 1; private static final int BLOCK = 8; private static final int UPGRADE_PLUS_BLOCK = 3; // Represents weak amount applied to enemy. private static final int MAGIC = 1; // Represents weak amount applied to self. private static final int SELF_MAGIC = 2; private static final int UPGRADE_PLUS_SELF_MAGIC = -1; public Disturb() { super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET); this.block = this.baseBlock = BLOCK; this.magicNumber = this.baseMagicNumber = MAGIC; this.selfMagicNumber = this.baseSelfMagicNumber = SELF_MAGIC; } @Override public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToBottom(new GainBlockAction(p, p, block)); AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new WeakPower(p, selfMagicNumber, false), selfMagicNumber)); AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(m, p, new WeakPower(p, magicNumber, false), magicNumber)); } @Override public void upgrade() { if (!upgraded) { upgradeName(); this.upgradeBlock(UPGRADE_PLUS_BLOCK); this.upgradeSelfMagicNumber(UPGRADE_PLUS_SELF_MAGIC); } } }
snonux/dtail
internal/color/color.go
<filename>internal/color/color.go // Package color is used to prettify console output via ANSII terminal colors. package color import ( "fmt" ) // Color name. type Color string // Attribute of a color. type Attribute string // The possible color variations. const ( escape = "\x1b" reset = escape + "[0m" seq string = "%s%s%s" Gray Color = escape + "[30m" Red Color = escape + "[31m" Green Color = escape + "[32m" Orange Color = escape + "[33m" Blue Color = escape + "[34m" Magenta Color = escape + "[35m" Yellow Color = escape + "[36m" LightGray Color = escape + "[37m" BgGray Color = escape + "[40m" BgRed Color = escape + "[41m" BgGreen Color = escape + "[42m" BgOrange Color = escape + "[43m" BgBlue Color = escape + "[44m" BgMagenta Color = escape + "[45m" BgYellow Color = escape + "[46m" BgLightGray Color = escape + "[47m" Bold Attribute = escape + "[1m" Italic Attribute = escape + "[3m" Underline Attribute = escape + "[4m" ReverseColor Attribute = escape + "[7m" resetBold = escape + "[22m" resetItalic = escape + "[23m" resetUnderline = escape + "[24m" Test Color = BgYellow TestAttr Attribute = Bold ) // Colored DTail client output enabled. var Colored bool // Paint a given string in a given color. func Paint(c Color, s string) string { return fmt.Sprintf(seq, c, s, reset) } // Attr adds a given attribute to a given string, such as "bold" or "italic". func Attr(c Attribute, s string) string { switch c { case Bold: return fmt.Sprintf(seq, Bold, s, resetBold) case Italic: return fmt.Sprintf(seq, Italic, s, resetItalic) case Underline: return fmt.Sprintf(seq, Underline, s, resetUnderline) } panic("Unknown attribute") }
gregbeech/scion
xenon-routing/lib/xenon/routing/security_directives.rb
require 'xenon/routing/route_directives' module Xenon module Routing module SecurityDirectives include RouteDirectives def authenticate(authenticator) extract_request(authenticator) do |user| if user yield user else reject :unauthorized, { scheme: authenticator.scheme }.merge(authenticator.auth_params) end end end def optional_authenticate(authenticator) extract_request(authenticator) do |user| yield user end end def authorize(check) if check.respond_to?(:call) extract_request(check) do |authorized| authorize(authorized) do yield end end elsif check yield else reject :forbidden end end end end end
ameyac-msft/BlingFire
blingfirecompile.library/inc/FARegexpTreeSimplify_disj.h
<gh_stars>0 /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_REGEXPTREESIMPLIFY_DISJ_H_ #define _FA_REGEXPTREESIMPLIFY_DISJ_H_ #include "FAConfig.h" #include "FAArray_cont_t.h" #include "FATopoSort_t.h" #include "FARegexpTreeTopoGraph.h" #include "FARegexpTree2Hash.h" #include "FARegexpTree2Str.h" class FARegexpTree; class FAAllocatorA; /// /// This class simplifies disjunctions. /// /// In reverse topological order do: /// 1. UniqDisj: /// 1.1 Disj(A, A) --> A /// 1.2 Disj(Disj(B, A), A) --> Disj(B, A) /// /// 2. Left factorization: /// 2.1. Disj(Conc(...Conc(P, A), B), Conc(...Conc(P, C), D)) --> /// Conc(P, Disj(Conc(...A, B), Conc(...C, D))); /// 2.1. Disj(Disj(Q, Conc(...Conc(P, A), B)), Conc(...Conc(P, C), D)) --> /// Disj(Q, Conc(P, Disj(Conc(...A, B), Conc(...C, D)))); /// /// Examples: /// 1. "(10|10|(10 10)|(10 10)) => (10)|(10 10)" /// 2. "(.* 10 20) | (.* 10 30)" => "(.* 10) (20|30)" /// class FARegexpTreeSimplify_disj { public: FARegexpTreeSimplify_disj (FAAllocatorA * pAlloc); public: void SetRegexp (const char * pRegexp, const int Length); void SetRegexpTree (FARegexpTree * pTree); void Process (); private: // calculates topological order of the nodes void TopoOrder (); // uniques disjunctions, assumed that they are sorted void UniqDisj (); // Disj(A, A) --> A inline void Simplify_11 ( const int NodeId, const int TrBr, const int TrBrOffset ); // Disj(Disj(B, A), A) --> Disj(B, A) inline void Simplify_12 ( const int NodeId, const int TrBr, const int TrBrOffset ); // puts common prefixes out of disjunctions void LeftFact (); // finds common prefix node in left sub-tree and right sub-tree // returns false if there were no common prefix found inline const bool FindCommonPref ( const int LeftConc, const int RightConc, int * pLeftPref, int * pRightPref ); // Disj(Conc(...Conc(P, A), B), Conc(...Conc(P, C), D)) --> // Conc(P, Disj(Conc(...A, B), Conc(...C, D))), inline void Simplify_21 ( const int NodeId, const int TrBr, const int TrBrOffset, const int LeftPref, const int RightPref ); // Disj(Disj(Q, Conc(...Conc(P, A), B)), Conc(...Conc(P, C), D)) --> // Disj(Q, Conc(P, Disj(Conc(...A, B), Conc(...C, D)))); inline void Simplify_22 ( const int NodeId, const int DisjTrBr, const int DisjTrBrOffset, const int ConcTrBr, const int ConcTrBrOffset, const int LeftPref, const int RightPref ); private: // regexp tree FARegexpTree * m_pTree; // topological sorter FATopoSort_t < FARegexpTreeTopoGraph > m_sort; // hash for each node FARegexpTree2Hash m_node2key; // string representation for two arbitrary nodes FARegexpTree2Str m_Node1Str; FARegexpTree2Str m_Node2Str; const char * m_pTmpRegexp; }; #endif
ybt195/determined
master/pkg/searcher/sha_test.go
<gh_stars>0 package searcher import ( "testing" "github.com/determined-ai/determined/master/pkg/model" ) func TestSHASearcher(t *testing.T) { actual := model.SyncHalvingConfig{ Metric: defaultMetric, NumRungs: 4, TargetTrialSteps: 800, StepBudget: 480, Divisor: 4, TrainStragglers: true, } expected := [][]Kind{ toKinds("12S 1V"), toKinds("12S 1V"), toKinds("12S 1V"), toKinds("12S 1V"), toKinds("12S 1V"), toKinds("12S 1V"), toKinds("12S 1V"), toKinds("12S 1V"), toKinds("12S 1V"), toKinds("12S 1V 38S 1V"), toKinds("12S 1V 38S 1V 150S 1V 600S 1V"), } searchMethod := newSyncHalvingSearch(actual, defaultBatchesPerStep) checkSimulation(t, searchMethod, nil, ConstantValidation, expected) } func TestSHASearchMethod(t *testing.T) { testCases := []valueSimulationTestCase{ { name: "smaller is better", expectedTrials: []predefinedTrial{ newConstantPredefinedTrial(0.01, 800, []int{12, 50, 200, 800}, nil), newConstantPredefinedTrial(0.02, 50, []int{12, 50}, nil), newConstantPredefinedTrial(0.03, 12, []int{12}, nil), newConstantPredefinedTrial(0.04, 12, []int{12}, nil), newConstantPredefinedTrial(0.05, 12, []int{12}, nil), newConstantPredefinedTrial(0.06, 12, []int{12}, nil), newConstantPredefinedTrial(0.07, 12, []int{12}, nil), newConstantPredefinedTrial(0.08, 12, []int{12}, nil), newConstantPredefinedTrial(0.09, 12, []int{12}, nil), newConstantPredefinedTrial(0.10, 12, []int{12}, nil), newConstantPredefinedTrial(0.11, 12, []int{12}, nil), }, config: model.SearcherConfig{ SyncHalvingConfig: &model.SyncHalvingConfig{ Metric: "error", NumRungs: 4, SmallerIsBetter: true, TargetTrialSteps: 800, StepBudget: 480, Divisor: 4, TrainStragglers: true, }, }, }, { name: "early exit -- smaller is better", expectedTrials: []predefinedTrial{ newConstantPredefinedTrial(0.01, 800, []int{12, 50, 200, 800}, nil), newEarlyExitPredefinedTrial(0.02, 50, []int{12}, nil), newConstantPredefinedTrial(0.03, 12, []int{12}, nil), newConstantPredefinedTrial(0.04, 12, []int{12}, nil), newConstantPredefinedTrial(0.05, 12, []int{12}, nil), newConstantPredefinedTrial(0.06, 12, []int{12}, nil), newConstantPredefinedTrial(0.07, 12, []int{12}, nil), newConstantPredefinedTrial(0.08, 12, []int{12}, nil), newConstantPredefinedTrial(0.09, 12, []int{12}, nil), newConstantPredefinedTrial(0.10, 12, []int{12}, nil), newEarlyExitPredefinedTrial(0.11, 11, nil, nil), }, config: model.SearcherConfig{ SyncHalvingConfig: &model.SyncHalvingConfig{ Metric: "error", NumRungs: 4, SmallerIsBetter: true, TargetTrialSteps: 800, StepBudget: 480, Divisor: 4, TrainStragglers: true, }, }, }, { name: "smaller is not better", expectedTrials: []predefinedTrial{ newConstantPredefinedTrial(0.11, 800, []int{12, 50, 200, 800}, nil), newConstantPredefinedTrial(0.10, 50, []int{12, 50}, nil), newConstantPredefinedTrial(0.09, 12, []int{12}, nil), newConstantPredefinedTrial(0.08, 12, []int{12}, nil), newConstantPredefinedTrial(0.07, 12, []int{12}, nil), newConstantPredefinedTrial(0.06, 12, []int{12}, nil), newConstantPredefinedTrial(0.05, 12, []int{12}, nil), newConstantPredefinedTrial(0.04, 12, []int{12}, nil), newConstantPredefinedTrial(0.03, 12, []int{12}, nil), newConstantPredefinedTrial(0.02, 12, []int{12}, nil), newConstantPredefinedTrial(0.01, 12, []int{12}, nil), }, config: model.SearcherConfig{ SyncHalvingConfig: &model.SyncHalvingConfig{ Metric: "error", NumRungs: 4, SmallerIsBetter: false, TargetTrialSteps: 800, StepBudget: 480, Divisor: 4, TrainStragglers: true, }, }, }, { name: "early exit -- smaller is not better", expectedTrials: []predefinedTrial{ newConstantPredefinedTrial(0.11, 800, []int{12, 50, 200, 800}, nil), newEarlyExitPredefinedTrial(0.10, 50, []int{12}, nil), newConstantPredefinedTrial(0.09, 12, []int{12}, nil), newConstantPredefinedTrial(0.08, 12, []int{12}, nil), newConstantPredefinedTrial(0.07, 12, []int{12}, nil), newConstantPredefinedTrial(0.06, 12, []int{12}, nil), newConstantPredefinedTrial(0.05, 12, []int{12}, nil), newConstantPredefinedTrial(0.04, 12, []int{12}, nil), newConstantPredefinedTrial(0.03, 12, []int{12}, nil), newConstantPredefinedTrial(0.02, 12, []int{12}, nil), newEarlyExitPredefinedTrial(0.01, 11, nil, nil), }, config: model.SearcherConfig{ SyncHalvingConfig: &model.SyncHalvingConfig{ Metric: "error", NumRungs: 4, SmallerIsBetter: false, TargetTrialSteps: 800, StepBudget: 480, Divisor: 4, TrainStragglers: true, }, }, }, } runValueSimulationTestCases(t, testCases) }
Droeftoeter/react-material-icons
src/editor/BorderStyle.js
<reponame>Droeftoeter/react-material-icons import React from 'react'; import BaseIcon from '../BaseIcon'; export default props => ( <BaseIcon { ...props } > <path d="M30 42h4v-4h-4v4zm8 0h4v-4h-4v4zm-24 0h4v-4h-4v4zm8 0h4v-4h-4v4zm16-8h4v-4h-4v4zm0-8h4v-4h-4v4zM6 6v36h4V10h32V6H6zm32 12h4v-4h-4v4z"/> </BaseIcon> );
ryanloney/openvino-1
src/core/reference/src/runtime/reference/multiclass_nms.cpp
<reponame>ryanloney/openvino-1<gh_stars>1-10 // Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/op/multiclass_nms.hpp" #include <algorithm> #include <cmath> #include <numeric> #include <queue> #include <vector> #include "ngraph/runtime/reference/multiclass_nms.hpp" #include "ngraph/runtime/reference/utils/nms_common.hpp" #include "ngraph/shape.hpp" using namespace ngraph; using namespace ngraph::runtime::reference; namespace ngraph { namespace runtime { namespace reference { namespace multiclass_nms_v8 { using Rectangle = runtime::reference::nms_common::Rectangle; using BoxInfo = runtime::reference::nms_common::BoxInfo; static float intersectionOverUnion(const Rectangle& boxI, const Rectangle& boxJ, const bool normalized) { const float norm = static_cast<float>(normalized == false); float areaI = (boxI.y2 - boxI.y1 + norm) * (boxI.x2 - boxI.x1 + norm); float areaJ = (boxJ.y2 - boxJ.y1 + norm) * (boxJ.x2 - boxJ.x1 + norm); if (areaI <= 0.0f || areaJ <= 0.0f) { return 0.0f; } float intersection_ymin = std::max(boxI.y1, boxJ.y1); float intersection_xmin = std::max(boxI.x1, boxJ.x1); float intersection_ymax = std::min(boxI.y2, boxJ.y2); float intersection_xmax = std::min(boxI.x2, boxJ.x2); float intersection_area = std::max(intersection_ymax - intersection_ymin + norm, 0.0f) * std::max(intersection_xmax - intersection_xmin + norm, 0.0f); return intersection_area / (areaI + areaJ - intersection_area); } struct SelectedIndex { SelectedIndex(int64_t batch_idx, int64_t box_idx, int64_t num_box) : flattened_index(batch_idx * num_box + box_idx) {} SelectedIndex() = default; int64_t flattened_index = 0; }; struct SelectedOutput { SelectedOutput(float class_idx, float score, float x1, float y1, float x2, float y2) : class_index{class_idx}, box_score{score}, xmin{x1}, ymin{y1}, xmax{x2}, ymax{y2} {} SelectedOutput() = default; float class_index = 0.0f; float box_score = 0.0f; float xmin, ymin, xmax, ymax; }; } // namespace multiclass_nms_v8 void multiclass_nms(const float* boxes_data, const Shape& boxes_data_shape, const float* scores_data, const Shape& scores_data_shape, const op::v8::MulticlassNms::Attributes& attrs, float* selected_outputs, const Shape& selected_outputs_shape, int64_t* selected_indices, const Shape& selected_indices_shape, int64_t* valid_outputs) { using SelectedIndex = multiclass_nms_v8::SelectedIndex; using SelectedOutput = multiclass_nms_v8::SelectedOutput; using BoxInfo = multiclass_nms_v8::BoxInfo; using Rectangle = multiclass_nms_v8::Rectangle; auto func = [](float iou, float adaptive_threshold) { return iou <= adaptive_threshold ? 1.0f : 0.0f; }; // boxes shape: {num_batches, num_boxes, 4} // scores shape: {num_batches, num_classes, num_boxes} int64_t num_batches = static_cast<int64_t>(scores_data_shape[0]); int64_t num_classes = static_cast<int64_t>(scores_data_shape[1]); int64_t num_boxes = static_cast<int64_t>(boxes_data_shape[1]); SelectedIndex* selected_indices_ptr = reinterpret_cast<SelectedIndex*>(selected_indices); SelectedOutput* selected_scores_ptr = reinterpret_cast<SelectedOutput*>(selected_outputs); std::vector<BoxInfo> filteredBoxes; // container for the whole batch for (int64_t batch = 0; batch < num_batches; batch++) { const float* boxesPtr = boxes_data + batch * num_boxes * 4; Rectangle* r = reinterpret_cast<Rectangle*>(const_cast<float*>(boxesPtr)); int64_t num_dets = 0; std::vector<BoxInfo> selected_boxes; // container for a batch element for (int64_t class_idx = 0; class_idx < num_classes; class_idx++) { if (class_idx == attrs.background_class) continue; auto adaptive_threshold = attrs.iou_threshold; const float* scoresPtr = scores_data + batch * (num_classes * num_boxes) + class_idx * num_boxes; std::vector<BoxInfo> candidate_boxes; for (int64_t box_idx = 0; box_idx < num_boxes; box_idx++) { if (scoresPtr[box_idx] >= attrs.score_threshold) /* NOTE: ">=" instead of ">" used in PDPD */ { candidate_boxes.emplace_back(r[box_idx], box_idx, scoresPtr[box_idx], 0, batch, class_idx); } } int candiate_size = candidate_boxes.size(); // threshold nms_top_k for each class // NOTE: "nms_top_k" in PDPD not exactly equal to // "max_output_boxes_per_class" in ONNX. if (attrs.nms_top_k > -1 && attrs.nms_top_k < candiate_size) { candiate_size = attrs.nms_top_k; } if (candiate_size <= 0) // early drop { continue; } // sort by score in current class std::partial_sort(candidate_boxes.begin(), candidate_boxes.begin() + candiate_size, candidate_boxes.end(), std::greater<BoxInfo>()); std::priority_queue<BoxInfo> sorted_boxes(candidate_boxes.begin(), candidate_boxes.begin() + candiate_size, std::less<BoxInfo>()); std::vector<BoxInfo> selected; // container for a class // Get the next box with top score, filter by iou_threshold BoxInfo next_candidate; float original_score; while (!sorted_boxes.empty()) { next_candidate = sorted_boxes.top(); original_score = next_candidate.score; sorted_boxes.pop(); bool should_hard_suppress = false; for (int64_t j = static_cast<int64_t>(selected.size()) - 1; j >= next_candidate.suppress_begin_index; --j) { float iou = multiclass_nms_v8::intersectionOverUnion(next_candidate.box, selected[j].box, attrs.normalized); next_candidate.score *= func(iou, adaptive_threshold); if (iou >= adaptive_threshold) { should_hard_suppress = true; break; } if (next_candidate.score <= attrs.score_threshold) { break; } } next_candidate.suppress_begin_index = selected.size(); if (!should_hard_suppress) { if (attrs.nms_eta < 1 && adaptive_threshold > 0.5) { adaptive_threshold *= attrs.nms_eta; } if (next_candidate.score == original_score) { selected.push_back(next_candidate); continue; } if (next_candidate.score > attrs.score_threshold) { sorted_boxes.push(next_candidate); } } } for (const auto& box_info : selected) { selected_boxes.push_back(box_info); } num_dets += selected.size(); } // for each class // sort inside batch element before go through keep_top_k std::sort(selected_boxes.begin(), selected_boxes.end(), [](const BoxInfo& l, const BoxInfo& r) { return ((l.batch_index == r.batch_index) && ((l.score > r.score) || ((std::fabs(l.score - r.score) < 1e-6) && l.class_index < r.class_index) || ((std::fabs(l.score - r.score) < 1e-6) && l.class_index == r.class_index && l.index < r.index))); }); // threshold keep_top_k for each batch element if (attrs.keep_top_k > -1 && attrs.keep_top_k < num_dets) { num_dets = attrs.keep_top_k; selected_boxes.resize(num_dets); } // sort if (!attrs.sort_result_across_batch) { if (attrs.sort_result_type == op::v8::MulticlassNms::SortResultType::CLASSID) { std::sort(selected_boxes.begin(), selected_boxes.end(), [](const BoxInfo& l, const BoxInfo& r) { return ((l.batch_index == r.batch_index) && ((l.class_index < r.class_index) || ((l.class_index == r.class_index) && l.score > r.score) || ((std::fabs(l.score - r.score) <= 1e-6) && l.class_index == r.class_index && l.index < r.index))); }); } // in case of "SCORE", pass through, as, // it has already gurranteed. } *valid_outputs++ = num_dets; for (auto& v : selected_boxes) { filteredBoxes.push_back(v); } } // for each batch element if (attrs.sort_result_across_batch) { /* sort across batch */ if (attrs.sort_result_type == op::v8::MulticlassNms::SortResultType::SCORE) { std::sort(filteredBoxes.begin(), filteredBoxes.end(), [](const BoxInfo& l, const BoxInfo& r) { return (l.score > r.score) || (l.score == r.score && l.batch_index < r.batch_index) || (l.score == r.score && l.batch_index == r.batch_index && l.class_index < r.class_index) || (l.score == r.score && l.batch_index == r.batch_index && l.class_index == r.class_index && l.index < r.index); }); } else if (attrs.sort_result_type == op::v8::MulticlassNms::SortResultType::CLASSID) { std::sort(filteredBoxes.begin(), filteredBoxes.end(), [](const BoxInfo& l, const BoxInfo& r) { return (l.class_index < r.class_index) || (l.class_index == r.class_index && l.batch_index < r.batch_index) || (l.class_index == r.class_index && l.batch_index == r.batch_index && l.score > r.score) || (l.class_index == r.class_index && l.batch_index == r.batch_index && l.score == r.score && l.index < r.index); }); } } /* output */ size_t max_num_of_selected_indices = selected_indices_shape[0]; size_t output_size = std::min(filteredBoxes.size(), max_num_of_selected_indices); size_t idx; for (idx = 0; idx < output_size; idx++) { const auto& box_info = filteredBoxes[idx]; SelectedIndex selected_index{box_info.batch_index, box_info.index, num_boxes}; SelectedOutput selected_score{static_cast<float>(box_info.class_index), box_info.score, box_info.box.x1, box_info.box.y1, box_info.box.x2, box_info.box.y2}; selected_indices_ptr[idx] = selected_index; selected_scores_ptr[idx] = selected_score; } SelectedIndex selected_index_filler{0, 0, 0}; SelectedOutput selected_score_filler{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; for (; idx < max_num_of_selected_indices; idx++) { selected_indices_ptr[idx] = selected_index_filler; selected_scores_ptr[idx] = selected_score_filler; } } } // namespace reference } // namespace runtime } // namespace ngraph
ruuuubi/corsairs-client
Client/src/FindPath.h
#pragma once class CGameScene; class CCharacter; class CFindPath { public: CFindPath(long step,int range); void RenderPath(MPTerrain* pTerrain); S_BVECTOR<D3DXVECTOR3>& GetResultPath() {return _vecPathPoint;} int GetLength() { return _nLength; } bool Find( CGameScene* pScene, CCharacter* pCha, int nSelfX, int nSelfY, int nTargetX, int nTargetY, bool &IsWalkLine ); bool GetPathFindingState(){return m_bFindPath;} bool LongPathFinding(){return m_bLongPathFinding;} void SetLongPathFinding(long step, int range); void SetShortPathFinding(long step, int range); protected: void SetTargetPos(int nCurX,int nCurY,int& nTargetX, int& nTargetY, bool bback = true); BOOL IsCross(int nCurX,int nCurY, int nTargetX, int nTargetY); BYTE* GetTempTerrain(CGameScene* pScene, CCharacter* pCha,int iCurX, int iCurY); void Lock() { _bblock = true; } void UnLock() { _bblock = false; } BOOL FindPath(CGameScene* pScene, CCharacter* pCha, int nSelfX, int nSelfY, int nTargetX, int nTargetY, bool &IsWalkLine); protected: D3DXVECTOR3 _vStart; int _nCurX,_nCurY; int _nTargetX; int _nTargetY; S_BVECTOR<BYTE> _vecDir; S_BVECTOR<BYTE> _vecDirSave; S_BVECTOR<D3DXVECTOR3> _vecPathPoint; int _nWidth; bool _bblock; int _nLength; private: long MAX_PATH_STEP; long STEP_LIMIT; BYTE* _byTempBlock; // jze bool m_bFindPath; //jze int m_iRange; //jze bool m_bLongPathFinding; //jze }; extern CFindPath g_cFindPath;
pointlesssoft/godevs
pkg/simulation/abstract_simulator.go
/* * Copyright (c) 2021, <NAME>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package simulation import "github.com/pointlesssoft/godevs/pkg/modeling" type AbstractSimulator interface { Initialize() // performs all the required operations before starting a simulation. Exit() // performs all the required operations to exit after a simulation. TA() float64 // time advance function. Collect() // collection function. Transition() // transition function. Clear() // clear function. GetModel() modeling.Component // returns the Component attached to the simulator. GetTL() float64 // returns simulator's last simulation time. SetTL(tl float64) // sets simulator's last simulation time. GetTN() float64 // returns simulator's next timeout. SetTN(tn float64) // sets simulator's next timeout. GetClock() Clock // returns abstract simulator's simulation Clock. } func NewAbstractSimulator(clock Clock) AbstractSimulator { s := abstractSimulator{clock, 0, 0} return &s } type abstractSimulator struct { clock Clock // Simulation Clock. tL float64 // Time of last event tN float64 // Time of next event } // Initialize performs all the required operations before starting a simulation. func (a *abstractSimulator) Initialize() { panic("implement me") } // Exit performs all the required operations to exit after a simulation. func (a *abstractSimulator) Exit() { panic("implement me") } // TA is the time advance function. It returns the elapsed time for the next timeout. func (a *abstractSimulator) TA() float64 { panic("implement me") } // Collect is the collection function. It is invoked on imminent simulators before the transition function. func (a *abstractSimulator) Collect() { panic("implement me") } // Transition is the transition function. It deals with internal and external transitions. func (a *abstractSimulator) Transition() { panic("implement me") } // Clear performs all the required operation to clear the simulation state. func (a *abstractSimulator) Clear() { panic("implement me") } // GetModel returns simulator's DEVS component. func (a *abstractSimulator) GetModel() modeling.Component { panic("implement me") } // GetTL returns simulator's last simulation time. func (a *abstractSimulator) GetTL() float64 { return a.tL } // SetTL sets simulator's last simulation time. func (a *abstractSimulator) SetTL(tL float64) { a.tL = tL } // GetTN returns simulator's next timeout. func (a *abstractSimulator) GetTN() float64 { return a.tN } // SetTN sets simulator's next timeout. func (a *abstractSimulator) SetTN(tN float64) { a.tN = tN } // GetClock returns abstract simulator's simulation Clock. func (a *abstractSimulator) GetClock() Clock { return a.clock }
demonCoder95/son-examples
vnfs/sonata-vtc-vnf-docker/pfring_web_api/vtc/PF_RING/drivers/ZC/intel/igb/igb-5.2.5-zc/src/e1000_i210.h
/******************************************************************************* Intel(R) Gigabit Ethernet Linux driver Copyright(c) 2007-2014 Intel Corporation. This program is free software; you can redistribute it and/or modify it under the terms and conditions of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope 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 <htt;://www.gnu.org/licenses/>. The full GNU General Public License is included in this distribution in the file called "COPYING". Contact Information: e1000-devel Mailing List <<EMAIL>> Intel Corporation, 5200 N.E. <NAME>way, Hillsboro, OR 97124-6497 *******************************************************************************/ #ifndef _E1000_I210_H_ #define _E1000_I210_H_ bool e1000_get_flash_presence_i210(struct e1000_hw *hw); s32 e1000_update_flash_i210(struct e1000_hw *hw); s32 e1000_update_nvm_checksum_i210(struct e1000_hw *hw); s32 e1000_validate_nvm_checksum_i210(struct e1000_hw *hw); s32 e1000_write_nvm_srwr_i210(struct e1000_hw *hw, u16 offset, u16 words, u16 *data); s32 e1000_read_nvm_srrd_i210(struct e1000_hw *hw, u16 offset, u16 words, u16 *data); s32 e1000_read_invm_version(struct e1000_hw *hw, struct e1000_fw_version *invm_ver); s32 e1000_acquire_swfw_sync_i210(struct e1000_hw *hw, u16 mask); void e1000_release_swfw_sync_i210(struct e1000_hw *hw, u16 mask); s32 e1000_read_xmdio_reg(struct e1000_hw *hw, u16 addr, u8 dev_addr, u16 *data); s32 e1000_write_xmdio_reg(struct e1000_hw *hw, u16 addr, u8 dev_addr, u16 data); s32 e1000_init_hw_i210(struct e1000_hw *hw); #define E1000_STM_OPCODE 0xDB00 #define E1000_EEPROM_FLASH_SIZE_WORD 0x11 #define INVM_DWORD_TO_RECORD_TYPE(invm_dword) \ (u8)((invm_dword) & 0x7) #define INVM_DWORD_TO_WORD_ADDRESS(invm_dword) \ (u8)(((invm_dword) & 0x0000FE00) >> 9) #define INVM_DWORD_TO_WORD_DATA(invm_dword) \ (u16)(((invm_dword) & 0xFFFF0000) >> 16) enum E1000_INVM_STRUCTURE_TYPE { E1000_INVM_UNINITIALIZED_STRUCTURE = 0x00, E1000_INVM_WORD_AUTOLOAD_STRUCTURE = 0x01, E1000_INVM_CSR_AUTOLOAD_STRUCTURE = 0x02, E1000_INVM_PHY_REGISTER_AUTOLOAD_STRUCTURE = 0x03, E1000_INVM_RSA_KEY_SHA256_STRUCTURE = 0x04, E1000_INVM_INVALIDATED_STRUCTURE = 0x0F, }; #define E1000_INVM_RSA_KEY_SHA256_DATA_SIZE_IN_DWORDS 8 #define E1000_INVM_CSR_AUTOLOAD_DATA_SIZE_IN_DWORDS 1 #define E1000_INVM_ULT_BYTES_SIZE 8 #define E1000_INVM_RECORD_SIZE_IN_BYTES 4 #define E1000_INVM_VER_FIELD_ONE 0x1FF8 #define E1000_INVM_VER_FIELD_TWO 0x7FE000 #define E1000_INVM_IMGTYPE_FIELD 0x1F800000 #define E1000_INVM_MAJOR_MASK 0x3F0 #define E1000_INVM_MINOR_MASK 0xF #define E1000_INVM_MAJOR_SHIFT 4 #define ID_LED_DEFAULT_I210 ((ID_LED_OFF1_ON2 << 8) | \ (ID_LED_DEF1_DEF2 << 4) | \ (ID_LED_OFF1_OFF2)) #define ID_LED_DEFAULT_I210_SERDES ((ID_LED_DEF1_DEF2 << 8) | \ (ID_LED_DEF1_DEF2 << 4) | \ (ID_LED_OFF1_ON2)) /* NVM offset defaults for I211 devices */ #define NVM_INIT_CTRL_2_DEFAULT_I211 0X7243 #define NVM_INIT_CTRL_4_DEFAULT_I211 0x00C1 #define NVM_LED_1_CFG_DEFAULT_I211 0x0184 #define NVM_LED_0_2_CFG_DEFAULT_I211 0x200C /* PLL Defines */ #define E1000_PCI_PMCSR 0x44 #define E1000_PCI_PMCSR_D3 0x03 #define E1000_MAX_PLL_TRIES 5 #define E1000_PHY_PLL_UNCONF 0xFF #define E1000_PHY_PLL_FREQ_PAGE 0xFC0000 #define E1000_PHY_PLL_FREQ_REG 0x000E #define E1000_INVM_DEFAULT_AL 0x202F #define E1000_INVM_AUTOLOAD 0x0A #define E1000_INVM_PLL_WO_VAL 0x0010 #endif
paladin74/terriajs
lib/ViewModels/LegendSectionViewModel.js
<gh_stars>1-10 'use strict'; /*global require*/ var defined = require('terriajs-cesium/Source/Core/defined'); var loadView = require('../Core/loadView'); var proxyCatalogItemUrl = require('../Models/proxyCatalogItemUrl'); var knockout = require('terriajs-cesium/Source/ThirdParty/knockout'); var LegendSectionViewModel = function(nowViewingTab, catalogMember) { this.nowViewingTab = nowViewingTab; this.catalogMember = catalogMember; knockout.defineProperty(this, 'proxiedLegendUrls', { get: function() { return this.catalogMember.legendUrls.map(function(legendUrl) { // Proxy each legend Url return proxyCatalogItemUrl(this, legendUrl); }, this); } }); }; LegendSectionViewModel.createForCatalogMember = function(nowViewingTab, catalogMember) { if (!defined(catalogMember.legendUrls) || catalogMember.legendUrls.length === 0) { return undefined; } return new LegendSectionViewModel(nowViewingTab, catalogMember); }; LegendSectionViewModel.prototype.show = function(container) { loadView(require('fs').readFileSync(__dirname + '/../Views/LegendSection.html', 'utf8'), container, this); }; var imageUrlRegex = /[.\/](png|jpg|jpeg|gif)/i; LegendSectionViewModel.prototype.urlIsImage = function(url) { if (!defined(url) || url.length === 0) { return false; } return url.match(imageUrlRegex); }; module.exports = LegendSectionViewModel;
bossm0n5t3r/BOJ
1244/main.cpp
#include <iostream> using namespace std; int N, numOfStudents, studentCode, num; int switchs[101]; void change(int studentCode, int num) { if (studentCode == 1) { for (int i = 1; i <= N / num; i++) switchs[num * i] = 1 - switchs[num * i]; } else { int start = num; int end = num; while (true) { if (switchs[start] != switchs[end]) { start++; end--; break; } if (start <= 1 || end >= N) break; start--; end++; } for (int i = start; i <= end; i++) switchs[i] = 1 - switchs[i]; } } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> N; for (int i = 1; i <= N; i++) cin >> switchs[i]; cin >> numOfStudents; while (numOfStudents--) { cin >> studentCode >> num; change(studentCode, num); } for (int i = 1; i <= N; i++) { cout << switchs[i] << " "; if (i % 20 == 0) cout << "\n"; } return 0; }
marksteward/BeatSaber-Quest-Codegen
include/GlobalNamespace/BitMask128.hpp
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include <stdint.h> #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: IBitMask`1 #include "GlobalNamespace/IBitMask_1.hpp" // Including type: LiteNetLib.Utils.INetImmutableSerializable`1 #include "LiteNetLib/Utils/INetImmutableSerializable_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: LiteNetLib::Utils namespace LiteNetLib::Utils { // Forward declaring type: NetDataWriter class NetDataWriter; // Forward declaring type: NetDataReader class NetDataReader; } // Completed forward declares // Begin il2cpp-utils forward declares struct Il2CppString; struct Il2CppObject; // Completed il2cpp-utils forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x10 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: BitMask128 // [TokenAttribute] Offset: FFFFFFFF // [IsReadOnlyAttribute] Offset: FFFFFFFF struct BitMask128/*, public System::ValueType, public GlobalNamespace::IBitMask_1<GlobalNamespace::BitMask128>, public LiteNetLib::Utils::INetImmutableSerializable_1<GlobalNamespace::BitMask128>*/ { public: // private readonly System.UInt64 _d0 // Size: 0x8 // Offset: 0x0 uint64_t d0; // Field size check static_assert(sizeof(uint64_t) == 0x8); // private readonly System.UInt64 _d1 // Size: 0x8 // Offset: 0x8 uint64_t d1; // Field size check static_assert(sizeof(uint64_t) == 0x8); // Creating value type constructor for type: BitMask128 constexpr BitMask128(uint64_t d0_ = {}, uint64_t d1_ = {}) noexcept : d0{d0_}, d1{d1_} {} // Creating interface conversion operator: operator System::ValueType operator System::ValueType() noexcept { return *reinterpret_cast<System::ValueType*>(this); } // Creating interface conversion operator: operator GlobalNamespace::IBitMask_1<GlobalNamespace::BitMask128> operator GlobalNamespace::IBitMask_1<GlobalNamespace::BitMask128>() noexcept { return *reinterpret_cast<GlobalNamespace::IBitMask_1<GlobalNamespace::BitMask128>*>(this); } // Creating interface conversion operator: operator LiteNetLib::Utils::INetImmutableSerializable_1<GlobalNamespace::BitMask128> operator LiteNetLib::Utils::INetImmutableSerializable_1<GlobalNamespace::BitMask128>() noexcept { return *reinterpret_cast<LiteNetLib::Utils::INetImmutableSerializable_1<GlobalNamespace::BitMask128>*>(this); } // Get instance field: private readonly System.UInt64 _d0 uint64_t _get__d0(); // Set instance field: private readonly System.UInt64 _d0 void _set__d0(uint64_t value); // Get instance field: private readonly System.UInt64 _d1 uint64_t _get__d1(); // Set instance field: private readonly System.UInt64 _d1 void _set__d1(uint64_t value); // public System.Int32 get_bitCount() // Offset: 0xF8CB44 int get_bitCount(); // static public BitMask128 get_maxValue() // Offset: 0x23D7478 static GlobalNamespace::BitMask128 get_maxValue(); // public System.Void .ctor(System.UInt64 d0, System.UInt64 d1) // Offset: 0xF8CB4C // template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> // ABORTED: conflicts with another method. BitMask128(uint64_t d0, uint64_t d1) // public System.Void .ctor(System.UInt64 value) // Offset: 0xF8CB54 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> BitMask128(uint64_t value) { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::BitMask128::.ctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, value); } // public BitMask128 SetBits(System.Int32 offset, System.UInt64 bits) // Offset: 0xF8CB5C GlobalNamespace::BitMask128 SetBits(int offset, uint64_t bits); // public System.UInt64 GetBits(System.Int32 offset, System.Int32 count) // Offset: 0xF8CB64 uint64_t GetBits(int offset, int count); // public System.Void Serialize(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0xF8CB6C void Serialize(LiteNetLib::Utils::NetDataWriter* writer); // public BitMask128 CreateFromSerializedData(LiteNetLib.Utils.NetDataReader reader) // Offset: 0xF8CB74 GlobalNamespace::BitMask128 CreateFromSerializedData(LiteNetLib::Utils::NetDataReader* reader); // static public BitMask128 Deserialize(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x23D7728 static GlobalNamespace::BitMask128 Deserialize(LiteNetLib::Utils::NetDataReader* reader); // public System.Boolean Equals(BitMask128 other) // Offset: 0xF8CB84 bool Equals(GlobalNamespace::BitMask128 other); // public override System.String ToString() // Offset: 0xF8CB7C // Implemented from: System.ValueType // Base method: System.String ValueType::ToString() ::Il2CppString* ToString(); // public override System.Boolean Equals(System.Object obj) // Offset: 0xF8CBA8 // Implemented from: System.ValueType // Base method: System.Boolean ValueType::Equals(System.Object obj) bool Equals(::Il2CppObject* obj); // public override System.Int32 GetHashCode() // Offset: 0xF8CBB0 // Implemented from: System.ValueType // Base method: System.Int32 ValueType::GetHashCode() int GetHashCode(); }; // BitMask128 #pragma pack(pop) static check_size<sizeof(BitMask128), 8 + sizeof(uint64_t)> __GlobalNamespace_BitMask128SizeCheck; static_assert(sizeof(BitMask128) == 0x10); // static public BitMask128 op_BitwiseOr(in BitMask128 a, in BitMask128 b) // Offset: 0x23D75CC GlobalNamespace::BitMask128 operator|(const GlobalNamespace::BitMask128&& a, const GlobalNamespace::BitMask128&& b); // static public BitMask128 op_BitwiseAnd(in BitMask128 a, in BitMask128 b) // Offset: 0x23D75E0 GlobalNamespace::BitMask128 operator&(const GlobalNamespace::BitMask128&& a, const GlobalNamespace::BitMask128&& b); // static public BitMask128 op_ExclusiveOr(in BitMask128 a, in BitMask128 b) // Offset: 0x23D75F4 GlobalNamespace::BitMask128 operator^(const GlobalNamespace::BitMask128&& a, const GlobalNamespace::BitMask128&& b); // static public BitMask128 op_LeftShift(in BitMask128 a, System.Int32 bits) // Offset: 0x23D7608 GlobalNamespace::BitMask128 operator<<(const GlobalNamespace::BitMask128&& a, const int& bits); // static public BitMask128 op_RightShift(in BitMask128 a, System.Int32 bits) // Offset: 0x23D7640 GlobalNamespace::BitMask128 operator>>(const GlobalNamespace::BitMask128&& a, const int& bits); // static public System.Boolean op_Equality(in BitMask128 a, in BitMask128 b) // Offset: 0x23D7678 bool operator ==(const GlobalNamespace::BitMask128&& a, const GlobalNamespace::BitMask128&& b); // static public System.Boolean op_Inequality(in BitMask128 a, in BitMask128 b) // Offset: 0x23D76A4 bool operator !=(const GlobalNamespace::BitMask128&& a, const GlobalNamespace::BitMask128&& b); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BitMask128, "", "BitMask128"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::BitMask128::get_bitCount // Il2CppName: get_bitCount template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::BitMask128::*)()>(&GlobalNamespace::BitMask128::get_bitCount)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "get_bitCount", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::get_maxValue // Il2CppName: get_maxValue template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::BitMask128 (*)()>(&GlobalNamespace::BitMask128::get_maxValue)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "get_maxValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::BitMask128 // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: GlobalNamespace::BitMask128::BitMask128 // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: GlobalNamespace::BitMask128::SetBits // Il2CppName: SetBits template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::BitMask128 (GlobalNamespace::BitMask128::*)(int, uint64_t)>(&GlobalNamespace::BitMask128::SetBits)> { static const MethodInfo* get() { static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* bits = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "SetBits", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{offset, bits}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::GetBits // Il2CppName: GetBits template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<uint64_t (GlobalNamespace::BitMask128::*)(int, int)>(&GlobalNamespace::BitMask128::GetBits)> { static const MethodInfo* get() { static auto* offset = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* count = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "GetBits", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{offset, count}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::Serialize // Il2CppName: Serialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::BitMask128::*)(LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::BitMask128::Serialize)> { static const MethodInfo* get() { static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::CreateFromSerializedData // Il2CppName: CreateFromSerializedData template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::BitMask128 (GlobalNamespace::BitMask128::*)(LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::BitMask128::CreateFromSerializedData)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "CreateFromSerializedData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::Deserialize // Il2CppName: Deserialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::BitMask128 (*)(LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::BitMask128::Deserialize)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "Deserialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::Equals // Il2CppName: Equals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::BitMask128::*)(GlobalNamespace::BitMask128)>(&GlobalNamespace::BitMask128::Equals)> { static const MethodInfo* get() { static auto* other = &::il2cpp_utils::GetClassFromName("", "BitMask128")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{other}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::ToString // Il2CppName: ToString template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::BitMask128::*)()>(&GlobalNamespace::BitMask128::ToString)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::Equals // Il2CppName: Equals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::BitMask128::*)(::Il2CppObject*)>(&GlobalNamespace::BitMask128::Equals)> { static const MethodInfo* get() { static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::GetHashCode // Il2CppName: GetHashCode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::BitMask128::*)()>(&GlobalNamespace::BitMask128::GetHashCode)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BitMask128), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::BitMask128::operator| // Il2CppName: op_BitwiseOr // Cannot perform method pointer template specialization from operators! // Writing MetadataGetter for method: GlobalNamespace::BitMask128::operator& // Il2CppName: op_BitwiseAnd // Cannot perform method pointer template specialization from operators! // Writing MetadataGetter for method: GlobalNamespace::BitMask128::operator^ // Il2CppName: op_ExclusiveOr // Cannot perform method pointer template specialization from operators! // Writing MetadataGetter for method: GlobalNamespace::BitMask128::operator<< // Il2CppName: op_LeftShift // Cannot perform method pointer template specialization from operators! // Writing MetadataGetter for method: GlobalNamespace::BitMask128::operator>> // Il2CppName: op_RightShift // Cannot perform method pointer template specialization from operators! // Writing MetadataGetter for method: GlobalNamespace::BitMask128::operator == // Il2CppName: op_Equality // Cannot perform method pointer template specialization from operators! // Writing MetadataGetter for method: GlobalNamespace::BitMask128::operator != // Il2CppName: op_Inequality // Cannot perform method pointer template specialization from operators!
fkleedorfer/webofneeds
webofneeds/won-bot/src/main/java/won/bot/framework/eventbot/event/impl/crawl/CrawlCommandEvent.java
<gh_stars>10-100 /* * Copyright 2012 Research Studios Austria Forschungsges.m.b.H. 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 won.bot.framework.eventbot.event.impl.crawl; import java.net.URI; import java.util.List; import org.apache.jena.sparql.path.Path; import won.bot.framework.eventbot.event.BaseAtomSpecificEvent; import won.bot.framework.eventbot.event.impl.cmd.CommandEvent; /** * Initiates the crawling of linked data. The WebID of the specified atom is * used. */ public class CrawlCommandEvent extends BaseAtomSpecificEvent implements CommandEvent { private List<Path> propertyPaths; private URI startURI; private int getMaxRequest; private int maxDepth; public CrawlCommandEvent(URI atomURI, URI startURI, List<Path> propertyPaths, int getMaxRequest, int maxDepth) { super(atomURI); this.propertyPaths = propertyPaths; this.startURI = startURI; this.getMaxRequest = getMaxRequest; this.maxDepth = maxDepth; } public URI getStartURI() { return startURI; } public List<Path> getPropertyPaths() { return propertyPaths; } public int getGetMaxRequest() { return getMaxRequest; } public int getMaxDepth() { return maxDepth; } }
j2fong/distributed-compliance-ledger
x/validator/keeper/validator.go
package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/zigbee-alliance/distributed-compliance-ledger/x/validator/types" ) // SetValidator set a specific validator in the store from its index. func (k Keeper) SetValidator(ctx sdk.Context, validator types.Validator) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix)) b := k.cdc.MustMarshal(&validator) store.Set(types.ValidatorKey( validator.GetOwner(), ), b) } // Check if the Validator record associated with a validator address is present in the store or not. func (k Keeper) IsValidatorPresent(ctx sdk.Context, owner sdk.ValAddress) bool { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix)) return store.Has(types.ValidatorKey(owner)) } // GetValidator returns a validator from its index. func (k Keeper) GetValidator( ctx sdk.Context, owner sdk.ValAddress, ) (val types.Validator, found bool) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix)) b := store.Get(types.ValidatorKey( owner, )) if b == nil { return val, false } k.cdc.MustUnmarshal(b, &val) return val, true } // func (k Keeper) mustGetValidator(ctx sdk.Context, owner sdk.ValAddress) types.Validator { // validator, found := k.GetValidator(ctx, owner) // if !found { // panic(fmt.Sprintf("validator record not found for address: %X\n", owner)) // } // return validator // } // RemoveValidator removes a validator from the store. func (k Keeper) RemoveValidator( ctx sdk.Context, owner sdk.ValAddress, ) { validator, found := k.GetValidator(ctx, owner) if !found { return } valConsAddr, err := validator.GetConsAddr() if err != nil { // TODO ??? issue 99: the best way to deal with that panic(err) } else { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorByConsAddrKeyPrefix)) store.Delete(types.ValidatorByConsAddrKey( valConsAddr, )) } // FIXME issue 99: owner should be a key here store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.LastValidatorPowerKeyPrefix)) store.Delete(types.LastValidatorPowerKey(owner)) store = prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix)) store.Delete(types.ValidatorKey(owner)) // TODO call hooks ??? } // validator index. func (k Keeper) SetValidatorByConsAddr(ctx sdk.Context, validator types.Validator) error { consAddr, err := validator.GetConsAddr() if err != nil { return err } store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorByConsAddrKeyPrefix)) store.Set(types.ValidatorByConsAddrKey( consAddr, ), validator.GetOwner()) return nil } // get a single validator by consensus address. func (k Keeper) GetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) (validator types.Validator, found bool) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorByConsAddrKeyPrefix)) owner := store.Get(types.ValidatorByConsAddrKey( consAddr, )) if owner == nil { return validator, false } return k.GetValidator(ctx, owner) } // func (k Keeper) mustGetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) types.Validator { // validator, found := k.GetValidatorByConsAddr(ctx, consAddr) // if !found { // panic(fmt.Errorf("validator with consensus-Address %s not found", consAddr)) // } // return validator // } // GetAllValidator returns all validator. func (k Keeper) GetAllValidator(ctx sdk.Context) (list []types.Validator) { k.IterateValidators(ctx, func(validator types.Validator) (stop bool) { list = append(list, validator) return false }) return } // iterate over validators and apply function. func (k Keeper) IterateValidators(ctx sdk.Context, process func(validator types.Validator) (stop bool)) { store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix)) iterator := sdk.KVStorePrefixIterator(store, []byte{}) defer iterator.Close() for ; iterator.Valid(); iterator.Next() { var val types.Validator k.cdc.MustUnmarshal(iterator.Value(), &val) if process(val) { return } } }
Tomcuzz/OctaHomeAutomation
OctaHomeProxmox/views.py
<filename>OctaHomeProxmox/views.py from django.http import HttpResponse, HttpResponseNotFound, Http404 from django.shortcuts import render from django.shortcuts import redirect from django.middleware.csrf import get_token from django.conf import settings import datetime from commands import * import sys from proxmoxer import ProxmoxAPI #View Object def ProxmoxMain(request): if not request.user.is_authenticated(): return redirect('/Login?next=%s' % request.path) proxmoxIpAddress = settings.PROXMOX_SERVER_IP_ADDRESS proxmoxUsername = settings.PROXMOX_USER proxmoxPassword = settings.PROXMOX_PASSWORD proxmoxVerifySsl = settings.PROXMOX_VERIFY_SSL proxmox = ProxmoxAPI(proxmoxIpAddress, user=proxmoxUsername, password=<PASSWORD>, verify_ssl=proxmoxVerifySsl) command = request.GET.get('command', 'none') currentNode = request.GET.get('node', 'none') currentVz = request.GET.get('openvz', 'none') currentVm = request.GET.get('qemu', 'none') if command != 'none': return runcommand(request, proxmox) elif currentVz != 'none': vms = getVmDict(proxmox) tasks = getAllServerTasks(proxmox) return render(request, 'OctaHomeProxmox/CT.html', {'links': getSideBar(request, proxmox), 'serverInfo':addWizardVeriables(request, proxmox), 'node':currentNode, 'Vz':vms[currentNode][currentVz], 'StorageDevices':getStorageDetails(proxmox), 'ServerStatuses':getServerStatuses(proxmox), 'tasks':tasks}) elif currentVm != 'none': raise Http404 elif currentNode != 'none': tasks = proxmox.nodes(currentNode).get('tasks') return render(request, 'OctaHomeProxmox/Node.html', {'links': getSideBar(request, proxmox), 'serverInfo':addWizardVeriables(request, proxmox), 'Node':currentNode, 'StorageDevices':getStorageDetails(proxmox), 'ServerStatuses':getServerStatuses(proxmox), 'tasks':tasks}) else: tasks = getAllServerTasks(proxmox) return render(request, 'OctaHomeProxmox/AllNodes.html', {'links': getSideBar(request, proxmox), 'serverInfo':addWizardVeriables(request, proxmox), 'StorageDevices':getStorageDetails(proxmox), 'ServerStatuses':getServerStatuses(proxmox), 'tasks':tasks}) raise Http404 def getVmDict(proxmox): nodes = {} for anode in proxmox.nodes.get(): vms = {} for avm in proxmox.nodes(anode['node']).openvz.get(): vms[str(avm['vmid'])] = avm for avm in proxmox.nodes(anode['node']).qemu.get(): vms[str(avm['vmid'])] = avm nodes[str(anode['node'])] = vms return nodes def addWizardVeriables(request, proxmox): nodes = [] templates = [] csrftoken = get_token(request) for node in proxmox.nodes.get(): nodes.append(node['node']) for node in proxmox.nodes.get(): nodeTemplates = [] for item in proxmox.nodes(node['node']).storage.local.content.get(): if item['content'] == 'vztmpl': nodeTemplates.append(item['volid']) templates.append({'node':node['node'], 'templates':nodeTemplates}) return {'nodes':nodes, 'templates':templates, 'csrftoken':csrftoken} def getSideBar(request, proxmox): currentPage = request.GET.get('currentPage', 'all') currentNode = request.GET.get('node', 'none') currentVz = request.GET.get('openvz', 'none') currentCt = request.GET.get('qemu', 'none') links = [{'title': 'System Stats', 'address': '/Proxmox/', 'active': getSideBarActiveState([currentNode, currentVz, currentCt], 'none')}] for node in proxmox.nodes.get(): nodeSublinks = [] containers = [] for vm in proxmox.nodes(node['node']).openvz.get(): sidebarItem = {'title': vm['vmid'] + ": " + vm['name'], 'address': '/Proxmox/?node=' + node['node'] + '&openvz=' + vm['vmid'], 'active':getSideBarActiveState(vm['vmid'], currentVz)} containers.append(sidebarItem) sidebarItem = {'title': 'CT\'s', 'sublinks':containers, 'active':''} nodeSublinks.append(sidebarItem) vms = [] for vm in proxmox.nodes(node['node']).qemu.get(): sidebarItem = {'title': vm['vmid'] + ": " + vm['name'], 'address': '/Proxmox/?node=' + node['node'] + '&qemu=' + vm['vmid'] , 'active':getSideBarActiveState(vm['vmid'], currentCt)} vms.append(sidebarItem) sidebarItem = {'title': 'VM\'s', 'sublinks':vms, 'active':''} nodeSublinks.append(sidebarItem) nodeItem = {'title': node['node'], 'address': '/Proxmox/?node=' + node['node'], 'sublinks':nodeSublinks, 'active':getSideBarActiveState(node['node'], currentNode)} links.append(nodeItem) sidebarItem = {'title': 'Add New Server', 'address': '', 'id': 'addServer' , 'active':getSideBarActiveState('add', currentPage)} links.append(sidebarItem) return links def getSideBarActiveState(sidebarItem, currentPage): if type(sidebarItem) is list: for anItem in sidebarItem: if anItem != currentPage: return '' return 'active' if sidebarItem == currentPage: return 'active' else: return '' def getAllServerTasks(proxmox): toReturn = [] for node in proxmox.nodes.get(): toReturn = toReturn + proxmox.nodes(node['node']).get('tasks') return toReturn def getServerStatuses(proxmox): containersOnline = 0 containersTotal = 0 vmsOnline = 0 vmsTotal = 0 serverUptimes = [] for node in proxmox.nodes.get(): uptime = datetime.timedelta(seconds=node['uptime']) uptimeItem = {'node':node['node'], 'uptime':uptime, 'secondUptime':node['uptime']} serverUptimes.append(uptimeItem) for vm in proxmox.nodes(node['node']).openvz.get(): containersTotal = containersTotal + 1 if vm['status'] == "running": containersOnline = containersOnline + 1 for vm in proxmox.nodes(node['node']).qemu.get(): vmsTotal = vmsTotal + 1 if vm['status'] == "running": vmsOnline = vmsOnline + 1 totalOnline = containersOnline + vmsOnline totalTotal = containersTotal + vmsTotal totalOnlinePercentage = float(100 * float(float(totalOnline) / float(totalTotal))) totalOffLinePercentage = float(100 * float(float(totalTotal - totalOnline) / totalTotal)) result = {} result['uptimes'] = serverUptimes result['containersOnline'] = str(containersOnline) result['containersTotal'] = str(containersTotal) result['vmsOnline'] = str(vmsOnline) result['vmsTotal'] = str(vmsTotal) result['totalOnline'] = str(totalOnline) result['totalTotal'] = str(totalTotal) result['totalOnlinePercentage'] = str(totalOnlinePercentage) result['totalOffLinePercentage'] = str(totalOffLinePercentage) return result def getStorageDetails(proxmox): toReturn = {} numberOfDevices = 0 numberOfNodes = 0 totalSpace = 0 totalSpaceGB = float(0) totalUsed = 0 totalUsedGB = float(0) nodeStorageDevices = [] allStorageDevice = [] for node in proxmox.nodes.get(): numberOfNodes = numberOfNodes + 1 nodeStorageDevices = proxmox.nodes(node['node']).get('storage') nodeNumberOfStorageDevices = 0 nodeTotalSpaceGb = float(0) nodeUsedSpaceGb = float(0) for nodeStorageDevice in nodeStorageDevices: name = nodeStorageDevice['storage'] numberOfDevices = numberOfDevices + 1 nodeNumberOfStorageDevices = nodeNumberOfStorageDevices + 1 totalSpace = totalSpace + int(nodeStorageDevice['total']) totalUsed = totalUsed + int(nodeStorageDevice['used']) gbTotalSpace = float(float(nodeStorageDevice['total']) / float(1073741824)) gbSpaceUsed = float(float(nodeStorageDevice['used']) / float(1073741824)) totalSpaceGB = totalSpaceGB + gbTotalSpace totalUsedGB = totalUsedGB + gbSpaceUsed nodeTotalSpaceGb = nodeTotalSpaceGb + gbTotalSpace nodeUsedSpaceGb = nodeUsedSpaceGb + gbSpaceUsed aDevice = {'node':node['node'], 'name':name, 'total':nodeStorageDevice['total'], 'used':nodeStorageDevice['used'], 'totalGb':totalSpaceGB, 'usedGb':totalUsedGB} allStorageDevice.append(aDevice) aNode = {'node':node['node'], 'totalGb':nodeTotalSpaceGb, 'usedGb':nodeUsedSpaceGb} nodeStorageDevices.append(aNode) allItem = {'total':totalSpace, 'used':totalUsed, 'nodes':numberOfNodes, 'devices':numberOfDevices, 'totalGb':totalSpaceGB, 'usedGb':totalUsedGB} toReturn['all'] = allItem toReturn['devices'] = allStorageDevice toReturn['nodes'] = nodeStorageDevices return toReturn
kkcookies99/UAST
Dataset/Leetcode/valid/62/234.java
public int XXX(int m, int n) { int[][] memo = new int[m+1][n+1]; return help(m,n,memo); } int help(int m ,int n,int[][]memo){ //base case if(m==1 || n ==1) return 1; if(memo[m][n]!=0) return memo[m][n]; memo[m][n] = help(m-1,n,memo) + help(m,n-1,memo); return memo[m][n]; }
valgur/OCP
opencascade/Transfer_FindHasher.hxx
<reponame>valgur/OCP // Created on: 1994-11-04 // Created by: <NAME> // Copyright (c) 1994-1999 Mat<NAME> // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Transfer_FindHasher_HeaderFile #define _Transfer_FindHasher_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <Standard_Boolean.hxx> class Transfer_Finder; //! FindHasher defines HashCode for Finder, which is : ask a //! Finder its HashCode ! Because this is the Finder itself which //! brings the HashCode for its Key //! //! This class complies to the template given in TCollection by //! MapHasher itself class Transfer_FindHasher { public: DEFINE_STANDARD_ALLOC //! Returns hash code for the given finder, in the range [1, theUpperBound]. //! Asks the finder its hash code, then transforms it to be in the required range //! @param theFinder the finder which hash code is to be computed //! @param theUpperBound the upper bound of the range a computing hash code must be within //! @return a computed hash code, in the range [1, theUpperBound] Standard_EXPORT static Standard_Integer HashCode (const Handle (Transfer_Finder) & theFinder, Standard_Integer theUpperBound); //! Returns True if two keys are the same. //! The test does not work on the Finders themselves but by //! calling their methods Equates Standard_EXPORT static Standard_Boolean IsEqual (const Handle(Transfer_Finder)& K1, const Handle(Transfer_Finder)& K2); protected: private: }; #endif // _Transfer_FindHasher_HeaderFile
ShowingCloud/Cancri
app/views/admin/news_types/index.json.jbuilder
json.array!(@news_types) do |news_type| json.extract! news_type, :name json.url news_type_url(news_type, format: :json) end
suzyz/leetcode_practice
p174/p174.cpp
class Solution { public: int calculateMinimumHP(vector<vector<int>>& dungeon) { int n = dungeon.size(); if (n == 0) return 0; int m = dungeon[0].size(); if (m == 0) return 0; vector<int> f(m+1,0); f[m] = 1; for (int j = m-1; j >= 0; --j) { int need = f[j+1] - dungeon[n-1][j]; f[j] = need > 0 ? need : 1; } f[m] = INT_MAX; for (int i = n-2; i >= 0; --i) for (int j = m-1; j >= 0; --j) { int need = min(f[j],f[j+1]) - dungeon[i][j]; f[j] = need > 0 ? need : 1; } return f[0]; } };
andriykislitsyn/macuitest
src/macuitest/lib/operating_system/memory_manager.py
import threading from typing import Dict from typing import List from typing import Optional import biplist from macuitest.lib import core class MemoryManager: """Interface to memory (RAM) information and manipulations on it.""" def __init__(self, executor): self._memory_slots: Optional[List[Dict[str, str]]] = None self.executor = executor def load_memory(self, percent_free: int, timeout: int = 15) -> None: """Simulate memory pressure on the system in background.""" threading.Thread( target=self.executor.execute, args=(f"memory_pressure -p {percent_free}", timeout) ).start() @property def total_memory_bytes(self) -> int: return core.convert_file_size_to_bytes(self.total_memory_str) @property def total_memory_str(self) -> str: return f"{self.total_memory} GB" @property def total_memory(self) -> int: return sum((int(bank.get("dimm_size").split()[0]) for bank in self.memory_slots)) @property def memory_banks(self) -> int: return len(self.memory_slots) @property def memory_speed(self) -> str: return self.memory_slots[0].get("dimm_speed") @property def memory_type(self) -> str: return self.memory_slots[0].get("dimm_type") @property def memory_slots(self) -> List[Dict[str, str]]: if self._memory_slots is not None: return self._memory_slots _info = bytes( self.executor.get_output("system_profiler -xml SPMemoryDataType"), encoding="utf-8" ) _slots = biplist.readPlistFromString(_info)[0].get("_items")[0].get("_items") self._memory_slots = _slots return _slots
physion/ovation-odata
src/ovation/odata/model/SourceModel.java
<gh_stars>1-10 package ovation.odata.model; import java.util.HashMap; import org.apache.log4j.Logger; import org.core4j.Func; import org.core4j.Func1; import ovation.Source; import com.google.common.collect.Maps; /** * presents Source data to the OData4J framework a * @author Ron */ public class SourceModel extends OvationModelBase<Source> { static final Logger _log = Logger.getLogger(SourceModel.class); static final HashMap<String,Class<?>> _propertyTypeMap = Maps.newHashMap(); static final HashMap<String,Class<?>> _collectionTypeMap = Maps.newHashMap(); static { addSource(_propertyTypeMap, _collectionTypeMap); } public SourceModel() { super(_propertyTypeMap, _collectionTypeMap); } public String getTypeName() { return "Source"; } public String entityName() { return "Sources"; } public Class<Source> getEntityType() { return Source.class; } public Iterable<?> getCollectionValue (Object target, String collectionName) { return getCollection((Source)target, CollectionName.valueOf(collectionName)); } public Object getPropertyValue (Object target, String propertyName) { return getProperty((Source)target, PropertyName.valueOf(propertyName)); } public Func<Iterable<Source>> allGetter() { return new Func<Iterable<Source>>() { public Iterable<Source> apply() { final Iterable<Source> queryIter = executeQueryInfo(); if (queryIter != null) { return queryIter; } return executeQuery(GET_ALL_PQL); } }; } public Func1<Source,String> idGetter() { return new Func1<Source,String>() { public String apply(Source record) { return record.getUuid(); } }; } }
offline7LY/demo
java-core/j8/src/main/java/com/lx/demo/improvement/ComparatorDemo.java
package com.lx.demo.improvement; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * @Description 大佬写点东西吧 * @auther lx7ly * @create 2019-10-23 下午6:59 */ public class ComparatorDemo { public static void main(String[] args) { final List<User> users = Arrays.asList(new User("xx", "zhang"), new User("xx", "li"), new User("zz", "zhang")); System.out.println("排序前----"); users.forEach(System.out::println); users.sort(Comparator.comparing(User::getLastName).thenComparing(User::getFirstName)); System.out.println("排序后----"); users.forEach(System.out::println); System.out.println("根据lastName长度倒序排列"); users.sort(Comparator.comparing(User::getLastName, (x, y) -> Integer.compare(y.length(), x.length()))); users.forEach(System.out::println); // null order final List<User> usersNull = Arrays.asList(new User("xx", "zhang"), new User("xx", "li"), new User("", "zhang")); System.out.println("null值优先排序, 排序前"); usersNull.sort(Comparator.comparing(User::getFirstName, Comparator.nullsFirst( Comparator.naturalOrder() ))); usersNull.forEach(System.out::println); } static class User{ public User() { } public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } private String firstName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return "User{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; } private String lastName; } }
Hyxogen/FdF
src/util/file_utils.h
/* ************************************************************************** */ /* */ /* :::::::: */ /* file_utils.h :+: :+: */ /* +:+ */ /* By: dmeijer <<EMAIL>> +#+ */ /* +#+ */ /* Created: 2022/02/02 15:21:36 by dmeijer #+# #+# */ /* Updated: 2022/02/02 15:21:36 by dmeijer ######## odam.nl */ /* */ /* ************************************************************************** */ #ifndef FILE_UTILS_H # define FILE_UTILS_H # include <ft_stdbool.h> # include "types.h" t_bool file_exits(const char *file); t_bool file_tell_size(const char *file, t_size *total_size); t_bool file_readall(const char *file, char **out, t_size *file_size); #endif
kravtsun/mapbox-gl-native
include/mbgl/storage/file_source.hpp
#pragma once #include <mbgl/storage/response.hpp> #include <mbgl/storage/resource.hpp> #include <mbgl/util/noncopyable.hpp> #include <mbgl/util/async_request.hpp> #include <functional> #include <memory> namespace mbgl { class FileSource : private util::noncopyable { public: virtual ~FileSource() = default; using Callback = std::function<void (Response)>; // Request a resource. The callback will be called asynchronously, in the same // thread as the request was made. This thread must have an active RunLoop. The // request may be cancelled before completion by releasing the returned AsyncRequest. // If the request is cancelled before the callback is executed, the callback will // not be executed. virtual std::unique_ptr<AsyncRequest> request(const Resource&, Callback) = 0; // When a file source supports optional requests, it must return true. // Optional requests are requests that aren't as urgent, but could be useful, e.g. // to cover part of the map while loading. The FileSource should only do cheap actions to // retrieve the data, e.g. load it from a cache, but not from the internet. virtual bool supportsOptionalRequests() const { return false; } }; } // namespace mbgl
Tibi02/hannablog
wp-content/plugins/wp-ultimate-recipe-premium/premium/addons/template-editor/js/preview.js
jQuery(document).ready(function() { // Only keep first recipe jQuery('.wpurp-container').first().addClass('wpurp-container-keep'); // Indicate which elements are parent to the recipe jQuery('.wpurp-container-keep').parents().each(function() { jQuery(this).addClass('wpurp-container-keep-parent'); }); // Remove all elements except for the recipe and its parents jQuery('body *').not('.wpurp-container-keep-parent, .wpurp-container-keep, .wpurp-container-keep *').remove(); jQuery('body').prepend('<div style="text-align: center; margin-bottom: 5px;"><select onchange="wpurp_preview_type(this.value)"><option value="desktop">Desktop Preview</option><option value="mobile">Mobile Preview</option></select></div>'); wpurp_preview_type('desktop'); jQuery(document).on('hover', '.wpurp-container', function(e) { var hovering = e.type == 'mouseenter'; WPUltimatePostGrid.hoverGridItem(jQuery(this), hovering); }); }); var wpurp_preview_type = function(type) { if(type == 'desktop') { jQuery('.wpurp-container').removeClass('wpurp-mobile-preview'); jQuery('.wpurp-responsive-mobile').css('display', 'none'); jQuery('.wpurp-responsive-desktop').css('display', 'block'); } else { jQuery('.wpurp-container').addClass('wpurp-mobile-preview'); jQuery('.wpurp-responsive-mobile').css('display', 'block'); jQuery('.wpurp-responsive-desktop').css('display', 'none'); } }
gurumobile/RemoteControlGalileoExam
RemoteControlGalileo/AV Capture/Kernel/Hardware.h
<gh_stars>10-100 // // Copyright (c) 2013 <NAME>. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall remain in place // in this source code. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifndef Hardware_H #define Hardware_H // todo: add support for other hardware // right now only iOS devices ^_^ namespace Hardware { enum Model { HM_Simulator = 0, // ^_^ HM_iPod_1g, HM_iPod_2g, HM_iPod_3g, HM_iPod_4g, HM_iPod_5g, // any newer models, currently HM_iPhone_1g, HM_iPhone_3g, HM_iPhone_3gs, HM_iPhone_4, HM_iPhone_4s, HM_iPhone_5, HM_iPad, HM_iPad_2, HM_iPad_3, HM_iPadMini, HM_Unknown, }; enum Family { HF_Simulator = 0, HF_iPod, HF_iPhone, HF_iPad, HF_Unknown }; Model getModel(); Family getFamily(); } #endif
jack-debug/Ares-1.0-Source-Leak
com/ares/mixin/MixinWorldProviderHell.java
<reponame>jack-debug/Ares-1.0-Source-Leak<gh_stars>1-10 package com.ares.mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; import net.minecraftforge.fml.common.eventhandler.Event; import net.minecraftforge.common.MinecraftForge; import com.ares.event.world.GetDimensionBrightness; import net.minecraft.world.WorldProviderHell; import org.spongepowered.asm.mixin.Mixin; @Mixin({ WorldProviderHell.class }) public class MixinWorldProviderHell { @ModifyConstant(method = { "generateLightBrightnessTable" }, constant = { @Constant(floatValue = 0.9f) }) private float getBrightness(final float a1) { final GetDimensionBrightness v1 = /*EL:16*/new GetDimensionBrightness(a1); MinecraftForge.EVENT_BUS.post(/*EL:17*/(Event)v1); /*SL:18*/return v1.initial; } }
inkubux/MediaSpeed
src/lib/streamer/basic-streamer.js
import mime from 'mime'; import fs from 'fs'; import stream from 'stream'; export default class BasicStreamer { constructor() { this.streamPositions = null; this.status = 200; } prepareStream(rangeHeaders, media) { const mimeType = mime.lookup(media.filePath); this.media = media; this.headers = { 'Content-Type': mimeType }; const range = false; if (range) { const parts = range.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : media.file_size - 1; const chunksize = end - start + 1; this.headers = { 'Content-Type': mimeType, 'Content-Range': `bytes ${start}-${end}/${media.file_size}`, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize }; this.status = 206; this.streamPositions = { start, end }; } } getHeaders() { return this.headers; } getStatus() { return this.status; } getStream() { let str = stream.PassThrough(); fs.createReadStream(this.media.filePath, this.streamPositions).pipe(str, { end: true }); return str; } }
Floern/generic-bot-frame
src/main/java/com/floern/genericbot/frame/redunda/RedundaService.java
/* * Floern, <EMAIL>, 2017, MIT Licence */ package com.floern.genericbot.frame.redunda; import com.floern.genericbot.frame.net.GsonLoader; import com.floern.genericbot.frame.net.HttpPostUrlEncoded; import com.floern.genericbot.frame.redunda.model.Status; import org.apache.http.client.methods.HttpPost; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class RedundaService { private static final Logger LOGGER = LoggerFactory.getLogger(RedundaService.class); private static final String REDUNDA_API_URL = "https://redunda.sobotics.org/status.json"; private final String apikey; private final String appVersion; private ScheduledExecutorService executorService; private OnStandbyStatusChangedListener standbyStatusChangedListener; private int checkInterval = 30; private TimeUnit checkIntervalUnit = TimeUnit.SECONDS; private Status lastKnownStatus; private boolean failedOver = false; /** * Create a Resunda service instance. * @param apikey Redunda API key */ public RedundaService(String apikey, String appVersion) { this.apikey = apikey; this.appVersion = appVersion; } public RedundaService setStandbyStatusChangedListener(OnStandbyStatusChangedListener standbyStatusChangedListener) { this.standbyStatusChangedListener = standbyStatusChangedListener; return this; } public RedundaService setCheckInterval(int interval, TimeUnit unit) { checkInterval = interval; checkIntervalUnit = unit; return this; } public void start() { if (executorService != null) { throw new IllegalStateException(); } executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleAtFixedRate(this::execute, 0, checkInterval, checkIntervalUnit); LOGGER.info("RedundaService started"); } private void execute() { try { HttpPost request = new HttpPostUrlEncoded(REDUNDA_API_URL, "key", apikey, "version", appVersion); new GsonLoader<>(request, Status.class) .onResult(newStatus -> { LOGGER.info(newStatus.getLocation() + " standby: " + Boolean.toString(newStatus.shouldStandby())); if (newStatus.shouldStandby()) { failedOver = false; } else if (!newStatus.shouldStandby() && lastKnownStatus != null && lastKnownStatus.shouldStandby()) { failedOver = true; } if (standbyStatusChangedListener != null) { if ((lastKnownStatus != null && lastKnownStatus.shouldStandby() != newStatus.shouldStandby()) || (lastKnownStatus == null && !newStatus.shouldStandby())) { standbyStatusChangedListener.onStandByStatusChanged(newStatus.shouldStandby()); } } lastKnownStatus = newStatus; }) .onError(Throwable::printStackTrace) .load(); } catch (Exception e) { e.printStackTrace(); } } /** * Get the location that was set by Redunda for this instance. * @return */ public String getStatusLocation() { return lastKnownStatus == null ? null : lastKnownStatus.getLocation(); } /** * Whether we are on standby. */ public boolean getStatusStandby() { return lastKnownStatus == null || lastKnownStatus.shouldStandby(); } /** * Whether we're running after a failover signal. */ public boolean failedOver() { return failedOver; } public void stop() { executorService.shutdown(); executorService = null; LOGGER.info("RedundaService stopped"); } /** * Start the Redunda service and block until we are not on standby. * @param apikey * @param appVersion * @param standbyStatusChangedListener * @return */ public static RedundaService startAndWaitForGo(String apikey, String appVersion, OnStandbyStatusChangedListener standbyStatusChangedListener) { CountDownLatch redundaHold = new CountDownLatch(1); RedundaService redundaService = new RedundaService(apikey, appVersion); redundaService.setStandbyStatusChangedListener(standby -> { standbyStatusChangedListener.onStandByStatusChanged(standby); if (standby) { LOGGER.info("STANDBY MODE ACTIVATED"); } else { LOGGER.info("STANDBY MODE DISABLED"); redundaHold.countDown(); } }); redundaService.start(); try { redundaHold.await(); } catch (InterruptedException e) { LOGGER.error("redunda hold await", e); throw new RuntimeException(e); } return redundaService; } public interface OnStandbyStatusChangedListener { void onStandByStatusChanged(boolean standby); } }
slowy07/ground-android
gnd/src/main/java/com/google/android/gnd/ui/home/BottomSheetDependentBehavior.java
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 com.google.android.gnd.ui.home; import android.content.Context; import android.util.AttributeSet; import android.view.View; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.google.android.gnd.R; /** * Base class for layout behaviors defining transitions dependent on bottom sheet changes (e.g., * scroll, expand, collapse). */ public abstract class BottomSheetDependentBehavior<V extends View> extends CoordinatorLayout.Behavior<V> { public BottomSheetDependentBehavior(Context context, AttributeSet attrs) { super(context, attrs); } /** * Overridden to define the behavior of layouts in relation to changes in the bottom sheet. In * general, this is called when the bottom sheet state changes (e.g., from hidden to collapsed), * and when the bottom sheet is scrolled up or down. */ protected abstract void onBottomSheetChanged( CoordinatorLayout parent, V child, BottomSheetMetrics metrics); @Override public boolean layoutDependsOn(CoordinatorLayout parent, V child, View dependency) { return dependency.getId() == R.id.bottom_sheet_layout; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View bottomSheet) { onBottomSheetChanged(parent, child, new BottomSheetMetrics(bottomSheet)); return false; } }
netsec/pytan
EXAMPLES/POC/pytan-integrations/patch_tanium_portal/config.py
<filename>EXAMPLES/POC/pytan-integrations/patch_tanium_portal/config.py # configure me config = { 'pytan_dir': '/Users/jolsen/gh/pytan/lib', 'tanium_username': 'Tanium User', 'tanium_password': '<PASSWORD>', 'tanium_host': '172.16.31.128', 'max_data_age': 60, 'pct_complete_threshold': 98.00, 'sync_scan_name': 'Run Patch Scan Synchronously', 'sync_scan_opts': { 'command': 'cmd /c cscript //T:3600 ..\\..\\Tools\\run-patch-scan.vbs', 'command_timeout_seconds': 1200, 'expire_seconds': 1800, }, # 'sync_install_name': 'Install Deployed Patches Synchronously', # 'sync_install_opts': { # 'command': 'cmd /c cscript //T:3600 ..\\..\\Tools\\install-patches.vbs', # 'command_timeout_seconds': 3600, # 'expire_seconds': 1200, # }, 'max_question_data_retry': 5, 'patchpkg_name': "Managed Windows Patch Deployment - {KB Article} - {Title}".format, 'patchpkg_opts': { 'command': 'cmd /c cscript //T:3600 ..\\..\\Tools\\copy-patch-files.vbs', 'expire_seconds': 7200, 'command_timeout_seconds': 3000, }, }
AllaMaevskaya/AliRoot
MUON/MUONshuttle/AliMUONTriggerDCSSubprocessor.cxx
<filename>MUON/MUONshuttle/AliMUONTriggerDCSSubprocessor.cxx<gh_stars>10-100 /************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ //----------------------------------------------------------------------------- /// \class AliMUONTriggerDCSSubprocessor /// /// A subprocessor to read Trigger DCS values for one run /// /// It simply creates a copy of the dcsAliasMap w/o information /// from the MUON TRG, and dumps this copy into the CDB /// /// \author <NAME>, Subatech //----------------------------------------------------------------------------- #include "AliMUONTriggerDCSSubprocessor.h" #include "AliMUONPreprocessor.h" #include "AliMpDEIterator.h" #include "AliMpDEManager.h" #include "AliMpConstants.h" #include "AliMpDCSNamer.h" #include "AliCDBMetaData.h" #include "AliLog.h" #include "AliDCSValue.h" #include "Riostream.h" #include "TMap.h" #include "TObjString.h" /// \cond CLASSIMP ClassImp(AliMUONTriggerDCSSubprocessor) /// \endcond //_____________________________________________________________________________ AliMUONTriggerDCSSubprocessor::AliMUONTriggerDCSSubprocessor(AliMUONPreprocessor* master) : AliMUONVSubprocessor(master, "TriggerDCS", "Get MUON Trigger HV and Current values from DCS") { /// ctor } //_____________________________________________________________________________ AliMUONTriggerDCSSubprocessor::~AliMUONTriggerDCSSubprocessor() { /// dtor } //_____________________________________________________________________________ UInt_t AliMUONTriggerDCSSubprocessor::Process(TMap* dcsAliasMap) { /// Make another alias map from dcsAliasMap, considering only MUON TRK aliases. TMap dcsMap; dcsMap.SetOwner(kTRUE); AliMpDCSNamer dcsMapNamer("TRIGGER"); AliMpDEIterator deIt; deIt.First(); TObjArray aliases; aliases.SetOwner(kTRUE); // we first generate a list of expected MTR DCS aliases we'll then look for while ( !deIt.IsDone() ) { Int_t detElemId = deIt.CurrentDEId(); if ( AliMpDEManager::GetStationType(detElemId) == AliMp::kStationTrigger) { for(Int_t iMeas=0; iMeas<AliMpDCSNamer::kNDCSMeas; iMeas++){ aliases.Add(new TObjString(dcsMapNamer.DCSAliasName(detElemId, 0, iMeas))); } } deIt.Next(); } TIter next(&aliases); TObjString* alias; Bool_t kNoAliases(kTRUE); Int_t aliasNotFound(0); Int_t valueNotFound(0); while ( ( alias = static_cast<TObjString*>(next()) ) ) { TString aliasName(alias->String()); TPair* dcsMapPair = static_cast<TPair*>(dcsAliasMap->FindObject(aliasName.Data())); if (!dcsMapPair) { ++aliasNotFound; } else { kNoAliases = kFALSE; if (!dcsMapPair->Value()) { ++valueNotFound; } else { TObjArray* values = static_cast<TObjArray*>(dcsMapPair->Value()->Clone()); RemoveValuesOutsideRun(values); dcsMap.Add(new TObjString(aliasName.Data()),values); } } } if ( kNoAliases ) { Master()->Log("ERROR : no DCS values found"); return 1; } if ( aliasNotFound ) { Master()->Log(Form("WARNING %d aliases not found",aliasNotFound)); } if ( valueNotFound ) { Master()->Log(Form("WARNING %d values not found",valueNotFound)); } Master()->Log("INFO Aliases successfully read in"); AliCDBMetaData metaData; metaData.SetBeamPeriod(0); metaData.SetResponsible("<NAME>"); metaData.SetComment("Computed by AliMUONTriggerDCSSubprocessor $Id$"); Bool_t validToInfinity(kFALSE); Bool_t result = Master()->Store("Calib","TriggerDCS",&dcsMap,&metaData,0,validToInfinity); return ( result != kTRUE); // return 0 if everything is ok }
junlon2006/camera_sdk
baytrail_sdk/version/release/baytrail/web/script/algShow.js
var UserNameLogin=$.cookie('UserNameLogin'); // var UserPassLogin=$.cookie('<PASSWORD>'); // var m_viewaudio= null; /************************************************* Function: Load_algViewer Description: 初始化智能展示界面 Input: 无 Output: 无 return: 无 *************************************************/ function Load_algViewer(){ window.parent.ChangeMenu(5); ChangeLanguage(parent.translator.szCurLanguage); if(document.all) { document.getElementById("mianAlgplugin").innerHTML ='<object classid=clsid:eb3c8939-56ae-5d53-a89a-cb2120cdcd29 id="plugin0" width="100%" height="100%" ></object>'; } else { document.getElementById("mianAlgplugin").innerHTML = '<embed type="application/x-ipcwebui" id = "plugin0" width="100%" height="100%"></embed>'; } StartRealPlay(); } /************************************************* Function: StartRealPlay Description: 开始预览 Output: 无 return: 无 *************************************************/ function StartRealPlay() { Plugin(); var videoid="1"; //视频源ID var chnid = "1"; //setTimeout("",1000); if(Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject) { setTimeout(function(){ document.getElementById("plugin0").creatFrameAss1("assframe1"); m_viewaudio="both"; //var ret=document.getElementById("plugin0").eventWebToPluginAss1("view", "start", camera_hostname,camera_port.toString(),videoid,chnid,$.cookie('authenticationinfo'),$.cookie('UserNameLogin'),$.cookie('UserPassLogin'),m_viewaudio); var ret=document.getElementById("plugin0").eventWebToPlugin("view", "start", camera_hostname,camera_port.toString(),videoid,chnid,$.cookie('authenticationinfo'),$.cookie('UserNameLogin'),$.cookie('UserPassLogin'),m_viewaudio); }, 100); } else { setTimeout(function(){ document.getElementById("plugin0").creatFrameAss1("assframe1"); document.getElementById("plugin0").getPluginVersion() m_viewaudio="both"; //var ret=document.getElementById("plugin0").eventWebToPluginAss1("view", "start", camera_hostname,camera_port.toString(),videoid,chnid,$.cookie('authenticationinfo'),$.cookie('UserNameLogin'),$.cookie('UserPassLogin'),m_viewaudio); var ret=document.getElementById("plugin0").eventWebToPlugin("view", "start", camera_hostname,camera_port.toString(),videoid,chnid,$.cookie('authenticationinfo'),$.cookie('UserNameLogin'),$.cookie('<PASSWORD>PassLogin'),m_viewaudio); }, 100); } }
bryancalisto/competitive_prog
codeo/Camino_mas_corto_tortuga/solution.py
# N, X, Y = list(map(lambda x: int(x), input().split(' '))) # print(min((Y-X) % N, (N-Y+X) % N)) # print(min(abs(Y-X) % N, abs(N-Y+X) % N)) def minMovs(N, X, Y): # N, X, Y = list(map(lambda x: int(x), input().split(' '))) # print(abs(N-max(Y, X) + min(Y, X)) % N) print(min((Y-X) % N, (N-Y+X) % N)) # print(min(abs(Y-X) % N, abs(N-max(Y, X) + min(Y, X)))) minMovs(7, 2, 6) # 3 minMovs(7, 3, 4) # 1 minMovs(7, 6, 0) # 1 minMovs(10, 9, 0) # 1 minMovs(49937, 39133, 23279) # 15854
huaweicloud/huaweicloud-sdk-java-v3
services/cpts/src/main/java/com/huaweicloud/sdk/cpts/v1/model/ListVariablesResponse.java
package com.huaweicloud.sdk.cpts.v1.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.huaweicloud.sdk.core.SdkResponse; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; /** Response Object */ public class ListVariablesResponse extends SdkResponse { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "code") private String code; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "message") private String message; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "variable_list") private List<VariableDetail> variableList = null; public ListVariablesResponse withCode(String code) { this.code = code; return this; } /** code * * @return code */ public String getCode() { return code; } public void setCode(String code) { this.code = code; } public ListVariablesResponse withMessage(String message) { this.message = message; return this; } /** message * * @return message */ public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ListVariablesResponse withVariableList(List<VariableDetail> variableList) { this.variableList = variableList; return this; } public ListVariablesResponse addVariableListItem(VariableDetail variableListItem) { if (this.variableList == null) { this.variableList = new ArrayList<>(); } this.variableList.add(variableListItem); return this; } public ListVariablesResponse withVariableList(Consumer<List<VariableDetail>> variableListSetter) { if (this.variableList == null) { this.variableList = new ArrayList<>(); } variableListSetter.accept(this.variableList); return this; } /** variable_list * * @return variableList */ public List<VariableDetail> getVariableList() { return variableList; } public void setVariableList(List<VariableDetail> variableList) { this.variableList = variableList; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ListVariablesResponse listVariablesResponse = (ListVariablesResponse) o; return Objects.equals(this.code, listVariablesResponse.code) && Objects.equals(this.message, listVariablesResponse.message) && Objects.equals(this.variableList, listVariablesResponse.variableList); } @Override public int hashCode() { return Objects.hash(code, message, variableList); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ListVariablesResponse {\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" message: ").append(toIndentedString(message)).append("\n"); sb.append(" variableList: ").append(toIndentedString(variableList)).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 "); } }
touxiong88/92_mediatek
packages/apps/CalendarImporter/tests/src/com/mediatek/calendarimporter/ShowPreviewActivityTest.java
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package com.mediatek.calendarimporter; import java.io.File; import android.content.ContentResolver; import android.content.Intent; import android.net.Uri; import android.test.ActivityInstrumentationTestCase2; import android.test.TouchUtils; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import com.mediatek.calendarimporter.utils.LogUtils; public class ShowPreviewActivityTest extends ActivityInstrumentationTestCase2<ShowPreviewActivity> { private String TAG = "ShowPreviewActivityTest"; private ShowPreviewActivity mPreviewActivity; private Uri mUri; private ContentResolver mResolver; public ShowPreviewActivityTest() { super(ShowPreviewActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); mResolver = getInstrumentation().getContext().getContentResolver(); } public void test01_startPreviewFromDBUri() { LogUtils.i(TAG, "test_startPreviewActivity"); mUri = TestUtils.addOneEventsToDB(mResolver); // add event Intent i = new Intent(); i.setData(mUri); setActivityIntent(i); mPreviewActivity = getActivity(); TestUtils.sleepForTime(TestUtils.DEFAULT_SLEEP_TIME); assertNotNull(mPreviewActivity); mPreviewActivity.finish(); TestUtils.removeTheAddedEvent(mResolver, mUri);// delete the added event } public void test02_startPreviewFromWrongFile() { File wrongVcsFile = TestUtils.addFile("wrongVcs.vcs", TestUtils.ONE_WRONG_VCS_DATA); mUri = Uri.fromFile(wrongVcsFile); Intent i = new Intent(); i.setData(mUri); setActivityIntent(i); mPreviewActivity = getActivity(); assertNotNull(mPreviewActivity); do { TestUtils.sleepForTime(TestUtils.DEFAULT_SLEEP_TIME); } while (mPreviewActivity.findViewById(R.id.preview_loading).getVisibility() != View.GONE); assertTrue(mPreviewActivity.findViewById(R.id.import_error_certain).getVisibility() == View.VISIBLE); mPreviewActivity.finish(); TestUtils.removeFile(wrongVcsFile); } public void test03_startJudgeAccountActivity() { TestUtils.addMockAccount(getInstrumentation().getContext(), "test"); File rightVcsFile = TestUtils.addFile("rightVcs.vcs", TestUtils.ONE_RIGHT_VCS_DATA); mUri = Uri.fromFile(rightVcsFile); Intent i = new Intent(); i.setData(mUri); setActivityIntent(i); mPreviewActivity = getActivity(); assertNotNull(mPreviewActivity); do { TestUtils.sleepForTime(TestUtils.DEFAULT_SLEEP_TIME); } while (mPreviewActivity.findViewById(R.id.preview_loading).getVisibility() != View.GONE); Button importButton = (Button) mPreviewActivity.findViewById(R.id.button_ok); try { TouchUtils.clickView(this, importButton); } catch (NullPointerException e) { } TestUtils.sleepForTime(TestUtils.DEFAULT_SLEEP_TIME); getInstrumentation().sendCharacterSync(KeyEvent.KEYCODE_BACK); TestUtils.sleepForTime(TestUtils.DEFAULT_SLEEP_TIME); assertTrue(mPreviewActivity.isFinishing()); TestUtils.removeTestAccounts(getInstrumentation().getContext()); TestUtils.removeFile(rightVcsFile); } }
savvasth96/fructose
src/main/java/fwcd/fructose/Option.java
package fwcd.fructose; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.ToDoubleFunction; import java.util.function.ToIntFunction; import java.util.function.ToLongFunction; import java.util.stream.Stream; /** * An immutable container that may or may not hold a non-null value. * * <p>This class closely follows the public interface * of {@link java.util.Optional}.</p> * * <p>Unlike {@link java.util.Optional} which is only designed * to support the optional return idiom, {@link Option} is * intended to be used as a general-purpose "Maybe"-type that * may be stored and serialized too.</p> * * <p>Additionally, {@link Option} is not marked as {@code final}, which * allows you to create subclasses (although it should be rarely * needed).</p> * * <p>{@link Option} forms a functional monad ({@code unit} is implemented * through {@code Option.of} and {@code bind} through {@code flatMap}). * Strictly speaking, the monad laws only apply in code that does * not rely on {@code null} as a valid value though, because {@link Option} * internally interprets {@code null} as {@code Option.empty} rather * than a valid reference.</p> */ public class Option<T> implements Serializable, Iterable<T> { private static final long serialVersionUID = -7974381950871417577L; private static final Option<?> EMPTY = new Option<>(null); private final T value; /** * Internally constructs a new {@link Option} instance. * * @param value - A nullable value */ private Option(T value) { this.value = value; } /** * Creates a new {@link Option} instance. * * @param value - A nullable value * @return An {@link Option} wrapping this value */ public static <R> Option<R> ofNullable(R value) { if (value == null) { return empty(); } else { return new Option<>(value); } } /** * Creates a new {@link Option} instance. * * @param value - A non-null value * @return An {@link Option} wrapping this value * @throws NullPointerException if the value is null */ public static <R> Option<R> of(R value) { if (value == null) { throw new NullPointerException("Tried to create a non-null Option of " + value); } return new Option<>(value); } /** * Converts a {@link java.util.Optional} to an {@link Option}. */ public static <R> Option<R> of(Optional<R> value) { return ofNullable(value.orElse(null)); } /** * Fetches an empty/absent {@link Option} instance. */ @SuppressWarnings("unchecked") public static <R> Option<R> empty() { return (Option<R>) EMPTY; } /** * Checks whether this value is present. */ public boolean isPresent() { return value != null; } /** * Invokes the consumer if the value is present * and returns this {@link Option}. * * <p>This method is analogous to {@code Stream.peek} * and is mainly intended for debugging of call chains. * Unlike {@code Stream.peek}, this method runs synchronously * and can thus be used safely for other purposes too. * If no return type is needed, {@code ifPresent} should be used * instead.</p> */ public Option<T> peek(Consumer<? super T> action) { if (value != null) { action.accept(value); } return this; } /** * Invokes the consumer if the value is present. */ public void ifPresent(Consumer<? super T> then) { if (value != null) { then.accept(value); } } /** * Invokes the first argument if the value is present, * otherwise runs the second argument. */ public void ifPresentOrElse(Consumer<? super T> then, Runnable otherwise) { if (value != null) { then.accept(value); } else { otherwise.run(); } } /** * Unwraps the value and throws an exception if absent. * * <p>Generally, you should avoid this method * and use {@code expect} or {@code orElse} instead.</p> * * @throws NoSuchElementException if absent * @return The wrapped value */ public T unwrap() { if (value == null) { throw new NoSuchElementException("Tried to unwrap an empty Option"); } return value; } /** * Unwraps the value and throws a message if absent. * * @param messageIfAbsent - The error message * @throws NoSuchElementException if absent * @return The wrapped value */ public T unwrap(String messageIfAbsent) { if (value == null) { throw new NoSuchElementException(messageIfAbsent); } return value; } /** * Returns the wrapped value in case the value is present * and matches the predicate, otherwise returns an empty * {@link Option}. */ public Option<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "Filter predicate can not be null"); if (value == null) { return this; } else { return predicate.test(value) ? this : empty(); } } /** * Returns an {@link Option} containing the result of the * function if present, otherwise returns an empty {@link Option}. */ public <R> Option<R> map(Function<? super T, ? extends R> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return empty(); } else { return of(mapper.apply(value)); } } /** * Returns an {@link Option} containing the result of the * function if this {@link Option} is present and the result * is not null, otherwise returns an empty {@link Option}. */ public <R> Option<R> mapToNullable(Function<? super T, ? extends R> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return empty(); } else { return ofNullable(mapper.apply(value)); } } /** * Returns an {@link OptionInt} containing the result of the * function if present, otherwise returns an empty {@link OptionInt}. */ public OptionInt mapToInt(ToIntFunction<? super T> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return OptionInt.empty(); } else { return OptionInt.of(mapper.applyAsInt(value)); } } /** * Returns an {@link OptionDouble} containing the result of the * function if present, otherwise returns an empty {@link OptionDouble}. */ public OptionDouble mapToDouble(ToDoubleFunction<? super T> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return OptionDouble.empty(); } else { return OptionDouble.of(mapper.applyAsDouble(value)); } } /** * Returns an {@link OptionLong} containing the result of the * function if present, otherwise returns an empty {@link OptionLong}. */ public OptionLong mapToLong(ToLongFunction<? super T> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return OptionLong.empty(); } else { return OptionLong.of(mapper.applyAsLong(value)); } } /** * Returns the result of the function if present, * otherwise returns an empty {@link Option}. */ public <R> Option<R> flatMap(Function<? super T, ? extends Option<R>> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return empty(); } else { return mapper.apply(value); } } /** * Returns the result of the function if present, * otherwise returns an empty {@link OptionInt}. */ public OptionInt flatMapToInt(Function<? super T, ? extends OptionInt> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return OptionInt.empty(); } else { return mapper.apply(value); } } /** * Returns the result of the function if present, * otherwise returns an empty {@link OptionDouble}. */ public OptionDouble flatMapToDouble(Function<? super T, ? extends OptionDouble> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return OptionDouble.empty(); } else { return mapper.apply(value); } } /** * Returns the result of the function if present, * otherwise returns an empty {@link OptionLong}. */ public OptionLong flatMapToLong(Function<? super T, ? extends OptionLong> mapper) { Objects.requireNonNull(mapper, "Mapper function can not be null"); if (value == null) { return OptionLong.empty(); } else { return mapper.apply(value); } } public Option<T> or(Supplier<Option<T>> other) { Objects.requireNonNull(other); return (value == null) ? Objects.requireNonNull(other.get()) : this; } /** * Returns this value if present, otherwise the parameter. */ public T orElse(T other) { return (value == null) ? other : value; } /** * Returns this value if present, otherwise the evaluated parameter. */ public T orElseGet(Supplier<? extends T> other) { return (value == null) ? Objects.requireNonNull(other.get()) : value; } public <E extends Throwable> T orElseThrow(Supplier<? extends E> exception) throws E { if (value == null) { throw exception.get(); } else { return value; } } /** * Converts this {@link Option} to a nullable value. */ public T orElseNull() { return value; } /** * Converts this {@link Option} to a {@link java.util.Optional}. */ public Optional<T> toOptional() { return Optional.ofNullable(value); } @Override public Iterator<T> iterator() { return (value == null) ? Collections.emptyIterator() : new SingleIterator<>(value); } public Stream<T> stream() { return (value == null) ? Stream.empty() : Stream.of(value); } /** * Converts this Option to an untyped array. */ public Object[] toArray() { return (value == null) ? new Object[0] : new Object[] {value}; } public List<T> toList() { return (value == null) ? Collections.emptyList() : Collections.singletonList(value); } public Set<T> toSet() { return (value == null) ? Collections.emptySet() : Collections.singleton(value); } /** * Converts this Option to a typed array using * the provided generator. * * <p>The generator can be concisely expressed * using a method reference: {@code String[]::new}<p> * * <p><b>This method is unsafe, which means it is * up to the programmer to verify that the value type * of this Option is assignable to the array type.</b></p> * * @param arrayConstructor - Takes the size of the array and yields an array */ @SuppressWarnings("unchecked") public <A> A[] toArrayUnchecked(IntFunction<A[]> arrayConstructor) { if (value == null) { return arrayConstructor.apply(0); } else { A[] array = arrayConstructor.apply(1); array[0] = (A) value; return array; } } /** * Converts this Option to a typed array using * the provided generator and does additional * runtime type checking. * * <p>The generator can be concisely expressed * using a method reference: {@code String[]::new}<p> * * @param arrayConstructor - Takes the size of the array and yields an array * @throws ArrayStoreException if the value type of this option is incompatible with the array type */ public <A> A[] toArray(IntFunction<A[]> arrayConstructor) { A[] array = toArrayUnchecked(arrayConstructor); if (value != null) { Class<?> arrayType = array.getClass().getComponentType(); Class<? extends Object> valueType = value.getClass(); if (!arrayType.isAssignableFrom(valueType)) { throw new ArrayStoreException("Can not store value of type " + valueType.getSimpleName() + " in array of component type " + arrayType.getSimpleName()); } } return array; } @Override public String toString() { if (value == null) { return "Option.empty"; } else { return "Option(" + value + ")"; } } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Option)) { return false; } Option<?> other = (Option<?>) obj; return Objects.equals(value, other.value); } @Override public int hashCode() { return Objects.hashCode(value); } }
spencer-melnick/simple-render
src/rendering/shader.hpp
<filename>src/rendering/shader.hpp #pragma once #include <string_view> #include <vulkan/vulkan.hpp> namespace Rendering { class Shader { public: Shader(const std::string_view& sourcePath); ~Shader(); vk::ShaderModule& getShaderModule() { return m_shaderModule.get(); } private: vk::UniqueShaderModule m_shaderModule; }; }
WowCZ/strac
semi/CNetTrain/liveDecode.py
<reponame>WowCZ/strac<filename>semi/CNetTrain/liveDecode.py<gh_stars>1-10 # outputs a decode file based on the live system output import sys, sutils, json def usage() : print "Usage:" print "python liveDecode.py dataroot dataset output_file" if len(sys.argv) != 4 : usage() sys.exit() dataroot, dataset, output_fname = sys.argv[-3:] dw = sutils.dataset_walker(dataset = dataset, dataroot=dataroot) output = { "dataset": dw.datasets, "sessions": [] } for call_num, call in enumerate(dw): session = {"session-id" : call.log["session-id"], "turns":[]} for log_turn, _ in call: live_hyps = log_turn["input"]["live"]["slu-hyps"] if len(live_hyps) == 0: live_hyps = [ { 'slu-hyp':[{'slots':[], 'act':'null'}], 'score':1.0 } ] session["turns"].append({ "slu-hyps": live_hyps }) output["sessions"].append(session) output_file = open(output_fname, "wb") json.dump(output, output_file, indent=4) output_file.close()
gamobink/anura
src/tbs_bot.cpp
<reponame>gamobink/anura<gh_stars>0 /* Copyright (C) 2003-2014 by <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <SDL.h> #include <boost/bind.hpp> #include <cstdint> #include "asserts.hpp" #include "formula.hpp" #include "preferences.hpp" #include "profile_timer.hpp" #include "tbs_bot.hpp" #include "tbs_web_server.hpp" namespace tbs { class tbs_bot_timer_proxy { public: explicit tbs_bot_timer_proxy(tbs::bot* bot) : bot_(bot) {} void cancel() { bot_ = nullptr; } void signal(const boost::system::error_code& error) { if(bot_) { bot_->process(error); } delete this; } private: tbs::bot* bot_; }; PREF_INT(tbs_bot_delay_ms, 20, "Artificial delay for tbs bots"); bot::bot(boost::asio::io_service& service, const std::string& host, const std::string& port, variant v) : session_id_(v["session_id"].as_int()), service_(service), timer_(service), host_(host), port_(port), script_(v["script"].as_list()), response_pos_(0), script_pos_(0), has_quit_(false), timer_proxy_(nullptr), on_create_(game_logic::Formula::createOptionalFormula(v["on_create"])), on_message_(game_logic::Formula::createOptionalFormula(v["on_message"])) { LOG_DEBUG("YYY: create_bot: " << intptr_t(this) << ", (" << v["on_create"].write_json() << ") -> " << intptr_t(on_create_.get())); timer_.expires_from_now(boost::posix_time::milliseconds(g_tbs_bot_delay_ms)); timer_proxy_ = new tbs_bot_timer_proxy(this); timer_.async_wait(boost::bind(&tbs_bot_timer_proxy::signal, timer_proxy_, boost::asio::placeholders::error)); } bot::~bot() { LOG_DEBUG("YYY: destroy bot: " << this); // has_quit_ = true; timer_.cancel(); if(timer_proxy_ != nullptr) { timer_proxy_->cancel(); } LOG_DEBUG("YYY: done destroy bot: " << this); } void bot::process(const boost::system::error_code& error) { timer_proxy_ = nullptr; if(has_quit_) { return; } if(error == boost::asio::error::operation_aborted) { LOG_INFO("tbs::bot::process cancelled"); return; } if(on_create_) { ///LOG_DEBUG("YYY: call on_create: " << intptr_t(this) << " -> " << intptr_t(on_create_.get())); executeCommand(on_create_->execute(*this)); on_create_.reset(); } if(ipc_client_) { ipc_client_->process(); } if((((!client_ || client_->num_requests_in_flight() == 0) && !preferences::internal_tbs_server()) || ipc_client_) && script_pos_ < script_.size()) { variant script = script_[script_pos_++]; //LOG_DEBUG("BOT: SEND @" << profile::get_tick_time() << " Sending response " << response_.size() << "/" << script_.size() << ": " << ipc_client_.get() << " " << script.write_json()); variant send = script["send"]; if(send.is_string()) { send = game_logic::Formula(send).execute(*this); } int session_id = -1; if(script.has_key("session_id")) { session_id = script["session_id"].as_int(); } ASSERT_LOG(send.is_map(), "NO REQUEST TO SEND: " << send.write_json() << " IN " << script.write_json()); game_logic::MapFormulaCallablePtr callable(new game_logic::MapFormulaCallable(this)); if(ipc_client_) { LOG_INFO("tbs_bot send using ipc_client"); ipc_client_->set_callable(callable); ipc_client_->set_handler(std::bind(&bot::handle_response, this, std::placeholders::_1, callable)); ipc_client_->send_request(send); } else { if(!client_) { client_.reset(new client(host_, port_, session_id, &service_)); } client_->set_use_local_cache(false); client_->send_request(send, callable, std::bind(&bot::handle_response, this, std::placeholders::_1, callable)); } } timer_.expires_from_now(boost::posix_time::milliseconds(g_tbs_bot_delay_ms)); timer_proxy_ = new tbs_bot_timer_proxy(this); timer_.async_wait(std::bind(&tbs_bot_timer_proxy::signal, timer_proxy_, std::placeholders::_1)); } void bot::handle_response(const std::string& type, game_logic::FormulaCallablePtr callable) { if(has_quit_) { return; } if(on_create_) { executeCommand(on_create_->execute(*this)); on_create_.reset(); } if(on_message_) { message_type_ = type; message_callable_ = callable; variant msg = callable->queryValue("message"); LOG_INFO("BOT: @" << profile::get_tick_time() << " GOT RESPONSE: " << type << ": " << msg.write_json()); runGarbageCollectionDebug("server-gc.txt"); //reapGarbageCollection(); if(msg.is_map() && msg["type"] == variant("player_quit")) { std::map<variant,variant> quit_msg; quit_msg[variant("session_id")] = variant(session_id_); std::map<variant,variant> msg; msg[variant("type")] = variant("quit"); quit_msg[variant("send")] = variant(&msg); script_.push_back(variant(&quit_msg)); } else if(msg.is_map() && msg["type"] == variant("bye")) { has_quit_ = true; ipc_client_.reset(); return; } else { const int ms = profile::get_tick_time(); //LOG_INFO("BOT: handle_message @ " << ms << " : " << type << "... ( " << callable->queryValue("message").write_json() << " )"); executeCommand(on_message_->execute(*this)); const int time_taken = profile::get_tick_time() - ms; //LOG_INFO("BOT: handled message in " << time_taken << "ms"); } } ASSERT_LOG(type != "connection_error", "GOT ERROR BACK WHEN SENDING REQUEST: " << callable->queryValue("message").write_json()); ASSERT_LOG(type == "message_received", "UNRECOGNIZED RESPONSE: " << type); variant script = script_[response_pos_]; std::vector<variant> validations; if(script.has_key("validate")) { variant validate = script["validate"]; for(int n = 0; n != validate.num_elements(); ++n) { std::map<variant,variant> m; m[variant("validate")] = validate[n][variant("expression")] + variant(" EQUALS ") + validate[n][variant("equals")]; game_logic::Formula f(validate[n][variant("expression")]); variant expression_result = f.execute(*callable); if(expression_result != validate[n][variant("equals")]) { m[variant("error")] = variant(1); } m[variant("value")] = expression_result; validations.push_back(variant(&m)); } } std::map<variant,variant> m; m[variant("message")] = callable->queryValue("message"); m[variant("validations")] = variant(&validations); ++response_pos_; //tbs::web_server::set_debug_state(generate_report()); } variant bot::getValueDefault(const std::string& key) const { if(message_callable_) { return message_callable_->queryValue(key); } return variant(); } BEGIN_DEFINE_CALLABLE_NOBASE(bot) DEFINE_FIELD(script, "[any]") std::vector<variant> s = obj.script_; return variant(&s); DEFINE_SET_FIELD obj.script_ = value.as_list(); DEFINE_FIELD(data, "any") return variant(obj.data_); DEFINE_SET_FIELD obj.data_ = value; DEFINE_FIELD(type, "string") return variant(obj.message_type_); DEFINE_FIELD(me, "any") return variant(&obj_instance); END_DEFINE_CALLABLE(bot) variant bot::generate_report() const { std::map<variant,variant> m; return variant(&m); } void bot::surrenderReferences(GarbageCollector* collector) { for(variant& script : script_) { collector->surrenderVariant(&script, "script"); } collector->surrenderPtr(&client_, "client"); collector->surrenderPtr(&ipc_client_, "ipc_client"); collector->surrenderVariant(&data_, "data"); collector->surrenderPtr(&message_callable_, "message_callable"); } }
Doriko/tessell
user/src/main/java/org/tessell/dispatch/client/DispatchAsync.java
<filename>user/src/main/java/org/tessell/dispatch/client/DispatchAsync.java package org.tessell.dispatch.client; import org.tessell.dispatch.server.ActionDispatch; import org.tessell.dispatch.shared.Action; import org.tessell.dispatch.shared.Result; import com.google.gwt.user.client.rpc.AsyncCallback; /** * This is an asynchronous equivalent of the {@link ActionDispatch} interface on the server side. * * @author <NAME> */ public interface DispatchAsync { <A extends Action<R>, R extends Result> void execute(A action, AsyncCallback<R> callback); }
XiaoMi/linden
linden-core/src/test/java/com/xiaomi/linden/core/TestLindenDynamicField.java
<filename>linden-core/src/test/java/com/xiaomi/linden/core/TestLindenDynamicField.java<gh_stars>100-1000 // Copyright 2016 Xiaomi, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.xiaomi.linden.core; import java.io.IOException; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.junit.Assert; import org.junit.Test; import com.xiaomi.linden.bql.BQLCompiler; import com.xiaomi.linden.thrift.common.LindenDocument; import com.xiaomi.linden.thrift.common.LindenField; import com.xiaomi.linden.thrift.common.LindenFieldSchema; import com.xiaomi.linden.thrift.common.LindenResult; import com.xiaomi.linden.thrift.common.LindenSchema; import com.xiaomi.linden.thrift.common.LindenSearchRequest; import com.xiaomi.linden.thrift.common.LindenType; public class TestLindenDynamicField extends TestLindenCoreBase { public LindenSchema schema; public String jsonStr = "{\n" + " \"id\": \"1\",\n" + " \"name\": \"appstore-search\",\n" + " \"level\": \"info\",\n" + " \"log\": \"search result is empty\",\n" + " \"host\": \"xiaomi-search01.bj\",\n" + " \"shard\": \"1\",\n" + " \"_dynamic\": [\n" + " {\n" + " \"mgroup\": \"misearch\",\n" + " \"_type\": \"string\"\n" + " },\n" + " {\n" + " \"cost\": 30,\n" + " \"_type\": \"long\",\n" + " },\n" + " {\n" + " \"num\": 7.7,\n" + " \"_type\": \"float\",\n" + " },\n" + " {\n" + " \"count\": 3,\n" + " \"_type\": \"int\",\n" + " },\n" + " {\n" + " \"val\": \"10.0\",\n" + " \"_type\": \"double\",\n" + " }\n" + " {\n" + " \"text\": \"this is a tokenized string field\",\n" + " \"_tokenize\": \"true\",\n" + " }\n" + " ]\n" + "}"; public TestLindenDynamicField() throws Exception { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("type", "index"); jsonObject.put("content", JSONObject.parseObject(jsonStr)); handleRequest(jsonObject.toString()); lindenCore.commit(); lindenCore.refresh(); bqlCompiler = new BQLCompiler(lindenConfig.getSchema()); } catch (IOException e) { e.printStackTrace(); } } @Override public void init() { schema = new LindenSchema().setId("id"); schema.addToFields( new LindenFieldSchema("name", LindenType.STRING).setIndexed(true).setTokenized(true) .setStored(true)); schema.addToFields( new LindenFieldSchema("level", LindenType.STRING).setIndexed(true).setStored(true)); schema.addToFields( new LindenFieldSchema("log", LindenType.STRING).setIndexed(true).setTokenized(true) .setStored(true)); schema.addToFields( new LindenFieldSchema("host", LindenType.STRING).setIndexed(true).setStored(true)); schema.addToFields( new LindenFieldSchema("shard", LindenType.INTEGER).setIndexed(true).setStored(true)); lindenConfig.setSchema(schema); } @Test public void testBuildField() throws IOException { LindenDocument lindenDocument = LindenDocumentBuilder.build(schema, JSON.parseObject(jsonStr)); List<LindenField> fields = lindenDocument.getFields(); Assert.assertEquals(true, fields.contains(new LindenField(new LindenFieldSchema() .setName("mgroup") .setType(LindenType.STRING) .setIndexed(true) .setStored(true), "misearch"))); Assert.assertEquals(true, fields.contains(new LindenField(new LindenFieldSchema() .setName("cost") .setType(LindenType.LONG) .setIndexed(true) .setStored(true), "30"))); } @Test public void testDynamicField() throws IOException { String bql = "select id,name,level,log,host,shard,cost.long,mgroup,num.float,count.int,val.double from linden by " + " query is 'name:appstore' where query is 'cost.long:{30 TO 340]' " + " source "; LindenSearchRequest request = bqlCompiler.compile(bql).getSearchRequest(); LindenResult result = lindenCore.search(request); Assert.assertEquals(0, result.getHitsSize()); bql = "select id,name,level,log,host,shard,cost.long,mgroup,num.float,count.int,val.double from linden by " + " query is 'name:appstore cost.long:{30 TO 340]' " + " source "; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); JSONObject hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals(30L, hit0Source.getLongValue("cost")); bql = "select id,name,level,log,host,shard,cost.long,mgroup,num.float,count.int,val.double from linden by " + " query is 'name:appstore' where query is 'cost.long:[30 TO 340]' " + " source "; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals(30L, hit0Source.getLongValue("cost")); bql = "select id,name,level,log,host,shard,cost.long,mgroup,num.float,count.int,val.double from linden by " + " query is '+name:appstore +cost.long:{30 TO 340]' " + " source "; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); Assert.assertEquals(0, result.getHitsSize()); bql = "select id,name,level,log,host,shard,cost.long,mgroup,num.float,count.int,val.double from linden by " + " query is 'name:appstore' where query is 'num.float:[3 TO 340]' " + " source "; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals(7.7f, hit0Source.getFloatValue("num"), 0.01); bql = "select id,name,level,log,host,shard,cost.long,mgroup,num.float,count.int,val.double from linden by " + " query is 'name:appstore' where query is 'count.int:[3 TO 340]' " + " source "; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals(3, hit0Source.getIntValue("count")); bql = "select id,name,level,log,host,shard,cost.long,mgroup,num.float,count.int,val.double from linden by " + " query is 'name:appstore' where query is 'val.double:[3 TO 340]' " + " source "; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals(10.0, hit0Source.getDoubleValue("val"), 0.01); bql = "select id,name,level,log,host,shard,cost.long,mgroup,num.float,count.int,val.double from linden by " + " query is 'name:appstore' order by val.double source"; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals(10.0, hit0Source.getDoubleValue("val"), 0.01); Assert.assertEquals("10.0", result.getHits().get(0).getFields().get("val")); bql = "select text.string from linden by query is 'name:appstore' source"; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals("this is a tokenized string field", hit0Source.getString("text")); bql = "select text from linden by query is 'name:appstore' source"; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals("this is a tokenized string field", hit0Source.getString("text")); bql = "select text from linden by query is 'text:field' source"; request = bqlCompiler.compile(bql).getSearchRequest(); result = lindenCore.search(request); hit0Source = JSON.parseObject(result.hits.get(0).getSource()); Assert.assertEquals("1", hit0Source.getString("id")); Assert.assertEquals("this is a tokenized string field", hit0Source.getString("text")); } }
ViljoenFritz/nspack
lib/masterfiles/repositories/cargo_temperature_repo.rb
<filename>lib/masterfiles/repositories/cargo_temperature_repo.rb # frozen_string_literal: true module MasterfilesApp class CargoTemperatureRepo < BaseRepo build_for_select :cargo_temperatures, label: :temperature_code, value: :id, order_by: :temperature_code build_inactive_select :cargo_temperatures, label: :temperature_code, value: :id, order_by: :temperature_code crud_calls_for :cargo_temperatures, name: :cargo_temperature, wrapper: CargoTemperature def for_select_cargo_temperatures query = <<~SQL SELECT temperature_code||' ('||set_point_temperature||')' AS code, id FROM cargo_temperatures SQL DB[query].select_map(%i[code id]) end end end
Adrninistrator/UnitTest
src/test/java/adrninistrator/test/testmock/static1/mock/defaultanswer/TestStMockDftAnsCallsRealMethodsA3.java
package adrninistrator.test.testmock.static1.mock.defaultanswer; import com.adrninistrator.static1.TestStaticPublicNonVoid2; import org.junit.Before; import org.mockito.internal.stubbing.answers.CallsRealMethods; import org.powermock.api.mockito.PowerMockito; /* 使用PowerMockito.mockStatic方法对类进行Mock,且指定默认Answer为执行真实方法 使用new CallsRealMethods() */ public class TestStMockDftAnsCallsRealMethodsA3 extends TestStMockDftAnsCallsRealMethodsBase { @Before public void init() { PowerMockito.mockStatic(TestStaticPublicNonVoid2.class, new CallsRealMethods()); } }
remz1337/ecj
contrib/lambda/ec/gp/lambda/app/churchNumerals/knownChurchNumerals/TrueSuccessor.java
/* Copyright 2014 by <NAME> Licensed under the Academic Free License version 3.0 See the file "LICENSE" for more information */ package ec.gp.lambda.app.churchNumerals.knownChurchNumerals; import java.io.Serializable; import ec.gp.GPNode; import ec.gp.lambda.*; //import ec.gp.lambda.LambdaIndividual; //import ec.gp.lambda.LambdaTree; /** * the hard-coded version of the successor function. * lambda n.lambda f.lambda x.f (n f x) */ public class TrueSuccessor extends LambdaIndividual implements Serializable{ private static final long serialVersionUID = 1; public TrueSuccessor(){ super(); LambdaTree tree = new LambdaTree(); tree.child = new LNode(); GPNode iter = tree.child; iter.children[0] = new LNode(); iter = iter.children[0]; iter.children[0] = new LNode(); iter = iter.children[0]; iter.children[0] = new PNode(); iter = iter.children[0]; iter.children[0] = new IndexNode(2); iter.children[1] = new PNode(); iter = iter.children[1]; iter.children[0] = new PNode(); iter.children[1] = new IndexNode(1); iter = iter.children[0]; iter.children[0] = new IndexNode(3); iter.children[1] = new IndexNode(2); this.trees[0] = tree; } }
luoshengming/MyReadings
books/java_cookbook_3e/src/main/java/gui_awt/ButtonDemo2c.java
package gui_awt; import java.applet.Applet; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Demonstrate use of Button */ // BEGIN main public class ButtonDemo2c extends Applet { Button b; public void init() { add(b = new Button("A button")); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showStatus("Thanks for pushing my first button!"); } }); add(b = new Button("Another button")); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showStatus("Thanks for pushing my second button!"); } }); } } // END main
omarquina/moVirt
moVirt/src/main/java/org/ovirt/mobile/movirt/rest/dto/v4/Vm.java
package org.ovirt.mobile.movirt.rest.dto.v4; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.ovirt.mobile.movirt.model.enums.VmStatus; import org.ovirt.mobile.movirt.util.IdHelper; import org.ovirt.mobile.movirt.util.RestMapper; @JsonIgnoreProperties(ignoreUnknown = true) public class Vm extends org.ovirt.mobile.movirt.rest.dto.Vm { public String status; public Host host; public Cluster cluster; public Nics nics; public org.ovirt.mobile.movirt.model.Vm toEntity(String accountId) { org.ovirt.mobile.movirt.model.Vm vm = super.toEntity(accountId); vm.setStatus(VmStatus.fromString(status)); vm.setClusterId(IdHelper.combinedIdSafe(accountId, cluster)); vm.setHostId(IdHelper.combinedIdSafe(accountId, host)); vm.setNics(RestMapper.mapToEntities(nics, accountId)); return vm; } }
hareshpatel/mage2.1.7
vendor/magento/module-catalog/view/adminhtml/web/component/image-size-field.js
/** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ define([ 'jquery', 'Magento_Ui/js/lib/validation/utils', 'Magento_Ui/js/form/element/abstract', 'Magento_Ui/js/lib/validation/validator' ], function ($, utils, Abstract, validator) { 'use strict'; validator.addRule( 'validate-image-size-range', function (value) { var dataAttrRange = /^(\d+)[Xx](\d+)$/, m; if (utils.isEmptyNoTrim(value)) { return true; } m = dataAttrRange.exec(value); return !!(m && m[1] > 0 && m[2] > 0); }, $.mage.__('This value does not follow the specified format (for example, 200x300).') ); return Abstract.extend({ /** * Checks for relevant value * * @returns {Boolean} */ isRangeCorrect: function () { return validator('validate-image-size-range', this.value()).passed; } }); });
hohner36/hexchan-engine
src/imageboard/migrations/0010_auto_20190204_1314.py
# Generated by Django 2.1.5 on 2019-02-04 13:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('imageboard', '0009_auto_20190129_1529'), ] operations = [ migrations.AlterModelOptions( name='board', options={'ordering': ['hid'], 'verbose_name': 'Board', 'verbose_name_plural': 'Boards'}, ), migrations.AlterModelOptions( name='image', options={'ordering': ['id'], 'verbose_name': 'Image', 'verbose_name_plural': 'Images'}, ), migrations.AlterModelOptions( name='post', options={'ordering': ['id'], 'verbose_name': 'Post', 'verbose_name_plural': 'Posts'}, ), migrations.AlterModelOptions( name='thread', options={'ordering': ['-updated_at'], 'verbose_name': 'Thread', 'verbose_name_plural': 'Threads'}, ), ]
CaoYouXin/serveV2
apis/blog/src/blog/service/IUserFavourRuleService.java
<filename>apis/blog/src/blog/service/IUserFavourRuleService.java package blog.service; import blog.data.EIUserFavourRule; import rest.Service; import java.util.List; public interface IUserFavourRuleService extends Service { List<EIUserFavourRule> list(); EIUserFavourRule save(EIUserFavourRule userFavourRule); List<EIUserFavourRule> listNotDisabled(); Boolean isFillRule(Long userId, Long ruleId, int limit); Boolean fullFillRule(Long userId, Long ruleId); }
jeorgedonato/spent-smart
client/src/components/Spinner/index.js
import React from 'react'; import styled from 'styled-components'; import SpinnerImg from '../spinner.gif'; const SpinnerStyle = styled.img` width: 200px; margin: auto; display: block; ` const Spinner = () => { return ( <> <SpinnerStyle src={SpinnerImg} alt="Loading..." /> </> ) } export default Spinner;
lihebi/emane
include/emane/packetinfo.h
<reponame>lihebi/emane /* * Copyright (c) 2013-2014 - Adjacent Link LLC, Bridgewater, New Jersey * Copyright (c) 2008 - DRS CenGen, LLC, Columbia, Maryland * 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 DRS CenGen, LLC nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef EMANEPACKETINFO_HEADER_ #define EMANEPACKETINFO_HEADER_ #include "emane/types.h" #include <uuid.h> namespace EMANE { /** * @class PacketInfo * * @brief Store source, destination, creation time and priority * information for a packet. * * @note Instances are immutable */ class PacketInfo { public: /** * Creates a PacketInfo instance * * @param source The src NEM * @param destination The destination NEM * @param priority The priority * @param creationTime Creation time of the packet */ PacketInfo(NEMId source, NEMId destination, Priority priority, TimePoint creationTime); /** * Creates a PacketInfo instance * * @param source The src NEM * @param destination The destination NEM * @param priority The priority * @param creationTime Creation time of the packet * @param uuid Application UUID (upstream only) */ PacketInfo(NEMId source, NEMId destination, Priority priority, TimePoint creationTime, const uuid_t & uuid); /** * Destroys an instance */ ~PacketInfo(); /** * Gets the source * * @return souce NEM id */ NEMId getSource() const; /** * Gets the destination * * @return Destination NEM * * @note May be NEM_BROADCAST_MAC_ADDRESS */ NEMId getDestination() const; /** * Gets the priority * * @ return prioroty */ Priority getPriority() const; /** * Gets the creation time * * @return creation time */ TimePoint getCreationTime() const; /** * Gets the application UUID * * @return uuid */ const uuid_t & getUUID() const; private: NEMId source_; NEMId destination_; Priority priority_; TimePoint creationTime_; uuid_t uuid_; }; } #include "emane/packetinfo.inl" #endif //EMANEPACKETINFO_HEADER_
Nyior/django-rest-paystack
paystack/services/webhook_service.py
import hashlib import hmac from django.conf import settings from rest_framework.exceptions import ValidationError from .customer_service import CustomerService from .transaction_service import TransactionService class WebhookService(object): def __init__(self, request) -> None: self.request = request def webhook_handler(self): try: secret = getattr(settings, "PAYSTACK_PRIVATE_KEY") except Exception as e: # If user hasn't declared variable raise ValidationError(e) webhook_data = self.request.data hash = hmac.new(secret, webhook_data, digestmod=hashlib.sha512).hexdigest() if hash != self.request.headers["x-paystack-signature"]: raise ValidationError("MAC authentication failed") if webhook_data["event"] == "charge.success": paystack_service = TransactionService() paystack_service.log_transaction(webhook_data["data"]) customer_service = CustomerService() customer_service.log_customer(webhook_data["data"]) return webhook_data
mF2C/COMPSsOLD
compss/runtime/resources/commons/src/main/java/es/bsc/compss/util/CloudManager.java
/* * Copyright 2002-2018 Barcelona Supercomputing Center (www.bsc.es) * * 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 es.bsc.compss.util; import es.bsc.compss.COMPSsConstants; import es.bsc.compss.log.Loggers; import es.bsc.compss.types.CloudProvider; import es.bsc.compss.connectors.ConnectorException; import es.bsc.compss.types.ResourceCreationRequest; import es.bsc.compss.types.resources.description.CloudInstanceTypeDescription; import java.io.File; import java.io.FileNotFoundException; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * The CloudManager class is an utility to manage all the cloud interactions and hide the details of each provider. */ public class CloudManager { private static final String CONNECTORS_REL_PATH = File.separator + "Runtime" + File.separator + "connectors" + File.separator; private static final String WARN_NO_COMPSS_HOME = "WARN: COMPSS_HOME not defined, no default connectors loaded"; private static final String WARN_NO_COMPSS_HOME_RESOURCES = "WARN_MSG = [COMPSS_HOME NOT DEFINED, NO DEFAULT CONNECTORS LOADED]"; private static final String WARN_NO_CONNECTORS_FOLDER = "WARN: Connectors folder not defined, no default connectors loaded"; private static final String WARN_NO_CONNECTORS_FOLDER_RESOURCES = "WARN_MSG = [CONNECTORS FOLDER NOT DEFINED, NO DEFAULT CONNECTORS LOADED]"; private static final Logger RUNTIME_LOGGER = LogManager.getLogger(Loggers.CM_COMP); private static final Logger RESOURCES_LOGGER = LogManager.getLogger(Loggers.RESOURCES); static { RUNTIME_LOGGER.debug("Loading runtime connectors to classpath..."); String compssHome = System.getenv(COMPSsConstants.COMPSS_HOME); if (compssHome == null || compssHome.isEmpty()) { RESOURCES_LOGGER.warn(WARN_NO_COMPSS_HOME_RESOURCES); RUNTIME_LOGGER.warn(WARN_NO_COMPSS_HOME); } else { String connPath = compssHome + CONNECTORS_REL_PATH; try { Classpath.loadPath(connPath, RUNTIME_LOGGER); } catch (FileNotFoundException fnfe) { ErrorManager.warn("Connector jar " + connPath + " not found."); RESOURCES_LOGGER.warn(WARN_NO_CONNECTORS_FOLDER_RESOURCES); RUNTIME_LOGGER.warn(WARN_NO_CONNECTORS_FOLDER); } } } /** * Relation between a Cloud provider name and its representation */ private final Map<String, CloudProvider> providers; private boolean useCloud; private int initialVMs = 0; private int minVMs = 0; private int maxVMs = Integer.MAX_VALUE; /** * Initializes the internal data structures * */ public CloudManager() { RUNTIME_LOGGER.info("Initializing Cloud Manager"); useCloud = false; providers = new HashMap<>(); } public int getMinVMs() { return minVMs; } public int getMaxVMs() { if (this.maxVMs > this.minVMs) { return maxVMs; } else { return this.minVMs; } } public int getInitialVMs() { int initialVMs = this.initialVMs; if (initialVMs > this.maxVMs) { initialVMs = this.maxVMs; } if (initialVMs < this.minVMs) { initialVMs = this.minVMs; } return initialVMs; } public void setMinVMs(Integer minVMs) { if (minVMs != null) { if (minVMs > 0) { this.minVMs = minVMs; if (minVMs > maxVMs) { ErrorManager .warn("Cloud: MaxVMs (" + maxVMs + ") is lower than MinVMs (" + this.minVMs + "). The current MaxVMs value (" + maxVMs + ") is ignored until MinVMs (" + this.minVMs + ") is lower than it"); } } else { this.minVMs = 0; } } } public void setMaxVMs(Integer maxVMs) { if (maxVMs != null) { if (maxVMs > 0) { this.maxVMs = maxVMs; } else { this.maxVMs = 0; } if (minVMs > maxVMs) { ErrorManager .warn("Cloud: MaxVMs (" + this.maxVMs + ") is lower than MinVMs (" + this.minVMs + "). The current MaxVMs value (" + this.maxVMs + ") is ignored until MinVMs (" + this.minVMs + ") is higher than it"); } } } public void setInitialVMs(Integer initialVMs) { if (initialVMs != null) { if (initialVMs > 0) { this.initialVMs = initialVMs; } else { this.initialVMs = 0; } } } /** * Check if Cloud is used to dynamically adapt the resource pool * * @return true if it is used */ public boolean isUseCloud() { return useCloud; } /** * Adds a new Provider to the management * * @param providerName * @param limitOfVMs * @param runtimeConnectorClass * @param connectorJarPath * @param connectorMainClass * @param connectorProperties * * @return * @throws es.bsc.compss.connectors.ConnectorException */ public CloudProvider registerCloudProvider(String providerName, Integer limitOfVMs, String runtimeConnectorClass, String connectorJarPath, String connectorMainClass, Map<String, String> connectorProperties) throws ConnectorException { CloudProvider cp = new CloudProvider(providerName, limitOfVMs, runtimeConnectorClass, connectorJarPath, connectorMainClass, connectorProperties); useCloud = true; providers.put(cp.getName(), cp); return cp; } public Collection<CloudProvider> getProviders() { return providers.values(); } public CloudProvider getProvider(String name) { if (providers.containsKey(name)) { return providers.get(name); } return null; } public void newCoreElementsDetected(List<Integer> newCores) { for (CloudProvider cp : providers.values()) { cp.newCoreElementsDetected(newCores); } } /** * ********************************************************************************************************* * ********************************************************************************************************* * RESOURCE REQUESTS MANAGEMENT * ********************************************************************************************************* * ********************************************************************************************************* */ /** * Queries the creation requests pending to be served * * @return Returns all the pending creation requests */ public List<ResourceCreationRequest> getPendingRequests() { List<ResourceCreationRequest> pendingRequests = new LinkedList<>(); for (CloudProvider cp : providers.values()) { pendingRequests.addAll(cp.getPendingRequests()); } return pendingRequests; } /** * Queries the amount of tasks that will be able to run simulataneously once all the VMs have been created * * @return Returns all the pending creation requests */ public int[] getPendingCoreCounts() { int coreCount = CoreManager.getCoreCount(); int[] pendingCoreCounts = new int[coreCount]; for (CloudProvider cp : providers.values()) { int[] providerCounts = cp.getPendingCoreCounts(); for (int coreId = 0; coreId < providerCounts.length; coreId++) { pendingCoreCounts[coreId] += providerCounts[coreId]; } } return pendingCoreCounts; } /** * CloudManager terminates all the resources obtained from any provider * * @throws ConnectorException */ public void terminateALL() throws ConnectorException { RUNTIME_LOGGER.debug("[Cloud Manager] Terminate ALL resources"); if (providers != null) { for (Entry<String, CloudProvider> vm : providers.entrySet()) { CloudProvider cp = vm.getValue(); cp.terminateAll(); } } } /** * Computes the cost per hour of the whole cloud resource pool * * @return the cost per hour of the whole pool */ public float currentCostPerHour() { float total = 0; for (CloudProvider cp : providers.values()) { total += cp.getCurrentCostPerHour(); } return total; } /** * The CloudManager notifies to all the connectors the end of generation of new tasks */ public void stopReached() { for (CloudProvider cp : providers.values()) { cp.stopReached(); } } /** * The CloudManager computes the accumulated cost of the execution * * @return cost of the whole execution */ public float getTotalCost() { float total = 0; for (CloudProvider cp : providers.values()) { total += cp.getTotalCost(); } return total; } /** * Returns how long will take a resource to be ready since the CloudManager asks for it. * * @return time required for a resource to be ready * @throws Exception * can not get the creation time for some providers. */ public long getNextCreationTime() throws Exception { long total = 0; for (CloudProvider cp : providers.values()) { total = Math.max(total, cp.getNextCreationTime()); } return total; } public long getTimeSlot() throws Exception { long total = Long.MAX_VALUE; for (CloudProvider cp : providers.values()) { total = Math.min(total, cp.getTimeSlot()); } return total; } /** * Gets the currently running machines on the cloud * * @return amount of machines on the Cloud */ public int getCurrentVMCount() { int total = 0; for (CloudProvider cp : providers.values()) { total += cp.getCurrentVMCount(); } return total; } public String getCurrentState(String prefix) { StringBuilder sb = new StringBuilder(); // Current state sb.append(prefix).append("CLOUD = [").append("\n"); sb.append(prefix).append("\t").append("CURRENT_STATE = [").append("\n"); for (CloudProvider cp : providers.values()) { sb.append(cp.getCurrentState(prefix + "\t" + "\t")); } sb.append(prefix).append("\t").append("]").append("\n"); // Pending requests sb.append(prefix).append("\t").append("PENDING_REQUESTS = [").append("\n"); for (CloudProvider cp : providers.values()) { for (ResourceCreationRequest rcr : cp.getPendingRequests()) { Map<CloudInstanceTypeDescription, int[]> composition = rcr.getRequested().getTypeComposition(); // REQUEST ARE COMPOSED OF A SINGLE INSTANCE TYPE for (CloudInstanceTypeDescription citd : composition.keySet()) { sb.append(prefix).append("\t").append("\t").append("REQUEST = ").append(citd.getName()).append("\n"); } } } sb.append(prefix).append("\t").append("]").append("\n"); sb.append(prefix).append("]"); return sb.toString(); } }
jasonlee529/code-challenge
src/main/java/cn/lee/hackerrank/algrithms/implementation/DesignerPDFViewer.java
<gh_stars>0 package cn.lee.hackerrank.algrithms.implementation; import java.util.Scanner; /** * https://www.hackerrank.com/challenges/designer-pdf-viewer/problem * <pre> * When you select a contiguous block of text in a PDF viewer, the selection is highlighted with a blue rectangle. In a new kind of PDF viewer, the selection of each word is independent of the other words; this means that each rectangular selection area forms independently around each highlighted word. For example: * * PDF-highighting.png * * In this type of PDF viewer, the width of the rectangular selection area is equal to the number of letters in the word times the width of a letter, and the height is the maximum height of any letter in the word. * * Consider a word consisting of lowercase English alphabetic letters, where each letter is wide. Given the height of each letter in millimeters (), find the total area that will be highlighted by blue rectangle in when the given word is selected in our new PDF viewer. * * Input Format * * The first line contains space-separated integers describing the respective heights of each consecutive lowercase English letter (i.e., ). * The second line contains a single word, consisting of lowercase English alphabetic letters. * * Constraints * * , where is an English lowercase letter. * Word contains no more than letters. * Output Format * * Print a single integer denoting the area of highlighted rectangle when the given word is selected. The unit of measurement for this is square millimeters (), but you must only print the integer. * * Sample Input 0 * * 1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 * abc * Sample Output 0 * * 9 * Explanation 0 * * We are highlighting the word abc: * * The tallest letter in abc is b, and . The selection area for this word is . * Note: Recall that the width of each character is . * * Sample Input 1 * * 1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 7 * zaba * Sample Output 1 * * 28 * Explanation 1 * * We are highlighting the word : * * The tallest letter in is and is . The selection area for this word is . * </pre> * Created by jason on 17-12-7. */ public class DesignerPDFViewer { public static void main(String[] args) { System.out.println((int) 'a'); design(new int[]{}, ""); } public static void input() { Scanner in = new Scanner(System.in); int[] h = new int[26]; for (int h_i = 0; h_i < 26; h_i++) { h[h_i] = in.nextInt(); } String word = in.next(); design(h, word); } private static void design(int[] ints, String s) { int max = 0; for (int i = 0; i < s.length(); i++) { int h = ints[(int) s.charAt(i) - 97]; max = max > h ? max : h; } int result = max * s.length(); System.out.print(result); } }
kametic/go-odoo
tax_adjustments_wizard.go
package odoo import ( "fmt" ) // TaxAdjustmentsWizard represents tax.adjustments.wizard model. type TaxAdjustmentsWizard struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` AdjustmentType *Selection `xmlrpc:"adjustment_type,omptempty"` Amount *Float `xmlrpc:"amount,omptempty"` CompanyCurrencyId *Many2One `xmlrpc:"company_currency_id,omptempty"` CreateDate *Time `xmlrpc:"create_date,omptempty"` CreateUid *Many2One `xmlrpc:"create_uid,omptempty"` CreditAccountId *Many2One `xmlrpc:"credit_account_id,omptempty"` Date *Time `xmlrpc:"date,omptempty"` DebitAccountId *Many2One `xmlrpc:"debit_account_id,omptempty"` DisplayName *String `xmlrpc:"display_name,omptempty"` Id *Int `xmlrpc:"id,omptempty"` JournalId *Many2One `xmlrpc:"journal_id,omptempty"` Reason *String `xmlrpc:"reason,omptempty"` TaxId *Many2One `xmlrpc:"tax_id,omptempty"` WriteDate *Time `xmlrpc:"write_date,omptempty"` WriteUid *Many2One `xmlrpc:"write_uid,omptempty"` } // TaxAdjustmentsWizards represents array of tax.adjustments.wizard model. type TaxAdjustmentsWizards []TaxAdjustmentsWizard // TaxAdjustmentsWizardModel is the odoo model name. const TaxAdjustmentsWizardModel = "tax.adjustments.wizard" // Many2One convert TaxAdjustmentsWizard to *Many2One. func (taw *TaxAdjustmentsWizard) Many2One() *Many2One { return NewMany2One(taw.Id.Get(), "") } // CreateTaxAdjustmentsWizard creates a new tax.adjustments.wizard model and returns its id. func (c *Client) CreateTaxAdjustmentsWizard(taw *TaxAdjustmentsWizard) (int64, error) { return c.Create(TaxAdjustmentsWizardModel, taw) } // UpdateTaxAdjustmentsWizard updates an existing tax.adjustments.wizard record. func (c *Client) UpdateTaxAdjustmentsWizard(taw *TaxAdjustmentsWizard) error { return c.UpdateTaxAdjustmentsWizards([]int64{taw.Id.Get()}, taw) } // UpdateTaxAdjustmentsWizards updates existing tax.adjustments.wizard records. // All records (represented by ids) will be updated by taw values. func (c *Client) UpdateTaxAdjustmentsWizards(ids []int64, taw *TaxAdjustmentsWizard) error { return c.Update(TaxAdjustmentsWizardModel, ids, taw) } // DeleteTaxAdjustmentsWizard deletes an existing tax.adjustments.wizard record. func (c *Client) DeleteTaxAdjustmentsWizard(id int64) error { return c.DeleteTaxAdjustmentsWizards([]int64{id}) } // DeleteTaxAdjustmentsWizards deletes existing tax.adjustments.wizard records. func (c *Client) DeleteTaxAdjustmentsWizards(ids []int64) error { return c.Delete(TaxAdjustmentsWizardModel, ids) } // GetTaxAdjustmentsWizard gets tax.adjustments.wizard existing record. func (c *Client) GetTaxAdjustmentsWizard(id int64) (*TaxAdjustmentsWizard, error) { taws, err := c.GetTaxAdjustmentsWizards([]int64{id}) if err != nil { return nil, err } if taws != nil && len(*taws) > 0 { return &((*taws)[0]), nil } return nil, fmt.Errorf("id %v of tax.adjustments.wizard not found", id) } // GetTaxAdjustmentsWizards gets tax.adjustments.wizard existing records. func (c *Client) GetTaxAdjustmentsWizards(ids []int64) (*TaxAdjustmentsWizards, error) { taws := &TaxAdjustmentsWizards{} if err := c.Read(TaxAdjustmentsWizardModel, ids, nil, taws); err != nil { return nil, err } return taws, nil } // FindTaxAdjustmentsWizard finds tax.adjustments.wizard record by querying it with criteria. func (c *Client) FindTaxAdjustmentsWizard(criteria *Criteria) (*TaxAdjustmentsWizard, error) { taws := &TaxAdjustmentsWizards{} if err := c.SearchRead(TaxAdjustmentsWizardModel, criteria, NewOptions().Limit(1), taws); err != nil { return nil, err } if taws != nil && len(*taws) > 0 { return &((*taws)[0]), nil } return nil, fmt.Errorf("tax.adjustments.wizard was not found") } // FindTaxAdjustmentsWizards finds tax.adjustments.wizard records by querying it // and filtering it with criteria and options. func (c *Client) FindTaxAdjustmentsWizards(criteria *Criteria, options *Options) (*TaxAdjustmentsWizards, error) { taws := &TaxAdjustmentsWizards{} if err := c.SearchRead(TaxAdjustmentsWizardModel, criteria, options, taws); err != nil { return nil, err } return taws, nil } // FindTaxAdjustmentsWizardIds finds records ids by querying it // and filtering it with criteria and options. func (c *Client) FindTaxAdjustmentsWizardIds(criteria *Criteria, options *Options) ([]int64, error) { ids, err := c.Search(TaxAdjustmentsWizardModel, criteria, options) if err != nil { return []int64{}, err } return ids, nil } // FindTaxAdjustmentsWizardId finds record id by querying it with criteria. func (c *Client) FindTaxAdjustmentsWizardId(criteria *Criteria, options *Options) (int64, error) { ids, err := c.Search(TaxAdjustmentsWizardModel, criteria, options) if err != nil { return -1, err } if len(ids) > 0 { return ids[0], nil } return -1, fmt.Errorf("tax.adjustments.wizard was not found") }
p2pcommons/sdk-js
tests/example-key.js
exports.exampleKey1 = '4e01f6848573dcc0a712bd2482e6a3074310757448cd4a78fe219547fc2e484f' exports.exampleKey1V5 = '4e01f6848573dcc0a712bd2482e6a3074310757448cd4a78fe219547fc2e484f+5' exports.exampleKey1V123 = '4e01f6848573dcc0a712bd2482e6a3074310757448cd4a78fe219547fc2e484f+123' exports.exampleKey2 = '<KEY>' exports.exampleKey2V5 = '<KEY>' exports.exampleKey2V40 = '<KEY>' exports.exampleKey2V123 = '<KEY>' exports.exampleKey3 = 'cca6eb69a3ad6104ca31b9fee7832d74068db16ef2169eaaab5b48096e128342' exports.exampleKey3V5 = 'cca6eb69a3ad6104ca31b9fee7832d74068db16ef2169eaaab5b48096e128342+5' exports.exampleKey4 = '<KEY>' exports.exampleKey5V12 = '<KEY>' exports.exampleKey6V4032 = '527f404aa77756b91cba4e3ba9fe30f72ee3eb5eef0f4da87172745f9389d1e5+4032'
ant512/ReallyBadEggs
include/bmp/greenblockleftbmp.h
<gh_stars>0 #ifndef _GREENBLOCKLEFTBMP_H_ #define _GREENBLOCKLEFTBMP_H_ #include <bitmapwrapper.h> class GreenBlockLeftBmp : public WoopsiGfx::BitmapWrapper { public: GreenBlockLeftBmp(); }; #endif
nageshwarrao19/BUILD
BUILD_UserResearch/client/tests/directives-participant-invitation.spec.js
/*global chai, sinon, inject */ /*eslint no-unused-expressions:0 */ 'use strict'; var expect = chai.expect; var userResearchModule; describe('User Research>> Dependencies test for ParticipantInvitationDirectiveCtrl', function () { before(function () { userResearchModule = angular.module('UserResearch'); }); it('User Research module should be registered', function () { expect(userResearchModule).not.to.equal(null); }); it('should have a ParticipantInvitationDirectiveCtrl controller', function () { expect(userResearchModule.ParticipantInvitationDirectiveCtrl).not.to.equal(null); }); }); describe('Unit tests for ParticipantInvitationDirectiveCtrl', function () { var scope, httpBackend, uiError = { create: function () {} }, // Mock data stateParams = { questionId: 'questionId1', studyId: 'studyId', currentProject: 'projectId' }, currentStudy = { name: 'test', description: 'test description', participants: [{_id: 'participant1', name: '<NAME>', avatar_url: 'http://api'}, {_id: 'participant2', name: '<NAME>', avatar_url: 'http://api'}], status: 'draft', _id: stateParams.studyId, questions: [{ _id: 'questionId1', text: 'url1 question1', ordinal: 0, url: 'url1' }, { _id: 'questionId2', text: 'url2 question1', ordinal: 1, url: 'url2' }] }; beforeEach(module('UserResearch')); beforeEach(module('common.ui.elements')); beforeEach(module('shell.aside')); beforeEach(module('shell.dashboard')); beforeEach(module('shell.projectLandingPage')); beforeEach(module('ngResource')); beforeEach(module(function ($provide) { $provide.value('$stateParams', stateParams); })); beforeEach(inject(function ($injector, $rootScope, $timeout, $controller, $q, $httpBackend) { httpBackend = $httpBackend; scope = $rootScope.$new(); $controller('ParticipantInvitationDirectiveCtrl', { $scope: scope, $stateParams: stateParams, uiError: uiError, Studies: {currentStudy: currentStudy} }); })); /*** TESTS ************************************************************************************/ it('should initialize variables', function () { expect(scope.countNewInvite).to.equal(0); expect(scope.inviteList.length).to.equal(scope.countNewInvite); }); it('should have a properly working ParticipantInvitationDirectiveCtrl controller', function () { // new new email var email1 = '<EMAIL>'; var email2 = '<EMAIL>'; var emailToRemove = email2; scope.addInvitee(email1); expect(scope.inviteList.length).to.equal(1); expect(scope.countNewInvite).to.equal(1); scope.addInvitee(email2); expect(scope.inviteList.length).to.equal(2); expect(scope.countNewInvite).to.equal(2); scope.removeInvite(emailToRemove); expect(scope.inviteList.length).to.equal(1); expect(scope.countNewInvite).to.equal(1); scope.addInvitee(email2); expect(scope.inviteList.length).to.equal(2); expect(scope.countNewInvite).to.equal(2); //Duplicate email var uiErrorSpy = sinon.spy(uiError, 'create'); scope.addInvitee(email1); expect(scope.inviteList.length).to.equal(2); expect(scope.countNewInvite).to.equal(2); uiErrorSpy.should.have.been.called; //Regex Test var pattern = new RegExp('/^[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/'); var invalidEmail = 'nvalidEmail@'; expect(pattern.test(invalidEmail)).to.false; invalidEmail = '<EMAIL>'; expect(pattern.test(invalidEmail)).to.false; invalidEmail = 'nvalidEmail.test.com'; expect(pattern.test(invalidEmail)).to.false; }); /*** TESTS ************************************************************************************/ afterEach(function () { httpBackend.verifyNoOutstandingExpectation(); httpBackend.verifyNoOutstandingRequest(); }); });
mikewang/ruoyi-nriam
ruoyi-project/src/main/java/com/ruoyi/performance/mapper/PerAddscoreapplyMapper.java
<gh_stars>0 package com.ruoyi.performance.mapper; import com.ruoyi.performance.domain.PerAddscoreapply; import java.util.List; public interface PerAddscoreapplyMapper { List<PerAddscoreapply> selectPerAddscoreapply(PerAddscoreapply record); PerAddscoreapply selectPerAddscoreapplyById(Integer applyid); int insertPerAddscoreapply(PerAddscoreapply record); int updatePerAddscoreapply(PerAddscoreapply record); int updatePerAddscoreapplyDeletedById(Integer applyid); // int updatePerAddscoreapplyConfirm(PerAddscoreapply record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PER_AddScoreApply * * @mbg.generated Tue Mar 23 09:30:21 CST 2021 */ PerAddscoreapply selectByPrimaryKey(Integer applyid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PER_AddScoreApply * * @mbg.generated Tue Mar 23 09:30:21 CST 2021 */ List<PerAddscoreapply> selectAll(); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table PER_AddScoreApply * * @mbg.generated Tue Mar 23 09:30:21 CST 2021 */ }
jkdubr/Proj4
Pod/Classes/Projection/MOBProjectionEPSG6271.h
<gh_stars>1-10 #import "MOBProjection.h" @interface MOBProjectionEPSG6271 : MOBProjection @end
uktrade/enquiry-mgmt-tool
app/enquiries/tests/test_adobe_integration.py
<filename>app/enquiries/tests/test_adobe_integration.py<gh_stars>1-10 import datetime from unittest import mock from django.conf import settings from django.test import TestCase from django.utils import timezone from faker import Faker from freezegun import freeze_time import app.enquiries.ref_data as ref_data from app.enquiries.common import email_campaign_utils as campaign from app.enquiries.common.adobe import AdobeClient from app.enquiries.models import Enquiry, Enquirer, EnquiryActionLog faker = Faker() class TestAdobeCampaign(TestCase): @freeze_time() def setUp(self): self.enquirer = Enquirer.objects.create( first_name=faker.name(), last_name=faker.name(), email=faker.email(), job_title='Manager', phone_country_code='1', phone=faker.phone_number(), request_for_call=ref_data.RequestForCall.YES_AFTERNOON.value, ) self.enquiry = Enquiry.objects.create( enquirer=self.enquirer, company_name=faker.company(), company_hq_address=faker.address(), date_received=datetime.datetime.now(), enquiry_stage=ref_data.EnquiryStage.NON_RESPONSIVE.value, how_they_heard_dit=ref_data.HowDidTheyHear.INTERNET_SEARCH.value, ist_sector=ref_data.ISTSector.AEM.value, primary_sector=ref_data.PrimarySector.AEROSPACE.value, website='http://example.com', ) self.enquiry_done = Enquiry.objects.create( enquirer=self.enquirer, company_name=faker.company(), company_hq_address=faker.address(), date_received=datetime.datetime.now(), enquiry_stage=ref_data.EnquiryStage.SENT_TO_POST.value, how_they_heard_dit=ref_data.HowDidTheyHear.INTERNET_SEARCH.value, ist_sector=ref_data.ISTSector.AEM.value, primary_sector=ref_data.PrimarySector.AEROSPACE.value, website='http://example.com', ) self.additional_data = { 'companyName': self.enquiry.company_name, 'companyHQAddress': self.enquiry.company_hq_address, 'country': self.enquiry.country, 'enquiry_stage': self.enquiry.enquiry_stage, 'howTheyHeard_DIT': self.enquiry.how_they_heard_dit, 'istSector': self.enquiry.ist_sector, 'jobTitle': self.enquiry.enquirer.job_title, 'phone': self.enquiry.enquirer.phone, 'primarySector': self.enquiry.primary_sector, 'requestForCall': self.enquiry.enquirer.request_for_call, 'website': self.enquiry.website, 'uploadDate': timezone.now().strftime('%Y-%m-%d %H:%M:%S'), 'enquiryDate': self.enquiry.created.strftime('%Y-%m-%d %H:%M:%S'), 'ditSource': campaign.ENQUIRY_SOURCE, } @freeze_time() def test_serialize_enquiry(self): override = { 'phone': '+14151234', 'jobTitle': 'CEO' } serialized = campaign.serialize_enquiry(self.enquiry, **override) assert 'jobTitle' in serialized assert serialized['jobTitle'] == override['jobTitle'] assert serialized['phone'] == override['phone'] @freeze_time() @mock.patch('app.enquiries.common.adobe.AdobeClient.get_token') @mock.patch('app.enquiries.common.adobe.AdobeClient.create_staging_profile') def test_process_latest_enquiries(self, mock_staging, mock_token): mock_staging.return_value = {'PKey': 1} mock_token.return_value = 'token' campaign.process_latest_enquiries() client = AdobeClient() client.create_staging_profile.assert_called_with( data=campaign.serialize_enquiry(self.enquiry) ) @freeze_time() @mock.patch('app.enquiries.common.adobe.AdobeClient.get_token') @mock.patch('app.enquiries.common.adobe.AdobeClient.start_workflow') @mock.patch('app.enquiries.common.adobe.AdobeClient.create_staging_profile') def test_process_workflow_kickoff(self, mock_staging, mock_wf, mock_token): mock_staging.return_value = {'PKey': 1} mock_wf.return_value = {} mock_token.return_value = 'token' campaign.process_latest_enquiries() client = AdobeClient() client.create_staging_profile.assert_called_with( data=campaign.serialize_enquiry(self.enquiry) ) client.start_workflow.assert_called_with(settings.ADOBE_STAGING_WORKFLOW) @freeze_time() @mock.patch('app.enquiries.common.adobe.AdobeClient.get_token') @mock.patch('app.enquiries.common.as_utils.hawk_request') @mock.patch('app.enquiries.common.adobe.AdobeClient.start_workflow') @mock.patch('app.enquiries.common.adobe.AdobeClient.create_staging_profile') def test_process_second_qualification(self, mock_staging, mock_wf, mock_as, mock_token): mock_staging.return_value = {'PKey': 1} mock_wf.return_value = {} mock_token.return_value = 'token' mock_as.return_value.ok = True mock_as.return_value.json.return_value = { 'hits': { 'hits': [ { '_source': { 'object': { settings.ACTIVITY_STREAM_ENQUIRY_DATA_OBJ: { 'emt_id': self.enquiry.id, 'phone_number': '0771231234', 'arrange_callback': 'yes', } } } } ] } } campaign.process_second_qualifications() client = AdobeClient() client.create_staging_profile.assert_called_once_with( data=campaign.serialize_enquiry(self.enquiry, **{ 'phone': '0771231234', 'phoneConsent': True, 'enquiry_stage': ref_data.EnquiryStage.NURTURE_AWAITING_RESPONSE, 'uploadDate': timezone.now().strftime('%Y-%m-%d %H:%M:%S'), }) ) client.start_workflow.assert_called_with(settings.ADOBE_STAGING_WORKFLOW) @freeze_time() @mock.patch('app.enquiries.common.adobe.AdobeClient.get_token') @mock.patch('app.enquiries.common.as_utils.hawk_request') def test_process_second_qualification_invalid_data(self, mock_as, mock_token): for emt_id, was_called in [ ('None', True), ('-1', True), (1.2, True), (None, False), ("", False), ]: with mock.patch( 'app.enquiries.common.email_campaign_utils.process_enquiry_update' ) as mock_update: phone = '0771231234' mock_token.return_value = 'token' mock_as.return_value.ok = True mock_as.return_value.json.return_value = { 'hits': { 'hits': [ { '_source': { 'object': { settings.ACTIVITY_STREAM_ENQUIRY_DATA_OBJ: { 'emt_id': emt_id, 'phone_number': phone, 'arrange_callback': 'yes', } } } } ] } } campaign.process_second_qualifications() assert mock_update.called is was_called if was_called: mock_update.assert_called_with(emt_id=emt_id, phone=phone, consent=True) @freeze_time() @mock.patch('app.enquiries.common.adobe.AdobeClient.get_token') @mock.patch('app.enquiries.common.adobe.AdobeClient.start_workflow') @mock.patch('app.enquiries.common.adobe.AdobeClient.create_staging_profile') def test_process_engaged(self, mock_staging, mock_wf, mock_token): mock_staging.return_value = {'PKey': 2} mock_wf.return_value = {} mock_token.return_value = 'token' EnquiryActionLog.objects.create( enquiry=self.enquiry_done, action=ref_data.EnquiryAction.EMAIL_CAMPAIGN_SUBSCRIBE, ) campaign.process_engaged_enquiries() client = AdobeClient() client.create_staging_profile.assert_called_once_with( data=campaign.serialize_enquiry(self.enquiry_done, **{ 'enquiry_stage': campaign.EXIT_STAGE.value, 'uploadDate': timezone.now().strftime('%Y-%m-%d %H:%M:%S'), }) ) client.start_workflow.assert_called_with(settings.ADOBE_STAGING_WORKFLOW) @freeze_time() def test_log_action(self): action = ref_data.EnquiryAction.EMAIL_CAMPAIGN_SUBSCRIBE campaign.log_action( action=action, enquiry=self.enquiry, emt_id=self.enquiry.id, action_data={'PKey': 1} ) last_action_date = EnquiryActionLog.get_last_action_date(action) self.assertEqual(last_action_date.enquiry.id, self.enquiry.id)
ololx/restful-data-storing-instances
active-jdbc/src/main/java/org/orm/patterns/instances/active/jdbc/ActiveJdbcApplication.java
package org.orm.patterns.instances.active.jdbc; import org.orm.patterns.instances.commons.CommonsApplication; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * The type ActiveJdbc configuration. */ @SpringBootApplication(scanBasePackageClasses = { CommonsApplication.class, ActiveJdbcApplication.class }) public class ActiveJdbcApplication { /** * The entry point of application. * * @param args the input arguments * @throws Exception the exception */ public static void main(String[] args) throws Exception { SpringApplication.run(ActiveJdbcApplication.class, args); } }
Kyle9021/trireme-lib
controller/pkg/ebpf/ebpf_linux.go
<reponame>Kyle9021/trireme-lib<gh_stars>100-1000 // +build !rhel6 package ebpf import ( "bytes" "encoding/binary" "os" "path/filepath" "strconv" "strings" "unsafe" bpflib "github.com/iovisor/gobpf/elf" "github.com/iovisor/gobpf/pkg/bpffs" provider "go.aporeto.io/enforcerd/trireme-lib/controller/pkg/aclprovider" "go.aporeto.io/enforcerd/trireme-lib/controller/pkg/connection" "go.aporeto.io/enforcerd/trireme-lib/controller/pkg/ebpf/bpfbuild" "go.uber.org/zap" ) type ebpfModule struct { m *bpflib.Module sessionMap *bpflib.Map bpfPath string } type flow struct { srcIP uint32 dstIP uint32 srcPort uint16 dstPort uint16 } const bpfPath = "/sys/fs/bpf/" const bpfPrefix = "app-ack" func removeOldBPFFiles() { removeFiles := func(path string, info os.FileInfo, err error) error { if strings.Contains(path, bpfPrefix) { if err := os.Remove(path); err != nil { zap.L().Debug("Failed to remove file", zap.String("path", path), zap.Error(err)) } } return nil } filepath.Walk(bpfPath, removeFiles) // nolint } // IsEBPFSupported is called once by the master enforcer to test if // the system supports eBPF. func IsEBPFSupported() bool { if err := bpffs.Mount(); err != nil { zap.L().Info("bpf mount failed", zap.Error(err)) return false } var bpf BPFModule if bpf = LoadBPF(); bpf == nil { return false } if err := provider.TestIptablesPinned(bpf.GetBPFPath()); err != nil { zap.L().Info("Kernel doesn't support iptables pinned path", zap.Error(err)) return false } removeOldBPFFiles() return true } // LoadBPF loads the bpf object in the memory and also pins the bpf to the file system. func LoadBPF() BPFModule { bpf := &ebpfModule{} bpf.bpfPath = bpfPath + bpfPrefix + strconv.Itoa(os.Getpid()) if err := os.Remove(bpf.bpfPath); err != nil { if !os.IsNotExist(err) { zap.L().Debug("Failed to remove bpf file", zap.Error(err)) } } buf, err := bpfbuild.Asset("socket-filter-bpf.o") if err != nil { zap.L().Info("Failed to locate asset socket-filter-bpf", zap.Error(err)) return nil } reader := bytes.NewReader(buf) m := bpflib.NewModuleFromReader(reader) if err := m.Load(nil); err != nil { zap.L().Info("Failed to load BPF in kernel", zap.Error(err)) return nil } sfAppAck := m.SocketFilter("socket/app_ack") if sfAppAck == nil { zap.L().Info("Failed to load socket filter app_ack") return nil } if err := bpflib.PinObject(sfAppAck.Fd(), bpf.bpfPath); err != nil { zap.L().Info("Failed to pin bpf to file system", zap.Error(err)) return nil } sessionMap := m.Map("sessions") if sessionMap == nil { zap.L().Info("Failed to load sessions map") return nil } bpf.m = m bpf.sessionMap = sessionMap return bpf } func (ebpf *ebpfModule) CreateFlow(tcpTuple *connection.TCPTuple) { var key flow var val uint8 key.srcIP = binary.BigEndian.Uint32(tcpTuple.SourceAddress) key.dstIP = binary.BigEndian.Uint32(tcpTuple.DestinationAddress) key.srcPort = tcpTuple.SourcePort key.dstPort = tcpTuple.DestinationPort val = 1 err := ebpf.m.UpdateElement(ebpf.sessionMap, unsafe.Pointer(&key), unsafe.Pointer(&val), 0) if err != nil { zap.L().Debug("Update bpf map failed", zap.String("packet", tcpTuple.String()), zap.Error(err)) } } func (ebpf *ebpfModule) RemoveFlow(tcpTuple *connection.TCPTuple) { var key flow key.srcIP = binary.BigEndian.Uint32(tcpTuple.SourceAddress) key.dstIP = binary.BigEndian.Uint32(tcpTuple.DestinationAddress) key.srcPort = tcpTuple.SourcePort key.dstPort = tcpTuple.DestinationPort err := ebpf.m.DeleteElement(ebpf.sessionMap, unsafe.Pointer(&key)) if err != nil { zap.L().Debug("Delete bpf map failed", zap.String("packet", tcpTuple.String()), zap.Error(err)) } } func (ebpf *ebpfModule) GetBPFPath() string { return ebpf.bpfPath } func (ebpf *ebpfModule) Cleanup() { if err := os.Remove(ebpf.bpfPath); err != nil { zap.L().Error("Failed to remove bpf file during cleanup", zap.Error(err)) } }
pauljriley/ChuckNorrisJokes
app/src/main/java/uk/me/paulriley/chucknorrisjokes/views/endless/JokesAdapter.java
<filename>app/src/main/java/uk/me/paulriley/chucknorrisjokes/views/endless/JokesAdapter.java package uk.me.paulriley.chucknorrisjokes.views.endless; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import uk.me.paulriley.chucknorrisjokes.R; import static uk.me.paulriley.chucknorrisjokes.utility.StringFormating.fromHtml; public class JokesAdapter extends RecyclerView.Adapter<JokesViewHolder> { private List<String> jokes = new ArrayList<>(); public void setData(List<String> jokes) { this.jokes.addAll(jokes); } @Override public JokesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); View view = LayoutInflater.from(context).inflate(R.layout.joke_card, parent, false); return new JokesViewHolder(view); } @Override public void onBindViewHolder(JokesViewHolder holder, int position) { String joke = jokes.get(position); holder.joke.setText(fromHtml(joke)); } @Override public int getItemCount() { return jokes.size(); } }
Sunrisepeak/Linux2.6-Reading
drivers/clk/mediatek/clk-mt8195-vdo0.c
<filename>drivers/clk/mediatek/clk-mt8195-vdo0.c // SPDX-License-Identifier: GPL-2.0-only // // Copyright (c) 2021 MediaTek Inc. // Author: <NAME> <<EMAIL>> #include "clk-gate.h" #include "clk-mtk.h" #include <dt-bindings/clock/mt8195-clk.h> #include <linux/clk-provider.h> #include <linux/platform_device.h> static const struct mtk_gate_regs vdo0_0_cg_regs = { .set_ofs = 0x104, .clr_ofs = 0x108, .sta_ofs = 0x100, }; static const struct mtk_gate_regs vdo0_1_cg_regs = { .set_ofs = 0x114, .clr_ofs = 0x118, .sta_ofs = 0x110, }; static const struct mtk_gate_regs vdo0_2_cg_regs = { .set_ofs = 0x124, .clr_ofs = 0x128, .sta_ofs = 0x120, }; #define GATE_VDO0_0(_id, _name, _parent, _shift) \ GATE_MTK(_id, _name, _parent, &vdo0_0_cg_regs, _shift, &mtk_clk_gate_ops_setclr) #define GATE_VDO0_1(_id, _name, _parent, _shift) \ GATE_MTK(_id, _name, _parent, &vdo0_1_cg_regs, _shift, &mtk_clk_gate_ops_setclr) #define GATE_VDO0_2(_id, _name, _parent, _shift) \ GATE_MTK(_id, _name, _parent, &vdo0_2_cg_regs, _shift, &mtk_clk_gate_ops_setclr) static const struct mtk_gate vdo0_clks[] = { /* VDO0_0 */ GATE_VDO0_0(CLK_VDO0_DISP_OVL0, "vdo0_disp_ovl0", "top_vpp", 0), GATE_VDO0_0(CLK_VDO0_DISP_COLOR0, "vdo0_disp_color0", "top_vpp", 2), GATE_VDO0_0(CLK_VDO0_DISP_COLOR1, "vdo0_disp_color1", "top_vpp", 3), GATE_VDO0_0(CLK_VDO0_DISP_CCORR0, "vdo0_disp_ccorr0", "top_vpp", 4), GATE_VDO0_0(CLK_VDO0_DISP_CCORR1, "vdo0_disp_ccorr1", "top_vpp", 5), GATE_VDO0_0(CLK_VDO0_DISP_AAL0, "vdo0_disp_aal0", "top_vpp", 6), GATE_VDO0_0(CLK_VDO0_DISP_AAL1, "vdo0_disp_aal1", "top_vpp", 7), GATE_VDO0_0(CLK_VDO0_DISP_GAMMA0, "vdo0_disp_gamma0", "top_vpp", 8), GATE_VDO0_0(CLK_VDO0_DISP_GAMMA1, "vdo0_disp_gamma1", "top_vpp", 9), GATE_VDO0_0(CLK_VDO0_DISP_DITHER0, "vdo0_disp_dither0", "top_vpp", 10), GATE_VDO0_0(CLK_VDO0_DISP_DITHER1, "vdo0_disp_dither1", "top_vpp", 11), GATE_VDO0_0(CLK_VDO0_DISP_OVL1, "vdo0_disp_ovl1", "top_vpp", 16), GATE_VDO0_0(CLK_VDO0_DISP_WDMA0, "vdo0_disp_wdma0", "top_vpp", 17), GATE_VDO0_0(CLK_VDO0_DISP_WDMA1, "vdo0_disp_wdma1", "top_vpp", 18), GATE_VDO0_0(CLK_VDO0_DISP_RDMA0, "vdo0_disp_rdma0", "top_vpp", 19), GATE_VDO0_0(CLK_VDO0_DISP_RDMA1, "vdo0_disp_rdma1", "top_vpp", 20), GATE_VDO0_0(CLK_VDO0_DSI0, "vdo0_dsi0", "top_vpp", 21), GATE_VDO0_0(CLK_VDO0_DSI1, "vdo0_dsi1", "top_vpp", 22), GATE_VDO0_0(CLK_VDO0_DSC_WRAP0, "vdo0_dsc_wrap0", "top_vpp", 23), GATE_VDO0_0(CLK_VDO0_VPP_MERGE0, "vdo0_vpp_merge0", "top_vpp", 24), GATE_VDO0_0(CLK_VDO0_DP_INTF0, "vdo0_dp_intf0", "top_vpp", 25), GATE_VDO0_0(CLK_VDO0_DISP_MUTEX0, "vdo0_disp_mutex0", "top_vpp", 26), GATE_VDO0_0(CLK_VDO0_DISP_IL_ROT0, "vdo0_disp_il_rot0", "top_vpp", 27), GATE_VDO0_0(CLK_VDO0_APB_BUS, "vdo0_apb_bus", "top_vpp", 28), GATE_VDO0_0(CLK_VDO0_FAKE_ENG0, "vdo0_fake_eng0", "top_vpp", 29), GATE_VDO0_0(CLK_VDO0_FAKE_ENG1, "vdo0_fake_eng1", "top_vpp", 30), /* VDO0_1 */ GATE_VDO0_1(CLK_VDO0_DL_ASYNC0, "vdo0_dl_async0", "top_vpp", 0), GATE_VDO0_1(CLK_VDO0_DL_ASYNC1, "vdo0_dl_async1", "top_vpp", 1), GATE_VDO0_1(CLK_VDO0_DL_ASYNC2, "vdo0_dl_async2", "top_vpp", 2), GATE_VDO0_1(CLK_VDO0_DL_ASYNC3, "vdo0_dl_async3", "top_vpp", 3), GATE_VDO0_1(CLK_VDO0_DL_ASYNC4, "vdo0_dl_async4", "top_vpp", 4), GATE_VDO0_1(CLK_VDO0_DISP_MONITOR0, "vdo0_disp_monitor0", "top_vpp", 5), GATE_VDO0_1(CLK_VDO0_DISP_MONITOR1, "vdo0_disp_monitor1", "top_vpp", 6), GATE_VDO0_1(CLK_VDO0_DISP_MONITOR2, "vdo0_disp_monitor2", "top_vpp", 7), GATE_VDO0_1(CLK_VDO0_DISP_MONITOR3, "vdo0_disp_monitor3", "top_vpp", 8), GATE_VDO0_1(CLK_VDO0_DISP_MONITOR4, "vdo0_disp_monitor4", "top_vpp", 9), GATE_VDO0_1(CLK_VDO0_SMI_GALS, "vdo0_smi_gals", "top_vpp", 10), GATE_VDO0_1(CLK_VDO0_SMI_COMMON, "vdo0_smi_common", "top_vpp", 11), GATE_VDO0_1(CLK_VDO0_SMI_EMI, "vdo0_smi_emi", "top_vpp", 12), GATE_VDO0_1(CLK_VDO0_SMI_IOMMU, "vdo0_smi_iommu", "top_vpp", 13), GATE_VDO0_1(CLK_VDO0_SMI_LARB, "vdo0_smi_larb", "top_vpp", 14), GATE_VDO0_1(CLK_VDO0_SMI_RSI, "vdo0_smi_rsi", "top_vpp", 15), /* VDO0_2 */ GATE_VDO0_2(CLK_VDO0_DSI0_DSI, "vdo0_dsi0_dsi", "top_dsi_occ", 0), GATE_VDO0_2(CLK_VDO0_DSI1_DSI, "vdo0_dsi1_dsi", "top_dsi_occ", 8), GATE_VDO0_2(CLK_VDO0_DP_INTF0_DP_INTF, "vdo0_dp_intf0_dp_intf", "top_edp", 16), }; static int clk_mt8195_vdo0_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *node = dev->parent->of_node; struct clk_onecell_data *clk_data; int r; clk_data = mtk_alloc_clk_data(CLK_VDO0_NR_CLK); if (!clk_data) return -ENOMEM; r = mtk_clk_register_gates(node, vdo0_clks, ARRAY_SIZE(vdo0_clks), clk_data); if (r) goto free_vdo0_data; r = of_clk_add_provider(node, of_clk_src_onecell_get, clk_data); if (r) goto free_vdo0_data; return r; free_vdo0_data: mtk_free_clk_data(clk_data); return r; } static struct platform_driver clk_mt8195_vdo0_drv = { .probe = clk_mt8195_vdo0_probe, .driver = { .name = "clk-mt8195-vdo0", }, }; builtin_platform_driver(clk_mt8195_vdo0_drv);
buraksaraloglu/whatwas
src/constants/routes.js
<gh_stars>1-10 export const HOME = '/'; export const DASHBOARD = '/dashboard'; export const SIGN_UP = '/signup'; export const SIGN_IN = '/signin'; export const NOTE = '/note';
kalexmills/proteus
query_mappers.go
<filename>query_mappers.go<gh_stars>100-1000 package proteus import ( "os" "github.com/rickar/props" ) type MapMapper map[string]string func (mm MapMapper) Map(name string) string { return mm[name] } type propFileMapper struct { properties *props.Properties } func (pm propFileMapper) Map(name string) string { return pm.properties.Get(name) } func PropFileToQueryMapper(name string) (QueryMapper, error) { file, err := os.Open(name) if err != nil { return nil, err } defer file.Close() properties, err := props.Read(file) if err != nil { return nil, err } return propFileMapper{properties}, nil }
Arcensoth/pyckaxe
pyckaxe/utils/io/json.py
<filename>pyckaxe/utils/io/json.py import asyncio import json from pathlib import Path from typing import Any, Dict from pyckaxe.lib.types import JsonValue __all__ = ( "load_json", "load_json_async", "dump_json", "dump_json_async", ) def load_json( path: Path, options: Dict[str, Any] = {}, ) -> JsonValue: """Load a JSON file synchronously.""" with open(path) as fp: data = json.load(fp, **options) return data def dump_json( data: JsonValue, path: Path, options: Dict[str, Any] = {}, ): """Dump a JSON file synchronously.""" with open(path, "w") as fp: json.dump(data, fp, **options) async def load_json_async( path: Path, options: Dict[str, Any] = {}, ) -> JsonValue: """Load a JSON file asynchronously.""" loop = asyncio.get_running_loop() data = await loop.run_in_executor(None, load_json, path, options) return data async def dump_json_async( data: JsonValue, path: Path, options: Dict[str, Any] = {}, ): """Dump a JSON file asynchronously.""" loop = asyncio.get_running_loop() await loop.run_in_executor(None, dump_json, data, path, options)
mateosss/monado
src/xrt/state_trackers/oxr/oxr_binding.c
<gh_stars>1-10 // Copyright 2018-2020, Collabora, Ltd. // SPDX-License-Identifier: BSL-1.0 /*! * @file * @brief Holds binding related functions. * @author <NAME> <<EMAIL>> * @ingroup oxr_main */ #include "util/u_misc.h" #include "xrt/xrt_compiler.h" #include "bindings/b_generated_bindings.h" #include "oxr_objects.h" #include "oxr_logger.h" #include "oxr_two_call.h" #include "oxr_subaction.h" #include <stdio.h> static void setup_paths(struct oxr_logger *log, struct oxr_instance *inst, struct binding_template *templ, struct oxr_binding *binding) { size_t count = 0; while (templ->paths[count] != NULL) { count++; } binding->num_paths = count; binding->paths = U_TYPED_ARRAY_CALLOC(XrPath, count); for (size_t x = 0; x < binding->num_paths; x++) { const char *str = templ->paths[x]; size_t len = strlen(str); oxr_path_get_or_create(log, inst, str, len, &binding->paths[x]); } } static bool interaction_profile_find(struct oxr_logger *log, struct oxr_instance *inst, XrPath path, struct oxr_interaction_profile **out_p) { for (size_t x = 0; x < inst->num_profiles; x++) { struct oxr_interaction_profile *p = inst->profiles[x]; if (p->path != path) { continue; } *out_p = p; return true; } return false; } static bool get_subaction_path_from_path(struct oxr_logger *log, struct oxr_instance *inst, XrPath path, enum oxr_subaction_path *out_subaction_path); static bool interaction_profile_find_or_create(struct oxr_logger *log, struct oxr_instance *inst, XrPath path, struct oxr_interaction_profile **out_p) { if (interaction_profile_find(log, inst, path, out_p)) { return true; } struct profile_template *templ = NULL; for (size_t x = 0; x < NUM_PROFILE_TEMPLATES; x++) { XrPath t_path = XR_NULL_PATH; oxr_path_get_or_create(log, inst, profile_templates[x].path, strlen(profile_templates[x].path), &t_path); if (t_path == path) { templ = &profile_templates[x]; break; } } if (templ == NULL) { *out_p = NULL; return false; } struct oxr_interaction_profile *p = U_TYPED_CALLOC(struct oxr_interaction_profile); p->xname = templ->name; p->num_bindings = templ->num_bindings; p->bindings = U_TYPED_ARRAY_CALLOC(struct oxr_binding, p->num_bindings); p->path = path; p->localized_name = templ->localized_name; for (size_t x = 0; x < templ->num_bindings; x++) { struct binding_template *t = &templ->bindings[x]; struct oxr_binding *b = &p->bindings[x]; XrPath subaction_path; XrResult r = oxr_path_get_or_create(log, inst, t->subaction_path, strlen(t->subaction_path), &subaction_path); if (r != XR_SUCCESS) { oxr_log(log, "Couldn't get subaction path %s\n", t->subaction_path); } if (!get_subaction_path_from_path(log, inst, subaction_path, &b->subaction_path)) { oxr_log(log, "Invalid subaction path %s\n", t->subaction_path); } b->localized_name = t->localized_name; setup_paths(log, inst, t, b); b->input = t->input; b->output = t->output; } // Add to the list of currently created interaction profiles. U_ARRAY_REALLOC_OR_FREE(inst->profiles, struct oxr_interaction_profile *, (inst->num_profiles + 1)); inst->profiles[inst->num_profiles++] = p; *out_p = p; return true; } static void reset_binding_keys(struct oxr_binding *binding) { free(binding->keys); free(binding->preferred_binding_path_index); binding->keys = NULL; binding->preferred_binding_path_index = NULL; binding->num_keys = 0; } static void reset_all_keys(struct oxr_binding *bindings, size_t num_bindings) { for (size_t x = 0; x < num_bindings; x++) { reset_binding_keys(&bindings[x]); } } static void add_key_to_matching_bindings(struct oxr_binding *bindings, size_t num_bindings, XrPath path, uint32_t key) { for (size_t x = 0; x < num_bindings; x++) { struct oxr_binding *b = &bindings[x]; bool found = false; uint32_t preferred_path_index; for (size_t y = 0; y < b->num_paths; y++) { if (b->paths[y] == path) { found = true; preferred_path_index = y; break; } } if (!found) { continue; } U_ARRAY_REALLOC_OR_FREE(b->keys, uint32_t, (b->num_keys + 1)); U_ARRAY_REALLOC_OR_FREE(b->preferred_binding_path_index, uint32_t, (b->num_keys + 1)); b->preferred_binding_path_index[b->num_keys] = preferred_path_index; b->keys[b->num_keys++] = key; } } static void add_string(char *temp, size_t max, ssize_t *current, const char *str) { if (*current > 0) { temp[(*current)++] = ' '; } ssize_t len = snprintf(temp + *current, max - *current, "%s", str); if (len > 0) { *current += len; } } static bool get_subaction_path_from_path(struct oxr_logger *log, struct oxr_instance *inst, XrPath path, enum oxr_subaction_path *out_subaction_path) { const char *str = NULL; size_t length = 0; XrResult ret; ret = oxr_path_get_string(log, inst, path, &str, &length); if (ret != XR_SUCCESS) { return false; } if (length >= 10 && strncmp("/user/head", str, 10) == 0) { *out_subaction_path = OXR_SUB_ACTION_PATH_HEAD; return true; } if (length >= 15 && strncmp("/user/hand/left", str, 15) == 0) { *out_subaction_path = OXR_SUB_ACTION_PATH_LEFT; return true; } if (length >= 16 && strncmp("/user/hand/right", str, 16) == 0) { *out_subaction_path = OXR_SUB_ACTION_PATH_RIGHT; return true; } if (length >= 13 && strncmp("/user/gamepad", str, 13) == 0) { *out_subaction_path = OXR_SUB_ACTION_PATH_GAMEPAD; return true; } return false; } static const char * get_subaction_path_str(enum oxr_subaction_path subaction_path) { switch (subaction_path) { case OXR_SUB_ACTION_PATH_HEAD: return "Head"; case OXR_SUB_ACTION_PATH_LEFT: return "Left"; case OXR_SUB_ACTION_PATH_RIGHT: return "Right"; case OXR_SUB_ACTION_PATH_GAMEPAD: return "Gameped"; default: return NULL; } } static XrPath get_interaction_bound_to_sub_path(struct oxr_session *sess, enum oxr_subaction_path subaction_path) { switch (subaction_path) { #define OXR_PATH_MEMBER(lower, CAP, _) \ case OXR_SUB_ACTION_PATH_##CAP: return sess->lower; OXR_FOR_EACH_VALID_SUBACTION_PATH_DETAILED(OXR_PATH_MEMBER) #undef OXR_PATH_MEMBER default: return XR_NULL_PATH; } } static const char * get_identifier_str_in_profile(struct oxr_logger *log, struct oxr_instance *inst, XrPath path, struct oxr_interaction_profile *oip) { const char *str = NULL; size_t length = 0; XrResult ret; ret = oxr_path_get_string(log, inst, path, &str, &length); if (ret != XR_SUCCESS) { return NULL; } for (size_t i = 0; i < oip->num_bindings; i++) { struct oxr_binding *binding = &oip->bindings[i]; for (size_t k = 0; k < binding->num_paths; k++) { if (binding->paths[k] != path) { continue; } str = binding->localized_name; i = oip->num_bindings; // Break the outer loop as well. break; } } return str; } /* * * 'Exported' functions. * */ void oxr_find_profile_for_device(struct oxr_logger *log, struct oxr_instance *inst, struct xrt_device *xdev, struct oxr_interaction_profile **out_p) { if (xdev == NULL) { return; } enum xrt_device_name name = xdev->name; //! @todo A lot more clever selecting the profile here. switch (name) { case XRT_DEVICE_HYDRA: interaction_profile_find(log, inst, inst->path_cache.khr_simple_controller, out_p); return; case XRT_DEVICE_PSMV: interaction_profile_find(log, inst, inst->path_cache.khr_simple_controller, out_p); interaction_profile_find(log, inst, inst->path_cache.mndx_ball_on_a_stick_controller, out_p); return; case XRT_DEVICE_DAYDREAM: interaction_profile_find(log, inst, inst->path_cache.khr_simple_controller, out_p); return; case XRT_DEVICE_SIMPLE_CONTROLLER: interaction_profile_find(log, inst, inst->path_cache.khr_simple_controller, out_p); return; case XRT_DEVICE_INDEX_CONTROLLER: interaction_profile_find(log, inst, inst->path_cache.khr_simple_controller, out_p); interaction_profile_find(log, inst, inst->path_cache.valve_index_controller, out_p); return; case XRT_DEVICE_VIVE_WAND: interaction_profile_find(log, inst, inst->path_cache.khr_simple_controller, out_p); interaction_profile_find(log, inst, inst->path_cache.htc_vive_controller, out_p); return; default: return; } } void oxr_binding_find_bindings_from_key(struct oxr_logger *log, struct oxr_interaction_profile *p, uint32_t key, struct oxr_binding *bindings[32], size_t *num_bindings) { if (p == NULL) { *num_bindings = 0; return; } //! @todo This function should be a two call function, or handle more //! then 32 bindings. size_t num = 0; for (size_t y = 0; y < p->num_bindings; y++) { struct oxr_binding *b = &p->bindings[y]; for (size_t z = 0; z < b->num_keys; z++) { if (b->keys[z] == key) { bindings[num++] = b; break; } } if (num >= 32) { *num_bindings = num; return; } } *num_bindings = num; } void oxr_binding_destroy_all(struct oxr_logger *log, struct oxr_instance *inst) { for (size_t x = 0; x < inst->num_profiles; x++) { struct oxr_interaction_profile *p = inst->profiles[x]; for (size_t y = 0; y < p->num_bindings; y++) { struct oxr_binding *b = &p->bindings[y]; reset_binding_keys(b); free(b->paths); b->paths = NULL; b->num_paths = 0; b->input = 0; b->output = 0; } free(p->bindings); p->bindings = NULL; p->num_bindings = 0; free(p); } free(inst->profiles); inst->profiles = NULL; inst->num_profiles = 0; } /* * * Client functions. * */ XrResult oxr_action_suggest_interaction_profile_bindings(struct oxr_logger *log, struct oxr_instance *inst, const XrInteractionProfileSuggestedBinding *suggestedBindings) { struct oxr_interaction_profile *p = NULL; // Path already validated. XrPath path = suggestedBindings->interactionProfile; interaction_profile_find_or_create(log, inst, path, &p); // Valid path, but not used. if (p == NULL) { return XR_SUCCESS; } struct oxr_binding *bindings = p->bindings; size_t num_bindings = p->num_bindings; // Everything is now valid, reset the keys. reset_all_keys(bindings, num_bindings); for (size_t i = 0; i < suggestedBindings->countSuggestedBindings; i++) { const XrActionSuggestedBinding *s = &suggestedBindings->suggestedBindings[i]; struct oxr_action *act = XRT_CAST_OXR_HANDLE_TO_PTR(struct oxr_action *, s->action); add_key_to_matching_bindings(bindings, num_bindings, s->binding, act->act_key); } return XR_SUCCESS; } XrResult oxr_action_get_current_interaction_profile(struct oxr_logger *log, struct oxr_session *sess, XrPath topLevelUserPath, XrInteractionProfileState *interactionProfile) { struct oxr_instance *inst = sess->sys->inst; if (sess->act_set_attachments == NULL) { return oxr_error(log, XR_ERROR_ACTIONSET_NOT_ATTACHED, "xrAttachSessionActionSets has not been " "called on this session."); } #define IDENTIFY_TOP_LEVEL_PATH(X) \ if (topLevelUserPath == inst->path_cache.X) { \ interactionProfile->interactionProfile = sess->X; \ } else OXR_FOR_EACH_VALID_SUBACTION_PATH(IDENTIFY_TOP_LEVEL_PATH) { // else clause return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "Top level path not handled?!"); } #undef IDENTIFY_TOP_LEVEL_PATH return XR_SUCCESS; } XrResult oxr_action_get_input_source_localized_name(struct oxr_logger *log, struct oxr_session *sess, const XrInputSourceLocalizedNameGetInfo *getInfo, uint32_t bufferCapacityInput, uint32_t *bufferCountOutput, char *buffer) { char temp[1024] = {0}; ssize_t current = 0; enum oxr_subaction_path subaction_path = 0; if (!get_subaction_path_from_path(log, sess->sys->inst, getInfo->sourcePath, &subaction_path)) { return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(getInfo->sourcePath) doesn't start with a " "valid subaction_path"); } // Get the interaction profile bound to this subaction_path. XrPath path = get_interaction_bound_to_sub_path(sess, subaction_path); if (path == XR_NULL_PATH) { return oxr_error(log, XR_ERROR_VALIDATION_FAILURE, "(getInfo->sourcePath) no interaction profile " "bound to subaction path"); } // Find the interaction profile. struct oxr_interaction_profile *oip = NULL; interaction_profile_find_or_create(log, sess->sys->inst, path, &oip); if (oip == NULL) { return oxr_error(log, XR_ERROR_RUNTIME_FAILURE, "no interaction profile found"); } // Add which hand to use. if (getInfo->whichComponents & XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT) { add_string(temp, sizeof(temp), &current, get_subaction_path_str(subaction_path)); } // Add a human readable and localized name of the device. if ((getInfo->whichComponents & XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT) != 0) { add_string(temp, sizeof(temp), &current, oip->localized_name); } //! @todo This implementation is very very very ugly. if ((getInfo->whichComponents & XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT) != 0) { /* * The above enum is miss-named it should be called identifier * instead of component. */ add_string(temp, sizeof(temp), &current, get_identifier_str_in_profile(log, sess->sys->inst, getInfo->sourcePath, oip)); } // Include the null character. current += 1; OXR_TWO_CALL_HELPER(log, bufferCapacityInput, bufferCountOutput, buffer, (size_t)current, temp, oxr_session_success_result(sess)); }
pajtimid/pod_sdkcore
SdkCore.framework/Headers/ArsdkFeatureArdrone3Accessorystate.h
/** Generated, do not edit ! */ #import <Foundation/Foundation.h> extern short const kArsdkFeatureArdrone3AccessorystateUid; struct arsdk_cmd; /** Accessory type */ typedef NS_ENUM(NSInteger, ArsdkFeatureArdrone3AccessorystateConnectedaccessoriesAccessoryType) { /** Unknown value from SdkCore. Only used if the received value cannot be matched with a declared value. This might occur when the drone or rc has a different sdk base from the controller. */ ArsdkFeatureArdrone3AccessorystateConnectedaccessoriesAccessoryTypeSdkCoreUnknown = -1, /** Parrot Sequoia (multispectral camera for agriculture) */ ArsdkFeatureArdrone3AccessorystateConnectedaccessoriesAccessoryTypeSequoia = 0, /** FLIR camera (thermal+rgb camera) */ ArsdkFeatureArdrone3AccessorystateConnectedaccessoriesAccessoryTypeFlir = 1, }; #define ArsdkFeatureArdrone3AccessorystateConnectedaccessoriesAccessoryTypeCnt 2 @protocol ArsdkFeatureArdrone3AccessorystateCallback<NSObject> @optional /** List of all connected accessories. This event presents the list of all connected accessories. To actually use the component, use the component dedicated feature. - parameter id: Id of the accessory for the session. - parameter accessory_type: - parameter uid: Unique Id of the accessory. This id is unique by accessory_type. - parameter swVersion: Software Version of the accessory. - parameter list_flags: List entry attribute Bitfield. 0x01: First: indicate it's the first element of the list. 0x02: Last: indicate it's the last element of the list. 0x04: Empty: indicate the list is empty (implies First/Last). All other arguments should be ignored. 0x08: Remove: This value should be removed from the existing list. */ - (void)onConnectedAccessories:(NSUInteger)id accessoryType:(ArsdkFeatureArdrone3AccessorystateConnectedaccessoriesAccessoryType)accessoryType uid:(NSString*)uid swversion:(NSString*)swversion listFlags:(NSUInteger)listFlags NS_SWIFT_NAME(onConnectedAccessories(id:accessoryType:uid:swversion:listFlags:)); /** Connected accessories battery. - parameter id: Id of the accessory for the session. - parameter batteryLevel: Battery level in percentage. - parameter list_flags: List entry attribute Bitfield. 0x01: First: indicate it's the first element of the list. 0x02: Last: indicate it's the last element of the list. 0x04: Empty: indicate the list is empty (implies First/Last). All other arguments should be ignored. 0x08: Remove: This value should be removed from the existing list. */ - (void)onBattery:(NSUInteger)id batterylevel:(NSUInteger)batterylevel listFlags:(NSUInteger)listFlags NS_SWIFT_NAME(onBattery(id:batterylevel:listFlags:)); @end @interface ArsdkFeatureArdrone3Accessorystate : NSObject + (NSInteger)decode:(struct arsdk_cmd*)command callback:(id<ArsdkFeatureArdrone3AccessorystateCallback>)callback; @end
xk11961677/sky-meteor
meteor-spring-boot-starter/src/main/java/com/sky/meteor/spring/AnnotationRegistrar.java
/* * The MIT License (MIT) * Copyright © 2019-2020 <sky> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the “Software”), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.sky.meteor.spring; import com.sky.meteor.rpc.annotation.Provider; import com.sky.meteor.spring.annotation.EnableRPC; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.TypeFilter; /** * 注解注册器 * * @author */ public class AnnotationRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(EnableRPC.class.getName(), false)); String scans = (String) attributes.get("scan"); String proxy = (String) attributes.get("proxy"); String cluster = (String) attributes.get("cluster"); String serialize = (String) attributes.get("serialize"); String loadBalance = (String) attributes.get("loadBalance"); AnnotationBeanProperties build = AnnotationBeanProperties.builder() .proxy(proxy) .cluster(cluster) .serializer(serialize) .loadBalance(loadBalance) .build(); addRpcAnnotationBean(registry, scans, build); addRpcDefinitionScanner(registry, scans); } /** * 增加拦截RPC注解业务BEAN * * @param registry * @param scans * @param properties */ private void addRpcAnnotationBean(BeanDefinitionRegistry registry, String scans, AnnotationBeanProperties properties) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(AnnotationBean.class); builder.addPropertyValue("annotationPackage", scans); builder.addPropertyValue("annotationBeanProperties", properties); registry.registerBeanDefinition(AnnotationBean.class.getName(), builder.getRawBeanDefinition()); } /** * 增加自动扫描注解 * * @param registry * @param scans */ private void addRpcDefinitionScanner(BeanDefinitionRegistry registry, String scans) { ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry); TypeFilter includeFilter = new AnnotationTypeFilter(Provider.class); scanner.addIncludeFilter(includeFilter); scanner.scan((scans == null || scans.length() == 0) ? null : AnnotationBean.COMMA_SPLIT_PATTERN.split(scans)); } }
nembrotorg/nembrot-api
db/migrate/20130908190027_change_pantographers_twitter_ids_to_bigint.rb
<reponame>nembrotorg/nembrot-api class ChangePantographersTwitterIdsToBigint < ActiveRecord::Migration def change remove_column :pantographers, :twitter_user_id add_column :pantographers, :twitter_user_id, :integer, limit: 8 end end
Qualia91/goLearning
patterns/microservices/reporting/doc.go
/*Providing Reporting. Solutions: - Reporting Service: Provides data for reporting by calling other services. Each service has a separate service that deals with reporting for that service. - Reporting Data Push App: Client services push reporting information to reporting service, then reporting service makes report when needed from local data. - Reporting event subscribers: Using a message broker so each service can send reports to a queue, and reporting systems subscribe to them. By combining this with event sourcing (only changes are saved), reporting can be done on any time through history. - Using backup databases for reporting: Databases are backed up. You can use these to do reporting. - ETL and data-wharehouses: Extraction, transform and load step that takes in databases across microservice, the saves it to datawarehouse that reporting uses. */ package reporting
pcsanwald/kibana
src/ui/public/kbn_top_nav/__tests__/kbn_top_nav.js
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import ngMock from 'ng_mock'; import expect from 'expect.js'; import { assign, pluck } from 'lodash'; import $ from 'jquery'; import '../kbn_top_nav'; import { KbnTopNavControllerProvider } from '../kbn_top_nav_controller'; describe('kbnTopNav directive', function () { let build; let KbnTopNavController; beforeEach(ngMock.module('kibana')); beforeEach(ngMock.inject(function ($compile, $rootScope, Private) { KbnTopNavController = Private(KbnTopNavControllerProvider); build = function (scopeVars = {}, attrs = {}) { const $el = $('<kbn-top-nav name="foo">').attr(attrs); const $scope = $rootScope.$new(); assign($scope, scopeVars); $compile($el)($scope); $scope.$digest(); return { $el, $scope }; }; })); it('sets the proper functions on the kbnTopNav prop on scope', function () { const { $scope } = build(); expect($scope.kbnTopNav.open).to.be.a(Function); expect($scope.kbnTopNav.close).to.be.a(Function); expect($scope.kbnTopNav.getCurrent).to.be.a(Function); expect($scope.kbnTopNav.toggle).to.be.a(Function); }); it('allows config at nested keys', function () { const scopeVars = { kbn: { top: { nav: [ { key: 'foo' } ] } } }; const { $scope } = build(scopeVars, { config: 'kbn.top.nav' }); const optKeys = pluck($scope.kbnTopNav.opts, 'key'); expect(optKeys).to.eql(['foo']); }); it('uses the KbnTopNavController if passed via config attribute', function () { const controller = new KbnTopNavController(); const { $scope } = build({ controller }, { config: 'controller' }); expect($scope.kbnTopNav).to.be(controller); }); });
only976/DesignPattern
src/main/java/Mould/BridgeTest.java
package Mould; import Color.*; import Shaped.*; /*Bridge模式测试*/ public class BridgeTest { public static void main(String[]args){ Mould mould1= new BigMould(new SphericalShaped(),new BlackColor()); Mould mould2=new MiddleMould(new SquareShaped(),new WhiteColor()); Mould mould3=new SmallMould(new StarShaped(),new BlackColor()); System.out.println(); System.out.println("模具mould1信息:"); mould1.getInfo(); System.out.println(); System.out.println("模具mould2信息:"); mould2.getInfo(); System.out.println(); System.out.println("模具mould3信息:"); mould3.getInfo(); System.out.println(); } }
adeleporte/vrni-go-client
model_top_talker_sort_enum.go
/* * vRealize Network Insight API Reference * * vRealize Network Insight API Reference * * API version: 1.1.8 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package vrni // TopTalkerSortEnum the model 'TopTalkerSortEnum' type TopTalkerSortEnum string // List of TopTalkerSortEnum const ( TOPTALKERSORTENUM_FLOW_VOLUME TopTalkerSortEnum = "FLOW_VOLUME" TOPTALKERSORTENUM_FLOW_COUNT TopTalkerSortEnum = "FLOW_COUNT" TOPTALKERSORTENUM_TRAFFIC_RATE TopTalkerSortEnum = "TRAFFIC_RATE" TOPTALKERSORTENUM_SESSION_COUNT TopTalkerSortEnum = "SESSION_COUNT" )
endlessbaum/UERANSIM
native/ngap-native/src/asn_generated/NGAP_NotificationControl.h
<filename>native/ngap-native/src/asn_generated/NGAP_NotificationControl.h /* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NGAP-IEs" * found in "asn/NGAP-IEs.asn" * `asn1c -fcompound-names -findirect-choice -fno-include-deps -gen-PER -no-gen-OER -no-gen-example -D ngap -pdu=all` */ #ifndef _NGAP_NotificationControl_H_ #define _NGAP_NotificationControl_H_ #include <asn_application.h> /* Including external dependencies */ #include <NativeEnumerated.h> #ifdef __cplusplus extern "C" { #endif /* Dependencies */ typedef enum NGAP_NotificationControl { NGAP_NotificationControl_notification_requested = 0 /* * Enumeration is extensible */ } e_NGAP_NotificationControl; /* NGAP_NotificationControl */ typedef long NGAP_NotificationControl_t; /* Implementation */ extern asn_per_constraints_t asn_PER_type_NGAP_NotificationControl_constr_1; extern asn_TYPE_descriptor_t asn_DEF_NGAP_NotificationControl; extern const asn_INTEGER_specifics_t asn_SPC_NGAP_NotificationControl_specs_1; asn_struct_free_f NGAP_NotificationControl_free; asn_struct_print_f NGAP_NotificationControl_print; asn_constr_check_f NGAP_NotificationControl_constraint; ber_type_decoder_f NGAP_NotificationControl_decode_ber; der_type_encoder_f NGAP_NotificationControl_encode_der; xer_type_decoder_f NGAP_NotificationControl_decode_xer; xer_type_encoder_f NGAP_NotificationControl_encode_xer; per_type_decoder_f NGAP_NotificationControl_decode_uper; per_type_encoder_f NGAP_NotificationControl_encode_uper; per_type_decoder_f NGAP_NotificationControl_decode_aper; per_type_encoder_f NGAP_NotificationControl_encode_aper; #ifdef __cplusplus } #endif #endif /* _NGAP_NotificationControl_H_ */ #include <asn_internal.h>
kasoki/project-zombye
src/source/zombye/audio/sound_collection.cpp
#include <zombye/assets/asset.hpp> #include <zombye/assets/asset_loader.hpp> #include <zombye/assets/asset_manager.hpp> #include <zombye/assets/native_loader.hpp> #include <zombye/audio/audiohelper.hpp> #include <zombye/audio/sound_collection.hpp> #include <zombye/utils/logger.hpp> zombye::sound_collection::sound_collection() { } Mix_Chunk* zombye::sound_collection::get(std::string name) { if(sounds_.find(name) != sounds_.end()) { return sounds_[name].get(); } return nullptr; } void zombye::sound_collection::add(std::string name, std::string asset_path) { static zombye::asset_manager manager; auto asset = manager.load(asset_path); auto raw = zombye::get_raw_from_asset(asset.get()); auto ptr = std::shared_ptr<Mix_Chunk>(Mix_LoadWAV_RW(raw, 1), Mix_FreeChunk); if(!ptr) { zombye::log(LOG_ERROR, "Could not read sound " + std::string(Mix_GetError())); } sounds_.insert(std::make_pair(name, ptr)); }
ddalpange/tui.chart
test/models/bounds/circleLegendCalculator.spec.js
<reponame>ddalpange/tui.chart<gh_stars>1-10 /** * @fileoverview Test for circleLegendCalculator. * @author <NAME>. * FE Development Lab <<EMAIL>> */ 'use strict'; var circleLegendCalculator = require('../../../src/js/models/bounds/circleLegendCalculator'); var chartConst = require('../../../src/js/const'); var renderUtil = require('../../../src/js/helpers/renderUtil'); describe('Test for circleLegendCalculator', function() { describe('_calculatePixelStep()', function() { it('calculate pixel step, when axis data is label type', function() { var actual = circleLegendCalculator._calculatePixelStep({ tickCount: 4, isLabelAxis: true }, 240); expect(actual).toBe(30); }); it('when axis data is not label type', function() { var actual = circleLegendCalculator._calculatePixelStep({ tickCount: 4 }, 240); expect(actual).toBe(80); }); }); describe('_calculateRadiusByAxisData()', function() { it('calculate radius by axis data', function() { var seriesDimension = { width: 400, height: 240 }; var axisDataMap = { xAxis: { tickCount: 5 }, yAxis: { tickCount: 4 } }; var actual = circleLegendCalculator._calculateRadiusByAxisData(seriesDimension, axisDataMap); expect(actual).toBe(80); }); }); describe('_getCircleLegendLabelMaxWidth()', function() { it('get max width of label for circle legend', function() { var maxLabel = '1,000'; var fontFamily = 'Verdana'; var actual; spyOn(renderUtil, 'getRenderedLabelWidth').and.returnValue(50); actual = circleLegendCalculator._getCircleLegendLabelMaxWidth(maxLabel, fontFamily); expect(renderUtil.getRenderedLabelWidth).toHaveBeenCalledWith('1,000', { fontSize: chartConst.CIRCLE_LEGEND_LABEL_FONT_SIZE, fontFamily: 'Verdana' }); expect(actual).toBe(50); }); }); describe('calculateCircleLegendWidth()', function() { it('calculate width of circle legend', function() { var seriesDimension = { width: 400, height: 240 }; var axisDataMap = { xAxis: { tickCount: 5, isLabelAxis: true }, yAxis: { tickCount: 4 } }; var maxLabel = '1,000'; var fontFamily = 'Verdana'; var actual; actual = circleLegendCalculator.calculateCircleLegendWidth( seriesDimension, axisDataMap, maxLabel, fontFamily ); expect(actual).toBe(90); }); }); describe('calculateMaxRadius()', function() { it('maxRadius should be calculated normally even without circlelegend.', function() { var axisDataMap = { xAxis: { tickCount: 4 }, yAxis: { tickCount: 4 } }; var dimensionMap = { circleLegend: { width: 0 }, series: { width: 300, height: 300 } }; expect(circleLegendCalculator.calculateMaxRadius(dimensionMap, axisDataMap)).toBe(100); }); }); });
Konstyantin/Recent
resources/assets/src/components/Guest/index.js
export * from './Guest';
UQdeco2800/singularity-server
common/src/main/java/uq/deco2800/singularity/common/representations/coaster/state/NewPlayer.java
package uq.deco2800.singularity.common.representations.coaster.state; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; /** * Created by rcarrier on 20/10/2016. */ public class NewPlayer extends Update { @JsonProperty @NotEmpty private String name; @JsonProperty private int tickrate; @JsonProperty @NotEmpty private boolean host; public NewPlayer() { } public void setName(String name) { this.name = name; } public String getName() { return name; } public NewPlayer(String name) { this.name = name; this.host = false; } public NewPlayer(String name, int tickrate) { this.tickrate = tickrate; this.name = name; this.host = true; } public void setTickrate(int tickrate) { this.tickrate = tickrate; } public int getTick() { return tickrate; } public boolean getHost() { return host; } }
sadupally/Dev
unisa-tools/unisa-booklistadmin/src/java/za/ac/unisa/lms/tools/booklistadmin/module/moduleImpl/BookSearcher_Publisher.java
package za.ac.unisa.lms.tools.booklistadmin.module.moduleImpl; import java.util.Iterator; import java.util.Vector; import java.util.List; import org.apache.struts.action.ActionMessages; import za.ac.unisa.lms.tools.booklistadmin.module.BookModule; import za.ac.unisa.lms.tools.booklistadmin.module.BookList; import za.ac.unisa.lms.tools.booklistadmin.module.moduleImpl.BookHelperClasses.BookGetterUtil; import za.ac.unisa.lms.tools.booklistadmin.module.moduleImpl.BookHelperClasses.BookSearchUtils; import za.ac.unisa.lms.tools.booklistadmin.module.moduleImpl.BookHelperClasses.BookValidator; import za.ac.unisa.lms.tools.booklistadmin.forms.BooklistAdminForm; public class BookSearcher_Publisher { BookSearchUtils bookSearchUtils; public BookSearcher_Publisher(BookGetterUtil bookDataGetter,BookList bookList) { bookSearchUtils=new BookSearchUtils(bookDataGetter,bookList); } public String searchBookByPublisher(BooklistAdminForm booklistAdminForm,ActionMessages messages) { BookValidator bookValidator=new BookValidator(); bookValidator.validateInputForSearchByPubisher(booklistAdminForm, messages); String nextPage="searchform"; if(messages.isEmpty()){ try{ setBookListInFormBean(booklistAdminForm); BookSearchUtils.handleEmptyList(booklistAdminForm, messages); nextPage=getNextPage(booklistAdminForm.getBooklist()); }catch (Exception e) { bookSearchUtils.handleException(messages,e); nextPage= "searchform"; } } return nextPage; } private void setBookListInFormBean(BooklistAdminForm booklistAdminForm)throws Exception{ Vector<BookModule> tempList = new Vector<BookModule>(); List list =bookSearchUtils.getList(booklistAdminForm); Iterator searchedBooks =list.iterator(); while (searchedBooks.hasNext()){ BookModule bookDetails = (BookModule) searchedBooks.next(); tempList.addElement(bookDetails); } booklistAdminForm.setBooklist(tempList); } public String getNextPage(List list){ String nextPage="bookfind"; if ((list==null)||(list.size()==0)){ nextPage="searchform"; } return nextPage; } }
FlashbackSRS/flashback
vendor/github.com/flimzy/kivik/session_test.go
package kivik import ( "context" "errors" "testing" "github.com/flimzy/diff" "github.com/flimzy/kivik/driver" ) type nonSessioner struct { driver.Client } type sessioner struct { driver.Client session *driver.Session err error } func (s *sessioner) Session(_ context.Context) (*driver.Session, error) { return s.session, s.err } func TestSession(t *testing.T) { tests := []struct { name string client driver.Client expected interface{} status int err string }{ { name: "driver doesn't implement Sessioner", client: &nonSessioner{}, status: StatusNotImplemented, err: "kivik: driver does not support sessions", }, { name: "driver returns error", client: &sessioner{err: errors.New("session error")}, status: StatusInternalServerError, err: "session error", }, { name: "good response", client: &sessioner{session: &driver.Session{ Name: "curly", Roles: []string{"stooges"}, }}, expected: &Session{ Name: "curly", Roles: []string{"stooges"}, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { client := &Client{driverClient: test.client} session, err := client.Session(context.Background()) var errMsg string if err != nil { errMsg = err.Error() } if errMsg != test.err { t.Errorf("Unexpected error: %s", errMsg) } if err != nil { return } if d := diff.Interface(test.expected, session); d != nil { t.Error(d) } }) } }
MarkDeMaria/origin
pkg/build/registry/test/buildconfig.go
<reponame>MarkDeMaria/origin package test import ( "sync" kapi "k8s.io/kubernetes/pkg/api" kapierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/watch" "github.com/openshift/origin/pkg/build/api" ) type BuildConfigRegistry struct { Err error BuildConfigs *api.BuildConfigList BuildConfig *api.BuildConfig DeletedConfigID string sync.Mutex } func (r *BuildConfigRegistry) ListBuildConfigs(ctx kapi.Context, options *kapi.ListOptions) (*api.BuildConfigList, error) { r.Lock() defer r.Unlock() return r.BuildConfigs, r.Err } func (r *BuildConfigRegistry) GetBuildConfig(ctx kapi.Context, id string) (*api.BuildConfig, error) { r.Lock() defer r.Unlock() if r.BuildConfig != nil && r.BuildConfig.Name == id { return r.BuildConfig, r.Err } return nil, kapierrors.NewNotFound(api.Resource("buildconfig"), id) } func (r *BuildConfigRegistry) CreateBuildConfig(ctx kapi.Context, config *api.BuildConfig) error { r.Lock() defer r.Unlock() r.BuildConfig = config return r.Err } func (r *BuildConfigRegistry) UpdateBuildConfig(ctx kapi.Context, config *api.BuildConfig) error { r.Lock() defer r.Unlock() r.BuildConfig = config return r.Err } func (r *BuildConfigRegistry) DeleteBuildConfig(ctx kapi.Context, id string) error { r.Lock() defer r.Unlock() r.DeletedConfigID = id r.BuildConfig = nil return r.Err } func (r *BuildConfigRegistry) WatchBuildConfigs(ctx kapi.Context, options *kapi.ListOptions) (watch.Interface, error) { return nil, r.Err }
pftx/niolex-network-nio
network-name/src/main/java/org/apache/niolex/network/name/bean/AddressRegiSerializer.java
<reponame>pftx/niolex-network-nio /** * AddressRegiSerializer.java * * Copyright 2012 Niolex, Inc. * * Niolex licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.apache.niolex.network.name.bean; import org.apache.niolex.commons.codec.StringUtil; import org.apache.niolex.network.Config; import org.apache.niolex.network.serialize.BaseSerializer; /** * The class to serialize address register bean. * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version 1.0.0 * @since 2012-6-27 */ public class AddressRegiSerializer extends BaseSerializer<AddressRegiBean> { /** * Create this AddressRegiSerializer with the given code. * * @param code the packet code */ public AddressRegiSerializer(short code) { super(code); } /** * Override super method * @see org.apache.niolex.network.serialize.BaseSerializer#toBytes(Object) */ @Override public byte[] toBytes(AddressRegiBean t) { return StringUtil.strToUtf8Byte(t.getAddressKey() + Config.NAME_FIELD_SEP + t.getAddressValue()); } /** * Override super method * @see org.apache.niolex.network.serialize.BaseSerializer#toObj(byte[]) */ @Override public AddressRegiBean toObj(byte[] arr) { String[] arr2 = StringUtil.split(StringUtil.utf8ByteToStr(arr), Config.NAME_FIELD_SEP, false); if (arr2.length != 2) { throw new IllegalArgumentException("Data is invalid."); } return new AddressRegiBean(arr2[0], arr2[1]); } }
alipay/alipay-sdk-java-all
src/main/java/com/alipay/api/response/AlipayEbppInvoiceEnterpriseconsumeEnterpriseopenruleCreateResponse.java
<filename>src/main/java/com/alipay/api/response/AlipayEbppInvoiceEnterpriseconsumeEnterpriseopenruleCreateResponse.java package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.ebpp.invoice.enterpriseconsume.enterpriseopenrule.create response. * * @author auto create * @since 1.0, 2021-09-24 18:21:34 */ public class AlipayEbppInvoiceEnterpriseconsumeEnterpriseopenruleCreateResponse extends AlipayResponse { private static final long serialVersionUID = 8481952385541858718L; /** * 开票规则id */ @ApiField("invoice_rule_id") private String invoiceRuleId; public void setInvoiceRuleId(String invoiceRuleId) { this.invoiceRuleId = invoiceRuleId; } public String getInvoiceRuleId( ) { return this.invoiceRuleId; } }
pupper68k/arcusandroid
arcusApp/app/src/main/java/arcus/app/subsystems/alarm/promonitoring/presenters/AlarmDeviceListPresenter.java
/* * Copyright 2019 Arcus Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package arcus.app.subsystems.alarm.promonitoring.presenters; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import arcus.cornea.provider.DeviceModelProvider; import arcus.cornea.subsystem.alarm.AlarmSubsystemController; import arcus.cornea.subsystem.alarm.model.AlarmModel; import arcus.cornea.subsystem.security.PromonSecurityDeviceListController; import com.iris.client.capability.AlarmSubsystem; import com.iris.client.capability.Contact; import com.iris.client.capability.DeviceConnection; import com.iris.client.capability.Motion; import com.iris.client.capability.MotorizedDoor; import com.iris.client.event.Listener; import com.iris.client.model.DeviceModel; import arcus.app.ArcusApplication; import arcus.app.R; import arcus.app.common.utils.CorneaUtils; import arcus.app.common.utils.StringUtils; import arcus.app.subsystems.alarm.promonitoring.models.AlertDeviceModel; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class AlarmDeviceListPresenter extends AlarmProviderOfflinePresenter<AlarmDeviceListContract.AlarmDeviceListView> implements AlarmDeviceListContract.AlarmDeviceListPresenter, AlarmSubsystemController.Callback, PromonSecurityDeviceListController.Callback { private String presentedAlarmType; @Override public void requestUpdate(String forAlarmType) { this.presentedAlarmType = forAlarmType; String deviceListListenerId = PromonSecurityDeviceListController.class.getCanonicalName(); String alarmListenerId = AlarmSubsystemController.class.getCanonicalName(); // Request for security device list--Alarm subsystem can't provide all the information, // so we delegate to SecuritySubsystem if (AlarmSubsystem.ACTIVEALERTS_SECURITY.equalsIgnoreCase(forAlarmType)) { addListener(deviceListListenerId, PromonSecurityDeviceListController.getInstance().setCallback(this)); PromonSecurityDeviceListController.getInstance().requestUpdate(); } // Request for smoke, co or water device list--ask AlarmSubsystem for it else { addListener(alarmListenerId, AlarmSubsystemController.getInstance().setCallback(this)); AlarmSubsystemController.getInstance().requestUpdate(); } } @Override public void onAlarmStateChanged(String newAlarmState) { // Nothing to do } @Override public void onSecurityModeChanged(String newMode) { // Nothing to do } @Override public void onAlertsChanged(List<String> activeAlerts, Set<String> availableAlerts, Set<String> monitoredAlerts) { // Nothing to do } @Override public void onIncidentChanged(String incidentAddress) { // Nothing to do } @Override public void onError(Throwable throwable) { } @Override public void onActivateComplete() { } @Override public void onAlarmsChanged(final List<AlarmModel> alarmModels) { DeviceModelProvider.instance().reload().onSuccess(new Listener<List<DeviceModel>>() { @Override public void onEvent(List<DeviceModel> deviceModels) { AlarmModel presentedModel = getModelForType(presentedAlarmType, alarmModels); switch (presentedAlarmType.toUpperCase()) { case AlarmSubsystem.AVAILABLEALERTS_SMOKE: case AlarmSubsystem.AVAILABLEALERTS_CO: case AlarmSubsystem.AVAILABLEALERTS_WATER: present(buildDeviceItems(deviceModels, presentedModel)); break; default: throw new IllegalArgumentException("Bug! Unimplemented alarm type: " + presentedAlarmType); } } }); } @Override public void onSubsystemAvailableChange(boolean available) { } @Override public void onParticipatingDevicesChanged(final Set<String> securityDevices, Set<String> triggeredDevices, final Set<String> readyDevices, final Set<String> armedDevices, final Set<String> bypassedDevices, final Set<String> offlineDevices, final Set<String> onModeDevices, final Set<String> partialModeDevices) { DeviceModelProvider.instance().reload().onSuccess(new Listener<List<DeviceModel>>() { @Override public void onEvent(List<DeviceModel> deviceModels) { // Get security-eligible devices that are not participating Set<String> notParticipatingDevices = new HashSet<>(securityDevices); notParticipatingDevices.removeAll(onModeDevices); notParticipatingDevices.removeAll(partialModeDevices); present(buildSecurityDeviceItems(deviceModels, offlineDevices, onModeDevices, partialModeDevices, bypassedDevices, notParticipatingDevices)); } }); } @NonNull private AlarmModel getModelForType(String alarmType, List<AlarmModel> models) { for (AlarmModel thisModel : models) { if (thisModel.getType().equalsIgnoreCase(presentedAlarmType)) { return thisModel; } } throw new IllegalArgumentException("Bug! No model for alarm type: " + alarmType); } @NonNull private List<AlertDeviceModel> buildDeviceItems(List<DeviceModel> deviceModels, AlarmModel presentedModel) { List<AlertDeviceModel> presentedItems = new ArrayList<>(); Set<String> activeAndTriggeredDevices = new HashSet<>(presentedModel.getActiveDevices()); activeAndTriggeredDevices.addAll(presentedModel.getTriggeredDevices()); activeAndTriggeredDevices.addAll(presentedModel.getOfflineDevices()); if (activeAndTriggeredDevices.size() > 0) { presentedItems.add(AlertDeviceModel.headerModelType(ArcusApplication.getContext().getString(R.string.security_device_participating))); for (String deviceAddress : activeAndTriggeredDevices) { DeviceModel deviceModel = getModelForAddress(deviceAddress, deviceModels); if (deviceModel != null) { if (DeviceConnection.STATE_ONLINE.equals(deviceModel.get(DeviceConnection.ATTR_STATE))) { presentedItems.add(AlertDeviceModel.forOnlineDevice(deviceModel)); } else{ presentedItems.add(AlertDeviceModel.forOfflineDevice(deviceModel)); } } } } return presentedItems; } @NonNull private List<AlertDeviceModel> buildSecurityDeviceItems(List<DeviceModel> deviceModels, Set<String> offlineDevices, Set<String> onModeDevices, Set<String> partialModeDevices, Set<String> bypassedDevices, Set<String> notParticipatingDevices) { List<AlertDeviceModel> presentedItems = new ArrayList<>(); Set<String> bypassedOnlineDevices = new HashSet<>(bypassedDevices); bypassedOnlineDevices.removeAll(offlineDevices); if (bypassedDevices.size() > 0) { List<AlertDeviceModel> sortedDevices = new ArrayList<>(); for (String thisBypassedDevice : bypassedOnlineDevices) { DeviceModel deviceModel = getModelForAddress(thisBypassedDevice, deviceModels); if (deviceModel != null) { //String actionText = getSecurityActionText(deviceModel); String actionText = ""; String modeText = getSecurityModeText(onModeDevices.contains(thisBypassedDevice), partialModeDevices.contains(thisBypassedDevice)); boolean isOnline = DeviceConnection.STATE_ONLINE.equals(deviceModel.get(DeviceConnection.ATTR_STATE)); sortedDevices.add(AlertDeviceModel.forSecurityDevice(deviceModel, actionText, modeText, isOnline)); } } Collections.sort(sortedDevices, AlertDeviceModel.sortAlphaOrder); if (sortedDevices.size() > 0) { presentedItems.add(AlertDeviceModel.headerModelType(ArcusApplication.getContext().getString(R.string.security_device_bypassed))); presentedItems.addAll(sortedDevices); } } Set<String> onAndParitalDevices = new HashSet<>(onModeDevices); onAndParitalDevices.addAll(partialModeDevices); onAndParitalDevices.removeAll(bypassedOnlineDevices); if (onAndParitalDevices.size() > 0) { presentedItems.add(AlertDeviceModel.headerModelType(ArcusApplication.getContext().getString(R.string.security_device_on_partial))); List<AlertDeviceModel> sortedDevices = new ArrayList<>(); for (String onOrPartialDevice : onAndParitalDevices) { DeviceModel deviceModel = getModelForAddress(onOrPartialDevice, deviceModels); if (deviceModel != null) { String actionText = getSecurityActionText(deviceModel); String modeText = getSecurityModeText(onModeDevices.contains(onOrPartialDevice), partialModeDevices.contains(onOrPartialDevice)); boolean isOnline = DeviceConnection.STATE_ONLINE.equals(deviceModel.get(DeviceConnection.ATTR_STATE)); sortedDevices.add(AlertDeviceModel.forSecurityDevice(deviceModel, actionText, modeText, isOnline)); } } Collections.sort(sortedDevices, AlertDeviceModel.sortAlphaOrder); presentedItems.addAll(sortedDevices); } if (notParticipatingDevices.size() > 0) { presentedItems.add(AlertDeviceModel.headerModelType(ArcusApplication.getContext().getString(R.string.security_device_not_participating))); List<AlertDeviceModel> sortedDevices = new ArrayList<>(); for (String notParticipatingDevice : notParticipatingDevices) { DeviceModel deviceModel = getModelForAddress(notParticipatingDevice, deviceModels); if (deviceModel != null) { String actionText = getSecurityActionText(deviceModel); boolean isOnline = DeviceConnection.STATE_ONLINE.equals(deviceModel.get(DeviceConnection.ATTR_STATE)); sortedDevices.add(AlertDeviceModel.forSecurityDevice(deviceModel, actionText, null, isOnline)); } } Collections.sort(sortedDevices, AlertDeviceModel.sortAlphaOrder); presentedItems.addAll(sortedDevices); } return presentedItems; } private String getSecurityModeText(boolean isOn, boolean isPartial) { if (isOn && isPartial) return ArcusApplication.getContext().getString(R.string.security_alarm_on_partial); if (isOn) return ArcusApplication.getContext().getString(R.string.security_alarm_on); if (isPartial) return ArcusApplication.getContext().getString(R.string.security_alarm_partial); return null; } private String getSecurityActionText(DeviceModel deviceModel) { if (CorneaUtils.hasCapability(deviceModel, Motion.class)) { return getSecurityActionTextForMotion(deviceModel); } else if (CorneaUtils.hasCapability(deviceModel, Contact.class)) { return getSecurityActionTextForContact(deviceModel); } else if (CorneaUtils.hasCapability(deviceModel, MotorizedDoor.class)) { return getSecurityActionTextForDoor(deviceModel); } return null; } private String getSecurityActionTextForDoor(DeviceModel deviceModel) { String doorState = CorneaUtils.getCapability(deviceModel, MotorizedDoor.class).getDoorstate(); String timestamp = StringUtils.getTimestampString(CorneaUtils.getCapability(deviceModel, MotorizedDoor.class).getDoorstatechanged()); if (MotorizedDoor.DOORSTATE_OPEN.equals(doorState) || MotorizedDoor.DOORSTATE_OPENING.equals(doorState)) { return ArcusApplication.getContext().getString(R.string.security_device_opened, timestamp); } else { return ArcusApplication.getContext().getString(R.string.security_device_closed, timestamp); } } private String getSecurityActionTextForMotion(DeviceModel deviceModel) { String timestamp = StringUtils.getTimestampString(CorneaUtils.getCapability(deviceModel, Motion.class).getMotionchanged()); return ArcusApplication.getContext().getString(R.string.security_device_motion, timestamp); } private String getSecurityActionTextForContact(DeviceModel deviceModel) { String timestamp = StringUtils.getTimestampString(CorneaUtils.getCapability(deviceModel, Contact.class).getContactchanged()); if (Contact.CONTACT_CLOSED.equals(CorneaUtils.getCapability(deviceModel, Contact.class).getContact())) { return ArcusApplication.getContext().getString(R.string.security_device_closed, timestamp); } else { return ArcusApplication.getContext().getString(R.string.security_device_opened, timestamp); } } private void present(final List<AlertDeviceModel> items) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if(isPresenting()) { getPresentedView().updateView(items); } } }); } private DeviceModel getModelForAddress(String deviceAddress, List<DeviceModel> models) { for (DeviceModel thisModel : models) { if (thisModel.getAddress().equalsIgnoreCase(deviceAddress)) return thisModel; } return null; } }
ckamtsikis/cmssw
CondFormats/JetMETObjects/src/JetCorrectionUncertainty.cc
#include "CondFormats/JetMETObjects/interface/JetCorrectionUncertainty.h" #include "CondFormats/JetMETObjects/interface/SimpleJetCorrectionUncertainty.h" #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "Math/PtEtaPhiE4D.h" #include "Math/Vector3D.h" #include "Math/LorentzVector.h" #include <vector> #include <string> ///////////////////////////////////////////////////////////////////////// JetCorrectionUncertainty::JetCorrectionUncertainty() { mJetEta = -9999; mJetPt = -9999; mJetPhi = -9999; mJetE = -9999; mJetEMF = -9999; mLepPx = -9999; mLepPy = -9999; mLepPz = -9999; mIsJetEset = false; mIsJetPtset = false; mIsJetPhiset = false; mIsJetEtaset = false; mIsJetEMFset = false; mIsLepPxset = false; mIsLepPyset = false; mIsLepPzset = false; mAddLepToJet = false; mUncertainty = new SimpleJetCorrectionUncertainty(); } ///////////////////////////////////////////////////////////////////////// JetCorrectionUncertainty::JetCorrectionUncertainty(const std::string& fDataFile) { mJetEta = -9999; mJetPt = -9999; mJetPhi = -9999; mJetE = -9999; mJetEMF = -9999; mLepPx = -9999; mLepPy = -9999; mLepPz = -9999; mIsJetEset = false; mIsJetPtset = false; mIsJetPhiset = false; mIsJetEtaset = false; mIsJetEMFset = false; mIsLepPxset = false; mIsLepPyset = false; mIsLepPzset = false; mAddLepToJet = false; mUncertainty = new SimpleJetCorrectionUncertainty(fDataFile); } ///////////////////////////////////////////////////////////////////////// JetCorrectionUncertainty::JetCorrectionUncertainty(const JetCorrectorParameters& fParameters) { mJetEta = -9999; mJetPt = -9999; mJetPhi = -9999; mJetE = -9999; mJetEMF = -9999; mLepPx = -9999; mLepPy = -9999; mLepPz = -9999; mIsJetEset = false; mIsJetPtset = false; mIsJetPhiset = false; mIsJetEtaset = false; mIsJetEMFset = false; mIsLepPxset = false; mIsLepPyset = false; mIsLepPzset = false; mAddLepToJet = false; mUncertainty = new SimpleJetCorrectionUncertainty(fParameters); } ///////////////////////////////////////////////////////////////////////// JetCorrectionUncertainty::~JetCorrectionUncertainty() { delete mUncertainty; } ///////////////////////////////////////////////////////////////////////// void JetCorrectionUncertainty::setParameters(const std::string& fDataFile) { //---- delete the mParameters pointer before setting the new address --- delete mUncertainty; mUncertainty = new SimpleJetCorrectionUncertainty(fDataFile); } ///////////////////////////////////////////////////////////////////////// float JetCorrectionUncertainty::getUncertainty(bool fDirection) { float result; std::vector<float> vx, vy; vx = fillVector(mUncertainty->parameters().definitions().binVar()); vy = fillVector(mUncertainty->parameters().definitions().parVar()); result = mUncertainty->uncertainty(vx, vy[0], fDirection); mIsJetEset = false; mIsJetPtset = false; mIsJetPhiset = false; mIsJetEtaset = false; mIsJetEMFset = false; mIsLepPxset = false; mIsLepPyset = false; mIsLepPzset = false; return result; } //------------------------------------------------------------------------ //--- Reads the parameter names and fills a vector of floats ------------- //------------------------------------------------------------------------ std::vector<float> JetCorrectionUncertainty::fillVector(const std::vector<std::string>& fNames) { std::vector<float> result; for (unsigned i = 0; i < fNames.size(); i++) { if (fNames[i] == "JetEta") { if (!mIsJetEtaset) { edm::LogError("JetCorrectionUncertainty::") << " jet eta is not set"; result.push_back(-999.0); } else { result.push_back(mJetEta); } } else if (fNames[i] == "JetPt") { if (!mIsJetPtset) { edm::LogError("JetCorrectionUncertainty::") << " jet pt is not set"; result.push_back(-999.0); } else { result.push_back(mJetPt); } } else if (fNames[i] == "JetPhi") { if (!mIsJetPhiset) { edm::LogError("JetCorrectionUncertainty::") << " jet phi is not set"; result.push_back(-999.0); } else { result.push_back(mJetPhi); } } else if (fNames[i] == "JetE") { if (!mIsJetEset) { edm::LogError("JetCorrectionUncertainty::") << " jet energy is not set"; result.push_back(-999.0); } else { result.push_back(mJetE); } } else if (fNames[i] == "JetEMF") { if (!mIsJetEMFset) { edm::LogError("JetCorrectionUncertainty::") << " jet emf is not set"; result.push_back(-999.0); } else { result.push_back(mJetEMF); } } else if (fNames[i] == "LepPx") { if (!mIsLepPxset) { edm::LogError("JetCorrectionUncertainty::") << " lepton px is not set"; result.push_back(-999.0); } else { result.push_back(mLepPx); } } else if (fNames[i] == "LepPy") { if (!mIsLepPyset) { edm::LogError("JetCorrectionUncertainty::") << " lepton py is not set"; result.push_back(-999.0); } else { result.push_back(mLepPy); } } else if (fNames[i] == "LepPz") { if (!mIsLepPzset) { edm::LogError("JetCorrectionUncertainty::") << " lepton pz is not set"; result.push_back(-999.0); } else { result.push_back(mLepPz); } } else { edm::LogError("JetCorrectionUncertainty::") << " unknown parameter " << fNames[i]; result.push_back(-999.0); } } return result; } //------------------------------------------------------------------------ //--- Calculate the PtRel (needed for the SLB) --------------------------- //------------------------------------------------------------------------ float JetCorrectionUncertainty::getPtRel() { typedef ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiE4D<float> > PtEtaPhiELorentzVector; typedef ROOT::Math::DisplacementVector3D<ROOT::Math::Cartesian3D<float> > XYZVector; PtEtaPhiELorentzVector jet; XYZVector lep; jet.SetPt(mJetPt); jet.SetEta(mJetEta); jet.SetPhi(mJetPhi); jet.SetE(mJetE); lep.SetXYZ(mLepPx, mLepPy, mLepPz); float lj_x = (mAddLepToJet) ? lep.X() + jet.Px() : jet.Px(); float lj_y = (mAddLepToJet) ? lep.Y() + jet.Py() : jet.Py(); float lj_z = (mAddLepToJet) ? lep.Z() + jet.Pz() : jet.Pz(); // absolute values squared float lj2 = lj_x * lj_x + lj_y * lj_y + lj_z * lj_z; float pTrel2 = -999.0; if (lj2 > 0) { float lep2 = lep.X() * lep.X() + lep.Y() * lep.Y() + lep.Z() * lep.Z(); // projection vec(mu) to lepjet axis float lepXlj = lep.X() * lj_x + lep.Y() * lj_y + lep.Z() * lj_z; // absolute value squared and normalized float pLrel2 = lepXlj * lepXlj / lj2; // lep2 = pTrel2 + pLrel2 pTrel2 = lep2 - pLrel2; } else edm::LogError("JetCorrectionUncertainty") << " not positive lepton-jet momentum: " << lj2; return (pTrel2 > 0) ? std::sqrt(pTrel2) : 0.0; } //------------------------------------------------------------------------ //--- Setters ------------------------------------------------------------ //------------------------------------------------------------------------ void JetCorrectionUncertainty::setJetEta(float fEta) { mJetEta = fEta; mIsJetEtaset = true; } //------------------------------------------------------------------------ void JetCorrectionUncertainty::setJetPt(float fPt) { mJetPt = fPt; mIsJetPtset = true; } //------------------------------------------------------------------------ void JetCorrectionUncertainty::setJetPhi(float fPhi) { mJetPhi = fPhi; mIsJetPhiset = true; } //------------------------------------------------------------------------ void JetCorrectionUncertainty::setJetE(float fE) { mJetE = fE; mIsJetEset = true; } //------------------------------------------------------------------------ void JetCorrectionUncertainty::setJetEMF(float fEMF) { mJetEMF = fEMF; mIsJetEMFset = true; } //------------------------------------------------------------------------ void JetCorrectionUncertainty::setLepPx(float fPx) { mLepPx = fPx; mIsLepPxset = true; } //------------------------------------------------------------------------ void JetCorrectionUncertainty::setLepPy(float fPy) { mLepPy = fPy; mIsLepPyset = true; } //------------------------------------------------------------------------ void JetCorrectionUncertainty::setLepPz(float fPz) { mLepPz = fPz; mIsLepPzset = true; } //------------------------------------------------------------------------
jbritt1/content-build
src/site/stages/build/process-cms-exports/schemas/input/node-full_width_banner_alert.js
/* eslint-disable camelcase */ module.exports = { type: 'object', properties: { title: { $ref: 'GenericNestedString' }, created: { $ref: 'GenericNestedString' }, changed: { $ref: 'GenericNestedString' }, metatag: { $ref: 'RawMetaTags' }, path: { $ref: 'RawPath' }, status: { $ref: 'GenericNestedBoolean' }, field_administration: { type: 'array', maxItems: 1, items: { $ref: 'EntityReference' }, }, field_alert_dismissable: { $ref: 'GenericNestedBoolean' }, field_alert_email_updates_button: { $ref: 'GenericNestedBoolean' }, field_alert_find_facilities_cta: { $ref: 'GenericNestedBoolean' }, field_alert_inheritance_subpages: { $ref: 'GenericNestedBoolean' }, field_alert_operating_status_cta: { $ref: 'GenericNestedBoolean' }, field_alert_type: { $ref: 'GenericNestedString' }, field_banner_alert_computdvalues: { $ref: 'GenericNestedString' }, field_banner_alert_vamcs: { type: 'array', maxItems: 1, items: { $ref: 'EntityReference' }, }, field_body: { $ref: 'GenericNestedString' }, field_operating_status_sendemail: { $ref: 'GenericNestedBoolean' }, field_situation_updates: { $ref: 'EntityReferenceArray' }, }, required: [ 'title', 'created', 'changed', 'metatag', 'path', 'status', 'field_administration', 'field_alert_dismissable', 'field_alert_email_updates_button', 'field_alert_find_facilities_cta', 'field_alert_inheritance_subpages', 'field_alert_operating_status_cta', 'field_alert_type', 'field_banner_alert_computdvalues', 'field_banner_alert_vamcs', 'field_body', 'field_operating_status_sendemail', 'field_situation_updates', ], };
jpalms/Team-Project
src/test/java/com/webcheckers/ui/PostResignGameRouteTest.java
package com.webcheckers.ui; import com.google.gson.Gson; import com.webcheckers.appl.GameManager; import com.webcheckers.model.Message; import com.webcheckers.model.Player; import com.webcheckers.model.TournamentScoreboard; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import spark.Request; import spark.Response; import spark.Session; import spark.TemplateEngine; import com.google.gson.Gson; import static org.mockito.Mockito.*; @Tag("UI-tier") public class PostResignGameRouteTest { // The component-under-test (CuT). private PostResignGameRoute CuT; private Request request; private Session session; private Response response; private GameManager gameManager; private TournamentScoreboard tournamentScoreboard; private Player player1; private Player player2; @BeforeEach public void setup(){ player1 = new Player("PlayerOne", Player.GameType.NORMAL); request = mock(Request.class); session = mock(Session.class); response = mock(Response.class); gameManager = mock(GameManager.class); tournamentScoreboard = mock(TournamentScoreboard.class); when(request.session()).thenReturn(session); when(session.attribute("Player")).thenReturn(player1); CuT = new PostResignGameRoute(gameManager, tournamentScoreboard); } @Test public void resign_success() { when(gameManager.resignGame(player1)).thenReturn(true); Object responseString = CuT.handle(request, response); Object gson = new Gson().toJson(new Message(player1.name + "Resigned", Message.MessageType.info)); assertEquals(responseString, gson); } @Test public void resign_fail() { when(gameManager.resignGame(player1)).thenReturn(false); Object responseString = CuT.handle(request, response); Object gson = new Gson().toJson(new Message(player1.name + "'s Resign failed", Message.MessageType.error)); assertEquals(responseString, gson); } }
gjkamstra/go-hsdp-api
cartel/start_test.go
<gh_stars>10-100 package cartel import ( "net/http" "testing" "github.com/stretchr/testify/assert" ) func TestStart(t *testing.T) { var startResponse = `{"message": {"foo.dev": {"cartel": "Instance started"}}}` var _ = `{"message": "Instance cannot be started due to current state: running"}` teardown, err := setup(t, &Config{ Token: sharedToken, Secret: sharedSecret, Host: "foo", NoTLS: true, }) muxCartel.HandleFunc("/v3/api/start", endpointMocker([]byte(sharedSecret), startResponse)) defer teardown() if err != nil { t.Fatal(err) } sr, resp, err := client.Start("foo.dev") if !assert.NotNil(t, resp) { return } if !assert.NotNil(t, sr) { return } assert.Nil(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, true, sr.Success()) } func TestAlreadyRunning(t *testing.T) { var failResponse = `{"message": "Instance cannot be started due to current state: running"}` teardown, err := setup(t, &Config{ Token: sharedToken, Secret: sharedSecret, Host: "foo", NoTLS: true, }) muxCartel.HandleFunc("/v3/api/start", endpointMocker([]byte(sharedSecret), failResponse, http.StatusBadRequest)) defer teardown() if err != nil { t.Fatal(err) } sr, resp, err := client.Start("foo.dev") if !assert.NotNil(t, resp) { return } if !assert.NotNil(t, sr) { return } if !assert.NotNil(t, err) { return } assert.Equal(t, http.StatusBadRequest, resp.StatusCode) assert.Equal(t, false, sr.Success()) }
yanzastro/RAIL
rail/creation/engines/flowEngine.py
<gh_stars>0 """ This is the subclass of Engine that wraps a pzflow Flow so that it can used to generate synthetic data """ import numpy as np import qp from pzflow import Flow from rail.core.data import PqHandle, QPHandle, FlowHandle from rail.creation.engines import Engine, PosteriorEvaluator class FlowEngine(Engine): """Engine wrapper for a pzflow Flow object.""" name = 'FlowEngine' inputs = [('flow', FlowHandle)] outputs = [('output', PqHandle)] def __init__(self, args, comm=None): """ Constructor Does standard Engine initialization and also gets the `Flow` object """ Engine.__init__(self, args, comm=comm) if not isinstance(args, dict): args = vars(args) self.set_flow(**args) def set_flow(self, **kwargs): """ Set the flow, either from an object or by loading from a file """ flow = kwargs.get('flow') if flow is None: #pragma: no cover return None if isinstance(flow, Flow): return self.set_data('flow', flow) return self.set_data('flow', data=None, path=flow) def run(self): """ Run method Calls `Flow.sample` to use the `Flow` object to generate photometric data Notes ----- Puts the data into the data store under this stages 'output' tag """ flow = self.get_data('flow') if flow is None: #pragma: no cover raise ValueError("Tried to run a FlowEngine before the Flow object is loaded") self.add_data('output', flow.sample(self.config.n_samples, self.config.seed)) class FlowPosterior(PosteriorEvaluator): """Engine wrapper for a pzflow Flow object Parameters ---------- data : pd.DataFrame Pandas dataframe of the data on which the posteriors are conditioned. Must have all columns in self.flow.data_columns, *except* for the column specified for the posterior (see below). column : str Name of the column for which the posterior is calculated. Must be one of the columns in self.flow.data_columns. However, whether or not this column is present in `data` is irrelevant. grid : np.ndarray Grid over which the posterior is calculated. err_samples : int, optional Number of samples from the error distribution to average over for the posterior calculation. If provided, Gaussian errors are assumed, and method will look for error columns in `inputs`. Error columns must end in `_err`. E.g. the error column for the variable `u` must be `u_err`. Zero error assumed for any missing error columns. seed: int, optional Random seed for drawing samples from the error distribution. marg_rules : dict, optional Dictionary with rules for marginalizing over missing variables. The dictionary must contain the key "flag", which gives the flag that indicates a missing value. E.g. if missing values are given the value 99, the dictionary should contain {"flag": 99}. The dictionary must also contain {"name": callable} for any variables that will need to be marginalized over, where name is the name of the variable, and callable is a callable that takes the row of variables and returns a grid over which to marginalize the variable. E.g. {"y": lambda row: np.linspace(0, row["x"], 10)}. Note: the callable for a given name must *always* return an array of the same length, regardless of the input row. DEFAULT: the default marg_rules dict is { "flag": np.nan, "u": np.linspace(25, 31, 10), } batch_size: int, default=None Size of batches in which to calculate posteriors. If None, all posteriors are calculated simultaneously. This is faster, but requires more memory. nan_to_zero : bool, default=True Whether to convert NaN's to zero probability in the final pdfs. """ name = 'FlowPosterior' config_options = PosteriorEvaluator.config_options.copy() config_options.update(grid=list, err_samples=10, seed=12345, marg_rules={"flag": np.nan, "mag_u_lsst": lambda row: np.linspace(25, 31, 10)}, batch_size=10000, nan_to_zero=True) inputs = [('flow', FlowHandle), ('input', PqHandle)] outputs = [('output', QPHandle)] def __init__(self, args, comm=None): """ Constructor Does standard Engine initialization and also gets the `Flow` object """ PosteriorEvaluator.__init__(self, args, comm=comm) def run(self): """ Run method Calls `Flow.posterior` to use the `Flow` object to get the posterior disrtibution Notes ----- Get the input data from the data store under this stages 'input' tag Puts the data into the data store under this stages 'output' tag """ data = self.get_data('input') flow = self.get_data('flow') if self.config.marg_rules is None: #pragma: no cover marg_rules = {"flag": np.nan, "mag_u_lsst": lambda row: np.linspace(25, 31, 10)} else: marg_rules = self.config.marg_rules pdfs = flow.posterior( inputs=data, column=self.config.column, grid=np.array(self.config.grid), err_samples=self.config.err_samples, seed=self.config.seed, marg_rules=marg_rules, batch_size=self.config.batch_size, nan_to_zero=self.config.nan_to_zero, ) ensemble = qp.Ensemble(qp.interp, data={"xvals": self.config.grid, "yvals": pdfs}) self.add_data('output', ensemble)
mtunganati/oneops
oneops-admin/lib/chef/knife/cloud_sync.rb
require 'chef/knife/base_sync' class Chef class Knife class CloudSync < Chef::Knife include ::BaseSync banner "Loads cloud templates into OneOps\nUsage: \n circuit cloud [OPTIONS] [CLOUDS...]" option :all, :short => "-a", :long => "--all", :description => "Sync all clouds" option :register, :short => "-r REGISTER", :long => "--register REGISTER", :description => "Specify the source register name to use during uploads" option :version, :short => "-v VERSION", :long => "--version VERSION", :description => "Specify the source register version to use during uploads" option :cloud_path, :short => "-o PATH:PATH", :long => "--cloud-path PATH:PATH", :description => "A colon-separated path to look for clouds in", :proc => lambda {|o| o.split(":")} option :reload, :long => "--reload", :description => "Remove the current cloud before syncing" def clouds_loader @clouds_loader ||= Knife::Core::ObjectLoader.new(Chef::Cloud, ui) end def run t1 = Time.now ENV['CMS_TRACE'] = 'true' if config[:cms_trace] config[:register] ||= Chef::Config[:register] config[:version] ||= Chef::Config[:version] config[:cloud_path] ||= Chef::Config[:cloud_path] @packs_loader ||= Knife::Core::ObjectLoader.new(Chef::Cloud, ui) if config[:all] files = (config[:cloud_path] || []).inject([]) {|a, dir| a + Dir.glob("#{dir}/*.rb").sort} else files = @name_args.inject([]) {|a, cloud| a << "#{cloud}.rb"} end if files.blank? && config[:all].blank? ui.error 'You must specify cloud name(s) or use the --all option to sync all.' exit(1) end comments = "#{ENV['USER']}:#{$0} #{config[:msg]}" files.each {|f| exit(1) unless sync_cloud(f, comments)} t2 = Time.now ui.info("\nProcessed #{files.size} clouds.\nDone at #{t2} in #{(t2 - t1).round(1)}sec") end def sync_cloud(file, comments) cloud = @packs_loader.load_from(config[:cloud_path], file) ui.info("\n--------------------------------------------------") ui.info(" #{cloud.name} ".blue(true)) ui.info('--------------------------------------------------') cloud.sync(config, comments) ui.info("\e[7m\e[32mSuccessfully synched\e[0m cloud #{cloud.name}") return cloud end end end end
ptrmu/camsim
src/sfm/sfm_isam2.hpp
#ifndef _SFM_ISAM2_HPP #define _SFM_ISAM2_HPP #include "sfm_resectioning.hpp" namespace camsim { class SfmIsam2Impl; class SfmIsam2 { std::unique_ptr<SfmIsam2Impl> impl_; public: SfmIsam2(int key_marker_id, const gtsam::Pose3 &key_marker_f_world); ~SfmIsam2(); void add_measurements(int camera_id, const PoseWithCovariance::StdVector &camera_f_markers); }; } int sfm_run_isam2(); #endif //_SFM_ISAM2_HPP
UniversityOfHelsinkiCS/grappa-front
src/studyfield/studyfield.actions.js
<reponame>UniversityOfHelsinkiCS/grappa-front export const STUDYFIELD_GET_ALL = "STUDYFIELD_GET_ALL"; export const STUDYFIELD_SAVE_ONE = "STUDYFIELD_SAVE_ONE"; export const STUDYFIELD_UPDATE_ONE = "STUDYFIELD_UPDATE_ONE"; export const STUDYFIELD_DELETE_ONE = "STUDYFIELD_DELETE_ONE"; export const getStudyfields = () => ( { type: STUDYFIELD_GET_ALL, payload: { request: { url: "/studyfield", method: "get", data: {} } } } ); export const saveStudyfield = (data) => ( { type: STUDYFIELD_SAVE_ONE, flashMessage: { type: "warning", title: "Request sent", body: "Waiting for Studyfield to be saved.", }, successMessage: { type: "success", title: "Success", body: "Studyfield was saved.", }, payload: { request: { method: "post", url: "/studyfield", data, } } } ); export const updateStudyfield = (data) => ( { type: STUDYFIELD_UPDATE_ONE, flashMessage: { type: "warning", title: "Request sent", body: "Waiting for Studyfield to be updated.", }, successMessage: { type: "success", title: "Success", body: "Studyfield was updated.", }, payload: { request: { method: "put", url: `/studyfield/${data.id}`, data, } } } ); export const deleteStudyfield = (studyfieldId) => ( { type: STUDYFIELD_DELETE_ONE, flashMessage: { type: "warning", title: "Request sent", body: "Waiting for Studyfield to be deleted.", }, successMessage: { type: "success", title: "Success", body: "Studyfield was deleted.", }, payload: { request: { method: "delete", url: `/studyfield/${studyfieldId}`, data: { id: studyfieldId }, } } } )