repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
TheInterventionCentre/NorMIT-Plan-App
Libs/MRML/Core/vtkMRMLDiffusionImageVolumeNode.h
<reponame>TheInterventionCentre/NorMIT-Plan-App /*=auto========================================================================= Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH) All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Program: 3D Slicer Module: $RCSfile: vtkMRMLVolumeNode.h,v $ Date: $Date: 2006/03/19 17:12:29 $ Version: $Revision: 1.13 $ =========================================================================auto=*/ #ifndef __vtkMRMLDiffusionImageVolumeNode_h #define __vtkMRMLDiffusionImageVolumeNode_h #include "vtkMRMLTensorVolumeNode.h" class vtkMRMLDiffusionWeightedVolumeNode; /// \brief MRML node for representing diffusion weighted MRI volume /// /// Diffusion Weigthed Volume nodes describe data sets that encode diffusion weigthed /// images. These images are the basis for computing the diffusion tensor. /// The node is a container for the neccesary information to interpert DW images: /// 1. Gradient information. /// 2. B value for each gradient. /// 3. Measurement frame that relates the coordinate system where the gradients are given /// to RAS. class VTK_MRML_EXPORT vtkMRMLDiffusionImageVolumeNode : public vtkMRMLTensorVolumeNode { public: static vtkMRMLDiffusionImageVolumeNode *New(); vtkTypeMacro(vtkMRMLDiffusionImageVolumeNode,vtkMRMLTensorVolumeNode); void PrintSelf(ostream& os, vtkIndent indent); virtual vtkMRMLNode* CreateNodeInstance(); /// /// Set node attributes virtual void ReadXMLAttributes( const char** atts); /// /// Write this node's information to a MRML file in XML format. virtual void WriteXML(ostream& of, int indent); /// /// Copy the node's attributes to this object virtual void Copy(vtkMRMLNode *node); /// /// Get node XML tag name (like Volume, Model) virtual const char* GetNodeTagName() {return "DiffusionImageVolume";}; /// Description: /// String ID of the storage MRML node void SetBaselineNodeID(const char* id); vtkGetStringMacro(BaselineNodeID); /// /// String ID of the display MRML node void SetMaskNodeID(const char* id); vtkGetStringMacro(MaskNodeID); /// Description: /// String ID of the display MRML node void SetDiffusionWeightedNodeID(const char* id); vtkGetStringMacro(DiffusionWeightedNodeID); /// /// Associated volume MRML node vtkMRMLVolumeNode* GetBaselineNode(); /// /// Associated volume MRML node vtkMRMLVolumeNode* GetMaskNode(); /// /// Associated volume MRML node vtkMRMLDiffusionWeightedVolumeNode* GetDiffusionWeightedNode(); /// /// Associated volume MRML node //vtkMRMLDiffusionImageVolumeDisplayNode* GetDisplayNode(); /// /// Update the stored reference to another node in the scene virtual void UpdateReferenceID(const char *oldID, const char *newID); /// /// Finds the storage node and read the data //void UpdateScene(vtkMRMLScene *scene); /// /// Updates this node if it depends on other nodes /// when the node is deleted in the scene void UpdateReferences(); /// /// alternative method to propagate events generated in Display nodes virtual void ProcessMRMLEvents ( vtkObject * /*caller*/, unsigned long /*event*/, void * /*callData*/ ); /// /// Create default storage node or NULL if does not have one virtual vtkMRMLStorageNode* CreateDefaultStorageNode() { return Superclass::CreateDefaultStorageNode(); }; protected: vtkMRMLDiffusionImageVolumeNode(); ~vtkMRMLDiffusionImageVolumeNode(); vtkMRMLDiffusionImageVolumeNode(const vtkMRMLDiffusionImageVolumeNode&); void operator=(const vtkMRMLDiffusionImageVolumeNode&); char *BaselineNodeID; char *MaskNodeID; char *DiffusionWeightedNodeID; }; #endif
mtauer/rl-deep-learning
pandemic-web/src/index.js
<filename>pandemic-web/src/index.js /* eslint-disable import/first */ /* eslint-disable import/newline-after-import */ import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider'; import { createMuiTheme } from '@material-ui/core/styles'; import store from './configureStore'; import MatchesPage from './pandemic/matches/MatchesPage'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; const theme = createMuiTheme({ typography: { fontFamily: '"IBM Plex Sans", sans-serif', }, overrides: { MuiTooltip: { tooltip: { backgroundColor: '#333333', }, }, MuiMenuItem: { root: { fontSize: '12px', paddingBottom: '2px', paddingTop: '2px', }, }, MuiTableRow: { root: { height: 40, }, head: { backgroundColor: '#F7F7F7', height: 32, }, }, MuiTableCell: { root: { paddingLeft: 16, paddingRight: 16, }, head: { borderTop: '2px solid #e0e0e0', }, }, }, }); ReactDOM.render( <Provider store={store}> <MuiThemeProvider theme={theme}> <MatchesPage /> </MuiThemeProvider> </Provider>, document.getElementById('root'), ); registerServiceWorker();
tangr1/operator
client/misc/put_notifications_markasread_responses.go
package misc // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "github.com/go-swagger/go-swagger/client" "github.com/go-swagger/go-swagger/httpkit" "github.com/go-swagger/go-swagger/strfmt" ) type PutNotificationsMarkasreadReader struct { formats strfmt.Registry } func (o *PutNotificationsMarkasreadReader) ReadResponse(response client.Response, consumer httpkit.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewPutNotificationsMarkasreadOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: return nil, NewAPIError("unknown error", response, response.Code()) } } // NewPutNotificationsMarkasreadOK creates a PutNotificationsMarkasreadOK with default headers values func NewPutNotificationsMarkasreadOK() *PutNotificationsMarkasreadOK { return &PutNotificationsMarkasreadOK{} } /*PutNotificationsMarkasreadOK 成功更新 */ type PutNotificationsMarkasreadOK struct { } func (o *PutNotificationsMarkasreadOK) Error() string { return fmt.Sprintf("[PUT /notifications/markasread][%d] putNotificationsMarkasreadOK ", 200) } func (o *PutNotificationsMarkasreadOK) readResponse(response client.Response, consumer httpkit.Consumer, formats strfmt.Registry) error { return nil }
ulilicht/picture-importer
src/components/Error/Error.js
<filename>src/components/Error/Error.js import React, {PropTypes} from 'react'; import classes from './Error.scss'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; class Error extends React.Component { constructor(props) { super(props); this.state = { shouldShowErrorWindow: this.props.hasError }; } static propTypes = { errorList: PropTypes.array.isRequired, clearError: PropTypes.func.isRequired, hasError: PropTypes.bool.isRequired }; renderError(error, index) { return ( <div className={classes.errorLine} key={index}> <div dangerouslySetInnerHTML={{__html: error.message}}></div> <div className={classes.errorAction}> <FlatButton onClick={() => this.props.clearError(error)} disabled={!error.isRetryPossible} label="Retry" secondary/></div> </div> ); } componentWillReceiveProps(nextProps) { if (nextProps.hasError) { this.setState({shouldShowErrorWindow: true}); } } handleClose = () => { this.setState({shouldShowErrorWindow: false}) } render() { let canBeClosed = true; this.props.errorList.forEach(error => { if (!error.canBeClosed) { canBeClosed = false } }); const actions = [ <FlatButton label="Close" primary={true} onTouchTap={this.handleClose} /> ]; return ( <div> <Dialog title="Please check: " actions={canBeClosed ? actions : null} modal open={this.state.shouldShowErrorWindow} > {this.props.errorList.map((error, index) => this.renderError(error, index))} </Dialog> </div> ); } } export default Error;
rxheem/tab-tracker
server/node_modules/joii/test/IssueReports/IssueReport21.js
/* Javascript Object Inheritance Implementation ______ ________ * (c) 2016 <<EMAIL>> __ / / __ \/ _/ _/ * Licensed under MIT. / // / /_/ // /_/ / * ------------------------------------------------------ \___/\____/___/__*/ var JOII = require('../../dist/joii').JOII; /** * Interface collisions */ test('IssueReports:IssueReport21', function(assert) { var InterfaceA = JOII.InterfaceBuilder('InterfaceA', {}); var InterfaceB = JOII.InterfaceBuilder('InterfaceB', {}); var InterfaceAImplemented = JOII.ClassBuilder({'implements': InterfaceA}, {}); var MyClass = JOII.ClassBuilder({ 'public nullable InterfaceA ia' : null }); var success; try { var myClass = new MyClass(); myClass.setIa(new InterfaceAImplemented()); success = true; } catch (exception){ console.error("exception thrown: " + exception.toString()); success = false; } ok(success, "myClass.setIa should not thrown an exception because the object is the right one"); });
ignaciocases/hermeneumatics
node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/collection/mutable/IndexedSeqView$$anon$2.js
/** @constructor */ ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2 = (function() { ScalaJS.c.scala_collection_mutable_IndexedSeqView$AbstractTransformed.call(this); this.endpoints$3 = null; this.$$outer$3 = null }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype = new ScalaJS.inheritable.scala_collection_mutable_IndexedSeqView$AbstractTransformed(); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.constructor = ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2; ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.length__I = (function() { return ScalaJS.impls.scala_collection_mutable_IndexedSeqView$Sliced$class__length__Lscala_collection_mutable_IndexedSeqView$Sliced__I(this) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.update__I__O__V = (function(idx, elem) { ScalaJS.impls.scala_collection_mutable_IndexedSeqView$Sliced$class__update__Lscala_collection_mutable_IndexedSeqView$Sliced__I__O__V(this, idx, elem) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.apply__I__O = (function(idx) { return ScalaJS.impls.scala_collection_GenSeqViewLike$Sliced$class__apply__Lscala_collection_GenSeqViewLike$Sliced__I__O(this, idx) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.foreach__Lscala_Function1__V = (function(f) { ScalaJS.impls.scala_collection_GenSeqViewLike$Sliced$class__foreach__Lscala_collection_GenSeqViewLike$Sliced__Lscala_Function1__V(this, f) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.iterator__Lscala_collection_Iterator = (function() { return ScalaJS.impls.scala_collection_GenSeqViewLike$Sliced$class__iterator__Lscala_collection_GenSeqViewLike$Sliced__Lscala_collection_Iterator(this) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.from__I = (function() { return ScalaJS.impls.scala_collection_GenTraversableViewLike$Sliced$class__from__Lscala_collection_GenTraversableViewLike$Sliced__I(this) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.until__I = (function() { return ScalaJS.impls.scala_collection_GenTraversableViewLike$Sliced$class__until__Lscala_collection_GenTraversableViewLike$Sliced__I(this) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.viewIdentifier__T = (function() { return ScalaJS.impls.scala_collection_GenTraversableViewLike$Sliced$class__viewIdentifier__Lscala_collection_GenTraversableViewLike$Sliced__T(this) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.endpoints__Lscala_collection_generic_SliceInterval = (function() { return this.endpoints$3 }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$mutable$IndexedSeqView$Sliced$$$outer__Lscala_collection_mutable_IndexedSeqView = (function() { return this.$$outer$3 }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenSeqViewLike$Sliced$$$outer__Lscala_collection_GenSeqViewLike = (function() { return this.$$outer$3 }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenIterableViewLike$Sliced$$$outer__Lscala_collection_GenIterableViewLike = (function() { return this.$$outer$3 }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenTraversableViewLike$Sliced$$$outer__Lscala_collection_GenTraversableViewLike = (function() { return this.$$outer$3 }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.apply__O__O = (function(v1) { return this.apply__I__O(ScalaJS.uI(v1)) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.init___Lscala_collection_mutable_IndexedSeqView__Lscala_collection_generic_SliceInterval = (function($$outer, _endpoints$1) { if (($$outer === null)) { throw new ScalaJS.c.java_lang_NullPointerException().init___() } else { this.$$outer$3 = $$outer }; var endpoints = _endpoints$1; this.endpoints$3 = endpoints; ScalaJS.c.scala_collection_mutable_IndexedSeqView$AbstractTransformed.prototype.init___Lscala_collection_mutable_IndexedSeqView.call(this, $$outer); ScalaJS.impls.scala_collection_GenTraversableViewLike$Sliced$class__$init$__Lscala_collection_GenTraversableViewLike$Sliced__V(this); ScalaJS.impls.scala_collection_GenIterableViewLike$Sliced$class__$init$__Lscala_collection_GenIterableViewLike$Sliced__V(this); ScalaJS.impls.scala_collection_GenSeqViewLike$Sliced$class__$init$__Lscala_collection_GenSeqViewLike$Sliced__V(this); ScalaJS.impls.scala_collection_mutable_IndexedSeqView$Sliced$class__$init$__Lscala_collection_mutable_IndexedSeqView$Sliced__V(this); return this }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.until__ = (function() { return ScalaJS.bI(this.until__I()) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.from__ = (function() { return ScalaJS.bI(this.from__I()) }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenTraversableViewLike$Sliced$$$outer__ = (function() { return this.scala$collection$GenTraversableViewLike$Sliced$$$outer__Lscala_collection_GenTraversableViewLike() }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenIterableViewLike$Sliced$$$outer__ = (function() { return this.scala$collection$GenIterableViewLike$Sliced$$$outer__Lscala_collection_GenIterableViewLike() }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$GenSeqViewLike$Sliced$$$outer__ = (function() { return this.scala$collection$GenSeqViewLike$Sliced$$$outer__Lscala_collection_GenSeqViewLike() }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.scala$collection$mutable$IndexedSeqView$Sliced$$$outer__ = (function() { return this.scala$collection$mutable$IndexedSeqView$Sliced$$$outer__Lscala_collection_mutable_IndexedSeqView() }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.endpoints__ = (function() { return this.endpoints__Lscala_collection_generic_SliceInterval() }); /** @constructor */ ScalaJS.inheritable.scala_collection_mutable_IndexedSeqView$$anon$2 = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_collection_mutable_IndexedSeqView$$anon$2.prototype = ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype; ScalaJS.is.scala_collection_mutable_IndexedSeqView$$anon$2 = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_mutable_IndexedSeqView$$anon$2))) }); ScalaJS.as.scala_collection_mutable_IndexedSeqView$$anon$2 = (function(obj) { if ((ScalaJS.is.scala_collection_mutable_IndexedSeqView$$anon$2(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.collection.mutable.IndexedSeqView$$anon$2") } }); ScalaJS.isArrayOf.scala_collection_mutable_IndexedSeqView$$anon$2 = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_mutable_IndexedSeqView$$anon$2))) }); ScalaJS.asArrayOf.scala_collection_mutable_IndexedSeqView$$anon$2 = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_collection_mutable_IndexedSeqView$$anon$2(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.collection.mutable.IndexedSeqView$$anon$2;", depth) } }); ScalaJS.data.scala_collection_mutable_IndexedSeqView$$anon$2 = new ScalaJS.ClassTypeData({ scala_collection_mutable_IndexedSeqView$$anon$2: 0 }, false, "scala.collection.mutable.IndexedSeqView$$anon$2", ScalaJS.data.scala_collection_mutable_IndexedSeqView$AbstractTransformed, { scala_collection_mutable_IndexedSeqView$$anon$2: 1, scala_collection_mutable_IndexedSeqView$Sliced: 1, scala_collection_SeqViewLike$Sliced: 1, scala_collection_GenSeqViewLike$Sliced: 1, scala_collection_IterableViewLike$Sliced: 1, scala_collection_GenIterableViewLike$Sliced: 1, scala_collection_TraversableViewLike$Sliced: 1, scala_collection_GenTraversableViewLike$Sliced: 1, scala_collection_mutable_IndexedSeqView$AbstractTransformed: 1, scala_collection_mutable_IndexedSeqView$Transformed: 1, scala_collection_mutable_IndexedSeqView: 1, scala_collection_mutable_IndexedSeqOptimized: 1, scala_collection_IndexedSeqOptimized: 1, scala_collection_mutable_IndexedSeq: 1, scala_collection_mutable_IndexedSeqLike: 1, scala_collection_IndexedSeq: 1, scala_collection_IndexedSeqLike: 1, scala_collection_mutable_Seq: 1, scala_collection_mutable_SeqLike: 1, scala_collection_mutable_Cloneable: 1, scala_Cloneable: 1, java_lang_Cloneable: 1, scala_collection_mutable_Iterable: 1, scala_collection_mutable_Traversable: 1, scala_Mutable: 1, scala_collection_SeqViewLike$AbstractTransformed: 1, scala_collection_SeqViewLike$Transformed: 1, scala_collection_GenSeqViewLike$Transformed: 1, scala_collection_SeqView: 1, scala_collection_GenSeqView: 1, scala_collection_SeqViewLike: 1, scala_collection_GenSeqViewLike: 1, scala_collection_IterableViewLike$Transformed: 1, scala_collection_GenIterableViewLike$Transformed: 1, scala_collection_TraversableViewLike$Transformed: 1, scala_collection_GenTraversableViewLike$Transformed: 1, scala_collection_IterableView: 1, scala_collection_GenIterableView: 1, scala_collection_IterableViewLike: 1, scala_collection_GenIterableViewLike: 1, scala_collection_TraversableView: 1, scala_collection_GenTraversableView: 1, scala_collection_TraversableViewLike: 1, scala_collection_GenTraversableViewLike: 1, scala_collection_ViewMkString: 1, scala_collection_Seq: 1, scala_collection_SeqLike: 1, scala_collection_GenSeq: 1, scala_collection_GenSeqLike: 1, scala_collection_Iterable: 1, scala_collection_IterableLike: 1, scala_Equals: 1, scala_collection_GenIterable: 1, scala_collection_GenIterableLike: 1, scala_collection_Traversable: 1, scala_collection_GenTraversable: 1, scala_collection_generic_GenericTraversableTemplate: 1, scala_collection_TraversableLike: 1, scala_collection_GenTraversableLike: 1, scala_collection_Parallelizable: 1, scala_collection_TraversableOnce: 1, scala_collection_GenTraversableOnce: 1, scala_collection_generic_FilterMonadic: 1, scala_collection_generic_HasNewBuilder: 1, scala_PartialFunction: 1, scala_Function1: 1, java_lang_Object: 1 }); ScalaJS.c.scala_collection_mutable_IndexedSeqView$$anon$2.prototype.$classData = ScalaJS.data.scala_collection_mutable_IndexedSeqView$$anon$2; //@ sourceMappingURL=IndexedSeqView$$anon$2.js.map
LimeChain/hashport-validator
bootstrap/watchers.go
/* * Copyright 2022 LimeChain Ltd. * * 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 bootstrap import ( "time" "github.com/limechain/hedera-eth-bridge-validator/app/domain/client" "github.com/limechain/hedera-eth-bridge-validator/app/domain/repository" "github.com/limechain/hedera-eth-bridge-validator/app/domain/service" aw "github.com/limechain/hedera-eth-bridge-validator/app/process/watcher/assets" cmw "github.com/limechain/hedera-eth-bridge-validator/app/process/watcher/message" pw "github.com/limechain/hedera-eth-bridge-validator/app/process/watcher/prometheus" tw "github.com/limechain/hedera-eth-bridge-validator/app/process/watcher/transfer" "github.com/limechain/hedera-eth-bridge-validator/config" log "github.com/sirupsen/logrus" ) func createTransferWatcher(configuration *config.Config, transferService service.Transfers, assetsService service.Assets, mirrorNode client.MirrorNode, repository *repository.Status, contractServices map[uint64]service.Contracts, prometheusService service.Prometheus, pricingService service.Pricing, ) *tw.Watcher { account := configuration.Bridge.Hedera.BridgeAccount log.Debugf("Added Transfer Watcher for account [%s]", account) return tw.NewWatcher( transferService, mirrorNode, account, configuration.Node.Clients.MirrorNode.PollingInterval, *repository, configuration.Node.Clients.Hedera.StartTimestamp, contractServices, assetsService, configuration.Node.Validator, prometheusService, pricingService, ) } func createConsensusTopicWatcher(configuration *config.Config, client client.MirrorNode, repository repository.Status, ) *cmw.Watcher { topic := configuration.Bridge.TopicId log.Debugf("Added Topic Watcher for topic [%s]\n", topic) return cmw.NewWatcher(client, topic, repository, configuration.Node.Clients.MirrorNode.PollingInterval, configuration.Node.Clients.Hedera.StartTimestamp) } func createAssetsWatcher( mirrorNode client.MirrorNode, configuration *config.Config, evmFungibleTokenClients map[uint64]map[string]client.EvmFungibleToken, evmNonFungibleTokenClients map[uint64]map[string]client.EvmNft, assetsService service.Assets, ) *aw.Watcher { log.Debugf("Added Assets Watcher") return aw.NewWatcher( mirrorNode, configuration.Bridge, evmFungibleTokenClients, evmNonFungibleTokenClients, assetsService) } func createPrometheusWatcher( dashboardPolling time.Duration, mirrorNode client.MirrorNode, configuration *config.Config, prometheusService service.Prometheus, evmFungibleTokenClients map[uint64]map[string]client.EvmFungibleToken, evmNonFungibleTokenClients map[uint64]map[string]client.EvmNft, assetsService service.Assets, ) *pw.Watcher { log.Debugf("Added Prometheus Watcher for dashboard metrics") return pw.NewWatcher( dashboardPolling, mirrorNode, configuration.Bridge, prometheusService, evmFungibleTokenClients, evmNonFungibleTokenClients, assetsService) }
TheSledgeHammer/2.11BSD
contrib/ingres/source/pipes.h
# /* ** pipes.h ** ** Interprocess pipe format and associated manifest constants */ # define PBUFSIZ 120 /* length of pipe buffer */ # define HDRSIZ 8 /* length of pipe header */ /* -- PIPE PARAMETERS -- */ # define NORM_STAT 0 /* HDRSTAT: data block */ # define LAST_STAT 1 /* HDRSTAT: last block of cmnd */ # define ERR_STAT 2 /* HDRSTAT: error block (sync) */ # define SYNC_STAT 3 /* sync on delete signal */ struct pipfrmt /* interprocess pipe format: */ { char exec_id; /* target overlay id */ char func_id; /* command id in target overlay */ int err_id; /* error status 0 - no errors non zero, error identifier */ char hdrstat; /* block status word 0 - good block in command 1 - last block in command */ char buf_len; /* # of useful bytes in PBUF values 0 to 120. rdpipe effectively concatenates significant parts of blocks. */ char param_id; /* one byte param available to calling pgm */ char expansion; /* reserved for expansion */ char pbuf[PBUFSIZ]; /* pipe data buffer */ int pbuf_pt; /* next available slot in PBUF */ }; /* modes for rdpipe and wrpipe */ # define P_PRIME 0 /* prime the pipe */ # define P_NORM 1 /* normal read or write */ # define P_SYNC 2 /* read for sync */ # define P_END 2 /* write a sync block */ # define P_EXECID 3 /* read execid */ # define P_FUNCID 4 /* read funcid */ # define P_FLUSH 3 /* write non-sync block */ # define P_WRITE 4 /* write block, previous type */ # define P_INT 5 /* synchronize on delete interrupt */ # define P_PARAM 6 /* set/get param field */ /* pipe descriptors */ extern int R_up; /* Read from process n-1 */ extern int W_up; /* Write to process n-1 */ extern int R_down; /* Read from process n+1 */ extern int W_down; /* Write to process n+1 */ extern int R_front; /* Read from front end */ extern int W_front; /* Write to front end */
rudylee/expo
packages/unimodules-permissions-interface/build/PermissionsInterface.js
export var PermissionStatus; (function (PermissionStatus) { PermissionStatus["GRANTED"] = "granted"; PermissionStatus["UNDETERMINED"] = "undetermined"; PermissionStatus["DENIED"] = "denied"; })(PermissionStatus || (PermissionStatus = {})); //# sourceMappingURL=PermissionsInterface.js.map
htfy96/leetcode-solutions
code/Group Anagrams.cpp
<filename>code/Group Anagrams.cpp class Solution { using CntT = array<int, 26>; static size_t h(const CntT& v) { size_t ans = 0; for (auto&& w: v) { ans = ans * 131 + w; } return ans; } public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<CntT, vector<string>, decltype(&h)> m(256, &h); for (auto&& s: strs) { CntT cnt {}; for (char c: s) cnt[c-'a']++; m[cnt].push_back(move(s)); } vector<vector<string>> ans; ans.reserve(m.size()); for (auto&& item: m) { ans.push_back(move(item.second)); } return ans; } };
allanfra/k-9
mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/FetchPartCallback.java
<gh_stars>1000+ package com.fsck.k9.mail.store.imap; import java.io.IOException; import com.fsck.k9.mail.BodyFactory; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.filter.FixedLengthInputStream; import com.fsck.k9.mail.internet.MimeHeader; class FetchPartCallback implements ImapResponseCallback { private final Part part; private final BodyFactory bodyFactory; FetchPartCallback(Part part, BodyFactory bodyFactory) { this.part = part; this.bodyFactory = bodyFactory; } @Override public Object foundLiteral(ImapResponse response, FixedLengthInputStream literal) throws IOException { if (response.getTag() == null && ImapResponseParser.equalsIgnoreCase(response.get(1), "FETCH")) { //TODO: check for correct UID String contentTransferEncoding = part.getHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)[0]; String contentType = part.getHeader(MimeHeader.HEADER_CONTENT_TYPE)[0]; return bodyFactory.createBody(contentTransferEncoding, contentType, literal); } return null; } }
xiangcman/YCAudioPlayer
app/src/main/java/cn/ycbjie/ycaudioplayer/ui/advert/model/api/AdvertApi.java
<filename>app/src/main/java/cn/ycbjie/ycaudioplayer/ui/advert/model/api/AdvertApi.java<gh_stars>1-10 package cn.ycbjie.ycaudioplayer.ui.advert.model.api; import cn.ycbjie.ycaudioplayer.model.bean.MusicLrc; import cn.ycbjie.ycaudioplayer.model.bean.SearchMusic; import cn.ycbjie.ycaudioplayer.ui.advert.model.bean.AdvertCommon; import cn.ycbjie.ycaudioplayer.ui.music.onLine.model.bean.ArtistInfo; import cn.ycbjie.ycaudioplayer.ui.music.onLine.model.bean.OnlineMusicList; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable; public interface AdvertApi { @GET("fundworks/media/getFlashScreen") Observable<AdvertCommon> getSplashImage(@Query("type") int type); }
Arkania/ArkCORE
src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp
/* * Copyright (C) 2008 - 2013 ArkCORE <http://www.arkania.net/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptPCH.h" #include "trial_of_the_crusader.h" enum eYells { SAY_STAGE_0_01 = -1649070, SAY_STAGE_0_02 = -1649071, SAY_STAGE_0_03a = -1649072, SAY_STAGE_0_03h = -1649073, SAY_STAGE_0_04 = -1649074, SAY_STAGE_0_05 = -1649075, SAY_STAGE_0_06 = -1649076, SAY_STAGE_0_WIPE = -1649077, SAY_STAGE_1_01 = -1649080, SAY_STAGE_1_02 = -1649081, SAY_STAGE_1_03 = -1649082, SAY_STAGE_1_04 = -1649083, SAY_STAGE_1_05 = -1649030, //INTRO Jaraxxus SAY_STAGE_1_06 = -1649084, SAY_STAGE_1_07 = -1649086, SAY_STAGE_1_08 = -1649087, SAY_STAGE_1_09 = -1649088, SAY_STAGE_1_10 = -1649089, SAY_STAGE_1_11 = -1649090, SAY_STAGE_2_01 = -1649091, SAY_STAGE_2_02a = -1649092, SAY_STAGE_2_02h = -1649093, SAY_STAGE_2_03 = -1649094, SAY_STAGE_2_04a = -1649095, SAY_STAGE_2_04h = -1649096, SAY_STAGE_2_05a = -1649097, SAY_STAGE_2_05h = -1649098, SAY_STAGE_2_06 = -1649099, SAY_STAGE_3_01 = -1649100, SAY_STAGE_3_02 = -1649101, SAY_STAGE_3_03a = -1649102, SAY_STAGE_3_03h = -1649103, SAY_STAGE_4_01 = -1649104, SAY_STAGE_4_02 = -1649105, SAY_STAGE_4_03 = -1649106, SAY_STAGE_4_04 = -1649107, SAY_STAGE_4_05 = -1649108, SAY_STAGE_4_06 = -1649109, SAY_STAGE_4_07 = -1649110, }; struct _Messages { eAnnouncerMessages msgnum; uint32 id; bool state; uint32 encounter; }; static _Messages _GossipMessage[]= { {MSG_BEASTS, GOSSIP_ACTION_INFO_DEF+1, false, TYPE_BEASTS}, {MSG_JARAXXUS, GOSSIP_ACTION_INFO_DEF+2, false, TYPE_JARAXXUS}, {MSG_CRUSADERS, GOSSIP_ACTION_INFO_DEF+3, false, TYPE_CRUSADERS}, {MSG_VALKIRIES, GOSSIP_ACTION_INFO_DEF+4, false, TYPE_VALKIRIES}, {MSG_LICH_KING, GOSSIP_ACTION_INFO_DEF+5, false, TYPE_ANUBARAK}, {MSG_ANUBARAK, GOSSIP_ACTION_INFO_DEF+6, true, TYPE_ANUBARAK} }; enum { NUM_MESSAGES = 6, }; class npc_announcer_toc10 : public CreatureScript { public: npc_announcer_toc10() : CreatureScript("npc_announcer_toc10") { } struct npc_announcer_toc10AI : public ScriptedAI { npc_announcer_toc10AI(Creature* creature) : ScriptedAI(creature) { m_pInstance = (InstanceScript*)creature->GetInstanceScript(); } InstanceScript* m_pInstance; void Reset() { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); if (Creature* pAlly = GetClosestCreatureWithEntry(me, NPC_THRALL, 300.0f)) pAlly->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); if (Creature* pAlly = GetClosestCreatureWithEntry(me, NPC_PROUDMOORE, 300.0f)) pAlly->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); } void AttackStart(Unit* /*who*/) {} }; bool OnGossipHello(Player* player, Creature* creature) { InstanceScript* instanceScript = creature->GetInstanceScript(); if (!instanceScript) return true; char const* _message = "We are ready!"; if (player->isInCombat() || instanceScript->IsEncounterInProgress() || instanceScript->GetData(TYPE_EVENT)) return true; uint8 i = 0; for (; i < NUM_MESSAGES; ++i) { if ((!_GossipMessage[i].state && instanceScript->GetData(_GossipMessage[i].encounter) != DONE) || (_GossipMessage[i].state && instanceScript->GetData(_GossipMessage[i].encounter) == DONE)) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, _message, GOSSIP_SENDER_MAIN, _GossipMessage[i].id); break; } } player->SEND_GOSSIP_MENU(_GossipMessage[i].msgnum, creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); player->CLOSE_GOSSIP_MENU(); InstanceScript* instanceScript = creature->GetInstanceScript(); if (!instanceScript) return true; switch (action) { case GOSSIP_ACTION_INFO_DEF+1: if (instanceScript->GetData(TYPE_BEASTS) != DONE) { instanceScript->SetData(TYPE_EVENT, 110); instanceScript->SetData(TYPE_NORTHREND_BEASTS, NOT_STARTED); instanceScript->SetData(TYPE_BEASTS, NOT_STARTED); } break; case GOSSIP_ACTION_INFO_DEF+2: if (Creature* icehowl = Unit::GetCreature(*player, instanceScript->GetData64(NPC_ICEHOWL))) icehowl->DespawnOrUnsummon(); if (Creature* jaraxxus = Unit::GetCreature(*player, instanceScript->GetData64(NPC_JARAXXUS))) { jaraxxus->RemoveAurasDueToSpell(SPELL_JARAXXUS_CHAINS); jaraxxus->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); jaraxxus->SetReactState(REACT_AGGRESSIVE); jaraxxus->SetInCombatWithZone(); } else if (instanceScript->GetData(TYPE_JARAXXUS) != DONE) { instanceScript->SetData(TYPE_EVENT, 1010); instanceScript->SetData(TYPE_JARAXXUS, NOT_STARTED); } break; case GOSSIP_ACTION_INFO_DEF+3: if (Creature* jaraxxus = Unit::GetCreature(*player, instanceScript->GetData64(NPC_JARAXXUS))) jaraxxus->DespawnOrUnsummon(); if (instanceScript->GetData(TYPE_CRUSADERS) != DONE) { if (player->GetTeam() == ALLIANCE) instanceScript->SetData(TYPE_EVENT, 3000); else instanceScript->SetData(TYPE_EVENT, 3001); instanceScript->SetData(TYPE_CRUSADERS, NOT_STARTED); } break; case GOSSIP_ACTION_INFO_DEF+4: if (instanceScript->GetData(TYPE_VALKIRIES) != DONE) { instanceScript->SetData(TYPE_EVENT, 4000); instanceScript->SetData(TYPE_VALKIRIES, NOT_STARTED); } break; case GOSSIP_ACTION_INFO_DEF+5: { if (instanceScript->GetData(TYPE_LICH_KING) != DONE && !player->isGameMaster()) return true; if (GameObject* floor = GameObject::GetGameObject(*player, instanceScript->GetData64(GO_ARGENT_COLISEUM_FLOOR))) floor->SetDestructibleState(GO_DESTRUCTIBLE_DESTROYED); creature->CastSpell(creature, 69016, false); Creature* anubArak = Unit::GetCreature(*creature, instanceScript->GetData64(NPC_ANUBARAK)); if (!anubArak || !anubArak->isAlive()) anubArak = creature->SummonCreature(NPC_ANUBARAK, AnubarakLoc[0].GetPositionX(), AnubarakLoc[0].GetPositionY(), AnubarakLoc[0].GetPositionZ(), 3, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME); instanceScript->SetData(TYPE_ANUBARAK, NOT_STARTED); if (creature->IsVisible()) creature->SetVisible(false); break; } } creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); return true; } CreatureAI* GetAI(Creature* creature) const { return new npc_announcer_toc10AI(creature); } }; class boss_lich_king_toc : public CreatureScript { public: boss_lich_king_toc() : CreatureScript("boss_lich_king_toc") { } struct boss_lich_king_tocAI : public ScriptedAI { boss_lich_king_tocAI(Creature* creature) : ScriptedAI(creature) { m_pInstance = (InstanceScript*)creature->GetInstanceScript(); } InstanceScript* m_pInstance; uint32 m_uiUpdateTimer; void Reset() { m_uiUpdateTimer = 0; me->SetReactState(REACT_PASSIVE); if (Creature* summoned = me->SummonCreature(NPC_TRIGGER, ToCCommonLoc[2].GetPositionX(), ToCCommonLoc[2].GetPositionY(), ToCCommonLoc[2].GetPositionZ(), 5, TEMPSUMMON_TIMED_DESPAWN, 60000)) { summoned->CastSpell(summoned, 51807, false); summoned->SetDisplayId(11686); } if (m_pInstance) m_pInstance->SetData(TYPE_LICH_KING, IN_PROGRESS); me->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); } void MovementInform(uint32 uiType, uint32 uiId) { if (uiType != POINT_MOTION_TYPE) return; switch (uiId) { case 0: m_pInstance->SetData(TYPE_EVENT, 5030); break; case 1: m_pInstance->SetData(TYPE_EVENT, 5050); break; } } void UpdateAI(const uint32 uiDiff) { if (!m_pInstance) return; if (m_pInstance->GetData(TYPE_EVENT_NPC) != NPC_LICH_KING_1) return; m_uiUpdateTimer = m_pInstance->GetData(TYPE_EVENT_TIMER); if (m_uiUpdateTimer <= uiDiff) { switch (m_pInstance->GetData(TYPE_EVENT)) { case 5010: DoScriptText(SAY_STAGE_4_02, me); m_uiUpdateTimer = 3000; me->GetMotionMaster()->MovePoint(0, LichKingLoc[0]); m_pInstance->SetData(TYPE_EVENT, 5020); break; case 5030: DoScriptText(SAY_STAGE_4_04, me); me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_TALK); m_uiUpdateTimer = 10000; m_pInstance->SetData(TYPE_EVENT, 5040); break; case 5040: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); me->GetMotionMaster()->MovePoint(1, LichKingLoc[1]); m_uiUpdateTimer = 1000; m_pInstance->SetData(TYPE_EVENT, 0); break; case 5050: me->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 5060); break; case 5060: DoScriptText(SAY_STAGE_4_05, me); me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL); m_uiUpdateTimer = 2500; m_pInstance->SetData(TYPE_EVENT, 5070); break; case 5070: me->CastSpell(me, 68198, false); m_uiUpdateTimer = 1500; m_pInstance->SetData(TYPE_EVENT, 5080); break; case 5080: if (GameObject* pGoFloor = m_pInstance->instance->GetGameObject(m_pInstance->GetData64(GO_ARGENT_COLISEUM_FLOOR))) pGoFloor->SetDestructibleState(GO_DESTRUCTIBLE_DESTROYED); me->CastSpell(me, 69016, false); if (m_pInstance) { m_pInstance->SetData(TYPE_LICH_KING, DONE); Creature* pTemp = Unit::GetCreature(*me, m_pInstance->GetData64(NPC_ANUBARAK)); if (!pTemp || !pTemp->isAlive()) pTemp = me->SummonCreature(NPC_ANUBARAK, AnubarakLoc[0].GetPositionX(), AnubarakLoc[0].GetPositionY(), AnubarakLoc[0].GetPositionZ(), 3, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME); m_pInstance->SetData(TYPE_EVENT, 0); } me->DespawnOrUnsummon(); m_uiUpdateTimer = 20000; break; } } else m_uiUpdateTimer -= uiDiff; m_pInstance->SetData(TYPE_EVENT_TIMER, m_uiUpdateTimer); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_lich_king_tocAI(creature); } }; class npc_fizzlebang_toc : public CreatureScript { public: npc_fizzlebang_toc() : CreatureScript("npc_fizzlebang_toc") { } struct npc_fizzlebang_tocAI : public ScriptedAI { npc_fizzlebang_tocAI(Creature* creature) : ScriptedAI(creature), Summons(me) { m_pInstance = (InstanceScript*)me->GetInstanceScript(); } InstanceScript* m_pInstance; SummonList Summons; uint32 m_uiUpdateTimer; uint64 m_uiPortalGUID; uint64 m_uiTriggerGUID; void JustDied(Unit* killer) { DoScriptText(SAY_STAGE_1_06, me, killer); m_pInstance->SetData(TYPE_EVENT, 1180); if (Creature* pTemp = Unit::GetCreature(*me, m_pInstance->GetData64(NPC_JARAXXUS))) { pTemp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pTemp->SetReactState(REACT_AGGRESSIVE); pTemp->SetInCombatWithZone(); } } void Reset() { me->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); m_uiPortalGUID = 0; me->GetMotionMaster()->MovePoint(1, ToCCommonLoc[10].GetPositionX(), ToCCommonLoc[10].GetPositionY()-60, ToCCommonLoc[10].GetPositionZ()); } void MovementInform(uint32 uiType, uint32 uiId) { if (uiType != POINT_MOTION_TYPE) return; switch (uiId) { case 1: me->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); if (m_pInstance) { m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); m_pInstance->SetData(TYPE_EVENT, 1120); m_pInstance->SetData(TYPE_EVENT_TIMER, 1000); } break; } } void JustSummoned(Creature* summoned) { Summons.Summon(summoned); } void UpdateAI(const uint32 uiDiff) { if (!m_pInstance) return; if (m_pInstance->GetData(TYPE_EVENT_NPC) != NPC_FIZZLEBANG) return; m_uiUpdateTimer = m_pInstance->GetData(TYPE_EVENT_TIMER); if (m_uiUpdateTimer <= uiDiff) { switch (m_pInstance->GetData(TYPE_EVENT)) { case 1110: if (Creature* pIcehowl = Unit::GetCreature(*me, m_pInstance->GetData64(NPC_ICEHOWL))) pIcehowl->DespawnOrUnsummon(); m_pInstance->SetData(TYPE_EVENT, 1120); m_uiUpdateTimer = 4000; break; case 1120: DoScriptText(SAY_STAGE_1_02, me); m_pInstance->SetData(TYPE_EVENT, 1130); m_uiUpdateTimer = 12000; break; case 1130: me->GetMotionMaster()->MovementExpired(); DoScriptText(SAY_STAGE_1_03, me); me->HandleEmoteCommand(EMOTE_ONESHOT_SPELLCAST_OMNI); if (Unit* pTrigger = me->SummonCreature(NPC_TRIGGER, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY(), ToCCommonLoc[1].GetPositionZ(), 4.69494f, TEMPSUMMON_MANUAL_DESPAWN)) { m_uiTriggerGUID = pTrigger->GetGUID(); pTrigger->SetFloatValue(OBJECT_FIELD_SCALE_X, 2.0f); pTrigger->SetDisplayId(22862); pTrigger->CastSpell(pTrigger, SPELL_WILFRED_PORTAL, false); } m_pInstance->SetData(TYPE_EVENT, 1132); m_uiUpdateTimer = 4000; break; case 1132: me->GetMotionMaster()->MovementExpired(); m_pInstance->SetData(TYPE_EVENT, 1134); m_uiUpdateTimer = 4000; break; case 1134: me->HandleEmoteCommand(EMOTE_ONESHOT_SPELLCAST_OMNI); if (Creature* pPortal = me->SummonCreature(NPC_WILFRED_PORTAL, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY(), ToCCommonLoc[1].GetPositionZ(), 4.71239f, TEMPSUMMON_MANUAL_DESPAWN)) { pPortal->SetReactState(REACT_PASSIVE); pPortal->SetFloatValue(OBJECT_FIELD_SCALE_X, 2.0f); pPortal->CastSpell(pPortal, SPELL_WILFRED_PORTAL, false); m_uiPortalGUID = pPortal->GetGUID(); } m_uiUpdateTimer = 4000; m_pInstance->SetData(TYPE_EVENT, 1135); break; case 1135: m_pInstance->SetData(TYPE_EVENT, 1140); m_uiUpdateTimer = 3000; break; case 1140: DoScriptText(SAY_STAGE_1_04, me); if (Creature* pTemp = me->SummonCreature(NPC_JARAXXUS, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY(), ToCCommonLoc[1].GetPositionZ(), 5.0f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME)) { pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pTemp->SetReactState(REACT_PASSIVE); pTemp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[1].GetPositionX(), ToCCommonLoc[1].GetPositionY()-10, ToCCommonLoc[1].GetPositionZ()); } m_pInstance->SetData(TYPE_EVENT, 1142); m_uiUpdateTimer = 5000; break; case 1142: if (Creature* pTemp = Unit::GetCreature(*me, m_pInstance->GetData64(NPC_JARAXXUS))) pTemp->SetTarget(me->GetGUID()); if (Creature* pTrigger = Unit::GetCreature(*me, m_uiTriggerGUID)) pTrigger->DespawnOrUnsummon(); if (Creature* pPortal = Unit::GetCreature(*me, m_uiPortalGUID)) pPortal->DespawnOrUnsummon(); m_pInstance->SetData(TYPE_EVENT, 1144); m_uiUpdateTimer = 10000; break; case 1144: if (Creature* pTemp = Unit::GetCreature(*me, m_pInstance->GetData64(NPC_JARAXXUS))) DoScriptText(SAY_STAGE_1_05, pTemp); m_pInstance->SetData(TYPE_EVENT, 1150); m_uiUpdateTimer = 5000; break; case 1150: if (Creature* pTemp = Unit::GetCreature(*me, m_pInstance->GetData64(NPC_JARAXXUS))) { //1-shot Fizzlebang pTemp->CastSpell(me, 67888, false); me->SetInCombatWith(pTemp); pTemp->AddThreat(me, 1000.0f); pTemp->AI()->AttackStart(me); } m_pInstance->SetData(TYPE_EVENT, 1160); m_uiUpdateTimer = 3000; break; } } else m_uiUpdateTimer -= uiDiff; m_pInstance->SetData(TYPE_EVENT_TIMER, m_uiUpdateTimer); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_fizzlebang_tocAI(creature); } }; class npc_tirion_toc : public CreatureScript { public: npc_tirion_toc() : CreatureScript("npc_tirion_toc") { } struct npc_tirion_tocAI : public ScriptedAI { npc_tirion_tocAI(Creature* creature) : ScriptedAI(creature) { m_pInstance = (InstanceScript*)me->GetInstanceScript(); } InstanceScript* m_pInstance; uint32 m_uiUpdateTimer; void Reset() {} void AttackStart(Unit* /*who*/) {} void UpdateAI(const uint32 uiDiff) { if (!m_pInstance) return; if (m_pInstance->GetData(TYPE_EVENT_NPC) != NPC_TIRION) return; m_uiUpdateTimer = m_pInstance->GetData(TYPE_EVENT_TIMER); if (m_uiUpdateTimer <= uiDiff) { switch (m_pInstance->GetData(TYPE_EVENT)) { case 110: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_TALK); DoScriptText(SAY_STAGE_0_01, me); m_uiUpdateTimer = 22000; m_pInstance->SetData(TYPE_EVENT, 120); break; case 140: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_TALK); DoScriptText(SAY_STAGE_0_02, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 150); m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); break; case 150: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_NONE); if (m_pInstance->GetData(TYPE_BEASTS) != DONE) { me->SummonCreature(NPC_GORMOK, ToCCommonLoc[10].GetPositionX(), ToCCommonLoc[10].GetPositionY(), ToCCommonLoc[10].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 30*IN_MILLISECONDS); if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_GORMOK))) { pTemp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[5].GetPositionX(), ToCCommonLoc[5].GetPositionY(), ToCCommonLoc[5].GetPositionZ()); pTemp->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); pTemp->SetReactState(REACT_PASSIVE); } } m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 155); break; case 155: if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_GORMOK))) { pTemp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); pTemp->SetReactState(REACT_AGGRESSIVE); pTemp->SetInCombatWithZone(); } m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); m_pInstance->SetData(TYPE_BEASTS, IN_PROGRESS); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 160); break; case 200: DoScriptText(SAY_STAGE_0_04, me); m_uiUpdateTimer = 8000; m_pInstance->SetData(TYPE_EVENT, 205); break; case 205: m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 210); m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); break; case 210: if (m_pInstance->GetData(TYPE_BEASTS) != DONE) { me->SummonCreature(NPC_DREADSCALE, ToCCommonLoc[3].GetPositionX(), ToCCommonLoc[3].GetPositionY(), ToCCommonLoc[3].GetPositionZ(), 5, TEMPSUMMON_MANUAL_DESPAWN); me->SummonCreature(NPC_ACIDMAW, ToCCommonLoc[4].GetPositionX(), ToCCommonLoc[4].GetPositionY(), ToCCommonLoc[4].GetPositionZ(), 5, TEMPSUMMON_MANUAL_DESPAWN); if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_DREADSCALE))) { pTemp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[8].GetPositionX(), ToCCommonLoc[8].GetPositionY(), ToCCommonLoc[8].GetPositionZ()); pTemp->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); pTemp->SetReactState(REACT_PASSIVE); } if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_ACIDMAW))) { pTemp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[9].GetPositionX(), ToCCommonLoc[9].GetPositionY(), ToCCommonLoc[9].GetPositionZ()); pTemp->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); pTemp->SetReactState(REACT_PASSIVE); } } m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 220); break; case 220: if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_DREADSCALE))) { pTemp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); pTemp->SetReactState(REACT_AGGRESSIVE); pTemp->SetInCombatWithZone(); } if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_ACIDMAW))) { pTemp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); pTemp->SetReactState(REACT_AGGRESSIVE); pTemp->SetInCombatWithZone(); } m_pInstance->SetData(TYPE_EVENT, 230); m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); break; case 300: DoScriptText(SAY_STAGE_0_05, me); m_uiUpdateTimer = 8000; m_pInstance->SetData(TYPE_EVENT, 305); break; case 305: m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 310); m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); break; case 310: if (m_pInstance->GetData(TYPE_BEASTS) != DONE) { me->SummonCreature(NPC_ICEHOWL, ToCCommonLoc[10].GetPositionX(), ToCCommonLoc[10].GetPositionY(), ToCCommonLoc[10].GetPositionZ(), 5, TEMPSUMMON_DEAD_DESPAWN); if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_ICEHOWL))) { pTemp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[5].GetPositionX(), ToCCommonLoc[5].GetPositionY(), ToCCommonLoc[5].GetPositionZ()); pTemp->SetInCombatWithZone(); } } m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 315); break; case 315: m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); m_pInstance->SetData(TYPE_EVENT, 320); break; case 400: DoScriptText(SAY_STAGE_0_06, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 0); break; case 666: DoScriptText(SAY_STAGE_0_WIPE, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 0); break; case 1010: DoScriptText(SAY_STAGE_1_01, me); m_uiUpdateTimer = 7000; m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); me->SummonCreature(NPC_FIZZLEBANG, ToCCommonLoc[10].GetPositionX(), ToCCommonLoc[10].GetPositionY(), ToCCommonLoc[10].GetPositionZ(), 2, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME); m_pInstance->SetData(TYPE_EVENT, 0); break; case 1180: DoScriptText(SAY_STAGE_1_07, me); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 0); break; case 2000: DoScriptText(SAY_STAGE_1_08, me); m_uiUpdateTimer = 18000; m_pInstance->SetData(TYPE_EVENT, 2010); break; case 2030: DoScriptText(SAY_STAGE_1_11, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 0); break; case 3000: DoScriptText(SAY_STAGE_2_01, me); m_uiUpdateTimer = 12000; m_pInstance->SetData(TYPE_EVENT, 3050); break; case 3001: DoScriptText(SAY_STAGE_2_01, me); m_uiUpdateTimer = 12000; m_pInstance->SetData(TYPE_EVENT, 3051); break; case 3060: DoScriptText(SAY_STAGE_2_03, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 3070); break; case 3061: DoScriptText(SAY_STAGE_2_03, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 3071); break; //Summoning crusaders case 3091: me->SummonCreature(NPC_CHAMPIONS_CONTROLLER, ToCCommonLoc[1]); if (Creature* pChampionController = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_CHAMPIONS_CONTROLLER))) pChampionController->AI()->SetData(0, HORDE); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 3092); break; //Summoning crusaders case 3090: me->SummonCreature(NPC_CHAMPIONS_CONTROLLER, ToCCommonLoc[1]); if (Creature* pChampionController = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_CHAMPIONS_CONTROLLER))) pChampionController->AI()->SetData(0, ALLIANCE); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 3092); break; case 3092: if (Creature* pChampionController = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_CHAMPIONS_CONTROLLER))) pChampionController->AI()->SetData(1, NOT_STARTED); m_pInstance->SetData(TYPE_EVENT, 3095); break; //Crusaders battle end case 3100: DoScriptText(SAY_STAGE_2_06, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 0); break; case 4000: DoScriptText(SAY_STAGE_3_01, me); m_uiUpdateTimer = 13000; m_pInstance->SetData(TYPE_EVENT, 4010); break; case 4010: DoScriptText(SAY_STAGE_3_02, me); m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 4015); break; case 4015: me->SummonCreature(NPC_LIGHTBANE, ToCCommonLoc[3].GetPositionX(), ToCCommonLoc[3].GetPositionY(), ToCCommonLoc[3].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME); if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_LIGHTBANE))) { pTemp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[6].GetPositionX(), ToCCommonLoc[6].GetPositionY(), ToCCommonLoc[6].GetPositionZ()); pTemp->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); me->SetReactState(REACT_PASSIVE); } me->SummonCreature(NPC_DARKBANE, ToCCommonLoc[4].GetPositionX(), ToCCommonLoc[4].GetPositionY(), ToCCommonLoc[4].GetPositionZ(), 5, TEMPSUMMON_CORPSE_TIMED_DESPAWN, DESPAWN_TIME); if (Creature* pTemp = Unit::GetCreature((*me), m_pInstance->GetData64(NPC_DARKBANE))) { pTemp->GetMotionMaster()->MovePoint(0, ToCCommonLoc[7].GetPositionX(), ToCCommonLoc[7].GetPositionY(), ToCCommonLoc[7].GetPositionZ()); pTemp->AddUnitMovementFlag(MOVEMENTFLAG_WALKING); me->SetReactState(REACT_PASSIVE); } m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 4016); break; case 4016: m_pInstance->SetData(TYPE_EVENT, 4017); m_pInstance->DoUseDoorOrButton(m_pInstance->GetData64(GO_MAIN_GATE_DOOR)); break; case 4040: m_uiUpdateTimer = 60000; m_pInstance->SetData(TYPE_EVENT, 5000); break; case 5000: DoScriptText(SAY_STAGE_4_01, me); m_uiUpdateTimer = 10000; m_pInstance->SetData(TYPE_EVENT, 5005); break; case 5005: m_uiUpdateTimer = 8000; m_pInstance->SetData(TYPE_EVENT, 5010); me->SummonCreature(NPC_LICH_KING_1, ToCCommonLoc[2].GetPositionX(), ToCCommonLoc[2].GetPositionY(), ToCCommonLoc[2].GetPositionZ(), 5); break; case 5020: DoScriptText(SAY_STAGE_4_03, me); m_uiUpdateTimer = 1000; m_pInstance->SetData(TYPE_EVENT, 0); break; case 6000: me->NearTeleportTo(AnubarakLoc[0].GetPositionX(), AnubarakLoc[0].GetPositionY(), AnubarakLoc[0].GetPositionZ(), 4.0f); m_uiUpdateTimer = 20000; m_pInstance->SetData(TYPE_EVENT, 6005); break; case 6005: DoScriptText(SAY_STAGE_4_06, me); m_uiUpdateTimer = 20000; m_pInstance->SetData(TYPE_EVENT, 6010); break; case 6010: if (IsHeroic()) { DoScriptText(SAY_STAGE_4_07, me); m_uiUpdateTimer = 60000; m_pInstance->SetData(TYPE_ANUBARAK, SPECIAL); m_pInstance->SetData(TYPE_EVENT, 6020); } else m_pInstance->SetData(TYPE_EVENT, 6030); break; case 6020: me->DespawnOrUnsummon(); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 6030); break; } } else m_uiUpdateTimer -= uiDiff; m_pInstance->SetData(TYPE_EVENT_TIMER, m_uiUpdateTimer); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_tirion_tocAI(creature); } }; class npc_garrosh_toc : public CreatureScript { public: npc_garrosh_toc() : CreatureScript("npc_garrosh_toc") { } struct npc_garrosh_tocAI : public ScriptedAI { npc_garrosh_tocAI(Creature* creature) : ScriptedAI(creature) { m_pInstance = (InstanceScript*)me->GetInstanceScript(); } InstanceScript* m_pInstance; uint32 m_uiUpdateTimer; void Reset() {} void AttackStart(Unit* /*who*/) {} void UpdateAI(const uint32 uiDiff) { if (!m_pInstance) return; if (m_pInstance->GetData(TYPE_EVENT_NPC) != NPC_GARROSH) return; m_uiUpdateTimer = m_pInstance->GetData(TYPE_EVENT_TIMER); if (m_uiUpdateTimer <= uiDiff) { switch (m_pInstance->GetData(TYPE_EVENT)) { case 130: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_TALK); DoScriptText(SAY_STAGE_0_03h, me); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 132); break; case 132: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_NONE); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 140); break; case 2010: DoScriptText(SAY_STAGE_1_09, me); m_uiUpdateTimer = 9000; m_pInstance->SetData(TYPE_EVENT, 2020); break; case 3050: DoScriptText(SAY_STAGE_2_02h, me); m_uiUpdateTimer = 15000; m_pInstance->SetData(TYPE_EVENT, 3060); break; case 3070: DoScriptText(SAY_STAGE_2_04h, me); m_uiUpdateTimer = 6000; m_pInstance->SetData(TYPE_EVENT, 3080); break; case 3081: DoScriptText(SAY_STAGE_2_05h, me); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 3091); break; case 4030: DoScriptText(SAY_STAGE_3_03h, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 4040); break; } } else m_uiUpdateTimer -= uiDiff; m_pInstance->SetData(TYPE_EVENT_TIMER, m_uiUpdateTimer); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_garrosh_tocAI(creature); } }; class npc_varian_toc : public CreatureScript { public: npc_varian_toc() : CreatureScript("npc_varian_toc") { } struct npc_varian_tocAI : public ScriptedAI { npc_varian_tocAI(Creature* creature) : ScriptedAI(creature) { m_pInstance = (InstanceScript*)me->GetInstanceScript(); } InstanceScript* m_pInstance; uint32 m_uiUpdateTimer; void Reset() {} void AttackStart(Unit* /*who*/) {} void UpdateAI(const uint32 uiDiff) { if (!m_pInstance) return; if (m_pInstance->GetData(TYPE_EVENT_NPC) != NPC_VARIAN) return; m_uiUpdateTimer = m_pInstance->GetData(TYPE_EVENT_TIMER); if (m_uiUpdateTimer <= uiDiff) { switch (m_pInstance->GetData(TYPE_EVENT)) { case 120: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_TALK); DoScriptText(SAY_STAGE_0_03a, me); m_uiUpdateTimer = 2000; m_pInstance->SetData(TYPE_EVENT, 122); break; case 122: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_NONE); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 130); break; case 2020: DoScriptText(SAY_STAGE_1_10, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 2030); break; case 3051: DoScriptText(SAY_STAGE_2_02a, me); m_uiUpdateTimer = 10000; m_pInstance->SetData(TYPE_EVENT, 3061); break; case 3071: DoScriptText(SAY_STAGE_2_04a, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 3081); break; case 3080: DoScriptText(SAY_STAGE_2_05a, me); m_uiUpdateTimer = 3000; m_pInstance->SetData(TYPE_EVENT, 3090); break; case 4020: DoScriptText(SAY_STAGE_3_03a, me); m_uiUpdateTimer = 5000; m_pInstance->SetData(TYPE_EVENT, 4040); break; } } else m_uiUpdateTimer -= uiDiff; m_pInstance->SetData(TYPE_EVENT_TIMER, m_uiUpdateTimer); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_varian_tocAI(creature); } }; void AddSC_trial_of_the_crusader() { new npc_announcer_toc10(); new boss_lich_king_toc(); new npc_fizzlebang_toc(); new npc_tirion_toc(); new npc_garrosh_toc(); new npc_varian_toc(); }
shuangwei-Ye/WeChat_tweak
Resources/WC_7_0_5_Headers/NewChatRoomMemberItemView.h
<filename>Resources/WC_7_0_5_Headers/NewChatRoomMemberItemView.h // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "MMUIView.h" @class CContact, MMCPLabel, MMMaskHeadImageView, NSString, UIButton, UIColor, UIImageView; @interface NewChatRoomMemberItemView : MMUIView { UIButton *m_viewMemberBtn; UIButton *m_addMemberBtn; UIButton *m_deleteMemberBtn; UIButton *m_actionBtn; MMMaskHeadImageView *m_headImageView; MMCPLabel *m_labelDisplayName; MMCPLabel *m_labelSubDesc; UIImageView *m_trackIcon; UIButton *m_smallDeleteBtn; CContact *m_contact; CContact *m_groupContact; id <NewChatRoomMemberItemViewDelegate> m_delegate; SEL m_updateItemViewForDeleteSel; _Bool m_bDeleteStatus; unsigned int m_uiIndex; UIColor *m_textColor; double m_fLeftMargin; double m_fRightMargin; _Bool m_noDisplayName; NSString *m_cpKeyForNickname; NSString *m_cpKeyForChatRoomDisplayName; _Bool m_isNickNameUnsafe; _Bool m_isChatRoomDisplayNameUnsafe; unsigned int _m_scence; } - (void).cxx_destruct; - (void)OnClickDeleteBtn; - (void)OnClickHeadImage; - (void)OnClickViewBtn; - (void)handleLongPressEx:(id)arg1; - (void)hiddenAllSubViews; - (id)initViewInChatRoomProfile; - (id)initViewInChatRoomProfile:(double)arg1 nameSize:(double)arg2; - (_Bool)isDisplayNameUnsafe; @property(retain, nonatomic) CContact *m_contact; // @synthesize m_contact; @property(nonatomic) __weak id <NewChatRoomMemberItemViewDelegate> m_delegate; // @synthesize m_delegate; @property(readonly) double m_fLeftMargin; // @synthesize m_fLeftMargin; @property(readonly) double m_fRightMargin; // @synthesize m_fRightMargin; @property(retain, nonatomic) CContact *m_groupContact; // @synthesize m_groupContact; @property(nonatomic) unsigned int m_scence; // @synthesize m_scence=_m_scence; @property(nonatomic) unsigned int m_uiIndex; // @synthesize m_uiIndex; - (void)setNoDisplayName:(_Bool)arg1; - (void)setTextColor:(id)arg1 shadowColor:(id)arg2; - (void)showTrackFlag; - (void)updateAddItemViewForDelete; - (void)updateAtIndexEx:(unsigned long long)arg1 withColumn:(unsigned long long)arg2; - (void)updateCPState; - (void)updateContact; - (void)updateContactItemSubview; - (void)updateContactItemViewForDelete; - (void)updateDeleteItemViewForDelete; - (void)updateItemViewForDelete:(_Bool)arg1; - (void)updateOpenim; - (void)updateWithAddMemberBtnAtIndexEx:(unsigned long long)arg1 withColumn:(unsigned long long)arg2; - (void)updateWithContactEx:(id)arg1 atIndex:(unsigned long long)arg2 withColumn:(unsigned long long)arg3; - (void)updateWithDeleteMemberBtnAtIndexEx:(unsigned long long)arg1 withColumn:(unsigned long long)arg2; - (void)updateWithViewMemberBtnAtIndexEx:(unsigned long long)arg1; - (void)updateWithViewMemberBtnAtIndexEx:(unsigned long long)arg1 withColumn:(unsigned long long)arg2; @end
SystemNinja/MyPythonPrograms
DateTime.py
<filename>DateTime.py<gh_stars>0 r""" Lesson 7 Lecture 71 This program demonstrates usage of date and time functions as well as how to work with them. http://strftime.org/ On this page you can look info about formating strftime() function. """ import datetime import time #Create a file which is named after current time and date filename = datetime.datetime.now() def create_file(): with open(filename.strftime("%Y-%m-%d-%H-%M")+".txt","w") as file: file.write("Current time of creation of me!") #writing empty string #create_file() #module - class - function, disregard red linez CurrentTime = datetime.datetime.now() print(CurrentTime) Yesterday = datetime.datetime(2018,1,6,9,8,52) print(Yesterday) after = CurrentTime + datetime.timedelta(days=2)#print current time for next 2 days after1 = CurrentTime + datetime.timedelta(seconds = 1000) #print current time for next 1000 seconds print(after) print(after1) print("\nSeparator\n") #For every 2 seconds in 6 seconds append current time to the list, sleep pauses program for 2 seconds then writes current time lst=[] for i in range(6): lst.append(datetime.datetime.now()) time.sleep(2) for k in lst: print(k) lst.clear()
henh-algosipda/algo-manage-sys
backend/src/main/java/com/henh/testman/common/errors/InvalidMapperException.java
package com.henh.testman.common.errors; public class InvalidMapperException extends RuntimeException { public InvalidMapperException(String message) { super(message); } public InvalidMapperException(String message, Throwable cause) { super(message, cause); } }
sorah/aws-sdk-ruby
lib/aws/glacier/vault_collection.rb
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. module AWS class Glacier class VaultCollection include Core::Collection::WithLimitAndNextToken # @param [Hash] options # @option options [String] :account_id def initialize options = {} @account_id = options[:account_id] || '-' super end # @return [String] attr_reader :account_id # @param [String] name def create name options = {} options[:vault_name] = name options[:account_id] = account_id client.create_vault(options) self[name] end # @param [String] name The name of the vault. # @return [Vault] Returns a vault with the given name. def [] name Vault.new(name, :config => config, :account_id => account_id) end protected def _each_item next_token, limit, options, &block options[:limit] = limit if limit options[:marker] = next_token if next_token options[:account_id] = account_id resp = client.list_vaults(options) resp[:vault_list].each do |v| vault = Vault.new_from(:list_vaults, v, v[:vault_name], :config => config, :account_id => account_id) yield(vault) end resp[:marker] end end end end
stahnma/puppet
lib/puppet/util/rails/reference_serializer.rb
<gh_stars>1-10 module Puppet::Util::ReferenceSerializer def unserialize_value(val) case val when /^--- / YAML.load(val) when "true" true when "false" false else val end end def serialize_value(val) case val when Puppet::Resource YAML.dump(val) when true, false # The database does this for us, but I prefer the # methods be their exact inverses. # Note that this means quoted booleans get returned # as actual booleans, but there doesn't appear to be # a way to fix that while keeping the ability to # search for parameters set to true. val.to_s else val end end end
zeknox/gofalcon
falcon/models/patterndisposition_pattern_disposition.go
<filename>falcon/models/patterndisposition_pattern_disposition.go // Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // PatterndispositionPatternDisposition patterndisposition pattern disposition // // swagger:model patterndisposition.PatternDisposition type PatterndispositionPatternDisposition struct { // bootup safeguard enabled // Required: true BootupSafeguardEnabled *bool `json:"bootup_safeguard_enabled"` // critical process disabled // Required: true CriticalProcessDisabled *bool `json:"critical_process_disabled"` // detect // Required: true Detect *bool `json:"detect"` // fs operation blocked // Required: true FsOperationBlocked *bool `json:"fs_operation_blocked"` // handle operation downgraded // Required: true HandleOperationDowngraded *bool `json:"handle_operation_downgraded"` // inddet mask // Required: true InddetMask *bool `json:"inddet_mask"` // indicator // Required: true Indicator *bool `json:"indicator"` // kill parent // Required: true KillParent *bool `json:"kill_parent"` // kill process // Required: true KillProcess *bool `json:"kill_process"` // kill subprocess // Required: true KillSubprocess *bool `json:"kill_subprocess"` // operation blocked // Required: true OperationBlocked *bool `json:"operation_blocked"` // policy disabled // Required: true PolicyDisabled *bool `json:"policy_disabled"` // process blocked // Required: true ProcessBlocked *bool `json:"process_blocked"` // quarantine file // Required: true QuarantineFile *bool `json:"quarantine_file"` // quarantine machine // Required: true QuarantineMachine *bool `json:"quarantine_machine"` // registry operation blocked // Required: true RegistryOperationBlocked *bool `json:"registry_operation_blocked"` // rooting // Required: true Rooting *bool `json:"rooting"` // sensor only // Required: true SensorOnly *bool `json:"sensor_only"` } // Validate validates this patterndisposition pattern disposition func (m *PatterndispositionPatternDisposition) Validate(formats strfmt.Registry) error { var res []error if err := m.validateBootupSafeguardEnabled(formats); err != nil { res = append(res, err) } if err := m.validateCriticalProcessDisabled(formats); err != nil { res = append(res, err) } if err := m.validateDetect(formats); err != nil { res = append(res, err) } if err := m.validateFsOperationBlocked(formats); err != nil { res = append(res, err) } if err := m.validateHandleOperationDowngraded(formats); err != nil { res = append(res, err) } if err := m.validateInddetMask(formats); err != nil { res = append(res, err) } if err := m.validateIndicator(formats); err != nil { res = append(res, err) } if err := m.validateKillParent(formats); err != nil { res = append(res, err) } if err := m.validateKillProcess(formats); err != nil { res = append(res, err) } if err := m.validateKillSubprocess(formats); err != nil { res = append(res, err) } if err := m.validateOperationBlocked(formats); err != nil { res = append(res, err) } if err := m.validatePolicyDisabled(formats); err != nil { res = append(res, err) } if err := m.validateProcessBlocked(formats); err != nil { res = append(res, err) } if err := m.validateQuarantineFile(formats); err != nil { res = append(res, err) } if err := m.validateQuarantineMachine(formats); err != nil { res = append(res, err) } if err := m.validateRegistryOperationBlocked(formats); err != nil { res = append(res, err) } if err := m.validateRooting(formats); err != nil { res = append(res, err) } if err := m.validateSensorOnly(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *PatterndispositionPatternDisposition) validateBootupSafeguardEnabled(formats strfmt.Registry) error { if err := validate.Required("bootup_safeguard_enabled", "body", m.BootupSafeguardEnabled); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateCriticalProcessDisabled(formats strfmt.Registry) error { if err := validate.Required("critical_process_disabled", "body", m.CriticalProcessDisabled); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateDetect(formats strfmt.Registry) error { if err := validate.Required("detect", "body", m.Detect); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateFsOperationBlocked(formats strfmt.Registry) error { if err := validate.Required("fs_operation_blocked", "body", m.FsOperationBlocked); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateHandleOperationDowngraded(formats strfmt.Registry) error { if err := validate.Required("handle_operation_downgraded", "body", m.HandleOperationDowngraded); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateInddetMask(formats strfmt.Registry) error { if err := validate.Required("inddet_mask", "body", m.InddetMask); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateIndicator(formats strfmt.Registry) error { if err := validate.Required("indicator", "body", m.Indicator); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateKillParent(formats strfmt.Registry) error { if err := validate.Required("kill_parent", "body", m.KillParent); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateKillProcess(formats strfmt.Registry) error { if err := validate.Required("kill_process", "body", m.KillProcess); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateKillSubprocess(formats strfmt.Registry) error { if err := validate.Required("kill_subprocess", "body", m.KillSubprocess); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateOperationBlocked(formats strfmt.Registry) error { if err := validate.Required("operation_blocked", "body", m.OperationBlocked); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validatePolicyDisabled(formats strfmt.Registry) error { if err := validate.Required("policy_disabled", "body", m.PolicyDisabled); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateProcessBlocked(formats strfmt.Registry) error { if err := validate.Required("process_blocked", "body", m.ProcessBlocked); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateQuarantineFile(formats strfmt.Registry) error { if err := validate.Required("quarantine_file", "body", m.QuarantineFile); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateQuarantineMachine(formats strfmt.Registry) error { if err := validate.Required("quarantine_machine", "body", m.QuarantineMachine); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateRegistryOperationBlocked(formats strfmt.Registry) error { if err := validate.Required("registry_operation_blocked", "body", m.RegistryOperationBlocked); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateRooting(formats strfmt.Registry) error { if err := validate.Required("rooting", "body", m.Rooting); err != nil { return err } return nil } func (m *PatterndispositionPatternDisposition) validateSensorOnly(formats strfmt.Registry) error { if err := validate.Required("sensor_only", "body", m.SensorOnly); err != nil { return err } return nil } // ContextValidate validates this patterndisposition pattern disposition based on context it is used func (m *PatterndispositionPatternDisposition) ContextValidate(ctx context.Context, formats strfmt.Registry) error { return nil } // MarshalBinary interface implementation func (m *PatterndispositionPatternDisposition) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *PatterndispositionPatternDisposition) UnmarshalBinary(b []byte) error { var res PatterndispositionPatternDisposition if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
andrejadd/HBR-net-inf
GCGP/GPstuff-4.4/SuiteSparse/CHOLMOD/Include/cholmod_modify.h
/* ========================================================================== */ /* === Include/cholmod_modify.h ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_modify.h. * Copyright (C) 2005-2006, <NAME> and <NAME> * CHOLMOD/Include/cholmod_modify.h is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.cise.ufl.edu/research/sparse * -------------------------------------------------------------------------- */ /* CHOLMOD Modify module. * * Sparse Cholesky modification routines: update / downdate / rowadd / rowdel. * Can also modify a corresponding solution to Lx=b when L is modified. This * module is most useful when applied on a Cholesky factorization computed by * the Cholesky module, but it does not actually require the Cholesky module. * The Core module can create an identity Cholesky factorization (LDL' where * L=D=I) that can then by modified by these routines. * * Primary routines: * ----------------- * * cholmod_updown multiple rank update/downdate * cholmod_rowadd add a row to an LDL' factorization * cholmod_rowdel delete a row from an LDL' factorization * * Secondary routines: * ------------------- * * cholmod_updown_solve update/downdate, and modify solution to Lx=b * cholmod_updown_mark update/downdate, and modify solution to partial Lx=b * cholmod_updown_mask update/downdate for LPDASA * cholmod_rowadd_solve add a row, and update solution to Lx=b * cholmod_rowadd_mark add a row, and update solution to partial Lx=b * cholmod_rowdel_solve delete a row, and downdate Lx=b * cholmod_rowdel_mark delete a row, and downdate solution to partial Lx=b * * Requires the Core module. Not required by any other CHOLMOD module. */ #ifndef CHOLMOD_MODIFY_H #define CHOLMOD_MODIFY_H #include "cholmod_core.h" /* -------------------------------------------------------------------------- */ /* cholmod_updown: multiple rank update/downdate */ /* -------------------------------------------------------------------------- */ /* Compute the new LDL' factorization of LDL'+CC' (an update) or LDL'-CC' * (a downdate). The factor object L need not be an LDL' factorization; it * is converted to one if it isn't. */ int cholmod_updown ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_updown (int, cholmod_sparse *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_updown_solve: update/downdate, and modify solution to Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_updown, except that it also updates/downdates the * solution to Lx=b+DeltaB. x and b must be n-by-1 dense matrices. b is not * need as input to this routine, but a sparse change to b is (DeltaB). Only * entries in DeltaB corresponding to columns modified in L are accessed; the * rest must be zero. */ int cholmod_updown_solve ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_updown_solve (int, cholmod_sparse *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_updown_mark: update/downdate, and modify solution to partial Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_updown_solve, except only part of L is used in * the update/downdate of the solution to Lx=b. This routine is an "expert" * routine. It is meant for use in LPDASA only. See cholmod_updown.c for * a description of colmark. */ int cholmod_updown_mark ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ int *colmark, /* int array of size n. See cholmod_updown.c */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_updown_mark (int, cholmod_sparse *, UF_long *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_updown_mask: update/downdate, for LPDASA */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_updown_mark, except has an additional "mask" * argument. This routine is an "expert" routine. It is meant for use in * LPDASA only. See cholmod_updown.c for a description of mask. */ int cholmod_updown_mask ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ int *colmark, /* int array of size n. See cholmod_updown.c */ int *mask, /* size n */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_updown_mask (int, cholmod_sparse *, UF_long *, UF_long *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowadd: add a row to an LDL' factorization (a rank-2 update) */ /* -------------------------------------------------------------------------- */ /* cholmod_rowadd adds a row to the LDL' factorization. It computes the kth * row and kth column of L, and then updates the submatrix L (k+1:n,k+1:n) * accordingly. The kth row and column of L must originally be equal to the * kth row and column of the identity matrix. The kth row/column of L is * computed as the factorization of the kth row/column of the matrix to * factorize, which is provided as a single n-by-1 sparse matrix R. */ int cholmod_rowadd ( /* ---- input ---- */ size_t k, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowadd (size_t, cholmod_sparse *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowadd_solve: add a row, and update solution to Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_rowadd, and also updates the solution to Lx=b * See cholmod_updown for a description of how Lx=b is updated. There is on * additional parameter: bk specifies the new kth entry of b. */ int cholmod_rowadd_solve ( /* ---- input ---- */ size_t k, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ double bk [2], /* kth entry of the right-hand-side b */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowadd_solve (size_t, cholmod_sparse *, double *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowadd_mark: add a row, and update solution to partial Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_rowadd_solve, except only part of L is used in * the update/downdate of the solution to Lx=b. This routine is an "expert" * routine. It is meant for use in LPDASA only. */ int cholmod_rowadd_mark ( /* ---- input ---- */ size_t k, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ double bk [2], /* kth entry of the right hand side, b */ int *colmark, /* int array of size n. See cholmod_updown.c */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowadd_mark (size_t, cholmod_sparse *, double *, UF_long *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowdel: delete a row from an LDL' factorization (a rank-2 update) */ /* -------------------------------------------------------------------------- */ /* Sets the kth row and column of L to be the kth row and column of the identity * matrix, and updates L(k+1:n,k+1:n) accordingly. To reduce the running time, * the caller can optionally provide the nonzero pattern (or an upper bound) of * kth row of L, as the sparse n-by-1 vector R. Provide R as NULL if you want * CHOLMOD to determine this itself, which is easier for the caller, but takes * a little more time. */ int cholmod_rowdel ( /* ---- input ---- */ size_t k, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowdel (size_t, cholmod_sparse *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowdel_solve: delete a row, and downdate Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_rowdel, but also downdates the solution to Lx=b. * When row/column k of A is "deleted" from the system A*y=b, this can induce * a change to x, in addition to changes arising when L and b are modified. * If this is the case, the kth entry of y is required as input (yk) */ int cholmod_rowdel_solve ( /* ---- input ---- */ size_t k, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ double yk [2], /* kth entry in the solution to A*y=b */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowdel_solve (size_t, cholmod_sparse *, double *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowdel_mark: delete a row, and downdate solution to partial Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_rowdel_solve, except only part of L is used in * the update/downdate of the solution to Lx=b. This routine is an "expert" * routine. It is meant for use in LPDASA only. */ int cholmod_rowdel_mark ( /* ---- input ---- */ size_t k, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ double yk [2], /* kth entry in the solution to A*y=b */ int *colmark, /* int array of size n. See cholmod_updown.c */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowdel_mark (size_t, cholmod_sparse *, double *, UF_long *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; #endif
VD-15/ValkyrieEngineCommon
docs/html/search/all_b.js
var searchData= [ ['quaternion_60',['Quaternion',['../classvlk_1_1Quaternion.html',1,'vlk']]], ['quaternion_2ehpp_61',['Quaternion.hpp',['../Quaternion_8hpp.html',1,'']]] ];
jrbeverly/JCompiler
src/test/resources/assignment_testcases/a1/J1_1_Cast_MultipleReferenceArray.java
//PARSER_WEEDER public class J1_1_Cast_MultipleReferenceArray { public J1_1_Cast_MultipleReferenceArray() {} public static int test() { Object a = null; a = (Object)(int[])(Object)(Integer[])a; return 123; } }
lanshunfang/alg-hw
src/org/neu/alg/hw/hw6/Cstring.java
package org.neu.alg.hw.hw6; import org.neu.alg.hw.*; /** * File Name: Cstring.java * Implements C String * * @author <NAME> * @year 2019 */ /* * To compile you require: CharArray.java Cstring */ class Cstring { private CharArray d; //Infinite array of char public int charArrLen = 0; static IntUtil u = new IntUtil(); Cstring(String stringAsNumber) { this.setCharArray(stringAsNumber); } Cstring(char charAsNumber) { this.setCharArray(Character.toString(charAsNumber)); } Cstring(int number) { this.setCharArray("" + number); } Cstring() { this.setCharArray(""); } Cstring(CharArray charArray, int lenStr) { this.d = charArray; this.setCharArrLen(lenStr); } public CharArray getCharArray() { return this.d; } public void set(int pos, char theChar) { this.getCharArray().set(pos, theChar); } public void set(int pos, int intAsChar) { if (this.charArrLen <= pos) { this.charArrLen = pos + 1; } this.set(pos, Character.forDigit(intAsChar, 10)); } public char get(int pos) { return this.getCharArray().get(pos); } public int getInt(int pos) { return Character.getNumericValue(this.get(pos)); } public void pLn(String prefix) { System.out.print(prefix); CustomIterator iterator = this.getIterator(false); while (iterator.hasNext()) { System.out.print(iterator.next()); } System.out.print("\n"); } public boolean isEqual(Cstring cstring) { if (cstring == null || cstring.charArrLen != this.charArrLen) { return false; } CustomIterator iteratorLeft = this.getIterator(false); CustomIterator iteratorRight = cstring.getIterator(false); while (iteratorLeft.hasNext() || iteratorRight.hasNext()) { if (!(iteratorLeft.hasNext() && iteratorRight.hasNext() && iteratorLeft.next() == iteratorRight.next())) { return false; } } return true; } public Cstring clone() { return this.add(new Cstring()); } public void reverse() { for (int i = 0, j = this.charArrLen - 1; i < j; i++, j--) { this.d.swap(i, j); } } private void setCharArray(String stringAsNumber) { this.d = new CharArray(); int i = 0; int lenStr = stringAsNumber.length(); for (; i < lenStr; i++) { this.d.set(i, stringAsNumber.charAt(i)); } this.setCharArrLen(lenStr); } private void setCharArrLen(int lenStr) { this.charArrLen = lenStr; } /** * immutable add, return a new Cstring * * @param cstring */ public Cstring add(Cstring cstring) { CustomIterator iteratorLeft = this.getIterator(false); CustomIterator iteratorRight = cstring.getIterator(false); CharArray tmpCharArray = new CharArray(); int i = 0; while (iteratorLeft.hasNext()) { tmpCharArray.set(i++, iteratorLeft.next()); } while (iteratorRight.hasNext()) { tmpCharArray.set(i++, iteratorRight.next()); } return new Cstring(tmpCharArray, i); } public Cstring add(String strToAdd) { return this.add(new Cstring(strToAdd)); } /** * mutable add, return the raw Cstring * * @param cstring */ public Cstring append(Cstring cstring) { CustomIterator iteratorRight = cstring.getIterator(false); CharArray tmpCharArray = this.d; int len = this.charArrLen; while (iteratorRight.hasNext()) { tmpCharArray.set(len++, iteratorRight.next()); } this.setCharArrLen(len); return this; } public Cstring append(String strToAppend) { return this.append(new Cstring(strToAppend)); } public Cstring append(int number) { return this.append(new Cstring(number)); } // public void push(char charAsNum) { // this.d.set(this.nextPushPos++, charAsNum); // this.charArrLen++; // } public CustomIterator getIterator(boolean rightToLeft) { return new CustomIterator(this.d, this.charArrLen, rightToLeft); } private static void testBench() { Cstring.testBasic(); Cstring.testAdd(); Cstring.testEqual(); } private static void testAdd() { Cstring a = new Cstring("UCSC"); Cstring b = new Cstring("Extension"); Cstring c = a.add(b); a.pLn("a = "); b.pLn("b = "); c.pLn("c = "); Cstring d = c.add("USA"); d.pLn("d = "); a.append(b); a.pLn("a+b = "); a.append("World"); a.pLn("a+b+World = "); } private static void testEqual() { Cstring a = new Cstring("123456789012345678901234567890123456789012345678901234567890"); a.pLn("a = "); Cstring b = new Cstring("123456789012345678901234567890123456789012345678901234567890"); b.pLn("b = "); u.myassert(a.isEqual(b)); Cstring c = new Cstring("12345678901234567890123456789012345678901234567890123456789"); c.pLn("c = "); u.myassert(a.isEqual(c) == false); } private static void testBasic() { Cstring a = new Cstring('b'); a.pLn("a = "); Cstring b = new Cstring('7'); b.pLn("b = "); Cstring c = new Cstring("123456789012345678901234567890123456789012345678901234567890"); c.pLn("c = "); Cstring d = c.clone(); d.pLn("d = "); Cstring e = new Cstring("A quick brown fox junped over a lazy dog"); e.pLn("e = "); Cstring f = new Cstring("Gateman sees name garageman sees nametag"); f.pLn("f = "); f.reverse(); f.pLn("f' = "); } public static void main(String[] args) { String version = System.getProperty("java.version"); System.out.println("Java version used for this program is " + version); System.out.println("Cstring.java starts"); testBench(); System.out.println("Cstring.java ends"); } } class CustomIterator { private CharArray charArray; private int charArrayNextPos = 0; // private int charArrLen; private boolean rightToLeft; public CustomIterator(CharArray charArray, int charArrLen, boolean rightToLeft) { // initialize cursor this.charArray = charArray; // this.charArrLen = charArrLen; this.rightToLeft = rightToLeft; if (rightToLeft) { this.charArrayNextPos = charArrLen - 1; } } // Checks if the next element exists public boolean hasNext() { return this.charArrayNextPos >= 0 && charArray.get(this.charArrayNextPos) != '\0'; } // moves the cursor/iterator to next element public char next() { char nextChar = charArray.get(this.charArrayNextPos); if (this.rightToLeft) { this.charArrayNextPos--; } else { this.charArrayNextPos++; } return nextChar; } }
albertz/music-player
mac/pyobjc-framework-Quartz/PyObjCTest/test_IKFilterBrowserPanel.py
from PyObjCTools.TestSupport import * from Quartz import * try: unicode except NameError: unicode = str class TestIKFilterBrowserPanel (TestCase): @min_os_level('10.5') def testMethods(self): self.assertArgIsSEL(IKFilterBrowserPanel.beginWithOptions_modelessDelegate_didEndSelector_contextInfo_, 2, b"v@:@" + objc._C_NSInteger + b"^v") self.assertArgIsSEL(IKFilterBrowserPanel.beginSheetWithOptions_modalForWindow_modalDelegate_didEndSelector_contextInfo_, 3, b"v@:@" + objc._C_NSInteger + b"^v") @min_os_level('10.5') def testConstants(self): self.assertIsInstance(IKFilterBrowserFilterSelectedNotification, unicode) self.assertIsInstance(IKFilterBrowserFilterDoubleClickNotification, unicode) self.assertIsInstance(IKFilterBrowserWillPreviewFilterNotification, unicode) self.assertIsInstance(IKFilterBrowserShowCategories, unicode) self.assertIsInstance(IKFilterBrowserShowPreview, unicode) self.assertIsInstance(IKFilterBrowserExcludeCategories, unicode) self.assertIsInstance(IKFilterBrowserExcludeFilters, unicode) self.assertIsInstance(IKFilterBrowserDefaultInputImage, unicode) if __name__ == "__main__": main()
devcreation1222/im5
modules/rrhhs/tests/client/rrhhs.client.controller.tests.js
'use strict'; (function() { // Rrhhs Controller Spec describe('Rrhhs Controller Tests', function() { // Initialize global variables var RrhhsController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Rrhhs controller. RrhhsController = $controller('RrhhsController', { $scope: scope }); })); it('$scope.find() should create an array with at least one Rrhh object fetched from XHR', inject(function(Rrhhs) { // Create sample Rrhh using the Rrhhs service var sampleRrhh = new Rrhhs({ name: '<NAME>' }); // Create a sample Rrhhs array that includes the new Rrhh var sampleRrhhs = [sampleRrhh]; // Set GET response $httpBackend.expectGET('api/rrhhs').respond(sampleRrhhs); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.rrhhs).toEqualData(sampleRrhhs); })); it('$scope.findOne() should create an array with one Rrhh object fetched from XHR using a rrhhId URL parameter', inject(function(Rrhhs) { // Define a sample Rrhh object var sampleRrhh = new Rrhhs({ name: 'New Rrhh' }); // Set the URL parameter $stateParams.rrhhId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET(/api\/rrhhs\/([0-9a-fA-F]{24})$/).respond(sampleRrhh); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.rrhh).toEqualData(sampleRrhh); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Rrhhs) { // Create a sample Rrhh object var sampleRrhhPostData = new Rrhhs({ name: 'New Rrhh' }); // Create a sample Rrhh response var sampleRrhhResponse = new Rrhhs({ _id: '525cf20451979dea2c000001', name: 'New Rrhh' }); // Fixture mock form input values scope.name = 'New Rrhh'; // Set POST response $httpBackend.expectPOST('api/rrhhs', sampleRrhhPostData).respond(sampleRrhhResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the Rrhh was created expect($location.path()).toBe('/rrhhs/' + sampleRrhhResponse._id); })); it('$scope.update() should update a valid Rrhh', inject(function(Rrhhs) { // Define a sample Rrhh put data var sampleRrhhPutData = new Rrhhs({ _id: '525cf20451979dea2c000001', name: '<NAME>' }); // Mock Rrhh in scope scope.rrhh = sampleRrhhPutData; // Set PUT response $httpBackend.expectPUT(/api\/rrhhs\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/rrhhs/' + sampleRrhhPutData._id); })); it('$scope.remove() should send a DELETE request with a valid rrhhId and remove the Rrhh from the scope', inject(function(Rrhhs) { // Create new Rrhh object var sampleRrhh = new Rrhhs({ _id: '525a8422f6d0f87f0e407a33' }); // Create new Rrhhs array and include the Rrhh scope.rrhhs = [sampleRrhh]; // Set expected DELETE response $httpBackend.expectDELETE(/api\/rrhhs\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(sampleRrhh); $httpBackend.flush(); // Test array after successful delete expect(scope.rrhhs.length).toBe(0); })); }); }());
houlz0507/XRT-1
tests/xrt/03_loopback/main.cpp
/** * Copyright (C) 2016-2017 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://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 2017 Xilinx, Inc. All rights reserved. #include <getopt.h> #include <iostream> #include <stdexcept> #include <string> #include <cstring> #include <sys/mman.h> // driver includes #include "ert.h" // host_src includes #include "xclhal2.h" #include "xclbin.h" // lowlevel common include #include "utils.h" #if defined(DSA64) #include "xloopback_hw_64.h" #else #include "xloopback_hw.h" #endif #include <fstream> static const int DATA_SIZE = 1024; /** * Trivial loopback example which runs OpenCL loopback kernel. Does not use OpenCL * runtime but directly exercises the XRT driver API. */ const static struct option long_options[] = { {"bitstream", required_argument, 0, 'k'}, {"hal_logfile", required_argument, 0, 'l'}, {"alignment", required_argument, 0, 'a'}, {"cu_index", required_argument, 0, 'c'}, {"device", required_argument, 0, 'd'}, {"verbose", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, // enable embedded runtime {"ert", no_argument, 0, '1'}, {0, 0, 0, 0} }; static void printHelp() { std::cout << "usage: %s [options] -k <bitstream>\n\n"; std::cout << " -k <bitstream>\n"; std::cout << " -l <hal_logfile>\n"; std::cout << " -a <alignment>\n"; std::cout << " -d <device_index>\n"; std::cout << " -c <cu_index>\n"; std::cout << " -v\n"; std::cout << " -h\n\n"; std::cout << ""; std::cout << " [--ert] enable embedded runtime (default: false)\n"; std::cout << ""; std::cout << "* If HAL driver is not specified, application will try to find the HAL driver\n"; std::cout << " using XILINX_OPENCL and XCL_PLATFORM environment variables\n"; std::cout << "* Bitstream is required\n"; std::cout << "* HAL logfile is optional but useful for capturing messages from HAL driver\n"; } int main(int argc, char** argv) { std::string sharedLibrary; std::string bitstreamFile; std::string halLogfile; size_t alignment = 128; int option_index = 0; unsigned index = 0; int cu_index = 0; bool verbose = false; bool ert = false; int c; while ((c = getopt_long(argc, argv, "s:k:l:a:c:d:vh", long_options, &option_index)) != -1) { switch (c) { case 0: if (long_options[option_index].flag != 0) break; case 1: ert = true; break; case 'k': bitstreamFile = optarg; break; case 'l': halLogfile = optarg; break; case 'a': alignment = std::atoi(optarg); break; case 'd': index = std::atoi(optarg); break; case 'c': cu_index = std::atoi(optarg); break; case 'h': printHelp(); return 0; case 'v': verbose = true; break; default: printHelp(); return -1; } } (void)verbose; if (bitstreamFile.size() == 0) { std::cout << "FAILED TEST\n"; std::cout << "No bitstream specified\n"; return -1; } if (halLogfile.size()) { std::cout << "Using " << halLogfile << " as HAL driver logfile\n"; } std::cout << "HAL driver = " << sharedLibrary << "\n"; std::cout << "Host buffer alignment = " << alignment << " bytes\n"; std::cout << "Compiled kernel = " << bitstreamFile << "\n" << std::endl; try { xclDeviceHandle handle; uint64_t cu_base_addr = 0; int first_mem = -1; uuid_t xclbinId; if (initXRT(bitstreamFile.c_str(), index, halLogfile.c_str(), handle, cu_index, cu_base_addr, first_mem, xclbinId)) return 1; if (first_mem < 0) return 1; if (xclOpenContext(handle, xclbinId, cu_index, true)) throw std::runtime_error("Cannot create context"); unsigned boHandle2 = xclAllocBO(handle, DATA_SIZE, XCL_BO_DEVICE_RAM, first_mem); char* bo2 = (char*)xclMapBO(handle, boHandle2, true); memset(bo2, 0, DATA_SIZE); std::string testVector = "hello\nthis is Xilinx OpenCL memory read write test\n:-)\n"; std::strcpy(bo2, testVector.c_str()); if(xclSyncBO(handle, boHandle2, XCL_BO_SYNC_BO_TO_DEVICE , DATA_SIZE,0)) return 1; unsigned boHandle1 = xclAllocBO(handle, DATA_SIZE, XCL_BO_DEVICE_RAM, first_mem); xclBOProperties p; uint64_t bo2devAddr = !xclGetBOProperties(handle, boHandle2, &p) ? p.paddr : -1; uint64_t bo1devAddr = !xclGetBOProperties(handle, boHandle1, &p) ? p.paddr : -1; if( (bo2devAddr == (uint64_t)(-1)) || (bo1devAddr == (uint64_t)(-1))) return 1; //Allocate the exec_bo unsigned execHandle = xclAllocBO(handle, DATA_SIZE, xclBOKind(0), (1<<31)); void* execData = xclMapBO(handle, execHandle, true); //construct the exec buffer cmd to start the kernel. { auto ecmd = reinterpret_cast<ert_start_kernel_cmd*>(execData); auto rsz = (XLOOPBACK_CONTROL_ADDR_LENGTH_R_DATA/4+1) + 1; // regmap array size std::memset(ecmd,0,(sizeof *ecmd) + rsz*4); ecmd->state = ERT_CMD_STATE_NEW; ecmd->opcode = ERT_START_CU; ecmd->count = 1 + rsz; ecmd->cu_mask = 0x1; ecmd->data[XLOOPBACK_CONTROL_ADDR_AP_CTRL] = 0x0; // ap_start #if defined(DSA64) ecmd->data[XLOOPBACK_CONTROL_ADDR_S1_DATA/4] = bo1devAddr & 0xFFFFFFFF; // s1 ecmd->data[XLOOPBACK_CONTROL_ADDR_S1_DATA/4 + 1] = (bo1devAddr >> 32) & 0xFFFFFFFF; // s1 ecmd->data[XLOOPBACK_CONTROL_ADDR_S2_DATA/4] = bo2devAddr & 0xFFFFFFFF; // s2 ecmd->data[XLOOPBACK_CONTROL_ADDR_S2_DATA/4 + 1] = (bo2devAddr >> 32) & 0xFFFFFFFF; // s2 ecmd->data[XLOOPBACK_CONTROL_ADDR_LENGTH_R_DATA/4] = DATA_SIZE; // length #else ecmd->data[XLOOPBACK_CONTROL_ADDR_S1_DATA/4] = bo1devAddr; // s1 ecmd->data[XLOOPBACK_CONTROL_ADDR_S2_DATA/4] = bo2devAddr; // s2 ecmd->data[XLOOPBACK_CONTROL_ADDR_LENGTH_R_DATA/4] = DATA_SIZE; // length #endif } std::cout << "Starting kernel..." << std::endl; //Send the "start kernel" command. if(xclExecBuf(handle, execHandle)) { std::cout << "Unable to issue xclExecBuf : start_kernel" << std::endl; std::cout << "FAILED TEST\n"; std::cout << "Write failed\n"; return 1; } //Wait on the command finish while (xclExecWait(handle,1000) == 0) { std::cout << "reentering wait...\n"; }; //Get the output; if(xclSyncBO(handle, boHandle1, XCL_BO_SYNC_BO_FROM_DEVICE , DATA_SIZE, 0)) return 1; char* bo1 = (char*)xclMapBO(handle, boHandle1, false); if (std::memcmp(bo2, bo1, DATA_SIZE)) { std::cout << "FAILED TEST\n"; std::cout << "Value read back does not match value written\n"; return 1; } //Clean up stuff munmap(bo1, DATA_SIZE); munmap(bo2, DATA_SIZE); munmap(execData, DATA_SIZE); xclFreeBO(handle,boHandle1); xclFreeBO(handle,boHandle2); xclFreeBO(handle,execHandle); xclCloseContext(handle, xclbinId, cu_index); } catch (std::exception const& e) { std::cout << "Exception: " << e.what() << "\n"; std::cout << "FAILED TEST\n"; return 1; } std::cout << "PASSED TEST\n"; return 0; }
kubeform/provider-aws-api
vendor/kubeform.dev/apimachinery/api/v1alpha1/termination_policy.go
/* Copyright AppsCode Inc. and Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 // +kubebuilder:validation:Enum=Delete;DoNotTerminate type TerminationPolicy string const ( TerminationPolicyDelete TerminationPolicy = "Delete" TerminationPolicyDoNotTerminate TerminationPolicy = "DoNotTerminate" )
k-kamalyesh/js-basex
module/operations/operationsOnArray/maximum.js
<gh_stars>0 const number = require('../../type/'); const { eBase } = require('../../type/base'); const ops = require('../../operations'); module.exports = { unsignedMaximum: (numbers) => { // returns maximum number's index from the array // does not considers sign of numbers let maxIndex = 0; let maxValue; if (numbers.length > 1) { maxValue = numbers[maxIndex]; for (let index = 1; index < numbers.length; index++) { const number = numbers[index]; let max = ops.unsignedMax(maxValue, number) if (ops.unsignedEquate(max, number)) { maxIndex = index; maxValue = numbers[maxIndex]; } } } return maxIndex; }, signedMaximum: (numbers) => { // returns maximum number's index from the array // considers signs in comparison let maxIndex = 0; let tempMax = 0; let maxValue; const OP_LESS_THAN = 1; const OP_GREATER_THAN = 1; let operation; if (numbers.length > 1) { tempMax = maxIndex; maxValue = numbers[maxIndex]; for (let index = 1; index < numbers.length; index++) { const number = numbers[index]; // check 0 // compare signs if (maxValue._flags._sign == number._flags._sign) { // if similar sign && sign is RESET (+ve), smaller value is maximum operation = OP_LESS_THAN } else { // if similar sign && sign is SET (-ve), greater value is maximum operation = OP_GREATER_THAN } if (operation == OP_LESS_THAN) { // check 1 // compare left lengths if (maxValue._leftLength > number._leftLength) { maxIndex = index; continue; } // check 2 // left lengths are equal else if (maxValue._leftLength == number._leftLength) { // check 2.3 // compare digits from left most to right most place let maxFound = false; let length = maxValue._leftLength; for (let index2 = length - 1; index2 >= 0; index2--) { const e1 = maxValue._getFaceValueAt(index2) ? maxValue._getFaceValueAt(index2) : eBase.ZERO; const e2 = number._getFaceValueAt(index2) ? number._getFaceValueAt(index2) : eBase.ZERO; if (e1.value < e2.value) { maxFound = true; break; } else if (e1.value > e2.value) { maxFound = true; maxIndex = index; break; } } if (maxFound == true) { continue; } if (maxIndex == tempMax) { // check 2.3.1 // now we have to check right parts // check 2.3.1.1 // compare right parts from left most to right most place let length = maxValue._rightLength < number._rightLength ? number._rightLength : maxValue._rightLength; for (let index2 = 0; index2 < length; index2++) { const e1 = maxValue._getFaceValueAt(-index2 - 1) ? maxValue._getFaceValueAt(-index2 - 1) : eBase.ZERO; const e2 = number._getFaceValueAt(-index2 - 1) ? number._getFaceValueAt(-index2 - 1) : eBase.ZERO; if (e1.value < e2.value) { maxIndex = index; break; } else if (e1.value > e2.value) { break; } } } } // check 3 else { // else nothing, // we already have out maxIndex. } } else if (operation == OP_GREATER_THAN) { // check 1 // compare left lengths if (maxValue._leftLength > number._leftLength) { maxIndex = index; continue; } // check 2 // left lengths are equal else if (maxValue._leftLength == number._leftLength) { // check 2.3 // compare digits from left most to right most place let maxFound = false; let length = maxValue._leftLength; for (let index2 = length - 1; index2 >= 0; index2--) { const e1 = maxValue._getFaceValueAt(index2) ? maxValue._getFaceValueAt(index2) : eBase.ZERO; const e2 = number._getFaceValueAt(index2) ? number._getFaceValueAt(index2) : eBase.ZERO; if (e1.value < e2.value) { maxFound = true; break; } else if (e1.value > e2.value) { maxFound = true; maxIndex = index; break; } } if (maxFound == true) { continue; } if (maxIndex == tempMax) { // check 2.3.1 // now we have to check right parts // check 2.3.1.1 // compare right parts from left most to right most place let length = maxValue._rightLength > number._rightLength ? number._rightLength : maxValue._rightLength; for (let index2 = 0; index2 < length; index2++) { const e1 = maxValue._getFaceValueAt(-index2 - 1) ? maxValue._getFaceValueAt(-index2 - 1) : eBase.ZERO; const e2 = number._getFaceValueAt(-index2 - 1) ? number._getFaceValueAt(-index2 - 1) : eBase.ZERO; if (e1.value > e2.value) { maxIndex = index; break; } else if (e1.value > e2.value) { break; } } } } // check 3 else { // else nothing, // we already have out maxIndex. } } } } return maxIndex; } }
f0xd3v/serposcope
scraper/src/test/java/com/serphacker/serposcope/scraper/captcha/solver/DecaptcherSolverIT.java
<gh_stars>100-1000 /* * Serposcope - SEO rank checker https://serposcope.serphacker.com/ * * Copyright (c) 2016 SERP Hacker * @author <NAME> <<EMAIL>> * @license https://opensource.org/licenses/MIT MIT License */ package com.serphacker.serposcope.scraper.captcha.solver; import org.junit.Before; import static org.junit.Assert.assertNotNull; /** * * @author admin */ public class DecaptcherSolverIT extends GenericSolverIT { public DecaptcherSolverIT() { } String login; String password; String login0balance; String password0balance; @Before public void readCredentials() throws Exception { assertNotNull(login = props.getProperty("decaptcher.login")); assertNotNull(password = props.getProperty("<PASSWORD>")); assertNotNull(login0balance = props.getProperty("decaptcher.login0balance")); assertNotNull(password0balance = props.getProperty("decaptcher.password0balance")); } @Override protected CaptchaSolver getSolver() { return new DecaptcherSolver(login, password); } @Override protected CaptchaSolver getSolverNoBalance() { return new DecaptcherSolver(login0balance, password0balance); } @Override protected CaptchaSolver getSolverInvalidCredentials() { return new DecaptcherSolver("wrong-login", "wrong-password"); } @Override public void testSolverRecaptcha() throws Exception { // not supported } }
sungmen/Acmicpc_Solve
Acmicpc/C++/BOJ4358.cpp
<filename>Acmicpc/C++/BOJ4358.cpp<gh_stars>1-10 #include <bits/stdc++.h> using namespace std; int main() { // freopen("input.txt", "r", stdin); ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); string str; int cnt = 0; map <string, double> m; while(getline(cin, str)) { cnt++; if (m.find(str)==m.end()) { m[str] = 1; } else { m.find(str)->second++; } } cout << fixed; cout.precision(4); for (map<string, double>::iterator it=m.begin(); it != m.end(); it++) { cout << it->first << ' ' << (round(it->second/cnt*100*10000)/10000) << '\n'; } return 0; }
cantbesure/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/tools/offlineEditsViewer/BinaryEditsVisitor.java
<reponame>cantbesure/hadoop-20<gh_stars>100-1000 /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.tools.offlineEditsViewer; import java.io.FileOutputStream; import java.io.DataOutputStream; import java.io.IOException; /** * BinaryEditsVisitor implements a binary EditsVisitor */ public class BinaryEditsVisitor extends EditsVisitor { final private DataOutputStream out; /** * Create a processor that writes to a given file and * reads using a given Tokenizer * * @param filename Name of file to write output to * @param tokenizer Input tokenizer */ public BinaryEditsVisitor(String filename, Tokenizer tokenizer) throws IOException { this(filename, tokenizer, false); } /** * Create a processor that writes to a given file and reads using * a given Tokenizer, may also print to screen * * @param filename Name of file to write output to * @param tokenizer Input tokenizer * @param printToScreen Mirror output to screen? (ignored for binary) */ public BinaryEditsVisitor(String filename, Tokenizer tokenizer, boolean printToScreen) throws IOException { super(tokenizer); out = new DataOutputStream(new FileOutputStream(filename)); } /** * Start the visitor (initialization) */ @Override void start() throws IOException { // nothing to do for binary format } /** * Finish the visitor */ @Override void finish() throws IOException { close(); } /** * Finish the visitor and indicate an error */ @Override void finishAbnormally() throws IOException { System.err.println("Error processing EditLog file. Exiting."); close(); } /** * Close output stream and prevent further writing */ private void close() throws IOException { out.close(); } /** * Visit a enclosing element (element that has other elements in it) */ @Override void visitEnclosingElement(Tokenizer.Token value) throws IOException { // nothing to do for binary format } /** * End of eclosing element */ @Override void leaveEnclosingElement() throws IOException { // nothing to do for binary format } /** * Visit a Token */ @Override Tokenizer.Token visit(Tokenizer.Token value) throws IOException { value.toBinary(out); return value; } }
JhonatanSK/pretty-style
src/br/com/sprintters/prettystyle/model/ProductCategory.java
<filename>src/br/com/sprintters/prettystyle/model/ProductCategory.java package br.com.sprintters.prettystyle.model; import java.sql.Timestamp; public class ProductCategory { private int idProduct; private Product product; private int idCategory; private Category category; private Timestamp createdAt; public ProductCategory() { } public ProductCategory(int idProduct, int idCategory) { this.idProduct = idProduct; this.idCategory = idCategory; } public ProductCategory(int idProduct, int idCategory, Timestamp createdAt) { this.idProduct = idProduct; this.idCategory = idCategory; this.createdAt = createdAt; } public int getIdProduct() { return idProduct; } public void setIdProduct(int idProduct) { this.idProduct = idProduct; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public int getIdCategory() { return idCategory; } public void setIdCategory(int idCategory) { this.idCategory = idCategory; } public Timestamp getCreatedAt() { return createdAt; } public void setCreatedAt(Timestamp createdAt) { this.createdAt = createdAt; } @Override public String toString() { return "ProductCategory [idProduct=" + idProduct + ", idCategory=" + idCategory + ", createdAt=" + createdAt + "]"; } }
TopRoupi/fec
app/channels/application_channel.rb
<gh_stars>0 # frozen_string_literal: true class ApplicationChannel < ApplicationCable::Channel def subscribed stream_from "application-stream" end end
mohdab98/cmps252_hw4.2
src/cmps252/HW4_2/UnitTesting/record_2677.java
<reponame>mohdab98/cmps252_hw4.2<filename>src/cmps252/HW4_2/UnitTesting/record_2677.java<gh_stars>1-10 package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("41") class Record_2677 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 2677: FirstName is Marylou") void FirstNameOfRecord2677() { assertEquals("Marylou", customers.get(2676).getFirstName()); } @Test @DisplayName("Record 2677: LastName is Showes") void LastNameOfRecord2677() { assertEquals("Showes", customers.get(2676).getLastName()); } @Test @DisplayName("Record 2677: Company is Gulf Stream Paints") void CompanyOfRecord2677() { assertEquals("Gulf Stream Paints", customers.get(2676).getCompany()); } @Test @DisplayName("Record 2677: Address is 159 Main St") void AddressOfRecord2677() { assertEquals("159 Main St", customers.get(2676).getAddress()); } @Test @DisplayName("Record 2677: City is Staten Island") void CityOfRecord2677() { assertEquals("Staten Island", customers.get(2676).getCity()); } @Test @DisplayName("Record 2677: County is Richmond") void CountyOfRecord2677() { assertEquals("Richmond", customers.get(2676).getCounty()); } @Test @DisplayName("Record 2677: State is NY") void StateOfRecord2677() { assertEquals("NY", customers.get(2676).getState()); } @Test @DisplayName("Record 2677: ZIP is 10307") void ZIPOfRecord2677() { assertEquals("10307", customers.get(2676).getZIP()); } @Test @DisplayName("Record 2677: Phone is 718-317-5503") void PhoneOfRecord2677() { assertEquals("718-317-5503", customers.get(2676).getPhone()); } @Test @DisplayName("Record 2677: Fax is 718-317-8035") void FaxOfRecord2677() { assertEquals("718-317-8035", customers.get(2676).getFax()); } @Test @DisplayName("Record 2677: Email is <EMAIL>") void EmailOfRecord2677() { assertEquals("<EMAIL>", customers.get(2676).getEmail()); } @Test @DisplayName("Record 2677: Web is http://www.maryloushowes.com") void WebOfRecord2677() { assertEquals("http://www.maryloushowes.com", customers.get(2676).getWeb()); } }
apr-suite/APR
docs/static/non-versioned/js/jsdoc.js
<gh_stars>0 (function () { 'use strict'; var el = function (selector, container) { return (container || document).querySelectorAll(selector); }; /** * Versions below 1.1.0 generated documentation * in /{browser,server}/index.html. * * Starting from version 1.1.0, documentation is generated * under /browser/{core,just}/index.html and server/index.html. */ var isVersionBelow1Dot2 = function (version) { return /^1\.[01]\./.test(version) && !/\-dev/.test(version); }; var versions = el('#versions')[0]; var bundles = el('#bundles')[0]; var location = window.location; var urlParts = location.pathname.match(/\/v([^.]+\.[^.]\.[^\/]+)\/(browser(?:\/(core|just))?|server)\//) || []; var activeVersion = urlParts[1]; // Normalize browser/just -> browser var activeBundle = (urlParts[2] || '').replace('/just', ''); versions.addEventListener('change', function (e) { var version = this.value; var pathname = location.pathname; var newUrl = (isVersionBelow1Dot2(version) // Redirect to the /browser build. ? pathname.replace(/(browser\/)(?:just|core)\//, '$1') // Redirect to the /browser/just/ build (the full version). : pathname.replace(/(browser)\/((?:just|core)\/)?/, function ($0, $1, $2) { return $1 + '/' + ($2 || 'just/'); }) ).replace(/v[^\/]+/, 'v' + version); location.href = newUrl; }); if (bundles) { bundles.addEventListener('change', function (e) { var bundle = this.value; var pathname = location.pathname; var newUrl = pathname // This will redirect browser/ -> server/, browser/core -> server/core, or viceversa. .replace(/(?:browser\/(?:(?:just|core)\/)?|server\/)/, bundle + '/') // This will change (invalid) server/just/ & server/core/ -> server/ .replace(/(server)\/(?:just|core)\//, '$1/'); if (!isVersionBelow1Dot2(activeVersion)) { // This will normalize urls -> browser/just | browser/core newUrl = newUrl.replace(/(browser)\/((?:just|core)\/)?/, function ($0, $1, $2) { return $1 + '/' + ($2 || 'just/'); }); } location.href = newUrl; }); } [versions, bundles].filter(function (v) { return v; }).forEach(function (select) { var id = select.id; var options = el('option', select); var selected = (el('option[value="' + (id === 'versions' ? activeVersion : activeBundle ) + '"]') || [])[0]; select.value = (selected ? selected.value : '' ); }); })();
ldr7/schema-registry-1
contract/src/main/java/io/pravega/schemaregistry/contract/generated/rest/model/ListGroupsResponse.java
<filename>contract/src/main/java/io/pravega/schemaregistry/contract/generated/rest/model/ListGroupsResponse.java /* * Pravega Schema Registry APIs * REST APIs for Pravega Schema Registry. * * OpenAPI spec version: 0.0.1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.pravega.schemaregistry.contract.generated.rest.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.pravega.schemaregistry.contract.generated.rest.model.GroupProperties; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.constraints.*; /** * Map of Group names to group properties. For partially created groups, the group properties may be null. */ @ApiModel(description = "Map of Group names to group properties. For partially created groups, the group properties may be null.") public class ListGroupsResponse { @JsonProperty("groups") private Map<String, GroupProperties> groups = null; @JsonProperty("continuationToken") private String continuationToken = null; public ListGroupsResponse groups(Map<String, GroupProperties> groups) { this.groups = groups; return this; } public ListGroupsResponse putGroupsItem(String key, GroupProperties groupsItem) { if (this.groups == null) { this.groups = new HashMap<String, GroupProperties>(); } this.groups.put(key, groupsItem); return this; } /** * Get groups * @return groups **/ @JsonProperty("groups") @ApiModelProperty(value = "") public Map<String, GroupProperties> getGroups() { return groups; } public void setGroups(Map<String, GroupProperties> groups) { this.groups = groups; } public ListGroupsResponse continuationToken(String continuationToken) { this.continuationToken = continuationToken; return this; } /** * Continuation token to identify the position of last group in the response. * @return continuationToken **/ @JsonProperty("continuationToken") @ApiModelProperty(required = true, value = "Continuation token to identify the position of last group in the response.") @NotNull public String getContinuationToken() { return continuationToken; } public void setContinuationToken(String continuationToken) { this.continuationToken = continuationToken; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ListGroupsResponse listGroupsResponse = (ListGroupsResponse) o; return Objects.equals(this.groups, listGroupsResponse.groups) && Objects.equals(this.continuationToken, listGroupsResponse.continuationToken); } @Override public int hashCode() { return Objects.hash(groups, continuationToken); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ListGroupsResponse {\n"); sb.append(" groups: ").append(toIndentedString(groups)).append("\n"); sb.append(" continuationToken: ").append(toIndentedString(continuationToken)).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 "); } }
codebycase/algorithms
src/main/java/a04_stacks_queues/RemoveDuplicates.java
package a04_stacks_queues; import java.util.Stack; /** * You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent * and equal letters from s and removing them, causing the left and the right side of the deleted * substring to concatenate together. * * We repeatedly make k duplicate removals on s until we no longer can. * * Return the final string after all such duplicate removals have been made. It is guaranteed that * the answer is unique. * * <pre> Example: Input: s = "deeedbbcccbdaa", k = 3 Output: "aa" Explanation: First delete "eee" and "ccc", get "ddbbbdaa" Then delete "bbb", get "dddaa" Finally delete "ddd", get "aa" * </pre> * * https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ * https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/ */ public class RemoveDuplicates { public String removeDuplicates(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (sb.length() > 0 && s.charAt(i) == sb.charAt(sb.length() - 1)) { sb.deleteCharAt(sb.length() - 1); } else { sb.append(s.charAt(i)); } } return sb.toString(); } /** * Copy characters within the same string using the fast and slow pointers. Each time we need to * erase k characters, we just move the slow pointer k positions back. */ public String removeDuplicates(String s, int k) { Stack<Integer> counts = new Stack<>(); char[] sa = s.toCharArray(); int j = 0; // a slow pointer for (int i = 0; i < s.length(); ++i, ++j) { sa[j] = sa[i]; // copy current if (j == 0 || sa[j] != sa[j - 1]) { counts.push(1); } else { int count = counts.pop() + 1; if (count == k) { j = j - k; // move back by k } else { counts.push(count); } } } return new String(sa, 0, j); } class Pair { int cnt; char ch; public Pair(int cnt, char ch) { this.ch = ch; this.cnt = cnt; } } public String removeDuplicates2(String s, int k) { Stack<Pair> counts = new Stack<>(); for (int i = 0; i < s.length(); ++i) { if (counts.empty() || s.charAt(i) != counts.peek().ch) { counts.push(new Pair(1, s.charAt(i))); } else { if (++counts.peek().cnt == k) { counts.pop(); } } } StringBuilder b = new StringBuilder(); while (!counts.empty()) { Pair p = counts.pop(); for (int i = 0; i < p.cnt; i++) { b.append(p.ch); } } return b.reverse().toString(); } }
dq922/PerfKitExplorer
client/components/widget/data_viz/gviz/chart-wrapper-service.js
<gh_stars>0 /** * @copyright Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @fileoverview chartWrapperService is an angular service used to create * instances of google.visualization.ChartWrapper. It also provides some helper * methods around ChartWrapper. To learn more about ChartWrapper, see: * https://developers.google.com/chart/interactive/docs/reference#chartwrapperobject * * @author <EMAIL> (<NAME>) */ goog.provide('p3rf.perfkit.explorer.components.widget.data_viz.gviz.ChartWrapperService'); goog.require('p3rf.perfkit.explorer.components.widget.data_viz.gviz.getGvizChartWrapper'); goog.require('p3rf.perfkit.explorer.models.ChartModel'); goog.require('p3rf.perfkit.explorer.models.ChartType'); goog.scope(function() { const explorer = p3rf.perfkit.explorer; const ChartModel = explorer.models.ChartModel; const ChartType = explorer.models.ChartType; /** * Describes the type definition for a chart. * @constructor */ explorer.components.widget.data_viz.gviz.ChartTypeModel = function() { /** * Provides a real-world title for the chart. * @export {string} */ this.title = ''; /** * Provides the className (and documentation id) for the chart. * @export {string} */ this.className = ''; }; var ChartTypeModel = explorer.components.widget.data_viz.gviz.ChartTypeModel; /** * See module docstring for more information about purpose and usage. * * @param {function(new:google.visualization.ChartWrapper)} GvizChartWrapper * @constructor * @ngInject */ explorer.components.widget.data_viz.gviz.ChartWrapperService = function($http, GvizChartWrapper, arrayUtilService) { /** * @private */ this.http_ = $http; /** * @type {function(new:google.visualization.ChartWrapper)} * @private */ this.GvizChartWrapper_ = GvizChartWrapper; /** * @type {!ArrayUtilService} * @private */ this.arrayUtilSvc_ = arrayUtilService; /** * A list of legend alignments for GViz charts. * @export {!Array.<!string>} */ this.LEGEND_ALIGNMENTS = [ 'start', 'center', 'end' ]; /** * A list of legend positions for GViz charts. * @export {!Array.<!string>} */ this.LEGEND_POSITIONS = [ 'none', 'top', 'right', 'bottom', 'left', 'in' ]; /** * An angular-exposed copy of ChartType. * @export @enum {string} */ this.CHART_TYPES = explorer.models.ChartType; /** * Provides an ordered list of charts. * @type {Array<!ChartTypeModel> * @export */ this.allCharts = []; /** * Provides an indexed list of charts. * @export {Object.<string, !ChartTypeModel>} */ this.allChartsIndex = {}; this.loadCharts(); }; const ChartWrapperService = ( explorer.components.widget.data_viz.gviz.ChartWrapperService); /** * Loads a list of available charts from a JSON file. */ ChartWrapperService.prototype.loadCharts = function() { this.http_.get('/static/components/widget/data_viz/gviz/gviz-charts.json'). success(angular.bind(this, function(response) { $.merge(this.allCharts, response); this.allChartsIndex = this.arrayUtilSvc_.getDictionary( this.allCharts, 'className'); })). error(angular.bind(this, function(response) { while (this.allCharts.length > 0) { this.allCharts.pop(); } })); }; /** * Returns a new instance of a google.visualization.ChartWrapper. * * @param {?string=} opt_chartType * @param {*=} opt_gvizOptions * @param {?google.visualization.DataTable=} opt_dataTable * @param {?google.visualization.DataView=} opt_dataView * @return {google.visualization.ChartWrapper} */ ChartWrapperService.prototype.create = function( opt_chartType, opt_gvizOptions, opt_dataTable, opt_dataView) { let chartWrapper = new this.GvizChartWrapper_(); if (opt_chartType) { chartWrapper.setChartType(opt_chartType); } if (opt_gvizOptions) { chartWrapper.setOptions(opt_gvizOptions); } if (opt_dataTable) { chartWrapper.setDataTable(opt_dataTable); } if (opt_dataView) { chartWrapper.setView(opt_dataView); } return chartWrapper; }; /** * Returns a ChartModel object based on the ChartWrapper configuration. * * @param {google.visualization.ChartWrapper} gvizChartWrapper * @return {ChartModel} */ ChartWrapperService.prototype.getChartModel = function(gvizChartWrapper) { let model = new ChartModel(); model.chartType = gvizChartWrapper.getChartType(); model.options = gvizChartWrapper.getOptions(); return model; }; }); // goog.scope
inordeng/TASO
src/dnnl/ops_mkl.cc
/* Copyright 2020 Stanford, Tsinghua * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "taso/ops.h" #include "taso/dnnl_helper.h" using namespace taso; Model::Model() : isTraining(false), print_cost(false) { global_unique_id = 100; workSpaceSize = WORK_SPACE_SIZE; eng = dnnl::engine(dnnl::engine::kind::cpu, 0); strm = dnnl::stream(eng); CHECK_NE(nullptr, workSpace = (DATATYPE*)malloc(workSpaceSize)); // allocate tensors for measuring performance CHECK_NE(nullptr, inputPtr = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); CHECK_NE(nullptr, biasPtr = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); CHECK_NE(nullptr, outputPtr = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); CHECK_NE(nullptr, filterPtr = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); // create tensors for batch norm CHECK_NE(nullptr, scalePtr = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); CHECK_NE(nullptr, runningMean = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); CHECK_NE(nullptr, runningVar = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); CHECK_NE(nullptr, saveMean = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); CHECK_NE(nullptr, saveVar = (DATATYPE*)malloc(MAX_TENSOR_SIZE)); } float Model::measure_oplist_runtime(const std::vector<OpBase*>& opBaseList) { const int num_runs = 100; // warmup for (int times = 0; times < num_runs; times++) for (size_t i = 0; i < opBaseList.size(); i++) opBaseList[i]->forward(); // measure runtime auto beg = microsecond_timer(); for (int times = 0; times < num_runs; times++) { for (size_t i = 0; i < opBaseList.size(); i++) opBaseList[i]->forward(); } auto end = microsecond_timer(); return (end - beg) / 1.e3 / num_runs; } void* Model::allocate_memory(size_t size, const DATATYPE* data_initial) { void* ptr; if (size == 0) { // Note: Special value for zero-sized tensor ptr = (void*) 0x1; } else { CHECK_NE(nullptr, ptr = malloc(size)); } if (data_initial != NULL) { memcpy(ptr, data_initial, size); } return ptr; } bool Model::copy_memory(DATATYPE* dst, const DATATYPE* src, size_t size) { memcpy(dst, src, size); return true; }
project-sunbird/groups
service/app/utils/ApplicationStart.java
package utils; import java.util.concurrent.CompletableFuture; import javax.inject.Inject; import javax.inject.Singleton; import org.sunbird.Application; import org.sunbird.auth.verifier.KeyManager; import org.sunbird.common.exception.BaseException; import org.sunbird.util.*; import play.api.Environment; import play.api.inject.ApplicationLifecycle; /** * This class will be called after on application startup. only one instance of this class will be * created. StartModule class has responsibility to eager load this class. */ @Singleton public class ApplicationStart { /** * All one time initialization which required during server startup will fall here. * * @param lifecycle ApplicationLifecycle */ @Inject public ApplicationStart(ApplicationLifecycle lifecycle, Environment environment) throws BaseException { // instantiate actor system and initialize all the actors Application.getInstance().init(); setEnvironment(environment); checkCassandraConnections(); HttpClientUtil.getInstance(); ActivityConfigReader.initialize(); SystemConfigUtil.init(); // Shut-down hook lifecycle.addStopHook( () -> { return CompletableFuture.completedFuture(null); }); KeyManager.init(); } private void setEnvironment(Environment environment) { // TODO: Any env specific work. if (environment.asJava().isDev()) { // env = ProjectUtil.Environment.dev; } else if (environment.asJava().isTest()) { // env = ProjectUtil.Environment.qa; } else { // env = ProjectUtil.Environment.prod; } } private static void checkCassandraConnections() throws BaseException { DBUtil.checkCassandraDbConnections(); } }
blackducksoftware/cerebros
go/pkg/polaris/api/metrics.go
<gh_stars>0 /* Copyright (C) 2020 Synopsys, Inc. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package api import ( "fmt" "github.com/prometheus/client_golang/prometheus" "time" ) var eventCounter *prometheus.CounterVec var statusCodeCounter *prometheus.CounterVec var responseTimeHistogram *prometheus.HistogramVec func recordEvent(event string, err error) { eventCounter.With(prometheus.Labels{"event": event, "iserror": fmt.Sprintf("%t", err != nil)}).Inc() } func recordResponseStatusCode(verb string, apiPath string, statusCode int) { statusCodeCounter.With(prometheus.Labels{"verb": verb, "apipath": apiPath, "code": fmt.Sprintf("%d", statusCode)}).Inc() } func recordResponseTime(verb string, apiPath string, duration time.Duration, statusCode int) { milliseconds := float64(duration / time.Millisecond) responseTimeHistogram.With(prometheus.Labels{ "verb": verb, "apipath": apiPath, "code": fmt.Sprintf("%d", statusCode), }).Observe(milliseconds) } func init() { eventCounter = prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: "cerebros", Subsystem: "polaris_api", Name: "event_counter", Help: "a count of events", }, []string{"event", "iserror"}) prometheus.MustRegister(eventCounter) statusCodeCounter = prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: "cerebros", Subsystem: "polaris_api", Name: "status_code_counter", Help: "a counter of status codes from http responses", }, []string{"verb", "apipath", "code"}) prometheus.MustRegister(statusCodeCounter) responseTimeHistogram = prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: "cerebros", Subsystem: "polaris_api", Name: "response_time_histogram", Help: "a histogram of polaris api response times in milliseconds", Buckets: prometheus.ExponentialBuckets(1, 2, 20), }, []string{"verb", "apipath", "code"}) prometheus.MustRegister(responseTimeHistogram) }
rcogal/coinapi-exchange
client/src/app/exchange-data-table/duck/actions.js
import types from './types.js'; const fetchCurrentOrderbook = (orderbooks) => { return { type: types.GET_CURRENT_ORDERBOOK, payload: orderbooks }; }; export default { fetchCurrentOrderbook };
petr-muller/abductor
cil/test/small1/init16.c
//The Gnome calendar application uses initializers with arithmetic expressions: #include "testharness.h" int x = ! (3 && ! 3); int array[(3 && !3) ? 6 : 8]; int main() { return x - 1; }
HeRaNO/ChickenRibs
UESTC-Programming-Course/Grade 1/Chapter 4/Homework/F.c
#include <stdio.h> char a[15]; int main() { printf("Enter the first 12 digits of an EAN:\n\n"); scanf("%s",a); int x=a[1]+a[3]+a[5]+a[7]+a[9]+a[11]-288; int y=a[0]+a[2]+a[4]+a[6]+a[8]+a[10]-288; x*=3;x+=y;x=(x-1)%10;x=9-x; printf("Check digit: %d \n",x); return 0; }
smalljvm/SmallJ
VM/src/smallj/core/SmallByteArray.java
class SmallByteArray extends SmallObject { public byte[] values; public SmallByteArray( SmallObject aClass, int size ) { super( aClass, 0 ); values = new byte[ size ]; } public SmallByteArray( SmallObject aClass, String text ) { super( aClass, 0 ); int size = text.length(); values = new byte[ size ]; for( int i = 0; i < size; i++ ) values[ i ] = ( byte ) text.charAt( i ); } @Override public SmallObject copy( SmallObject aClass ) { SmallByteArray newObj = new SmallByteArray( aClass, values.length ); for( int i = 0; i < values.length; i++ ) { newObj.values[ i ] = values[ i ]; } return newObj; } @Override public String toString() { // we assume its a string, tho not always true... return new String( values ); } }
nms-htc/eip-vnm
src/main/java/com/nms/vnm/eip/web/controller/admin/VideoBean.java
/** * Copyright (C) 2014 Next Generation Mobile Service JSC., (NMS). All rights * reserved. */ package com.nms.vnm.eip.web.controller.admin; import com.nms.vnm.eip.entity.Video; import com.nms.vnm.eip.service.entity.BaseService; import com.nms.vnm.eip.service.entity.VideoService; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Named; @Named @ViewScoped public class VideoBean extends AbstractProductBean<Video> { private static final long serialVersionUID = -1514605817248554643L; @EJB private VideoService videoService; @Override protected Video initEntity() { return new Video(); } @Override protected BaseService<Video> getBaseService() { return videoService; } }
viktornikolov038/Javascript-Essentials-May-2019
Objects and DOM/Exercise/03. Number-Convertor/solution.js
<reponame>viktornikolov038/Javascript-Essentials-May-2019<gh_stars>0 function solve() { let selectToMenu = document.getElementById("selectMenuTo"); let selectMenuToBinaryOption = selectToMenu.children[0]; selectMenuToBinaryOption.value = "binary"; selectMenuToBinaryOption.textContent = "Binary"; let selectMenuToHexadecimal = document.createElement("option"); selectMenuToHexadecimal.value = "hexadecimal"; selectMenuToHexadecimal.textContent = "Hexadecimal"; selectToMenu.appendChild(selectMenuToHexadecimal); let convertButton = document.getElementsByTagName("BUTTON")[0]; convertButton.addEventListener("click", function(){ let inputNumberField = document.getElementById("input"); let numberToConvert = Number(inputNumberField.value); let convertTo = selectToMenu.options[selectToMenu.selectedIndex].textContent; let convertedNumber; if (convertTo === "Binary") { convertedNumber = numberToConvert.toString(2); } else if(convertTo === "Hexadecimal") { convertedNumber = numberToConvert.toString(16); } let resultField = document.getElementById("result"); resultField.value = convertedNumber.toUpperCase(); }); }
fapbatista/mindinsight
tests/ut/datavisual/data_transform/test_events_data.py
# Copyright 2019 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """ Function: Test mindinsight.datavisual.data_transform.events_data. Usage: pytest tests/ut/datavisual """ import threading from collections import namedtuple import pytest from mindinsight.conf import settings from mindinsight.datavisual.data_transform import events_data from mindinsight.datavisual.data_transform.events_data import EventsData, TensorEvent, _Tensor from ..mock import MockLogger class MockReservoir: """Use this class to replace reservoir.Reservoir in test.""" def __init__(self, size): self.size = size self._samples = [ _Tensor('wall_time1', 1, 'value1', 'filename1'), _Tensor('wall_time2', 2, 'value2', 'filename2'), _Tensor('wall_time3', 3, 'value3', 'filename3') ] def samples(self): """Replace the samples function.""" return self._samples def add_sample(self, sample): """Replace the add_sample function.""" self._samples.append(sample) def remove_sample(self, sample): """Replace the remove_sample function.""" self._samples.remove(sample) # use for test parameters when tensor event does not have the required attrs Event1 = namedtuple('tensor_event', 'EVENT_TAG VALUE') class TestEventsData: """Test EventsData class.""" def setup_method(self): """Mock original logger, init a EventsData object for use.""" self._ev_data = EventsData() self._ev_data._tags_by_plugin = { 'plugin_name1': [f'tag{i}' for i in range(10)], 'plugin_name2': [f'tag{i}' for i in range(20, 30)] } self._ev_data._tags_by_plugin_mutex_lock.update({'plugin_name1': threading.Lock()}) self._ev_data._reservoir_by_tag = {'tag0': MockReservoir(500), 'new_tag': MockReservoir(500)} self._ev_data._tags = [f'tag{i}' for i in range(settings.MAX_TAG_SIZE_PER_EVENTS_DATA)] def get_ev_data(self): """Get the EventsData object.""" return self._ev_data def test_get_tags_by_plugin_name_with_not_exist_key(self): """Test get_tags_by_plugin_name method when key not exist.""" ev_data = self.get_ev_data() with pytest.raises(KeyError): ev_data.list_tags_by_plugin('plugin_name3') def test_get_tags_by_plugin_name_success(self): """Test get_tags_by_plugin_name method success.""" ev_data = self.get_ev_data() res = ev_data.list_tags_by_plugin('plugin_name1') assert set(res) == set(f'tag{i}' for i in range(10)) @pytest.mark.parametrize('t_event', [Event1(1, 2)]) def test_add_tensor_event_with_not_events_data(self, t_event): """Test when given event do not have attrs tag or value.""" events_data.logger = MockLogger ev_data = self.get_ev_data() with pytest.raises(TypeError) as ex: ev_data.add_tensor_event(t_event) assert ex.value.args[0] == 'Expect to get data of type `TensorEvent`.' def test_add_tensor_event_success(self): """Test add_tensor_event success.""" ev_data = self.get_ev_data() t_event = TensorEvent(wall_time=1, step=4, tag='new_tag', plugin_name='plugin_name1', value='value1', filename='filename') ev_data.add_tensor_event(t_event) assert 'tag0' not in ev_data._tags assert ev_data._tags[-1] == 'new_tag' assert 'tag0' not in ev_data._tags_by_plugin['plugin_name1'] assert 'tag0' not in ev_data._reservoir_by_tag assert 'new_tag' in ev_data._tags_by_plugin['plugin_name1'] assert ev_data._reservoir_by_tag['new_tag'].samples()[-1] == _Tensor(t_event.wall_time, t_event.step, t_event.value, 'filename') def test_add_tensor_event_out_of_order(self): """Test add_tensor_event success for out_of_order summaries.""" wall_time = 1 value = '1' tag = 'tag' plugin_name = 'scalar' file1 = 'file1' ev_data = EventsData() steps = [i for i in range(2, 10)] for step in steps: t_event = TensorEvent(wall_time=1, step=step, tag=tag, plugin_name=plugin_name, value=value, filename=file1) ev_data.add_tensor_event(t_event) t_event = TensorEvent(wall_time=1, step=1, tag=tag, plugin_name=plugin_name, value=value, filename=file1) ev_data.add_tensor_event(t_event) # Current steps should be: [1, 2, 3, 4, 5, 6, 7, 8, 9] assert len(ev_data._reservoir_by_tag[tag].samples()) == len(steps) + 1 file2 = 'file2' new_steps_1 = [5, 10] for step in new_steps_1: t_event = TensorEvent(wall_time=1, step=step, tag=tag, plugin_name=plugin_name, value=value, filename=file2) ev_data.add_tensor_event(t_event) assert ev_data._reservoir_by_tag[tag].samples()[-1] == _Tensor(wall_time, step, value, file2) # Current steps should be: [1, 2, 3, 4, 5, 10] steps = [1, 2, 3, 4, 5, 10] samples = ev_data._reservoir_by_tag[tag].samples() for step, sample in zip(steps, samples): filename = file1 if sample.step < 5 else file2 assert sample == _Tensor(wall_time, step, value, filename) new_steps_2 = [7, 11, 3] for step in new_steps_2: t_event = TensorEvent(wall_time=1, step=step, tag=tag, plugin_name=plugin_name, value=value, filename=file2) ev_data.add_tensor_event(t_event) # Current steps should be: [1, 2, 3, 5, 7, 10, 11], file2: [3, 5, 7, 10, 11] steps = [1, 2, 3, 5, 7, 10, 11] new_steps_2.extend(new_steps_1) samples = ev_data._reservoir_by_tag[tag].samples() for step, sample in zip(steps, samples): filename = file2 if sample.step in new_steps_2 else file1 assert sample == _Tensor(wall_time, step, value, filename)
trkin/premesti.se
app/helpers/translate_helper.rb
module TranslateHelper # there are two ways of calling this helper: # t_crud 'are_you_sure_to_remove_item', item: @move # t_crud 'edit', User def t_crud(action, model_class) if model_class.class == Hash t(action, item: t("neo4j.models.#{model_class[:item].name.downcase}.accusative")) else "#{t(action)} #{t("neo4j.models.#{model_class.name.downcase}.accusative")}" end end end
slok/ragnarok
master/web/handler/api/v1/api.go
package v1 import ( "encoding/json" "fmt" "io/ioutil" "net/http" chaosv1 "github.com/slok/ragnarok/api/chaos/v1" "github.com/slok/ragnarok/apimachinery/serializer" clichaosv1 "github.com/slok/ragnarok/client/api/chaos/v1" "github.com/slok/ragnarok/log" ) // Handler is the handler that has all the required handlers to create the rest api V1 // of the application. type Handler interface { // Debug will create a new debug experiment on the desired node. Debug(w http.ResponseWriter, r *http.Request) // WriteExperiment will handle the WR operations on an experiment (create & update). WriteExperiment(w http.ResponseWriter, r *http.Request) } // JSONHandler is the base implementation of Handler using JSON format. Satisfies Handler interface. type JSONHandler struct { experimentCli clichaosv1.ExperimentClientInterface serializer serializer.Serializer logger log.Logger } // NewJSONHandler returns a new api v1 JSON handler. func NewJSONHandler(experimentCli clichaosv1.ExperimentClientInterface, logger log.Logger) *JSONHandler { return &JSONHandler{ experimentCli: experimentCli, serializer: serializer.JSONSerializerDefault, logger: logger, } } func (j *JSONHandler) setInternalError(w http.ResponseWriter, errorStr string) { w.WriteHeader(http.StatusInternalServerError) w.Header().Set("Content-Type", "application/json") body, _ := json.Marshal(map[string]string{ "error": errorStr, }) w.Write(body) } func (j *JSONHandler) setBadRequest(w http.ResponseWriter, errorStr string) { w.WriteHeader(http.StatusBadRequest) w.Header().Set("Content-Type", "application/json") body, _ := json.Marshal(map[string]string{ "error": errorStr, }) w.Write(body) } func (j *JSONHandler) setOK(w http.ResponseWriter, str string) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") body, _ := json.Marshal(map[string]string{ "msg": str, }) w.Write(body) } func (j *JSONHandler) decodeJSONExperiment(body []byte) (chaosv1.Experiment, error) { return chaosv1.NewExperiment(), nil } // Debug will create a new experiment on the desired node. func (j *JSONHandler) Debug(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") w.Write([]byte("Not implemented")) } // WriteExperiment will get an experiment in JSON and store an experiment on the repository. func (j *JSONHandler) WriteExperiment(w http.ResponseWriter, r *http.Request) { switch r.Method { case "POST": // TODO: Check experiment exists before creating a new one. // Deserialize experiment. b, err := ioutil.ReadAll(r.Body) if err != nil { j.setInternalError(w, err.Error()) return } expTmp, err := j.serializer.Decode(b) if err != nil { j.setBadRequest(w, err.Error()) return } exp, ok := expTmp.(*chaosv1.Experiment) if !ok { j.setBadRequest(w, "decoded object is not an experiment") return } if _, err := j.experimentCli.Create(exp); err != nil { j.setInternalError(w, err.Error()) return } j.setOK(w, fmt.Sprintf("experiment %s scheduled", exp.Metadata.ID)) return } j.setBadRequest(w, "wrong request") }
lolwhitaker/sbt-jupiter-interface
src/plugin/src/sbt-test/basic/tags/src/test/java/jupiter/TestTwo.java
package jupiter; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @Tag("fast") public class TestTwo { @Test public void a() { Reporter.report("two-a"); } @Test public void b() { Reporter.report("two-b"); } }
renmeng8875/springboot
ch9_2/src/main/java/com/wisely/ch9_2/batch/CsvBeanValidator.java
package com.wisely.ch9_2.batch; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.ValidatorFactory; import org.springframework.batch.item.validator.ValidationException; import org.springframework.batch.item.validator.Validator; import org.springframework.beans.factory.InitializingBean; public class CsvBeanValidator<T> implements Validator<T>,InitializingBean { private javax.validation.Validator validator; @Override public void afterPropertiesSet() throws Exception { //1 ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); validator = validatorFactory.usingContext().getValidator(); } @Override public void validate(T value) throws ValidationException { Set<ConstraintViolation<T>> constraintViolations = validator.validate(value); //2 if(constraintViolations.size()>0){ StringBuilder message = new StringBuilder(); for (ConstraintViolation<T> constraintViolation : constraintViolations) { message.append(constraintViolation.getMessage() + "\n"); } throw new ValidationException(message.toString()); } } }
raulval/PetGree
src/main/java/br/edu/utfpr/carloseduardofreitas/petgree/model/Agendamento.java
<filename>src/main/java/br/edu/utfpr/carloseduardofreitas/petgree/model/Agendamento.java package br.edu.utfpr.carloseduardofreitas.petgree.model; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDate; import java.time.LocalTime; @Entity @Table(name = "Agendamento") public class Agendamento implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "age_data",nullable = false) private LocalDate data; @Column(name = "age_hora",nullable = false) private LocalTime hora; @Column(name = "age_pago", nullable = false) private boolean pago; @OneToOne @JoinColumn(name = "ani_id",nullable = false) private Animal animal; @OneToOne @JoinColumn(name = "usu_id",nullable = false) private Usuario usuario; @OneToOne @JoinColumn(name = "ser_id",nullable = false) private Servico servico; @Column(name = "age_data_cadastro", nullable = true) private LocalDate dataCadastro; public int getId() { return id; } public void setId(int id) { this.id = id; } public LocalDate getData() { return data; } public void setData(LocalDate data) { this.data = data; } public boolean isPago() { return pago; } public void setPago(boolean pago) { this.pago = pago; } public Animal getAnimal() { return animal; } public void setAnimal(Animal animal) { this.animal = animal; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Servico getServico() { return servico; } public void setServico(Servico servico) { this.servico = servico; } public LocalTime getHora() { return hora; } public void setHora(LocalTime hora) { this.hora = hora; } public LocalDate getDataCadastro() { return dataCadastro; } public void setDataCadastro(LocalDate dataCadastro) { this.dataCadastro = dataCadastro; } }
matrixknight/KendoUI-Admin-Site
admin/views/dashboard/forms/form_elements.js
$(function () { // 月份 $('#monthNormal, #monthReadonly, #monthDisabled').kendoDatePicker({ start: 'year', depth: 'year', format: 'yyyy/MM' }); // 星期 $('#weekNormal, #weekReadonly, #weekDisabled').kendoDatePicker({ weekNumber: true }); // 日期 $('#dateNormal, #dateReadonly, #dateDisabled').kendoDatePicker(); // 时间 $('#timeNormal, #timeReadonly, #timeDisabled').kendoTimePicker(); // 时日 $('#datetimeNormal, #datetimeReadonly, #datetimeDisabled').kendoDateTimePicker(); // 数字 $('#numberNormal, #numberReadonly, #numberDisabled').kendoNumericTextBox(); // 范围 $('#rangeNormal, #rangeDisabled').kendoSlider(); // 颜色 $('#colorNormal, #colorDisabled').kendoColorPicker(); $('#paletteNormal').kendoColorPalette(); $('#paletteDisabled').kendoColorPalette().data('kendoColorPalette').enable(false); // 复选框 $('.indeterminate').prop('indeterminate', true); // 选择框 $('#selectNormal, #selectDisabled').kendoDropDownList(); $('#selectReadonly').kendoDropDownList().data('kendoDropDownList').readonly(); // 多选框 $('#multipleNormal').kendoMultiSelect({ placeholder: '正常' }); $('#multipleReadonly').kendoMultiSelect({ placeholder: '只读' }).data('kendoMultiSelect').readonly(); $('#multipleDisabled').kendoMultiSelect({ placeholder: '禁用' }); // 文件域 $('#fileNormal').kendoUpload(); $('#fileDisabled').kendoUpload().data('kendoUpload').disable(); });
srafehi/riberry
riberry/app/backends/impl/pool/tasks/background.py
import logging import riberry from ..task_queue import TaskQueue log = logging.getLogger(__name__) def background(queue: TaskQueue): riberry.app.tasks.echo() with queue.lock: if not queue.limit_reached(): riberry.app.tasks.poll(track_executions=True, filter_func=lambda _: not queue.limit_reached()) else: log.debug('Queue limit reached, skipped task polling') riberry.app.tasks.refresh()
Haakenlid/tassen
django/apps/frontpage/__init__.py
<reponame>Haakenlid/tassen default_app_config = 'apps.frontpage.appconf.FrontpageAppConfig'
antonmedv/year
packages/1976/12/25/index.js
<reponame>antonmedv/year module.exports = new Date(1976, 11, 25)
GuillaumeCisco/react-json-prettify
src/themes/grayscale.js
export default { background: 'rgb(255, 255, 255)', brace: 'rgb(51, 51, 51)', keyQuotes: 'rgb(51, 51, 51)', valueQuotes: 'rgb(51, 51, 51)', colon: 'rgb(51, 51, 51)', comma: 'rgb(51, 51, 51)', key: 'rgb(51, 51, 51)', value: { string: 'rgb(51, 51, 51)', null: 'rgb(119, 119, 119)', number: 'rgb(119, 119, 119)', boolean: 'rgb(119, 119, 119)', }, bracket: 'rgb(51, 51, 51)', };
DhairyaDoc/TelegramApi
src/main/java/org/telegram/api/functions/messages/TLRequestMessagesGetPinnedDialogs.java
package org.telegram.api.functions.messages; import org.telegram.api.messages.TLMessagesPeerDialogs; import org.telegram.tl.StreamingUtils; import org.telegram.tl.TLContext; import org.telegram.tl.TLMethod; import org.telegram.tl.TLObject; import java.io.IOException; import java.io.InputStream; public class TLRequestMessagesGetPinnedDialogs extends TLMethod<TLMessagesPeerDialogs> { public static final int CLASS_ID = 0xe254d64e; public TLRequestMessagesGetPinnedDialogs() { super(); } public int getClassId() { return CLASS_ID; } public TLMessagesPeerDialogs deserializeResponse(InputStream stream, TLContext context) throws IOException { final TLObject res = StreamingUtils.readTLObject(stream, context); if (res == null) { throw new IOException("Unable to parse response"); } if ((res instanceof TLMessagesPeerDialogs)) { return (TLMessagesPeerDialogs) res; } throw new IOException("Incorrect response type. Expected " + TLMessagesPeerDialogs.class.getName() + ", got: " + res.getClass().getCanonicalName()); } public String toString() { return "messages.getPinnedDialogs#e254d64e"; } }
xavier-shui/hrm-parent
hrm-course-parent/hrm-course-common/src/main/java/cn/xavier/hrm/constant/CourseConstant.java
<filename>hrm-course-parent/hrm-course-common/src/main/java/cn/xavier/hrm/constant/CourseConstant.java package cn.xavier.hrm.constant; /** * @author <NAME> * @date 12/20/2021 */ public interface CourseConstant { String COURSE_TYPE = "course_type"; Integer OFFLINE = 0; Integer ONLINE = 1; }
alexpenev-s/service-manager
storage/postgres/service_offering.go
<reponame>alexpenev-s/service-manager /* * Copyright 2018 The Service Manager Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package postgres import ( "context" "fmt" "github.com/Peripli/service-manager/pkg/query" "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/types" ) type serviceOfferingStorage struct { db pgDB } func (sos *serviceOfferingStorage) Create(ctx context.Context, serviceOffering *types.ServiceOffering) (string, error) { so := &ServiceOffering{} so.FromDTO(serviceOffering) return create(ctx, sos.db, serviceOfferingTable, so) } func (sos *serviceOfferingStorage) Get(ctx context.Context, id string) (*types.ServiceOffering, error) { serviceOffering := &ServiceOffering{} if err := get(ctx, sos.db, id, serviceOfferingTable, serviceOffering); err != nil { return nil, err } return serviceOffering.ToDTO(), nil } func (sos *serviceOfferingStorage) List(ctx context.Context, criteria ...query.Criterion) ([]*types.ServiceOffering, error) { var serviceOfferings []ServiceOffering if err := validateFieldQueryParams(ServiceOffering{}, criteria); err != nil { return nil, err } err := listByFieldCriteria(ctx, sos.db, serviceOfferingTable, &serviceOfferings, criteria) if err != nil || len(serviceOfferings) == 0 { return []*types.ServiceOffering{}, err } serviceOfferingDTOs := make([]*types.ServiceOffering, 0, len(serviceOfferings)) for _, so := range serviceOfferings { serviceOfferingDTOs = append(serviceOfferingDTOs, so.ToDTO()) } return serviceOfferingDTOs, nil } func (sos *serviceOfferingStorage) ListWithServicePlansByBrokerID(ctx context.Context, brokerID string) ([]*types.ServiceOffering, error) { query := fmt.Sprintf(`SELECT %[1]s.*, %[2]s.id "%[2]s.id", %[2]s.name "%[2]s.name", %[2]s.description "%[2]s.description", %[2]s.created_at "%[2]s.created_at", %[2]s.updated_at "%[2]s.updated_at", %[2]s.free "%[2]s.free", %[2]s.bindable "%[2]s.bindable", %[2]s.plan_updateable "%[2]s.plan_updateable", %[2]s.catalog_id "%[2]s.catalog_id", %[2]s.catalog_name "%[2]s.catalog_name", %[2]s.metadata "%[2]s.metadata", %[2]s.schemas "%[2]s.schemas", %[2]s.service_offering_id "%[2]s.service_offering_id" FROM %[1]s JOIN %[2]s ON %[1]s.id = %[2]s.service_offering_id WHERE %[1]s.broker_id=$1;`, serviceOfferingTable, servicePlanTable) log.C(ctx).Debugf("Executing query %s", query) rows, err := sos.db.QueryxContext(ctx, query, brokerID) defer func() { if err := rows.Close(); err != nil { log.C(ctx).Errorf("Could not release connection when checking database s. Error: %s", err) } }() if err != nil { return nil, checkSQLNoRows(err) } services := make(map[string]*types.ServiceOffering) result := make([]*types.ServiceOffering, 0) for rows.Next() { row := struct { *ServiceOffering *ServicePlan `db:"service_plans"` }{} if err := rows.StructScan(&row); err != nil { return nil, err } if serviceOffering, ok := services[row.ServiceOffering.ID]; !ok { serviceOffering = row.ServiceOffering.ToDTO() serviceOffering.Plans = append(serviceOffering.Plans, row.ServicePlan.ToDTO()) services[row.ServiceOffering.ID] = serviceOffering result = append(result, serviceOffering) } else { serviceOffering.Plans = append(serviceOffering.Plans, row.ServicePlan.ToDTO()) } } return result, nil } func (sos *serviceOfferingStorage) Delete(ctx context.Context, criteria ...query.Criterion) error { return deleteAllByFieldCriteria(ctx, sos.db, serviceOfferingTable, ServiceOffering{}, criteria) } func (sos *serviceOfferingStorage) Update(ctx context.Context, serviceOffering *types.ServiceOffering) error { so := &ServiceOffering{} so.FromDTO(serviceOffering) return update(ctx, sos.db, serviceOfferingTable, so) }
goszjacek/scex
scex-core/src/main/scala/com/avsystem/scex/symboldsl/TypeInfo.scala
package com.avsystem.scex package symboldsl import scala.reflect.api.{TypeCreator, Universe} class TypeInfo(typeCreator: TypeCreator, val clazz: Option[Class[_]], val isJava: Boolean, typeRepr: String) { def typeIn(u: Universe): u.Type = u.TypeTag[Any](u.rootMirror, typeCreator).tpe override def toString = typeRepr }
lixiaobin-bjhl/vue-component
function/getDayOption.js
<reponame>lixiaobin-bjhl/vue-component<filename>function/getDayOption.js /** * @file 日期选择 * @author <NAME>(<EMAIL>) */ 'use strict' export default function getDayOption () { var length = 32 var result = [] while (length--) { if (length) { result.unshift(length) } } return result }
operativeF/Kvasir
Lib/Chip/ATSAM3U4C.hpp
<gh_stars>0 #pragma once #include <cstdint> #include <Chip/CM3/Atmel/ATSAM3U4C/HSMCI.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/SSC.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/SPI.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/TC0.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/TWI0.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/TWI1.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/PWM.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/USART0.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/USART1.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/USART2.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/UDPHS.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/ADC12B.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/ADC.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/DMAC.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/SMC.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/MATRIX.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/PMC.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/UART.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/CHIPID.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/EFC0.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/EFC1.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/PIOA.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/PIOB.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/RSTC.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/SUPC.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/RTT.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/WDT.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/RTC.hpp> #include <Chip/CM3/Atmel/ATSAM3U4C/GPBR.hpp>
HoangNhat629/Android
btap1/app2/app/src/main/java/com/example/app2/ContactAdapter.java
<gh_stars>1-10 package com.example.app2; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.List; public class ContactAdapter extends ArrayAdapter<Contact> { private Context context; private int resource; private List<Contact> arrContact; public ContactAdapter(Context context, int resource, List<Contact> objects) { super(context, resource, objects); this.context = context; this. resource = resource; this.arrContact = objects; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { ViewHolder viewHolder; if(convertView == null){ viewHolder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(R.layout.item_contact_lv, parent, false); viewHolder.ivAvatar = convertView.findViewById(R.id.iv_image); viewHolder.tvName = convertView.findViewById(R.id.tv_name); viewHolder.tvNumber = convertView.findViewById(R.id.tv_number); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } Contact contact = arrContact.get(position); viewHolder.ivAvatar.setBackgroundResource(R.drawable.ic_person_black_24dp); viewHolder.tvName.setText(contact.getmName()); viewHolder.tvNumber.setText(contact.getmNumber()); return convertView; } public class ViewHolder{ ImageView ivAvatar; TextView tvName; TextView tvNumber; } }
bioko/system
src/main/java/org/biokoframework/system/repository/sql/SqlRepository.java
<filename>src/main/java/org/biokoframework/system/repository/sql/SqlRepository.java<gh_stars>0 /* * Copyright (c) 2014 * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * * * 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 org.biokoframework.system.repository.sql; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.biokoframework.system.repository.core.AbstractRepository; import org.biokoframework.system.repository.service.IRepositoryService; import org.biokoframework.system.repository.sql.query.SqlQuery; import org.biokoframework.system.repository.sql.translator.SqlTypesTranslator; import org.biokoframework.system.repository.sql.util.SqlStatementsHelper; import org.biokoframework.system.services.entity.IEntityBuilderService; import org.biokoframework.utils.domain.DomainEntity; import org.biokoframework.utils.domain.annotation.field.ComponingFieldsFactory; import org.biokoframework.utils.domain.annotation.field.Field; import org.biokoframework.utils.exception.ValidationException; import org.biokoframework.utils.repository.RepositoryException; import javax.inject.Inject; import java.sql.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map.Entry; public class SqlRepository<DE extends DomainEntity> extends AbstractRepository<DE> { private static final Logger LOGGER = Logger.getLogger(SqlRepository.class); protected final SqlConnector fDbConnector; protected final Class<DE> fEntityClass; protected final String fTableName; private LinkedHashMap<String, Field> fFieldNames; private SqlTypesTranslator fTranslator; @SuppressWarnings("rawtypes") public SqlRepository(Class entityClass, String tableName, SqlConnector connector, IEntityBuilderService entityBuilderService, IRepositoryService repositoryService) throws RepositoryException { super(entityBuilderService, repositoryService); fEntityClass = (Class<DE>) entityClass; fTableName = tableName; try { fFieldNames = ComponingFieldsFactory.createWithAnnotation(fEntityClass); } catch (Exception exception) { // Should never happen fFieldNames = null; exception.printStackTrace(); } fDbConnector = connector; fTranslator = connector.getTypesTranslator(); ensureTable(); } @SuppressWarnings("rawtypes") @Inject public SqlRepository(Class entityClass, SqlConnector connectionHelper, IEntityBuilderService entityBuilderService, IRepositoryService repositoryService) throws RepositoryException { this(entityClass, entityClass.getSimpleName(), connectionHelper, entityBuilderService, repositoryService); } @SuppressWarnings("unchecked") @Override public DE saveAfterValidation(DomainEntity entity) throws RepositoryException, ValidationException { DE castedEntity = (DE) entity; if (!entity.isValid()) { throw new ValidationException(entity.getValidationErrors()); } if (entity.getId() != null && !entity.getId().isEmpty()) { return update(castedEntity); } else { return insert(castedEntity); } } private DE insert(DE entity) throws RepositoryException { String id = null; Connection connection = null; PreparedStatement insertStatement = null; try { connection = fDbConnector.getConnection(); insertStatement = SqlStatementsHelper.preparedCreateStatement(fEntityClass, fTableName, connection); int i = 1; for (Entry<String, Field> anEntry : fFieldNames.entrySet()) { String aFieldName = anEntry.getKey(); fTranslator.insertIntoStatement(aFieldName, entity.get(aFieldName), anEntry.getValue(), insertStatement, i); i++; } insertStatement.execute(); //id = SqlStatementsHelper.retrieveId(insertStatement.getGeneratedKeys()); id = fDbConnector.getLastInsertId(connection).toString(); } catch (SQLException exception) { LOGGER.error("Error in insert", exception); } finally { closeDumbSql(connection, insertStatement, null); } if (!StringUtils.isEmpty(id) && !id.equals("0")) { entity.setId(id); return entity; } else { return null; } } private DE update(DE entity) { boolean updated = false; Connection connection = null; PreparedStatement updateStatement = null; try { connection = fDbConnector.getConnection(); updateStatement = SqlStatementsHelper.preparedUpdateStatement(fEntityClass, fTableName, connection); int i = 1; for (Entry<String, Field> anEntry : fFieldNames.entrySet()) { String aFieldName = anEntry.getKey(); fTranslator.insertIntoStatement(aFieldName, entity.get(aFieldName), anEntry.getValue(), updateStatement, i); i++; } updateStatement.setString(fFieldNames.size() + 1, entity.getId()); updateStatement.execute(); updated = updateStatement.getUpdateCount() > 0; updateStatement.close(); connection.close(); } catch (SQLException exception) { LOGGER.error("Error in retrieve", exception); closeDumbSql(connection, updateStatement, null); } if (updated) { return entity; } else { return null; } } @Override public DE retrieve(String anEntityKey) { ArrayList<DE> entities = new ArrayList<DE>(); Connection connection = null; PreparedStatement retrieveStatement = null; try { connection = fDbConnector.getConnection(); retrieveStatement = SqlStatementsHelper.preparedRetrieveByIdStatement(fEntityClass, fTableName, connection); retrieveStatement.setObject(1, anEntityKey); retrieveStatement.execute(); entities = SqlStatementsHelper.retrieveEntities(retrieveStatement.getResultSet(), fEntityClass, fTranslator, fEntityBuilderService); } catch (SQLException exception) { exception.printStackTrace(); } finally { closeDumbSql(connection, retrieveStatement, null); } if (entities.isEmpty()) { return null; } else { return entities.get(0); } } @SuppressWarnings("unchecked") @Override public DE retrieve(DomainEntity anEntity) { DE castedEntity = (DE) anEntity; return retrieve(castedEntity.getId()); } @Override public DE delete(String anEntityKey) { DE toBeDeleted = retrieve(anEntityKey); boolean deleted = false; Connection connection = null; PreparedStatement deleteStatement = null; try { connection = fDbConnector.getConnection(); deleteStatement = SqlStatementsHelper.preparedDeleteByIdStatement(fEntityClass, fTableName, connection); deleteStatement.setString(1, anEntityKey); deleteStatement.execute(); deleted = deleteStatement.getUpdateCount() > 0; deleteStatement.close(); connection.close(); } catch (SQLException exception) { closeDumbSql(connection, deleteStatement, null); exception.printStackTrace(); } if (deleted) { return toBeDeleted; } else { return null; } } @Override public ArrayList<DE> getAll() { ArrayList<DE> entities = new ArrayList<DE>(); Connection connection = null; PreparedStatement retrieveStatement = null; try { connection = fDbConnector.getConnection(); retrieveStatement = SqlStatementsHelper.preparedRetrieveAllStatement(fEntityClass, fTableName, connection); retrieveStatement.execute(); entities = SqlStatementsHelper.retrieveEntities(retrieveStatement.getResultSet(), fEntityClass, fTranslator, fEntityBuilderService); retrieveStatement.close(); connection.close(); } catch (SQLException exception) { closeDumbSql(connection, retrieveStatement, null); exception.printStackTrace(); } return entities; } @Override public ArrayList<DE> getEntitiesByForeignKey(String foreignKeyName, Object foreignKeyValue) { ArrayList<DE> entities = new ArrayList<DE>(); Connection connection = null; PreparedStatement retrieveStatement = null; try { connection = fDbConnector.getConnection(); retrieveStatement = SqlStatementsHelper.prepareRetrieveByForeignKey(fEntityClass, fTableName, connection, foreignKeyName); retrieveStatement.setObject(1, foreignKeyValue); retrieveStatement.execute(); entities = SqlStatementsHelper.retrieveEntities(retrieveStatement.getResultSet(), fEntityClass, fTranslator, fEntityBuilderService); } catch (SQLException exception) { exception.printStackTrace(); } finally { closeDumbSql(connection, retrieveStatement, null); } return entities; } @Override public DE retrieveByForeignKey(String foreignKeyName, Object foreignKeyValue) { ArrayList<DE> entities = new ArrayList<DE>(); Connection connection = null; PreparedStatement retrieveStatement = null; try { connection = fDbConnector.getConnection(); retrieveStatement = SqlStatementsHelper.prepareRetrieveOneByForeignKey(fEntityClass, fTableName, connection, foreignKeyName); retrieveStatement.setObject(1, foreignKeyValue); retrieveStatement.execute(); entities = SqlStatementsHelper.retrieveEntities(retrieveStatement.getResultSet(), fEntityClass, fTranslator, fEntityBuilderService); retrieveStatement.close(); connection.close(); } catch (SQLException exception) { LOGGER.error("Retrieve:", exception); exception.printStackTrace(); } finally { closeDumbSql(connection, retrieveStatement, null); } if (entities.isEmpty()) { return null; } else { return entities.get(0); } } @Override public SqlQuery<DE> createQuery() { return new SqlQuery<DE>(fDbConnector, fEntityBuilderService); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public String getTableName() { return fTableName; } public SqlTypesTranslator getTranslator() { return fTranslator; } public LinkedHashMap<String,Field> getFieldNames() { return fFieldNames; } private void ensureTable() throws RepositoryException { try { if (!fDbConnector.tableExists(fTableName)) { createTableFor(fEntityClass, fDbConnector); } } catch (Exception exception) { LOGGER.error("DB table check", exception); throw new RepositoryException(exception); } } private void createTableFor(Class<DE> entityClass, SqlConnector helper) throws SQLException { Connection connection = null; Statement statement = null; try { connection = helper.getConnection(); ArrayList<String> fieldEntries = new ArrayList<String>(); try { for (Entry<String, Field> entry : ComponingFieldsFactory.createWithAnnotation(entityClass).entrySet()) { fieldEntries.add(entry.getKey() + " " + fTranslator.getSqlType(entry.getKey(), entry.getValue())); } fieldEntries.add(DomainEntity.ID + " " + fTranslator.getSqlType(DomainEntity.ID, null)); fieldEntries.addAll(fTranslator.getAllConstraints()); fTranslator.clearConstraintsList(); } catch (Exception exception) { // THIS SHOULD NEVER HAPPEN System.err.println("[EASY MAN] - cannot retrieve annotation stuff in create SQL table"); exception.printStackTrace(); } StringBuilder sql = new StringBuilder(). append("CREATE TABLE ").append(fTableName). append(" (").append(StringUtils.join(fieldEntries, ", ")).append(") ").append(fDbConnector.getCreateTableTail()); // System.out.println(sql); statement = connection.createStatement(); statement.execute(sql.toString()); statement.close(); connection.close(); } catch (SQLException exception) { closeDumbSql(connection, statement, null); } } private void closeDumbSql(Connection connection, Statement statement, ResultSet set) { if (set != null) { try { set.close(); } catch (SQLException e) { } } if (statement != null) { try { statement.close(); } catch (SQLException closeException) { } } if (connection != null) { try { connection.close(); } catch (SQLException closeException) { } } } }
zjyau/nutui
src/packages/grid/index.js
import Row from '../gridrow/gridrow.vue'; import Col from '../gridcol/gridcol.vue'; import './grid.scss'; Row.install = function(Vue) { Vue.component(Row.name, Row); }; Col.install = function(Vue) { Vue.component(Col.name, Col); }; export { Row, Col };
wangwenwang/CM_Driver
CMDriver/Supply/MySupplyListViewController.h
<gh_stars>0 // // MySupplyListViewController.h // CMDriver // // Created by 凯东源 on 17/6/21. // Copyright © 2017年 城马联盟. All rights reserved. // #import <UIKit/UIKit.h> @interface MySupplyListViewController : UIViewController @end
nonggia/mrshell
src/main/java/com/ss/dw/mrshell/log/MRIndexLog.java
package com.ss.dw.mrshell.log; import java.util.List; import com.ss.dw.mrshell.util.ReflectionUtil; public class MRIndexLog extends MRLog { private List<String> values; public MRIndexLog() { } public boolean load(List<String> values) { this.values = values; return true; } public Integer getInt(int index) { try { return ReflectionUtil.parseInt(values.get(index)); } catch (IndexOutOfBoundsException e) { return null; } catch (NullPointerException e) { return null; } } public Double getDouble(int index) { try { return ReflectionUtil.parseDouble(values.get(index)); } catch (IndexOutOfBoundsException e) { return null; } catch (NullPointerException e) { return null; } } public Float getFloat(int index) { try { return ReflectionUtil.parseFloat(values.get(index)); } catch (IndexOutOfBoundsException e) { return null; } catch (NullPointerException e) { return null; } } public Short getShort(int index) { try { return ReflectionUtil.parseShort(values.get(index)); } catch (IndexOutOfBoundsException e) { return null; } catch (NullPointerException e) { return null; } } public Long getLong(int index) { try { return ReflectionUtil.parseLong(values.get(index)); } catch (IndexOutOfBoundsException e) { return null; } catch (NullPointerException e) { return null; } } public String getString(int index) { try { return values.get(index); } catch (IndexOutOfBoundsException e) { return null; } catch (NullPointerException e) { return null; } } public Boolean getBoolean(int index) { try { return ReflectionUtil.parseBoolean(values.get(index)); } catch (IndexOutOfBoundsException e) { return null; } catch (NullPointerException e) { return null; } } public Byte getByte(int index) { try { return ReflectionUtil.parseByte(values.get(index)); } catch (IndexOutOfBoundsException e) { return null; } catch (NullPointerException e) { return null; } } public Object getValue(Class<?> type, int index) { if (String.class.equals(type)) { return getString(index); } else if (Integer.class.equals(type)) { return getInt(index); } else if (Long.class.equals(type)) { return getLong(index); } else if (Boolean.class.equals(type)) { return getBoolean(index); } else if (Short.class.equals(type)) { return getShort(index); } else if (Double.class.equals(type)) { return getDouble(index); } else if (Float.class.equals(type)) { return getFloat(index); } else if (Byte.class.equals(type)) { return getByte(index); } else { return null; } } public boolean isValid() { return (values != null); } }
cliveyao/waltz
waltz-ng/client/org-units/pages/list-view/list-view.js
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * 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 * */ import _ from "lodash"; import angular from "angular"; import {termSearch} from "../../../common"; import {buildHierarchies} from "../../../common/hierarchy-utils"; import {buildPropertySummer} from "../../../common/tally-utils"; import template from './list-view.html'; const FIELDS_TO_SEARCH = ['name', 'description']; function setupBlockProcessor($state) { return b => { b.block.onclick = () => $state.go('main.org-unit.view', { id: b.value }); angular .element(b.block) .addClass('clickable'); }; } function loadDiagrams(svgStore, vm, $state) { svgStore .findByGroup('ORG_UNIT') .then(xs => vm.diagrams = xs); vm.blockProcessor = setupBlockProcessor($state); } function prepareOrgUnitTree(orgUnits, appTallies, endUserAppTallies) { const orgUnitsById = _.keyBy(orgUnits, 'id'); const enrichWithDirectCounts = (tallies, keyName) => { _.each(tallies, t => { const ou = orgUnitsById[t.id]; if (ou) ou[keyName] = t.count; }); }; enrichWithDirectCounts(appTallies, "appCount"); enrichWithDirectCounts(endUserAppTallies, "endUserAppCount"); const rootUnits = buildHierarchies(orgUnits); const appCountSummer = buildPropertySummer("appCount", "totalAppCount", "childAppCount"); const endUserAppCountSummer = buildPropertySummer("endUserAppCount", "totalEndUserAppCount", "childEndUserAppCount"); _.each(rootUnits, appCountSummer); _.each(rootUnits, endUserAppCountSummer); return rootUnits; } function controller(orgUnits, appTallies, endUserAppTallies, svgStore, $state) { const vm = this; loadDiagrams(svgStore, vm, $state); vm.filteredOrgUnits = []; vm.trees = prepareOrgUnitTree(orgUnits, appTallies, endUserAppTallies); vm.orgUnits = orgUnits; vm.doSearch = (q) => { if (!q || q.length < 3) { vm.clearSearch(); } else { vm.filteredOrgUnits = termSearch(orgUnits, q, FIELDS_TO_SEARCH); } }; vm.clearSearch = (q) => vm.filteredOrgUnits = []; } controller.$inject = [ 'orgUnits', 'appTallies', 'endUserAppTallies', 'SvgDiagramStore', '$state' ]; export default { template, controller, controllerAs: 'ctrl' };
Boom618/DigitalFarms
app/src/main/java/com/ty/digitalfarms/net/ProgressCancelListener.java
package com.ty.digitalfarms.net; /** * description:取消Progress提示框时取消Http请求 * author: XingZheng * date: 2016/11/22. */ public interface ProgressCancelListener { /** * 取消Progress提示框 */ void onCancelProgress(); }
JohnBearon/wecodekc-group-project
src/components/AdminComponents/AdminSubComponents/EventControl.js
<filename>src/components/AdminComponents/AdminSubComponents/EventControl.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import Calendar from '../../../components/AdminComponents/Calendar/Calendar'; import mapStoreToProps from '../../../redux/mapStoreToProps'; //Material-UI imports import { Typography } from '@material-ui/core'; // Basic class component structure for React with default state // value setup. When making a new component be sure to replace // the component name TemplateClass with the name for the new // component. class EventControl extends Component { render() { return ( <div className="adminPageDisplay"> <Typography variant="h4" gutterBottom> Calendar </Typography> <Calendar /> </div> ); } } export default connect(mapStoreToProps)(EventControl);
chanRoot/ruoyi-vue-pro
yudao-module-pay/yudao-module-pay-impl/src/main/java/cn/iocoder/yudao/module/pay/controller/admin/refund/PayRefundController.java
<gh_stars>1-10 package cn.iocoder.yudao.module.pay.controller.admin.refund; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ObjectUtil; import cn.iocoder.yudao.module.pay.controller.admin.refund.vo.*; import cn.iocoder.yudao.module.pay.convert.refund.PayRefundConvert; import cn.iocoder.yudao.module.pay.dal.dataobject.merchant.PayAppDO; import cn.iocoder.yudao.module.pay.dal.dataobject.merchant.PayMerchantDO; import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderDO; import cn.iocoder.yudao.module.pay.dal.dataobject.refund.PayRefundDO; import cn.iocoder.yudao.module.pay.service.merchant.PayAppService; import cn.iocoder.yudao.module.pay.service.merchant.PayMerchantService; import cn.iocoder.yudao.module.pay.service.order.PayOrderService; import cn.iocoder.yudao.module.pay.service.refund.PayRefundService; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.framework.pay.core.enums.PayChannelEnum; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT; @Api(tags = "管理后台 - 退款订单") @RestController @RequestMapping("/pay/refund") @Validated public class PayRefundController { @Resource private PayRefundService refundService; @Resource private PayMerchantService merchantService; @Resource private PayAppService appService; @Resource private PayOrderService orderService; @GetMapping("/get") @ApiOperation("获得退款订单") @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class) @PreAuthorize("@ss.hasPermission('pay:refund:query')") public CommonResult<PayRefundDetailsRespVO> getRefund(@RequestParam("id") Long id) { PayRefundDO refund = refundService.getRefund(id); if (ObjectUtil.isNull(refund)) { return success(new PayRefundDetailsRespVO()); } PayMerchantDO merchantDO = merchantService.getMerchant(refund.getMerchantId()); PayAppDO appDO = appService.getApp(refund.getAppId()); PayChannelEnum channelEnum = PayChannelEnum.getByCode(refund.getChannelCode()); PayOrderDO orderDO = orderService.getOrder(refund.getOrderId()); PayRefundDetailsRespVO refundDetail = PayRefundConvert.INSTANCE.refundDetailConvert(refund); refundDetail.setMerchantName(ObjectUtil.isNotNull(merchantDO) ? merchantDO.getName() : "未知商户"); refundDetail.setAppName(ObjectUtil.isNotNull(appDO) ? appDO.getName() : "未知应用"); refundDetail.setChannelCodeName(ObjectUtil.isNotNull(channelEnum) ? channelEnum.getName() : "未知渠道"); refundDetail.setSubject(orderDO.getSubject()); return success(refundDetail); } @GetMapping("/page") @ApiOperation("获得退款订单分页") @PreAuthorize("@ss.hasPermission('pay:refund:query')") public CommonResult<PageResult<PayRefundPageItemRespVO>> getRefundPage(@Valid PayRefundPageReqVO pageVO) { PageResult<PayRefundDO> pageResult = refundService.getRefundPage(pageVO); if (CollectionUtil.isEmpty(pageResult.getList())) { return success(new PageResult<>(pageResult.getTotal())); } // 处理商户ID数据 Map<Long, PayMerchantDO> merchantMap = merchantService.getMerchantMap( CollectionUtils.convertList(pageResult.getList(), PayRefundDO::getMerchantId)); // 处理应用ID数据 Map<Long, PayAppDO> appMap = appService.getAppMap( CollectionUtils.convertList(pageResult.getList(), PayRefundDO::getAppId)); List<PayRefundPageItemRespVO> list = new ArrayList<>(pageResult.getList().size()); pageResult.getList().forEach(c -> { PayMerchantDO merchantDO = merchantMap.get(c.getMerchantId()); PayAppDO appDO = appMap.get(c.getAppId()); PayChannelEnum channelEnum = PayChannelEnum.getByCode(c.getChannelCode()); PayRefundPageItemRespVO item = PayRefundConvert.INSTANCE.pageItemConvert(c); item.setMerchantName(ObjectUtil.isNotNull(merchantDO) ? merchantDO.getName() : "未知商户"); item.setAppName(ObjectUtil.isNotNull(appDO) ? appDO.getName() : "未知应用"); item.setChannelCodeName(ObjectUtil.isNotNull(channelEnum) ? channelEnum.getName() : "未知渠道"); list.add(item); }); return success(new PageResult<>(list, pageResult.getTotal())); } @GetMapping("/export-excel") @ApiOperation("导出退款订单 Excel") @PreAuthorize("@ss.hasPermission('pay:refund:export')") @OperateLog(type = EXPORT) public void exportRefundExcel(@Valid PayRefundExportReqVO exportReqVO, HttpServletResponse response) throws IOException { List<PayRefundDO> list = refundService.getRefundList(exportReqVO); if (CollectionUtil.isEmpty(list)) { ExcelUtils.write(response, "退款订单.xls", "数据", PayRefundExcelVO.class, new ArrayList<>()); } // 处理商户ID数据 Map<Long, PayMerchantDO> merchantMap = merchantService.getMerchantMap( CollectionUtils.convertList(list, PayRefundDO::getMerchantId)); // 处理应用ID数据 Map<Long, PayAppDO> appMap = appService.getAppMap( CollectionUtils.convertList(list, PayRefundDO::getAppId)); List<PayRefundExcelVO> excelDatum = new ArrayList<>(list.size()); // 处理商品名称数据 Map<Long, PayOrderDO> orderMap = orderService.getOrderSubjectMap( CollectionUtils.convertList(list, PayRefundDO::getOrderId)); list.forEach(c -> { PayMerchantDO merchantDO = merchantMap.get(c.getMerchantId()); PayAppDO appDO = appMap.get(c.getAppId()); PayChannelEnum channelEnum = PayChannelEnum.getByCode(c.getChannelCode()); PayRefundExcelVO excelItem = PayRefundConvert.INSTANCE.excelConvert(c); excelItem.setMerchantName(ObjectUtil.isNotNull(merchantDO) ? merchantDO.getName() : "未知商户"); excelItem.setAppName(ObjectUtil.isNotNull(appDO) ? appDO.getName() : "未知应用"); excelItem.setChannelCodeName(ObjectUtil.isNotNull(channelEnum) ? channelEnum.getName() : "未知渠道"); excelItem.setSubject(orderMap.get(c.getOrderId()).getSubject()); excelDatum.add(excelItem); }); // 导出 Excel ExcelUtils.write(response, "退款订单.xls", "数据", PayRefundExcelVO.class, excelDatum); } }
legendmohe/LEHomeMobile_android
app/src/main/java/my/home/lehome/helper/NetworkHelper.java
<gh_stars>10-100 /* * 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 my.home.lehome.helper; import android.annotation.TargetApi; import android.os.Build; import org.apache.http.conn.util.InetAddressUtils; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.List; /** * http://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the- * device * <p/> * Needed manifest permissions : * <p/> * <uses-permission android:name="android.permission.INTERNET" /> * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> * <p/> * Test functions : * <p/> * Utils.getMACAddress("wlan0"); Utils.getMACAddress("eth0"); * Utils.getIPAddress(true); // IPv4 Utils.getIPAddress(false); // IPv6 */ public class NetworkHelper { /** * Returns MAC address of the given interface name. * * @param interfaceName eth0, wlan0 or NULL=use first interface * @return mac address or empty string */ @TargetApi(Build.VERSION_CODES.GINGERBREAD) public static String getMACAddress(String interfaceName) { if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { throw new IllegalStateException( "You use getMACAddress() only after API " + Build.VERSION_CODES.GINGERBREAD); } try { List<NetworkInterface> interfaces = Collections .list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { if (interfaceName != null) { if (!intf.getName().equalsIgnoreCase(interfaceName)) continue; } byte[] mac = intf.getHardwareAddress(); if (mac == null) return ""; StringBuilder buf = new StringBuilder(); for (int idx = 0; idx < mac.length; idx++) buf.append(String.format("%02X:", mac[idx])); if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1); return buf.toString(); } } catch (SocketException e) { } // for now eat exceptions return ""; /* * try { // this is so Linux hack return * loadFileAsString("/sys/class/net/" +interfaceName + * "/address").toUpperCase().trim(); } catch (IOException ex) { return * null; } */ } /** * Get IP address from first non-localhost interface * * @param ipv4 true=return ipv4, false=return ipv6 * @return address or empty string */ public static String getIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections .list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf .getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { // drop ip6 port suffix int delim = sAddr.indexOf('%'); return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (SocketException e) { } // for now eat exceptions return ""; } }
sboldur/harvest-client
src/test/java/ch/aaap/harvestclient/impl/estimateMessage/EstimateMessagesApiCreateTest.java
package ch.aaap.harvestclient.impl.estimateMessage; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import ch.aaap.harvestclient.HarvestTest; import ch.aaap.harvestclient.api.EstimateMessagesApi; import ch.aaap.harvestclient.core.Harvest; import ch.aaap.harvestclient.domain.*; import ch.aaap.harvestclient.exception.RequestProcessingException; import util.ExistingData; import util.TestSetupUtil; @HarvestTest public class EstimateMessagesApiCreateTest { private static final MessageRecipient testRecipient = ImmutableMessageRecipient.of("Marco", TestSetupUtil.getDevNullEmail()); private static final Harvest harvest = TestSetupUtil.getAdminAccess(); private final EstimateMessagesApi api = harvest.estimateMessages(); private Estimate estimate; private EstimateMessage estimateMessage; private void refreshEstimate() { estimate = harvest.estimates().get(estimate); } @BeforeEach void beforeEach() { Estimate creationInfo = ImmutableEstimate.builder() .client(ExistingData.getInstance().getClientReference()) .build(); estimate = harvest.estimates().create(creationInfo); } @AfterEach void afterEach() { if (estimateMessage != null) { harvest.estimateMessages().delete(estimate, estimateMessage); estimateMessage = null; } if (estimate != null) { harvest.estimates().delete(estimate); estimate = null; } } @Test void createDefault() { EstimateMessage creationInfo = ImmutableEstimateMessage.builder() .addMessageRecipient(testRecipient) .build(); estimateMessage = api.create(estimate, creationInfo); assertThat(estimateMessage).isEqualToIgnoringNullFields(creationInfo); } @Test void createAllOptions() { EstimateMessage creationInfo = ImmutableEstimateMessage.builder() .addMessageRecipient(testRecipient) .subject("test subject") .body("This is the body") .sendMeACopy(true) // .eventType(EstimateMessage.EventType.SEND) .build(); estimateMessage = api.create(estimate, creationInfo); assertThat(estimateMessage).isEqualToComparingOnlyGivenFields(creationInfo, "subject", "body"); assertThat(estimateMessage.getMessageRecipients()).contains(testRecipient); assertThat(estimateMessage.getMessageRecipients()).hasSize(2); } @EnumSource(value = EstimateMessage.EventType.class, names = { "RE_OPEN", "VIEW", "INVOICE" }) @ParameterizedTest void cannot(EstimateMessage.EventType type) { assertThrows(RequestProcessingException.class, () -> api.markAs(estimate, type)); } @Test void accept() { EstimateMessage creationInfo = ImmutableEstimateMessage.builder() .addMessageRecipient(testRecipient) .subject("test subject") .body("This is the body") .sendMeACopy(true) .eventType(EstimateMessage.EventType.ACCEPT) .build(); estimateMessage = api.create(estimate, creationInfo); assertThat(estimateMessage).isEqualToComparingOnlyGivenFields(creationInfo, "subject", "body"); // refresh estimate estimate = harvest.estimates().get(estimate); assertThat(estimate.getAcceptedAt()).isNotNull(); assertThat(estimate.getState() == Estimate.State.ACCEPTED); } @Test void send() { EstimateMessage creationInfo = ImmutableEstimateMessage.builder() .addMessageRecipient(testRecipient) .subject("test subject") .body("This is the body") .sendMeACopy(true) .eventType(EstimateMessage.EventType.SEND) .build(); estimateMessage = api.create(estimate, creationInfo); assertThat(estimateMessage).isEqualToComparingOnlyGivenFields(creationInfo, "subject", "body"); // refresh estimate estimate = harvest.estimates().get(estimate); assertThat(estimate.getSentAt()).isNotNull(); assertThat(estimate.getState() == Estimate.State.OPEN); } @Test void SendAccept() { api.markAs(estimate, EstimateMessage.EventType.SEND); refreshEstimate(); assertThat(estimate.getSentAt()).isNotNull(); assertThat(estimate.getState() == Estimate.State.OPEN); api.markAs(estimate, EstimateMessage.EventType.ACCEPT); refreshEstimate(); assertThat(estimate.getAcceptedAt()).isNotNull(); assertThat(estimate.getState() == Estimate.State.ACCEPTED); } @Test void AcceptSendReAccept() { api.markAs(estimate, EstimateMessage.EventType.ACCEPT); refreshEstimate(); assertThat(estimate.getAcceptedAt()).isNotNull(); assertThat(estimate.getState() == Estimate.State.ACCEPTED); // sending directly will not work, we need to reopen the estimate assertThrows(RequestProcessingException.class, () -> api.markAs(estimate, EstimateMessage.EventType.SEND)); api.markAs(estimate, EstimateMessage.EventType.RE_OPEN); assertThat(estimate.getState() == Estimate.State.OPEN); api.markAs(estimate, EstimateMessage.EventType.SEND); refreshEstimate(); assertThat(estimate.getSentAt()).isNotNull(); assertThat(estimate.getAcceptedAt()).isNull(); api.markAs(estimate, EstimateMessage.EventType.ACCEPT); refreshEstimate(); assertThat(estimate.getAcceptedAt()).isNotNull(); assertThat(estimate.getState() == Estimate.State.ACCEPTED); } @Test void AcceptDecline() { EstimateMessage message = api.markAs(estimate, EstimateMessage.EventType.ACCEPT); // cannot decline accepted estimate assertThrows(RequestProcessingException.class, () -> api.markAs(estimate, EstimateMessage.EventType.DECLINE)); // deleting a message does not change the status api.delete(estimate, message); refreshEstimate(); assertThat(estimate.getAcceptedAt()).isNotNull(); assertThat(estimate.getState() == Estimate.State.ACCEPTED); // still cannot decline assertThrows(RequestProcessingException.class, () -> api.markAs(estimate, EstimateMessage.EventType.DECLINE)); } }
elukey/ores
ores/about.py
<reponame>elukey/ores __name__ = "ores" __version__ = "1.4.0" __author__ = "<NAME>" __author_email__ = "<EMAIL>" __description__ = "A webserver for hosting scorer models." __url__ = "https://github.com/wikimedia/ores" __license__ = "MIT"
jacadcaps/webkitty
Source/WebInspectorUI/UserInterface/Models/CSSRule.js
/* * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ WI.CSSRule = class CSSRule extends WI.Object { constructor(nodeStyles, ownerStyleSheet, id, type, sourceCodeLocation, selectorText, selectors, matchedSelectorIndices, style, groupings) { super(); console.assert(nodeStyles); this._nodeStyles = nodeStyles; this._ownerStyleSheet = ownerStyleSheet || null; this._id = id || null; this._type = type || null; this._initialState = null; this.update(sourceCodeLocation, selectorText, selectors, matchedSelectorIndices, style, groupings, true); } // Public get ownerStyleSheet() { return this._ownerStyleSheet; } get id() { return this._id; } get type() { return this._type; } get initialState() { return this._initialState; } get sourceCodeLocation() { return this._sourceCodeLocation; } get selectors() { return this._selectors; } get matchedSelectorIndices() { return this._matchedSelectorIndices; } get style() { return this._style; } get groupings() { return this._groupings; } get editable() { return !!this._id && this._type !== WI.CSSStyleSheet.Type.UserAgent; } get selectorText() { return this._selectorText; } setSelectorText(selectorText) { console.assert(this.editable); if (!this.editable) return Promise.reject(); return this._nodeStyles.changeRuleSelector(this, selectorText).then(this._selectorResolved.bind(this)); } update(sourceCodeLocation, selectorText, selectors, matchedSelectorIndices, style, groupings) { sourceCodeLocation = sourceCodeLocation || null; selectorText = selectorText || ""; selectors = selectors || []; matchedSelectorIndices = matchedSelectorIndices || []; style = style || null; groupings = groupings || []; if (this._style) this._style.ownerRule = null; this._sourceCodeLocation = sourceCodeLocation; this._selectorText = selectorText; this._selectors = selectors; this._matchedSelectorIndices = matchedSelectorIndices; this._style = style; this._groupings = groupings; if (this._style) this._style.ownerRule = this; } isEqualTo(rule) { if (!rule) return false; return Object.shallowEqual(this._id, rule.id); } // Protected get nodeStyles() { return this._nodeStyles; } // Private // This method only needs to be called for CSS rules that don't match the selected DOM node. // CSS rules that match the selected DOM node get updated by WI.DOMNodeStyles.prototype._parseRulePayload. _selectorResolved(rulePayload) { if (!rulePayload) return; let selectorText = rulePayload.selectorList.text; if (selectorText === this._selectorText) return; let selectors = WI.DOMNodeStyles.parseSelectorListPayload(rulePayload.selectorList); let sourceCodeLocation = null; let sourceRange = rulePayload.selectorList.range; if (sourceRange) { sourceCodeLocation = WI.DOMNodeStyles.createSourceCodeLocation(rulePayload.sourceURL, { line: sourceRange.startLine, column: sourceRange.startColumn, documentNode: this._nodeStyles.node.ownerDocument, }); } if (this._ownerStyleSheet) { if (!sourceCodeLocation && sourceRange) sourceCodeLocation = this._ownerStyleSheet.createSourceCodeLocation(sourceRange.startLine, sourceRange.startColumn); sourceCodeLocation = this._ownerStyleSheet.offsetSourceCodeLocation(sourceCodeLocation); } this.update(sourceCodeLocation, selectorText, selectors, [], this._style, this._groupings); } };
tommmyy/ramda-extension
packages/ramda-extension/src/__tests__/splitByNonAlphaNumeric-test.js
import { splitByNonAlphaNumeric } from '../'; describe('splitByNonAlphaNumeric', () => { describe('should split string by non-alphanumeric characters', () => { const splitByNonAlphaNumericUtil = (str, result) => it(`${str} to be ${result}`, () => expect(splitByNonAlphaNumeric(str)).toEqual(result)); splitByNonAlphaNumericUtil('h e.l//l o wo.../r8****ld', [ 'h', 'e', 'l', 'l', 'o', 'wo', 'r8', 'ld', ]); }); });
onkore/open2ch_ngword
src/commands/abornCommand.js
<reponame>onkore/open2ch_ngword import getStatesFromChromeStorage from '../storage' import { nodeListToArray, getThreadComments } from '../util' const isNgComment = (comment, ngword) => { return !!comment.textContent.match(ngword) } const filterThreadComments = results => { const [states, comments] = results comments.forEach(comment => { states.forEach(state => { if (isNgComment(comment, state.ngword)) comment.dataset.ngword = state.ngword }) }) return comments.filter(c => c.hasAttribute('data-ngword')) } const debugMessage = (filtered) => { console.log(`filtered: ${filtered.length}`) console.log(filtered) } export const abornNodeCommand = (nodes) => { return Promise.all([getStatesFromChromeStorage(), nodes]) .then(filterThreadComments) .then(debugMessage) .catch(e => console.log(e)) } export const abornPageCommand = (query = '.thread > dl') => { return Promise.all([getStatesFromChromeStorage(), getThreadComments(query)]) .then(filterThreadComments) .then(debugMessage) .catch(e => console.log(e)) } export const abornPageByNGWordCommand = (ngword) => { return Promise.all([[{ ngword }], getThreadComments()]) .then(filterThreadComments) .then(debugMessage) .catch(e => console.log(e)) }
qualitesys/openssl-1
docs/QcrReportFile01File574detailjsondata.js
console.log('leListeStr main01 start json de data maDataBlocs'); var maDataBlocs = { "data00" : { "fic1" : "./qc/crypto/ocsp/ocsp_http.c.html" , "texte" : "File crypto/ocsp/ocsp_http.c 30 rule violations " , "fic2" : "./qc/crypto/ocsp/ocsp_http.c.xml" , "fic3" : "" } , "data01" : [ ] , "data02" : [ ] , "data03" : [ ] , "data04" : [ ] , "data05" : [ ] , "data06" : [ ] , "data07" : [ ] , "data08" : [ ] , "data11" : [ ] , "data14" : [ ] , "data13a" : [ { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000012" , "c3" : "The condition expression is invariable, always true or false" , "c4" : "21" }} , { "ligne" : { "c1" : "BLOCKER" , "c2" : "QC-CPP000018" , "c3" : "A suspicious bitwise expression is compared to a numerical expression" , "c4" : "3" }} , { "ligne" : { "c1" : "MAJOR" , "c2" : "QC-CPP000007" , "c3" : "goto statement" , "c4" : "3" }} , { "ligne" : { "c1" : "MAJOR" , "c2" : "QC-CPP000014" , "c3" : "A pointer is defined but not initialized" , "c4" : "3" }} ] , "data13b" : [ { "ligne" : { "c1" : "01188" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1188" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01188] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "01193" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1193" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01193] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "01218" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1218" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01218] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "01222" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1222" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[01222] Suspicious mix of Bitwise and Literal expressions in (__size|__n)&gt;=(((size_t )1)&lt;&lt;(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "01225" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1225" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01225] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "01250" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1250" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01250] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "01254" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1254" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[01254] Suspicious mix of Bitwise and Literal expressions in (__size|__n)&gt;=(((size_t )1)&lt;&lt;(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "01258" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1258" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[01258] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "01266" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#1266" , "c2" : "BLOCKER" , "c3" : "QC-CPP000018[01266] Suspicious mix of Bitwise and Literal expressions in (__size|__n)&lt;(((size_t )1)&lt;&lt;(8 * sizeof (size_t)/2))" }} , { "ligne" : { "c1" : "02312" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2312" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[02312] The pointer __p is declared but not initialized" }} , { "ligne" : { "c1" : "02475" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2475" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02475] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "02502" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2502" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02502] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "02506" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2506" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02506] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "02528" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2528" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02528] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "02528" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2528" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02528] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "02552" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2552" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02552] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "02558" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2558" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02558] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "02583" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2583" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02583] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "02587" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#2587" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[02587] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "08426" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#8426" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[08426] The expression 2&gt;1 is invariable" }} , { "ligne" : { "c1" : "12862" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12862" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[12862] The expression 1 is invariable, always true" }} , { "ligne" : { "c1" : "12872" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12872" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[12872] goto statement jump to err" }} , { "ligne" : { "c1" : "12879" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12879" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[12879] The expression 1 is invariable, always true" }} , { "ligne" : { "c1" : "12880" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12880" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[12880] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "12880" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12880" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[12880] The expression 0 is invariable, always false" }} , { "ligne" : { "c1" : "12881" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12881" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[12881] goto statement jump to err" }} , { "ligne" : { "c1" : "12887" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12887" , "c2" : "BLOCKER" , "c3" : "QC-CPP000012[12887] The expression 'application/ocsp-request' is invariable" }} , { "ligne" : { "c1" : "12890" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12890" , "c2" : "MAJOR" , "c3" : "QC-CPP000007[12890] goto statement jump to err" }} , { "ligne" : { "c1" : "12909" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12909" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[12909] The pointer ctx is declared but not initialized" }} , { "ligne" : { "c1" : "12910" , "c1link" : "./qc/crypto/ocsp/ocsp_http.c.html#12910" , "c2" : "MAJOR" , "c3" : "QC-CPP000014[12910] The pointer mem is declared but not initialized" }} ] }; console.log('leListeStr 99 main end');
waconley/ldaptive
beans/src/main/java/org/ldaptive/beans/reflect/AbstractAttributeValueMutator.java
<reponame>waconley/ldaptive<gh_stars>0 /* See LICENSE for licensing and NOTICE for copyright. */ package org.ldaptive.beans.reflect; import org.ldaptive.SortBehavior; import org.ldaptive.beans.AttributeValueMutator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base implementation of a {@link AttributeValueMutator}. Uses a {@link ReflectionTranscoder} for mutating values. * * @author <NAME> */ public abstract class AbstractAttributeValueMutator implements AttributeValueMutator { /** Logger for this class. */ protected final Logger logger = LoggerFactory.getLogger(getClass()); /** Name of the attribute. */ private final String attributeName; /** Whether this attribute is binary. */ private final boolean attributeBinary; /** Sort behavior of this attribute. */ private final SortBehavior attributeSortBehavior; /** Transcoder for modifying this attribute. */ private final ReflectionTranscoder valueTranscoder; /** * Creates a new abstract attribute value mutator. * * @param name of the attribute * @param binary whether this attribute is binary * @param sortBehavior how to sort this attribute * @param transcoder for mutating the attribute */ public AbstractAttributeValueMutator( final String name, final boolean binary, final SortBehavior sortBehavior, final ReflectionTranscoder transcoder) { attributeName = name; attributeBinary = binary; attributeSortBehavior = sortBehavior; valueTranscoder = transcoder; } @Override public String getName() { return attributeName; } @Override public boolean isBinary() { return attributeBinary; } @Override public SortBehavior getSortBehavior() { return attributeSortBehavior; } /** * Returns the reflection transcoder. * * @return reflection transcoder */ protected ReflectionTranscoder getReflectionTranscoder() { return valueTranscoder; } }
fosterrath-mila/myia
debug/steps.py
from myia.pipeline.steps import ( step_cconv as cconv, step_compile as export, step_debug_opt as debug_opt, step_infer as infer, step_opt as opt, step_opt2 as opt2, step_parse as parse, step_resolve as resolve, step_simplify_types as simplify_types, step_specialize as specialize, step_validate as validate, ) from myia.utils import Partial standard = [ parse, resolve, infer, specialize, simplify_types, opt, opt2, validate, cconv, export ] _debug_opt = [ parse, resolve, infer, specialize, simplify_types, debug_opt, opt2, validate, cconv, export ] _bang_parse = standard[:standard.index(parse) + 1] _bang_resolve = standard[:standard.index(resolve) + 1] _bang_infer = standard[:standard.index(infer) + 1] _bang_specialize = standard[:standard.index(specialize) + 1] _bang_simplify_types = standard[:standard.index(simplify_types) + 1] _bang_opt = standard[:standard.index(opt) + 1] _bang_opt2 = standard[:standard.index(opt2) + 1] _bang_validate = standard[:standard.index(validate) + 1] _bang_cconv = standard[:standard.index(cconv) + 1] _bang_export = standard[:standard.index(export) + 1] _bang_debug_opt = _debug_opt[:_debug_opt.index(debug_opt) + 1] def _adjust(): for name, g in globals().items(): if isinstance(g, Partial): g._name = name _adjust()
cschulc/JiraRestService
src/main/java/com/github/cschulc/jirarestservice/services/SystemRestService.java
<gh_stars>1-10 /* * Copyright (c) 2019. cschulc (https://github.com/cschulc) * * 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.github.cschulc.jirarestservice.services; import com.github.cschulc.jirarestservice.domain.AttachmentMetaBean; import com.github.cschulc.jirarestservice.domain.IssuetypeBean; import com.github.cschulc.jirarestservice.domain.PriorityBean; import com.github.cschulc.jirarestservice.domain.StatusBean; import com.github.cschulc.jirarestservice.domain.avatar.AvatarBean; import com.github.cschulc.jirarestservice.domain.avatar.AvatarType; import com.github.cschulc.jirarestservice.domain.avatar.SystemAvatarsBean; import com.github.cschulc.jirarestservice.domain.field.CreateFieldBean; import com.github.cschulc.jirarestservice.domain.field.FieldBean; import com.github.cschulc.jirarestservice.domain.system.ConfigurationBean; import java.util.List; import java.util.concurrent.Future; public interface SystemRestService { /** * Return the ConfigurationBean of the remote Jira Instanz * * @return ConfigurationBean */ Future<ConfigurationBean> getConfiguration(); /** * Returns a list of all issue types visible to the connected client. * * @return list of issue types */ Future<List<IssuetypeBean>> getIssueTypes(); /** * Returns a list of all statuses. * * @return list of statuses */ Future<List<StatusBean>> getStates(); /** * Returns a List of all PriorityBean Object from the Remote Jira. * * @return A {@link List} of {@link PriorityBean} */ Future<List<PriorityBean>> getPriorities(); /** * Return a List of all FieldEnum configure in Jira, standard and custom * * @return a List of FieldEnum */ Future<List<FieldBean>> getAllFields(); /** * Return all Custom FieldEnum configure in the Jira * * @return a List of FieldEnum */ Future<List<FieldBean>> getAllCustomFields(); /** * Return a Custom FieldEnum by Id * */ Future<FieldBean> getCustomFieldById(String id); /** * Get the AttachmentBean MetaBean Information for the jira instanz * * @return AttachmentMetaBean */ Future<AttachmentMetaBean> getAttachmentMeta(); /** * Creates a Custom FieldEnum * * @param fieldBean The CreateFieldBean with the create Informations * @return The created FieldEnum as FieldEnum */ Future<FieldBean> createCustomField(CreateFieldBean fieldBean); /** * Returns all system avatars of the given type. * * @param avatarType The {@link AvatarType} * @return SystemAvatarsBean with a List of {@link AvatarBean} */ Future<SystemAvatarsBean> getAllSystemAvatars(AvatarType avatarType); }
gridgentoo/PSTL
pstl/src/main/scala/com/microfocus/pstl/QueryDaemon.scala
/* * (c) Copyright [2018] Micro Focus or one of its affiliates. * * 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.microfocus.pstl import java.util.UUID import java.util.concurrent.TimeUnit import scala.collection.JavaConverters._ import scala.concurrent.duration._ import akka.actor.{Actor, ActorLogging, Timers} import org.apache.spark.sql.streaming.StreamingQueryListener._ import com.microfocus.pstl.utils.ExponentialBackoff import scala.util.control.NonFatal object QueryDaemon { case object Heartbeat case object HeartbeatKey case object RestartQuery case object RestartQueryKey } class QueryDaemon(session: JobSession) extends Actor with Timers with ActorJobSettings with ActorLogging { import QueryDaemon._ private var batchId: Long = -1L private var queryId: UUID = _ private var queryName: String = _ private var queryOptions: QueryOptions = _ private var queryMetrics: QueryDaemonMetrics = _ private var queryRestarts: Int = 0 private val heartbeatInterval: FiniteDuration = 100.milliseconds override def postStop(): Unit = { clearMetrics() } override def receive: Receive = { case e: QueryStartedEvent => onQueryStarted(e) case e: QueryProgressEvent => onQueryProgress(e) case e: QueryTerminatedEvent => onQueryTerminated(e) case RestartQuery => onRestartQuery() case Heartbeat => onHeartbeat() } private def onQueryStarted(e: QueryStartedEvent): Unit = { this.queryId = e.id this.queryName = e.name this.queryOptions = session.queryOptions(e.name) this.queryMetrics = new QueryDaemonMetrics(session.jobId, e.name) this.queryMetrics.upGauge.set(1d) timers.startPeriodicTimer( HeartbeatKey, Heartbeat, heartbeatInterval) } private def onQueryProgress(e: QueryProgressEvent): Unit = { this.queryRestarts = 0 // only increment batch id if we processed new data, progress events show up // when a streaming query is "idle", so incrementing blindly can indicate // we are processing batches when we arent (eg. batch id is same in multiple // progress events while no new data is available from source). if(e.progress.batchId > batchId) { this.batchId = e.progress.batchId this.queryMetrics.batchCounter.inc() } this.queryMetrics.batchGauge.set(e.progress.batchId) this.queryMetrics.inputRowCounter.inc(e.progress.numInputRows) this.queryMetrics.inputRowGauge.set(e.progress.inputRowsPerSecond) this.queryMetrics.processedRowGauge.set(e.progress.processedRowsPerSecond) e.progress.durationMs.asScala.foreach { case (stageId, durationMs) => val durationSec = durationMs / 1000d this.queryMetrics.executionTimeCounter(stageId).inc(durationSec) } } private def onQueryTerminated(e: QueryTerminatedEvent): Unit = { this.queryMetrics.upGauge.set(0d) e.exception.either( some = scheduleRestart, none = shutdownGracefully()) } private def scheduleRestart(exception: String): Unit = { val delay = ExponentialBackoff( restartCount = queryRestarts, minBackoff = queryOptions.retryMinBackoff.getOrElse(jobSettings.RetryMinBackoff), maxBackoff = queryOptions.retryMaxBackoff.getOrElse(jobSettings.RetryMaxBackoff), randomFactor = queryOptions.retryRandomFactor.getOrElse(jobSettings.RetryRandomFactor)) timers.startSingleTimer( RestartQueryKey, RestartQuery, delay) this.queryMetrics.restartTimerGauge.set(delay.toUnit(TimeUnit.SECONDS)) } private def shutdownGracefully(): Unit = { context.stop(self) } private def onRestartQuery(): Unit = { this.queryRestarts += 1 this.queryMetrics.restartCounter.inc() try { // blocking op on spark which never triggers a QueryStartedEvent -> QueryTerminatedEvent // if it fails during initialization of underlying DAG and relevant resources. // todo: we need to make job session more explicit so we can deal with this via supervision // and custom exception types rather than needing specific error handling here. session.restart(queryName) } catch { case NonFatal(e) => log.error(e, "query restart failed {}", this) scheduleRestart(e.getMessage) } } private def onHeartbeat(): Unit = { val retryTimer = queryMetrics.restartTimerGauge.get() val heartbeatSecondsElapsed = heartbeatInterval.toUnit(TimeUnit.SECONDS) queryMetrics.restartTimerGauge.set(Math.max(0d, retryTimer - heartbeatSecondsElapsed)) } private def clearMetrics(): Unit = Option(queryMetrics).foreach { m => m.upGauge.set(0d) m.restartTimerGauge.set(0d) } override def toString: String = { s"[batchId=$batchId, queryId=$queryId, queryName=$queryName]" } }
saqib364/hh
resource_server/src/main/java/com/commerce/backend/model/entity/ProductVariant.java
package com.commerce.backend.model.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import javax.persistence.*; @Entity @Table(name = "product_variant") @Getter @Setter @NoArgsConstructor @ToString public class ProductVariant { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @ManyToOne @JoinColumn(name = "product_id") private Product product; @ManyToOne @JoinColumn(name = "color_id") private Color color; @Column(name = "width") private String width; @Column(name = "height") private String height; @Column(name = "composition") private String composition; @Column(name = "price") private Float price; @Column(name = "cargo_price") private Float cargoPrice; @Column(name = "tax_percent") private Float taxPercent; @Column(name = "image") private String image; @Column(name = "thumb") private String thumb; @Column(name = "stock") private Integer stock; @Column(name = "sell_count") private Integer sellCount; @Column(name = "live") private Integer live; }
skyscooby/sahasrahbot
alttprbot/alttprgen/randomizer/__init__.py
from .aosr import roll_aosr from .ffr import roll_ffr from .smb3r import roll_smb3r from .z1r import roll_z1r from .smdash import roll_smdash from .ootr import roll_ootr from .bingosync import BingoSync
ShurtanMSC/ShurtanMSC
src/main/java/javafish/clients/opc/lang/Translate.java
package javafish.clients.opc.lang; import javafish.clients.opc.property.PropertyLoader; import java.util.Locale; import java.util.MissingResourceException; import java.util.Properties; import java.util.ResourceBundle; /** * Basic translator is based on ResourceBundle. */ public class Translate { private static ResourceBundle resourceBundle; private static Properties props; private static Locale locale; static { // load properties props = PropertyLoader.loadProperties(Translate.class.getName()); // set current locale String lang = props.getProperty("locale"); if (lang == null || lang.trim().equals("")) { locale = Locale.getDefault(); } else { locale = new Locale(props.getProperty("locale")); } // prepare lang resources resourceBundle = ResourceBundle.getBundle(props.getProperty("resource"), locale); } /** * Get translate String * * @param key String * @return translate word String, if not exist: return NULL */ public static String getString(String key) { try { return resourceBundle.getString(key); } catch (MissingResourceException e) { return null; } } /** * Get current locale * * @return locale Locale */ public static Locale getCurrentLocale() { return locale; } }
DYefremov/H2dbAdmin
src/main/java/by/post/data/ConditionRow.java
<filename>src/main/java/by/post/data/ConditionRow.java package by.post.data; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; /** *This class used in ViewCreationDialogController as data model * * @author <NAME> */ public class ConditionRow { private SimpleStringProperty name; private SimpleStringProperty condition; private SimpleBooleanProperty selected; public ConditionRow() { this.name = new SimpleStringProperty(); this.condition = new SimpleStringProperty(); this.selected = new SimpleBooleanProperty(false); } public ConditionRow(String name, String condition, boolean selected) { this.name = new SimpleStringProperty(name); this.condition = new SimpleStringProperty(condition); this.selected = new SimpleBooleanProperty(selected); } public String getName() { return name.get(); } public SimpleStringProperty nameProperty() { return name; } public void setName(String name) { this.name.set(name); } public String getCondition() { return condition.get(); } public SimpleStringProperty conditionProperty() { return condition; } public void setCondition(String condition) { this.condition.set(condition); } public boolean isSelected() { return selected.get(); } public SimpleBooleanProperty selectedProperty() { return selected; } public void setSelected(boolean selected) { this.selected.set(selected); } @Override public String toString() { return "ConditionRow{" + "name=" + name + ", condition=" + condition + ", selected=" + selected + '}'; } }
bobmcwhirter/drools
drools-core/src/main/java/org/drools/common/InternalRuleBase.java
package org.drools.common; /* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.Map; import java.util.List; import org.drools.FactException; import org.drools.FactHandle; import org.drools.RuleBase; import org.drools.RuleBaseConfiguration; import org.drools.StatefulSession; import org.drools.process.core.Process; import org.drools.reteoo.Rete; import org.drools.reteoo.ReteooWorkingMemory; import org.drools.rule.CompositeClassLoader; import org.drools.rule.MapBackedClassLoader; import org.drools.rule.Package; import org.drools.rule.TypeDeclaration; import org.drools.spi.FactHandleFactory; import org.drools.spi.PropagationContext; public interface InternalRuleBase extends RuleBase { /** * @return the id */ public String getId(); public int nextWorkingMemoryCounter(); public FactHandleFactory newFactHandleFactory(); public FactHandleFactory newFactHandleFactory(int id, long counter) throws IOException ; public Map getGlobals(); public Map getAgendaGroupRuleTotals(); public RuleBaseConfiguration getConfiguration(); public Package getPackage(String name); public Map getPackagesMap(); void disposeStatefulSession(StatefulSession statefulSession); void executeQueuedActions(); /** * Assert a fact object. * * @param handle * The handle. * @param object * The fact. * @param workingMemory * The working-memory. * * @throws FactException * If an error occurs while performing the assertion. */ public void assertObject(FactHandle handle, Object object, PropagationContext context, InternalWorkingMemory workingMemory) throws FactException; /** * Retract a fact object. * * @param handle * The handle. * @param workingMemory * The working-memory. * * @throws FactException * If an error occurs while performing the retraction. */ public void retractObject(FactHandle handle, PropagationContext context, ReteooWorkingMemory workingMemory) throws FactException; public CompositeClassLoader getRootClassLoader(); public Rete getRete(); public InternalWorkingMemory[] getWorkingMemories(); public Process getProcess(String id); /** * Returns true if clazz represents an Event class. False otherwise. * * @param clazz * @return */ public boolean isEvent( Class<?> clazz ); public int getNodeCount(); /** * Returns the type declaration associated to the given class * * @param clazz * @return */ public TypeDeclaration getTypeDeclaration(Class<?> clazz); /** * Creates and allocates a new partition ID for this rulebase * * @return */ public RuleBasePartitionId createNewPartitionId(); /** * Return the list of Partition IDs for this rulebase * @return */ List<RuleBasePartitionId> getPartitionIds(); }
andrewschmidt-a/azure-iot-platform-dotnet
src/webui/src/components/pages/devices/flyouts/createDeviceQuery/createDeviceQuery.container.js
<filename>src/webui/src/components/pages/devices/flyouts/createDeviceQuery/createDeviceQuery.container.js // Copyright (c) Microsoft. All rights reserved. import { connect } from 'react-redux'; import { withNamespaces } from 'react-i18next'; import { CreateDeviceQuery } from './createDeviceQuery'; import { epics as devicesEpics } from 'store/reducers/devicesReducer'; import { redux as appRedux, epics as appEpics, getActiveDeviceQueryConditions, getActiveDeviceGroupConditions, getActiveDeviceGroup } from 'store/reducers/appReducer'; const mapStateToProps = state => ({ activeDeviceQueryConditions: getActiveDeviceQueryConditions(state), activeDeviceGroupConditions: getActiveDeviceGroupConditions(state), activeDeviceGroup: getActiveDeviceGroup(state) }); const mapDispatchToProps = dispatch => ({ closeFlyout: () => dispatch(appRedux.actions.setCreateDeviceQueryFlyoutStatus(false)), setActiveDeviceQueryConditions: queryConditions => dispatch(appRedux.actions.setActiveDeviceQueryConditions(queryConditions)), insertDeviceGroup: (deviceGroup) => dispatch(appRedux.actions.insertDeviceGroups([deviceGroup])), logEvent: diagnosticsModel => dispatch(appEpics.actions.logEvent(diagnosticsModel)) }); export const CreateDeviceQueryContainer = withNamespaces()(connect(mapStateToProps, mapDispatchToProps)(CreateDeviceQuery));
edumi538/bopepo
src/main/java/com/github/braully/boleto/testeBradescoBoleto.java
/* * Copyright 2019 Projeto JRimum. * * 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.github.braully.boleto; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import org.jrimum.bopepo.BancosSuportados; import org.jrimum.domkee.banco.Agencia; import org.jrimum.domkee.banco.Carteira; import org.jrimum.domkee.banco.Cedente; import org.jrimum.domkee.banco.ContaBancaria; import org.jrimum.domkee.banco.NumeroDaConta; import org.jrimum.domkee.banco.Sacado; import org.jrimum.domkee.banco.SacadorAvalista; import org.jrimum.domkee.banco.TipoDeTitulo; import org.jrimum.domkee.banco.Titulo; import org.jrimum.domkee.banco.Titulo.Aceite; import org.jrimum.domkee.pessoa.CEP; import org.jrimum.domkee.pessoa.Endereco; import org.jrimum.domkee.pessoa.UnidadeFederativa; import org.jrimum.bopepo.Boleto; import org.jrimum.bopepo.view.BoletoViewer; /** * * @author root */ public class testeBradescoBoleto { public static void main(String[] args) { /* * INFORMANDO DADOS SOBRE O CEDENTE. */ Cedente cedente = new Cedente("PROJETO JRimum", "00.000.208/0001-00"); /* * INFORMANDO DADOS SOBRE O SACADO. */ Sacado sacado = new Sacado("JavaDeveloper Pronto Para Férias", "222.222.222-22"); // Informando o endereço do sacado. Endereco enderecoSac = new Endereco(); enderecoSac.setUF(UnidadeFederativa.RN); enderecoSac.setLocalidade("Natal"); enderecoSac.setCep(new CEP("59064-120")); enderecoSac.setBairro("Grande Centro"); enderecoSac.setLogradouro("Rua poeta dos programas"); enderecoSac.setNumero("1"); sacado.addEndereco(enderecoSac); /* * INFORMANDO DADOS SOBRE O SACADOR AVALISTA. */ SacadorAvalista sacadorAvalista = new SacadorAvalista("JRimum Enterprise", "00.000.000/0001-91"); // Informando o endereço do sacador avalista. Endereco enderecoSacAval = new Endereco(); enderecoSacAval.setUF(UnidadeFederativa.DF); enderecoSacAval.setLocalidade("Brasília"); enderecoSacAval.setCep(new CEP("59000-000")); enderecoSacAval.setBairro("Grande Centro"); enderecoSacAval.setLogradouro("Rua Eternamente Principal"); enderecoSacAval.setNumero("001"); sacadorAvalista.addEndereco(enderecoSacAval); /* * INFORMANDO OS DADOS SOBRE O TÍTULO. */ // Informando dados sobre a conta bancária do título. ContaBancaria contaBancaria = new ContaBancaria(BancosSuportados.BANCO_BRADESCO.create()); contaBancaria.setNumeroDaConta(new NumeroDaConta(123456, "0")); contaBancaria.setCarteira(new Carteira(30)); contaBancaria.setAgencia(new Agencia(1234, "1")); Titulo titulo = new Titulo(contaBancaria, sacado, cedente, sacadorAvalista); titulo.setNumeroDoDocumento("123456"); titulo.setNossoNumero("99345678912"); titulo.setDigitoDoNossoNumero("5"); titulo.setValor(BigDecimal.valueOf(0.23)); titulo.setDataDoDocumento(new Date()); titulo.setDataDoVencimento(new Date()); titulo.setTipoDeDocumento(TipoDeTitulo.DM_DUPLICATA_MERCANTIL); titulo.setAceite(Aceite.A); titulo.setDesconto(new BigDecimal(0.05)); titulo.setDeducao(BigDecimal.ZERO); titulo.setMora(BigDecimal.ZERO); titulo.setAcrecimo(BigDecimal.ZERO); titulo.setValorCobrado(BigDecimal.ZERO); /* * INFORMANDO OS DADOS SOBRE O BOLETO. */ Boleto boleto = new Boleto(titulo); boleto.setLocalPagamento("Pagável preferencialmente na Rede X ou em " + "qualquer Banco até o Vencimento."); boleto.setInstrucaoAoSacado("Senhor sacado, sabemos sim que o valor " + "cobrado não é o esperado, aproveite o DESCONTÃO!"); boleto.setInstrucao1("PARA PAGAMENTO 1 até Hoje não cobrar nada!"); boleto.setInstrucao2("PARA PAGAMENTO 2 até Amanhã Não cobre!"); boleto.setInstrucao3("PARA PAGAMENTO 3 até Depois de amanhã, OK, não cobre."); boleto.setInstrucao4("PARA PAGAMENTO 4 até 04/xx/xxxx de 4 dias atrás COBRAR O VALOR DE: R$ 01,00"); boleto.setInstrucao5("PARA PAGAMENTO 5 até 05/xx/xxxx COBRAR O VALOR DE: R$ 02,00"); boleto.setInstrucao6("PARA PAGAMENTO 6 até 06/xx/xxxx COBRAR O VALOR DE: R$ 03,00"); boleto.setInstrucao7("PARA PAGAMENTO 7 até xx/xx/xxxx COBRAR O VALOR QUE VOCÊ QUISER!"); boleto.setInstrucao8("APÓS o Vencimento, Pagável Somente na Rede X."); /* * GERANDO O BOLETO BANCÁRIO. */ // Instanciando um objeto "BoletoViewer", classe responsável pela // geração do boleto bancário. BoletoViewer boletoViewer = new BoletoViewer(boleto); // Gerando o arquivo. No caso o arquivo mencionado será salvo na mesma // pasta do projeto. Outros exemplos: // WINDOWS: boletoViewer.getAsPDF("C:/Temp/MeuBoleto.pdf"); // LINUX: boletoViewer.getAsPDF("/home/temp/MeuBoleto.pdf"); File arquivoPdf = boletoViewer.getPdfAsFile("MeuPrimeiroBoleto.pdf"); // Mostrando o boleto gerado na tela. mostreBoletoNaTela(arquivoPdf); } /** * Exibe o arquivo na tela. * * @param arquivoBoleto */ private static void mostreBoletoNaTela(File arquivoBoleto) { java.awt.Desktop desktop = java.awt.Desktop.getDesktop(); try { desktop.open(arquivoBoleto); } catch (IOException e) { e.printStackTrace(); } } }
AlexandreSuperCC/mysite_backend_public
src/main/java/com/ycao/mysite/utils/APIResponse.java
package com.ycao.mysite.utils; import lombok.Data; /** * api response after used * Created by ycao on 10/24 */ @Data public class APIResponse <T> { private String code; private T data; private String msg; private String token; private String userId; public APIResponse(String code) { this.code = code; } public APIResponse(String code, String msg) { this.code = code; this.msg = msg; } public APIResponse(String code, T data) { this.code = code; this.data = data; } public APIResponse(String code, T data,String msg) { this.code = code; this.data = data; this.msg = msg; } private static final String CODE_SUCCESS = "success"; private static final String CODE_FAIL = "fail"; public static APIResponse fail(String msg) { return new APIResponse(CODE_FAIL, msg); } public static APIResponse fail(Object data,String msg) { return new APIResponse(CODE_FAIL, data, msg); } public static APIResponse success() { return new APIResponse(CODE_SUCCESS); } public static APIResponse success(Object data){ return new APIResponse(CODE_SUCCESS,data); } public static APIResponse success(String msg){ return new APIResponse(CODE_SUCCESS,msg); } /** * used in home to get article * @param * @return */ public static APIResponse success(Object data,String msg){ return new APIResponse(CODE_SUCCESS,data,msg); } }
ZengineHQ/zengine-ui-react
src/api/atoms/Input/Input.test.js
import React from 'react'; import { fireEvent, render } from '@testing-library/react'; import { act } from 'react-dom/test-utils'; import Input from './Input'; test('Renders a input HTML tag', () => { const { container } = render(<Input/>); expect(container.getElementsByTagName('input')).toHaveProperty('length', 1); }); test('Renders a type text input by default', () => { const { container } = render(<Input/>); expect(container.firstChild).toHaveAttribute('type', 'text'); }); test('Renders correct input type when specified', () => { const { container } = render(<Input type="number"/>); expect(container.firstChild).toHaveAttribute('type', 'number'); }); test('Marks input as required when specified', () => { const { container } = render(<Input required={ true }/>); expect(container.firstChild).toHaveAttribute('required'); }); test('Sets aria-required attribute when required', () => { const { container } = render(<Input required={ true }/>); expect(container.firstChild).toHaveAttribute('aria-required', 'true'); }); test('Doesn\'t set aria-required attribute when not required', () => { const { container } = render(<Input required={ false }/>); expect(container.firstChild).not.toHaveAttribute('aria-required'); }); test('Marks input as disabled when specified', () => { const { container } = render(<Input disabled={ true }/>); expect(container.firstChild).toHaveAttribute('disabled'); }); test('Sets aria-disabled attribute when disabled', () => { const { container } = render(<Input disabled={ true }/>); expect(container.firstChild).toHaveAttribute('aria-disabled', 'true'); }); test('Marks input as readonly when specified', () => { const { container } = render(<Input readonly={ true }/>); expect(container.firstChild).toHaveAttribute('readonly'); }); test('Sets aria-readonly attribute when readonly', () => { const { container } = render(<Input readonly={ true }/>); expect(container.firstChild).toHaveAttribute('aria-readonly', 'true'); }); test('Sets input placeholder when specified', () => { const { container } = render(<Input placeholder="foo"/>); expect(container.firstChild).toHaveAttribute('placeholder', 'foo'); }); test('Sets input name when specified', () => { const { container } = render(<Input name="foo"/>); expect(container.firstChild).toHaveAttribute('name', 'foo'); }); test('Sets input id when specified', () => { const { container } = render(<Input name="foo" id="bar"/>); expect(container.firstChild).toHaveAttribute('id', 'bar'); }); test('Adds custom classes when specified', () => { const { container } = render(<Input classes="foo bar baz"/>); expect(container.firstChild).toHaveClass('foo bar baz'); }); test('Fires custom onChange handler if specified', async () => { const mock = jest.fn(); const { container } = render(<Input name="foo" onChange={ mock }/>); const input = container.getElementsByTagName('input')[0]; await act(async () => { fireEvent.change(input, { target: { value: 'hello', }, }); }); expect(input.value).toEqual('hello'); expect(mock).toBeCalled(); }); test('Fires custom onBlur handler if specified', async () => { const mock = jest.fn(); const { container } = render(<Input name="foo" onBlur={ mock }/>); const input = container.getElementsByTagName('input')[0]; await act(async () => { fireEvent.change(input, { target: { value: 'testing', }, }); }); await act(async () => { fireEvent.blur(input); }); expect(input.value).toEqual('testing'); expect(mock).toBeCalled(); });
mengxy/swc
crates/swc_webpack_ast/tests/fixture/css-escape/1/output.js
if (exports) module.exports = null; else { define, define.amd; define([], factory.bind(root, root)); }
wearemolecule/date-range-picker
tests/integration/pods/components/year-display/component-test.js
<reponame>wearemolecule/date-range-picker import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import moment from 'moment'; moduleForComponent('year-display', 'Integration | Component | year display', { integration: true }); // year-display use the current year as the placeholder test('it renders', function(assert) { this.setProperties({ startDate: moment('2016-01-01', 'YYYY-MM-DD'), endDate: moment('2016-12-30', 'YYYY-MM-DD'), }); this.render(hbs`{{year-display startDate=startDate endDate=endDate}}`); let currentYear = moment().format('YYYY'); assert.equal(this.$().text().trim(), currentYear, 'displays the correct placeholder year'); }); test('it renders as an energy year display', function(assert) { this.setProperties({ startDate: moment('2016-06-01', 'YYYY-MM-DD'), endDate: moment('2017-05-31', 'YYYY-MM-DD'), }); this.render(hbs`{{year-display startDate=startDate endDate=endDate energyYear=true}}`); let currentYear = moment().format('YYYY'); assert.equal(this.$().text().trim(), "EY " + currentYear, 'displays the correct placeholder year'); }); test('expands to show all the years', function(assert) { this.setProperties({ startDate: moment('2016-01-01', 'YYYY-MM-DD'), endDate: moment('2016-12-30', 'YYYY-MM-DD'), }); this.render(hbs`{{year-display startDate=startDate endDate=endDate isExpanded=true}}`); this.$("button:contains('2016')").click(); assert.equal(this.$('.dp-year-body button').length, 21, 'shows 21 (10 + 1 + 10) years at a time by default'); }); test('selecting a year retains the month', function(assert) { this.setProperties({ startDate: moment('2016-03-01', 'YYYY-MM-DD') }); this.render(hbs`{{year-display startDate=startDate}}`); this.$("button:contains('2016')").click(); this.$("button:contains('2017')").click(); assert.equal(this.get('startDate').format('MM'), '03', 'Month should still be March.'); }); test('updating the year changes the displayed year', function(assert) { this.setProperties({ startDate: moment('2016-01-01', 'YYYY-MM-DD'), endDate: moment('2016-12-30', 'YYYY-MM-DD'), }); this.render(hbs`{{year-display startDate=startDate endDate=endDate month=startDate}}`); this.$("button:contains('2016')").click(); this.$("button:contains('2017')").click(); assert.equal(this.get('startDate').format("YYYY"), '2017', 'startDate is updated to 2017.'); assert.equal(this.get('endDate').format("YYYY"), '2017', 'startDate is updated to 2017.'); assert.equal(this.$('.dp-btn-year').text().trim(), '2017', 'Year button displays 2017.'); }); test('updating the year changes the displayed year as an energy year display', function(assert) { this.setProperties({ startDate: moment('2016-06-01', 'YYYY-MM-DD'), endDate: moment('2017-05-31', 'YYYY-MM-DD'), }); this.render(hbs`{{year-display startDate=startDate endDate=endDate month=endDate energyYear=true}}`); this.$("button:contains('2017')").click(); this.$("button:contains('2020')").click(); assert.equal(this.get('startDate').format("YYYY"), '2019', 'startDate is updated to 2019.'); assert.equal(this.get('endDate').format("YYYY"), '2020', 'endDate is updated to 2020.'); assert.equal(this.$('.dp-btn-year').text().trim(), 'EY 2020', 'Year button displays EY 2020.'); });
LaudateCorpus1/google-cloud-ruby
google-cloud-talent-v4/test/google/cloud/talent/v4/completion_test.rb
<filename>google-cloud-talent-v4/test/google/cloud/talent/v4/completion_test.rb # frozen_string_literal: true # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! require "helper" require "gapic/grpc/service_stub" require "google/cloud/talent/v4/completion_service_pb" require "google/cloud/talent/v4/completion_service_services_pb" require "google/cloud/talent/v4/completion" class ::Google::Cloud::Talent::V4::Completion::ClientTest < Minitest::Test class ClientStub attr_accessor :call_rpc_count, :requests def initialize response, operation, &block @response = response @operation = operation @block = block @call_rpc_count = 0 @requests = [] end def call_rpc *args, **kwargs @call_rpc_count += 1 @requests << @block&.call(*args, **kwargs) yield @response, @operation if block_given? @response end end def test_complete_query # Create GRPC objects. grpc_response = ::Google::Cloud::Talent::V4::CompleteQueryResponse.new grpc_operation = GRPC::ActiveCall::Operation.new nil grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure grpc_options = {} # Create request parameters for a unary method. tenant = "hello world" query = "hello world" language_codes = ["hello world"] page_size = 42 company = "hello world" scope = :COMPLETION_SCOPE_UNSPECIFIED type = :COMPLETION_TYPE_UNSPECIFIED complete_query_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:| assert_equal :complete_query, name assert_kind_of ::Google::Cloud::Talent::V4::CompleteQueryRequest, request assert_equal "hello world", request["tenant"] assert_equal "hello world", request["query"] assert_equal ["hello world"], request["language_codes"] assert_equal 42, request["page_size"] assert_equal "hello world", request["company"] assert_equal :COMPLETION_SCOPE_UNSPECIFIED, request["scope"] assert_equal :COMPLETION_TYPE_UNSPECIFIED, request["type"] refute_nil options end Gapic::ServiceStub.stub :new, complete_query_client_stub do # Create client client = ::Google::Cloud::Talent::V4::Completion::Client.new do |config| config.credentials = grpc_channel end # Use hash object client.complete_query({ tenant: tenant, query: query, language_codes: language_codes, page_size: page_size, company: company, scope: scope, type: type }) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use named arguments client.complete_query tenant: tenant, query: query, language_codes: language_codes, page_size: page_size, company: company, scope: scope, type: type do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use protobuf object client.complete_query ::Google::Cloud::Talent::V4::CompleteQueryRequest.new(tenant: tenant, query: query, language_codes: language_codes, page_size: page_size, company: company, scope: scope, type: type) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use hash object with options client.complete_query({ tenant: tenant, query: query, language_codes: language_codes, page_size: page_size, company: company, scope: scope, type: type }, grpc_options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Use protobuf object with options client.complete_query(::Google::Cloud::Talent::V4::CompleteQueryRequest.new(tenant: tenant, query: query, language_codes: language_codes, page_size: page_size, company: company, scope: scope, type: type), grpc_options) do |response, operation| assert_equal grpc_response, response assert_equal grpc_operation, operation end # Verify method calls assert_equal 5, complete_query_client_stub.call_rpc_count end end def test_configure grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure client = block_config = config = nil Gapic::ServiceStub.stub :new, nil do client = ::Google::Cloud::Talent::V4::Completion::Client.new do |config| config.credentials = grpc_channel end end config = client.configure do |c| block_config = c end assert_same block_config, config assert_kind_of ::Google::Cloud::Talent::V4::Completion::Client::Configuration, config end end
siweilxy/openjdkstudy
src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/nodes/UnaryMathIntrinsicNode.java
/* * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.replacements.nodes; import static org.graalvm.compiler.nodeinfo.NodeCycles.CYCLES_64; import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_1; import jdk.vm.ci.meta.Value; import org.graalvm.compiler.core.common.spi.ForeignCallDescriptor; import org.graalvm.compiler.core.common.type.FloatStamp; import org.graalvm.compiler.core.common.type.PrimitiveStamp; import org.graalvm.compiler.core.common.type.Stamp; import org.graalvm.compiler.core.common.type.StampFactory; import org.graalvm.compiler.debug.GraalError; import org.graalvm.compiler.graph.NodeClass; import org.graalvm.compiler.graph.spi.CanonicalizerTool; import org.graalvm.compiler.lir.gen.ArithmeticLIRGeneratorTool; import org.graalvm.compiler.nodeinfo.NodeInfo; import org.graalvm.compiler.nodes.ConstantNode; import org.graalvm.compiler.nodes.NodeView; import org.graalvm.compiler.nodes.ValueNode; import org.graalvm.compiler.nodes.calc.UnaryNode; import org.graalvm.compiler.nodes.spi.ArithmeticLIRLowerable; import org.graalvm.compiler.nodes.spi.Lowerable; import org.graalvm.compiler.nodes.spi.LoweringTool; import jdk.vm.ci.meta.JavaKind; import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool; @NodeInfo(nameTemplate = "MathIntrinsic#{p#operation/s}", cycles = CYCLES_64, size = SIZE_1) public final class UnaryMathIntrinsicNode extends UnaryNode implements ArithmeticLIRLowerable, Lowerable { public static final NodeClass<UnaryMathIntrinsicNode> TYPE = NodeClass.create(UnaryMathIntrinsicNode.class); protected final UnaryOperation operation; public enum UnaryOperation { LOG(new ForeignCallDescriptor("arithmeticLog", double.class, double.class)), LOG10(new ForeignCallDescriptor("arithmeticLog10", double.class, double.class)), SIN(new ForeignCallDescriptor("arithmeticSin", double.class, double.class)), COS(new ForeignCallDescriptor("arithmeticCos", double.class, double.class)), TAN(new ForeignCallDescriptor("arithmeticTan", double.class, double.class)), EXP(new ForeignCallDescriptor("arithmeticExp", double.class, double.class)); public final ForeignCallDescriptor foreignCallDescriptor; UnaryOperation(ForeignCallDescriptor foreignCallDescriptor) { this.foreignCallDescriptor = foreignCallDescriptor; } public double compute(double value) { switch (this) { case LOG: return Math.log(value); case LOG10: return Math.log10(value); case EXP: return Math.exp(value); case SIN: return Math.sin(value); case COS: return Math.cos(value); case TAN: return Math.tan(value); default: throw new GraalError("unknown op %s", this); } } public Stamp computeStamp(Stamp valueStamp) { if (valueStamp instanceof FloatStamp) { FloatStamp floatStamp = (FloatStamp) valueStamp; switch (this) { case COS: case SIN: { boolean nonNaN = floatStamp.lowerBound() != Double.NEGATIVE_INFINITY && floatStamp.upperBound() != Double.POSITIVE_INFINITY && floatStamp.isNonNaN(); return StampFactory.forFloat(JavaKind.Double, -1.0, 1.0, nonNaN); } case TAN: { boolean nonNaN = floatStamp.lowerBound() != Double.NEGATIVE_INFINITY && floatStamp.upperBound() != Double.POSITIVE_INFINITY && floatStamp.isNonNaN(); return StampFactory.forFloat(JavaKind.Double, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, nonNaN); } case LOG: case LOG10: { double lowerBound = compute(floatStamp.lowerBound()); double upperBound = compute(floatStamp.upperBound()); if (floatStamp.contains(0.0)) { // 0.0 and -0.0 infinity produces -Inf lowerBound = Double.NEGATIVE_INFINITY; } boolean nonNaN = floatStamp.lowerBound() >= 0.0 && floatStamp.isNonNaN(); return StampFactory.forFloat(JavaKind.Double, lowerBound, upperBound, nonNaN); } case EXP: { double lowerBound = Math.exp(floatStamp.lowerBound()); double upperBound = Math.exp(floatStamp.upperBound()); boolean nonNaN = floatStamp.isNonNaN(); return StampFactory.forFloat(JavaKind.Double, lowerBound, upperBound, nonNaN); } } } return StampFactory.forKind(JavaKind.Double); } } public UnaryOperation getOperation() { return operation; } public static ValueNode create(ValueNode value, UnaryOperation op) { ValueNode c = tryConstantFold(value, op); if (c != null) { return c; } return new UnaryMathIntrinsicNode(value, op); } protected static ValueNode tryConstantFold(ValueNode value, UnaryOperation op) { if (value.isConstant()) { return ConstantNode.forDouble(op.compute(value.asJavaConstant().asDouble())); } return null; } protected UnaryMathIntrinsicNode(ValueNode value, UnaryOperation op) { super(TYPE, op.computeStamp(value.stamp(NodeView.DEFAULT)), value); assert value.stamp(NodeView.DEFAULT) instanceof FloatStamp && PrimitiveStamp.getBits(value.stamp(NodeView.DEFAULT)) == 64; this.operation = op; } @Override public Stamp foldStamp(Stamp valueStamp) { return getOperation().computeStamp(valueStamp); } @Override public void lower(LoweringTool tool) { tool.getLowerer().lower(this, tool); } @Override public void generate(NodeLIRBuilderTool nodeValueMap, ArithmeticLIRGeneratorTool gen) { // We can only reach here in the math stubs Value input = nodeValueMap.operand(getValue()); Value result; switch (getOperation()) { case LOG: result = gen.emitMathLog(input, false); break; case LOG10: result = gen.emitMathLog(input, true); break; case EXP: result = gen.emitMathExp(input); break; case SIN: result = gen.emitMathSin(input); break; case COS: result = gen.emitMathCos(input); break; case TAN: result = gen.emitMathTan(input); break; default: throw GraalError.shouldNotReachHere(); } nodeValueMap.setResult(this, result); } @Override public ValueNode canonical(CanonicalizerTool tool, ValueNode forValue) { ValueNode c = tryConstantFold(forValue, getOperation()); if (c != null) { return c; } return this; } @NodeIntrinsic public static native double compute(double value, @ConstantNodeParameter UnaryOperation op); }
stefanwimmer128/core
packages/core-utils/src/extend.js
<gh_stars>1-10 /* @flow */ import { keys, transform, } from "lodash"; export default function (target: any, ...sources: any[]): any { return transform(sources, (target, source) => transform(keys(source), (target, key) => target[key] = source[key], target), target); }
psychobob666/safmq
SAFMQManagerSnapin/CUserEditor.cpp
/* Copyright 2005 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This software implements a platform independent Store and Forward Message Queue. */ // CUserEditor.cpp : Implementation of CCUserEditor #include "stdafx.h" #include "CUserEditor.h" #include "PasswordDialog.h" #include "GroupAddDialog.h" using namespace std; ///////////////////////////////////////////////////////////////////////////// // CUserEditor CUserEditor::CUserEditor() { m_bWindowOnly = TRUE; images = ImageList_LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDB_STRIP_16), 16, 0, RGB(0, 128, 128), IMAGE_BITMAP, LR_CREATEDIBSECTION); CalcExtent(m_sizeExtent); } CUserEditor::~CUserEditor() { ::FreeResource(images); } HWND CUserEditor::Create(HWND hWndParent, RECT& r, LPARAM dwInitParam) { HWND theWnd = CComCompositeControl<CUserEditor>::Create(hWndParent, r, dwInitParam); COLORREF color = ::GetSysColor(COLOR_3DFACE); m_hbrBackground = ::CreateSolidBrush(color); modifyUsers = GetDlgItem(IDC_MOD_USERS); modifyGroups = GetDlgItem(IDC_MOD_GROUPS); modifyQueues = GetDlgItem(IDC_MOD_QUEUES); name = GetDlgItem(IDC_NAME); description = GetDlgItem(IDC_DESCRIPTION); groups = GetDlgItem(IDC_GROUPS); groups.SetImageList(images, LVSIL_SMALL); return theWnd; } LRESULT CUserEditor::OnOwnerDraw(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { DRAWITEMSTRUCT *dis = (DRAWITEMSTRUCT*)lParam; return bHandled=FALSE; } STDMETHODIMP CUserEditor::Initialize(BSTR username, BSTR description, BOOL modifyUsers, BOOL modifyGroups, BOOL modifyQueues, VARIANT groupList) { this->username = username; this->name.SetWindowText(this->username); this->description.SetWindowText(_bstr_t(description)); this->modifyUsers.SetCheck(modifyUsers); this->modifyGroups.SetCheck(modifyGroups); this->modifyQueues.SetCheck(modifyQueues); VariantVector<BSTR, VT_BSTR> vgrps(groupList); int count = vgrps.getBounds(); vgrps.lock(); for(int x = 0; x < count; x++) { groups.InsertItem(LVIF_TEXT | LVIF_IMAGE, count + x, _bstr_t(vgrps[x]), 0, 0, IMG_GROUP, 0); } vgrps.unlock(); return S_OK; } LRESULT CUserEditor::OnSetPassword(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { CPasswordDialog dlg(this->username); if (dlg.DoModal() == IDOK) { Fire_ChangePassword(dlg.getPassword()); } return bHandled = TRUE; } LRESULT CUserEditor::OnAddGroup(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { VARIANT varGroups; memset(&varGroups, 0, sizeof(varGroups)); if (Fire_GetAvailableGroups(&varGroups) == S_OK) { VariantVector<BSTR, VT_BSTR> vgrps(varGroups, true); // take ownership and release when done vector<string> gps; vector<string>::iterator p; vgrps.lock(); long count = vgrps.getBounds(); long x; for(x=0; x<count; x++) gps.push_back((const char*)_bstr_t(vgrps[x])); vgrps.unlock(); LVITEM item; char buffer[1024] = ""; memset(&item, 0, sizeof(item)); item.mask = LVIF_TEXT | LVIF_STATE | LVIF_PARAM; item.pszText = buffer; item.cchTextMax = sizeof(buffer); count = groups.GetItemCount(); for (x=0; x<count; x++) { item.iItem = x; groups.GetItem(&item); p = std::find(gps.begin(), gps.end(), string(item.pszText)); if (p != gps.end()) gps.erase(p); } CGroupAddDialog dlg(gps); if (dlg.DoModal() == IDOK) { dlg.getGroups(gps); for(x=0; x<(int)gps.size(); x++) { groups.InsertItem(LVIF_TEXT | LVIF_IMAGE, count + x, gps[x].c_str(), 0, 0, IMG_GROUP, 0); } } } return bHandled = TRUE; } LRESULT CUserEditor::OnApply(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled) { int count = groups.GetItemCount(); LVITEM item; char buffer[1024] = ""; VariantVector<BSTR, VT_BSTR> gl(count); memset(&item, 0, sizeof(item)); item.mask = LVIF_TEXT | LVIF_STATE | LVIF_PARAM; item.pszText = buffer; item.cchTextMax = sizeof(buffer); gl.lock(); for(int x=0; x<count; x++) { item.iItem = x; BOOL res = groups.GetItem(&item); gl[x] = _bstr_t(item.pszText).copy(); } gl.unlock(); this->Fire_ApplyChanges(modifyUsers.GetCheck(), modifyGroups.GetCheck(), modifyQueues.GetCheck(), gl); return bHandled = TRUE; } LRESULT CUserEditor::OnGroupKey(int idCtrl, LPNMHDR pnmh, BOOL& bHandled) { NMLVKEYDOWN* info = ( NMLVKEYDOWN*)pnmh; if (info->wVKey == VK_DELETE) { int iItem = -1; vector<int> deletes; while ((iItem = groups.GetNextItem(iItem, LVNI_SELECTED)) >= 0) { deletes.push_back(iItem); } sort(deletes.begin(),deletes.end()); vector<int>::reverse_iterator r; for(r = deletes.rbegin(); r != deletes.rend(); r++) { groups.DeleteItem(*r); } } return bHandled = FALSE; }
juansgonzalez/famillyBank
src/main/java/com/juanseb/bank/backend/service/impl/TarjetaServiceImpl.java
package com.juanseb.bank.backend.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.juanseb.bank.backend.model.Tarjeta; import com.juanseb.bank.backend.repository.TarjetaRepository; import com.juanseb.bank.backend.service.TarjetaService; import javax.persistence.EntityNotFoundException; import java.util.List; @Service public class TarjetaServiceImpl implements TarjetaService { @Autowired TarjetaRepository tarjetaRepository; @Transactional @Override public Tarjeta crearTarjeta(Tarjeta tarjetaNueva) { return tarjetaRepository.save(tarjetaNueva); } @Transactional @Override public List<Tarjeta> obtenerTarjetaByCuenta(Long cuentaId) { return tarjetaRepository.findByCuentaId(cuentaId); } @Transactional @Override public Tarjeta obtenerTarjetaByNumeroTarjeta(Long numeroTarjeta) { return tarjetaRepository.obtenerTarjetaByNumeroTarjeta(numeroTarjeta); } @Transactional @Override public Tarjeta obtenerTarjetaById(Long idTarjeta) throws EntityNotFoundException{ return tarjetaRepository.findById(idTarjeta).orElseThrow(() -> new EntityNotFoundException("No se ha encontrado tarjeta con numero: "+idTarjeta)); } }