repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
chris110408/gameoflife-master
server/server.js
var http = require('http'); const path = require('path'); const webpack = require('webpack'); const express = require('express'); const config = require('../webpack.config.dev.js'); import dummyData from './dummyData'; import serverConfig from './config'; const app = express(); app.use(express.static('public')) global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; const compiler = webpack(config); app.use(require('webpack-dev-middleware')(compiler, { publicPath: config.output.publicPath })); app.use(require('webpack-hot-middleware')(compiler)); app.get('/', function(req, res) { res.sendFile(path.join(__dirname, '../index.html')); }); var server = http.createServer(app); server.listen(8000, function(err) { if (err) { return console.error(err); } console.log('Listening at http://localhost:8000/'); });
sys0pp/c5
ext/classic/classic/test/specs/grid/column/Check.js
<gh_stars>10-100 describe("Ext.grid.column.Check", function() { var grid, store, col; function getColCfg() { return { xtype: 'checkcolumn', text: 'Checked', dataIndex: 'val' }; } function makeGrid(columns) { store = new Ext.data.Store({ model: spec.CheckColumnModel, data: [{ val: true }, { val: true }, { val: false }, { val: true }, { val: false }] }); if (!columns) { columns = [getColCfg()]; } grid = new Ext.grid.Panel({ width: 200, height: 100, renderTo: Ext.getBody(), store: store, columns: columns }); col = grid.getColumnManager().getFirst(); } function triggerCellMouseEvent(type, rowIdx, cellIdx, button, x, y) { var target = getCellImg(rowIdx, cellIdx); jasmine.fireMouseEvent(target, type, x, y, button); } function getCell(rowIdx) { return grid.getView().getCellInclusive({ row: rowIdx, column: 0 }); } function getCellImg(rowIdx) { var cell = getCell(rowIdx); return Ext.fly(cell).down('.x-grid-checkcolumn'); } function hasCls(el, cls) { return Ext.fly(el).hasCls(cls); } beforeEach(function() { Ext.define('spec.CheckColumnModel', { extend: 'Ext.data.Model', fields: ['val'] }); }); afterEach(function() { Ext.destroy(grid, store); col = grid = store = null; Ext.undefine('spec.CheckColumnModel'); Ext.data.Model.schema.clear(); }); describe("check rendering", function() { it("should add the x-grid-checkcolumn class to the checkbox element", function() { makeGrid(); expect(hasCls(getCellImg(0), 'x-grid-checkcolumn')).toBe(true); }); it("should set the x-grid-checkcolumn-checked class on checked items", function() { makeGrid(); expect(hasCls(getCellImg(0), 'x-grid-checkcolumn-checked')).toBe(true); expect(hasCls(getCellImg(2), 'x-grid-checkcolumn-checked')).toBe(false); }); }); describe("enable/disable", function() { describe("during config", function() { it("should not include the disabledCls if the column is not disabled", function() { makeGrid(); expect(hasCls(getCell(0), col.disabledCls)).toBe(false); }); it("should include the disabledCls if the column is disabled", function() { var cfg = getColCfg(); cfg.disabled = true; makeGrid([cfg]); expect(hasCls(getCell(0), col.disabledCls)).toBe(true); }); }); describe("after render", function() { it("should add the disabledCls if disabling", function() { makeGrid(); col.disable(); expect(hasCls(getCell(0), col.disabledCls)).toBe(true); expect(hasCls(getCell(1), col.disabledCls)).toBe(true); expect(hasCls(getCell(2), col.disabledCls)).toBe(true); expect(hasCls(getCell(3), col.disabledCls)).toBe(true); expect(hasCls(getCell(4), col.disabledCls)).toBe(true); }); it("should remove the disabledCls if enabling", function() { var cfg = getColCfg(); cfg.disabled = true; makeGrid([cfg]); col.enable(); expect(hasCls(getCell(0), col.disabledCls)).toBe(false); expect(hasCls(getCell(1), col.disabledCls)).toBe(false); expect(hasCls(getCell(2), col.disabledCls)).toBe(false); expect(hasCls(getCell(3), col.disabledCls)).toBe(false); expect(hasCls(getCell(4), col.disabledCls)).toBe(false); }); }); }); describe("interaction", function() { describe("stopSelection", function() { describe("stopSelection: false", function() { it("should select when a full row update is required", function() { var cfg = getColCfg(); cfg.stopSelection = false; // Template column always required a full update makeGrid([cfg, { xtype: 'templatecolumn', dataIndex: 'val', tpl: '{val}' }]); triggerCellMouseEvent('click', 0); expect(grid.getSelectionModel().isSelected(store.getAt(0))).toBe(true); }); it("should select when a full row update is not required", function() { var cfg = getColCfg(); cfg.stopSelection = false; // Template column always required a full update makeGrid([cfg, { dataIndex: 'val' }]); triggerCellMouseEvent('click', 0); expect(grid.getSelectionModel().isSelected(store.getAt(0))).toBe(true); }); }); describe("stopSelection: true", function() { it("should not select when a full row update is required", function() { var cfg = getColCfg(); cfg.stopSelection = true; // Template column always required a full update makeGrid([cfg, { xtype: 'templatecolumn', dataIndex: 'val', tpl: '{val}' }]); triggerCellMouseEvent('click', 0); expect(grid.getSelectionModel().isSelected(store.getAt(0))).toBe(false); }); it("should not select when a full row update is not required", function() { var cfg = getColCfg(); cfg.stopSelection = true; // Template column always required a full update makeGrid([cfg, { dataIndex: 'val' }]); triggerCellMouseEvent('click', 0); expect(grid.getSelectionModel().isSelected(store.getAt(0))).toBe(false); }); }); }); describe("events", function() { it("should pass the column, record index & new checked state for beforecheckchange", function() { var arg1, arg2, arg3; makeGrid(); col.on('beforecheckchange', function(a, b, c) { arg1 = a; arg2 = b; arg3 = c; }); triggerCellMouseEvent('mousedown', 0); expect(arg1).toBe(col); expect(arg2).toBe(0); expect(arg3).toBe(false); }); it("should pass the column, record index & new checked state for checkchange", function() { var arg1, arg2, arg3; makeGrid(); col.on('checkchange', function(a, b, c) { arg1 = a; arg2 = b; arg3 = c; }); triggerCellMouseEvent('mousedown', 2); expect(arg1).toBe(col); expect(arg2).toBe(2); expect(arg3).toBe(true); }); it("should not fire fire checkchange if beforecheckchange returns false", function() { var called = false; makeGrid(); col.on('checkchange', function(a, b, c) { called = true; }); col.on('beforecheckchange', function() { return false; }); triggerCellMouseEvent('mousedown', 2); expect(called).toBe(false); }); }); it("should invert the record value", function() { makeGrid(); triggerCellMouseEvent('mousedown', 0); expect(store.getAt(0).get('val')).toBe(false); triggerCellMouseEvent('mousedown', 2); expect(store.getAt(2).get('val')).toBe(true); }); it("should not trigger any changes when disabled", function() { var cfg = getColCfg(); cfg.disabled = true; makeGrid([cfg]); triggerCellMouseEvent('mousedown', 0); expect(store.getAt(0).get('val')).toBe(true); triggerCellMouseEvent('mousedown', 2); expect(store.getAt(2).get('val')).toBe(false); }); }); });
csgn/Price-Tracker
Source/Backend/core/category/views.py
from util import makeQuery, convertToPSQL def categories_view(request): if request.method == 'GET': return makeQuery(f""" select * from category """) def categories_category_view(request, categoryid): if request.method == 'GET': return makeQuery(f""" select * from category where categoryid = {categoryid} """) elif request.method == 'PUT': import json props = convertToPSQL(json.loads(request.body)) return makeQuery(f""" update category set {props} where categoryid = {categoryid} """, False) elif request.method == 'DELETE': return makeQuery(f""" delete from category where categoryid = {categoryid} """, False) def categories_category_subcategories_view(request, categoryid): if request.method == 'GET': return makeQuery(f""" select sub.subcategoryid, sub.name, sub.url, sub.categoryid from category cat join subcategory sub on sub.categoryid = cat.categoryid where cat.categoryid = {categoryid} """) def categories_category_brands_view(request, categoryid): if request.method == 'GET': return makeQuery(f""" select br.brandid, br.name, br.url from category cat join categoryownedbybrand cobb on cobb.categoryid = cat.categoryid join brand br on br.brandid = cobb.brandid where cat.categoryid = {categoryid} """) def categories_category_supplier_view(request, categoryid): if request.method == 'GET': return makeQuery(f""" select supp.supplierid, supp.name, supp.rate, supp.url from category cat join categoryownedbysupplier cobs on cobs.categoryid = cat.categoryid join supplier supp on supp.supplierid = cobs.supplierid where cat.categoryid = {categoryid} """) def categories_category_product_view(request, categoryid): if request.method == 'GET': return makeQuery(f""" select prod.productid, prod.name, prod.images, prod.url, prod.rate, prod.brandid, prod.categoryid from category cat join product prod on prod.categoryid = cat.categoryid where cat.categoryid = {categoryid} """)
duarterafael/Conformitate
MainProject/use-4.0.0-323/src/main/org/tzi/use/parser/generator/ASTGBarrier.java
<filename>MainProject/use-4.0.0-323/src/main/org/tzi/use/parser/generator/ASTGBarrier.java /* * USE - UML based specification environment * Copyright (C) 1999-2010 <NAME>, University of Bremen * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ // $Id$ package org.tzi.use.parser.generator; import org.tzi.use.gen.assl.statics.GInstrBarrier; import org.tzi.use.gen.assl.statics.GInstruction; import org.tzi.use.parser.Context; import org.tzi.use.parser.SemanticException; import org.tzi.use.uml.ocl.expr.Expression; /** * AST class for the barrier statement. * @author <NAME> * */ public abstract class ASTGBarrier extends ASTGInstruction { /* (non-Javadoc) * @see org.tzi.use.parser.generator.ASTGInstruction#gen(org.tzi.use.parser.Context) */ @Override public GInstruction gen(Context ctx) throws SemanticException { Expression theExpression = genExpression(ctx); return new GInstrBarrier(theExpression); } /** * Generates the OCL expression to be validated. * @param ctx * @return */ protected abstract Expression genExpression(Context ctx) throws SemanticException; }
gebond/image-processing-java
ip-view/src/main/java/com/gebond/ip/view/MainForm.java
<filename>ip-view/src/main/java/com/gebond/ip/view/MainForm.java package com.gebond.ip.view; import static gebond.ip.domain.manager.LogManager.log; import com.gebond.ip.model.metric.Metrics; import com.gebond.ip.model.setting.CompressionSetting; import com.gebond.ip.model.setting.ImageSetting; import com.gebond.ip.model.setting.TransformSetting; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JRadioButton; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.WindowConstants; /** * Created on 28/02/18. */ public class MainForm extends JFrame { private static final int WIDTH = 650; private static final int HEIGHT = 500; protected JButton runButton; protected JSlider slider1; protected JSlider slider2; protected JSlider slider3; protected JPanel compressionPanel; protected JPanel submitPanel; protected JPanel transformationPanel; protected JPanel rightPanel; protected JPanel leftPanel; protected JPanel imagePanel; protected JPanel browserPanel; protected JPanel mainPanel; protected JComboBox<TransformSetting.TransformationType> selectMethodBox; protected JButton browserButton; protected JLabel imageLabel; protected JRadioButton rgbRadioButton; protected JRadioButton ycrcbRadioButton; protected JPanel fourierSettingPanel; protected JLabel selectMethod; protected JPanel discreteSettingPanel; protected JRadioButton sizeX8RadioButton; protected JRadioButton sizeX16RadioButton; protected JRadioButton sizeX32RadioButton; protected JTextField a3TextField; protected JButton cancelButton; protected JProgressBar progressBar1; protected JPanel emptyPanel; protected JPanel progressPanel; protected JPanel colorSchemaPanel; protected JLabel sliderValue1; protected JLabel sliderValue2; protected JLabel sliderValue3; protected JLabel sliderLabel1; protected JLabel sliderLabel2; protected JLabel sliderLabel3; protected JLabel totalValue; private JPanel metricsPanel; private JCheckBox MSECheckBox; private JCheckBox PSNRCheckBox; private JLabel metricsLabel; public MainForm() { super("Processing Form"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setSize(WIDTH, HEIGHT); setContentPane(mainPanel); setLocationRelativeTo(null); log("mainForm initialized"); } public JButton getRunButton() { return runButton; } public JSlider getSlider1() { return slider1; } public JSlider getSlider2() { return slider2; } public JSlider getSlider3() { return slider3; } public JPanel getCompressionPanel() { return compressionPanel; } public JPanel getSubmitPanel() { return submitPanel; } public JPanel getTransformationPanel() { return transformationPanel; } public JPanel getRightPanel() { return rightPanel; } public JPanel getLeftPanel() { return leftPanel; } public JPanel getImagePanel() { return imagePanel; } public JPanel getBrowserPanel() { return browserPanel; } public JPanel getMainPanel() { return mainPanel; } public JComboBox<TransformSetting.TransformationType> getSelectMethodBox() { return selectMethodBox; } public JButton getBrowserButton() { return browserButton; } public JLabel getImageabel() { return imageLabel; } public JRadioButton getRgbRadioButton() { return rgbRadioButton; } public JRadioButton getYcrcbRadioButton() { return ycrcbRadioButton; } public JPanel getFourierSettingPanel() { return fourierSettingPanel; } public JPanel getDiscreteSettingPanel() { return discreteSettingPanel; } public JLabel getSelectMethod() { return selectMethod; } public JRadioButton getSizeX8RadioButton() { return sizeX8RadioButton; } public JRadioButton getSizeX16RadioButton() { return sizeX16RadioButton; } public JRadioButton getSizeX32RadioButton() { return sizeX32RadioButton; } public JButton getCancelButton() { return cancelButton; } public JPanel getProgressPanel() { return progressPanel; } public JLabel getSliderValue1() { return sliderValue1; } public JLabel getSliderValue2() { return sliderValue2; } public JLabel getSliderValue3() { return sliderValue3; } public JLabel getSliderLabel1() { return sliderLabel1; } public JLabel getSliderLabel2() { return sliderLabel2; } public JLabel getSliderLabel3() { return sliderLabel3; } public ImageSetting buildImageSetting(BufferedImage lastImage) { return ImageSetting.startBuilder() .withImage(lastImage) .withSegmentSize(buildSegmentSize()) .withSchema(buildSchema()) .withCompressions(buildCompressionSettings()) .build(); } public TransformSetting buildTransformSetting() { TransformSetting.TransformSettingBuilder builder = TransformSetting.startBuilder(); if (MSECheckBox.isSelected()) { builder.addMetrics(Metrics.MetricsType.MSE); } if (PSNRCheckBox.isSelected()) { builder.addMetrics(Metrics.MetricsType.PSNR); } return builder .withType((TransformSetting.TransformationType) selectMethodBox.getSelectedItem()) .build(); } private ImageSetting.SegmentSize buildSegmentSize() { if (sizeX8RadioButton.isSelected()) { return ImageSetting.SegmentSize.X8; } if (sizeX16RadioButton.isSelected()) { return ImageSetting.SegmentSize.X16; } if (sizeX32RadioButton.isSelected()) { return ImageSetting.SegmentSize.X32; } return ImageSetting.SegmentSize.X8; } private Map<Integer, CompressionSetting> buildCompressionSettings() { Map<Integer, CompressionSetting> compressionSettingMap = new HashMap<>(); compressionSettingMap .put(ImageSetting.RGB.RED.getOrder(), CompressionSetting.of(slider1.getValue())); compressionSettingMap .put(ImageSetting.RGB.GREEN.getOrder(), CompressionSetting.of(slider2.getValue())); compressionSettingMap .put(ImageSetting.RGB.BLUE.getOrder(), CompressionSetting.of(slider3.getValue())); return compressionSettingMap; } private ImageSetting.ImageSchema buildSchema() { if (rgbRadioButton.isSelected()) { return ImageSetting.ImageSchema.RGB; } if (ycrcbRadioButton.isSelected()) { return ImageSetting.ImageSchema.YCRCB; } return ImageSetting.ImageSchema.RGB; } }
MihaiIon/website-generator
src/components/QuickMenu/core/constants.js
// ====================================================== // Components / Quick Menu / Core / Constants/ // ====================================================== export const IGNORE_ACTIONS_TIME = 1200;
jsicree/kafka-demo
simple-producer/src/main/java/com/kafkademo/simpleproducer/port/MessagePort.java
<reponame>jsicree/kafka-demo<gh_stars>0 package com.kafkademo.simpleproducer.port; import com.kafkademo.simpleproducer.domain.ProducerMessage; public interface MessagePort { public void sendMessage(ProducerMessage message); }
iamzken/aliyun-openapi-cpp-sdk
dataworks-public/src/model/GetMetaColumnLineageResult.cc
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/dataworks-public/model/GetMetaColumnLineageResult.h> #include <json/json.h> using namespace AlibabaCloud::Dataworks_public; using namespace AlibabaCloud::Dataworks_public::Model; GetMetaColumnLineageResult::GetMetaColumnLineageResult() : ServiceResult() {} GetMetaColumnLineageResult::GetMetaColumnLineageResult(const std::string &payload) : ServiceResult() { parse(payload); } GetMetaColumnLineageResult::~GetMetaColumnLineageResult() {} void GetMetaColumnLineageResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; if(!dataNode["TotalCount"].isNull()) data_.totalCount = std::stol(dataNode["TotalCount"].asString()); if(!dataNode["PageNum"].isNull()) data_.pageNum = std::stoi(dataNode["PageNum"].asString()); if(!dataNode["PageSize"].isNull()) data_.pageSize = std::stoi(dataNode["PageSize"].asString()); auto allDataEntityListNode = dataNode["DataEntityList"]["DataEntityListItem"]; for (auto dataNodeDataEntityListDataEntityListItem : allDataEntityListNode) { Data::DataEntityListItem dataEntityListItemObject; if(!dataNodeDataEntityListDataEntityListItem["ColumnName"].isNull()) dataEntityListItemObject.columnName = dataNodeDataEntityListDataEntityListItem["ColumnName"].asString(); if(!dataNodeDataEntityListDataEntityListItem["ColumnGuid"].isNull()) dataEntityListItemObject.columnGuid = dataNodeDataEntityListDataEntityListItem["ColumnGuid"].asString(); if(!dataNodeDataEntityListDataEntityListItem["ClusterId"].isNull()) dataEntityListItemObject.clusterId = dataNodeDataEntityListDataEntityListItem["ClusterId"].asString(); if(!dataNodeDataEntityListDataEntityListItem["DatabaseName"].isNull()) dataEntityListItemObject.databaseName = dataNodeDataEntityListDataEntityListItem["DatabaseName"].asString(); if(!dataNodeDataEntityListDataEntityListItem["TableName"].isNull()) dataEntityListItemObject.tableName = dataNodeDataEntityListDataEntityListItem["TableName"].asString(); data_.dataEntityList.push_back(dataEntityListItemObject); } if(!value["ErrorCode"].isNull()) errorCode_ = value["ErrorCode"].asString(); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); if(!value["HttpStatusCode"].isNull()) httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString()); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } int GetMetaColumnLineageResult::getHttpStatusCode()const { return httpStatusCode_; } GetMetaColumnLineageResult::Data GetMetaColumnLineageResult::getData()const { return data_; } std::string GetMetaColumnLineageResult::getErrorCode()const { return errorCode_; } std::string GetMetaColumnLineageResult::getErrorMessage()const { return errorMessage_; } bool GetMetaColumnLineageResult::getSuccess()const { return success_; }
daicang/Leetcode
number-of-islands.py
<filename>number-of-islands.py<gh_stars>0 from typing import List class Solution: def numIslands(self, grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 rows = len(grid) cols = len(grid[0]) islands = 0 visited = [] for _ in range(rows): visited.append([False] * cols) def visit(row, col): targets = [(row, col)] while targets: row, col = targets.pop() if visited[row][col]: continue visited[row][col] = True if row > 0 and grid[row-1][col] == '1': targets.append((row-1, col)) if row < rows-1 and grid[row+1][col] == '1': targets.append((row+1, col)) if col > 0 and grid[row][col-1] == '1': targets.append((row, col-1)) if col < cols-1 and grid[row][col+1] == '1': targets.append((row, col+1)) for row in range(rows): for col in range(cols): if visited[row][col] or grid[row][col] == '0': continue visit(row, col) islands += 1 return islands
hankai17/test
pdns-recursor-4.0.6/json.hh
/* * This file is part of PowerDNS or dnsdist. * Copyright -- PowerDNS.COM B.V. and its contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * In addition, for the avoidance of any doubt, permission is granted to * link this program with OpenSSL and to (re)distribute the binaries * produced as the result of such linking. * * 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. */ #pragma once // it is 2012, deal with it #include <string> #include <stdexcept> #include "json11.hpp" int intFromJson(const json11::Json container, const std::string& key); int intFromJson(const json11::Json container, const std::string& key, const int default_value); double doubleFromJson(const json11::Json container, const std::string& key); double doubleFromJson(const json11::Json container, const std::string& key, const double default_value); std::string stringFromJson(const json11::Json container, const std::string &key); bool boolFromJson(const json11::Json container, const std::string& key); bool boolFromJson(const json11::Json container, const std::string& key, const bool default_value); class JsonException : public std::runtime_error { public: JsonException(const std::string& what) : std::runtime_error(what) { } };
voxel-web/EFG
db/data_fixes/2012-11-27_add_missing_sic_codes.rb
ActiveRecord::Base.transaction do { '47800' => 'Stall Sales', '52100' => 'Operation of warehousing & storage facilities', '52240' => 'Cargo Handling', '53200' => 'Courier activities' }.each do |(code, desc)| unless SicCode.exists?(code: code) SicCode.create!(code: code, description: desc, eligible: false, public_sector_restricted: false, active: false) end end end
lht19900714/Leetcode_Solutions
Algorithms/0589_N-ary_Tree_Preorder_Traversal/Java/N-AryTreePreorderTraversalSolution1.java
<gh_stars>0 // Space: O(n) // Time: O(n) /* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ class Solution { public List<Integer> preorder(Node root) { if (root == null) return new ArrayList<>(); if (root.children == null) return new ArrayList<Integer>(Arrays.asList(root.val)); List<Integer> res = new ArrayList<>(); List<Node> queue = new ArrayList<>(); queue.add(root); while (queue.size() > 0) { Node cur = queue.remove(0); res.add(cur.val); if (cur.children != null) { cur.children.addAll(queue); queue = cur.children; } } return res; } }
chen-png/zephyr
drivers/usb/device/usb_dc_native_posix_adapt.h
<filename>drivers/usb/device/usb_dc_native_posix_adapt.h /* * Copyright (c) 2018 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ struct op_common { u16_t version; u16_t code; u32_t status; } __packed; struct devlist_device { char path[256]; char busid[32]; u32_t busnum; u32_t devnum; u32_t speed; u16_t idVendor; u16_t idProduct; u16_t bcdDevice; u8_t bDeviceClass; u8_t bDeviceSubClass; u8_t bDeviceProtocol; u8_t bConfigurationValue; u8_t bNumConfigurations; u8_t bNumInterfaces; } __packed; #define OP_REQUEST (0x80 << 8) #define OP_REPLY (0x00 << 8) /* Devlist */ #define OP_DEVLIST 0x05 #define OP_REQ_DEVLIST (OP_REQUEST | OP_DEVLIST) #define OP_REP_DEVLIST (OP_REPLY | OP_DEVLIST) /* Import USB device */ #define OP_IMPORT 0x03 #define OP_REQ_IMPORT (OP_REQUEST | OP_IMPORT) #define OP_REP_IMPORT (OP_REPLY | OP_IMPORT) /* USBIP requests */ #define USBIP_CMD_SUBMIT 0x0001 #define USBIP_CMD_UNLINK 0x0002 #define USBIP_RET_SUBMIT 0x0003 #define USBIP_RET_UNLINK 0x0004 /* USBIP direction */ #define USBIP_DIR_OUT 0x00 #define USBIP_DIR_IN 0x01 struct usbip_header_common { u32_t command; u32_t seqnum; u32_t devid; u32_t direction; u32_t ep; } __packed; struct usbip_submit { u32_t transfer_flags; s32_t transfer_buffer_length; s32_t start_frame; s32_t number_of_packets; s32_t interval; } __packed; struct usbip_unlink { u32_t seqnum; } __packed; struct usbip_submit_rsp { struct usbip_header_common common; s32_t status; s32_t actual_length; s32_t start_frame; s32_t number_of_packets; s32_t error_count; u64_t setup; } __packed; struct usbip_header { struct usbip_header_common common; union { struct usbip_submit submit; struct usbip_unlink unlink; } u; } __packed; /* Function definitions */ int usbip_recv(u8_t *buf, size_t len); int usbip_send_common(u8_t ep, u32_t data_len); int usbip_send(u8_t ep, const u8_t *data, size_t len); void usbip_start(void); int handle_usb_control(struct usbip_header *hdr); int handle_usb_data(struct usbip_header *hdr);
arpangs/spikebot-android-v1
app/src/main/java/com/spike/bot/adapter/TTlockInfoAdapter.java
<filename>app/src/main/java/com/spike/bot/adapter/TTlockInfoAdapter.java package com.spike.bot.adapter; import android.annotation.SuppressLint; import android.content.Context; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.PopupMenu; import androidx.appcompat.view.ContextThemeWrapper; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.AppCompatTextView; import androidx.appcompat.widget.SwitchCompat; import androidx.recyclerview.widget.RecyclerView; import com.kp.core.DateHelper; import com.spike.bot.R; import com.spike.bot.core.Common; import com.spike.bot.core.Constants; import com.spike.bot.customview.OnSwipeTouchListener; import com.spike.bot.model.DoorSensorResModel; import java.text.ParseException; public class TTlockInfoAdapter extends RecyclerView.Adapter<TTlockInfoAdapter.SensorViewHolder> { DoorSensorResModel.DATA.DoorList.NotificationList[] notificationList; private boolean isCF; private OnNotificationContextMenu onNotificationContextMenu; private Context mContext; String startTime, endTime, conDateStart, conDateEnd; public TTlockInfoAdapter(DoorSensorResModel.DATA.DoorList.NotificationList[] notificationList, boolean cfType, OnNotificationContextMenu onNotificationContextMenu) { this.notificationList = notificationList; this.isCF = cfType; this.onNotificationContextMenu = onNotificationContextMenu; } @Override public SensorViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_door_sensor_info, parent, false); mContext = view.getContext(); return new SensorViewHolder(view); } @Override public void onBindViewHolder(final SensorViewHolder holder, final int position) { if (position == 0) { holder.viewLine.setVisibility(View.GONE); } else { holder.viewLine.setVisibility(View.VISIBLE); } final DoorSensorResModel.DATA.DoorList.NotificationList notification = notificationList[position]; startTime = notification.getmStartDateTime(); endTime = notification.getmEndDateTime(); if (Common.getPrefValue(mContext, Constants.USER_ADMIN_TYPE).equalsIgnoreCase("0")) { if (Common.getPrefValue(mContext, Constants.USER_ID).equalsIgnoreCase(notification.getUser_id())) { holder.imgOptions.setVisibility(View.VISIBLE); } else { holder.imgOptions.setVisibility(View.INVISIBLE); } } try { conDateStart = DateHelper.formateDate(DateHelper.parseTimeSimple(startTime, DateHelper.DATE_FROMATE_HH_MM), DateHelper.DATE_FROMATE_H_M_AMPM); conDateEnd = DateHelper.formateDate(DateHelper.parseTimeSimple(endTime, DateHelper.DATE_FROMATE_HH_MM), DateHelper.DATE_FROMATE_H_M_AMPM); holder.txtMin.setText(conDateStart); holder.txtMax.setText(conDateEnd); } catch (final ParseException e) { holder.txtMin.setText(startTime); holder.txtMax.setText(endTime); e.printStackTrace(); } if (!TextUtils.isEmpty(notification.getmIsActive()) && !notification.getmIsActive().equalsIgnoreCase("null")) { holder.switchCompat.setChecked(Integer.parseInt(notification.getmIsActive()) > 0); } holder.imgOptions.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { displayContextMenu(v, notification, position); } }); holder.switchCompat.setOnTouchListener(new OnSwipeTouchListener(mContext) { @Override public void onClick() { super.onClick(); holder.switchCompat.setChecked(holder.switchCompat.isChecked()); onNotificationContextMenu.onSwitchChanged(notification, holder.switchCompat, position, !holder.switchCompat.isChecked()); } @Override public void onSwipeLeft() { super.onSwipeLeft(); holder.switchCompat.setChecked(holder.switchCompat.isChecked()); onNotificationContextMenu.onSwitchChanged(notification, holder.switchCompat, position, !holder.switchCompat.isChecked()); } @Override public void onSwipeRight() { super.onSwipeRight(); holder.switchCompat.setChecked(holder.switchCompat.isChecked()); onNotificationContextMenu.onSwitchChanged(notification, holder.switchCompat, position, !holder.switchCompat.isChecked()); } }); } /** * @param v * @param notification * @param position */ private void displayContextMenu(View v, final DoorSensorResModel.DATA.DoorList.NotificationList notification, final int position) { PopupMenu popup = new PopupMenu(mContext, v); @SuppressLint("RestrictedApi") Context wrapper = new ContextThemeWrapper(mContext, R.style.PopupMenu); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { popup = new PopupMenu(wrapper, v, Gravity.RIGHT); } else { popup = new PopupMenu(wrapper, v); } popup.getMenuInflater().inflate(R.menu.menu_dots, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_edit_dots: onNotificationContextMenu.onEditOpetion(notification, position, true); break; case R.id.action_delete_dots: onNotificationContextMenu.onEditOpetion(notification, position, false); break; } return true; } }); popup.show(); } @Override public int getItemCount() { return notificationList.length; } public class SensorViewHolder extends RecyclerView.ViewHolder { private AppCompatTextView txtMin, txtMax; private SwitchCompat switchCompat; private AppCompatImageView imgOptions; public View viewLine; public SensorViewHolder(View itemView) { super(itemView); txtMin = (AppCompatTextView) itemView.findViewById(R.id.txt_min); txtMax = (AppCompatTextView) itemView.findViewById(R.id.txt_max); switchCompat = (SwitchCompat) itemView.findViewById(R.id.switch_onoff); imgOptions = (AppCompatImageView) itemView.findViewById(R.id.img_options); viewLine = (View) itemView.findViewById(R.id.viewLine); } } public interface OnNotificationContextMenu { void onEditOpetion(DoorSensorResModel.DATA.DoorList.NotificationList notification, int position, boolean isEdit); void onSwitchChanged(DoorSensorResModel.DATA.DoorList.NotificationList notification, SwitchCompat swithcCompact, int position, boolean isActive); } }
scala-steward/scala-commons
commons-core/src/test/scala/com/avsystem/commons/rpc/RPCTest.scala
package com.avsystem.commons package rpc import com.avsystem.commons.concurrent.{HasExecutionContext, RunNowEC} import com.avsystem.commons.rpc.DummyRPC._ import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec} import scala.collection.mutable.ArrayBuffer class RPCTest extends WordSpec with Matchers with BeforeAndAfterAll { trait RunNowFutureCallbacks extends HasExecutionContext { protected implicit final def executionContext: ExecutionContext = RunNowEC } implicit class jsInterpolation(sc: StringContext) { def js(): String = write(sc.parts.mkString) } def get[T](f: Future[T]): T = f.value.get.get "rpc caller" should { "should properly deserialize RPC calls" in { val invocations = new ArrayBuffer[RawInvocation] val rawRpc = AsRawRPC[TestRPC].asRaw(TestRPC.rpcImpl((inv, _) => { invocations += inv inv.rpcName })) rawRpc.fire(RawInvocation("handleMore", Nil)) rawRpc.fire(RawInvocation("doStuff", List("42", js"omgsrsly", "true"))) assert(js"doStuffResult" == get(rawRpc.call(RawInvocation("doStuffBoolean", List("true"))))) rawRpc.fire(RawInvocation("doStuffInt", List("5"))) rawRpc.fire(RawInvocation("doStuffInt", Nil)) rawRpc.fire(RawInvocation("handleMore", Nil)) rawRpc.fire(RawInvocation("handle", Nil)) rawRpc.fire(RawInvocation("takeCC", Nil)) rawRpc.fire(RawInvocation("srslyDude", Nil)) rawRpc.get(RawInvocation("innerRpc", List(js"innerName"))).fire(RawInvocation("proc", Nil)) assert(js"innerRpc.funcResult" == get(rawRpc.get(RawInvocation("innerRpc", List(js"innerName"))) .call(RawInvocation("func", List("42"))))) assert(js"generallyDoStuffResult" == get(rawRpc.call(RawInvocation("generallyDoStuff", List(js"String", "[\"generallyDoStuffResult\"]"))))) assert(invocations.toList == List( RawInvocation("handleMore", Nil), RawInvocation("doStuff", List("42", js"omgsrsly", "true")), RawInvocation("doStuffBoolean", List("true")), RawInvocation("doStuffInt", List("5")), RawInvocation("doStuffInt", List("42")), RawInvocation("handleMore", Nil), RawInvocation("handle", Nil), RawInvocation("takeCC", List("""{"i":-1,"fuu":"_"}""")), RawInvocation("srslyDude", Nil), RawInvocation("innerRpc", List(js"innerName")), RawInvocation("innerRpc.proc", Nil), RawInvocation("innerRpc", List(js"innerName")), RawInvocation("innerRpc.func", List("42")), RawInvocation("generallyDoStuff", List(js"String", "[\"generallyDoStuffResult\"]")) )) } "fail on bad input" in { val rawRpc = AsRawRPC[TestRPC].asRaw(TestRPC.rpcImpl((_, _) => ())) intercept[UnknownRpc](rawRpc.fire(RawInvocation("whatever", Nil))) intercept[MissingRpcArgument](rawRpc.call(RawInvocation("doStuffBoolean", Nil))) intercept[InvalidRpcArgument](rawRpc.call(RawInvocation("doStuffBoolean", List("notbool")))) } "real rpc should properly serialize calls to raw rpc" in { val invocations = new ArrayBuffer[RawInvocation] object rawRpc extends RawRPC with RunNowFutureCallbacks { def fire(inv: RawInvocation): Unit = invocations += inv def call(inv: RawInvocation): Future[String] = { invocations += inv Future.successful(write(inv.rpcName + "Result")) } def get(inv: RawInvocation): RawRPC = { invocations += inv this } } val realRpc = AsRealRPC[TestRPC].asReal(rawRpc) realRpc.handleMore() realRpc.doStuff(42, "omgsrsly")(Some(true)) assert("doStuffBooleanResult" == get(realRpc.doStuff(true))) realRpc.doStuff(5) realRpc.handleMore() realRpc.handle realRpc.innerRpc("innerName").proc() realRpc.innerRpc("innerName").moreInner("moreInner").moreInner("evenMoreInner").func(42) assert(get(realRpc.generallyDoStuff(List("generallyDoStuffResult"))).contains("generallyDoStuffResult")) assert(invocations.toList == List( RawInvocation("handleMore", Nil), RawInvocation("doStuff", List("42", js"omgsrsly", "true")), RawInvocation("doStuffBoolean", List("true")), RawInvocation("doStuffInt", List("5")), RawInvocation("handleMore", Nil), RawInvocation("handle", Nil), RawInvocation("innerRpc", List(js"innerName")), RawInvocation("proc", Nil), RawInvocation("innerRpc", List(js"innerName")), RawInvocation("moreInner", List(js"moreInner")), RawInvocation("moreInner", List(js"evenMoreInner")), RawInvocation("func", List("42")), RawInvocation("generallyDoStuff", List(js"String", "[\"generallyDoStuffResult\"]")) )) } } trait BaseRPC[T] { def accept(t: T): Unit } trait ConcreteRPC extends BaseRPC[String] object ConcreteRPC extends RPCCompanion[ConcreteRPC] trait EmptyRPC object EmptyRPC extends RPCCompanion[EmptyRPC] }
symfund/microwindows
src/demos/nanox/nxterm.c
<filename>src/demos/nanox/nxterm.c<gh_stars>1-10 /* * nxterm - terminal emulator for Nano-X * * (C) 1994,95,96 by <NAME> (TeSche) * <EMAIL> * * - quite some changes for W1R1 * - yet more changes for W1R2 * * TeSche 01/96: * - supports W_ICON & W_CLOSE * - supports /etc/utmp logging for SunOS4 and Linux * - supports catching of console output for SunOS4 * Phx 02-06/96: * - supports NetBSD-Amiga * Eero 11/97: * - unsetenv(DISPLAY), setenv(LINES, COLUMNS). * - Add new text modes (you need to use terminfo...). * Eero 2/98: * - Implemented fg/bgcolor setting. With monochrome server it changes * bgmode variable, which tells in which mode to draw to screen * (M_CLEAR/M_DRAW) and affects F_REVERSE settings. * - Added a couple of checks. * 1/23/10 ghaerr * added support for UNIX98 ptys (Linux default) * added ngterm terminal type and environment variable * * TODO: * - Allocate and set sensible window palette for fg/bg color setting. * - add scroll-region ('cs') command. Fairly many programs * can take advantage of that. * - Add xterm like mouse event to terminfo key event conversion... :) * * Georg 16th Nov 2013: * - Added ANSI emulation with color support and scrolling region support * tested the emulation with the Nano editor. * made ANSI the default, select vt52 with -5 command line switch * - 8th Dec 2013: improved ANSI emulation and Nano support * - 15th Dec 2013: added reading program from command line for Linux * use double quotes when calling from a script e.g.: * bin/nano-X & bin/nxterm "ls -l *.sh >test.log" & sleep 10000 */ #define GR_COLOR_WHITESMOKE MWRGB(245,245,245) #define GR_COLOR_GAINSBORO MWRGB(220,220,220) #define GR_COLOR_ANTIQUEWHITE MWRGB(250,235,215) #define GR_COLOR_BLANCHEDALMOND MWRGB(255,235,205) #define GR_COLOR_LAVENDER MWRGB(230,230,250) #define GR_COLOR_WHITE MWRGB(255,255,255) #define _XOPEN_SOURCE 600 #include <stdio.h> #include <stdlib.h> #include <string.h> #define MWINCLUDECOLORS #include "nano-X.h" #include "nxterm.h" #include "uni_std.h" #if UNIX #include <errno.h> #include <fcntl.h> #include <pwd.h> #include <signal.h> //#include <utmp.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <termios.h> #define NSIG _NSIG #define UNIX98 1 /* use new-style /dev/ptmx, /dev/pts/0*/ #endif #define stdforeground BLACK //#define stdbackground GR_COLOR_GAINSBORO //LTGRAY //#define stdbackground BLUE //LTGRAY #define stdbackground LTGRAY #define stdcol 80 #define stdrow 50 //25 #define TITLE "nxterm" #define SMALLBUFFER stdcol //80 #define LARGEBUFFER 10240 //keyboard #define debug_screen 0 #define debug_kbd 0 /* * globals */ GR_WINDOW_ID w1; /* id for window */ GR_GC_ID gc1; /* graphics context */ GR_FONT_ID regFont; /*GR_FONT_ID boldFont;*/ GR_SCREEN_INFO si; /* screen info */ GR_FONT_INFO fi; /* Font Info */ #define fonh fi.height #define fonw fi.maxwidth GR_WINDOW_INFO wi; GR_GC_INFO gi; GR_BOOL havefocus = GR_FALSE; pid_t pid; short winw, winh, console; int pipeh; short cblink = 0, visualbell = 0, debug = 0; int fgcolor[12] = { 0,1,2,3,4,5,6,7,8,9,11 }; int bgcolor[12] = { 0,1,2,3,4,5,6,7,8,9,11 }; int scrolledFlag; /* set when screen has been scrolled up */ int isMaximized = 0; char prog_to_start[128]; int scrolltop; int scrollbottom; int ReverseMode=0; int semicolonflag = 0; int nobracket = 0; int roundbracket = 0; int savex; int savey; /* the wterm terminal code, almost like VT52 */ short termtype = 0; // 0=ANSI short bgmode, escstate, curx, cury, curon, curvis; short savx, savy, wrap, style; short col, row, colmask = 0x7f, rowmask = 0x7f; short sbufcnt = 0; short sbufx, sbufy; char lineBuffer[SMALLBUFFER+1]; char *sbuf = lineBuffer; void sigchild(int signo); int term_init(void); void sflush(void); void lineRedraw(void); void sadd(char c); void show_cursor(void); void draw_cursor(void); void hide_cursor(void); void vscrollup(int lines); void vscrolldown(int lines); void esc5(unsigned char c); void esc4(unsigned char c); void esc3(unsigned char c); void esc2(unsigned char c); void esc1(unsigned char c); void esc0(unsigned char c); void esc100(unsigned char c); //ANSI codes void printc(unsigned char c); void init(void); void term(void); void usage(char *s); int do_special_key(unsigned char *buffer, int key, int modifiers); int do_special_key_ansi(unsigned char *buffer, int key, int modifiers); void pos_xaxis(int c); /* cursor position x axis for ansi */ void pos_yaxis(int c); /* cursor position x axis for ansi */ void rendition(int escvalue); /* **************************************************************************/ void sflush(void) { if (sbufcnt) { GrText(w1,gc1, sbufx*fonw, sbufy*fonh, sbuf, sbufcnt, GR_TFTOP); sbufcnt = 0; } } void lineRedraw(void) { GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, curx*fonw, cury*fonh, (col-curx)*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); if (sbufcnt) { sbuf[sbufcnt] = 0; GrText(w1,gc1, sbufx*fonw, sbufy*fonh, sbuf, sbufcnt, GR_TFTOP); } } void sadd(char c) { if (sbufcnt == SMALLBUFFER) sflush (); if (!sbufcnt) { sbufx = curx; sbufy = cury; } sbuf[sbufcnt++] = c; } void show_cursor(void) { GrSetGCMode(gc1,GR_MODE_XOR); GrSetGCForeground(gc1, WHITE); GrFillRect(w1, gc1, curx*fonw, cury*fonh+1, fonw, fonh-1); GrSetGCForeground(gc1, gi.foreground); GrSetGCMode(gc1,GR_MODE_COPY); } void draw_cursor (void) { if(curon) if(!curvis) { curvis = 1; show_cursor(); } } void hide_cursor (void) { if(curvis) { curvis = 0; show_cursor(); } } void vscrollup(int lines) { hide_cursor(); GrCopyArea(w1,gc1, 0, (scrolltop-1)*fonh, winw, (scrollbottom-(scrolltop-1)-lines)*fonh, w1, 0, (scrolltop-1+lines)*fonh, MWROP_COPY); GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, 0, (scrollbottom-lines)*fonh, winw, lines*fonh); GrSetGCForeground(gc1,gi.foreground); } void vscrolldown(int lines) { hide_cursor(); GrCopyArea(w1,gc1, 0, (scrolltop+lines)*fonh, winw, (scrollbottom-scrolltop-lines)*fonh, w1, 0, scrolltop*fonh, MWROP_COPY); GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, 0, scrolltop*fonh, winw, lines*fonh); GrSetGCForeground(gc1,gi.foreground); } void esc5(unsigned char c) /* setting background color */ { GrSetGCBackground(gc1, c); GrGetGCInfo(gc1,&gi); escstate = 0; } void esc4(unsigned char c) /* setting foreground color */ { GrSetGCForeground(gc1,c); GrGetGCInfo(gc1,&gi); escstate = 0; } void esc3(unsigned char c) /* cursor position x axis */ { curx = (c - 32) & colmask; if (curx >= col) curx = col - 1; else if (curx < 0) curx = 0; escstate = 0; } void esc2(unsigned char c) /* cursor position y axis */ { cury = (c - 32) & rowmask; if (cury >= row) cury = row - 1; else if (cury < 0) cury = 0; escstate = 3; } void esc1(unsigned char c) /* various control codes */ { escstate = 0; /* detect ANSI / VT100 codes */ if (c=='['){ escstate = 10; return; } if (c=='('){ escstate = 10; roundbracket=1; return; } if (termtype==0){ //no bracket code - just ESC+letter //so read no further char just do esc100 and terminate //ESC state to read new sequence or unescaped chars. nobracket = 1; esc100(c); escstate = 0; return; } //now vt52 codes switch(c) { case 'A':/* cursor up */ hide_cursor(); if ((cury -= 1) < 0) cury = 0; break; case 'B':/* cursor down */ hide_cursor(); if ((cury += 1) >= row) cury = row - 1; break; case 'C':/* cursor right */ hide_cursor(); if ((curx += 1) >= col) curx = col - 1; break; case 'D':/* cursor left */ hide_cursor(); if ((curx -= 1) < 0) curx = 0; break; case 'E':/* clear screen & home */ GrClearWindow(w1, 0); curx = 0; cury = 0; break; case 'H':/* cursor home */ curx = 0; cury = 0; break; case 'I':/* reverse index */ scrolledFlag = 1; if ((cury -= 1) < 0) { cury = 0; vscrollup(1); } break; case 'J':/* erase to end of page */ if (cury < row-1) { GrSetGCForeground(gc1,gi.background); GrFillRect(w1,gc1, 0,(cury+1)*fonh, winw, (row-1-cury)*fonh); GrSetGCForeground(gc1,gi.foreground); } GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, curx*fonw, cury*fonh, (col-curx)*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); break; case 'K':/* erase to end of line */ GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, curx*fonw, cury*fonh, (col-curx)*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); break; case 'L':/* insert line */ if (cury < row-1) { vscrollup(1); } curx = 0; break; case 'M':/* delete line */ if (cury < row-1) vscrollup(1); curx = 0; break; case 'Y':/* position cursor */ escstate = 2; break; case 'b':/* set foreground color */ escstate = 4; break; case 'c':/* set background color */ escstate = 5; break; case 'd':/* erase beginning of display */ /* w_setmode(win, bgmode); */ if (cury > 0) { GrSetGCForeground(gc1,gi.background); GrFillRect(w1,gc1, 0, 0, winw, cury*fonh); GrSetGCForeground(gc1,gi.foreground); } if (curx > 0) { GrSetGCForeground(gc1,gi.background); GrFillRect(w1,gc1, 0, cury*fonh, curx*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); } break; case 'e':/* enable cursor */ curon = 1; break; case 'f':/* disable cursor */ curon = 0; break; case 'j':/* save cursor position */ savx = curx; savy = cury; break; case 'k':/* restore cursor position */ curx = savx; cury = savy; break; case 'l':/* erase entire line */ GrSetGCForeground(gc1,gi.background); GrFillRect(w1,gc1, 0, cury*fonh, winw, fonh); GrSetGCForeground(gc1,gi.foreground); curx = 0; break; case 'o':/* erase beginning of line */ if (curx > 0) { GrSetGCForeground(gc1,gi.background); GrFillRect(w1,gc1,0, cury*fonh, curx*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); } break; case 'p':/* enter reverse video mode */ if(!ReverseMode) { GrSetGCForeground(gc1,gi.background); GrSetGCBackground(gc1,gi.foreground); ReverseMode=1; } break; case 'q':/* exit reverse video mode */ if(ReverseMode) { GrSetGCForeground(gc1,gi.foreground); GrSetGCBackground(gc1,gi.background); ReverseMode=0; } break; case 'v':/* enable wrap at end of line */ wrap = 1; break; case 'w':/* disable wrap at end of line */ wrap = 0; break; /* and these are the extentions not in VT52 */ case 'G': /* clear all attributes */ break; case 'g': /* enter bold mode */ /*GrSetGCFont(gc1, boldFont); */ break; case 'h': /* exit bold mode */ /* GrSetGCFont(gc1, regFont); */ break; case 'i': /* enter underline mode */ break; /* j, k and l are already used */ case 'm': /* exit underline mode */ break; /* these ones aren't yet on the termcap entries */ case 'n': /* enter italic mode */ break; /* o, p and q are already used */ case 'r': /* exit italic mode */ break; case 's': /* enter light mode */ break; case 't': /* exit ligth mode */ break; default: /* unknown escape sequence */ #if debug_screen GrError("default:>%c<,",c); #endif break; } } void pos_xaxis(int c) /* cursor position x axis for ansi */ { curx = c & colmask; if (curx >= col) curx = col - 1; else if (curx < 0) curx = 0; } void pos_yaxis(int c) /* cursor position y axis for ansi */ { cury = c & rowmask; /* if (cury >= row) cury = row - 1; else if (cury < 0) cury = 0; */ if (cury >= scrollbottom) cury = scrollbottom - 1; else if (cury < scrolltop) cury = scrolltop-1; } void rendition(int escvalue) { if (escvalue==0) { //reset to default GrSetGCForeground(gc1, stdforeground); GrSetGCBackground(gc1, stdbackground); ReverseMode=0; } else if (escvalue==7) { //inverse if(!ReverseMode) { GrSetGCForeground(gc1,gi.background); GrSetGCBackground(gc1,gi.foreground); ReverseMode=1; } } else if (escvalue==27) { //inverse off if(ReverseMode) { GrSetGCForeground(gc1,gi.foreground); GrSetGCBackground(gc1,gi.background); ReverseMode=0; } } else if ((escvalue>29) && (escvalue<38)){ switch(escvalue) { case 30: GrSetGCForeground(gc1, BLACK); break; case 31: GrSetGCForeground(gc1, RED); break; case 32: GrSetGCForeground(gc1, GREEN); break; case 33: GrSetGCForeground(gc1, BROWN); break; case 34: GrSetGCForeground(gc1, BLUE); break; case 35: GrSetGCForeground(gc1, MAGENTA); break; case 36: GrSetGCForeground(gc1, CYAN); break; case 37: GrSetGCForeground(gc1, WHITE); break; case 39: GrSetGCForeground(gc1, stdforeground); //default color break; } } else if ((escvalue>39) && (escvalue<49)){ switch(escvalue) { case 40: GrSetGCBackground(gc1, BLACK); break; case 41: GrSetGCBackground(gc1, RED); break; case 42: GrSetGCBackground(gc1, GREEN); break; case 43: GrSetGCBackground(gc1, BROWN); break; case 44: GrSetGCBackground(gc1, BLUE); break; case 45: GrSetGCBackground(gc1, MAGENTA); break; case 46: GrSetGCBackground(gc1, CYAN); break; case 47: GrSetGCBackground(gc1, WHITE); break; case 49: GrSetGCBackground(gc1, stdbackground); //default color break; } } //if escvalue } //rendition void esc100(unsigned char c) /* various ANSI control codes */ { //leave escstate=10 till done. This states gets this function called. static int escvalue1,escvalue2,escvalue3; static char valuebuffer[3]; valuebuffer[2]='\0'; if (c == '?') return; //skip question mark for now, e.g. ESC[?7h for wrap on if (nobracket==1){ //fall through }else if (roundbracket == 1) { //just remove ESC(B for set US ASCII //fall through } else if ( (c > 0x2F) && (c<':') ) // is it a number? { if (valuebuffer[0] != '\0' ) { valuebuffer[1]=c; } else { valuebuffer[0]=c; } return; } else if (c == ';') { if (semicolonflag==0) { escvalue1=atoi(valuebuffer); semicolonflag++; valuebuffer[0]='\0'; valuebuffer[1]='\0'; return; } else if (semicolonflag==1) { escvalue2=atoi(valuebuffer); semicolonflag++; valuebuffer[0]='\0'; valuebuffer[1]='\0'; return; } } else if (((c > '@')&&(c<'[')) || ((c>0x60)&&(c<'{'))) //is it a letter? { if (semicolonflag==0) { escvalue1=atoi(valuebuffer); escvalue2=0; escvalue3=0; } else if (semicolonflag==1) { escvalue2=atoi(valuebuffer); escvalue3=0; } else if (semicolonflag==2) { escvalue3=atoi(valuebuffer); } escstate=0; valuebuffer[0]='\0'; valuebuffer[1]='\0'; } else { //unknown return; } //fall through now if letter received //now interpret the ESC sequence /* the cursor positions: cury,curx are zero based, so 0,0 is home position also if command asks to position to 5 this has to be 4 y is the row/line position, x is the column position fonh = fi.height = height of character or line in pixel fonw = fi.maxwidth = width of character in pixel winw = width of line in pixel winh = height of screen in pixel col = number of columns for current screen width row = number of lines for current screen height scrolltop, scrollbottom = upper and lower scroll region limit in lines/rows */ //GrError("\n\nC:%c,val1:%d,val2:%d,val3:%d,scflag:%d,curx:%d,cury:%d,nobracket:%d\n",c,escvalue1,escvalue2,escvalue3,semicolonflag,curx,cury,nobracket); if (nobracket==1){ if (c=='8'){ //Restore cursor //HOME will reduce by one below, so add here! escvalue1=savey+1; escvalue2=savex+1; c='H'; //position cursor } else if (c=='7'){ //save cursor savex=curx; savey=cury; c='!'; //done, so invalid code } else if (c=='M'){ //reverse index, same as cursor up but scroll display at top if (cury <= scrolltop){ escvalue1=1; c='L'; //insert line //cury--; //vscrolldown(1); //c='!'; //invalid code } else { cury--; pos_yaxis(cury); c='!'; //invalid code } } else if (c=='D'){ //index, same as cursor down but scroll display at bottom if ((cury+1) > scrollbottom){ escvalue1=1; c='M'; //delete line //vscrollup(1); //c='!'; //invalid code } else { cury++; pos_yaxis(cury); c='!'; //invalid code } } //c==8 } //nobracket nobracket=0; //always reset if (roundbracket==1){ //remove ESC(B for set to US ASCII c=0; roundbracket=0; } switch(c) { case 'A':/* cursor up */ if (escvalue1==0) escvalue1=1; hide_cursor(); if ((cury -= escvalue1) < 0) //cury = 0; cury = scrolltop-1; //cury zero based break; case 'B':/* cursor down */ if (escvalue1==0) escvalue1=1; hide_cursor(); if ((cury += escvalue1) >= row) //cury = row - 1; cury = scrollbottom-1; //cury zero based break; case 'C':/* cursor right */ if (escvalue1==0) escvalue1=1; hide_cursor(); if ((curx += escvalue1) >= col) curx = col - 1; break; case 'D':/* cursor left */ if (escvalue1==0) escvalue1=1; hide_cursor(); if ((curx -= escvalue1) < 0) curx = 0; break; case 'J': if (escvalue1==0) { //erase from current cursor to end of page/scrollbottom if (cury < scrollbottom-1) { //erase area below current line GrSetGCForeground(gc1,gi.background); GrFillRect(w1,gc1, 0,(cury+1)*fonh, winw, (scrollbottom-1-cury)*fonh); GrSetGCForeground(gc1,gi.foreground); } //erase from cursor to end of line GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, curx*fonw, cury*fonh, (col-curx)*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); break; } else if (escvalue1==1) { //erase from home/scrolltop to cursor if (cury < scrollbottom-1) { //erase area from top to line above current line GrSetGCForeground(gc1,gi.background); GrFillRect(w1,gc1, 0, scrolltop, winw, (cury+1)*fonh); GrSetGCForeground(gc1,gi.foreground); } //erase from beginning of line to cursor position GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, 0, cury*fonh, curx*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); break; } else if (escvalue1==2) { //erase entire page - leave cursor untouched //GrClearWindow(w1, 0); //erase just the scrolling area GrSetGCForeground(gc1,gi.background); GrFillRect(w1,gc1, 0, scrolltop, winw, (scrollbottom)*fonh); GrSetGCForeground(gc1,gi.foreground); break; } case 'K':/* erase to end of line */ if (escvalue1==0) { //erase from current cursor to end of line GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, curx*fonw, cury*fonh, (col-curx)*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); break; } else if (escvalue1==1) { //erase from beginning of line to cursor GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, 0, cury*fonh, curx*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); break; } else if (escvalue1==2) { //erase entire line - leave cursor untouched GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, 0, cury*fonh, winw, fonh); GrSetGCForeground(gc1,gi.foreground); break; } case 'P':/* erase number of characters after and including the cursor and move remaining to this position */ if (escvalue1==0) escvalue1=1; GrSetGCForeground(gc1,gi.background); //copy remaining chars on line to cursor position GrCopyArea(w1,gc1, curx*fonw, cury*fonh, (col-curx-escvalue1)*fonw, fonh, w1, (curx+escvalue1)*fonw, cury*fonh, MWROP_COPY); //clear space at end of line GrFillRect(w1, gc1, (col-escvalue1)*fonw, cury*fonh, (escvalue1)*fonw, fonh); GrSetGCForeground(gc1,gi.foreground); break; case 'L':/* insert lines */ if (escvalue1==0) escvalue1=1; hide_cursor(); //copy from cursor the number of lines down GrCopyArea(w1,gc1, 0, (cury+escvalue1)*fonh, winw, (scrollbottom-cury-escvalue1)*fonh, w1, 0, cury*fonh, MWROP_COPY); //clear number of lines starting at cursor position GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, 0, cury*fonh, winw, escvalue1*fonh); GrSetGCForeground(gc1,gi.foreground); break; case 'M':/* delete lines */ if (escvalue1==0) escvalue1=1; GrCopyArea(w1,gc1, 0, cury*fonh, winw, (scrollbottom-cury-escvalue1)*fonh, w1, 0, (cury+escvalue1)*fonh, MWROP_COPY); //clear number of lines starting from scrollbottom up GrSetGCForeground(gc1,gi.background); GrFillRect(w1, gc1, 0, (scrollbottom-escvalue1)*fonh, winw, escvalue1*fonh); GrSetGCForeground(gc1,gi.foreground); break; case 'S':/* scroll page up number of lines */ if (escvalue1==0) escvalue1=1; vscrollup(escvalue1); break; case 'T':/* scroll page down number of lines */ if (escvalue1==0) escvalue1=1; vscrolldown(escvalue1); break; case 'H':/* position cursor */ case 'f':/* position cursor */ if (escvalue1>0) escvalue1--; if (escvalue2>0) escvalue2--; pos_yaxis(escvalue1); pos_xaxis(escvalue2); break; case 'E':/* lines down, col=1 */ if (escvalue1==0) escvalue1=1; hide_cursor(); if ((cury += escvalue1) >= scrollbottom) cury = scrollbottom - 1; curx = 0; break; case 'F':/* lines up, col=1 */ if (escvalue1==0) escvalue1=1; hide_cursor(); if ((cury -= escvalue1) < 0) cury = 0; curx = 0; break; case 'd':/* position cursor to row */ if (escvalue1>0) escvalue1--; pos_yaxis(escvalue1); break; case '`':/* position cursor to col */ case 'G':/* position cursor to col */ if (escvalue1>0) escvalue1--; pos_xaxis(escvalue1); break; case 'e':/* move cursor down rows */ if (escvalue1>0) escvalue1--; pos_yaxis(escvalue1+cury); break; case 'a':/* move cursor right columns */ if (escvalue1>0) escvalue1--; pos_xaxis(escvalue1+curx); break; case 'm':/* Set graphics rendition */ //may be more values, do just up to three here //foreground colors run from 30 to 37, background from 40 to 47 rendition(escvalue1); //always, even if 0 if (escvalue2!=0) rendition(escvalue2); if (escvalue3!=0) rendition(escvalue3); escvalue1=0; escvalue2=0; escvalue3=0; GrGetGCInfo(gc1,&gi); break; case 's':/* save cursor position */ savx = curx; savy = cury; break; case 'u':/* restore cursor position */ curx = savx; cury = savy; break; case 'r':/* set scrolling region */ if ((escvalue1>-1) && (escvalue2 <= (winh-1))){ scrolltop = escvalue1; scrollbottom = escvalue2; } break; case 'h':/* enable private modes - e.g. wrap at end of line */ if (escvalue1==7) wrap = 1; if (escvalue1==25) show_cursor(); break; case 'l':/* disable private modes - e.g. wrap at end of line */ if (escvalue1==7) wrap = 0; if (escvalue1==25) hide_cursor(); break; default: /* unknown escape sequence */ break; } //GrError("end-C:%c,val1:%d,val2:%d,val3:%d,scflag:%d,curx:%d,cury:%d\n",c,escvalue1,escvalue2,escvalue3,semicolonflag,curx,cury); } /* * un-escaped character print routine */ void esc0 (unsigned char c) { switch (c) { case 0: /* * printing \000 on a terminal means "do nothing". * But since we use \000 as string terminator none * of the characters that follow were printed. * * perl -e 'printf("a%ca", 0);' * * said 'a' in a wterm, but should say 'aa'. This * bug screwed up most ncurses programs. */ break; case 7: /* bell */ if (visualbell) { /* w_setmode(win, M_INVERS); */ /* w_pbox(win, 0, 0, winw, winh); */ /* w_test(win, 0, 0); */ /* w_pbox(win, 0, 0, winw, winh); */ ; } else GrBell(); break; case 8: /* backspace */ hide_cursor(); if ((curx -= 1) < 0) /* lineRedraw(); if (--curx < 0) */ curx = 0; pos_xaxis(curx); break; case 9: /* tab */ { int borg,i; borg = (((curx >> 3) + 1) << 3); if(borg >= col) borg = col-1; borg = borg-curx; for(i=0; i < borg; ++i) sadd(' '); if ((curx = ((curx >> 3) + 1) << 3) >= col) curx = col - 1; pos_xaxis(curx); } break; case 10: /* line feed */ //GrError("\nLF\n"); sflush(); if (++cury >= scrollbottom) { //have to scroll before moving cursor, so reduce and add again cury--; vscrollup(1); cury++; //set cursor into lowest line (cury zero based so -1) cury = scrollbottom-1; //cury = row-1; } pos_yaxis(cury); break; case 13: /* carriage return */ sflush(); curx = 0; pos_xaxis(curx); break; case 27: /* escape */ sflush(); semicolonflag=0; escstate = 1; break; case 127: /* delete */ break; default: /* any printable char */ sadd(c); if (++curx >= col) { sflush(); if (!wrap) curx = col-1; else { curx = 0; if (++cury >= scrollbottom) vscrollup(1); } } break; } } void printc(unsigned char c) { #if debug_screen GrError("%c,",c); #endif switch(escstate) { case 0: esc0(c); break; case 1: sflush(); esc1(c); break; case 2: sflush(); esc2(c); break; case 3: sflush(); esc3(c); break; case 4: sflush(); esc4(c); break; case 5: sflush(); esc5(c); break; case 10: sflush(); esc100(c); break; default: escstate = 0; break; } } void init(void) { curx = savx = 0; cury = savy = 0; wrap = 1; curon = 1; curvis = 0; escstate = 0; } /* * general code... */ void term(void) { long in, l; GR_EVENT wevent; GR_EVENT_KEYSTROKE *kp; unsigned char buf[LARGEBUFFER]; int bufflen; if (prog_to_start[0]) { //enter program name from command line plus newline to call it now //GrError("prog_to_start:%s,len:%d\n",prog_to_start,strlen(prog_to_start)); (void)write(pipeh,prog_to_start,strlen(prog_to_start)); } while (42) { if (havefocus) draw_cursor(); GrGetNextEvent(&wevent); switch(wevent.type) { case GR_EVENT_TYPE_CLOSE_REQ: GrClose(); exit(0); break; case GR_EVENT_TYPE_KEY_DOWN: /* deal with special keys*/ kp = (GR_EVENT_KEYSTROKE *)&wevent; #if debug_kbd GrError("key-in:%X\n",kp->ch); #endif if (kp->ch & MWKEY_NONASCII_MASK) if (termtype==0){ bufflen = do_special_key_ansi(buf,kp->ch,kp->modifiers); } else { bufflen = do_special_key(buf,kp->ch,kp->modifiers); } else { *buf = kp->ch & 0xff; bufflen = 1; } if( bufflen > 0) (void)write(pipeh, buf, bufflen); #if debug_kbd GrError("key-out:%X,%X,bufflen:%d\n",buf[0],buf[1],bufflen); #endif break; case GR_EVENT_TYPE_FOCUS_IN: havefocus = GR_TRUE; break; case GR_EVENT_TYPE_FOCUS_OUT: havefocus = GR_FALSE; hide_cursor(); break; case GR_EVENT_TYPE_UPDATE: /* * if we get temporarily unmapped (moved), * set cursor state off. */ if (wevent.update.utype == GR_UPDATE_UNMAPTEMP) curvis = 0; break; case GR_EVENT_TYPE_EXPOSURE: //screen is empty otherwise - so this workaround (void)write(pipeh,"clear\n",strlen("clear\n")); break; case GR_EVENT_TYPE_FDINPUT: hide_cursor(); while ((in = read(pipeh, buf, sizeof(buf))) > 0) { for (l=0; l<in; l++) { printc(buf[l]); // if (buf[l] == '\n') // printc('\r'); } sflush(); } break; } } } int do_special_key(unsigned char *buffer, int key, int modifier) //handle vt52 keys here { int len; char *str, locbuff[256]; switch (key) { case MWKEY_LEFT: str="\033D"; len = 2; break; case MWKEY_RIGHT: str="\033C"; len=2; break; case MWKEY_UP: if(scrolledFlag) { str=""; len = 0; scrolledFlag=0; } else { str="\033A"; len=2; } break; case MWKEY_DOWN: str="\033B"; len=2; break; case MWKEY_KP0: str="\033\077\160"; len=3; break; case MWKEY_KP1: str="\033\077\161"; len=3; break; case MWKEY_KP2: str="\033\077\162"; len=3; break; case MWKEY_KP3: str="\033\077\163"; len=3; break; case MWKEY_KP4: str="\033\077\164"; len=3; break; case MWKEY_KP5: str="\033\077\165"; len=3; break; case MWKEY_KP6: str="\033\077\166"; len=3; break; case MWKEY_KP7: str="\033\077\167"; len=3; break; case MWKEY_KP8: str="\033\077\170"; len=3; break; case MWKEY_KP9: str="\033\077\161"; len=3; break; case MWKEY_KP_PERIOD: str="\033\077\156"; len=3; break; case MWKEY_KP_ENTER: str="\033\077\115"; len=3; break; case MWKEY_DELETE: str="\033C\177"; len=3; break; case MWKEY_F1 ... MWKEY_F12: if ( modifier & MWKMOD_LMETA) { /* we set background color */ locbuff[0]=033; locbuff[1]='c'; locbuff[2]=(char)bgcolor[key - MWKEY_F1]; str = locbuff; len=3; } else if ( modifier & MWKMOD_RMETA ) { /* we set foreground color */ locbuff[0]=033; locbuff[1]='b'; locbuff[2]=(char)fgcolor[key - MWKEY_F1]; str = locbuff; len=3; } else { switch (key) { case MWKEY_F1: str="\033Y"; len=2; break; case MWKEY_F2: str="\033P"; len=2; break; case MWKEY_F3: str="\033Q"; len=2; break; case MWKEY_F4: str="\033R"; len=2; break; case MWKEY_F5: str="\033S"; len=2; break; case MWKEY_F6: str="\033T"; len=2; break; case MWKEY_F7: str="\033U"; len=2; break; case MWKEY_F8: str="\033V"; len=2; break; case MWKEY_F9: str="\033W"; len=2; break; case MWKEY_F10: str="\033X"; len=2; break; } } /* fall thru*/ default: str = ""; len = 0; } if(len > 0) sprintf((char *)buffer,"%s",str); else buffer[0] = '\0'; return len; } int do_special_key_ansi(unsigned char *buffer, int key, int modifier) { int len; char *str, locbuff[256]; switch (key) { case MWKEY_LEFT: str="\033OD"; len = 3; break; case MWKEY_RIGHT: str="\033OC"; len=3; break; case MWKEY_UP: if(scrolledFlag) { str=""; len = 0; scrolledFlag=0; } else { str="\033OA"; len=3; } break; case MWKEY_DOWN: str="\033OB"; len=3; break; case MWKEY_HOME: str="\033[1~"; len=4; break; case MWKEY_INSERT: str="\033[2~"; len=4; break; case MWKEY_KP0: str="\033Op"; len=3; break; case MWKEY_END: str="\033[4~"; len=4; break; case MWKEY_KP1: str="\033Oq"; len=3; break; case MWKEY_KP2: str="\033Or"; len=3; break; case MWKEY_PAGEDOWN: str="\033[6~"; len=4; break; case MWKEY_KP3: str="\033Os"; len=3; break; case MWKEY_KP4: str="\033Ot"; len=3; break; case MWKEY_KP5: str="\033Ou"; len=3; break; case MWKEY_KP6: str="\033Ov"; len=3; break; case MWKEY_KP7: str="\033Ow"; len=3; break; case MWKEY_KP8: str="\033Ox"; len=3; break; case MWKEY_PAGEUP: str="\033[5~"; len=4; break; case MWKEY_KP9: str="\033Oy"; len=3; break; /* case MWKEY_KP_PERIOD: str="\033On"; len=3; break; */ case MWKEY_KP_ENTER: str="\033OM"; len=3; break; case MWKEY_KP_PERIOD: case MWKEY_DELETE: str="\033[3~"; len=4; break; case MWKEY_F1 ... MWKEY_F12: if ( modifier & MWKMOD_LMETA) { /* we set background color */ locbuff[0]=033; locbuff[1]='c'; locbuff[2]=(char)bgcolor[key - MWKEY_F1]; str = locbuff; len=3; } else if ( modifier & MWKMOD_RMETA ) { /* we set foreground color */ locbuff[0]=033; locbuff[1]='b'; locbuff[2]=(char)fgcolor[key - MWKEY_F1]; str = locbuff; len=3; } else { switch (key) { case MWKEY_F1: str="\033OP"; len=3; break; case MWKEY_F2: str="\033OQ"; len=3; break; case MWKEY_F3: str="\033OR"; len=3; break; case MWKEY_F4: str="\033OS"; len=3; break; case MWKEY_F5: str="\033[15~"; len=5; break; case MWKEY_F6: str="\033[17~"; //this is correct len=5; break; case MWKEY_F7: str="\033[18~"; len=5; break; case MWKEY_F8: str="\033[19~"; len=5; break; case MWKEY_F9: str="\033[20~"; len=5; break; case MWKEY_F10: str="\033[21~"; len=5; break; case MWKEY_F11: str="\033[22~"; len=5; break; case MWKEY_F12: str="\033[23~"; len=5; break; } } /* fall thru*/ default: str = ""; len = 0; } if(len > 0) sprintf((char *)buffer,"%s",str); else buffer[0] = '\0'; return len; } void usage(char *s) { if (s) GrError("error: %s\n", s); GrError("usage: nxterm [-f <font family>] [-s <font size>]\n"); GrError(" [-5] [-c] [-h] [program {args}]\n"); GrError(" -f = select font, -s = font size -5 = vt52 mode\n"); GrError(" -c = catch console output (SunOS4) -h = this help\n"); exit(0); } #if UNIX static void *mysignal(int signum, void *handler) { struct sigaction sa, so; sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sigaction(signum, &sa, &so); return so.sa_handler; } #if unused void maximize(void) { static short x0, y0, w, h, w_max,h_max; if (!isMaximized) { w_max=si.cols-wi.bordersize; h_max=si.rows-wi.bordersize; GrMoveWindow(w1,0,0); GrResizeWindow(w1,w_max, h_max); isMaximized=1; } else { GrResizeWindow(w1, w, h); GrMoveWindow(w1, x0, y0); isMaximized=0; } } #endif static void sigpipe(int sig) { /* this one musn't close the window */ /*_write_utmp(pty, "", "", 0); */ kill(-pid, SIGHUP); _exit(sig); } static void sigchld(int sig) { /* _write_utmp(pty, "", "", 0); */ _exit(sig); } static void sigquit(int sig) { signal(sig, SIG_IGN); kill(-pid, SIGHUP); } #endif /* UNIX*/ int main(int argc, char **argv) { short xp, yp, fsize; short uid; char *family, *shell = NULL, *cptr, *geometry = NULL; struct passwd *pw; char buf[stdcol]; char thesh[128]; GR_BITMAP bitmap1fg[7]; /* mouse cursor */ GR_BITMAP bitmap1bg[7]; GR_WM_PROPERTIES props; #if UNIX #ifdef SIGTTOU /* just in case we're started in the background */ signal(SIGTTOU, SIG_IGN); #endif /* who am I? */ if (!(pw = getpwuid((uid = getuid())))) { GrError("error: wterm can't determine determine your login name\n"); exit(-1); } #endif if (GrOpen() < 0) { GrError("cannot open graphics\n"); exit(1); } GrGetScreenInfo(&si); /* * scan arguments... */ console = 0; argv++; while (*argv && **argv=='-') switch (*(*argv+1)) { case '5': //vt52 mode termtype = 1; argv++; break; case 'b': cblink = 1; argv++; break; case 'c': console = 1; argv++; break; case 'd': debug = 1; argv++; break; case 'f': if (*++argv) family = *argv++; else usage("-f option requires an argument"); break; case 's': if (*++argv) fsize = atoi(*argv++); else usage("-s option requires an argument"); break; case 'g': if (*++argv) geometry = *argv++; else usage("-g option requires an argument"); break; case 'h': /* this will never return */ usage(""); break; case 'v': visualbell = 1; argv++; break; default: usage("unknown option"); } #if UNIX /* * now *argv either points to a program to start or is zero */ #ifdef __FreeBSD__ //now UNIX98 - shell is passed in FreeBSD only if (*argv) shell = *argv; #else if (*argv) { while (*argv) sprintf(prog_to_start, "%s ", *argv++); strcat(prog_to_start,"\n"); } #endif if (!shell) shell = getenv("SHELL="); if (!shell) shell = pw->pw_shell; if (!shell) shell = "/bin/sh"; if (!*argv) { /* * the '-' makes the shell think it is a login shell, * we leave argv[0] alone if it isn`t a shell (ie. * the user specified the program to run as an argument * to wterm. */ cptr = strrchr(shell, '/'); sprintf (thesh, "-%s", cptr ? cptr + 1 : shell); *--argv = thesh; } #endif col = stdcol; row = stdrow; scrolltop=0; scrollbottom=row; //zero based xp = 0; yp = 0; /* if (geometry) { if (col < 1) col = stdcol; if (row < 1) row = stdrow; if (col > 0x7f) colmask = 0xffff; if (row > 0x7f) rowmask = 0xffff; } */ regFont = GrCreateFontEx(GR_FONT_SYSTEM_FIXED, 0, 0, NULL); /*regFont = GrCreateFontEx(GR_FONT_OEM_FIXED, 0, 0, NULL);*/ /*boldFont = GrCreateFontEx(GR_FONT_SYSTEM_FIXED, 0, 0, NULL);*/ GrGetFontInfo(regFont, &fi); winw = col*fi.maxwidth; winh = (row+1)*fi.height; //w1 = GrNewWindow(GR_ROOT_WINDOW_ID, 10,10,winw, winh,0,BLACK,LTBLUE); w1 = GrNewWindow(GR_ROOT_WINDOW_ID, 10,10,winw, winh,0,stdbackground,stdforeground); props.flags = GR_WM_FLAGS_TITLE; props.title = TITLE; GrSetWMProperties(w1, &props); GrSelectEvents(w1, GR_EVENT_MASK_BUTTON_DOWN | GR_EVENT_MASK_EXPOSURE | GR_EVENT_MASK_KEY_DOWN | GR_EVENT_MASK_FOCUS_IN | GR_EVENT_MASK_FOCUS_OUT | GR_EVENT_MASK_UPDATE | GR_EVENT_MASK_CLOSE_REQ); GrMapWindow(w1); gc1 = GrNewGC(); GrSetGCFont(gc1, regFont); #define _ ((unsigned) 0) /* off bits */ #define X ((unsigned) 1) /* on bits */ #define MASK7(a,b,c,d,e,f,g) (((((((((((((a * 2) + b) * 2) + c) * 2) + d) * 2) + e) * 2) + f) * 2) + g) << 9) bitmap1fg[0] = MASK7(_,_,X,_,X,_,_); bitmap1fg[1] = MASK7(_,_,_,X,_,_,_); bitmap1fg[2] = MASK7(_,_,_,X,_,_,_); bitmap1fg[3] = MASK7(_,_,_,X,_,_,_); bitmap1fg[4] = MASK7(_,_,_,X,_,_,_); bitmap1fg[5] = MASK7(_,_,_,X,_,_,_); bitmap1fg[6] = MASK7(_,_,X,_,X,_,_); bitmap1bg[0] = MASK7(_,X,X,X,X,X,_); bitmap1bg[1] = MASK7(_,_,X,X,X,_,_); bitmap1bg[2] = MASK7(_,_,X,X,X,_,_); bitmap1bg[3] = MASK7(_,_,X,X,X,_,_); bitmap1bg[4] = MASK7(_,_,X,X,X,_,_); bitmap1bg[5] = MASK7(_,_,X,X,X,_,_); bitmap1bg[6] = MASK7(_,X,X,X,X,X,_); GrSetCursor(w1, 7, 7, 3, 3, stdforeground, stdbackground, bitmap1fg, bitmap1bg); GrSetGCForeground(gc1, stdforeground); GrSetGCBackground(gc1, stdbackground); GrGetWindowInfo(w1,&wi); GrGetGCInfo(gc1,&gi); #if UNIX /*sprintf(buf, "wterm: %s", shell); */ if (termtype==1) { //set TERM and TERMCAP for vt52 only - default is ANSI or "linux" /* * what kind of terminal do we want to emulate? */ putenv(termtype_string); /* TERM=ngterm for Linux*/ /* * this one should enable us to get rid of an /etc/termcap entry for * both curses and ncurses, hopefully... */ if (termcap_string[0]) { /* TERMCAP= string*/ sprintf(termcap_string + strlen (termcap_string), "li#%d:co#%d:", row, col); putenv(termcap_string); } } //termtype /* in case program absolutely needs terminfo entry, these 'should' * transmit the screen size of correctly (at least xterm sets these * and everything seems to work correctly...). Unlike putenv(), * setenv() allocates also the given string not just a pointer. */ sprintf(buf, "%d", col); setenv("COLUMNS", buf, 1); sprintf(buf, "%d", row); setenv("LINES", buf, 1); /* * create a pty */ pipeh = term_init(); GrRegisterInput(pipeh); /*_write_utmp(pty, pw->pw_name, "", time(0)); */ /* * grantpt docs: "The behavior of grantpt() is unspecified if a signal handler * is installed to catch SIGCHLD signals. " */ /* catch some signals */ mysignal(SIGTERM, sigquit); mysignal(SIGHUP, sigquit); mysignal(SIGINT, SIG_IGN); mysignal(SIGQUIT, sigquit); mysignal(SIGPIPE, sigpipe); mysignal(SIGCHLD, sigchld); /* prepare to catch console output */ if (console) { /* for any OS chr$(7) might cause endless loops if caught from console*/ visualbell = 1; console = 0; /* data will come to normal pipe handle */ ioctl(pipeh, TIOCCONS, 0); } #endif /* UNIX*/ init(); term(); return 0; } #if UNIX /* * pty create/open routines */ #if ELKS char * nargv[2] = {"/bin/sash", NULL}; #elif DOS_DJGPP char * nargv[2] = {"bash", NULL}; #else char * nargv[2] = {"/bin/sh", NULL}; #endif void sigchild(int signo) { GrClose(); exit(0); } #if UNIX98 int term_init(void) { int tfd; pid_t pid; char ptyname[50]; tfd = posix_openpt(O_RDWR | O_NOCTTY | O_NONBLOCK); if (tfd < 0) goto err; signal(SIGCHLD, SIG_DFL); /* required before grantpt()*/ if (grantpt(tfd) || unlockpt(tfd)) goto err; signal(SIGCHLD, sigchild); signal(SIGINT, sigchild); sprintf(ptyname,"%s",ptsname(tfd)); if ((pid = fork()) == -1) { GrError("No processes\n"); return -1; } if (!pid) { close(STDIN_FILENO); close(STDOUT_FILENO); close(tfd); setsid(); if ((tfd = open(ptyname, O_RDWR)) < 0) { GrError("Child: Can't open pty %s\n", ptyname); exit(1); } close(STDERR_FILENO); dup2(tfd, STDIN_FILENO); dup2(tfd, STDOUT_FILENO); dup2(tfd, STDERR_FILENO); execv(nargv[0], nargv); exit(1); } return tfd; err: GrError("Can't create pty /dev/ptmx\n"); return -1; } #elif !defined(__FreeBSD) /* !UNIX98*/ int term_init(void) { int tfd; pid_t pid; char pty_name[12]; again: sprintf(pty_name, "/dev/ptyp%d", n); if ((tfd = open(pty_name, O_RDWR | O_NONBLOCK)) < 0) { GrError("Can't create pty %s\n", pty_name); return -1; } signal(SIGCHLD, sigchild); signal(SIGINT, sigchild); if ((pid = fork()) == -1) { GrError("No processes\n"); return -1; } if (!pid) { close(STDIN_FILENO); close(STDOUT_FILENO); close(tfd); setsid(); pty_name[5] = 't'; if ((tfd = open(pty_name, O_RDWR)) < 0) { GrError("Child: Can't open pty %s\n", pty_name); exit(1); } close(STDERR_FILENO); dup2(tfd, STDIN_FILENO); dup2(tfd, STDOUT_FILENO); dup2(tfd, STDERR_FILENO); execv(nargv[0], nargv); exit(1); } return tfd; } #elif defined(__FreeBSD) #include <libutil.h> static char pty[SMALLBUFFER]; static struct winsize winsz; term_init(void) { char *ptr; winsz.ws_col = col; winsz.ws_row = row; if ((pid = forkpty(&pipeh, pty, NULL, &winsz)) < 0) { GrError("wterm: can't create pty\r\n"); perror("wterm"); sleep(2); GrKillWindow(w1); exit(-1); } if ((ptr = rindex(pty, '/'))) strcpy(pty, ptr + 1); if (!pid) { int i; for (i = getdtablesize(); --i >= 3; ) close (i); /* * SIG_IGN are not reset on exec() */ for (i = NSIG; --i >= 0; ) signal (i, SIG_DFL); /* caution: start shell with correct user id! */ seteuid(getuid()); setegid(getgid()); /* this shall not return */ execvp(shell, argv); /* oops? */ GrError("wterm: can't start shell\r\n"); sleep(3); GrKillWindow(w1); _exit(-1); } } #endif /* __FreeBSD__*/ #endif /* UNIX*/ #if 0 void _write_utmp(char *line, char *user, char *host, int time) { int fh, offset, isEmpty, isLine; struct utmp ut; if ((fh = open("/etc/utmp", O_RDWR)) < 0) return; /* first of all try to find an entry with the same line */ offset = 0; isEmpty = -1; isLine = -1; while ((isLine < 0) && (read(fh, &ut, sizeof(ut)) == sizeof(ut))) { if (!ut.ut_line[0]) { if (isEmpty < 0) isEmpty = offset; } else { if (!strncmp(ut.ut_line, line, sizeof(ut.ut_line))) isLine = offset; } offset += sizeof(ut); } if (isLine != -1) { /* we've found a match */ lseek(fh, isLine, SEEK_SET); } else if (isEmpty != -1) { /* no match found, but at least an empty entry */ lseek(fh, isLine, SEEK_SET); } else { /* not even an empty entry found, assume we can append to the file */ } if (time) { strncpy(ut.ut_line, line, sizeof(ut.ut_line)); strncpy(ut.ut_name, user, sizeof(ut.ut_name)); strncpy(ut.ut_host, host, sizeof(ut.ut_host)); ut.ut_time = time; } else memset(&ut, 0, sizeof(ut)); write(fh, &ut, sizeof(ut)); close(fh); } #endif
twosigma/beaker-notebook-archive
kernel/base/src/test/java/com/twosigma/beaker/chart/xychart/TimePlotTest.java
<gh_stars>1-10 /* * Copyright 2014 TWO SIGMA OPEN SOURCE, 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. */ package com.twosigma.beaker.chart.xychart; import com.twosigma.beaker.jupyter.KernelManager; import com.twosigma.beaker.KernelTest; import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; public class TimePlotTest { Date lowerBound, upperBound; @Before public void initStubData() throws ParseException { KernelManager.register(new KernelTest()); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); lowerBound = sdf.parse("01-01-2000"); upperBound = sdf.parse("05-05-2005"); } @After public void tearDown() throws Exception { KernelManager.register(null); } @Test public void setXBoundWithTwoDatesParams_shouldSetXBoundParams() { //when TimePlot timePlot = new TimePlot(); timePlot.setXBound(lowerBound, upperBound); //then Assertions.assertThat(timePlot.getXLowerBound()).isGreaterThan(0); Assertions.assertThat(timePlot.getXUpperBound()).isGreaterThan(0); Assertions.assertThat(timePlot.getXAutoRange()).isFalse(); } @Test public void setXBoundWithListParam_shouldSetXBoundParams() { //when TimePlot timePlot = new TimePlot(); timePlot.setXBound(Arrays.asList(lowerBound, upperBound)); //then Assertions.assertThat(timePlot.getXLowerBound()).isGreaterThan(0); Assertions.assertThat(timePlot.getXUpperBound()).isGreaterThan(0); Assertions.assertThat(timePlot.getXAutoRange()).isFalse(); } }
ablaev-rs/startupjs
packages/ui/components/typography/headers/H3/index.js
import generateHeader from '../generateHeader' export default generateHeader('h3')
camillobruni/pygirl
pypy/module/select/interp_select.py
from pypy.interpreter.typedef import TypeDef from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.gateway import W_Root, ObjSpace, interp2app from pypy.interpreter.error import OperationError from pypy.rlib import rpoll defaultevents = rpoll.POLLIN | rpoll.POLLOUT | rpoll.POLLPRI def poll(space): """Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events.""" return Poll() def as_fd_w(space, w_fd): if not space.is_true(space.isinstance(w_fd, space.w_int)): try: w_fileno = space.getattr(w_fd, space.wrap('fileno')) except OperationError, e: if e.match(space, space.w_AttributeError): raise OperationError(space.w_TypeError, space.wrap("argument must be an int, or have a fileno() method.")) raise w_fd = space.call_function(w_fileno) if not space.is_true(space.isinstance(w_fd, space.w_int)): raise OperationError(space.w_TypeError, space.wrap('filneo() return a non-integer')) fd = space.int_w(w_fd) if fd < 0: raise OperationError(space.w_ValueError, space.wrap("file descriptor cannot be a negative integer (%d)"%fd)) return fd class Poll(Wrappable): def __init__(self): self.fddict = {} def register(self, space, w_fd, events=defaultevents): fd = as_fd_w(space, w_fd) self.fddict[fd] = events register.unwrap_spec = ['self', ObjSpace, W_Root, int] def unregister(self, space, w_fd): fd = as_fd_w(space, w_fd) try: del self.fddict[fd] except KeyError: raise OperationError(space.w_KeyError, space.wrap(fd)) unregister.unwrap_spec = ['self', ObjSpace, W_Root] def poll(self, space, w_timeout=None): if space.is_w(w_timeout, space.w_None): timeout = -1 else: timeout = space.int_w(w_timeout) try: retval = rpoll.poll(self.fddict, timeout) except rpoll.PollError, e: w_module = space.getbuiltinmodule('select') w_errortype = space.getattr(w_module, space.wrap('error')) message = e.get_msg() raise OperationError(w_errortype, space.newtuple([space.wrap(e.errno), space.wrap(message)])) retval_w = [] for fd, revents in retval: retval_w.append(space.newtuple([space.wrap(fd), space.wrap(revents)])) return space.newlist(retval_w) poll.unwrap_spec = ['self', ObjSpace, W_Root] pollmethods = {} for methodname in 'register unregister poll'.split(): method = getattr(Poll, methodname) assert hasattr(method,'unwrap_spec'), methodname assert method.im_func.func_code.co_argcount == len(method.unwrap_spec), methodname pollmethods[methodname] = interp2app(method, unwrap_spec=method.unwrap_spec) Poll.typedef = TypeDef('select.poll', **pollmethods)
ns2j/nos2jdbc
nos2jdbc-core/src/test/java/org/seasar/extension/sql/parser/SqlTokenizerImplTest.java
/* * Copyright 2004-2015 the Seasar Foundation and the Others. * * 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.seasar.extension.sql.parser; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; import org.seasar.extension.sql.SqlTokenizer; import org.seasar.extension.sql.TokenNotClosedRuntimeException; /** * @author higa * */ class SqlTokenizerImplTest { /** * @throws Exception */ @Test void testNext() throws Exception { String sql = "SELECT * FROM emp"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "1"); assertEquals(sql, tokenizer.getToken(), "2"); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "3"); assertEquals(null, tokenizer.getToken(), "4"); } /** * @throws Exception */ @Test void testCommentEndNotFound() throws Exception { String sql = "SELECT * FROM emp/*hoge"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "1"); assertEquals("SELECT * FROM emp", tokenizer.getToken(), "2"); try { tokenizer.next(); fail("3"); } catch (TokenNotClosedRuntimeException ex) { System.out.println(ex); } } /** * @throws Exception */ @Test void testBindVariable() throws Exception { String sql = "SELECT * FROM emp WHERE job = /*job*/'CLER K' AND deptno = /*deptno*/20"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "1"); assertEquals("SELECT * FROM emp WHERE job = ", tokenizer.getToken(), "2"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "3"); assertEquals("job", tokenizer.getToken(), "4"); tokenizer.skipToken(); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "5"); assertEquals(" AND deptno = ", tokenizer.getToken(), "6"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "7"); assertEquals("deptno", tokenizer.getToken(), "8"); tokenizer.skipToken(); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "9"); } /** * @throws Exception */ @Test void testParseBindVariable2() throws Exception { String sql = "SELECT * FROM emp WHERE job = /*job*/'CLERK'/**/"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "1"); assertEquals("SELECT * FROM emp WHERE job = ", tokenizer.getToken(), "2"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "3"); assertEquals("job", tokenizer.getToken(), "4"); tokenizer.skipToken(); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "5"); assertEquals("", tokenizer.getToken(), "6"); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "7"); } /** * @throws Exception */ @Test void testParseBindVariable3() throws Exception { String sql = "/*job*/'CLERK',"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "1"); assertEquals("job", tokenizer.getToken(), "2"); tokenizer.skipToken(); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "3"); assertEquals(",", tokenizer.getToken(), "4"); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "5"); } /** * @throws Exception */ @Test void testParseElse() throws Exception { String sql = "SELECT * FROM emp WHERE /*IF job != null*/job = /*job*/'CLERK'-- ELSE job is null/*END*/"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "1"); assertEquals("SELECT * FROM emp WHERE ", tokenizer.getToken(), "2"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "3"); assertEquals("IF job != null", tokenizer.getToken(), "4"); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "5"); assertEquals("job = ", tokenizer.getToken(), "6"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "7"); assertEquals("job", tokenizer.getToken(), "8"); tokenizer.skipToken(); assertEquals(SqlTokenizer.ELSE, tokenizer.next(), "9"); tokenizer.skipWhitespace(); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "10"); assertEquals("job is null", tokenizer.getToken(), "11"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "12"); assertEquals("END", tokenizer.getToken(), "13"); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "14"); } /** * @throws Exception */ @Test void testParseElse2() throws Exception { String sql = "/*IF false*/aaa -- ELSE bbb = /*bbb*/123/*END*/"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "1"); assertEquals("IF false", tokenizer.getToken(), "2"); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "3"); assertEquals("aaa ", tokenizer.getToken(), "4"); assertEquals(SqlTokenizer.ELSE, tokenizer.next(), "5"); tokenizer.skipWhitespace(); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "6"); assertEquals("bbb = ", tokenizer.getToken(), "7"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "8"); assertEquals("bbb", tokenizer.getToken(), "9"); tokenizer.skipToken(); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "10"); assertEquals("END", tokenizer.getToken(), "11"); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "12"); } /** * @throws Exception */ @Test void testAnd() throws Exception { String sql = " AND bbb"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(" ", tokenizer.skipWhitespace(), "1"); assertEquals("AND", tokenizer.skipToken(), "2"); assertEquals(" AND", tokenizer.getBefore(), "3"); assertEquals(" bbb", tokenizer.getAfter(), "3"); } /** * @throws Exception */ @Test void testBindVariable2() throws Exception { String sql = "? abc ? def ?"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.BIND_VARIABLE, tokenizer.next(), "1"); assertEquals("$1", tokenizer.getToken(), "2"); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "3"); assertEquals(" abc ", tokenizer.getToken(), "4"); assertEquals(SqlTokenizer.BIND_VARIABLE, tokenizer.next(), "5"); assertEquals("$2", tokenizer.getToken(), "6"); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "7"); assertEquals(" def ", tokenizer.getToken(), "8"); assertEquals(SqlTokenizer.BIND_VARIABLE, tokenizer.next(), "9"); assertEquals("$3", tokenizer.getToken(), "10"); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "11"); } /** * @throws Exception */ @Test void testBindVariable3() throws Exception { String sql = "abc ? def"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "1"); assertEquals("abc ", tokenizer.getToken(), "2"); assertEquals(SqlTokenizer.BIND_VARIABLE, tokenizer.next(), "3"); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "4"); assertEquals(" def", tokenizer.getToken(), "5"); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "6"); } /** * @throws Exception */ @Test void testBindVariable4() throws Exception { String sql = "/*IF false*/aaa--ELSE bbb = /*bbb*/123/*END*/"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "1"); assertEquals("IF false", tokenizer.getToken(), "2"); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "3"); assertEquals("aaa", tokenizer.getToken(), "4"); assertEquals(SqlTokenizer.ELSE, tokenizer.next(), "5"); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "6"); assertEquals(" bbb = ", tokenizer.getToken(), "7"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "8"); assertEquals("bbb", tokenizer.getToken(), "9"); } /** * @throws Exception */ @Test void testSkipTokenForParent() throws Exception { String sql = "INSERT INTO TABLE_NAME (ID) VALUES (/*id*/20)"; SqlTokenizer tokenizer = new SqlTokenizerImpl(sql); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "1"); assertEquals(SqlTokenizer.COMMENT, tokenizer.next(), "2"); assertEquals("20", tokenizer.skipToken(), "3"); assertEquals(SqlTokenizer.SQL, tokenizer.next(), "4"); assertEquals(")", tokenizer.getToken(), "5"); assertEquals(SqlTokenizer.EOF, tokenizer.next(), "6"); } }
marcingrzejszczak/micro-infra-spring
micro-deps/micro-deps-spring-config/src/main/java/com/ofg/infrastructure/discovery/ServiceResolverConfiguration.java
<filename>micro-deps/micro-deps-spring-config/src/main/java/com/ofg/infrastructure/discovery/ServiceResolverConfiguration.java package com.ofg.infrastructure.discovery; import com.ofg.config.BasicProfiles; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** * Configuration that binds together whole service discovery. Imports: * <p/> * <ul> * <li>{@link AddressProviderConfiguration} - contains beans related to microservice's address and port resolution</li> * <li>{@link ServiceDiscoveryInfrastructureConfiguration} - contains beans related to connection to service discovery provider (available only in {@link BasicProfiles#PRODUCTION}</li> * <li>{@link DependencyResolutionConfiguration} - Configuration of microservice's dependencies resolving classes. * </ul> */ @Import({AddressProviderConfiguration.class, ServiceDiscoveryInfrastructureConfiguration.class, DependencyResolutionConfiguration.class }) @Configuration public class ServiceResolverConfiguration { }
pavelkalinin/codeeval
src/main/java/xyz/enhorse/codeeval/easy/EvenNumbers.java
package xyz.enhorse.codeeval.easy; import xyz.enhorse.codeeval.TestData; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * https://www.codeeval.com/open_challenges/100/ */ public class EvenNumbers { public static final int BUFFER_SIZE = 1024; private static final String FILE_NAME = TestData.PATH + "evennumbers.txt"; public static void main(String[] args) throws IOException { File inputFile = new File(args.length > 0 ? args[0] : FILE_NAME); FileInputStream buffer = new FileInputStream(inputFile); byte[] input = new byte[BUFFER_SIZE]; int inputLength; StringBuilder result = new StringBuilder(); int value = -1; while ((inputLength = buffer.read(input)) != -1) { for (int i = 0; i < inputLength; i++) { if (inputLength < BUFFER_SIZE && input[inputLength - 1] != '\n') { input[inputLength++] = '\n'; } if (input[i] >= '0' && input[i] <= '9') { value = input[i]; } else { if (input[i] == '\n') { result.append((value - '0') % 2 == 0 ? '1' : '0').append('\n'); } } } } System.out.print(result); buffer.close(); } }
cc1-cloud/cc1
src/wi/forms/iso_image.py
<reponame>cc1-cloud/cc1 # -*- coding: utf-8 -*- # @COPYRIGHT_begin # # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # @COPYRIGHT_end """@package src.wi.forms.iso_image @author <NAME> @author <NAME> @date 10.06.2011 """ from django import forms from django.utils.translation import ugettext_lazy as _ from wi.utils import parsing from wi.utils.forms import attrs_dict, BetterForm from wi.utils.widgets import SelectWithDisabled class UploadISOForm(BetterForm): """ Form for <b>ISO image's ulpoad</b>. """ class Meta: """ Fieldset names definition. """ fieldsets = (('description', {'fields': ('name', 'description'), 'legend': _('Disk description')}), ('settings', {'fields': ('path', 'disk_controller'), 'legend': _('Settings')}),) def __init__(self): pass name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=45)), label=_('Name')) description = forms.CharField(required=False, widget=forms.Textarea(attrs=dict(attrs_dict, maxlength=512, rows=3, cols=20)), label=_('Description')) path = forms.CharField(widget=forms.Textarea(attrs=dict(attrs_dict, maxlength=500, rows=3, cols=20)), label=_('Link to ISO image (http:// or ftp://)')) def __init__(self, *args, **kwargs): rest_data = kwargs.pop('rest_data') super(UploadISOForm, self).__init__(*args, **kwargs) self.fields['disk_controller'] = forms.ChoiceField(choices=parsing.parse_generic_enabled(rest_data, 'disk_controllers'), widget=SelectWithDisabled(attrs=dict()), label=_("Bus")) self.fields['disk_controller'].widget.attrs['class'] = 'medium' def clean_disk_controller(self): """ Cast 'disk_controller' to int. """ return int(self.cleaned_data['disk_controller']) class EditISOForm(forms.Form): """ Form for <b>ISO image edition</b>. """ name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=45)), label=_('ISO image name')) description = forms.CharField(required=False, widget=forms.Textarea(attrs=dict(attrs_dict, maxlength=512, rows=3, cols=20)), label=_('ISO image description')) def __init__(self, *args, **kwargs): rest_data = kwargs.pop('rest_data') super(EditISOForm, self).__init__(*args, **kwargs) self.fields['disk_controller'] = forms.ChoiceField(choices=parsing.parse_generic_enabled(rest_data, 'disk_controllers'), widget=SelectWithDisabled(attrs=dict()), label=_("Bus")) self.fields['disk_controller'].widget.attrs['class'] = 'medium' def clean_disk_controller(self): """ Cast 'disk_controller' to int. """ return int(self.cleaned_data['disk_controller'])
vincentliu98/voogaSalad
src/authoring_backend/src/groovy/api/GroovyFactory.java
<reponame>vincentliu98/voogaSalad<filename>src/authoring_backend/src/groovy/api/GroovyFactory.java<gh_stars>1-10 package groovy.api; import authoringUtils.frontendUtils.Try; import gameObjects.crud.GameObjectsCRUDInterface; import groovy.graph.BlockEdgeImpl; import groovy.graph.BlockGraphImpl; import groovy.graph.blocks.core.*; import groovy.graph.blocks.small_factory.LiteralFactory; import java.util.Map; /** * A Factory that can generate Graph/Node/Edge that represents Groovy code. */ public class GroovyFactory { private GameObjectsCRUDInterface entityDB; public GroovyFactory(GameObjectsCRUDInterface entityDB) { this.entityDB = entityDB; } /** * Makes an createPhaseGraph BlockGraph with one source node */ public BlockGraph createEmptyGraph() { return new BlockGraphImpl(); } public BlockGraph createDefaultGuard() { try { var graph = new BlockGraphImpl(); var returnBlock = functionBlock(1000, 1200, "GameMethods.$return", Map.of(Ports.A, "Object retVal")); var trueBlock = booleanBlock(1200, 1200, "true").get(); graph.addNode(returnBlock); graph.addNode(trueBlock); graph.addEdge(createEdge(returnBlock, Ports.A, trueBlock)); graph.addEdge(createEdge(graph.source(), Ports.FLOW_OUT, returnBlock)); return graph; } catch (Throwable throwable) { throwable.printStackTrace(); } // can't fail! return createEmptyGraph(); } public BlockGraph createDefaultImageSelector() { try { var graph = new BlockGraphImpl(); var returnBlock = functionBlock(1000, 1200, "GameMethods.$return", Map.of(Ports.A, "Object retVal")); var zeroBlock = integerBlock(1200, 1200, "0").get(); graph.addNode(returnBlock); graph.addNode(zeroBlock); graph.addEdge(createEdge(returnBlock, Ports.A, zeroBlock)); graph.addEdge(createEdge(graph.source(), Ports.FLOW_OUT, returnBlock)); return graph; } catch (Throwable throwable) { throwable.printStackTrace(); } // can't fail! return createEmptyGraph(); } /** * Makes an edge */ public BlockEdge createEdge(GroovyBlock from, Ports fromPort, GroovyBlock to) { return new BlockEdgeImpl(from, fromPort, to); } /** * Core Blocks */ public GroovyBlock<?> ifBlock(double x, double y) { return new IfBlock(x, y, false); } public GroovyBlock<?> ifElseBlock(double x, double y) { return new IfBlock(x, y, true); } public GroovyBlock<?> elseBlock(double x, double y) { return new ElseBlock(x, y); } public GroovyBlock<?> forEachBlock(double x, double y, String loopvar) { return new ForEachBlock(x, y, loopvar); } public GroovyBlock<?> assignBlock(double x, double y) { return new AssignBlock(x, y); } public Try<GroovyBlock<?>> booleanBlock(double x, double y, String value) { return LiteralFactory.booleanBlock(x, y, value); } public Try<GroovyBlock<?>> integerBlock(double x, double y, String value) { return LiteralFactory.integerBlock(x, y, value); } public Try<GroovyBlock<?>> keyBlock(double x, double y, String value) { return LiteralFactory.keyBlock(x, y, value); } public Try<GroovyBlock<?>> doubleBlock(double x, double y, String value) { return LiteralFactory.doubleBlock(x, y, value); } public Try<GroovyBlock<?>> listBlock(double x, double y, String value) { return LiteralFactory.listBlock(x, y, value); } public Try<GroovyBlock<?>> mapBlock(double x, double y, String value) { return LiteralFactory.mapBlock(x, y, value); } public GroovyBlock<?> stringBlock(double x, double y, String value) { return LiteralFactory.stringBlock(x, y, value); } public Try<GroovyBlock<?>> refBlock(double x, double y, String value) { return LiteralFactory.refBlock(x, y, value, entityDB); } public GroovyBlock<?> functionBlock(double x, double y, String op, Map<Ports, String> portInfo) { return new FunctionBlock(x, y, op, portInfo); } public GroovyBlock<?> binaryBlock(double x, double y, String op) { return new InfixBinaryBlock(x, y, op); } public GroovyBlock<?> rawBlock(double x, double y, String code) { return new RawGroovyBlock(x, y, code); } }
fa1c0n1/PublicCMS
publiccms-parent/publiccms-trade/src/main/java/com/publiccms/logic/service/trade/TradeOrderProductService.java
package com.publiccms.logic.service.trade; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; // Generated 2021-6-26 22:16:13 by com.publiccms.common.generator.SourceGenerator import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.publiccms.common.base.BaseService; import com.publiccms.common.handler.PageHandler; import com.publiccms.common.tools.CommonUtils; import com.publiccms.entities.cms.CmsContent; import com.publiccms.entities.cms.CmsContentProduct; import com.publiccms.entities.trade.TradeOrderProduct; import com.publiccms.logic.dao.trade.TradeOrderProductDao; import com.publiccms.logic.service.cms.CmsContentProductService; import com.publiccms.logic.service.cms.CmsContentService; /** * * TradeOrderProductService * */ @Service @Transactional public class TradeOrderProductService extends BaseService<TradeOrderProduct> { /** * @param siteId * @param orderId * @param pageIndex * @param pageSize * @return results page */ @Transactional(readOnly = true) public PageHandler getPage(Short siteId, Long orderId, Integer pageIndex, Integer pageSize) { return dao.getPage(siteId, orderId, pageIndex, pageSize); } /** * @param siteId * @param orderId * @param pageIndex * @param pageSize * @return results page */ @Transactional(readOnly = true) public List<TradeOrderProduct> getList(Short siteId, Long orderId) { return dao.getList(siteId, orderId); } @Transactional(isolation = Isolation.SERIALIZABLE) public BigDecimal create(short siteId, long orderId, List<TradeOrderProduct> tradeOrderProductList) { BigDecimal amount = BigDecimal.ZERO; if (null != tradeOrderProductList && 0 < tradeOrderProductList.size()) { Date now = CommonUtils.getDate(); List<Long> contentIdsList = new ArrayList<>(); List<Long> productIdsList = new ArrayList<>(); for (TradeOrderProduct entity : tradeOrderProductList) { contentIdsList.add(entity.getContentId()); productIdsList.add(entity.getProductId()); } List<CmsContent> contentList = contentService.getEntitys(contentIdsList.toArray(new Long[contentIdsList.size()])); Map<Long, CmsContent> contentMap = CommonUtils.listToMap(contentList, k -> k.getId(), null, null); List<CmsContentProduct> productList = productService .getEntitys(productIdsList.toArray(new Long[productIdsList.size()])); Map<Long, CmsContentProduct> productMap = CommonUtils.listToMap(productList, k -> k.getId(), null, null); for (TradeOrderProduct entity : tradeOrderProductList) { CmsContent content = contentMap.get(entity.getContentId()); CmsContentProduct product = productMap.get(entity.getProductId()); if (null != content && !content.isDisabled() && CmsContentService.STATUS_NORMAL == content.getStatus() && now.after(content.getPublishDate()) && (null == content.getExpiryDate() || now.before(content.getExpiryDate())) && null != product && product.getContentId() == content.getId() && 0 < product.getInventory() && 0 < entity.getQuantity() && product.getInventory() >= entity.getQuantity() && (null == product.getMinQuantity() || product.getMinQuantity() <= entity.getQuantity()) && (null == product.getMaxQuantity() || product.getMaxQuantity() >= entity.getQuantity())) { entity.setId(null); entity.setSiteId(siteId); entity.setOrderId(orderId); entity.setPrice(product.getPrice()); entity.setAmount(product.getPrice().multiply(new BigDecimal(entity.getQuantity()))); amount = amount.add(entity.getAmount()); } else { return null; } } save(tradeOrderProductList); return amount; } return null; } @Autowired private TradeOrderProductDao dao; @Autowired private CmsContentService contentService; @Autowired private CmsContentProductService productService; }
hypery2k/java-markdom
module/core/src/test/java/io/markdom/common/MarkdomHeadingLevelTests.java
<reponame>hypery2k/java-markdom package io.markdom.common; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class MarkdomHeadingLevelTests { @Test void markdomHeadingLevelByLegalOrdinal() { MarkdomHeadingLevel markdomHeadingLevel = MarkdomHeadingLevel.fromOrdinal(MarkdomHeadingLevel.LEVEL_1.toOrdinal()); assertEquals(MarkdomHeadingLevel.LEVEL_1, markdomHeadingLevel); } @Test void markdomHeadingLevelByTooSmallOrdinal() { Assertions.assertThrows(IllegalArgumentException.class, () -> { MarkdomHeadingLevel.fromOrdinal(MarkdomHeadingLevel.LEVEL_1.toOrdinal() - 1); }); } @Test void markdomHeadingLevelByTooLargeOrdinal() { Assertions.assertThrows(IllegalArgumentException.class, () -> { MarkdomHeadingLevel.fromOrdinal(MarkdomHeadingLevel.LEVEL_6.toOrdinal() + 1); }); } }
DuoSoftware/DBF-DBModels
Models/IDData.js
/** * Created by Dilshan on 5/16/2019. */ var mongoose = require('mongoose'); var Schema = mongoose.Schema; var IDDataSchema = new Schema({ recordID: {type: String}, field: {type: String}, record: {type: String}, created_at: {type: Date, default: Date.now}, updated_at: {type: Date, default: Date.now} }); module.exports.IDData = mongoose.model('IDData', IDDataSchema);
AjayKrP/Machine-Learning
MLBook/12 Evolutionary/PBIL.py
<reponame>AjayKrP/Machine-Learning # Code from Chapter 12 of Machine Learning: An Algorithmic Perspective # by <NAME> (http://seat.massey.ac.nz/personal/s.r.marsland/MLBook.html) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no warranty of any kind. # <NAME>, 2008 # The Population Based Incremental Learning algorithm # Comment and uncomment fitness functions as appropriate (as an import and the fitnessFunction variable) from pylab import * from numpy import * #import fourpeaks as fF import knapsack as fF def PBIL(): ion() populationSize = 100 stringLength = 20 eta = 0.005 #fitnessFunction = 'fF.fourpeaks' fitnessFunction = 'fF.knapsack' p = 0.5*ones(stringLength) best = zeros(501,dtype=float) for count in range(501): # Generate samples population = random.rand(populationSize,stringLength) for i in range(stringLength): population[:,i] = where(population[:,i]<p[i],1,0) # Evaluate fitness fitness = eval(fitnessFunction)(population) # Pick best best[count] = max(fitness) bestplace = argmax(fitness) fitness[bestplace] = 0 secondplace = argmax(fitness) # Update vector p = p*(1-eta) + eta*((population[bestplace,:]+population[secondplace,:])/2) if (mod(count,100)==0): print count, best[count] plot(best,'kx-') xlabel('Epochs') ylabel('Fitness') show() #print p PBIL()
ThakurKarthik/expo
ios/versioned-react-native/ABI27_0_0/Expo/Core/Api/Components/ABI27_0_0EXLinearGradient.h
<reponame>ThakurKarthik/expo // Copyright 2015-present 650 Industries. All rights reserved. #import <UIKit/UIKit.h> #import <ReactABI27_0_0/ABI27_0_0RCTView.h> @interface ABI27_0_0EXLinearGradient : ABI27_0_0RCTView @end
TheYaumrDevR/Exorions
src/de/ethasia/exorions/core/DamageTypes.java
<reponame>TheYaumrDevR/Exorions package de.ethasia.exorions.core; public enum DamageTypes { BLUNT, CUT, STAB, SUFFOCATION, SQUEEZE, RIP, SHATTER, SQUASH, POISON, INFECTION, BURN, ELECTROCUTION, DROWNING, FROST_BURN, GROUND, WIND, RADIOACTIVITY, DRYING, DISINTEGRATION }
Glaciohound/VCML
utility/cache.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # File : cache.py # Author : <NAME>, <NAME> # Email : <EMAIL>, <EMAIL> # Date : 06.08.2019 # Last Modified Date: 30.08.2019 # Last Modified By : Chi Han, Jiayuan Mao # # This file is part of the VCML codebase # Distributed under MIT license import os from utility.common import load, dump, make_parent_dir class Cache: def __init__(self, name, logger, args): self.name = name self.logger = logger self.args = args if self.args.clear_cache: logger('Clearing cache: {self.filename}') self.rm_file(empty_ok=True) def exist(self): output = os.path.exists(self.filename) return output def load(self): self.logger(f'Using cache: {self.filename}') output = load(self.filename) return output def cache(self, obj): self.logger(f'Saving cache: {self.filename}') make_parent_dir(self.filename) dump(obj, self.filename) self.obj = obj def rm_file(self, empty_ok=False): if empty_ok and not os.path.exists(self.filename): return os.remove(self.filename) @property def filename(self): output = os.path.join( self.args.cache_dir, self.name+'.pkl' ) return output def __enter__(self): if self.exist(): self.obj = self.load() else: self.logger(f'Cache not found: {self.filename}') self.obj = None return self def __exit__(self, _type, _value, _traceback): pass
ZetBrush/VidGen
app/src/main/java/org/jcodec/common/ByteArrayList.java
package org.jcodec.common; import java.util.Arrays; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * @author <NAME> * */ public class ByteArrayList { private static final int DEFAULT_GROW_AMOUNT = 2048; private byte[] storage; private int size; private int growAmount; public ByteArrayList() { this(DEFAULT_GROW_AMOUNT); } public ByteArrayList(int growAmount) { this.growAmount = growAmount; this.storage = new byte[growAmount]; } public byte[] toArray() { byte[] result = new byte[size]; System.arraycopy(storage, 0, result, 0, size); return result; } public void add(byte val) { if (size >= storage.length) { byte[] ns = new byte[storage.length + growAmount]; System.arraycopy(storage, 0, ns, 0, storage.length); storage = ns; } storage[size++] = val; } public void set(int index, byte value) { storage[index] = value; } public byte get(int index) { return storage[index]; } public void fill(int start, int end, byte val) { if (end > storage.length) { byte[] ns = new byte[end + growAmount]; System.arraycopy(storage, 0, ns, 0, storage.length); storage = ns; } Arrays.fill(storage, start, end, val); size = Math.max(size, end); } public int size() { return size; } public void addAll(byte[] other) { if (size + other.length >= storage.length) { byte[] ns = new byte[size + growAmount + other.length]; System.arraycopy(storage, 0, ns, 0, size); storage = ns; } System.arraycopy(other, 0, storage, size, other.length); size += other.length; } }
ucool2007/hiveha
src/main/java/concurrency/cookbook/chapter1/DataSourcesLoader.java
package concurrency.cookbook.chapter1; import java.util.Date; import java.util.concurrent.TimeUnit; /** * Created by lhao on 6/18/17. */ public class DataSourcesLoader implements Runnable { public void run() { System.out.printf("%s\n",new Date()); try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Data sources loading has finished:%s\n",new Date()); } public static void main(String[] args) { DataSourcesLoader dataSourcesLoader = new DataSourcesLoader(); Thread thread = new Thread(dataSourcesLoader); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Main: Configuration has been loaded: %s\n",new Date()); } }
wyj2080/springBoot
src/main/java/com/test/springBoot/mybatisPlus/service/impl/MybatisPlusServiceImpl.java
<filename>src/main/java/com/test/springBoot/mybatisPlus/service/impl/MybatisPlusServiceImpl.java package com.test.springBoot.mybatisPlus.service.impl; import com.test.springBoot.mybatisPlus.entity.MybatisPlus; import com.test.springBoot.mybatisPlus.mapper.MybatisPlusMapper; import com.test.springBoot.mybatisPlus.service.IMybatisPlusService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author author * @since 2021-07-27 */ @Service public class MybatisPlusServiceImpl extends ServiceImpl<MybatisPlusMapper, MybatisPlus> implements IMybatisPlusService { @Override public void getAndUpdate(Long id) { MybatisPlus mybatisPlus = getById(1420715833606426626L); mybatisPlus.setAge(21); updateById(mybatisPlus); } }
ChrisHampu/eve-exchange-frontend
client/components/Profile/ProfileAPIAccess.js
<gh_stars>0 /* eslint-disable global-require */ import 'whatwg-fetch'; import React from 'react'; import { connect } from 'react-redux'; import store from '../../store'; import s1 from './ProfileAPIAccess.scss'; import s2 from './ProfileSubscription.scss'; import cx from 'classnames'; import { getAuthToken } from '../../deepstream'; import { APIEndpointURL } from '../../globals'; import { sendAppNotification } from '../../actions/appActions'; import { formatNumber } from '../../utilities'; import GuidebookLink from '../Guidebook/GuidebookLink'; import RaisedButton from 'material-ui/RaisedButton'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton' class APIAccess extends React.Component { constructor(props) { super(props); this.state = { subUpgradeDialogOpen: false, subDowngradeDialogOpen: false }; } getAccessCost() { return 150000000; } getAccessCostProrate() { // Find when subscription renews const renewal = new Date(new Date(this.props.subscription.subscription_date).getTime() + 2592000000); // Current date const current = new Date(); // Offset from renewal date to today const offset = renewal.getTime() - current.getTime(); // Convert from milliseconds to number of days const days = Math.floor(offset / 1000 / 60 / 60 / 24); // Cost is total cost - prorated const cost = this.getAccessCost() - Math.max(0, Math.min(this.getAccessCost(), 5000000 * (29 - days))); return cost; } openSubUpgrade = () => this.setState({subUpgradeDialogOpen: true}); closeSubUpgrade = () => this.setState({subUpgradeDialogOpen: false}); openSubDowngrade = () => this.setState({subDowngradeDialogOpen: true}); closeSubDowngrade = () => this.setState({subDowngradeDialogOpen: false}); doEnableAPI() { fetch(`${APIEndpointURL}/subscription/api/enable`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `Token ${getAuthToken()}` } }) .then(res => { return res.json(); }) .then(res => { if (res.error) { // Something went wrong store.dispatch(sendAppNotification("There was a problem processing your request: " + res.error, 5000)); } else { store.dispatch(sendAppNotification(res.message)); } }); this.closeSubUpgrade(); }; doDisableAPI() { fetch(`${APIEndpointURL}/subscription/api/disable`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': `Token ${getAuthToken()}` } }) .then(res => { return res.json(); }) .then(res => { if (res.error) { // Something went wrong store.dispatch(sendAppNotification("There was a problem processing your request: " + res.error, 5000)); } else { store.dispatch(sendAppNotification(res.message)); } }); this.closeSubDowngrade(); } renderActivation() { if (this.props.settings.premium === false) { return <div>You need an active premium subscription in order to enable API access.</div>; } if (this.props.subscription.api_access === true) { return ( <RaisedButton backgroundColor="rgb(30, 35, 39)" labelColor="rgb(235, 169, 27)" label="Disable API Access" disabledBackgroundColor="rgb(30, 35, 39)" onTouchTap={this.openSubDowngrade} /> ); } const cost = this.getAccessCost(); return ( <RaisedButton backgroundColor="rgb(30, 35, 39)" labelColor="rgb(235, 169, 27)" label="Enable API Access" disabledBackgroundColor="rgb(30, 35, 39)" disabled={this.props.subscription.balance < cost} onTouchTap={this.openSubUpgrade} /> ); } render() { const subUpgradeActions = [ <FlatButton label="Cancel" labelStyle={{color: "rgb(235, 169, 27)"}} primary={true} onTouchTap={this.closeSubUpgrade} />, <FlatButton label="Confirm" labelStyle={{color: "rgb(235, 169, 27)"}} primary={true} keyboardFocused={true} onTouchTap={()=>{this.doEnableAPI()}} />, ]; const subDowngradeActions = [ <FlatButton label="Cancel" labelStyle={{color: "rgb(235, 169, 27)"}} primary={true} keyboardFocused={true} onTouchTap={this.closeSubDowngrade} />, <FlatButton label="Confirm" labelStyle={{color: "rgb(235, 169, 27)"}} primary={true} onTouchTap={()=>{this.doDisableAPI()}} />, ]; return ( <div className={s1.root}> <Dialog actions={subUpgradeActions} modal={false} open={this.state.subUpgradeDialogOpen} onRequestClose={this.closeSubUpgrade} > Please confirm your request to enable API access. </Dialog> <Dialog actions={subDowngradeActions} modal={false} open={this.state.subDowngradeDialogOpen} onRequestClose={this.closeSubDowngrade} > Please confirm your request to disable API access.<br /> </Dialog> <GuidebookLink settingsKey="api_access" page="api" /> <div className={s2.subscription_info} style={{marginTop: "1.5rem"}}> <div className={s2.info_row}> <div className={s2.info_key}>Your API key</div> <div className={s2.info_value}>{this.props.settings.api_key}</div> </div> <div className={s2.info_row}> <div className={s2.info_key}>Access Status</div> <div className={s2.info_value}>{this.props.subscription.api_access===true?<div style={{color: "#4CAF50"}}>Enabled</div>:<div style={{color: "#F44336"}}>Disabled</div>}</div> </div> { this.props.subscription.api_access===false? <div className={s2.info_row}> <div className={s2.info_key}>Initial Access Cost (Prorated)</div> <div className={s2.info_value}> {formatNumber(this.getAccessCostProrate())} ISK </div> </div> : false } <div className={s2.info_row}> <div className={s2.info_key}>Renewal Cost (Monthly)</div> <div className={s2.info_value}> {formatNumber(this.getAccessCost())} ISK </div> </div> </div> { this.renderActivation() } <div></div> <div> <p>The API access cost is prorated from the current day to the day your premium subscription renews, and will then cost the full amount to renew alongside your premium subscription. Premium must be maintained otherwise API access will not renew and will be disabled.</p> <p>Benefits of subscribing to API access includes access to all 23+ endpoints fully documented at <a target="_blank" href="https://api.eve.exchange">our API page</a>.</p> <p>Including the following useful endpoints:</p> <ul> <li>Current market prices (5 minute cache time)</li> <li>Market history (5 minutes, hourly, daily)</li> <li>Retrieving portfolios</li> <li>Retrieving market orders for all profiles</li> <li>Retrieving account notifications</li> </ul> </div> </div> ); } } const mapStateToProps = function(store) { return { settings: store.settings, subscription: store.subscription }; } export default connect(mapStateToProps)(APIAccess);
xman2020/x-monitor
x-monitor-server/src/test/java/x/platform/auto/dao/test/OrderDaoTest.java
package x.platform.auto.dao.test; import org.apache.ibatis.session.RowBounds; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import tk.mybatis.mapper.entity.Condition; import tk.mybatis.mapper.entity.Example; import x.platform.auto.dao.intf.OrderDao; import x.platform.auto.dmo.Order; import x.platform.monitor.Application; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class OrderDaoTest { @Autowired private OrderDao orderDao; @Test public void testInsert() { Order order = new Order(); order.setName("西瓜"); order.setMemo("海南的西瓜"); order.setPrice(BigDecimal.valueOf(4.52d)); order.setAmount(3L); order.setTotal(order.getPrice().multiply(BigDecimal.valueOf(order.getAmount()))); order.setCreateUser("dongdong"); order.setCreateTime(new Date()); this.orderDao.insert(order); } @Test public void testUpdate() { Order order = this.orderDao.selectByPrimaryKey(4); order.setMemo(null); order.setName(order.getName() + "u"); order.setUpdateUser("huihui"); order.setUpdateTime(new Date()); this.orderDao.updateByPrimaryKey(order); // 更新前:4 西瓜 海南的西瓜 4.52 3 13.56 dongdong 2020-03-27 18:34:02 // 更新后:4 西瓜u 4.52 3 13.56 dongdong huihui 2020-03-27 18:34:02 2020-03-27 18:38:38 //this.orderDao.updateByPrimaryKeySelective(order); } @Test public void testDelete() { this.orderDao.deleteByPrimaryKey(3); } @Test public void testGetById() { Order order = this.orderDao.selectByPrimaryKey(1); } @Test public void testSelectSimple() throws ParseException { Condition condition = new Condition(Order.class); Example.Criteria criteria = condition.createCriteria(); // criteria.andEqualTo("name", "苹果"); // criteria.andGreaterThan("total", 100); //criteria.andLike("name", "%西瓜%"); Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-03-27 14:00:00"); Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-03-27 18:23:00"); criteria.andBetween("createTime", date1, date2); condition.orderBy("createTime").desc(); List<Order> list = this.orderDao.selectByExample(condition); } @Test public void testSelectByPage() throws ParseException { Condition condition = new Condition(Order.class); Example.Criteria criteria = condition.createCriteria(); Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-03-27 14:00:00"); Date date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-03-30 18:23:00"); criteria.andBetween("createTime", date1, date2); condition.orderBy("createTime").desc(); RowBounds rowbounds = new RowBounds(2, 2); List<Order> list = this.orderDao.selectByExampleAndRowBounds(condition, rowbounds); } //@Test public void generate() { } }
enpelonio/O-CNN
tensorflow/script/network_segnet.py
import tensorflow as tf from ocnn import * def network_segnet(octree, flags, training, reuse=False): depth, channel_in = flags.depth, flags.channel channels = [2**(9-d) for d in range(0, 8)] with tf.variable_scope('ocnn_segnet', reuse=reuse): with tf.variable_scope('signal'): data = octree_property(octree, property_name='feature', dtype=tf.float32, depth=depth, channel=channel_in) data = tf.reshape(data, [1, channel_in, -1, 1]) # encoder unpool_idx = [None]*10 for d in range(depth, 2, -1): with tf.variable_scope('conv_%d' % d): data = octree_conv_bn_relu(data, octree, d, channels[d], training) data, unpool_idx[d] = octree_max_pool(data, octree, d) # # decoder with tf.variable_scope('deconv_2'): deconv = octree_conv_bn_relu(data, octree, 2, channels[3], training) for d in range(3, depth+1): with tf.variable_scope('deconv_%d' % d): deconv = octree_max_unpool(deconv, unpool_idx[d], octree, d-1) deconv = octree_conv_bn_relu(deconv, octree, d, channels[d+1], training) # header with tf.variable_scope('predict_label'): logit = predict_module(deconv, flags.nout, 64, training) logit = tf.transpose(tf.squeeze(logit, [0, 3])) # (1, C, H, 1) -> (H, C) return logit
Tommy-Liu/MovieQA_Contest
legacy/extract_feature.py
<filename>legacy/extract_feature.py import argparse import os from functools import partial from math import ceil from multiprocessing import Pool from os.path import join, exists import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from numpy.lib.format import read_array_header_1_0, read_magic from tqdm import tqdm from config import MovieQAPath from legacy.inception_preprocessing import preprocess_image from legacy.inception_resnet_v2 import inception_resnet_v2_arg_scope, inception_resnet_v2 from utils import data_utils as du from utils import func_utils as fu _mp = MovieQAPath() def make_parallel(model, num_gpus, imgs): out_split = [] for i in range(num_gpus): with tf.device(tf.DeviceSpec(device_type="GPU", device_index=i)): with tf.variable_scope(tf.get_variable_scope(), reuse=i > 0): out_split.append(model(images=imgs[i])) # return tf.concat(out_split, axis=0) return out_split def models(images): with slim.arg_scope(inception_resnet_v2_arg_scope()): logits, end_points = inception_resnet_v2(images, num_classes=1001, is_training=False) # return tf.nn.max_pool(end_points['Conv2d_7b_1x1'], [1, 2, 2, 1], [1, 2, 2, 1], 'VALID') return end_points['Conv2d_7b_1x1'] def load_shape(n): with open(n, 'rb') as f: major, minor = read_magic(f) shape, fortran, dtype = read_array_header_1_0(f) if len(shape) != 4: raise TypeError('Errr! Single image... %s' % n) return shape def collect(video_data, k): imgs = [join(_mp.image_dir, k, '%s_%05d.jpg' % (k, i + 1)) for i in range(0, video_data[k]['real_frames'], 10)] npy_name = join(_mp.feature_dir, k + '.npy') if not exists(npy_name) or load_shape(npy_name)[0] != len(imgs): return npy_name, len(imgs), imgs else: return None def get_images_path(): file_names, capacity, npy_names = [], [], [] video_data = dict(item for v in du.json_load(_mp.video_data_file).values() for item in v.items()) func = partial(collect, video_data) with Pool(16) as pool, tqdm(total=len(video_data), desc='Collect images') as pbar: for ins in pool.imap_unordered(func, list(video_data.keys())): if ins: npy_names.append(ins[0]) capacity.append(ins[1]) file_names.extend(ins[2]) pbar.update() return file_names, capacity, npy_names def get_images_path_v2(): file_names, capacity, npy_names = [], [], [] video_data = du.json_load(_mp.video_data_file) for imdb_key in tqdm(video_data, desc='Collect Images'): npy_names.append(join(_mp.feature_dir, imdb_key + '.npy')) videos = list(video_data[imdb_key].keys()) videos.sort() num = 0 for v in tqdm(videos): images = [join(_mp.image_dir, v, '%s_%05d.jpg' % (v, i + 1)) for i in range(0, video_data[imdb_key][v]['real_frames'], 15)] file_names.extend(images) num += len(images) capacity.append(num) print(capacity, npy_names) return file_names, capacity, npy_names def get_images_path_v3(): file_names, capacity, npy_names = [], [], [] sample = du.json_load(_mp.sample_frame_file) for imdb_key in tqdm(sample, desc='Collect Images'): # if not exists(join(_mp.feature_dir, imdb_key + '.npy')): npy_names.append(join(_mp.feature_dir, imdb_key + '.npy')) videos = list(sample[imdb_key].keys()) videos.sort() num = 0 for v in tqdm(videos): images = [join(_mp.image_dir, v, '%s_%05d.jpg' % (v, i + 1)) for i in sample[imdb_key][v]] file_names.extend(images) num += len(images) capacity.append(num) # print(capacity, npy_names) return file_names, capacity, npy_names def count_num(features_list): num = 0 for features in features_list: num += features.shape[0] return num def writer_worker(queue, capacity, npy_names): video_idx = 0 local_feature = [] local_filename = [] with tqdm(total=len(npy_names)) as pbar: while len(capacity) > video_idx: item = queue.get() if item: f, n = item local_feature.append(f) local_filename.extend(n) local_size = len(local_filename) while len(capacity) > video_idx and local_size >= capacity[video_idx]: concat_feature = np.concatenate(local_feature, axis=0) final_features = concat_feature[:capacity[video_idx]] final_filename = local_filename[:capacity[video_idx]] assert final_features.shape[0] == capacity[video_idx], \ "%s Both frames are not same!" % npy_names[video_idx] for i in range(len(final_features)): assert fu.basename_wo_ext(npy_names[video_idx]) == \ fu.basename_wo_ext(final_filename[i]).split('.')[0], \ "Wrong images! %s\n%s" % (npy_names[video_idx], final_filename[i]) try: np.save(npy_names[video_idx], final_features) except Exception as e: np.save(npy_names[video_idx], final_features) raise e pbar.set_description(' '.join([fu.basename_wo_ext(npy_names[video_idx]), str(len(final_features))])) del local_feature[:] local_feature.append(concat_feature[capacity[video_idx]:]) local_filename = local_filename[capacity[video_idx]:] local_size = len(local_filename) video_idx += 1 pbar.update() else: break def parse_func(filename): raw_image = tf.read_file(filename) image = tf.image.decode_jpeg(raw_image, channels=3) return image, filename def preprocess_func(image, filename): image = preprocess_image(image, 299, 299, is_training=False) return image, filename def input_pipeline(filename_placeholder, batch_size=32, num_worker=4): dataset = tf.data.Dataset.from_tensor_slices(filename_placeholder) dataset = dataset.repeat(1) images, names_, iterator = [], [], [] if args.num_gpu > 1: for i in range(args.num_gpu): dd = dataset.shard(args.num_gpu, i) dd = dd.map(parse_func, num_parallel_calls=num_worker) dd = dd.map(preprocess_func, num_parallel_calls=num_worker) dd = dd.batch(batch_size) dd = dd.prefetch(16) itit = dd.make_initializable_iterator() im, n_ = itit.get_next() images.append(im) names_.append(n_) iterator.append(itit) else: dataset = dataset.map(parse_func, num_parallel_calls=num_worker) dataset = dataset.batch(batch_size) dataset = dataset.prefetch(1000) iterator = dataset.make_initializable_iterator() images, names_ = iterator.get_next() return images, names_, iterator def args_parse(): parser = argparse.ArgumentParser() parser.add_argument('--num_gpu', default=1, type=int, help='Number of GPU going to be used') parser.add_argument('--batch_size', default=8, type=int, help='Batch size of images') parser.add_argument('--num_worker', default=2, type=int, help='Number of worker reading data.') parser.add_argument('--reset', action='store_true', help='Reset all the extracted features.') return parser.parse_args() if __name__ == '__main__': args = args_parse() bsize = args.batch_size num_w = args.num_worker reset = args.reset if reset: os.system('rm -rf %s' % _mp.feature_dir) fu.make_dirs(_mp.feature_dir) fn, cap, npy_n = get_images_path_v3() num_step = int(ceil(len(fn) / bsize)) fp = tf.placeholder(tf.string, shape=[None]) img, names, it = input_pipeline(fp, bsize, num_w) if args.num_gpu > 1: feature_tensor = make_parallel(models, args.num_gpu, img) else: feature_tensor = models(img) print('Pipeline setup done !!') saver = tf.train.Saver(tf.global_variables()) print('Start extract !!') config = tf.ConfigProto(allow_soft_placement=True) config.gpu_options.allow_growth = True # config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1 with tf.Session(config=config) as sess: # q = Queue() # p = Process(target=writer_worker, args=(q, cap, npy_n)) # p.start() tf.global_variables_initializer().run() tf.local_variables_initializer().run() saver.restore(sess, './inception_resnet_v2_2016_08_30.ckpt') sess.run([iit.initializer for iit in it], feed_dict={fp: fn}) # print(sess.run(feature_tensor).shape) try: for _ in range(num_step): feature, name = sess.run([feature_tensor, names]) # q.put((feature, [i.decode() for i in name])) # q.put(None) except KeyboardInterrupt: print() # p.terminate() finally: pass # p.join() # q.close()
homich1991/ignite
modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcThinBulkLoadAbstractSelfTest.java
/* * 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.ignite.jdbc.thin; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.QueryEntity; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.internal.processors.query.QueryUtils; import org.apache.ignite.testframework.GridTestUtils; import java.sql.BatchUpdateException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import java.util.Collections; import java.util.Objects; import java.util.concurrent.Callable; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SQL_PARSER_DISABLE_H2_FALLBACK; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; import static org.apache.ignite.internal.util.IgniteUtils.resolveIgnitePath; /** * COPY statement tests. */ public abstract class JdbcThinBulkLoadAbstractSelfTest extends JdbcThinAbstractDmlStatementSelfTest { /** Default table name. */ private static final String TBL_NAME = "Person"; /** JDBC statement. */ private Statement stmt; /** A CSV file with zero records */ private static final String BULKLOAD_EMPTY_CSV_FILE = Objects.requireNonNull(resolveIgnitePath("/modules/clients/src/test/resources/bulkload0.csv")) .getAbsolutePath(); /** A CSV file with one record. */ private static final String BULKLOAD_ONE_LINE_CSV_FILE = Objects.requireNonNull(resolveIgnitePath("/modules/clients/src/test/resources/bulkload1.csv")) .getAbsolutePath(); /** A CSV file with two records. */ private static final String BULKLOAD_TWO_LINES_CSV_FILE = Objects.requireNonNull(resolveIgnitePath("/modules/clients/src/test/resources/bulkload2.csv")) .getAbsolutePath(); /** A file with UTF records. */ private static final String BULKLOAD_UTF_CSV_FILE = Objects.requireNonNull(resolveIgnitePath("/modules/clients/src/test/resources/bulkload2_utf.csv")) .getAbsolutePath(); /** Basic COPY statement used in majority of the tests. */ public static final String BASIC_SQL_COPY_STMT = "copy from \"" + BULKLOAD_TWO_LINES_CSV_FILE + "\"" + " into " + TBL_NAME + " (_key, age, firstName, lastName)" + " format csv"; /** {@inheritDoc} */ @Override protected CacheConfiguration cacheConfig() { return cacheConfigWithIndexedTypes(); } /** * Creates cache configuration with {@link QueryEntity} created * using {@link CacheConfiguration#setIndexedTypes(Class[])} call. * * @return The cache configuration. */ @SuppressWarnings("unchecked") private CacheConfiguration cacheConfigWithIndexedTypes() { CacheConfiguration<?,?> cache = defaultCacheConfiguration(); cache.setCacheMode(cacheMode()); cache.setAtomicityMode(atomicityMode()); cache.setWriteSynchronizationMode(FULL_SYNC); if (cacheMode() == PARTITIONED) cache.setBackups(1); if (nearCache()) cache.setNearConfiguration(new NearCacheConfiguration()); cache.setIndexedTypes( String.class, Person.class ); return cache; } /** * Returns true if we are testing near cache. * * @return true if we are testing near cache. */ protected abstract boolean nearCache(); /** * Returns cache atomicity mode we are testing. * * @return The cache atomicity mode we are testing. */ protected abstract CacheAtomicityMode atomicityMode(); /** * Returns cache mode we are testing. * * @return The cache mode we are testing. */ protected abstract CacheMode cacheMode(); /** * Creates cache configuration with {@link QueryEntity} created * using {@link CacheConfiguration#setQueryEntities(Collection)} call. * * @return The cache configuration. */ private CacheConfiguration cacheConfigWithQueryEntity() { CacheConfiguration<?,?> cache = defaultCacheConfiguration(); cache.setCacheMode(PARTITIONED); cache.setBackups(1); cache.setWriteSynchronizationMode(FULL_SYNC); QueryEntity e = new QueryEntity(); e.setKeyType(String.class.getName()); e.setValueType("Person"); e.addQueryField("id", Integer.class.getName(), null); e.addQueryField("age", Integer.class.getName(), null); e.addQueryField("firstName", String.class.getName(), null); e.addQueryField("lastName", String.class.getName(), null); cache.setQueryEntities(Collections.singletonList(e)); return cache; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); System.setProperty(IGNITE_SQL_PARSER_DISABLE_H2_FALLBACK, "TRUE"); stmt = conn.createStatement(); assertNotNull(stmt); assertFalse(stmt.isClosed()); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { if (stmt != null && !stmt.isClosed()) stmt.close(); assertTrue(stmt.isClosed()); System.clearProperty(IGNITE_SQL_PARSER_DISABLE_H2_FALLBACK); super.afterTest(); } /** * Dead-on-arrival test. Imports two-entry CSV file into a table and checks * the created entries using SELECT statement. * * @throws SQLException If failed. */ public void testBasicStatement() throws SQLException { int updatesCnt = stmt.executeUpdate(BASIC_SQL_COPY_STMT); assertEquals(2, updatesCnt); checkCacheContents(TBL_NAME, true, 2); } /** * Imports two-entry CSV file with UTF-8 characters into a table and checks * the created entries using SELECT statement. * * @throws SQLException If failed. */ public void testUtf() throws SQLException { int updatesCnt = stmt.executeUpdate( "copy from \"" + BULKLOAD_UTF_CSV_FILE + "\" into " + TBL_NAME + " (_key, age, firstName, lastName)" + " format csv"); assertEquals(2, updatesCnt); checkUtfCacheContents(TBL_NAME, true, 2); } /** * Imports two-entry CSV file with UTF-8 characters into a table using packet size of one byte * (thus splitting each two-byte UTF-8 character into two batches) * and checks the created entries using SELECT statement. * * @throws SQLException If failed. */ public void testUtfPacketSize_1() throws SQLException { int updatesCnt = stmt.executeUpdate( "copy from \"" + BULKLOAD_UTF_CSV_FILE + "\" into " + TBL_NAME + " (_key, age, firstName, lastName)" + " format csv packet_size 1"); assertEquals(2, updatesCnt); checkUtfCacheContents(TBL_NAME, true, 2); } /** * Imports one-entry CSV file into a table and checks the entry created using SELECT statement. * * @throws SQLException If failed. */ public void testOneLineFile() throws SQLException { int updatesCnt = stmt.executeUpdate( "copy from \"" + BULKLOAD_ONE_LINE_CSV_FILE + "\" into " + TBL_NAME + " (_key, age, firstName, lastName)" + " format csv"); assertEquals(1, updatesCnt); checkCacheContents(TBL_NAME, true, 1); } /** * Imports zero-entry CSV file into a table and checks that no entries are created * using SELECT statement. * * @throws SQLException If failed. */ public void testEmptyFile() throws SQLException { int updatesCnt = stmt.executeUpdate( "copy from \"" + BULKLOAD_EMPTY_CSV_FILE + "\" into " + TBL_NAME + " (_key, age, firstName, lastName)" + " format csv"); assertEquals(0, updatesCnt); checkCacheContents(TBL_NAME, true, 0); } /** * Checks that error is reported for a non-existent file. */ public void testWrongFileName() { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { stmt.executeUpdate( "copy from \"nonexistent\" into Person" + " (_key, age, firstName, lastName)" + " format csv"); return null; } }, SQLException.class, "Failed to read file: 'nonexistent'"); } /** * Checks that error is reported if the destination table is missing. */ public void testMissingTable() { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { stmt.executeUpdate( "copy from \"" + BULKLOAD_TWO_LINES_CSV_FILE + "\" into Peterson" + " (_key, age, firstName, lastName)" + " format csv"); return null; } }, SQLException.class, "Table does not exist: PETERSON"); } /** * Checks that error is reported when a non-existing column is specified in the SQL command. */ public void testWrongColumnName() { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { stmt.executeUpdate( "copy from \"" + BULKLOAD_TWO_LINES_CSV_FILE + "\" into Person" + " (_key, age, firstName, lostName)" + " format csv"); return null; } }, SQLException.class, "Column \"LOSTNAME\" not found"); } /** * Checks that error is reported if field read from CSV file cannot be converted to the type of the column. */ public void testWrongColumnType() { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { stmt.executeUpdate( "copy from \"" + BULKLOAD_TWO_LINES_CSV_FILE + "\" into Person" + " (_key, firstName, age, lastName)" + " format csv"); return null; } }, SQLException.class, "Value conversion failed [from=java.lang.String, to=java.lang.Integer]"); } /** * Checks that if even a subset of fields is imported, the imported fields are set correctly. * * @throws SQLException If failed. */ public void testFieldsSubset() throws SQLException { int updatesCnt = stmt.executeUpdate( "copy from \"" + BULKLOAD_TWO_LINES_CSV_FILE + "\" into " + TBL_NAME + " (_key, age, firstName)" + " format csv"); assertEquals(2, updatesCnt); checkCacheContents(TBL_NAME, false, 2); } /** * Checks that bulk load works when we create table using 'CREATE TABLE' command. * * The majority of the tests in this class use {@link CacheConfiguration#setIndexedTypes(Class[])} * to create the table. * * @throws SQLException If failed. */ public void testCreateAndBulkLoadTable() throws SQLException { String tblName = QueryUtils.DFLT_SCHEMA + ".\"PersonTbl\""; execute(conn, "create table " + tblName + " (id int primary key, age int, firstName varchar(30), lastName varchar(30))"); int updatesCnt = stmt.executeUpdate( "copy from \"" + BULKLOAD_TWO_LINES_CSV_FILE + "\" into " + tblName + "(_key, age, firstName, lastName)" + " format csv"); assertEquals(2, updatesCnt); checkCacheContents(tblName, true, 2); } /** * Checks that bulk load works when we create table with {@link CacheConfiguration#setQueryEntities(Collection)}. * * The majority of the tests in this class use {@link CacheConfiguration#setIndexedTypes(Class[])} * to create a table. * * @throws SQLException If failed. */ @SuppressWarnings("unchecked") public void testConfigureQueryEntityAndBulkLoad() throws SQLException { ignite(0).getOrCreateCache(cacheConfigWithQueryEntity()); int updatesCnt = stmt.executeUpdate(BASIC_SQL_COPY_STMT); assertEquals(2, updatesCnt); checkCacheContents(TBL_NAME, true, 2); } /** * Checks that bulk load works when we use packet size of 1 byte and thus * create multiple packetes per COPY. * * @throws SQLException If failed. */ public void testPacketSize_1() throws SQLException { int updatesCnt = stmt.executeUpdate(BASIC_SQL_COPY_STMT + " packet_size 1"); assertEquals(2, updatesCnt); checkCacheContents(TBL_NAME, true, 2); } /** * Verifies exception thrown if COPY is added into a batch. * * @throws SQLException If failed. */ public void testMultipleStatement() throws SQLException { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { stmt.addBatch(BASIC_SQL_COPY_STMT); stmt.addBatch("copy from \"" + BULKLOAD_ONE_LINE_CSV_FILE + "\" into " + TBL_NAME + " (_key, age, firstName, lastName)" + " format csv"); stmt.addBatch("copy from \"" + BULKLOAD_UTF_CSV_FILE + "\" into " + TBL_NAME + " (_key, age, firstName, lastName)" + " format csv"); stmt.executeBatch(); return null; } }, BatchUpdateException.class, "COPY command cannot be executed in batch mode."); } /** * Verifies that COPY command is rejected by Statement.executeQuery(). * * @throws SQLException If failed. */ public void testExecuteQuery() throws SQLException { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { stmt.executeQuery(BASIC_SQL_COPY_STMT); return null; } }, SQLException.class, "The query isn't SELECT query"); } /** * Verifies that COPY command works in Statement.execute(). * * @throws SQLException If failed. */ public void testExecute() throws SQLException { boolean isRowSet = stmt.execute(BASIC_SQL_COPY_STMT); assertFalse(isRowSet); checkCacheContents(TBL_NAME, true, 2); } /** * Verifies that COPY command can be called with PreparedStatement.executeUpdate(). * * @throws SQLException If failed. */ public void testPreparedStatementWithExecuteUpdate() throws SQLException { PreparedStatement pstmt = conn.prepareStatement(BASIC_SQL_COPY_STMT); int updatesCnt = pstmt.executeUpdate(); assertEquals(2, updatesCnt); checkCacheContents(TBL_NAME, true, 2); } /** * Verifies that COPY command reports an error when used with PreparedStatement parameter. * * @throws SQLException If failed. */ public void testPreparedStatementWithParameter() throws SQLException { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { PreparedStatement pstmt = conn.prepareStatement( "copy from \"" + BULKLOAD_TWO_LINES_CSV_FILE + "\" into " + TBL_NAME + " (_key, age, firstName, lastName)" + " format ?"); pstmt.setString(1, "csv"); pstmt.executeUpdate(); return null; } }, SQLException.class, "Unexpected token: \"?\" (expected: \"[identifier]\""); } /** * Verifies that COPY command can be called with PreparedStatement.execute(). * * @throws SQLException If failed. */ public void testPreparedStatementWithExecute() throws SQLException { PreparedStatement pstmt = conn.prepareStatement(BASIC_SQL_COPY_STMT); boolean isRowSet = pstmt.execute(); assertFalse(isRowSet); checkCacheContents(TBL_NAME, true, 2); } /** * Verifies that COPY command is rejected by PreparedStatement.executeQuery(). */ public void testPreparedStatementWithExecuteQuery() { GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { PreparedStatement pstmt = conn.prepareStatement(BASIC_SQL_COPY_STMT); pstmt.executeQuery(); return null; } }, SQLException.class, "The query isn't SELECT query"); } /** * Checks cache contents for a typical test using SQL SELECT command. * * @param tblName Table name to query. * @param checkLastName Check 'lastName' column (not imported in some tests). * @param recCnt Number of records to expect. * @throws SQLException When one of checks has failed. */ private void checkCacheContents(String tblName, boolean checkLastName, int recCnt) throws SQLException { ResultSet rs = stmt.executeQuery("select _key, age, firstName, lastName from " + tblName); assert rs != null; int cnt = 0; while (rs.next()) { int id = rs.getInt("_key"); if (id == 123) { assertEquals(12, rs.getInt("age")); assertEquals("FirstName123 MiddleName123", rs.getString("firstName")); if (checkLastName) assertEquals("LastName123", rs.getString("lastName")); } else if (id == 456) { assertEquals(45, rs.getInt("age")); assertEquals("FirstName456", rs.getString("firstName")); if (checkLastName) assertEquals("LastName456", rs.getString("lastName")); } else fail("Wrong ID: " + id); cnt++; } assertEquals(recCnt, cnt); } /** * Checks cache contents for a UTF-8 bulk load tests using SQL SELECT command. * * @param tblName Table name to query. * @param checkLastName Check 'lastName' column (not imported in some tests). * @param recCnt Number of records to expect. * @throws SQLException When one of checks has failed. */ private void checkUtfCacheContents(String tblName, boolean checkLastName, int recCnt) throws SQLException { ResultSet rs = stmt.executeQuery("select _key, age, firstName, lastName from " + tblName); assert rs != null; int cnt = 0; while (rs.next()) { int id = rs.getInt("_key"); if (id == 123) { assertEquals(12, rs.getInt("age")); assertEquals("Имя123 Отчество123", rs.getString("firstName")); if (checkLastName) assertEquals("Фамилия123", rs.getString("lastName")); } else if (id == 456) { assertEquals(45, rs.getInt("age")); assertEquals("Имя456", rs.getString("firstName")); if (checkLastName) assertEquals("Фамилия456", rs.getString("lastName")); } else fail("Wrong ID: " + id); cnt++; } assertEquals(recCnt, cnt); } }
zakharchenkoAndrii/expo
packages/expo-ads-admob/build/AdMobBanner.web.js
import * as React from 'react'; import { Text, View } from 'react-native'; const AdMobBanner = () => (React.createElement(View, null, React.createElement(Text, null, "AdMobBanner component not supported on the web"))); export default AdMobBanner; //# sourceMappingURL=AdMobBanner.web.js.map
McLeodMoores/starling
projects/util/src/test/java/com/opengamma/util/result/ResultTest.java
<filename>projects/util/src/test/java/com/opengamma/util/result/ResultTest.java /** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.util.result; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.testng.AssertJUnit; import org.testng.annotations.Test; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.opengamma.util.test.TestGroup; /** * Tests for {@link Result}s. */ @Test(groups = TestGroup.UNIT) public class ResultTest { private static final Function<String, Result<Integer>> FUNCTION_STRLEN = new Function<String, Result<Integer>>() { @Override public Result<Integer> apply(final String input) { return Result.success(input.length()); } }; private static final Function2<String, String, Result<String>> FUNCTION_MERGE = new Function2<String, String, Result<String>>() { @Override public Result<String> apply(final String t, final String u) { return Result.success(t + " " + u); } }; //------------------------------------------------------------------------- /** * Tests a successful result. */ @Test public void success() { final Result<String> test = Result.success("success"); assertEquals(true, test.isSuccess()); assertEquals(SuccessStatus.SUCCESS, test.getStatus()); assertEquals("success", test.getValue()); assertTrue(test.getStatus().isResultAvailable()); } /** * Tests that a successful result does not have a failure message. */ @Test(expectedExceptions = IllegalStateException.class) public void successGetFailureMessage() { final Result<String> test = Result.success("success"); test.getFailureMessage(); } /** * Tests that a successful result does not contain any failures. */ @Test(expectedExceptions = IllegalStateException.class) public void successGetFailures() { final Result<String> test = Result.success("success"); test.getFailures(); } /** * Tests a flat map of a success. */ @Test public void successFlatMap() { final Result<String> success = Result.success("success"); final Result<Integer> test = success.flatMap(FUNCTION_STRLEN); assertEquals(true, test.isSuccess()); assertEquals(SuccessStatus.SUCCESS, test.getStatus()); assertEquals(Integer.valueOf(7), test.getValue()); } /** * Tests the indication of the success. */ @Test public void successIfSuccess() { final Result<String> success = Result.success("success"); final Result<Integer> test = success.ifSuccess(FUNCTION_STRLEN); assertEquals(true, test.isSuccess()); assertEquals(SuccessStatus.SUCCESS, test.getStatus()); assertEquals(Integer.valueOf(7), test.getValue()); } /** * Combines two successful results. */ @Test public void successCombineWithSuccess() { final Result<String> success1 = Result.success("Hello"); final Result<String> success2 = Result.success("World"); final Result<String> test = success1.combineWith(success2, FUNCTION_MERGE); assertEquals(true, test.isSuccess()); assertEquals(SuccessStatus.SUCCESS, test.getStatus()); assertTrue(test.getStatus().isResultAvailable()); assertEquals("Hello World", test.getValue()); } /** * Combines a success and a failure. */ @Test public void successCombineWithFailure() { final Result<String> success = Result.success("Hello"); final Result<String> failure = Result.failure(new IllegalArgumentException()); final Result<String> test = success.combineWith(failure, FUNCTION_MERGE); assertEquals(false, test.isSuccess()); assertEquals(FailureStatus.ERROR, test.getStatus()); assertFalse(test.getStatus().isResultAvailable()); assertEquals(1, test.getFailures().size()); } //------------------------------------------------------------------------- /** * Tests a failure result. */ @Test public void failure() { final Result<String> test = Result.failure(new IllegalArgumentException("failure")); assertEquals(false, test.isSuccess()); assertEquals(FailureStatus.ERROR, test.getStatus()); assertEquals("failure", test.getFailureMessage()); assertEquals(1, test.getFailures().size()); final Result<Integer> test2 = test.ifSuccess(FUNCTION_STRLEN); assertSame(test, test2); final Result<Integer> test3 = test.flatMap(FUNCTION_STRLEN); assertSame(test, test3); } /** * Tests that a value cannot be retrieved from a failure. */ @Test(expectedExceptions = IllegalStateException.class) public void failureGetValue() { final Result<String> test = Result.failure(new IllegalArgumentException()); test.getValue(); } /** * Combines a failure and a success. */ @Test public void failureCombineWithSuccess() { final Result<String> failure = Result.failure(new IllegalArgumentException("failure")); final Result<String> success = Result.success("World"); final Result<String> test = failure.combineWith(success, FUNCTION_MERGE); assertEquals(FailureStatus.ERROR, test.getStatus()); assertFalse(test.getStatus().isResultAvailable()); assertEquals("failure", test.getFailureMessage()); } /** * Combines two failures.. */ @Test public void failureCombineWithFailure() { final Result<String> failure1 = Result.failure(new IllegalArgumentException("failure")); final Result<String> failure2 = Result.failure(new IllegalArgumentException("fail")); final Result<String> test = failure1.combineWith(failure2, FUNCTION_MERGE); assertEquals(FailureStatus.ERROR, test.getStatus()); assertEquals("failure, fail", test.getFailureMessage()); } //------------------------------------------------------------------------- /** * Tests if there are failures in varargs results. */ @Test public void anyFailuresVarargs() { final Result<String> success1 = Result.success("success 1"); final Result<String> success2 = Result.success("success 1"); final Result<Object> failure1 = Result.failure(FailureStatus.MISSING_DATA, "failure 1"); final Result<Object> failure2 = Result.failure(FailureStatus.ERROR, "failure 2"); assertTrue(Result.anyFailures(failure1, failure2)); assertTrue(Result.anyFailures(failure1, success1)); assertFalse(Result.anyFailures(success1, success2)); } /** * Tests if there are failures in an iterable of results. */ @Test public void anyFailuresIterable() { final Result<String> success1 = Result.success("success 1"); final Result<String> success2 = Result.success("success 1"); final Result<Object> failure1 = Result.failure(FailureStatus.MISSING_DATA, "failure 1"); final Result<Object> failure2 = Result.failure(FailureStatus.ERROR, "failure 2"); assertTrue(Result.anyFailures(ImmutableList.of(failure1, failure2))); assertTrue(Result.anyFailures(ImmutableList.of(failure1, success1))); assertFalse(Result.anyFailures(ImmutableList.of(success1, success2))); } /** * Tests if all results are successful in varargs results. */ @Test public void allSuccessVarargs() { final Result<String> success1 = Result.success("success 1"); final Result<String> success2 = Result.success("success 1"); final Result<Object> failure1 = Result.failure(FailureStatus.MISSING_DATA, "failure 1"); final Result<Object> failure2 = Result.failure(FailureStatus.ERROR, "failure 2"); assertFalse(Result.allSuccessful(failure1, failure2)); assertFalse(Result.allSuccessful(failure1, success1)); assertTrue(Result.allSuccessful(success1, success2)); } /** * Tets if all results are successful in an iterable of results. */ @Test public void testAllSuccessIterable() { final Result<String> success1 = Result.success("success 1"); final Result<String> success2 = Result.success("success 1"); final Result<Object> failure1 = Result.failure(FailureStatus.MISSING_DATA, "failure 1"); final Result<Object> failure2 = Result.failure(FailureStatus.ERROR, "failure 2"); assertFalse(Result.allSuccessful(ImmutableList.of(failure1, failure2))); assertFalse(Result.allSuccessful(ImmutableList.of(failure1, success1))); assertTrue(Result.allSuccessful(ImmutableList.of(success1, success2))); } /** * Tests that failures are propagated when combining results. */ @Test public void propagateFailures() { final Result<String> success1 = Result.success("success 1"); final Result<String> success2 = Result.success("success 1"); final Result<Object> failure1 = Result.failure(FailureStatus.MISSING_DATA, "failure 1"); final Result<Object> failure2 = Result.failure(FailureStatus.ERROR, "failure 2"); final Result<Object> composite1 = Result.failure(success1, success2, failure1, failure2); final Collection<Failure> failures = composite1.getFailures(); final Set<Failure> expected = new HashSet<>(); expected.addAll(failure1.getFailures()); expected.addAll(failure2.getFailures()); assertEquals(expected, failures); } /** * Tests that successes cannot construct a failure. */ @Test(expectedExceptions = IllegalArgumentException.class) public void propagateSuccesses() { final Result<String> success1 = Result.success("success 1"); final Result<String> success2 = Result.success("success 1"); Result.failure(success1, success2); } /** * Tests the construction of a failure from an exception. */ @Test public void generateFailureFromException() { final Exception exception = new Exception("something went wrong"); final Result<Object> failure = Result.failure(exception); assertThat(failure.getStatus(), is((ResultStatus) FailureStatus.ERROR)); assertThat(failure.getFailureMessage(), is("something went wrong")); } /** * Tests that the exception message is used. */ @Test public void generateFailureFromExceptionWithMessage() { final Exception exception = new Exception("something went wrong"); final Result<Object> failure = Result.failure(exception, "my message"); assertThat(failure.getStatus(), is((ResultStatus) FailureStatus.ERROR)); assertThat(failure.getFailureMessage(), is("my message")); } /** * Tests that the exception message is used. */ @Test public void generateFailureFromExceptionWithCustomStatus() { final Exception exception = new Exception("something went wrong"); final Result<Object> failure = Result.failure(FailureStatus.PERMISSION_DENIED, exception); assertThat(failure.getStatus(), is((ResultStatus) FailureStatus.PERMISSION_DENIED)); assertThat(failure.getFailureMessage(), is("something went wrong")); } /** * Tests that the exception message is used. */ @Test public void generateFailureFromExceptionWithCustomStatusAndMessage() { final Exception exception = new Exception("something went wrong"); final Result<Object> failure = Result.failure(FailureStatus.PERMISSION_DENIED, exception, "my message"); assertThat(failure.getStatus(), is((ResultStatus) FailureStatus.PERMISSION_DENIED)); assertThat(failure.getFailureMessage(), is("my message")); } //------------------------------------------------------------------------- /** * Tests a duplicate failure. */ @Test public void failureDeduplicateFailure() { final Result<Object> result = Result.failure(FailureStatus.MISSING_DATA, "failure"); final Failure failure = result.getFailures().iterator().next(); final Result<Object> test1 = Result.failure(result, result); assertEquals(1, test1.getFailures().size()); assertEquals(ImmutableSet.of(failure), test1.getFailures()); assertEquals("failure", test1.getFailureMessage()); } /** * Tests combining multiple failures of the same type. */ @Test public void failureSameType() { final Result<Object> failure1 = Result.failure(FailureStatus.MISSING_DATA, "message 1"); final Result<Object> failure2 = Result.failure(FailureStatus.MISSING_DATA, "message 2"); final Result<Object> failure3 = Result.failure(FailureStatus.MISSING_DATA, "message 3"); final List<Failure> failures = new ArrayList<>(); failures.addAll(failure1.getFailures()); failures.addAll(failure2.getFailures()); failures.addAll(failure3.getFailures()); final Result<?> composite = FailureResult.of(failures); AssertJUnit.assertEquals(FailureStatus.MISSING_DATA, composite.getStatus()); AssertJUnit.assertEquals("message 1, message 2, message 3", composite.getFailureMessage()); } /** * Tests combining multiple failures of different types. */ @Test public void failureDifferentTypes() { final Result<Object> failure1 = Result.failure(FailureStatus.MISSING_DATA, "message 1"); final Result<Object> failure2 = Result.failure(FailureStatus.CALCULATION_FAILED, "message 2"); final Result<Object> failure3 = Result.failure(FailureStatus.ERROR, "message 3"); final List<Failure> failures = new ArrayList<>(); failures.addAll(failure1.getFailures()); failures.addAll(failure2.getFailures()); failures.addAll(failure3.getFailures()); final Result<?> composite = FailureResult.of(failures); AssertJUnit.assertEquals(FailureStatus.MULTIPLE, composite.getStatus()); AssertJUnit.assertEquals("message 1, message 2, message 3", composite.getFailureMessage()); } }
bihealth/sodar_core
projectroles/email.py
<filename>projectroles/email.py """Email creation and sending for the projectroles app""" import logging from django.conf import settings from django.contrib import auth, messages from django.core.mail import EmailMessage from django.urls import reverse from django.utils.timezone import localtime from projectroles.utils import build_invite_url, get_display_name # Access Django user model User = auth.get_user_model() # Settings SUBJECT_PREFIX = settings.EMAIL_SUBJECT_PREFIX EMAIL_SENDER = settings.EMAIL_SENDER DEBUG = settings.DEBUG SITE_TITLE = settings.SITE_INSTANCE_TITLE ADMIN_RECIPIENT = settings.ADMINS[0] logger = logging.getLogger(__name__) # Generic Elements ------------------------------------------------------------- MESSAGE_HEADER = r''' Dear {recipient}, This email has been automatically sent to you by {site_title}. '''.lstrip() MESSAGE_HEADER_NO_RECIPIENT = r''' This email has been automatically sent to you by {site_title}. '''.lstrip() NO_REPLY_NOTE = r''' Please do not reply to this email. ''' MESSAGE_FOOTER = r''' For support and reporting issues regarding {site_title}, contact {admin_name} ({admin_email}). ''' # Role Change Template --------------------------------------------------------- SUBJECT_ROLE_CREATE = 'Membership granted for {project_label} "{project}"' SUBJECT_ROLE_UPDATE = 'Membership changed in {project_label} "{project}"' SUBJECT_ROLE_DELETE = 'Membership removed from {project_label} "{project}"' MESSAGE_ROLE_CREATE = r''' {issuer_name} ({issuer_email}) has granted you the membership in {project_label} "{project}" with the role of "{role}". To access the {project_label} in {site_title}, please click on the following link: {project_url} '''.lstrip() MESSAGE_ROLE_UPDATE = r''' {issuer_name} ({issuer_email}) has changed your membership role in {project_label} "{project}" into "{role}". To access the {project_label} in {site_title}, please click on the following link: {project_url} '''.lstrip() MESSAGE_ROLE_DELETE = r''' {issuer_name} ({issuer_email}) has removed your membership from {project_label} "{project}". '''.lstrip() # Invite Template -------------------------------------------------------------- SUBJECT_INVITE = 'Invitation for {project_label} "{project}"' MESSAGE_INVITE_BODY = r''' You have been invited by {issuer_name} ({issuer_email}) to share data in the {project_label} "{project}" with the role of "{role}". To accept the invitation and access the {project_label} in {site_title}, please click on the following link: {invite_url} Please note that the link is only to be used once. After successfully accepting the invitation, please access the project with its URL or through the project list on the site's "Home" page. This invitation will expire on {date_expire}. ''' MESSAGE_INVITE_ISSUER = r''' Message from the sender of this invitation: ---------------------------------------- {} ---------------------------------------- ''' # Invite Acceptance Notification Template -------------------------------------- SUBJECT_ACCEPT = ( 'Invitation accepted by {user_name} for {project_label} "{project}"' ) MESSAGE_ACCEPT_BODY = r''' Invitation sent by you for role of "{role}" in {project_label} "{project}" has been accepted by {user_name} ({user_email}). They have been granted access in the {project_label} accordingly. '''.lstrip() # Invite Expiry Notification Template ------------------------------------------ SUBJECT_EXPIRY = 'Expired invitation used by {user_name} in "{project}"' MESSAGE_EXPIRY_BODY = r''' Invitation sent by you for role of "{role}" in {project_label} "{project}" was attempted to be used by {user_name} ({user_email}). This invitation has expired on {date_expire}. Because of this, access was not granted to the user. Please add the role manually with "Add Member", if you still wish to grant the user access to the {project_label}. '''.lstrip() # Project/Category Creation Notification Template ------------------------------ SUBJECT_PROJECT_CREATE = '{project_type} "{project}" created by {user_name}' MESSAGE_PROJECT_CREATE_BODY = r''' {user_name} ({user_email}) has created a new {project_type} under "{category}". You are receiving this email because you are the owner of the parent category. You have automatically inherited owner rights to the created {project_type}. Title: {project} Owner: {owner_name} ({owner_email}) You can access the project at the following link: {project_url} '''.lstrip() # Project/Category Moving Notification Template ------------------------------ SUBJECT_PROJECT_MOVE = '{project_type} "{project}" moved by {user_name}' MESSAGE_PROJECT_MOVE_BODY = r''' {user_name} ({user_email}) has moved the {project_type} "{project}" under "{category}". You are receiving this email because you are the owner of the parent category. You have automatically inherited owner rights to the created {project_type}. Title: {project} Owner: {owner_name} ({owner_email}) You can access the project at the following link: {project_url} '''.lstrip() # Email composing helpers ------------------------------------------------------ def get_invite_body(project, issuer, role_name, invite_url, date_expire_str): """ Return the invite content header. :param project: Project object :param issuer: User object :param role_name: Display name of the Role object :param invite_url: Generated URL for the invite :param date_expire_str: Expiry date as a pre-formatted string :return: string """ body = MESSAGE_HEADER_NO_RECIPIENT.format(site_title=SITE_TITLE) body += MESSAGE_INVITE_BODY.format( issuer_name=issuer.get_full_name(), issuer_email=issuer.email, project=project.title, role=role_name, invite_url=invite_url, date_expire=date_expire_str, site_title=SITE_TITLE, project_label=get_display_name(project.type), ) if not issuer.email and not settings.PROJECTROLES_EMAIL_SENDER_REPLY: body += NO_REPLY_NOTE return body def get_invite_message(message=None): """ Return the message from invite issuer, of empty string if not set. :param message: Optional user message as string :return: string """ if message and len(message) > 0: return MESSAGE_INVITE_ISSUER.format(message) return '' def get_email_header(header): """ Return the email header. :return: string """ return getattr(settings, 'PROJECTROLES_EMAIL_HEADER', None) or header def get_email_footer(): """ Return the email footer. :return: string """ return getattr( settings, 'PROJECTROLES_EMAIL_FOOTER', None ) or MESSAGE_FOOTER.format( site_title=SITE_TITLE, admin_name=ADMIN_RECIPIENT[0], admin_email=ADMIN_RECIPIENT[1], ) def get_invite_subject(project): """ Return invite email subject. :param project: Project object :return: string """ return ( SUBJECT_PREFIX + ' ' + SUBJECT_INVITE.format( project=project.title, project_label=get_display_name(project.type) ) ) def get_role_change_subject(change_type, project): """ Return role change email subject. :param change_type: Change type ('create', 'update', 'delete') :param project: Project object :return: String """ subject = SUBJECT_PREFIX + ' ' subject_kwargs = { 'project': project.title, 'project_label': get_display_name(project.type), } if change_type == 'create': subject += SUBJECT_ROLE_CREATE.format(**subject_kwargs) elif change_type == 'update': subject += SUBJECT_ROLE_UPDATE.format(**subject_kwargs) elif change_type == 'delete': subject += SUBJECT_ROLE_DELETE.format(**subject_kwargs) return subject def get_role_change_body( change_type, project, user_name, role_name, issuer, project_url ): """ Return role change email body. :param change_type: Change type ('create', 'update', 'delete') :param project: Project object :param user_name: Name of target user :param role_name: Name of role as string :param issuer: User object for issuing user :param project_url: URL for the project :return: String """ body = get_email_header( MESSAGE_HEADER.format(recipient=user_name, site_title=SITE_TITLE) ) if change_type == 'create': body += MESSAGE_ROLE_CREATE.format( issuer_name=issuer.get_full_name(), issuer_email=issuer.email, role=role_name, project=project.title, project_url=project_url, site_title=SITE_TITLE, project_label=get_display_name(project.type), ) elif change_type == 'update': body += MESSAGE_ROLE_UPDATE.format( issuer_name=issuer.get_full_name(), issuer_email=issuer.email, role=role_name, project=project.title, project_url=project_url, site_title=SITE_TITLE, project_label=get_display_name(project.type), ) elif change_type == 'delete': body += MESSAGE_ROLE_DELETE.format( issuer_name=issuer.get_full_name(), issuer_email=issuer.email, project=project.title, project_label=get_display_name(project.type), ) if not issuer.email and not settings.PROJECTROLES_EMAIL_SENDER_REPLY: body += NO_REPLY_NOTE body += get_email_footer() return body def send_mail(subject, message, recipient_list, request, reply_to=None): """ Wrapper for send_mail() with logging and error messaging. :param subject: Message subject (string) :param message: Message body (string) :param recipient_list: Recipients of email (list) :param request: Request object :param reply_to: List of emails for the "reply-to" header (optional) :return: Amount of sent email (int) """ try: e = EmailMessage( subject=subject, body=message, from_email=EMAIL_SENDER, to=recipient_list, reply_to=reply_to if isinstance(reply_to, list) else [], ) ret = e.send(fail_silently=False) logger.debug( '{} email{} sent to {}'.format( ret, 's' if ret != 1 else '', ', '.join(recipient_list) ) ) return ret except Exception as ex: error_msg = 'Error sending email: {}'.format(str(ex)) logger.error(error_msg) if DEBUG: raise ex messages.error(request, error_msg) return 0 # Sending functions ------------------------------------------------------------ def send_role_change_mail(change_type, project, user, role, request): """ Send email to user when their role in a project has been changed. :param change_type: Change type ('create', 'update', 'delete') :param project: Project object :param user: User object :param role: Role object (can be None for deletion) :param request: HTTP request :return: Amount of sent email (int) """ project_url = request.build_absolute_uri( reverse('projectroles:detail', kwargs={'project': project.sodar_uuid}) ) subject = get_role_change_subject(change_type, project) message = get_role_change_body( change_type=change_type, project=project, user_name=user.get_full_name(), role_name=role.name if role else '', issuer=request.user, project_url=project_url, ) reply_to = [request.user.email] if request.user.email else None return send_mail(subject, message, [user.email], request, reply_to) def send_invite_mail(invite, request): """ Send an email invitation to user not yet registered in the system. :param invite: ProjectInvite object :param request: HTTP request :return: Amount of sent email (int) """ invite_url = build_invite_url(invite, request) message = get_invite_body( project=invite.project, issuer=invite.issuer, role_name=invite.role.name, invite_url=invite_url, date_expire_str=localtime(invite.date_expire).strftime( '%Y-%m-%d %H:%M' ), ) message += get_invite_message(invite.message) message += get_email_footer() subject = get_invite_subject(invite.project) reply_to = [invite.issuer.email] if invite.issuer.email else None return send_mail(subject, message, [invite.email], request, reply_to) def send_accept_note(invite, request, user): """ Send a notification email to the issuer of an invitation when a user accepts the invitation. :param invite: ProjectInvite object :param request: HTTP request :return: Amount of sent email (int) """ subject = ( SUBJECT_PREFIX + ' ' + SUBJECT_ACCEPT.format( user_name=user.get_full_name(), project_label=get_display_name(invite.project.type), project=invite.project.title, ) ) message = get_email_header( MESSAGE_HEADER.format( recipient=invite.issuer.get_full_name(), site_title=SITE_TITLE ) ) message += MESSAGE_ACCEPT_BODY.format( role=invite.role.name, project=invite.project.title, user_name=user.get_full_name(), user_email=user.email, site_title=SITE_TITLE, project_label=get_display_name(invite.project.type), ) if not settings.PROJECTROLES_EMAIL_SENDER_REPLY: message += NO_REPLY_NOTE message += get_email_footer() return send_mail(subject, message, [invite.issuer.email], request) def send_expiry_note(invite, request, user_name): """ Send a notification email to the issuer of an invitation when a user attempts to accept an expired invitation. :param invite: ProjectInvite object :param request: HTTP request :param user_name: User name of invited user :return: Amount of sent email (int) """ subject = ( SUBJECT_PREFIX + ' ' + SUBJECT_EXPIRY.format( user_name=user_name, project=invite.project.title ) ) message = get_email_header( MESSAGE_HEADER.format( recipient=invite.issuer.get_full_name(), site_title=SITE_TITLE ) ) message += MESSAGE_EXPIRY_BODY.format( role=invite.role.name, project=invite.project.title, user_name=user_name, user_email=invite.email, date_expire=localtime(invite.date_expire).strftime('%Y-%m-%d %H:%M'), site_title=SITE_TITLE, project_label=get_display_name(invite.project.type), ) if not settings.PROJECTROLES_EMAIL_SENDER_REPLY: message += NO_REPLY_NOTE message += get_email_footer() return send_mail(subject, message, [invite.issuer.email], request) def send_project_create_mail(project, request): """ Send email about project creation to the owner of the parent category, if they are a different user than the project creator. :param project: Project object for the newly created project :param request: Request object :return: Amount of sent email (int) """ parent = project.parent parent_owner = project.parent.get_owner() if project.parent else None project_owner = project.get_owner() if not parent or not parent_owner or parent_owner.user == request.user: return 0 subject = SUBJECT_PROJECT_CREATE.format( project_type=get_display_name(project.type, title=True), project=project.title, user_name=request.user.get_full_name(), ) message = get_email_header( MESSAGE_HEADER.format( recipient=parent_owner.user.get_full_name(), site_title=SITE_TITLE ) ) message += MESSAGE_PROJECT_CREATE_BODY.format( user_name=request.user.get_full_name(), user_email=request.user.email, project_type=get_display_name(project.type), category=parent.title, project=project.title, owner_name=project_owner.user.get_full_name(), owner_email=project_owner.user.email, project_url=request.build_absolute_uri( reverse( 'projectroles:detail', kwargs={'project': project.sodar_uuid} ) ), ) message += get_email_footer() return send_mail( subject, message, [parent_owner.user.email], request, reply_to=[request.user.email], ) def send_project_move_mail(project, request): """ Send email about project being moved to the owner of the parent category, if they are a different user than the project creator. :param project: Project object for the newly created project :param request: Request object :return: Amount of sent email (int) """ parent = project.parent parent_owner = project.parent.get_owner() if project.parent else None project_owner = project.get_owner() if not parent or not parent_owner or parent_owner.user == request.user: return 0 subject = SUBJECT_PROJECT_MOVE.format( project_type=get_display_name(project.type, title=True), project=project.title, user_name=request.user.get_full_name(), ) message = get_email_header( MESSAGE_HEADER.format( recipient=parent_owner.user.get_full_name(), site_title=SITE_TITLE ) ) message += MESSAGE_PROJECT_MOVE_BODY.format( user_name=request.user.get_full_name(), user_email=request.user.email, project_type=get_display_name(project.type), category=parent.title, project=project.title, owner_name=project_owner.user.get_full_name(), owner_email=project_owner.user.email, project_url=request.build_absolute_uri( reverse( 'projectroles:detail', kwargs={'project': project.sodar_uuid} ) ), ) message += get_email_footer() return send_mail( subject, message, [parent_owner.user.email], request, reply_to=[request.user.email], ) def send_generic_mail( subject_body, message_body, recipient_list, request, reply_to=None ): """ Send a notification email to the issuer of an invitation when a user attempts to accept an expired invitation. :param subject_body: Subject body without prefix (string) :param message_body: Message body before header or footer (string) :param recipient_list: Recipients (list of User objects or email strings) :param reply_to: List of emails for the "reply-to" header (optional) :param request: HTTP request :return: Amount of mail sent (int) """ subject = SUBJECT_PREFIX + ' ' + subject_body ret = 0 for recipient in recipient_list: if isinstance(recipient, User): recp_name = recipient.get_full_name() recp_email = recipient.email else: recp_name = 'recipient' recp_email = recipient message = get_email_header( MESSAGE_HEADER.format(recipient=recp_name, site_title=SITE_TITLE) ) message += message_body if not reply_to and not settings.PROJECTROLES_EMAIL_SENDER_REPLY: message += NO_REPLY_NOTE message += get_email_footer() ret += send_mail(subject, message, [recp_email], request, reply_to) return ret
golap-cn/contact-web-app
bizui/src/actioncenter/ActionCenter.model.js
<gh_stars>1-10 import ActionCenterService from './ActionCenter.service' import { notification } from 'antd' export default { namespace: 'actioncenter', state: {}, subscriptions: { setup({ dispatch, history }) { }, }, effects: { *executeAction({ payload }, { call, put }) { //const {ProvinceService} = GlobalComponents; const {action, url,successAction}= payload if(!url){ return } // yield put({ type: 'showLoading', payload }) const data = yield call(ActionCenterService.execute, payload.url) console.log("action center received data",data) //const {successAction} = payload.successAction notification.success({ message: `${action.actionName}成功`, description: `${action.actionName}执行成功`, }) yield put(successAction) }, }, reducers: { updateState(state, action) { const payload = { ...action.payload, loading: false } return { ...payload } }, }, }
Howinfun/study-in-work-and-life
test-demo/src/main/java/com/hyf/testDemo/redis/cluster/TestCluster.java
<reponame>Howinfun/study-in-work-and-life package com.hyf.testDemo.redis.cluster; import lombok.extern.slf4j.Slf4j; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import java.util.HashSet; import java.util.Set; /** * 测试Redis集群 * @author winfun * @date 2020/10/21 5:48 下午 **/ public class TestCluster { public static void main(String[] args) throws Exception{ Set<HostAndPort> nodes = new HashSet<>(6); nodes.add(new HostAndPort("127.0.0.1",6379)); nodes.add(new HostAndPort("127.0.0.1",6380)); nodes.add(new HostAndPort("127.0.0.1",6381)); JedisCluster cluster = new JedisCluster(nodes); String value = cluster.get("key"); System.out.println("get: key is key,value is "+value); String result = cluster.set("key2","hello world"); System.out.println("set: key is key2,result is "+result); cluster.close(); } }
NLeSC/escxnat
nl.esciencecenter.xnattool/testsrc/tests/other/webclient/Test_WebClientSSL.java
<reponame>NLeSC/escxnat /* * Copyright 2012-2013 Netherlands eScience Center. * * 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 the following location: * * 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. * * For the full license, see: LICENSE.txt (located in the root folder of this distribution). * --- */ // source: package tests.other.webclient; import nl.esciencecenter.ptk.crypt.Secret; import nl.esciencecenter.ptk.data.StringHolder; import nl.esciencecenter.ptk.ssl.CertificateStore; import nl.esciencecenter.ptk.util.logging.ClassLogger; import nl.esciencecenter.ptk.web.WebClient; public class Test_WebClientSSL { public static void main(String args[]) { ClassLogger.getLogger(WebClient.class).setLevelToDebug(); ClassLogger.getLogger(CertificateStore.class).setLevelToDebug(); try { WebClient client = Test_WebClient.initClient("admin", new Secret("admin".toCharArray()), "localhost", 443, "/escXnat", false); // CertificateStore certStore=CertificateStore.getDefault(false); Secret secret = new Secret(CertificateStore.DEFAULT_PASSPHRASE.toCharArray()); String cacertLocation = System.getProperty("user.home") + "/cacerts"; CertificateStore certStore = CertificateStore.loadCertificateStore(cacertLocation, secret, true, true); client.setCertificateStore(certStore); // client.setCredentials(null, null); client.connect(); StringHolder resultTextHolder = new StringHolder(); StringHolder contentEncodingHolder = new StringHolder(); client.doGet("/", resultTextHolder, contentEncodingHolder); outPrintf("> Get Encoding=%s\n", contentEncodingHolder.value); outPrintf("---- Get result ----\n%s\n----------------\n", resultTextHolder.value); } catch (Exception e) { e.printStackTrace(); } } public static void outPrintf(String format, Object... args) { System.err.printf(format, args); } }
pavetw17/NewCountrySide
ntk2015/src/com/cwrs/ntk/models/TblBienbanHophoidongEntity.java
package com.cwrs.ntk.models; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; import java.sql.Date; import java.util.Arrays; /** * Created by VN on 3/5/2015. */ @Entity @javax.persistence.Table(name = "tbl_bienban_hophoidong", schema = "public", catalog = "ntm") public class TblBienbanHophoidongEntity { private int idDetai; public static final String BIENBAN_HOPHOIDONG_TBL = "tbl_bienban_hophoidong"; public static final String BIENBAN_HOPHOIDONG_ID_DETAI = "id_detai"; public static final String BIENBAN_HOPHOIDONG_QUYETDINH_THANHLAP_HOIDONG = "quyetdinh_thanhlap_hoidong"; public static final String BIENBAN_HOPHOIDONG_NGAY_RA_QUYETDINH = "ngay_ra_quyetdinh"; public static final String BIENBAN_HOPHOIDONG_DIADIEM = "diadiem"; public static final String BIENBAN_HOPHOIDONG_THOIGIAN = "thoigian"; public static final String BIENBAN_HOPHOIDONG_SOTHANHVIEN_HOIDONG = "sothanhvien_hoidong_comat"; public static final String BIENBAN_HOPHOIDONG_TONGSO_THANHVIEN = "tongso_thanhvien_hoidong"; public static final String BIENBAN_HOPHOIDONG_ID_THUKI = "id_thuki"; public static final String BIENBAN_HOPHOIDONG_NOIDUNG_LAMVIEC = "noidunglamviec"; public static final String BIENBAN_HOPHOIDONG_ID_TRUONGBAN_KIMEPHIEU = "id_truongbankiemphieu"; public static final String BIENBAN_HOPHOIDONG_ID_THANHVIEN_01 = "id_thanhvienkiemphieu01"; public static final String BIENBAN_HOPHOIDONG_ID_THANHVIEN_02 = "id_thanhvienkiemphieu02"; public static final String BIENBAN_HOPHOIDONG_ID_TOCHUC_TRUNGTUYEN = "id_tochuc_trungtuyen"; public static final String BIENBAN_HOPHOIDONG_ID_CHUTICH_HOIDONG = "id_chutich_hoidong"; public static final String BIENBAN_HOPHOIDONG_KETLUAN = "ketluan"; public static final String BIENBAN_HOPHOIDONG_FILE_BIENBAN = "file_bienban"; public static final String BIENBAN_HOPHOIDONG_TENFILE = "tenfile"; // id_detai integer NOT NULL DEFAULT nextval(('public.tbl_bienban_hophoidong_id_detai_seq'::text)::regclass), // quyetdinh_thanhlap_hoidong character varying(100), // ngay_ra_quyetdinh integer, // diadiem character varying(200), // thoigian date, // sothanhvien_hoidong_comat integer, // tongso_thanhvien_hoidong integer, // id_thuki integer, -- lấy mã từ bảng tbl_chuyengia // noidunglamviec character varying(1000), // id_truongbankiemphieu integer, // id_thanhvienkiemphieu01 integer, // id_thanhvienkiemphieu02 integer, // id_tochuc_trungtuyen integer, // id_chutich_hoidong integer, // ketluan character varying(1000), // file_bienban bytea, // tenfile character varying(100), @Id @javax.persistence.Column(name = "id_detai") public int getIdDetai() { return idDetai; } public void setIdDetai(int idDetai) { this.idDetai = idDetai; } private String quyetdinhThanhlapHoidong; @Basic @javax.persistence.Column(name = "quyetdinh_thanhlap_hoidong") public String getQuyetdinhThanhlapHoidong() { return quyetdinhThanhlapHoidong; } public void setQuyetdinhThanhlapHoidong(String quyetdinhThanhlapHoidong) { this.quyetdinhThanhlapHoidong = quyetdinhThanhlapHoidong; } private Integer ngayRaQuyetdinh; @Basic @javax.persistence.Column(name = "ngay_ra_quyetdinh") public Integer getNgayRaQuyetdinh() { return ngayRaQuyetdinh; } public void setNgayRaQuyetdinh(Integer ngayRaQuyetdinh) { this.ngayRaQuyetdinh = ngayRaQuyetdinh; } private String diadiem; @Basic @javax.persistence.Column(name = "diadiem") public String getDiadiem() { return diadiem; } public void setDiadiem(String diadiem) { this.diadiem = diadiem; } private Date thoigian; @Basic @javax.persistence.Column(name = "thoigian") public Date getThoigian() { return thoigian; } public void setThoigian(Date thoigian) { this.thoigian = thoigian; } private Integer sothanhvienHoidongComat; @Basic @javax.persistence.Column(name = "sothanhvien_hoidong_comat") public Integer getSothanhvienHoidongComat() { return sothanhvienHoidongComat; } public void setSothanhvienHoidongComat(Integer sothanhvienHoidongComat) { this.sothanhvienHoidongComat = sothanhvienHoidongComat; } private Integer tongsoThanhvienHoidong; @Basic @javax.persistence.Column(name = "tongso_thanhvien_hoidong") public Integer getTongsoThanhvienHoidong() { return tongsoThanhvienHoidong; } public void setTongsoThanhvienHoidong(Integer tongsoThanhvienHoidong) { this.tongsoThanhvienHoidong = tongsoThanhvienHoidong; } private Integer idThuki; @Basic @javax.persistence.Column(name = "id_thuki") public Integer getIdThuki() { return idThuki; } public void setIdThuki(Integer idThuki) { this.idThuki = idThuki; } private String noidunglamviec; @Basic @javax.persistence.Column(name = "noidunglamviec") public String getNoidunglamviec() { return noidunglamviec; } public void setNoidunglamviec(String noidunglamviec) { this.noidunglamviec = noidunglamviec; } private Integer idTruongbankiemphieu; @Basic @javax.persistence.Column(name = "id_truongbankiemphieu") public Integer getIdTruongbankiemphieu() { return idTruongbankiemphieu; } public void setIdTruongbankiemphieu(Integer idTruongbankiemphieu) { this.idTruongbankiemphieu = idTruongbankiemphieu; } private Integer idThanhvienkiemphieu01; @Basic @javax.persistence.Column(name = "id_thanhvienkiemphieu01") public Integer getIdThanhvienkiemphieu01() { return idThanhvienkiemphieu01; } public void setIdThanhvienkiemphieu01(Integer idThanhvienkiemphieu01) { this.idThanhvienkiemphieu01 = idThanhvienkiemphieu01; } private Integer idThanhvienkiemphieu02; @Basic @javax.persistence.Column(name = "id_thanhvienkiemphieu02") public Integer getIdThanhvienkiemphieu02() { return idThanhvienkiemphieu02; } public void setIdThanhvienkiemphieu02(Integer idThanhvienkiemphieu02) { this.idThanhvienkiemphieu02 = idThanhvienkiemphieu02; } private Integer idTochucTrungtuyen; @Basic @javax.persistence.Column(name = "id_tochuc_trungtuyen") public Integer getIdTochucTrungtuyen() { return idTochucTrungtuyen; } public void setIdTochucTrungtuyen(Integer idTochucTrungtuyen) { this.idTochucTrungtuyen = idTochucTrungtuyen; } private Integer idChutichHoidong; @Basic @javax.persistence.Column(name = "id_chutich_hoidong") public Integer getIdChutichHoidong() { return idChutichHoidong; } public void setIdChutichHoidong(Integer idChutichHoidong) { this.idChutichHoidong = idChutichHoidong; } private String ketluan; @Basic @javax.persistence.Column(name = "ketluan") public String getKetluan() { return ketluan; } public void setKetluan(String ketluan) { this.ketluan = ketluan; } private byte[] fileBienban; @Basic @javax.persistence.Column(name = "file_bienban") public byte[] getFileBienban() { return fileBienban; } public void setFileBienban(byte[] fileBienban) { this.fileBienban = fileBienban; } private String tenfile; @Basic @javax.persistence.Column(name = "tenfile") public String getTenfile() { return tenfile; } public void setTenfile(String tenfile) { this.tenfile = tenfile; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TblBienbanHophoidongEntity that = (TblBienbanHophoidongEntity) o; if (idDetai != that.idDetai) return false; if (diadiem != null ? !diadiem.equals(that.diadiem) : that.diadiem != null) return false; if (!Arrays.equals(fileBienban, that.fileBienban)) return false; if (idChutichHoidong != null ? !idChutichHoidong.equals(that.idChutichHoidong) : that.idChutichHoidong != null) return false; if (idThanhvienkiemphieu01 != null ? !idThanhvienkiemphieu01.equals(that.idThanhvienkiemphieu01) : that.idThanhvienkiemphieu01 != null) return false; if (idThanhvienkiemphieu02 != null ? !idThanhvienkiemphieu02.equals(that.idThanhvienkiemphieu02) : that.idThanhvienkiemphieu02 != null) return false; if (idThuki != null ? !idThuki.equals(that.idThuki) : that.idThuki != null) return false; if (idTochucTrungtuyen != null ? !idTochucTrungtuyen.equals(that.idTochucTrungtuyen) : that.idTochucTrungtuyen != null) return false; if (idTruongbankiemphieu != null ? !idTruongbankiemphieu.equals(that.idTruongbankiemphieu) : that.idTruongbankiemphieu != null) return false; if (ketluan != null ? !ketluan.equals(that.ketluan) : that.ketluan != null) return false; if (ngayRaQuyetdinh != null ? !ngayRaQuyetdinh.equals(that.ngayRaQuyetdinh) : that.ngayRaQuyetdinh != null) return false; if (noidunglamviec != null ? !noidunglamviec.equals(that.noidunglamviec) : that.noidunglamviec != null) return false; if (quyetdinhThanhlapHoidong != null ? !quyetdinhThanhlapHoidong.equals(that.quyetdinhThanhlapHoidong) : that.quyetdinhThanhlapHoidong != null) return false; if (sothanhvienHoidongComat != null ? !sothanhvienHoidongComat.equals(that.sothanhvienHoidongComat) : that.sothanhvienHoidongComat != null) return false; if (tenfile != null ? !tenfile.equals(that.tenfile) : that.tenfile != null) return false; if (thoigian != null ? !thoigian.equals(that.thoigian) : that.thoigian != null) return false; if (tongsoThanhvienHoidong != null ? !tongsoThanhvienHoidong.equals(that.tongsoThanhvienHoidong) : that.tongsoThanhvienHoidong != null) return false; return true; } @Override public int hashCode() { int result = idDetai; result = 31 * result + (quyetdinhThanhlapHoidong != null ? quyetdinhThanhlapHoidong.hashCode() : 0); result = 31 * result + (ngayRaQuyetdinh != null ? ngayRaQuyetdinh.hashCode() : 0); result = 31 * result + (diadiem != null ? diadiem.hashCode() : 0); result = 31 * result + (thoigian != null ? thoigian.hashCode() : 0); result = 31 * result + (sothanhvienHoidongComat != null ? sothanhvienHoidongComat.hashCode() : 0); result = 31 * result + (tongsoThanhvienHoidong != null ? tongsoThanhvienHoidong.hashCode() : 0); result = 31 * result + (idThuki != null ? idThuki.hashCode() : 0); result = 31 * result + (noidunglamviec != null ? noidunglamviec.hashCode() : 0); result = 31 * result + (idTruongbankiemphieu != null ? idTruongbankiemphieu.hashCode() : 0); result = 31 * result + (idThanhvienkiemphieu01 != null ? idThanhvienkiemphieu01.hashCode() : 0); result = 31 * result + (idThanhvienkiemphieu02 != null ? idThanhvienkiemphieu02.hashCode() : 0); result = 31 * result + (idTochucTrungtuyen != null ? idTochucTrungtuyen.hashCode() : 0); result = 31 * result + (idChutichHoidong != null ? idChutichHoidong.hashCode() : 0); result = 31 * result + (ketluan != null ? ketluan.hashCode() : 0); result = 31 * result + (fileBienban != null ? Arrays.hashCode(fileBienban) : 0); result = 31 * result + (tenfile != null ? tenfile.hashCode() : 0); return result; } }
rulan87/devclab.bc
bc/2/arrayMax.c
<reponame>rulan87/devclab.bc // Написать функцию: // int arrayMax(int array[], int size) // Вернуть значение максимального элемента в массиве. int arrayMax(int array[], int size) { int max = array[0]; for ( int i = 1; i < size; i++ ) { if ( array[i] > max ) { max = array[i]; } } return max; }
constgen/eslint-plugin-vue
tests/lib/rules/no-deprecated-slot-scope-attribute.js
<reponame>constgen/eslint-plugin-vue<filename>tests/lib/rules/no-deprecated-slot-scope-attribute.js<gh_stars>1-10 'use strict' const RuleTester = require('eslint').RuleTester const rule = require('../../../lib/rules/no-deprecated-slot-scope-attribute') const tester = new RuleTester({ parser: require.resolve('vue-eslint-parser'), parserOptions: { ecmaVersion: 2015 } }) tester.run('no-deprecated-slot-scope-attribute', rule, { valid: [ `<template> <LinkList> <template v-slot:name><a /></template> </LinkList> </template>`, `<template> <LinkList> <template #name><a /></template> </LinkList> </template>`, `<template> <LinkList> <template v-slot="{a}"><a /></template> </LinkList> </template>`, `<template> <LinkList v-slot="{a}"> <a /> </LinkList> </template>`, `<template> <LinkList> <template #default="{a}"><a /></template> </LinkList> </template>`, `<template> <LinkList> <a slot="name" /> </LinkList> </template>`, `<template> <LinkList> <template><a /></template> </LinkList> </template>`, `<template> <LinkList> <a /> </LinkList>` ], invalid: [ { code: ` <template> <LinkList> <template slot-scope="{a}"><a /></template> </LinkList> </template>`, output: ` <template> <LinkList> <template v-slot="{a}"><a /></template> </LinkList> </template>`, errors: [ { message: '`slot-scope` are deprecated.', line: 4 } ] }, { code: ` <template> <LinkList> <template slot-scope><a /></template> </LinkList> </template>`, output: ` <template> <LinkList> <template v-slot><a /></template> </LinkList> </template>`, errors: [ { message: '`slot-scope` are deprecated.', line: 4 } ] }, // cannot fix { code: ` <template> <LinkList> <a slot-scope="{a}" /> </LinkList> </template>`, output: null, errors: [ { message: '`slot-scope` are deprecated.', line: 4 } ] }, { code: ` <template> <LinkList> <template slot-scope="{a}" slot="foo"><a /></template> </LinkList> </template>`, output: null, errors: [ { message: '`slot-scope` are deprecated.', line: 4 } ] }, { code: ` <template> <LinkList> <template slot-scope="{a}" :slot="arg"><a /></template> </LinkList> </template>`, output: null, errors: [ { message: '`slot-scope` are deprecated.', line: 4 } ] } ] })
wya-team/rn-env
babel.config.js
<gh_stars>1-10 module.exports = function(api) { api.cache(true); return { "presets": [ "babel-preset-expo" ], "plugins": [ ["@babel/plugin-transform-flow-strip-types"], ["@babel/plugin-proposal-decorators", { "legacy": true }], ["@babel/plugin-proposal-class-properties", { "loose": true }], [ "import", { "libraryName": "@ant-design/react-native" }, "@ant-design/react-native" ], [ "module-resolver", { "root": ["./src"], "extensions": [".js", ".ios.js", ".android.js", ".png"], "alias": { "@assets": "./src/assets", "@css": "./src/css", "@images": "./src/images", "@components": "./src/pages/components", "@common": "./src/pages/components/_common", "@constants": "./src/pages/constants", "@containers": "./src/pages/containers", "@routers": "./src/pages/routers", "@stores": "./src/pages/stores", "@services": "./src/pages/stores/services", "@utils": "./src/pages/utils", "pure-render-decorator": "./src/pages/utils/pure-render-decorator" } } ] ] }; };
OussamaKasraoui/Anass
FrontEnd/src/screens/moderator/packs.screen.js
<reponame>OussamaKasraoui/Anass import React, { useRef, useState } from 'react'; import axios from 'axios'; function FileUpload() { const [file, setFile] = useState(''); const [data, getFile] = useState({ name: "", path: "" }); const [progress, setProgess] = useState(0); const el = useRef(); const handleChange = (e) => { setProgess(0) const file = e.target.files[0] console.log(file); setFile(file) } const uploadFile = () => { const formData = new FormData(); formData.append('file', file) axios.post('http://localhost:5000/api/packs/add', formData, { onUploadProgress: (ProgressEvent) => { let progress = Math.round(ProgressEvent.loaded / ProgressEvent.total * 100) + '%'; setProgess(progress) } }).then(res => { console.log(res); getFile({ name: res.data.name, path: 'http://localhost:5000/' + res.data.path }) // el.current.value = ""; }).catch(err => console.log(err)) } return ( <div> <div className="file-upload"> <input type="file" ref={el} onChange={handleChange} /> <div className="progessBar" style={{ width: progress }}>{progress}</div> <button onClick={uploadFile} className="upbutton">upload</button> </div> <hr /> {data.path && <div><textarea value={data.path} onChange={uploadFile} /></div>} {data.path && <img src={data.path} alt={data.name} />} </div> ); } export default FileUpload;
jiangmichaellll/java-pubsublite
google-cloud-pubsublite/src/main/java/com/google/cloud/pubsublite/v1/PublisherServiceSettings.java
<filename>google-cloud-pubsublite/src/main/java/com/google/cloud/pubsublite/v1/PublisherServiceSettings.java /* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.pubsublite.v1; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.ClientSettings; import com.google.api.gax.rpc.StreamingCallSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.cloud.pubsublite.proto.PublishRequest; import com.google.cloud.pubsublite.proto.PublishResponse; import com.google.cloud.pubsublite.v1.stub.PublisherServiceStubSettings; import java.io.IOException; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS /** * Settings class to configure an instance of {@link PublisherServiceClient}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (pubsublite.googleapis.com) and default port (443) are used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. */ @Generated("by gapic-generator") @BetaApi public class PublisherServiceSettings extends ClientSettings<PublisherServiceSettings> { /** Returns the object with the settings used for calls to publish. */ public StreamingCallSettings<PublishRequest, PublishResponse> publishSettings() { return ((PublisherServiceStubSettings) getStubSettings()).publishSettings(); } public static final PublisherServiceSettings create(PublisherServiceStubSettings stub) throws IOException { return new PublisherServiceSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return PublisherServiceStubSettings.defaultExecutorProviderBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return PublisherServiceStubSettings.getDefaultEndpoint(); } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return PublisherServiceStubSettings.getDefaultServiceScopes(); } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return PublisherServiceStubSettings.defaultCredentialsProviderBuilder(); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return PublisherServiceStubSettings.defaultGrpcTransportProviderBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return PublisherServiceStubSettings.defaultTransportChannelProvider(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return PublisherServiceStubSettings.defaultApiClientHeaderProviderBuilder(); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected PublisherServiceSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); } /** Builder for PublisherServiceSettings. */ public static class Builder extends ClientSettings.Builder<PublisherServiceSettings, Builder> { protected Builder() throws IOException { this((ClientContext) null); } protected Builder(ClientContext clientContext) { super(PublisherServiceStubSettings.newBuilder(clientContext)); } private static Builder createDefault() { return new Builder(PublisherServiceStubSettings.newBuilder()); } protected Builder(PublisherServiceSettings settings) { super(settings.getStubSettings().toBuilder()); } protected Builder(PublisherServiceStubSettings.Builder stubSettings) { super(stubSettings); } public PublisherServiceStubSettings.Builder getStubSettingsBuilder() { return ((PublisherServiceStubSettings.Builder) getStubSettings()); } // NEXT_MAJOR_VER: remove 'throws Exception' /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) throws Exception { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } /** Returns the builder for the settings used for calls to publish. */ public StreamingCallSettings.Builder<PublishRequest, PublishResponse> publishSettings() { return getStubSettingsBuilder().publishSettings(); } @Override public PublisherServiceSettings build() throws IOException { return new PublisherServiceSettings(this); } } }
simplygreatwork/goodshow-dom
examples/kitchen-sink/panels/panel.js
example.panels.panel.Panel = goodshow.Panel.extend({ initialize: function(options) { goodshow.Panel.prototype.initialize.call(this, Object.assign({ background: 'orange', constrain : { extent: 250 }, invoke : { action : function() { var miller = goodshow.Utility.ancestor.find(this, goodshow.Miller); miller.toggle(new example.panels.panel.Two()); }.bind(this) } }, options || {})); } }); example.panels.panel.One = example.panels.panel.Panel.extend({ }); example.panels.panel.Two = goodshow.Panel.extend({ initialize: function(options) { goodshow.Panel.prototype.initialize.call(this, Object.assign({ background: 'white', constrain : { extent: 400 }, invoke : { action : function() { var miller = goodshow.Utility.ancestor.find(this, goodshow.Miller); miller.toggle(new example.panels.panel.Three()); }.bind(this) }, markup : { url : '../assets/templates/index.html', } }, options || {})); } }); example.panels.panel.Three = goodshow.Panel.extend({ initialize: function(options) { goodshow.Panel.prototype.initialize.call(this, Object.assign({ background: 'brown', constrain : { extent: 300 }, invoke : { action : function() { var miller = goodshow.Utility.ancestor.find(this, goodshow.Miller); miller.toggle(new example.panels.panel.Four()); }.bind(this) } }, options || {})); } }); example.panels.panel.Four = goodshow.Panel.extend({ initialize: function(options) { goodshow.Panel.prototype.initialize.call(this, Object.assign({ background: 'purple', constrain : { extent: 200 }, invoke : { action : function() { var miller = goodshow.Utility.ancestor.find(this, goodshow.Miller); miller.toggle(new example.panels.panel.Five()); }.bind(this) } }, options || {})); } }); example.panels.panel.Five = goodshow.Panel.extend({ initialize: function(options) { goodshow.Panel.prototype.initialize.call(this, Object.assign({ background: 'yellow', constrain : { extent: 200 }, invoke : { action : function() { var miller = goodshow.Utility.ancestor.find(this, goodshow.Miller); miller.toggle(new example.panels.panel.One()); }.bind(this) } }, options || {})); } });
cday97/beam
src/main/scala/beam/utils/Stats.scala
package beam.utils /** * Created by sfeygin on 2/6/17. */ object Stats { final val STATS_EPS = 1e-12 final val INV_SQRT_2PI = 1.0 / Math.sqrt(2.0 * Math.PI) } class Stats[T](values: Vector[T])(implicit ev$1: T => Double) { class _Stats(var minValue: Double, var maxValue: Double, var sum: Double, var sumSqr: Double) require(values.nonEmpty, "Stats: Cannot initialize stats with undefined values") private[this] val sums = values.foldLeft((0.0, 0.0))((acc, s) => (acc._1 + s, acc._2 + s * s)) @inline lazy val mean: Double = sums._1 / values.size lazy val variance: Double = (sums._2 - mean * mean * values.size) / (values.size - 1) lazy val stdDev: Double = Math.sqrt(variance) }
sktanwar2014/fme_system
server/controllers/product/brand.js
<reponame>sktanwar2014/fme_system const Brand = require('../../models/product/brand.js'); const all = async function(req, res, next) { try { const brandList = await new Brand({}).all(); res.send({ brandList }); } catch (err) { next(err); } }; const add = async function(req, res, next) { const brandParam = { brand_name: req.body.brand_name, user_id: req.decoded.id, }; try { const newBrand = new Brand(brandParam); await newBrand.addBrand(); const brandList = await new Brand({}).all(); res.send({ brandList }); } catch (err) { next(err); } }; module.exports = {all,add};
open-garden/garden
Zipc_Model/src/com/zipc/garden/model/scenario/impl/OtherVehicleImpl.java
<filename>Zipc_Model/src/com/zipc/garden/model/scenario/impl/OtherVehicleImpl.java /** */ package com.zipc.garden.model.scenario.impl; import com.zipc.garden.model.scenario.OtherVehicle; import com.zipc.garden.model.scenario.ScenarioPackage; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Other Vehicle</b></em>'. * <!-- end-user-doc --> * * @generated */ public class OtherVehicleImpl extends VehicleImpl implements OtherVehicle { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected OtherVehicleImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ScenarioPackage.Literals.OTHER_VEHICLE; } } //OtherVehicleImpl
Ahmet-Kaplan/ph-commons
ph-json/src/test/java/com/helger/json/EqualsHashcodeFuncTest.java
/** * Copyright (C) 2014-2017 <NAME> (www.helger.com) * philip[at]helger[dot]com * * 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.helger.json; import static org.junit.Assert.assertNotNull; import java.math.BigDecimal; import javax.annotation.Nullable; import org.junit.Test; import com.helger.commons.collection.ext.CommonsArrayList; import com.helger.commons.collection.ext.CommonsHashMap; import com.helger.commons.collection.ext.CommonsLinkedHashMap; import com.helger.commons.collection.ext.CommonsTreeMap; import com.helger.commons.collection.ext.ICommonsMap; import com.helger.commons.mock.CommonsTestHelper; import com.helger.json.convert.JsonConverter; import com.helger.json.serialize.JsonReader; /** * Test class for equals and hashCode. * * @author <NAME> */ public final class EqualsHashcodeFuncTest { private void _testEqualsHashcode (@Nullable final Object aValue) { final IJson aJson = JsonConverter.convertToJson (aValue); assertNotNull ("Failed: " + aValue, aJson); final String sJson = aJson.getAsJsonString (); assertNotNull (sJson); final IJson aJsonRead = JsonReader.readFromString (sJson); assertNotNull ("Failed to read: " + sJson, aJsonRead); CommonsTestHelper.testDefaultImplementationWithEqualContentObject (aJson, aJsonRead); } @Test public void testSimpleValues () { _testEqualsHashcode (Integer.valueOf (Integer.MIN_VALUE)); _testEqualsHashcode (Integer.valueOf (Integer.MAX_VALUE)); _testEqualsHashcode (Long.valueOf (Long.MIN_VALUE)); _testEqualsHashcode (Long.valueOf (Long.MAX_VALUE)); _testEqualsHashcode ("a string"); _testEqualsHashcode ("a string/with/a/slash"); _testEqualsHashcode (Double.valueOf (3.1234)); _testEqualsHashcode (new BigDecimal ("3.12341234123412341234123412341234123412341234")); } @Test public void testArray () { _testEqualsHashcode (new boolean [] { true, false, true }); _testEqualsHashcode (new byte [] { 0, 1, 2 }); _testEqualsHashcode (new char [] { 'a', 'b', 'c' }); _testEqualsHashcode (new int [] { 1, 2, 3 }); _testEqualsHashcode (new long [] { 1, 2, 3 }); _testEqualsHashcode (new short [] { 1, 2, 3 }); _testEqualsHashcode (new String [] { "foo", "bar", "bla" }); _testEqualsHashcode (new CommonsArrayList <> (Double.valueOf (3.1234), Double.valueOf (4.1415), Double.valueOf (5.1415))); } @Test public void testMap () { final ICommonsMap <String, Object> aMap = new CommonsHashMap <> (); aMap.put ("foo", "bar"); _testEqualsHashcode (aMap); final ICommonsMap <String, Object> aTreeMap = new CommonsTreeMap <> (); aTreeMap.put ("foo", "bar"); aTreeMap.put ("foo2", Integer.valueOf (5)); _testEqualsHashcode (aTreeMap); final ICommonsMap <String, Object> aLinkedMap = new CommonsLinkedHashMap <> (); aLinkedMap.put ("foo", "bar"); aLinkedMap.put ("foo2", Integer.valueOf (5)); _testEqualsHashcode (aLinkedMap); } }
jasonoctaviano/RPM
contiki/platform/pc-6001/apps/multithread/mt-test.c
<filename>contiki/platform/pc-6001/apps/multithread/mt-test.c /* * Copyright (c) 2007, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. * * This file is part of the Contiki operating system. * * Author: <NAME> <<EMAIL>> * */ /** * \file * A very simple Contiki application showing how to use the Contiki * Multi-threading library * \author * <NAME> <<EMAIL>> * \author for PC-6001 version * <NAME> <<EMAIL>> */ #include <stdio.h> #include "contiki.h" #include "ctk.h" #include "sys/mt.h" #include "mtarch.h" #define WIN_XSIZE 10 #define WIN_YSIZE 10 static char log[WIN_XSIZE * WIN_YSIZE]; static struct ctk_window window; static struct ctk_label loglabel = {CTK_LABEL(0, 0, WIN_XSIZE, WIN_YSIZE, log)}; PROCESS(mt_process, "Multi-threading test"); static char buf[20]; void println(char *str1) { unsigned int i; for(i = 1; i < WIN_YSIZE; i++) { memcpy(&log[(i - 1) * WIN_XSIZE], &log[i * WIN_XSIZE], WIN_XSIZE); } memset(&log[(WIN_YSIZE - 1) * WIN_XSIZE], 0, WIN_XSIZE); strncpy(&log[(WIN_YSIZE - 1) * WIN_XSIZE], str1, WIN_XSIZE); CTK_WIDGET_REDRAW(&loglabel); } /*---------------------------------------------------------------------------*/ static void thread_func(char *str, int len) { println((char *) (str + len)); mt_yield(); if(len) { thread_func(str, len - 1); mt_yield(); } println((char *) (str + len)); } /*---------------------------------------------------------------------------*/ static void thread_main(void *data) { while(1) { thread_func((char *)data, 9); } mt_exit(); } /*---------------------------------------------------------------------------*/ PROCESS_THREAD(mt_process, ev, data) { static struct etimer timer; static int toggle = 0; static struct mt_thread th1; static struct mt_thread th2; PROCESS_BEGIN(); ctk_window_new(&window, WIN_XSIZE, WIN_YSIZE, "Multithread"); CTK_WIDGET_ADD(&window, &loglabel); memset(log, 0, sizeof(log)); ctk_window_open(&window); mt_init(); mt_start(&th1, thread_main, "JIHGFEDCBA"); mt_start(&th2, thread_main, "9876543210"); etimer_set(&timer, CLOCK_SECOND / 2); while(1) { PROCESS_WAIT_EVENT(); if(ev == PROCESS_EVENT_TIMER) { if(toggle) { mt_exec(&th1); toggle--; } else { mt_exec(&th2); toggle++; } etimer_set(&timer, CLOCK_SECOND / 2); } else if(ev == ctk_signal_window_close || ev == PROCESS_EVENT_EXIT) { ctk_window_close(&window); process_exit(&mt_process); LOADER_UNLOAD(); } } mt_stop(&th1); mt_stop(&th2); mt_remove(); while(1) { PROCESS_WAIT_EVENT(); } PROCESS_END(); } /*---------------------------------------------------------------------------*/
clairechingching/ScaffCC
clang/test/SemaCXX/warn-using-namespace-in-header.h
<gh_stars>10-100 // Lots of vertical space to make the error line match up with the line of the // expected line in the source file. namespace warn_in_header_in_global_context {} using namespace warn_in_header_in_global_context; // While we want to error on the previous using directive, we don't when we are // inside a namespace namespace dont_warn_here { using namespace warn_in_header_in_global_context; } // We should warn in toplevel extern contexts. namespace warn_inside_linkage {} extern "C++" { using namespace warn_inside_linkage; } // This is really silly, but we should warn on it: extern "C++" { extern "C" { extern "C++" { using namespace warn_inside_linkage; } } } // But we shouldn't warn in extern contexts inside namespaces. namespace dont_warn_here { extern "C++" { using namespace warn_in_header_in_global_context; } } // We also shouldn't warn in case of functions. inline void foo() { using namespace warn_in_header_in_global_context; } namespace macronamespace {} #define USING_MACRO using namespace macronamespace; // |using namespace| through a macro should warn if the instantiation is in a // header. USING_MACRO
Ilyabasharov/made_mail.ru
1_term/made_2019_cpp/01/Calculator/calculation.hpp
<filename>1_term/made_2019_cpp/01/Calculator/calculation.hpp // // Recursive descent parser main class // // calculation.hpp // Calculator // // Created by <NAME> on 15/10/2019. // Copyright © 2019 <NAME>. All rights reserved. // #ifndef calculation_hpp #define calculation_hpp #include <iostream> #include <string> #include <string.h> #include <algorithm> const int ERROR_CODE = 1; class DescentParser { public: std::string expression; std::string::iterator cursor; bool user_error = false; int RecursiveDescentParser(); int GetNumber(); int GetAdditionOrSubtraction(); int GetMultiplyingOrDivision(); int GetPriority(); int GetUnaryMinusOrPlus(); void Update(const char *tmp_string); DescentParser(const char *tmp_string); ~DescentParser(); }; bool isBackspacing(const char* string); #endif /* calculation_hpp */
nkolytschew/mki4-hsrt-sose19
microservices-example/user.service/src/main/java/com/github/nkolytschew/user/service/rest/UserController.java
package com.github.nkolytschew.user.service.rest; import com.github.nkolytschew.user.service.remote.UserService; import org.springframework.core.io.Resource; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { private final UserService service; public UserController(UserService service) { this.service = service; } @CrossOrigin(origins = "http://localhost:4200") @GetMapping("users") public Resource getUsers() { return this.service.getUsers(); } }
emafazillah/andhow
andhow-junit5-extensions/src/main/java/org/yarnandtail/andhow/junit5/ext/RestoreSysPropsAfterEachTestExt.java
<reponame>emafazillah/andhow package org.yarnandtail.andhow.junit5.ext; import org.junit.jupiter.api.extension.*; import java.util.Properties; /** * JUnit 5 extension that restores System.Properties values after each test. * * System.Properties values are copied prior to any testing in the Test class. Then, after each * test completes, the values are restored. */ public class RestoreSysPropsAfterEachTestExt extends ExtensionBase implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback { protected final static String KEY = "KEY"; /** * Store the original Sys Props prior to any testing. * * Happens before {@code @BeforeAll}, so this stores Sys Props as they were * prior to any mods in {@code @BeforeAll}, i.e., these are sys Props prior to * any affects of the test class. * * @param context * @throws Exception */ @Override public void beforeAll(ExtensionContext context) throws Exception { getPerTestClassStore(context).put(KEY, System.getProperties().clone()); } /** * Store the original Sys Props as they were prior to this test run. * * Happens after {@code @BeforeAll} and before {@code @BeforeEach}, so this stores * Sys Props as they were after possible mods in {@code @BeforeAll}. * * @param context * @throws Exception */ @Override public void beforeEach(ExtensionContext context) throws Exception { getPerTestMethodStore(context).put(KEY, System.getProperties().clone()); } /** * Restore Sys Props to their values as l * * Happens before {@code @AfterEach}, so {@code @AfterEach} will see the state left * by {@code @BeforeEach} unless it was modified by the test. * * @param context * @throws Exception */ @Override public void afterEach(ExtensionContext context) throws Exception { Properties p = getPerTestMethodStore(context).remove(KEY, Properties.class); System.setProperties(p); } /** * One final restore after all tests are done, restoring to what the Sys Props were * prior the the test class and any BeforeAll modifications. * * Happens after {@code @AfterAll}, so {@code @AfterAll} will see the state left * by {@code @BeforeAll} unless it was modified by the test. * * @param context * @throws Exception */ @Override public void afterAll(ExtensionContext context) throws Exception { Properties p = getPerTestClassStore(context).remove(KEY, Properties.class); System.setProperties(p); } }
hayounglee/LaTTe
src/translator/reg.c
<gh_stars>1-10 /* reg.c physical register related functions Written by: <NAME> <<EMAIL>> Copyright (C) 1999 MASS Lab., Seoul, Korea. See the file LICENSE for usage and redistribution terms and a disclaimer of all warranties. */ #include "config.h" #include "reg.h" /* sparc physical registers */ int _is_available_register[] = { 0, 0, 0, 0, 0, 0, 0, 0, /* g0-g7 : not available */ 1, 1, 1, 1, 1, 1, 0, 0, /* o0-o7 */ 1, 1, 1, 1, 1, 1, 1, 1, /* l0-l7 */ 1, 1, 1, 1, 1, 1, 0, 0, /* i0-i7 */ 1, 1, 1, 1, 1, 1, 1, 1, /* f0-f7 */ 1, 1, 1, 1, 1, 1, 1, 1, /* f8-f15 */ 1, 1, 1, 1, 1, 1, 1, 1, /* f16-f23 */ 1, 1, 1, 1, 1, 1, 1, 1, /* f24-31 */ 1, 1, 1, 1, 1, 1, 1, 1, /* cc0-cc7 */ REG_INVALID }; int _parameter_registers[] = { o0, o1, o2, o3, o4, o5, REG_INVALID }; int _argument_registers[] = { i0, i1, i2, i3, i4, i5, REG_INVALID }; char *_reg_names[] = { "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7", "o0", "o1", "o2", "o3", "o4", "o5", "sp", "o7", "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7", "i0", "i1", "i2", "i3", "i4", "i5", "fp", "i7", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31" }; #undef INLINE #define INLINE #include "reg.ic" /* actual function definitions are in reg.ic */
nobullet/library
src/test/java/com/nobullet/algo/KnapsackTest.java
package com.nobullet.algo; import static com.nobullet.MoreAssertions.assertListsEqual; import static org.junit.Assert.assertEquals; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.nobullet.algo.KnapsackItem.RepeatableItem; import java.util.List; import java.util.Map; import org.junit.Test; /** * Tests for Knapsack problem. */ public class KnapsackTest { @Test public void testGreedy() { List<Integer> result = Knapsack.greedy(26, asMap(25, 4, 10, 3, 5, 2, 1, 1)); assertListsEqual(Lists.newArrayList(25, 1), result); result = Knapsack.greedy(26, asMap(25, 10, 10, 3, 5, 2, 1, 1)); assertListsEqual(Lists.newArrayList(10, 10, 5, 1), result); result = Knapsack.greedy(10, asMap(25, 1, 10, 3, 5, 2, 1, 4)); assertListsEqual(Lists.newArrayList(10), result); result = Knapsack.greedy(99, asMap(25, 1, 10, 3, 5, 2, 1, 4)); assertListsEqual(Lists.newArrayList(25, 25, 25, 10, 10, 1, 1, 1, 1), result); } @Test public void testZeroOne1() { List<KnapsackItem> result = Knapsack.zeroOne(80, new int[]{20, 30, 50}, new int[]{60, 90, 100}); assertListsEqual(Lists.newArrayList(new KnapsackItem(90, 30), new KnapsackItem(100, 50)), result); } @Test public void testZeroOne_2() { List<KnapsackItem> result = Knapsack.zeroOne(14, new int[]{5, 10, 6, 5}, new int[]{3, 5, 4, 2}); assertListsEqual(Lists.newArrayList(new KnapsackItem(3, 5), new KnapsackItem(4, 6)), result); } @Test public void testZeroOne3() { List<KnapsackItem> result = Knapsack.zeroOne(13, new int[]{3, 4, 5, 9, 9}, new int[]{1, 6, 6, 7, 6}); assertListsEqual(Lists.newArrayList(new KnapsackItem(1, 3), new KnapsackItem(6, 4), new KnapsackItem(6, 5)), result); } @Test public void testGeneric_1() { List<KnapsackItem> result = Knapsack.generic(80, new int[]{20, 30, 50}, new int[]{60, 90, 100}, new int[]{1, 1, 1}); assertListsEqual(Lists.newArrayList(new KnapsackItem(90, 30), new KnapsackItem(100, 50)), result); } @Test public void testGeneric2() { List<KnapsackItem> result = Knapsack.generic(14, new int[]{5, 10, 6, 5}, new int[]{3, 5, 4, 2}, new int[]{1, 1, 1, 1}); assertListsEqual(Lists.newArrayList(new KnapsackItem(3, 5), new KnapsackItem(4, 6)), result); } @Test public void testGeneric3() { List<KnapsackItem> result = Knapsack.generic(13, new int[]{3, 4, 5, 9, 9, 14}, new int[]{1, 6, 6, 7, 6, 45}, new int[]{1, 1, 1, 1, 1, 2}); assertListsEqual(Lists.newArrayList(new KnapsackItem(1, 3), new KnapsackItem(6, 4), new KnapsackItem(6, 5)), result); } @Test public void testGeneric3_duplicates() { List<KnapsackItem> result = Knapsack.generic(17, new int[]{3, 4, 5, 9, 9, 18}, new int[]{1, 6, 6, 7, 6, 45}, new int[]{1, 2, 1, 1, 1, 10}); assertListsEqual(Lists.newArrayList(new KnapsackItem(1, 3), new KnapsackItem(6, 4), new KnapsackItem(6, 4), new KnapsackItem(6, 5)), result); } @Test public void testGeneric_allItems() { List<KnapsackItem> result = Knapsack.generic(1000, new int[]{3, 4, 5, 9, 9}, new int[]{1, 6, 6, 7, 6}, new int[]{1, 1, 1, 1, 1}); assertListsEqual(Lists.newArrayList(new KnapsackItem(1, 3), new KnapsackItem(6, 4), new KnapsackItem(6, 5), new KnapsackItem(6, 9), new KnapsackItem(7, 9)), result); } @Test public void testBounded() { List<RepeatableItem> result = Knapsack.bounded(17, new int[]{3, 4, 5, 9, 9}, new int[]{1, 6, 6, 7, 6}, new int[]{1, 2, 1, 1, 1}); assertListsEqual( Lists.newArrayList( new RepeatableItem(1, 3, 1), new RepeatableItem(6, 4, 2), new RepeatableItem(6, 5, 1)), result); } @Test public void testBounded_repeatableItems() { List<RepeatableItem> result = Knapsack.bounded(17, Sets.newHashSet( new RepeatableItem(1, 3, 1), new RepeatableItem(6, 4, 2), new RepeatableItem(6, 5, 1), new RepeatableItem(7, 9, 1), new RepeatableItem(6, 9, 1) )); assertListsEqual( Lists.newArrayList( new RepeatableItem(1, 3, 1), new RepeatableItem(6, 4, 2), new RepeatableItem(6, 5, 1)), result); } @Test public void testBounded_big() { // Test is from here: http://www.codeproject.com/Articles/706838/Bounded-Knapsack-Algorithm List<RepeatableItem> result = Knapsack.bounded(1000, Sets.newHashSet( new RepeatableItem("Apple", 40, 39, 4), new RepeatableItem("Banana", 60, 27, 4), new RepeatableItem("Beer", 10, 52, 12), new RepeatableItem("Book", 10, 30, 2), new RepeatableItem("Camera", 30, 32, 1), new RepeatableItem("Cheese", 30, 23, 4), new RepeatableItem("Chocolate Bar", 60, 15, 10), new RepeatableItem("Compass", 35, 13, 1), new RepeatableItem("Jeans", 10, 48, 1), new RepeatableItem("Map", 150, 9, 1), new RepeatableItem("Notebook", 80, 22, 1), new RepeatableItem("Sandwich", 160, 50, 4), new RepeatableItem("Ski Jacket", 75, 43, 1), new RepeatableItem("Ski Pants", 70, 42, 1), new RepeatableItem("Socks", 50, 4, 2), new RepeatableItem("Sunglasses", 20, 7, 1), new RepeatableItem("Suntan Lotion", 70, 11, 1), new RepeatableItem("T-Shirt", 15, 24, 1), new RepeatableItem("Tin", 45, 68, 1), new RepeatableItem("Towel", 12, 18, 1), new RepeatableItem("Umbrella", 40, 73, 1), new RepeatableItem("Water", 200, 153, 1) )); assertListsEqual( Lists.newArrayList( new RepeatableItem("Apple", 40, 39, 3), new RepeatableItem("Banana", 60, 27, 4), new RepeatableItem("Cheese", 30, 23, 4), new RepeatableItem("Chocolate Bar", 60, 15, 10), new RepeatableItem("Compass", 35, 13, 1), new RepeatableItem("Map", 150, 9, 1), new RepeatableItem("Notebook", 80, 22, 1), new RepeatableItem("Sandwich", 160, 50, 4), new RepeatableItem("Ski Jacket", 75, 43, 1), new RepeatableItem("Ski Pants", 70, 42, 1), new RepeatableItem("Socks", 50, 4, 2), new RepeatableItem("Sunglasses", 20, 7, 1), new RepeatableItem("Suntan Lotion", 70, 11, 1), new RepeatableItem("T-Shirt", 15, 24, 1), new RepeatableItem("Water", 200, 153, 1) ), result); } @Test public void testBounded_empty() { List<RepeatableItem> result = Knapsack.bounded(2, new int[]{3, 4, 5, 9, 9}, new int[]{1, 6, 6, 7, 6}, new int[]{1, 2, 1, 1, 1}); assertListsEqual(Lists.newArrayList(), result); } @Test public void testZeroOne_BruteForce() { Knapsack k = new Knapsack(); int[] profits = {1, 6, 10, 16}; int[] weights = {1, 2, 3, 5}; assertEquals(22, k.zeroOneBruteForce(7, weights, profits)); assertEquals(17, k.zeroOneBruteForce(6, weights, profits)); assertEquals(22, k.zeroOneBruteForceWMemoization(7, weights, profits)); assertEquals(17, k.zeroOneBruteForceWMemoization(6, weights, profits)); assertEquals(22, k.zeroOneWMatrix(7, weights, profits)); assertEquals(17, k.zeroOneWMatrix(6, weights, profits)); } @Test public void testUnbounded() { Knapsack k = new Knapsack(); assertEquals(k.unboundedRecursive(5, new int[] {1, 2, 3}, new int[] {15, 20, 50}), 80); assertEquals(k.unboundedWMatrix(5, new int[] {1, 2, 3}, new int[] {15, 20, 50}), 80); assertEquals(k.unboundedWMatrix(8, new int[] {1, 3, 4, 5}, new int[] {15, 50, 60, 90}), 140); } /** * Builds a map from given arguments. Treats arguments as key, value, key, value... * * @param args Arguments. Even number of integers is expected. * @return Map that treats arguments as key, value, key, value... */ private static Map<Integer, Integer> asMap(int... args) { if (args.length == 0 || args.length % 2 == 1) { throw new IllegalArgumentException("Expected value/weight pairs."); } Map<Integer, Integer> result = Maps.newHashMapWithExpectedSize(args.length / 2); for (int i = 0; i < args.length; i += 2) { result.put(args[i], args[i + 1]); } return result; } }
IIyass/Portfolio
src/Utils/Information.js
<reponame>IIyass/Portfolio import React from "react" import { Link } from "gatsby" import ProjectCards from "../components/ProjectCard" export const AboutMe = ( <div> <p> I am a software engineer, passionate about innovation and new technologies. I love high-performance, maintainable and well organized code. I'm a Full-Stack developer working in an environment full of challenges. </p> <span id="Phone">0621280720</span> <Link to="/aboutMe">More ...</Link> </div> ) export const ProjectContent = ( <ProjectCards name="Twtter clone" url="https://github.com/IIyass/Social-Media-Clone" description="Twitter clone" /> )
pjbizon/pulumi-gcp
sdk/go/gcp/compute/regionDiskIamBinding.go
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package compute import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Three different resources help you manage your IAM policy for Compute Engine Disk. Each of these resources serves a different use case: // // * `compute.DiskIamPolicy`: Authoritative. Sets the IAM policy for the disk and replaces any existing policy already attached. // * `compute.DiskIamBinding`: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other roles within the IAM policy for the disk are preserved. // * `compute.DiskIamMember`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the disk are preserved. // // > **Note:** `compute.DiskIamPolicy` **cannot** be used in conjunction with `compute.DiskIamBinding` and `compute.DiskIamMember` or they will fight over what your policy should be. // // > **Note:** `compute.DiskIamBinding` resources **can be** used in conjunction with `compute.DiskIamMember` resources **only if** they do not grant privilege to the same role. // // ## google\_compute\_disk\_iam\_policy // // ```go // package main // // import ( // "github.com/pulumi/pulumi-gcp/sdk/v6/go/gcp/compute" // "github.com/pulumi/pulumi-gcp/sdk/v6/go/gcp/organizations" // "github.com/pulumi/pulumi/sdk/v3/go/pulumi" // ) // // func main() { // pulumi.Run(func(ctx *pulumi.Context) error { // admin, err := organizations.LookupIAMPolicy(ctx, &organizations.LookupIAMPolicyArgs{ // Bindings: []organizations.GetIAMPolicyBinding{ // organizations.GetIAMPolicyBinding{ // Role: "roles/viewer", // Members: []string{ // "user:<EMAIL>", // }, // }, // }, // }, nil) // if err != nil { // return err // } // _, err = compute.NewDiskIamPolicy(ctx, "policy", &compute.DiskIamPolicyArgs{ // Project: pulumi.Any(google_compute_disk.Default.Project), // Zone: pulumi.Any(google_compute_disk.Default.Zone), // PolicyData: pulumi.String(admin.PolicyData), // }) // if err != nil { // return err // } // return nil // }) // } // ``` // // ## google\_compute\_disk\_iam\_binding // // ```go // package main // // import ( // "github.com/pulumi/pulumi-gcp/sdk/v6/go/gcp/compute" // "github.com/pulumi/pulumi/sdk/v3/go/pulumi" // ) // // func main() { // pulumi.Run(func(ctx *pulumi.Context) error { // _, err := compute.NewDiskIamBinding(ctx, "binding", &compute.DiskIamBindingArgs{ // Project: pulumi.Any(google_compute_disk.Default.Project), // Zone: pulumi.Any(google_compute_disk.Default.Zone), // Role: pulumi.String("roles/viewer"), // Members: pulumi.StringArray{ // pulumi.String("user:<EMAIL>"), // }, // }) // if err != nil { // return err // } // return nil // }) // } // ``` // // ## google\_compute\_disk\_iam\_member // // ```go // package main // // import ( // "github.com/pulumi/pulumi-gcp/sdk/v6/go/gcp/compute" // "github.com/pulumi/pulumi/sdk/v3/go/pulumi" // ) // // func main() { // pulumi.Run(func(ctx *pulumi.Context) error { // _, err := compute.NewDiskIamMember(ctx, "member", &compute.DiskIamMemberArgs{ // Project: pulumi.Any(google_compute_disk.Default.Project), // Zone: pulumi.Any(google_compute_disk.Default.Zone), // Role: pulumi.String("roles/viewer"), // Member: pulumi.String("user:<EMAIL>"), // }) // if err != nil { // return err // } // return nil // }) // } // ``` // // ## Import // // For all import syntaxes, the "resource in question" can take any of the following forms* projects/{{project}}/zones/{{zone}}/disks/{{name}} * {{project}}/{{zone}}/{{name}} * {{zone}}/{{name}} * {{name}} Any variables not passed in the import command will be taken from the provider configuration. Compute Engine disk IAM resources can be imported using the resource identifiers, role, and member. IAM member imports use space-delimited identifiersthe resource in question, the role, and the member identity, e.g. // // ```sh // $ pulumi import gcp:compute/regionDiskIamBinding:RegionDiskIamBinding editor "projects/{{project}}/zones/{{zone}}/disks/{{disk}} roles/viewer user:<EMAIL>" // ``` // // IAM binding imports use space-delimited identifiersthe resource in question and the role, e.g. // // ```sh // $ pulumi import gcp:compute/regionDiskIamBinding:RegionDiskIamBinding editor "projects/{{project}}/zones/{{zone}}/disks/{{disk}} roles/viewer" // ``` // // IAM policy imports use the identifier of the resource in question, e.g. // // ```sh // $ pulumi import gcp:compute/regionDiskIamBinding:RegionDiskIamBinding editor projects/{{project}}/zones/{{zone}}/disks/{{disk}} // ``` // // -> **Custom Roles**If you're importing a IAM resource with a custom role, make sure to use the // // full name of the custom role, e.g. `[projects/my-project|organizations/my-org]/roles/my-custom-role`. type RegionDiskIamBinding struct { pulumi.CustomResourceState Condition RegionDiskIamBindingConditionPtrOutput `pulumi:"condition"` // (Computed) The etag of the IAM policy. Etag pulumi.StringOutput `pulumi:"etag"` Members pulumi.StringArrayOutput `pulumi:"members"` // Used to find the parent resource to bind the IAM policy to Name pulumi.StringOutput `pulumi:"name"` // The ID of the project in which the resource belongs. // If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used. Project pulumi.StringOutput `pulumi:"project"` Region pulumi.StringOutput `pulumi:"region"` // The role that should be applied. Only one // `compute.DiskIamBinding` can be used per role. Note that custom roles must be of the format // `[projects|organizations]/{parent-name}/roles/{role-name}`. Role pulumi.StringOutput `pulumi:"role"` } // NewRegionDiskIamBinding registers a new resource with the given unique name, arguments, and options. func NewRegionDiskIamBinding(ctx *pulumi.Context, name string, args *RegionDiskIamBindingArgs, opts ...pulumi.ResourceOption) (*RegionDiskIamBinding, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.Members == nil { return nil, errors.New("invalid value for required argument 'Members'") } if args.Role == nil { return nil, errors.New("invalid value for required argument 'Role'") } var resource RegionDiskIamBinding err := ctx.RegisterResource("gcp:compute/regionDiskIamBinding:RegionDiskIamBinding", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetRegionDiskIamBinding gets an existing RegionDiskIamBinding resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetRegionDiskIamBinding(ctx *pulumi.Context, name string, id pulumi.IDInput, state *RegionDiskIamBindingState, opts ...pulumi.ResourceOption) (*RegionDiskIamBinding, error) { var resource RegionDiskIamBinding err := ctx.ReadResource("gcp:compute/regionDiskIamBinding:RegionDiskIamBinding", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering RegionDiskIamBinding resources. type regionDiskIamBindingState struct { Condition *RegionDiskIamBindingCondition `pulumi:"condition"` // (Computed) The etag of the IAM policy. Etag *string `pulumi:"etag"` Members []string `pulumi:"members"` // Used to find the parent resource to bind the IAM policy to Name *string `pulumi:"name"` // The ID of the project in which the resource belongs. // If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used. Project *string `pulumi:"project"` Region *string `pulumi:"region"` // The role that should be applied. Only one // `compute.DiskIamBinding` can be used per role. Note that custom roles must be of the format // `[projects|organizations]/{parent-name}/roles/{role-name}`. Role *string `pulumi:"role"` } type RegionDiskIamBindingState struct { Condition RegionDiskIamBindingConditionPtrInput // (Computed) The etag of the IAM policy. Etag pulumi.StringPtrInput Members pulumi.StringArrayInput // Used to find the parent resource to bind the IAM policy to Name pulumi.StringPtrInput // The ID of the project in which the resource belongs. // If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used. Project pulumi.StringPtrInput Region pulumi.StringPtrInput // The role that should be applied. Only one // `compute.DiskIamBinding` can be used per role. Note that custom roles must be of the format // `[projects|organizations]/{parent-name}/roles/{role-name}`. Role pulumi.StringPtrInput } func (RegionDiskIamBindingState) ElementType() reflect.Type { return reflect.TypeOf((*regionDiskIamBindingState)(nil)).Elem() } type regionDiskIamBindingArgs struct { Condition *RegionDiskIamBindingCondition `pulumi:"condition"` Members []string `pulumi:"members"` // Used to find the parent resource to bind the IAM policy to Name *string `pulumi:"name"` // The ID of the project in which the resource belongs. // If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used. Project *string `pulumi:"project"` Region *string `pulumi:"region"` // The role that should be applied. Only one // `compute.DiskIamBinding` can be used per role. Note that custom roles must be of the format // `[projects|organizations]/{parent-name}/roles/{role-name}`. Role string `pulumi:"role"` } // The set of arguments for constructing a RegionDiskIamBinding resource. type RegionDiskIamBindingArgs struct { Condition RegionDiskIamBindingConditionPtrInput Members pulumi.StringArrayInput // Used to find the parent resource to bind the IAM policy to Name pulumi.StringPtrInput // The ID of the project in which the resource belongs. // If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used. Project pulumi.StringPtrInput Region pulumi.StringPtrInput // The role that should be applied. Only one // `compute.DiskIamBinding` can be used per role. Note that custom roles must be of the format // `[projects|organizations]/{parent-name}/roles/{role-name}`. Role pulumi.StringInput } func (RegionDiskIamBindingArgs) ElementType() reflect.Type { return reflect.TypeOf((*regionDiskIamBindingArgs)(nil)).Elem() } type RegionDiskIamBindingInput interface { pulumi.Input ToRegionDiskIamBindingOutput() RegionDiskIamBindingOutput ToRegionDiskIamBindingOutputWithContext(ctx context.Context) RegionDiskIamBindingOutput } func (*RegionDiskIamBinding) ElementType() reflect.Type { return reflect.TypeOf((**RegionDiskIamBinding)(nil)).Elem() } func (i *RegionDiskIamBinding) ToRegionDiskIamBindingOutput() RegionDiskIamBindingOutput { return i.ToRegionDiskIamBindingOutputWithContext(context.Background()) } func (i *RegionDiskIamBinding) ToRegionDiskIamBindingOutputWithContext(ctx context.Context) RegionDiskIamBindingOutput { return pulumi.ToOutputWithContext(ctx, i).(RegionDiskIamBindingOutput) } // RegionDiskIamBindingArrayInput is an input type that accepts RegionDiskIamBindingArray and RegionDiskIamBindingArrayOutput values. // You can construct a concrete instance of `RegionDiskIamBindingArrayInput` via: // // RegionDiskIamBindingArray{ RegionDiskIamBindingArgs{...} } type RegionDiskIamBindingArrayInput interface { pulumi.Input ToRegionDiskIamBindingArrayOutput() RegionDiskIamBindingArrayOutput ToRegionDiskIamBindingArrayOutputWithContext(context.Context) RegionDiskIamBindingArrayOutput } type RegionDiskIamBindingArray []RegionDiskIamBindingInput func (RegionDiskIamBindingArray) ElementType() reflect.Type { return reflect.TypeOf((*[]*RegionDiskIamBinding)(nil)).Elem() } func (i RegionDiskIamBindingArray) ToRegionDiskIamBindingArrayOutput() RegionDiskIamBindingArrayOutput { return i.ToRegionDiskIamBindingArrayOutputWithContext(context.Background()) } func (i RegionDiskIamBindingArray) ToRegionDiskIamBindingArrayOutputWithContext(ctx context.Context) RegionDiskIamBindingArrayOutput { return pulumi.ToOutputWithContext(ctx, i).(RegionDiskIamBindingArrayOutput) } // RegionDiskIamBindingMapInput is an input type that accepts RegionDiskIamBindingMap and RegionDiskIamBindingMapOutput values. // You can construct a concrete instance of `RegionDiskIamBindingMapInput` via: // // RegionDiskIamBindingMap{ "key": RegionDiskIamBindingArgs{...} } type RegionDiskIamBindingMapInput interface { pulumi.Input ToRegionDiskIamBindingMapOutput() RegionDiskIamBindingMapOutput ToRegionDiskIamBindingMapOutputWithContext(context.Context) RegionDiskIamBindingMapOutput } type RegionDiskIamBindingMap map[string]RegionDiskIamBindingInput func (RegionDiskIamBindingMap) ElementType() reflect.Type { return reflect.TypeOf((*map[string]*RegionDiskIamBinding)(nil)).Elem() } func (i RegionDiskIamBindingMap) ToRegionDiskIamBindingMapOutput() RegionDiskIamBindingMapOutput { return i.ToRegionDiskIamBindingMapOutputWithContext(context.Background()) } func (i RegionDiskIamBindingMap) ToRegionDiskIamBindingMapOutputWithContext(ctx context.Context) RegionDiskIamBindingMapOutput { return pulumi.ToOutputWithContext(ctx, i).(RegionDiskIamBindingMapOutput) } type RegionDiskIamBindingOutput struct{ *pulumi.OutputState } func (RegionDiskIamBindingOutput) ElementType() reflect.Type { return reflect.TypeOf((**RegionDiskIamBinding)(nil)).Elem() } func (o RegionDiskIamBindingOutput) ToRegionDiskIamBindingOutput() RegionDiskIamBindingOutput { return o } func (o RegionDiskIamBindingOutput) ToRegionDiskIamBindingOutputWithContext(ctx context.Context) RegionDiskIamBindingOutput { return o } type RegionDiskIamBindingArrayOutput struct{ *pulumi.OutputState } func (RegionDiskIamBindingArrayOutput) ElementType() reflect.Type { return reflect.TypeOf((*[]*RegionDiskIamBinding)(nil)).Elem() } func (o RegionDiskIamBindingArrayOutput) ToRegionDiskIamBindingArrayOutput() RegionDiskIamBindingArrayOutput { return o } func (o RegionDiskIamBindingArrayOutput) ToRegionDiskIamBindingArrayOutputWithContext(ctx context.Context) RegionDiskIamBindingArrayOutput { return o } func (o RegionDiskIamBindingArrayOutput) Index(i pulumi.IntInput) RegionDiskIamBindingOutput { return pulumi.All(o, i).ApplyT(func(vs []interface{}) *RegionDiskIamBinding { return vs[0].([]*RegionDiskIamBinding)[vs[1].(int)] }).(RegionDiskIamBindingOutput) } type RegionDiskIamBindingMapOutput struct{ *pulumi.OutputState } func (RegionDiskIamBindingMapOutput) ElementType() reflect.Type { return reflect.TypeOf((*map[string]*RegionDiskIamBinding)(nil)).Elem() } func (o RegionDiskIamBindingMapOutput) ToRegionDiskIamBindingMapOutput() RegionDiskIamBindingMapOutput { return o } func (o RegionDiskIamBindingMapOutput) ToRegionDiskIamBindingMapOutputWithContext(ctx context.Context) RegionDiskIamBindingMapOutput { return o } func (o RegionDiskIamBindingMapOutput) MapIndex(k pulumi.StringInput) RegionDiskIamBindingOutput { return pulumi.All(o, k).ApplyT(func(vs []interface{}) *RegionDiskIamBinding { return vs[0].(map[string]*RegionDiskIamBinding)[vs[1].(string)] }).(RegionDiskIamBindingOutput) } func init() { pulumi.RegisterInputType(reflect.TypeOf((*RegionDiskIamBindingInput)(nil)).Elem(), &RegionDiskIamBinding{}) pulumi.RegisterInputType(reflect.TypeOf((*RegionDiskIamBindingArrayInput)(nil)).Elem(), RegionDiskIamBindingArray{}) pulumi.RegisterInputType(reflect.TypeOf((*RegionDiskIamBindingMapInput)(nil)).Elem(), RegionDiskIamBindingMap{}) pulumi.RegisterOutputType(RegionDiskIamBindingOutput{}) pulumi.RegisterOutputType(RegionDiskIamBindingArrayOutput{}) pulumi.RegisterOutputType(RegionDiskIamBindingMapOutput{}) }
swedenconnect/eidas-eu-mock
cef-20-demo-hub/src/main/java/se/swedenconnect/eidas/test/cef20demohub/data/ResponseData.java
package se.swedenconnect.eidas.test.cef20demohub.data; import eu.eidas.SimpleProtocol.Response; import lombok.Data; import java.util.Map; @Data public class ResponseData { private Response response; private String b64Response; private Map<String,Boolean> requestedAttributesMap; private boolean error; private String statusCode; private String errorMessage; private String errorMessageTitle; public ResponseData() { this.response = new Response(); } }
marcosortiz/iot-water-tank-workshop
backend/src/tanks/provisioning/greengrass/provision/createGreengrassLoggerDefinition.js
<reponame>marcosortiz/iot-water-tank-workshop 'use strict' var AWS = require('aws-sdk/global'); var Greengrass = require('aws-sdk/clients/greengrass'); AWS.config.region = process.env.AWS_REGION; var greengrass = new Greengrass(); module.exports = { createGreengrassLoggerDefinition: async (event, context) => { var params = { InitialVersion: { Loggers: [ { Component: 'GreengrassSystem', Id: `${event.thingName}-Logger`, Level: 'INFO', Type: 'AWSCloudWatch' } ] }, Name: `${event.thingName}-Logger-Definition` }; var data = await greengrass.createLoggerDefinition(params).promise(); return data; } }
chicojfp/orquestra
src/main/java/io/breezil/orquestra/CliOptions.java
package io.breezil.orquestra; import java.util.Objects; public class CliOptions { private String grammarFile; private String scriptFile; private String objectDefinitionFile; private String webdriver = CHROME; public static String CHROME = "chrome"; public static String FIREFOX = "firefox"; public boolean hasValidArgs() { return !Objects.isNull(this.grammarFile) && !Objects.isNull(this.scriptFile); } public String getGrammarFile() { return grammarFile; } public void setGrammarFile(String grammarFile) { this.grammarFile = grammarFile; } public String getScriptFile() { return scriptFile; } public void setScriptFile(String scriptFile) { this.scriptFile = scriptFile; } public String getObjectDefinitionFile() { return objectDefinitionFile; } public void setObjectDefinitionFile(String objectDefinitionFile) { this.objectDefinitionFile = objectDefinitionFile; } public void setWebDriver(String webdriver) { this.webdriver = webdriver; } public String getWebDriver() { return this.webdriver; } }
IvayloIV/Java
Hibernate/Exams/20.12.2018/src/main/java/hiberspring/domain/dtos/xml/ProductRootXmlDto.java
package hiberspring.domain.dtos.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.List; @XmlRootElement(name = "products") @XmlAccessorType(XmlAccessType.FIELD) public class ProductRootXmlDto implements Serializable { @XmlElement(name = "product") private List<ProductXmlDto> productsDto; public List<ProductXmlDto> getProductsDto() { return productsDto; } public void setProductsDto(List<ProductXmlDto> productsDto) { this.productsDto = productsDto; } }
ahamilton55/ctlptl
pkg/cluster/docker_desktop_dial_windows.go
// +build windows package cluster import ( "net" "os" "time" "gopkg.in/natefinch/npipe.v2" ) func dockerDesktopSocketPaths() ([]string, error) { return []string{ `\\.\pipe\dockerWebApiServer`, `\\.\pipe\dockerBackendNativeApiServer`, }, nil } // Use npipe.Dial to create a connection. // // npipe.Dial will wait if the socket doesn't exist. Stat it first and // dial on a timeout. // // https://github.com/natefinch/npipe#func-dial func dialDockerDesktop(socketPath string) (net.Conn, error) { _, err := os.Stat(socketPath) if err != nil { return nil, err } return npipe.DialTimeout(socketPath, 2*time.Second) }
Grosskopf/openoffice
main/qadevOOo/java/OOoRunner/src/main/java/util/WriterTools.java
<reponame>Grosskopf/openoffice /************************************************************** * * 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 util; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XNamed; import com.sun.star.drawing.XDrawPage; import com.sun.star.drawing.XDrawPageSupplier; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.XText; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.uno.UnoRuntime; // access the implementations via names import com.sun.star.uno.XInterface; import util.DesktopTools; public class WriterTools { public static XTextDocument createTextDoc(XMultiServiceFactory xMSF) { PropertyValue[] Args = new PropertyValue[0]; XComponent comp = DesktopTools.openNewDoc(xMSF, "swriter", Args); XTextDocument WriterDoc = (XTextDocument) UnoRuntime.queryInterface( XTextDocument.class, comp); return WriterDoc; } // finish createTextDoc public static XTextDocument loadTextDoc(XMultiServiceFactory xMSF, String url) { PropertyValue[] Args = new PropertyValue[0]; XTextDocument WriterDoc = loadTextDoc(xMSF, url, Args); return WriterDoc; } // finish createTextDoc public static XTextDocument loadTextDoc(XMultiServiceFactory xMSF, String url, PropertyValue[] Args) { XComponent comp = DesktopTools.loadDoc(xMSF, url, Args); XTextDocument WriterDoc = (XTextDocument) UnoRuntime.queryInterface( XTextDocument.class, comp); return WriterDoc; } // finish createTextDoc public static XDrawPage getDrawPage(XTextDocument aDoc) { XDrawPage oDP = null; try { XDrawPageSupplier oDPS = (XDrawPageSupplier) UnoRuntime.queryInterface( XDrawPageSupplier.class, aDoc); oDP = (XDrawPage) oDPS.getDrawPage(); } catch (Exception e) { throw new IllegalArgumentException("Couldn't get drawpage"); } return oDP; } public static void insertTextGraphic(XTextDocument aDoc, XMultiServiceFactory xMSF, int hpos, int vpos, int width, int height, String pic, String name) { try { Object oGObject = (XInterface) xMSF.createInstance( "com.sun.star.text.GraphicObject"); XText the_text = aDoc.getText(); XTextCursor the_cursor = the_text.createTextCursor(); XTextContent the_content = (XTextContent) UnoRuntime.queryInterface( XTextContent.class, oGObject); the_text.insertTextContent(the_cursor, the_content, true); XPropertySet oProps = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, oGObject); String fullURL = util.utils.getFullTestURL(pic); oProps.setPropertyValue("GraphicURL", fullURL); oProps.setPropertyValue("HoriOrientPosition", new Integer(hpos)); oProps.setPropertyValue("VertOrientPosition", new Integer(vpos)); oProps.setPropertyValue("Width", new Integer(width)); oProps.setPropertyValue("Height", new Integer(height)); XNamed the_name = (XNamed) UnoRuntime.queryInterface(XNamed.class, oGObject); the_name.setName(name); } catch (Exception ex) { System.out.println("Exception while insertin TextGraphic"); ex.printStackTrace(); } } }
MarioSomodi/Comic-Codex
src/containers/SeriesContainers/SeriesDetails.js
/* eslint-disable react-hooks/exhaustive-deps */ import React, {useState, useEffect} from 'react'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import { View, HStack, Image, Text, Divider, VStack, ScrollView, Icon, IconButton, Center, Spinner, Heading, Button, } from 'native-base'; import {firebase} from '@react-native-firebase/database'; import placeholderImage from '../../assets/images/Placeholder.png'; import PureCreatorItemView from '../../components/CreatorComponents/PureCreatorItemView'; import {GetSeriesSingle} from '../../api/controllers/seriesController'; const ComicDetails = ({route, navigation, user}) => { const [seriesSingle, setSeriesSingle] = useState(null); const [favoriteSeries, setFavoriteSeries] = useState(null); const getSingleSeries = async () => { var response = await GetSeriesSingle(route.params.loadFromId); setSeriesSingle(response); }; const database = firebase .app() .database( 'https://comic-codex-default-rtdb.europe-west1.firebasedatabase.app/', ); const addSeriesToFavorites = async () => { database .ref('/series/' + user.uid) .once('value') .then(value => { if (value === null) { database .ref('/series/' + user.uid + '/' + seriesSingle.id) .set(seriesSingle); } else { database .ref('/series/' + user.uid + '/' + seriesSingle.id) .set(seriesSingle); } }); }; const removeSeriesFromFavorites = async () => { database.ref('/series/' + user.uid + '/' + seriesSingle.id).remove(); }; useEffect(() => { database.ref('/series/' + user.uid).on('value', snapshot => { var favoriteSeriesDB = snapshot.val(); if (favoriteSeriesDB !== null) { favoriteSeriesDB = Object.values(favoriteSeriesDB); var fSeries = []; favoriteSeriesDB.forEach(usersFavoriteSeries => { fSeries.push(usersFavoriteSeries); }); setFavoriteSeries(fSeries); } else { setFavoriteSeries([]); } }); if (route.params.seriesSingle != null) { setSeriesSingle(route.params.seriesSingle); } }, []); useEffect(() => { if (route.params.load === true) { getSingleSeries(); } }, [route.params.load]); return ( <ScrollView contentContainerStyle={{ justifyContent: seriesSingle != null ? 'flex-start' : 'center', flexGrow: 1, }} p={2}> {seriesSingle != null ? ( <VStack mb={10}> <HStack justifyContent="center" alignItems="center"> <Image alignSelf="center" borderColor="black" borderWidth={1} borderRadius="md" justifyContent="center" alignItems="center" alt={seriesSingle.title} h={225} w={150} key={seriesSingle.id} source={ seriesSingle.thumbnail === true ? placeholderImage : {uri: seriesSingle.thumbnail} } /> <Divider w={1} mx={2} orientation="vertical" borderRadius={50} backgroundColor="red.800" /> <VStack flex={1}> <Text m={1} bold={true} fontSize={20}> {seriesSingle.title} </Text> <Divider h={0.5} borderRadius={50} backgroundColor="red.800" /> {seriesSingle.startYear != null ? ( <View> <Text m={1} fontSize={17}> <Text fontSize={18} bold={true}> Start year </Text> : {seriesSingle.startYear} </Text> <Divider h={0.5} borderRadius={50} backgroundColor="red.800" /> </View> ) : null} {seriesSingle.endYear != null ? ( <View> <Text m={1} fontSize={17}> <Text fontSize={18} bold={true}> End year </Text> : {seriesSingle.endYear} </Text> <Divider h={0.5} borderRadius={50} backgroundColor="red.800" /> </View> ) : null} {seriesSingle.type != null ? ( <View> <Text m={1} fontSize={17}> <Text fontSize={18} bold={true}> Type </Text> : {seriesSingle.type} </Text> <Divider h={0.5} borderRadius={50} backgroundColor="red.800" /> </View> ) : null} {seriesSingle.rating != null ? ( <View> <Text m={1} fontSize={17}> <Text fontSize={18} bold={true}> Rating </Text> : {seriesSingle.rating} </Text> <Divider h={0.5} borderRadius={50} backgroundColor="red.800" /> </View> ) : null} </VStack> </HStack> <Text m={1} mt={3} fontSize={15}> {seriesSingle.description} </Text> {favoriteSeries && favoriteSeries.some(favoritSeriesSingle => { if (favoritSeriesSingle.id === seriesSingle.id) { return true; } else { return false; } }) ? ( <Button alignSelf="center" my={2} w="100%" onPress={removeSeriesFromFavorites} variant="solid" backgroundColor="red.800" borderRadius="full" size="lg"> <HStack alignItems="center"> <Text color="white" mr={2}> Remove from favorites </Text> <Icon color="white" as={MaterialIcons} name="star" size="sm" /> </HStack> </Button> ) : ( <Button alignSelf="center" my={2} w="100%" onPress={addSeriesToFavorites} variant="solid" backgroundColor="red.800" borderRadius="full" size="lg"> <HStack alignItems="center"> <Text color="white" mr={2}> Add to favorites </Text> <Icon color="white" as={MaterialIcons} name="star-outline" size="sm" /> </HStack> </Button> )} {seriesSingle.charactersAvailable !== 0 || seriesSingle.storiesAvailable !== 0 || seriesSingle.comicsAvailable !== 0 || seriesSingle.eventsAvailable !== 0 ? ( <View> <Divider mt={3} h={1} borderRadius={50} backgroundColor="red.800" /> <HStack justifyContent="center" alignItems="center"> {seriesSingle.charactersAvailable !== 0 ? ( <VStack mx={2}> <IconButton alignSelf="center" mt={3} variant="solid" backgroundColor="red.800" borderRadius="full" size="lg" onPress={() => navigation.navigate('Root', { screen: 'Characters', params: { id: seriesSingle.id, name: seriesSingle.title, type: 'series', }, }) } icon={ <Icon color="white" as={MaterialIcons} name="person" size="sm" /> } /> <Text textAlign="center" fontSize={14}> Characters </Text> </VStack> ) : null} {seriesSingle.comicsAvailable !== null ? ( <VStack mx={2}> <IconButton alignSelf="center" mt={3} variant="solid" backgroundColor="red.800" borderRadius="full" size="lg" onPress={() => navigation.navigate('Root', { screen: 'Comics', params: { id: seriesSingle.id, name: seriesSingle.title, type: 'series', }, }) } icon={ <Icon color="white" as={MaterialIcons} name="menu-book" size="sm" /> } /> <Text textAlign="center" fontSize={14}> Comics </Text> </VStack> ) : null} {seriesSingle.eventsAvailable !== 0 ? ( <VStack mx={2}> <IconButton alignSelf="center" mt={3} variant="solid" backgroundColor="red.800" borderRadius="full" size="lg" onPress={() => navigation.navigate('Root', { screen: 'Events', params: { id: seriesSingle.id, name: seriesSingle.title, type: 'series', }, }) } icon={ <Icon color="white" as={MaterialIcons} name="event" size="sm" /> } /> <Text textAlign="center" fontSize={14}> Events </Text> </VStack> ) : null} {seriesSingle.storiesAvailable !== 0 ? ( <VStack mx={2}> <IconButton alignSelf="center" mt={3} variant="solid" backgroundColor="red.800" borderRadius="full" size="lg" onPress={() => navigation.navigate('Root', { screen: 'Stories', params: { id: seriesSingle.id, name: seriesSingle.title, type: 'series', }, }) } icon={ <Icon color="white" as={MaterialIcons} name="library-books" size="sm" /> } /> <Text textAlign="center" fontSize={14}> Stories </Text> </VStack> ) : null} </HStack> <Text textAlign="center" mt={2} fontSize={11}> <Text mb={-2} fontSize={11} bold={true}> Hint: </Text>{' '} pressing the buttons above will bring up this series specified item/s. </Text> </View> ) : null} {seriesSingle.creators.length > 0 ? ( <View> <Divider mt={3} h={1} borderRadius={50} backgroundColor="red.800" /> <VStack m={1} mt={3}> <Text textAlign="center" mb={3} key={-1} bold={true} fontSize={18}> Creators </Text> {seriesSingle.creators.map((creator, index) => { return ( <PureCreatorItemView key={index} navigation={navigation} item={creator} origin="comics" /> ); })} </VStack> </View> ) : null} </VStack> ) : ( <Center> <Spinner accessibilityLabel="Loading series" color="red.800" size="lg" /> <Heading color="red.800" fontSize="lg"> Loading series </Heading> </Center> )} </ScrollView> ); }; export default ComicDetails;
jcencek/draftpod
src/store/modules/draft/set/set-aer.js
import * as cube from './cube' import * as booster from './booster' export default { name: "<NAME>", expansion_set: true, pack_set: pack_number => { return ((pack_number % 3) === 0) ? 'kld' : 'aer' }, pack_cards: () => 14, capabilities: { arena_decklists: false }, cube: cube.build, booster(selectCards) { let cards = [].concat( selectCards(booster.packRareSlot, 1), selectCards(booster.uncommon, 3), selectCards(booster.common, 10) ); return cards; }, }
redding/much-rails
test/unit/wrap_method_tests.rb
<filename>test/unit/wrap_method_tests.rb # frozen_string_literal: true require "assert" require "much-rails/wrap_method" module MuchRails::WrapMethod class UnitTests < Assert::Context desc "MuchRails::WrapMethod" subject{ unit_class } let(:unit_class){ MuchRails::WrapMethod } should "include MuchRails::Mixin" do assert_that(subject).includes(MuchRails::Mixin) end end class ReceiverTests < UnitTests desc "receiver" subject{ receiver_class } let(:receiver_class) do Class.new do include MuchRails::WrapMethod attr_reader :object, :object_kargs def initialize(object, **object_kargs) @object = object @object_kargs = object_kargs end def self.build(object, **object_kargs) new(object, initializer_method: :build, **object_kargs) end end end let(:objects){ [object1, object2] } let(:object1){ OpenStruct.new(name: "OBJECT1") } let(:object2){ OpenStruct.new(name: "OBJECT2") } let(:object_kargs) do { test_key1: 1, test_key2: 2, } end should have_imeths :wrap, :wrap_with_index, :wrap_initializer_method end class WrapAndWrapWithIndexTests < ReceiverTests desc "wrap and wrap with index" subject{ receiver_class } should "call new for each given object" do wrapped_objects = subject.wrap(objects, **object_kargs) assert_that(wrapped_objects.size).equals(objects.size) wrapped_objects.each_with_index do |wrapped_object, index| assert_that(wrapped_object).is_instance_of(subject) assert_that(wrapped_object.object).equals(objects[index]) assert_that(wrapped_object.object_kargs).equals(object_kargs) end wrapped_objects = subject.wrap_with_index(objects, **object_kargs) assert_that(wrapped_objects.size).equals(objects.size) wrapped_objects.each_with_index do |wrapped_object, index| assert_that(wrapped_object).is_instance_of(subject) assert_that(wrapped_object.object).equals(objects[index]) assert_that(wrapped_object.object_kargs) .equals(object_kargs.update(index: index)) end end end class CustomWrapInitializerMethodTests < ReceiverTests desc "with a custom wrap initializer method" subject{ receiver_class } setup do receiver_class.wrap_initializer_method(:build) end should "call the custom method for each given object" do wrapped_objects = subject.wrap(objects, **object_kargs) assert_that(wrapped_objects.size).equals(objects.size) wrapped_objects.each_with_index do |wrapped_object, index| assert_that(wrapped_object).is_instance_of(subject) assert_that(wrapped_object.object).equals(objects[index]) assert_that(wrapped_object.object_kargs) .equals(object_kargs.merge(initializer_method: :build)) end end end class WrapMethodConfigTests < ReceiverTests desc "receiver_class::WrapMethodConfig" subject{ config_class.new } let(:config_class){ receiver_class::WrapMethodConfig } should have_accessors :wrap_initializer_method should "know its attribute values" do assert_that(subject.wrap_initializer_method).equals(:new) end end end
chenbin1985/react-practice
app/containers/Layout/index.js
import React from 'react'; import ReactGridLayout from 'react-grid-layout' import styles from './styles.css' import 'react-grid-layout/css/styles.css' import 'react-resizable/css/styles.css' const Layout = () => { return ( <div className={styles.page}> <div className={styles.header}> Header </div> <div className={styles.container}> <div className={styles.main}> main word-break: break-all; word-wrap: break-word;content content content content 我是中文,我是中文 </div> <div className={styles.left}>left</div> <div className={styles.right}>right</div> </div> <div className={styles.container}> <div className={styles.main1}> <div className={styles.content}> main word-break: break-all; content content content content 我是中文,我是中文 </div> </div> <div className={styles.left}>left</div> <div className={styles.right}>right</div> </div> <div className={styles.container}> <div className={styles.float_left}>left</div> <div className={styles.float_right}>right</div> <div className={styles.float_main}> main word-wrap: break-word; content content content content content 我是中文,我是中文 </div> </div> <div className={styles.footer}> Footer </div> <ReactGridLayout className="layout" cols={12} rowHeight={30} width={1200}> <div key="a" data-grid={{x: 0, y: 0, w: 1, h: 2, static: true}}>a</div> <div key="b" data-grid={{x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4}}>b</div> <div key="c" data-grid={{x: 4, y: 0, w: 1, h: 2}}>c</div> </ReactGridLayout> </div> ); }; export default Layout;
Crystalnix/BitPop
chrome/browser/ui/webui/chrome_url_data_manager.h
<reponame>Crystalnix/BitPop<filename>chrome/browser/ui/webui/chrome_url_data_manager.h // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_WEBUI_CHROME_URL_DATA_MANAGER_H_ #define CHROME_BROWSER_UI_WEBUI_CHROME_URL_DATA_MANAGER_H_ #include <string> #include <vector> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner_helpers.h" #include "base/synchronization/lock.h" #include "chrome/browser/profiles/profile_keyed_service.h" class ChromeURLDataManagerBackend; class MessageLoop; class Profile; namespace base { class DictionaryValue; class RefCountedMemory; } // To serve dynamic data off of chrome: URLs, implement the // ChromeURLDataManager::DataSource interface and register your handler // with AddDataSource. DataSources must be added on the UI thread (they are also // deleted on the UI thread). Internally the DataSources are maintained by // ChromeURLDataManagerBackend, see it for details. class ChromeURLDataManager : public ProfileKeyedService { public: class DataSource; // Trait used to handle deleting a DataSource. Deletion happens on the UI // thread. // // Implementation note: the normal shutdown sequence is for the UI loop to // stop pumping events then the IO loop and thread are stopped. When the // DataSources are no longer referenced (which happens when IO thread stops) // they get added to the UI message loop for deletion. But because the UI loop // has stopped by the time this happens the DataSources would be leaked. // // To make sure DataSources are properly deleted ChromeURLDataManager manages // deletion of the DataSources. When a DataSource is no longer referenced it // is added to |data_sources_| and a task is posted to the UI thread to handle // the actual deletion. During shutdown |DeleteDataSources| is invoked so that // all pending DataSources are properly deleted. struct DeleteDataSource { static void Destruct(const DataSource* data_source) { ChromeURLDataManager::DeleteDataSource(data_source); } }; // A DataSource is an object that can answer requests for data // asynchronously. DataSources are collectively owned with refcounting smart // pointers and should never be deleted on the IO thread, since their calls // are handled almost always on the UI thread and there's a possibility of a // data race. The |DeleteDataSource| trait above is used to enforce this. // // An implementation of DataSource should handle calls to // StartDataRequest() by starting its (implementation-specific) asynchronous // request for the data, then call SendResponse() to notify. class DataSource : public base::RefCountedThreadSafe< DataSource, DeleteDataSource> { public: // See source_name_ and message_loop_ below for docs on these parameters. DataSource(const std::string& source_name, MessageLoop* message_loop); // Sent by the DataManager to request data at |path|. The source should // call SendResponse() when the data is available or if the request could // not be satisfied. virtual void StartDataRequest(const std::string& path, bool is_incognito, int request_id) = 0; // Return the mimetype that should be sent with this response, or empty // string to specify no mime type. virtual std::string GetMimeType(const std::string& path) const = 0; // Report that a request has resulted in the data |bytes|. // If the request can't be satisfied, pass NULL for |bytes| to indicate // the request is over. virtual void SendResponse(int request_id, base::RefCountedMemory* bytes); // Returns the MessageLoop on which the DataSource wishes to have // StartDataRequest called to handle the request for |path|. If the // DataSource does not care which thread StartDataRequest is called on, // this should return NULL. The default implementation always returns // message_loop_, which generally results in processing on the UI thread. // It may be beneficial to return NULL for requests that are safe to handle // directly on the IO thread. This can improve performance by satisfying // such requests more rapidly when there is a large amount of UI thread // contention. virtual MessageLoop* MessageLoopForRequestPath(const std::string& path) const; const std::string& source_name() const { return source_name_; } // Returns true if this DataSource should replace an existing DataSource // with the same name that has already been registered. The default is // true. // // WARNING: this is invoked on the IO thread. // // TODO: nuke this and convert all callers to not replace. virtual bool ShouldReplaceExistingSource() const; // Returns true if responses from this DataSource can be cached. virtual bool AllowCaching() const { return true; } static void SetFontAndTextDirection( base::DictionaryValue* localized_strings); protected: virtual ~DataSource(); private: friend class ChromeURLDataManagerBackend; friend class ChromeURLDataManager; friend class base::DeleteHelper<DataSource>; // SendResponse invokes this on the IO thread. Notifies the backend to // handle the actual work of sending the data. virtual void SendResponseOnIOThread( int request_id, scoped_refptr<base::RefCountedMemory> bytes); // The name of this source. // E.g., for favicons, this could be "favicon", which results in paths for // specific resources like "favicon/34" getting sent to this source. const std::string source_name_; // The MessageLoop for the thread where this DataSource lives. // Used to send messages to the DataSource. MessageLoop* message_loop_; // This field is set and maintained by ChromeURLDataManagerBackend. It is // set when the DataSource is added, and unset if the DataSource is removed. // A DataSource can be removed in two ways: the ChromeURLDataManagerBackend // is deleted, or another DataSource is registered with the same // name. backend_ should only be accessed on the IO thread. // This reference can't be via a scoped_refptr else there would be a cycle // between the backend and data source. ChromeURLDataManagerBackend* backend_; }; explicit ChromeURLDataManager( const base::Callback<ChromeURLDataManagerBackend*(void)>& backend); virtual ~ChromeURLDataManager(); // Adds a DataSource to the collection of data sources. This *must* be invoked // on the UI thread. // // If |AddDataSource| is called more than once for a particular name it will // release the old |DataSource|, most likely resulting in it getting deleted // as there are no other references to it. |DataSource| uses the // |DeleteOnUIThread| trait to insure that the destructor is called on the UI // thread. This is necessary as some |DataSource|s notably |FileIconSource| // and |FaviconSource|, have members that will DCHECK if they are not // destructed in the same thread as they are constructed (the UI thread). void AddDataSource(DataSource* source); // Deletes any data sources no longer referenced. This is normally invoked // for you, but can be invoked to force deletion (such as during shutdown). static void DeleteDataSources(); // Convenience wrapper function to add |source| to |profile|'s // |ChromeURLDataManager|. static void AddDataSource(Profile* profile, DataSource* source); private: typedef std::vector<const ChromeURLDataManager::DataSource*> DataSources; // If invoked on the UI thread the DataSource is deleted immediatlye, // otherwise it is added to |data_sources_| and a task is scheduled to handle // deletion on the UI thread. See note abouve DeleteDataSource for more info. static void DeleteDataSource(const DataSource* data_source); // Returns true if |data_source| is scheduled for deletion (|DeleteDataSource| // was invoked). static bool IsScheduledForDeletion(const DataSource* data_source); // A callback that returns the ChromeURLDataManagerBackend. Only accessible on // the IO thread. This is necessary because ChromeURLDataManager is created on // the UI thread, but ChromeURLDataManagerBackend lives on the IO thread. const base::Callback<ChromeURLDataManagerBackend*(void)> backend_; // |data_sources_| that are no longer referenced and scheduled for deletion. // Protected by g_delete_lock in the .cc file. static DataSources* data_sources_; DISALLOW_COPY_AND_ASSIGN(ChromeURLDataManager); }; #endif // CHROME_BROWSER_UI_WEBUI_CHROME_URL_DATA_MANAGER_H_
MarkRDavison/AdventOfCode
test/2016/Day13PuzzleTests.cpp
<filename>test/2016/Day13PuzzleTests.cpp #include <catch/catch.hpp> #include <2016/Day13Puzzle.hpp> namespace TwentySixteen { TEST_CASE("2016 Day 13 get traversable works", "[2016][Day13]") { REQUIRE(Day13Puzzle::getTraversable({ 0, 0 }, 10)); REQUIRE_FALSE(Day13Puzzle::getTraversable({ 1, 0 }, 10)); REQUIRE(Day13Puzzle::getTraversable({ 2, 0 }, 10)); REQUIRE_FALSE(Day13Puzzle::getTraversable({ 3, 0 }, 10)); REQUIRE_FALSE(Day13Puzzle::getTraversable({ 4, 0 }, 10)); REQUIRE_FALSE(Day13Puzzle::getTraversable({ 5, 0 }, 10)); REQUIRE_FALSE(Day13Puzzle::getTraversable({ 6, 0 }, 10)); REQUIRE_FALSE(Day13Puzzle::getTraversable({ 2, 1 }, 10)); REQUIRE(Day13Puzzle::getTraversable({ 1, 1 }, 10)); } TEST_CASE("2016 Day 13 Part 1 Example work", "[2016][Day13]") { core::CartesianNetwork<OfficeCell> network; const OfficeInteger number = 10; const ze::Vector2<OfficeInteger> size = { 50, 50 }; const ze::Vector2<OfficeInteger> start = { 1, 1 }; const ze::Vector2<OfficeInteger> goal = { 7, 4 }; Day13Puzzle::searchSpace(network, number, size); const auto& path = network.performAStarSearch(start, goal); REQUIRE(11 == Day13Puzzle::pathLength(network, start, goal)); } }
FWinkler79/kyma
tests/end-to-end/external-solution-integration/pkg/testkit/compass_connector.go
<reponame>FWinkler79/kyma package testkit import ( "crypto/tls" "github.com/kyma-incubator/compass/components/connector/pkg/graphql/clientset" ) type CompassConnectorClient struct { connector *clientset.ConnectorClientSet } func NewCompassConnectorClient(skipTLSVerify bool) *CompassConnectorClient { return &CompassConnectorClient{ connector: clientset.NewConnectorClientSet(clientset.WithSkipTLSVerify(skipTLSVerify)), } } func (cc *CompassConnectorClient) GenerateCertificateForToken(token, connectorURL string) (tls.Certificate, error) { return cc.connector.GenerateCertificateForToken(token, connectorURL) }
kikislater/micmac
src/interface/test_ISA0/include_isa/Affichage.cpp
#include "StdAfx.h" #include "Affichage.h" using namespace std; Affichage::Affichage(ListImg* l, string dossier, int i) : lstImg(l), img0(i), dossierImg(dossier) {} bool Affichage::Can_open(const char * name) //renvoie true si le fichier de la photo est trouvé { ELISE_fp fp; if (! fp.ropen(name,true)) return false; fp.close(); return true; } Tiff_Im Affichage::GetImage(int img, bool& b, INT& max_val, INT& mult, Pt2di& size) { string chemin=(*lstImg).at(img-1-img0).GetChemin(); string nomImg=(*lstImg).at(img-1-img0).GetNomImg(); char buf[200]; sprintf(buf,"%s%s/%s",chemin.c_str(),dossierImg.c_str(),nomImg.c_str()); cout << "affichage " << buf << "\n"; ELISE_ASSERT(Can_open(buf),("Pb lecture image "+string(buf)).c_str()); Tiff_Im Image(buf); max_val = 1 << Image.bitpp(); mult = 255 / (max_val-1); size=ElGenFileIm(Image).Sz2(); b=true; return Image; } void Affichage::MakeTiff(Bitm_Win aW, string result) { char *c = new char[strlen(result.c_str())]; strcpy(c,result.c_str()); aW.make_tif(c); } void Affichage::AffichePointsImage(ListPt* LstInit, ListPt* LstFin, int img, string result) { //affiche tous les points de l'image en fonction de leur multiplicité if (img-img0>signed((*lstImg).size())) return; INT max_val; INT mult; Pt2di size; bool b; Tiff_Im Image=GetImage(img, b, max_val, mult, size); if (!b) return; Elise_Set_Of_Palette aSPal = GlobPal(); Bitm_Win aW("toto",aSPal,size); ELISE_COPY(aW.all_pts(),mult * Image.in(max_val/2),aW.ogray()); for(ListPt::const_iterator itp=(*LstInit).begin(); itp!=(*LstInit).end(); itp++){ if (Point(*itp).GetCoord().GetImg()==img) { if(Point(*itp).GetNbHom()==4) aW.draw_circle_abs((*itp).GetPt2dr(), 2.0,Line_St(aW.prgb()(255,0,0),2)); if(Point(*itp).GetNbHom()==3) aW.draw_circle_abs((*itp).GetPt2dr(), 2.0,aW.prgb()(0,255,0)); if(Point(*itp).GetNbHom()==2) aW.draw_circle_abs((*itp).GetPt2dr(), 2.0,aW.prgb()(0,0,255)); if(Point(*itp).GetNbHom()==1) aW.draw_circle_abs((*itp).GetPt2dr(), 2.0,aW.prgb()(130,130,130)); } } for(ListPt::const_iterator itp=(*LstFin).begin(); itp!=(*LstFin).end(); itp++){ if (Point(*itp).GetCoord().GetImg()==img) { if(Point(*itp).GetNbHom()==4) aW.draw_circle_abs((*itp).GetPt2dr(), 20.0,Line_St(aW.prgb()(255,0,0),2)); if(Point(*itp).GetNbHom()==3) aW.draw_circle_abs((*itp).GetPt2dr(), 20.0,aW.prgb()(0,255,0)); if(Point(*itp).GetNbHom()==2) aW.draw_circle_abs((*itp).GetPt2dr(), 20.0,aW.prgb()(0,0,255)); if(Point(*itp).GetNbHom()==1) aW.draw_circle_abs((*itp).GetPt2dr(), 20.0,aW.prgb()(130,130,130)); } } MakeTiff(aW, result); } template void Affichage::AffichePointsPaire(list<Point1>::const_iterator itBegin, list<Point1>::const_iterator itEnd, int img, int img2, string result1, string result2, bool segment); template void Affichage::AffichePointsPaire(ListPt::const_iterator itBegin, ListPt::const_iterator itEnd, int img, int img2, string result1, string result2, bool segment);
johan--/inputex
build/inputex-ipv4/lang/inputex-ipv4_pt-BR.js
YUI.add("lang/inputex-ipv4_pt-BR",function(e){e.Intl.add("inputex-ipv4","pt-BR",{invalidIPv4:"Endere\u00e7o IPv4 inv\u00e1lido, ex: 192.168.0.1"})},"@VERSION@");
LaudateCorpus1/bosh-oracle-cpi
vendor/oracle/oci/core/client/blockstorage/create_volume_backup_parameters.go
<reponame>LaudateCorpus1/bosh-oracle-cpi package blockstorage // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "net/http" "time" "golang.org/x/net/context" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" strfmt "github.com/go-openapi/strfmt" "oracle/oci/core/models" ) // NewCreateVolumeBackupParams creates a new CreateVolumeBackupParams object // with the default values initialized. func NewCreateVolumeBackupParams() *CreateVolumeBackupParams { var () return &CreateVolumeBackupParams{ timeout: cr.DefaultTimeout, } } // NewCreateVolumeBackupParamsWithTimeout creates a new CreateVolumeBackupParams object // with the default values initialized, and the ability to set a timeout on a request func NewCreateVolumeBackupParamsWithTimeout(timeout time.Duration) *CreateVolumeBackupParams { var () return &CreateVolumeBackupParams{ timeout: timeout, } } // NewCreateVolumeBackupParamsWithContext creates a new CreateVolumeBackupParams object // with the default values initialized, and the ability to set a context for a request func NewCreateVolumeBackupParamsWithContext(ctx context.Context) *CreateVolumeBackupParams { var () return &CreateVolumeBackupParams{ Context: ctx, } } // NewCreateVolumeBackupParamsWithHTTPClient creates a new CreateVolumeBackupParams object // with the default values initialized, and the ability to set a custom HTTPClient for a request func NewCreateVolumeBackupParamsWithHTTPClient(client *http.Client) *CreateVolumeBackupParams { var () return &CreateVolumeBackupParams{ HTTPClient: client, } } /*CreateVolumeBackupParams contains all the parameters to send to the API endpoint for the create volume backup operation typically these are written to a http.Request */ type CreateVolumeBackupParams struct { /*CreateVolumeBackupDetails Request to create a new backup of given volume. */ CreateVolumeBackupDetails *models.CreateVolumeBackupDetails /*OpcRetryToken A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations (e.g., if a resource has been deleted and purged from the system, then a retry of the original creation request may be rejected). */ OpcRetryToken *string timeout time.Duration Context context.Context HTTPClient *http.Client } // WithTimeout adds the timeout to the create volume backup params func (o *CreateVolumeBackupParams) WithTimeout(timeout time.Duration) *CreateVolumeBackupParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the create volume backup params func (o *CreateVolumeBackupParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the create volume backup params func (o *CreateVolumeBackupParams) WithContext(ctx context.Context) *CreateVolumeBackupParams { o.SetContext(ctx) return o } // SetContext adds the context to the create volume backup params func (o *CreateVolumeBackupParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the create volume backup params func (o *CreateVolumeBackupParams) WithHTTPClient(client *http.Client) *CreateVolumeBackupParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the create volume backup params func (o *CreateVolumeBackupParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithCreateVolumeBackupDetails adds the createVolumeBackupDetails to the create volume backup params func (o *CreateVolumeBackupParams) WithCreateVolumeBackupDetails(createVolumeBackupDetails *models.CreateVolumeBackupDetails) *CreateVolumeBackupParams { o.SetCreateVolumeBackupDetails(createVolumeBackupDetails) return o } // SetCreateVolumeBackupDetails adds the createVolumeBackupDetails to the create volume backup params func (o *CreateVolumeBackupParams) SetCreateVolumeBackupDetails(createVolumeBackupDetails *models.CreateVolumeBackupDetails) { o.CreateVolumeBackupDetails = createVolumeBackupDetails } // WithOpcRetryToken adds the opcRetryToken to the create volume backup params func (o *CreateVolumeBackupParams) WithOpcRetryToken(opcRetryToken *string) *CreateVolumeBackupParams { o.SetOpcRetryToken(opcRetryToken) return o } // SetOpcRetryToken adds the opcRetryToken to the create volume backup params func (o *CreateVolumeBackupParams) SetOpcRetryToken(opcRetryToken *string) { o.OpcRetryToken = opcRetryToken } // WriteToRequest writes these params to a swagger request func (o *CreateVolumeBackupParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.CreateVolumeBackupDetails == nil { o.CreateVolumeBackupDetails = new(models.CreateVolumeBackupDetails) } if err := r.SetBodyParam(o.CreateVolumeBackupDetails); err != nil { return err } if o.OpcRetryToken != nil { // header param opc-retry-token if err := r.SetHeaderParam("opc-retry-token", *o.OpcRetryToken); err != nil { return err } } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
shootsoft/practice
LeetCode/python/001-030/028-implement-strstr/strstr.py
<reponame>shootsoft/practice class Solution: # @param haystack, a string # @param needle, a string # @return an integer def strStr(self, haystack, needle): if needle == haystack or needle== '' : return 0 elif needle== None or haystack == None or haystack=='': return -1 h = len(haystack) n = len(needle) if n >= h : return -1 for i in range(h-n+1): find = True for j in range(n): if haystack[i + j]!=needle[j]: find = False break if find: return i return -1 s = Solution() print s.strStr("mississippi", "pi")
ogryzko/laplace
source/laplace/platform/dummy.h
<filename>source/laplace/platform/dummy.h<gh_stars>0 /* laplace/platform/dummy.h * * Copyright (c) 2021 <NAME> * * This file is part of the Laplace project. * * Laplace 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 MIT License for more details. */ #ifndef laplace_platform_dummy_h #define laplace_platform_dummy_h #include "../core/slib.h" #include "events.h" #include "opengl.h" #include "thread.h" #include <cstdint> #include <string> namespace laplace::platform::dummy { inline void set_background_mode(bool is_background_mode) { } inline void set_realtime_mode(bool is_realtime_mode) { } inline void set_thread_priority(int priority) { } inline void set_thread_priority(std::thread &th, int priority) { } inline auto gl_init() -> bool { return false; } inline void gl_cleanup() { } inline auto gl_get_proc_address(const char *s) -> gl::ptr_function { return nullptr; } class input { public: input() { } ~input() { } void on_key_down(event_key_down) { } void on_wheel(event_wheel) { } void use_system_cursor(bool) { } void set_cursor_enabled(bool) { } void set_mouse_resolution(sl::whole, sl::whole) { } void set_clamp(bool, bool) { } auto is_capslock() const -> bool { return false; } auto is_numlock() const -> bool { return false; } auto is_scrolllock() const -> bool { return false; } auto is_alt() const -> bool { return false; } auto is_shift() const -> bool { return false; } auto is_control() const -> bool { return false; } auto is_key_down(sl::index) const -> bool { return false; } auto is_key_up(sl::index) const -> bool { return true; } auto is_key_changed(sl::index) const -> bool { return false; } auto is_key_pressed(sl::index) const -> bool { return false; } auto is_key_unpressed(sl::index) const -> bool { return false; } auto get_mouse_resolution_x() const -> sl::whole { return 0u; } auto get_mouse_resolution_y() const -> sl::whole { return 0u; } auto get_mouse_x() const -> sl::index { return 0; } auto get_mouse_y() const -> sl::index { return 0; } auto get_mouse_delta_x() const -> sl::index { return 0; } auto get_mouse_delta_y() const -> sl::index { return 0; } auto get_cursor_x() const -> sl::index { return 0; } auto get_cursor_y() const -> sl::index { return 0; } auto get_wheel_delta() const -> sl::index { return 0; } auto get_text() const -> std::u8string_view { static constexpr auto nil = u8""; return nil; } void refresh() { } }; class window { public: using native_handle = std::nullptr_t; static constexpr sl::whole default_frame_width = 0; static constexpr sl::whole default_frame_height = 0; static constexpr sl::whole default_frame_rate = 0; window() { } window(native_handle) { } void on_init(event_init) { } void on_cleanup(event_cleanup) { } void on_frame(event_frame) { } void on_size(event_size) { } void on_focus(event_focus) { } void on_drop_file(event_drop_file) { } void set_name(std::string_view) { } void set_name(std::wstring_view) { } void set_visible(bool) { } void set_fullscreen(bool) { } void set_centered() { } void set_position(sl::index, sl::index) { } void set_size(sl::whole, sl::whole) { } void set_fullscreen_windowed() { } void set_fullscreen_mode(sl::whole, sl::whole, sl::whole) { } void set_input(std::shared_ptr<input>) { } void set_parent(native_handle) { } void reset_parent() { } auto message_loop() -> int { return 0; } void quit(int = 0) { } auto get_screen_width() const -> sl::whole { return 0u; } auto get_screen_height() const -> sl::whole { return 0u; } auto get_fullscreen_width() const -> sl::whole { return 0u; } auto get_fullscreen_height() const -> sl::whole { return 0u; } auto get_x() const -> sl::index { return 0u; } auto get_y() const -> sl::index { return 0u; } auto get_width() const -> sl::whole { return 0u; } auto get_height() const -> sl::whole { return 0u; } auto get_frame_width() const -> sl::whole { return 0u; } auto get_frame_height() const -> sl::whole { return 0u; } auto is_visible() const -> bool { return false; } auto is_fullscreen() const -> bool { return false; } auto is_fullscreen_windowed() const -> bool { return false; } auto has_focus() const -> bool { return false; } auto has_cursor() const -> bool { return false; } auto get_native_handle() const -> native_handle { return nullptr; } }; class glcontext { public: glcontext(std::shared_ptr<window>) { } void swap_buffers() { } static void set_forward_compatible(bool) { } }; class audio { }; class clipboard { }; } #endif
falbech/wegnology-cli
lib/get-export-params.js
<gh_stars>1-10 const { dataTables } = require('./constants'); const paginateRequest = require('./paginate-request'); const stringify = require('csv-stringify'); const { defer } = require('omnibelt'); const dataTablesParams = { apiType: dataTables.apiType, commandType: dataTables.commandType, localStatusParams: dataTables.localStatusParams, remoteStatusParams: dataTables.remoteStatusParams, getData: async (dataTable, api) => { let data; const deferred = defer(); const rows = await paginateRequest(api.dataTableRows.get, { applicationId: dataTable.applicationId, dataTableId: dataTable.id }, true); stringify(rows, { header: true }, (err, output) => { data = output; deferred.resolve(); if (err) { throw err; } }); await deferred.promise; return data; } }; module.exports = { dataTables: dataTablesParams };
matortheeternal/mod-picker
mod-picker/db/migrate/20161116190426_add_url_to_mod_list_custom_mods.rb
class AddUrlToModListCustomMods < ActiveRecord::Migration def change add_column :mod_list_custom_mods, :url, :string, after: :name end end
JoshZero87/site
contacts/admin_views.py
<filename>contacts/admin_views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse_lazy from django.utils import timezone from django.views.generic import FormView from .forms import PhoneOptOutUploadForm from .models import add_phone_opt_out, OptOutType import csv import logging logger = logging.getLogger(__name__) class PhoneOptOutUploadView(PermissionRequiredMixin, FormView): """ Upload CSV of Phone Opt Outs for Calling and save any new ones to db Always assumes Opt Out Type = Calling. Do not upload other types. TODO: need to set request.current_app to self.admin_site.name? https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#adding-views-to-admin-sites """ ''' ''' form_class = PhoneOptOutUploadForm login_url = reverse_lazy( 'admin:contacts_phoneoptout_changelist' ) permission_required = 'contacts.change_phoneoptout' success_url = reverse_lazy( 'admin:contacts_phoneoptout_changelist' ) template_name = 'admin/phone_opt_out_upload.html' def form_valid(self, form): """Handle file upload""" csv_file = self.request.FILES['csv_file'] reader = csv.DictReader(csv_file, fieldnames=['phone']) """Set source code""" user = self.request.user timestamp = timezone.now().strftime("%Y%m%d%H%M%S") source = 'Admin Upload by %s [%s] %s' % ( user.email, str(user.id), timestamp, ) """Go through each row and add opt out for phone""" add_count = 0 invalid_count = 0 total_count = 0 for row in reader: phone = row['phone'] (phone_opt_out, created) = add_phone_opt_out( phone, OptOutType.calling, source, ) """Update counts""" total_count += 1 if created: add_count += 1 if phone_opt_out is None: invalid_count += 1 messages.success( self.request, """ Upload successful. Added %s new opt outs out of %s total records. %s records were considered invalid. """ % ( add_count, total_count, invalid_count, ) ) return HttpResponseRedirect(self.get_success_url())
Andreas237/AndroidPolicyAutomation
ExtractedJars/PACT_com.pactforcure.app/javafiles/com/crashlytics/android/core/MiddleOutStrategy.java
<reponame>Andreas237/AndroidPolicyAutomation // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.crashlytics.android.core; // Referenced classes of package com.crashlytics.android.core: // StackTraceTrimmingStrategy class MiddleOutStrategy implements StackTraceTrimmingStrategy { public MiddleOutStrategy(int i) { // 0 0:aload_0 // 1 1:invokespecial #13 <Method void Object()> trimmedSize = i; // 2 4:aload_0 // 3 5:iload_1 // 4 6:putfield #15 <Field int trimmedSize> // 5 9:return } public StackTraceElement[] getTrimmedStackTrace(StackTraceElement astacktraceelement[]) { if(astacktraceelement.length <= trimmedSize) //* 0 0:aload_1 //* 1 1:arraylength //* 2 2:aload_0 //* 3 3:getfield #15 <Field int trimmedSize> //* 4 6:icmpgt 11 { return astacktraceelement; // 5 9:aload_1 // 6 10:areturn } else { int i = trimmedSize / 2; // 7 11:aload_0 // 8 12:getfield #15 <Field int trimmedSize> // 9 15:iconst_2 // 10 16:idiv // 11 17:istore_2 int j = trimmedSize - i; // 12 18:aload_0 // 13 19:getfield #15 <Field int trimmedSize> // 14 22:iload_2 // 15 23:isub // 16 24:istore_3 StackTraceElement astacktraceelement1[] = new StackTraceElement[trimmedSize]; // 17 25:aload_0 // 18 26:getfield #15 <Field int trimmedSize> // 19 29:anewarray StackTraceElement[] // 20 32:astore 4 System.arraycopy(((Object) (astacktraceelement)), 0, ((Object) (astacktraceelement1)), 0, j); // 21 34:aload_1 // 22 35:iconst_0 // 23 36:aload 4 // 24 38:iconst_0 // 25 39:iload_3 // 26 40:invokestatic #26 <Method void System.arraycopy(Object, int, Object, int, int)> System.arraycopy(((Object) (astacktraceelement)), astacktraceelement.length - i, ((Object) (astacktraceelement1)), j, i); // 27 43:aload_1 // 28 44:aload_1 // 29 45:arraylength // 30 46:iload_2 // 31 47:isub // 32 48:aload 4 // 33 50:iload_3 // 34 51:iload_2 // 35 52:invokestatic #26 <Method void System.arraycopy(Object, int, Object, int, int)> return astacktraceelement1; // 36 55:aload 4 // 37 57:areturn } } private final int trimmedSize; }
zoek1/unlock
unlock-app/src/services/currencyLookupService.js
<filename>unlock-app/src/services/currencyLookupService.js<gh_stars>0 import axios from 'axios' const URL = require('url') /** * Provides currency lookup abstraction for down stream consumers. */ export default class CurrencyLookupService { constructor(uri) { /* Added as our lint rules are currently configured for node 11, the functionality utilized below is indeed deprecated */ /* eslint-disable node/no-deprecated-api */ this.host = URL.parse(uri).host } /** * Based upon the currently configured host fot the object, will provide * information regarding the provided base and currency. * * @param {*} base * @param {*} currency */ async lookupPrice(base, currency) { if (RegExp('api.coinbase.com', 'ig').test(this.host)) { return this._handleCoinbaseFetch(base, currency) } else { throw 'Unknown Currency Conversion Provider' } } /** * Returns the appropriate API request to be utilized when requesting * currency information from Coinbase's API * * @param {String} base * @param {String} currency * * @returns {String} */ _constructCoinbaseLookupURI(base, currency) { return `https://api.coinbase.com/v2/prices/${base.toUpperCase()}-${currency.toUpperCase()}/buy` } /** * Requests currency information from Coinbase and package consistently * for consumers. * * @param {String} base * @param {String} currency */ async _handleCoinbaseFetch(base, currency) { let result = await axios.get( this._constructCoinbaseLookupURI(base, currency) ) return Promise.resolve({ currency: result.data.data.currency, amount: result.data.data.amount, }) } }
liuzhenyulive/iBlogs
blog-admin/src/main/java/site/iblogs/admin/controller/CommentController.java
package site.iblogs.admin.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import site.iblogs.admin.dto.request.CommentDeleteParam; import site.iblogs.admin.dto.request.CommentStatusUpdateParam; import site.iblogs.admin.service.CommentService; import site.iblogs.common.api.ApiResponse; import site.iblogs.common.dto.request.CommentPageParam; /** * @author: <EMAIL> * @date: 9/22/2020 22:35 */ @Api(tags = "CommentController", value = "评论 api") @Controller @RequestMapping("/comment") public class CommentController { @Autowired private CommentService commentService; @ApiOperation("获取评论") @RequestMapping(value = "/comments", method = RequestMethod.POST) @ResponseBody public ApiResponse commentList(@RequestBody CommentPageParam param) { return ApiResponse.success(commentService.commentList(param)); } @ApiOperation("删除评论") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public ApiResponse deleteComment(@RequestBody CommentDeleteParam param) { if(commentService.deleteComment(param.getId())){ return ApiResponse.success(param.getId()); }else { return ApiResponse.failed(); } } @ApiOperation("修改评论状态") @RequestMapping(value = "/status", method = RequestMethod.POST) @ResponseBody public ApiResponse updateStatus(@RequestBody CommentStatusUpdateParam param) { return ApiResponse.success(commentService.updateStatus(param)); } }
skaes/fpm-fry
spec/channel_spec.rb
require 'fpm/fry/channel' describe FPM::Fry::Channel do subject{ chan = FPM::Fry::Channel.new chan.subscribe subscriber chan } let(:subscriber){ double(:subscriber) } context 'with exceptions' do it 'allows logging exceptions' do ex = Exception.new("foo") expect(subscriber).to receive(:<<).with(level: :error, message: "foo", exception: ex, backtrace: nil) subject.error(ex) end it "merges #data" do ex = Exception.new("foo") def ex.data {blub: "bla"} end expect(subscriber).to receive(:<<).with(level: :error, message: "foo", exception: ex, backtrace: nil, blub: "bla") subject.error(ex) end it "doesn't allow overwriting" do ex = Exception.new("foo") def ex.data {blub: "bla", message: "bar", level: :warning} end expect(subscriber).to receive(:<<).with(level: :error, message: "foo", exception: ex, backtrace: nil, blub: "bla") subject.error(ex) end end context 'with a Hash' do it 'dups the hash' do expect(subscriber).to receive(:<<).with(level: :info,blub: "blub"){|data| data[:foo] = 'bar' } hsh = {blub: 'blub'} subject.info(hsh) expect(hsh).not_to include(:foo) end end context '#hint' do it 'uses the hint level' do expect(subscriber).to receive(:<<).with(level: :hint, message: "bar") subject.hint("bar") end it 'can be disabled with #hint=' do subject.hint = false subject.hint("bar") end end end
Ashwin-Paudel/Tries
OSDev/Try-17/KripayaOS/Kernel/Drivers/Display/Display.h
<reponame>Ashwin-Paudel/Tries // // Display.hpp // AutoCompletions // // Created by <NAME> on 2021-06-08. // #ifndef Display_h #define Display_h #include <Kernel/Drivers/Port.h> #include <Kernel/Drivers/Display/Colors.h> #include <KriLib/String.h> #define VIDEO_ADDRESS 0xb8000 #define MAX_ROWS 25 #define MAX_COLS 80 #define VGA_CTRL_REGISTER 0x3d4 #define VGA_DATA_REGISTER 0x3d5 #define VGA_OFFSET_LOW 0x0f #define VGA_OFFSET_HIGH 0x0e // Set the current cursor position void set_cursor(int offset); // Get the current cursor position int get_cursor(); // Print a character in the screen void set_character_at_video_memory(char character, int offset); void set_character_at_video_memory(char character, int offset, unsigned char Color); int get_row_from_offset(int offset); int getOffset(int col, int row); int moveOffsetToNewLine(int offset); void memoryCopy(char *source, char *dest, int nbytes); int scroll_ln(int offset); void clearScreen(); // Print a string into the screen void print(char *string); void print(char *string, unsigned char Color); void print(KriLib::String string, unsigned char Color); void newLine(); void deleteLine(); void backspace(); #endif /* Display_h */
calderon/blog
src/assets/styles/base.js
<filename>src/assets/styles/base.js import { createGlobalStyle } from "styled-components" import { srOnly, srOnlyFocusable, skipLink } from "../../assets/styles/helpers" const BaseStyle = createGlobalStyle` .copyright { display: inline-block; } .unscrolled { overflow: hidden; } .srOnly { ${srOnly}; } .srOnlyFocusable { ${srOnly}; } .skipLink { ${skipLink}; } ` export default BaseStyle
endritarrahmani-prosperoware/cxjs
packages/cx/src/widgets/icons/search.js
import {VDOM} from '../../ui/Widget'; import {registerIcon} from './registry'; export default registerIcon('search', props => { return <svg {...props} viewBox="0 0 32 32"> <path fill="currentColor" d="M25.595 22.036l-5.26-5.075c.75-1.18 1.206-2.56 1.206-4.05 0-4.32-3.63-7.82-8.103-7.82-4.477 0-8.107 3.503-8.107 7.82 0 4.32 3.63 7.825 8.106 7.825 1.544 0 2.972-.44 4.198-1.162l5.26 5.074c.37.356.98.354 1.35 0l1.352-1.304c.37-.357.37-.947 0-1.304zm-12.16-3.91c-2.985 0-5.405-2.336-5.405-5.216 0-2.88 2.42-5.214 5.405-5.214 2.984 0 5.404 2.335 5.404 5.214 0 2.88-2.42 5.215-5.407 5.215z" /> </svg> }, true);
DAIAD/home-web
home/src/main/java/eu/daiad/home/config/_Marker.java
<reponame>DAIAD/home-web package eu.daiad.home.config; public class _Marker { }
YANG-DB/yang-db
fuse-asg/src/main/java/com/yangdb/fuse/asg/translator/cypher/strategies/MatchCypherTranslatorStrategy.java
package com.yangdb.fuse.asg.translator.cypher.strategies; /*- * #%L * fuse-asg * %% * Copyright (C) 2016 - 2019 The YangDb Graph Database Project * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.yangdb.fuse.asg.translator.cypher.strategies.expressions.ExpressionStrategies; import com.yangdb.fuse.asg.translator.cypher.strategies.expressions.ReturnClauseNodeCypherTranslator; import com.yangdb.fuse.asg.translator.cypher.strategies.expressions.WhereClauseNodeCypherTranslator; import com.yangdb.fuse.model.asgQuery.AsgQuery; import org.opencypher.v9_0.ast.*; import org.opencypher.v9_0.expressions.PatternElement; import org.opencypher.v9_0.expressions.PatternPart; import scala.collection.Seq; import java.util.Collection; import java.util.List; import java.util.Optional; import static scala.collection.JavaConverters.asJavaCollectionConverter; public class MatchCypherTranslatorStrategy implements CypherTranslatorStrategy { public MatchCypherTranslatorStrategy(Iterable<CypherElementTranslatorStrategy> strategies, WhereClauseNodeCypherTranslator whereClause, ReturnClauseNodeCypherTranslator returnClause) { this.strategies = strategies; this.whereClause = whereClause; this.returnClause = returnClause; } @Override public void apply(AsgQuery query, CypherStrategyContext context) { final Statement statement = context.getStatement(); if (!(statement instanceof Query)) return; Query cypherQuery = (Query) statement; final QueryPart part = cypherQuery.part(); if (part instanceof SingleQuery) { manageMatchStatement(query, context, (SingleQuery) part); manageReturnStatement(query, context, (SingleQuery) part); } } private void manageReturnStatement(AsgQuery query, CypherStrategyContext context, SingleQuery part) { final Seq<Clause> clauses = part.clauses(); final Optional<Clause> clause = asJavaCollectionConverter(clauses).asJavaCollection() .stream().filter(c -> c.getClass().isAssignableFrom(Return.class)).findAny(); if (!clause.isPresent()) return; Return aReturn = (Return) clause.get(); // handle return aliases and functions (distinct / groupBy ) returnClause.apply(aReturn, query, context); } private void manageMatchStatement(AsgQuery query, CypherStrategyContext context, SingleQuery part) { final Seq<Clause> clauses = part.clauses(); final Optional<Clause> matchClause = asJavaCollectionConverter(clauses).asJavaCollection() .stream().filter(c -> c.getClass().isAssignableFrom(Match.class)).findAny(); if (!matchClause.isPresent()) return; //manage patterns final Match match = (Match) matchClause.get(); if (!match.where().isEmpty()) { context.where(match.where().get()); } final Collection<PatternPart> patternParts = asJavaCollectionConverter(match.pattern().patternParts()).asJavaCollection(); //for multi patterns match clause patternParts.forEach(p -> applyPattern(p.element(), context, query)); //manage where clause if (!match.where().isEmpty()) { Where where = match.where().get(); whereClause.apply(where, query, context); } } protected void applyPattern(PatternElement patternPart, CypherStrategyContext context, AsgQuery query) { strategies.forEach(s -> s.apply(patternPart, query, context)); } private Iterable<CypherElementTranslatorStrategy> strategies; private WhereClauseNodeCypherTranslator whereClause; private ReturnClauseNodeCypherTranslator returnClause; }
timgreen/cook
test/cook/util/GlobScannerTest.scala
<gh_stars>1-10 package cook.util import org.scalatest.BeforeAndAfter import org.scalatest.FlatSpec import org.scalatest.matchers.ShouldMatchers import scala.reflect.io.{ Path => SPath, Directory, File } class GlobScannerTest extends FlatSpec with ShouldMatchers with BeforeAndAfter { val testRoot = SPath("testdata") def comparePathSet(results: Seq[SPath], excepts: Seq[SPath]) { results should have length (excepts.length) for (p <- excepts) { results should contain (p) } } import GlobScanner._ "Pattern" should "normalize input pattern" in { val p = GlobScanner.Pattern("a**b") p.items should be (List(CharItem('a'), **, CharItem('b'))) } it should "normalize '*******/??' as '**/??'" in { val p = GlobScanner.Pattern("*******/??") p.items should be (List(**, CharItem('/'), ?, ?)) } it should "normalize asfd/sfa/**" in { val p = GlobScanner.Pattern("asfd/sfa/**") p.items should be (List( CharItem('a'), CharItem('s'), CharItem('f'), CharItem('d'), CharItem('/'), CharItem('s'), CharItem('f'), CharItem('a'), CharItem('/'), ** )) } it should "** should be match all" in { val p = GlobScanner.Pattern("**") p.hasMatchAll should be (true) } it should "asfd/sfa/** should be match all" in { val p = GlobScanner.Pattern("asfd/sfa/**").copy(indexes = Set(9)) p.hasMatchAll should be (true) } it should "asfd/sfa/**xx should not be match all" in { val p = GlobScanner.Pattern("asfd/sfa/**xx") p.hasMatchAll should be (false) } it should "? should match a" in { val p = GlobScanner.Pattern("?") p.matches("a").hasMatched should be (true) } it should "? should not match ab" in { val p = GlobScanner.Pattern("?") p.matches("ab").hasMatched should be (false) } it should "?? should match ab" in { val p = GlobScanner.Pattern("??") p.matches("ab").hasMatched should be (true) } it should "?? should not match a" in { val p = GlobScanner.Pattern("??") p.matches("a").hasMatched should be (false) } it should "a*a*a?? should match asdfasdfasd" in { val p = GlobScanner.Pattern("a*a*a??") p.matches("asdfasdfasd").hasMatched should be (true) } it should "a*a*a?? should not match asdfasdfasdf" in { val p = GlobScanner.Pattern("a*a*a??") p.matches("asdfasdfasdf").hasMatched should be (false) } it should "*******a*a*a??,0 should extend to 0,1" in { val p = GlobScanner.Pattern("*******a*a*a??") p.extendedIndexes should be (Set(0, 1)) } it should "???a*a*a??,0 should extend to 0" in { val p = GlobScanner.Pattern("???a*a*a??") p.extendedIndexes should be (Set(0)) } // 0 1 2 3 4 5 6 7 // ** a * a * a ? ? it should "*******a*a*a?? match a" in { val p = GlobScanner.Pattern("*******a*a*a??") p.matches("a") should be (Pattern(p.items, Set(0, 1, 2, 3))) } it should "*******a*a*a?? match aa" in { val p = GlobScanner.Pattern("*******a*a*a??") p.matches("aa") should be (Pattern(p.items, Set(0, 1, 2, 3, 4, 5))) } it should "*******a*a*a?? should match aaaxx" in { val p = GlobScanner.Pattern("*******a*a*a??") p.matches("aaaxx").hasMatched should be (true) } "Glob Scanner" should "throw java.lang.IllegalArgumentException when dir not exist" in { val root = (testRoot / "not_exist").toDirectory evaluating { GlobScanner(root) } should produce [IllegalArgumentException] } it should "throw java.lang.IllegalArgumentException when dir is null" in { evaluating { GlobScanner(null) } should produce [IllegalArgumentException] } it should "return all items in the dir by default" in { val root = (testRoot / "test_scan_all").toDirectory val result = GlobScanner(root) val except = List( root / "a", root / "b", root / "c", root / "d", root / "d" / "e", root / "d" / "e" / "f", root / "d" / "e" / "f" / "g", root / "d" / "e" / "f" / "h", root / "d" / "e" / "f" / "j", root / "d" / "e" / "f" / "j" / "k", root / "d" / "e" / "f" / "j" / "k" / "1", root / "d" / "e" / "f" / "j" / "k" / "2" ) comparePathSet(result, except) } it should "return all items in the dir for '**'" in { val root = (testRoot / "test_scan_all").toDirectory val result = GlobScanner(root, List("**")) val except = List( root / "a", root / "b", root / "c", root / "d", root / "d" / "e", root / "d" / "e" / "f", root / "d" / "e" / "f" / "g", root / "d" / "e" / "f" / "h", root / "d" / "e" / "f" / "j", root / "d" / "e" / "f" / "j" / "k", root / "d" / "e" / "f" / "j" / "k" / "1", root / "d" / "e" / "f" / "j" / "k" / "2" ) comparePathSet(result, except) } it should "return all files in the dir when fileOnly = true" in { val root = (testRoot / "test_scan_all").toDirectory val result = GlobScanner(root, fileOnly = true) val except = List( root / "a", root / "b", root / "c", root / "d" / "e" / "f" / "g", root / "d" / "e" / "f" / "h", root / "d" / "e" / "f" / "j" / "k" / "1", root / "d" / "e" / "f" / "j" / "k" / "2" ) comparePathSet(result, except) } it should "'d/e/f' should match 'd/e/f'" in { val root = (testRoot / "test_scan_all").toDirectory val result = GlobScanner(root, Seq("d/e/f")) val except = List( root / "d" / "e" / "f" ) comparePathSet(result, except) } it should "'d/?/f' should match 'd/e/f'" in { val root = (testRoot / "test_scan_all").toDirectory val result = GlobScanner(root, Seq("d/?/f")) val except = List( root / "d" / "e" / "f" ) comparePathSet(result, except) } it should "'d/?/f/?' should match 3 items" in { val root = (testRoot / "test_scan_all").toDirectory val result = GlobScanner(root, Seq("d/?/f/?")) val except = List( root / "d" / "e" / "f" / "g", root / "d" / "e" / "f" / "h", root / "d" / "e" / "f" / "j" ) comparePathSet(result, except) } it should "'d/?/f/**' should match 6 items" in { val root = (testRoot / "test_scan_all").toDirectory val result = GlobScanner(root, Seq("d/?/f/**")) val except = List( root / "d" / "e" / "f" / "g", root / "d" / "e" / "f" / "h", root / "d" / "e" / "f" / "j", root / "d" / "e" / "f" / "j" / "k", root / "d" / "e" / "f" / "j" / "k" / "1", root / "d" / "e" / "f" / "j" / "k" / "2" ) comparePathSet(result, except) } it should "'a/*/*' should match 'a/b/c'" in { val root = (testRoot / "test_a").toDirectory val result = GlobScanner(root, Seq("a/*/*")) val except = List( root / "a" / "b" / "c" ) comparePathSet(result, except) } it should "'a/**/d' should match 'a/b/c/d'" in { val root = (testRoot / "test_b").toDirectory val result = GlobScanner(root, Seq("a/**/d")) val except = List( root / "a" / "b" / "c" / "d" ) comparePathSet(result, except) } it should "'a/*/d' should not match 'a/b/c/d'" in { val root = (testRoot / "test_b").toDirectory val result = GlobScanner(root, Seq("a/*/d")) val except = Nil comparePathSet(result, except) } it should "'?' should match 'a'" in { val root = (testRoot / "test_b").toDirectory val result = GlobScanner(root, Seq("?")) val except = List( root / "a" ) comparePathSet(result, except) } it should "'?/?' should match 'a/b'" in { val root = (testRoot / "test_b").toDirectory val result = GlobScanner(root, Seq("?/?")) val except = List( root / "a" / "b" ) comparePathSet(result, except) } it should "'**/?' should match all items under 'a'" in { val root = (testRoot / "test_b").toDirectory val result = GlobScanner(root, Seq("**/?")) val except = List( root / "a" / "b", root / "a" / "b" / "c", root / "a" / "b" / "c" / "d" ) comparePathSet(result, except) } it should "'**/d' should match 'a/b/c/d'" in { val root = (testRoot / "test_b").toDirectory val result = GlobScanner(root, Seq("**/d")) val except = List( root / "a" / "b" / "c" / "d" ) comparePathSet(result, except) } it should "'**/??' should not match 'a/b/c/d'" in { val root = (testRoot / "test_b").toDirectory val result = GlobScanner(root, Seq("**/??")) val except = Nil comparePathSet(result, except) } it should "'dir1/as*' should match 4 items" in { val root = (testRoot / "test_c").toDirectory val result = GlobScanner(root, Seq("dir1/as*")) val except = List( root / "dir1" / "asdf1", root / "dir1" / "asdf2", root / "dir1" / "asdfasdf3", root / "dir1" / "asdfasdfasdfasdfasdf4" ) comparePathSet(result, except) } it should "'*1/as*' should match 4 items" in { val root = (testRoot / "test_c").toDirectory val result = GlobScanner(root, Seq("*1/as*")) val except = List( root / "dir1" / "asdf1", root / "dir1" / "asdf2", root / "dir1" / "asdfasdf3", root / "dir1" / "asdfasdfasdfasdfasdf4" ) comparePathSet(result, except) } it should "'**/as*' should match 8 items" in { val root = (testRoot / "test_c").toDirectory val result = GlobScanner(root, Seq("**/as*")) val except = List( root / "dir1" / "asdf1", root / "dir1" / "asdf2", root / "dir1" / "asdfasdf3", root / "dir1" / "asdfasdfasdfasdfasdf4", root / "dir02" / "asdf1", root / "dir02" / "asdf2", root / "dir02" / "asdfasdf3", root / "dir02" / "asdfasdfasdfasdfasdf4" ) comparePathSet(result, except) } it should "'**/as*' x 2 should match 8 items" in { val root = (testRoot / "test_c").toDirectory val result = GlobScanner(root, Seq("**/as*", "**/as*")) val except = List( root / "dir1" / "asdf1", root / "dir1" / "asdf2", root / "dir1" / "asdfasdf3", root / "dir1" / "asdfasdfasdfasdfasdf4", root / "dir02" / "asdf1", root / "dir02" / "asdf2", root / "dir02" / "asdfasdf3", root / "dir02" / "asdfasdfasdfasdfasdf4" ) comparePathSet(result, except) } it should "work with excludes" in { val root = (testRoot / "test_c").toDirectory val result = GlobScanner(root, Seq("**/as*", "**/as*"), Seq("?????/**")) val except = List( root / "dir1" / "asdf1", root / "dir1" / "asdf2", root / "dir1" / "asdfasdf3", root / "dir1" / "asdfasdfasdfasdfasdf4" ) comparePathSet(result, except) } it should "work with excludes all" in { val root = (testRoot / "test_c").toDirectory val result = GlobScanner(root, Seq("**/as*", "**/as*"), Seq("**")) val except = Nil comparePathSet(result, except) } }
D3ATHBRINGER13/Protocol
bedrock/bedrock-codec/src/main/java/org/cloudburstmc/protocol/bedrock/packet/InteractPacket.java
package org.cloudburstmc.protocol.bedrock.packet; import com.nukkitx.math.vector.Vector3f; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.cloudburstmc.protocol.common.PacketSignal; @Data @EqualsAndHashCode(doNotUseGetters = true) @ToString(doNotUseGetters = true) public class InteractPacket implements BedrockPacket { private Action action; private long runtimeEntityId; private Vector3f mousePosition; @Override public final PacketSignal handle(BedrockPacketHandler handler) { return handler.handle(this); } public BedrockPacketType getPacketType() { return BedrockPacketType.INTERACT; } public enum Action { NONE, INTERACT, DAMAGE, LEAVE_VEHICLE, MOUSEOVER, NPC_OPEN, OPEN_INVENTORY } }
geometryzen/Algebrite
dist/sources/arctan.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arctan = exports.Eval_arctan = void 0; const defs_1 = require("../runtime/defs"); const find_1 = require("../runtime/find"); const stack_1 = require("../runtime/stack"); const misc_1 = require("../sources/misc"); const bignum_1 = require("./bignum"); const denominator_1 = require("./denominator"); const eval_1 = require("./eval"); const is_1 = require("./is"); const list_1 = require("./list"); const multiply_1 = require("./multiply"); const numerator_1 = require("./numerator"); /* arctan ===================================================================== Tags ---- scripting, JS, internal, treenode, general concept Parameters ---------- x General description ------------------- Returns the inverse tangent of x. */ function Eval_arctan(x) { stack_1.push(arctan(eval_1.Eval(defs_1.cadr(x)))); } exports.Eval_arctan = Eval_arctan; function arctan(x) { if (defs_1.car(x) === defs_1.symbol(defs_1.TAN)) { return defs_1.cadr(x); } if (defs_1.isdouble(x)) { return bignum_1.double(Math.atan(x.d)); } if (is_1.isZeroAtomOrTensor(x)) { return defs_1.Constants.zero; } if (is_1.isnegative(x)) { return multiply_1.negate(arctan(multiply_1.negate(x))); } // arctan(sin(a) / cos(a)) ? if (find_1.Find(x, defs_1.symbol(defs_1.SIN)) && find_1.Find(x, defs_1.symbol(defs_1.COS))) { const p2 = numerator_1.numerator(x); const p3 = denominator_1.denominator(x); if (defs_1.car(p2) === defs_1.symbol(defs_1.SIN) && defs_1.car(p3) === defs_1.symbol(defs_1.COS) && misc_1.equal(defs_1.cadr(p2), defs_1.cadr(p3))) { return defs_1.cadr(p2); } } // arctan(1/sqrt(3)) -> pi/6 // second if catches the other way of saying it, sqrt(3)/3 if ((defs_1.ispower(x) && is_1.equaln(defs_1.cadr(x), 3) && is_1.equalq(defs_1.caddr(x), -1, 2)) || (defs_1.ismultiply(x) && is_1.equalq(defs_1.car(defs_1.cdr(x)), 1, 3) && defs_1.car(defs_1.car(defs_1.cdr(defs_1.cdr(x)))) === defs_1.symbol(defs_1.POWER) && is_1.equaln(defs_1.car(defs_1.cdr(defs_1.car(defs_1.cdr(defs_1.cdr(x))))), 3) && is_1.equalq(defs_1.car(defs_1.cdr(defs_1.cdr(defs_1.car(defs_1.cdr(defs_1.cdr(x)))))), 1, 2))) { return multiply_1.multiply(bignum_1.rational(1, 6), defs_1.Constants.Pi()); } // arctan(1) -> pi/4 if (is_1.equaln(x, 1)) { return multiply_1.multiply(bignum_1.rational(1, 4), defs_1.Constants.Pi()); } // arctan(sqrt(3)) -> pi/3 if (defs_1.ispower(x) && is_1.equaln(defs_1.cadr(x), 3) && is_1.equalq(defs_1.caddr(x), 1, 2)) { return multiply_1.multiply(bignum_1.rational(1, 3), defs_1.Constants.Pi()); } return list_1.makeList(defs_1.symbol(defs_1.ARCTAN), x); } exports.arctan = arctan;
al1k0s/dashsync-iOS
DashSync/shared/Models/Entities/DSProviderUpdateServiceTransactionEntity+CoreDataClass.h
// // DSProviderUpdateServiceTransactionEntity+CoreDataClass.h // DashSync // // Created by <NAME> on 2/21/19. // // #import "DSSpecialTransactionEntity+CoreDataClass.h" #import <Foundation/Foundation.h> @class DSLocalMasternodeEntity; NS_ASSUME_NONNULL_BEGIN @interface DSProviderUpdateServiceTransactionEntity : DSSpecialTransactionEntity @end NS_ASSUME_NONNULL_END #import "DSProviderUpdateServiceTransactionEntity+CoreDataProperties.h"
RajBhaduri/development
oscm-portal/javasrc/org/oscm/ui/model/PricedEventRow.java
/******************************************************************************* * * Copyright FUJITSU LIMITED 2016 * * Author: pock * * Creation Date: 16.07.2010 * *******************************************************************************/ package org.oscm.ui.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.oscm.ui.common.SteppedPriceComparator; import org.oscm.ui.common.VOFinder; import org.oscm.internal.vo.VOEventDefinition; import org.oscm.internal.vo.VOPricedEvent; import org.oscm.internal.vo.VOServiceDetails; import org.oscm.internal.vo.VOSteppedPrice; /** * PricedEvent table row which either contains only a priced event or a priced * event with a stepped priced * */ public class PricedEventRow implements Serializable { private static final long serialVersionUID = 1L; private VOPricedEvent pricedEvent; private VOSteppedPrice steppedPrice; /** * Create a list with PricedEventRow objects for the given service. * * @param service * the service for which the list is created * * @returns the created list. */ public static List<PricedEventRow> createPricedEventRowList( VOServiceDetails service) { List<PricedEventRow> result = new ArrayList<PricedEventRow>(); for (VOEventDefinition event : service.getTechnicalService() .getEventDefinitions()) { VOPricedEvent pricedEvent = null; if (service.getPriceModel() != null) { pricedEvent = VOFinder.findPricedEvent(service.getPriceModel() .getConsideredEvents(), event); } if (pricedEvent == null) { pricedEvent = new VOPricedEvent(event); } PricedEventRow row; if (pricedEvent.getSteppedPrices().isEmpty()) { row = new PricedEventRow(); row.setPricedEvent(pricedEvent); result.add(row); } else { Collections.sort(pricedEvent.getSteppedPrices(), new SteppedPriceComparator()); for (VOSteppedPrice sp : pricedEvent.getSteppedPrices()) { row = new PricedEventRow(); row.setPricedEvent(pricedEvent); row.setSteppedPrice(sp); result.add(row); } } } return result; } public VOPricedEvent getPricedEvent() { return pricedEvent; } public void setPricedEvent(VOPricedEvent pricedEvent) { this.pricedEvent = pricedEvent; } public BigDecimal getEventPrice() { return pricedEvent.getEventPrice(); } public void setEventPrice(BigDecimal eventPrice) { pricedEvent.setEventPrice(eventPrice); } public String getEventDescription() { if (isEmptyOrFirstSteppedPrice()) { return pricedEvent.getEventDefinition().getEventDescription(); } return null; } public VOSteppedPrice getSteppedPrice() { return steppedPrice; } public void setSteppedPrice(VOSteppedPrice steppedPrice) { this.steppedPrice = steppedPrice; } public Long getLimit() { return steppedPrice.getLimit(); } public void setLimit(Long limit) { steppedPrice.setLimit(limit); } public BigDecimal getPrice() { return steppedPrice.getPrice(); } public void setPrice(BigDecimal price) { steppedPrice.setPrice(price); } public boolean isFirstSteppedPrice() { if (steppedPrice == null) { return false; } return steppedPrice == getPricedEvent().getSteppedPrices().get(0); } public boolean isEmptyOrFirstSteppedPrice() { if (steppedPrice == null) { return true; } return steppedPrice == getPricedEvent().getSteppedPrices().get(0); } public boolean isLastSteppedPrice() { if (steppedPrice == null) { return false; } return steppedPrice == getPricedEvent().getSteppedPrices().get( getPricedEvent().getSteppedPrices().size() - 1); } }