max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
679
<reponame>Grosskopf/openoffice<gh_stars>100-1000 #!/usr/bin/env python # ************************************************************* # # 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. # # ************************************************************* # ------------------------------------------------------------------------------ # Hacky little delta debug tool to figure out the proper includes for a pch file # # Usage: # # pchdelta.py <pch_target> <dir1> [<dir2> <dir3> ...] # # <pch_target> File to perform delta debugging on. The section to test # is delimeted by '//---MARKER---' lines. # <dir1> .. <dirn> Sequence of directories to run dmake in to test if the # modification works # # Examples: # # pchdelta.py inc/pch/precompiled_sfx2.hxx inc source/dialog # # Run pchdelta inside sfx2 first building the pch files and then files in # source/dialog # # ------------------------------------------------------------------------------ import os import os.path import sys # C++ MARKER="//---MARKER---\n" # dmake #MARKER="#---MARKER---\n" # ------------------------------------------------------------------------------ # Sequentially build all argument directories from scratch def testSequenceBuild(dirlist): cwd = os.path.abspath(os.getcwd()) for path in dirlist: os.chdir(path) buildcommand = "dmake -u" buildcommand += " >>" + cwd + "/buildlog.txt 2>&1" buildresult = os.system(buildcommand) os.chdir(cwd) if buildresult != 0: return False return True # ------------------------------------------------------------------------------ # Dump out the delta file with corresponding markers def writePch(pchname, header, footer, acceptedlines, testlines): outputfile = file(pchname, "w") outputfile.write(header) outputfile.write(MARKER) outputfile.write("\n".join(acceptedlines)) if len(testlines) > 0: outputfile.write("\n\n//---Candidate marker---\n") outputfile.write("\n".join(testlines) + "\n") outputfile.write("//---Candidate marker end---\n") outputfile.write(MARKER) outputfile.write(footer) outputfile.close() # ------------------------------------------------------------------------------ # Recursive tester routine. Test the segment given and if an error is # encountered splits the segment into <fanout> subsegment and recurses. Failing # one liners are rejected. The set of accepted lines are built sequentially from # the beginning. def binaryTest(dirlist, lines, pchname, header, footer, acceptedlines, indent, startpoint): linecount = len(lines) if linecount == 0: return # Test if this slice passes the buildtest writePch(pchname, header, footer, acceptedlines, lines) if testSequenceBuild(dirlist): return acceptedlines + lines # Reject one liners if linecount == 1: print(indent + "Rejected: " + lines[0]) return acceptedlines # Recurse with multiline slices fanout = 4 splits = [] for i in range(3): splits.append(linecount * (i + 1) / fanout) splits.append(linecount) splitstart = 0 for splitend in splits: # avoid splitting in case we have no resulting lines if (splitend - splitstart) == 0: continue splitslice = lines[splitstart:splitend] print(indent + "[" + str(startpoint + splitstart) + ":" + str(startpoint + splitend) + "] (" + str(splitend - splitstart) + ")") acceptedlines = binaryTest(dirlist, splitslice, pchname, header, footer, acceptedlines, indent + " ", startpoint + splitstart) splitstart = splitend return acceptedlines # ------------------------------------------------------------------------------ # Main entry point if len(sys.argv) < 3: print("Usage: " + sys.argv[0] + " <pch_target> <dir1> [<dir2> <dir3> ...]") sys.exit(1) pchname = os.path.abspath(sys.argv[1]) dirlist = sys.argv[2:] # remove old build log file if os.path.exists("buildlog.txt"): os.remove("buildlog.txt") # test for corner case of everything working from the start if testSequenceBuild(dirlist): print("pch working, nothing to do.") sys.exit(0) # Open the header file for reading inputfile = file(pchname, "r+") inputdata = inputfile.read() inputfile.close() segments = inputdata.split(MARKER) header = segments[0] footer = segments[2] lines = segments[1].split("\n") writePch(pchname + "_backup", header, footer, lines, []) # test for corner case of no convergence possible writePch(pchname, header, footer, [], []) if not testSequenceBuild(dirlist): writePch(pchname, header, footer, lines, []) print("Building with no candidate lines failed. Convergence questionable, aborting.") sys.exit(0) # Starting pruning print("Starting evaluation of " + str(len(lines)) + " lines") acceptedlines = binaryTest(dirlist, lines, pchname, header, footer, [], "", 0) writePch(pchname, header, footer, acceptedlines, [])
1,930
332
// // ISHPermissionRequestEventStore.h // ISHPermissionKit // // Created by <NAME> on 02.07.14. // Copyright (c) 2014 iosphere GmbH. All rights reserved. // #import "ISHPermissionRequest.h" #if defined(ISHPermissionRequestCalendarEnabled) || defined(ISHPermissionRequestRemindersEnabled) /** * Permission request for calendar events and reminders. * * @sa ISHPermissionCategoryReminders, ISHPermissionCategoryEvents */ @interface ISHPermissionRequestEventStore : ISHPermissionRequest @end #endif
157
945
<reponame>RYH61/iotdb<gh_stars>100-1000 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.db.mpp.plan.analyze; import org.apache.iotdb.commons.path.PartialPath; import org.apache.iotdb.db.mpp.plan.expression.Expression; import org.apache.iotdb.db.mpp.plan.expression.ExpressionType; import org.apache.iotdb.db.mpp.plan.expression.binary.AdditionExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.DivisionExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.EqualToExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.GreaterEqualExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.GreaterThanExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.LessEqualExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.LessThanExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.LogicAndExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.LogicOrExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.ModuloExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.MultiplicationExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.NonEqualExpression; import org.apache.iotdb.db.mpp.plan.expression.binary.SubtractionExpression; import org.apache.iotdb.db.mpp.plan.expression.leaf.ConstantOperand; import org.apache.iotdb.db.mpp.plan.expression.leaf.TimeSeriesOperand; import org.apache.iotdb.db.mpp.plan.expression.leaf.TimestampOperand; import org.apache.iotdb.db.mpp.plan.expression.multi.FunctionExpression; import org.apache.iotdb.db.mpp.plan.expression.unary.InExpression; import org.apache.iotdb.db.mpp.plan.expression.unary.LikeExpression; import org.apache.iotdb.db.mpp.plan.expression.unary.LogicNotExpression; import org.apache.iotdb.db.mpp.plan.expression.unary.NegationExpression; import org.apache.iotdb.db.mpp.plan.expression.unary.RegularExpression; import org.apache.iotdb.db.mpp.plan.expression.unary.UnaryExpression; import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType; import org.apache.iotdb.tsfile.read.filter.TimeFilter; import org.apache.iotdb.tsfile.read.filter.basic.Filter; import java.util.ArrayList; import java.util.List; public class ExpressionUtils { public static List<Expression> reconstructTimeSeriesOperands( List<? extends PartialPath> actualPaths) { List<Expression> resultExpressions = new ArrayList<>(); for (PartialPath actualPath : actualPaths) { resultExpressions.add(new TimeSeriesOperand(actualPath)); } return resultExpressions; } public static List<Expression> reconstructFunctionExpressions( FunctionExpression expression, List<List<Expression>> childExpressionsList) { List<Expression> resultExpressions = new ArrayList<>(); for (List<Expression> functionExpressions : childExpressionsList) { resultExpressions.add( new FunctionExpression( expression.getFunctionName(), expression.getFunctionAttributes(), functionExpressions)); } return resultExpressions; } public static List<Expression> reconstructUnaryExpressions( UnaryExpression expression, List<Expression> childExpressions) { List<Expression> resultExpressions = new ArrayList<>(); for (Expression childExpression : childExpressions) { switch (expression.getExpressionType()) { case IN: resultExpressions.add( new InExpression( childExpression, ((InExpression) expression).isNotIn(), ((InExpression) expression).getValues())); break; case LIKE: resultExpressions.add( new LikeExpression( childExpression, ((LikeExpression) expression).getPatternString(), ((LikeExpression) expression).getPattern())); break; case LOGIC_NOT: resultExpressions.add(new LogicNotExpression(childExpression)); break; case NEGATION: resultExpressions.add(new NegationExpression(childExpression)); break; case REGEXP: resultExpressions.add( new RegularExpression( childExpression, ((RegularExpression) expression).getPatternString(), ((RegularExpression) expression).getPattern())); break; default: throw new IllegalArgumentException( "unsupported expression type: " + expression.getExpressionType()); } } return resultExpressions; } public static List<Expression> reconstructBinaryExpressions( ExpressionType expressionType, List<Expression> leftExpressions, List<Expression> rightExpressions) { List<Expression> resultExpressions = new ArrayList<>(); for (Expression le : leftExpressions) { for (Expression re : rightExpressions) { switch (expressionType) { case ADDITION: resultExpressions.add(new AdditionExpression(le, re)); break; case SUBTRACTION: resultExpressions.add(new SubtractionExpression(le, re)); break; case MULTIPLICATION: resultExpressions.add(new MultiplicationExpression(le, re)); break; case DIVISION: resultExpressions.add(new DivisionExpression(le, re)); break; case MODULO: resultExpressions.add(new ModuloExpression(le, re)); break; case LESS_THAN: resultExpressions.add(new LessThanExpression(le, re)); break; case LESS_EQUAL: resultExpressions.add(new LessEqualExpression(le, re)); break; case GREATER_THAN: resultExpressions.add(new GreaterThanExpression(le, re)); break; case GREATER_EQUAL: resultExpressions.add(new GreaterEqualExpression(le, re)); break; case EQUAL_TO: resultExpressions.add(new EqualToExpression(le, re)); break; case NON_EQUAL: resultExpressions.add(new NonEqualExpression(le, re)); break; case LOGIC_AND: resultExpressions.add(new LogicAndExpression(le, re)); break; case LOGIC_OR: resultExpressions.add(new LogicOrExpression(le, re)); break; default: throw new IllegalArgumentException("unsupported expression type: " + expressionType); } } } return resultExpressions; } public static <T> void cartesianProduct( List<List<T>> dimensionValue, List<List<T>> resultList, int layer, List<T> currentList) { if (layer < dimensionValue.size() - 1) { if (dimensionValue.get(layer).isEmpty()) { cartesianProduct(dimensionValue, resultList, layer + 1, currentList); } else { for (int i = 0; i < dimensionValue.get(layer).size(); i++) { List<T> list = new ArrayList<>(currentList); list.add(dimensionValue.get(layer).get(i)); cartesianProduct(dimensionValue, resultList, layer + 1, list); } } } else if (layer == dimensionValue.size() - 1) { if (dimensionValue.get(layer).isEmpty()) { resultList.add(currentList); } else { for (int i = 0; i < dimensionValue.get(layer).size(); i++) { List<T> list = new ArrayList<>(currentList); list.add(dimensionValue.get(layer).get(i)); resultList.add(list); } } } } public static Filter constructTimeFilter( ExpressionType expressionType, Expression timeExpression, Expression valueExpression) { if (timeExpression instanceof TimestampOperand && valueExpression instanceof ConstantOperand && ((ConstantOperand) valueExpression).getDataType() == TSDataType.INT64) { long value = Long.parseLong(((ConstantOperand) valueExpression).getValueString()); switch (expressionType) { case LESS_THAN: return TimeFilter.lt(value); case LESS_EQUAL: return TimeFilter.ltEq(value); case GREATER_THAN: return TimeFilter.gt(value); case GREATER_EQUAL: return TimeFilter.gtEq(value); case EQUAL_TO: return TimeFilter.eq(value); case NON_EQUAL: return TimeFilter.notEq(value); default: throw new IllegalArgumentException("unsupported expression type: " + expressionType); } } return null; } public static Expression constructQueryFilter(List<Expression> expressions) { if (expressions.size() == 1) { return expressions.get(0); } return ExpressionUtils.constructBinaryFilterTreeWithAnd(expressions); } private static Expression constructBinaryFilterTreeWithAnd(List<Expression> expressions) { // TODO: consider AVL tree if (expressions.size() == 2) { return new LogicAndExpression(expressions.get(0), expressions.get(1)); } else { return new LogicAndExpression( expressions.get(0), constructBinaryFilterTreeWithAnd(expressions.subList(1, expressions.size()))); } } }
3,954
3,323
<gh_stars>1000+ """Test AdaNet estimator single graph implementation for TF 2. Copyright 2019 The AdaNet Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import logging from adanet import tf_compat from adanet.core import testing_utils as tu from adanet.core.estimator import Estimator from adanet.core.report_materializer import ReportMaterializer from adanet.subnetwork import Builder from adanet.subnetwork import SimpleGenerator from adanet.subnetwork import Subnetwork import tensorflow.compat.v2 as tf from tensorflow_estimator.python.estimator.head import regression_head logging.set_verbosity(logging.INFO) XOR_FEATURES = [[1., 0.], [0., 0], [0., 1.], [1., 1.]] XOR_LABELS = [[1.], [0.], [1.], [0.]] class _SimpleBuilder(Builder): """A simple subnetwork builder that takes feature_columns.""" def __init__(self, name, seed=42): self._name = name self._seed = seed @property def name(self): return self._name def build_subnetwork(self, features, logits_dimension, training, iteration_step, summary, previous_ensemble=None): seed = self._seed if previous_ensemble: # Increment seed so different iterations don't learn the exact same thing. seed += 1 with tf_compat.v1.variable_scope("simple"): input_layer = tf_compat.v1.feature_column.input_layer( features=features, feature_columns=tf.feature_column.numeric_column("x", 2)) last_layer = input_layer with tf_compat.v1.variable_scope("logits"): logits = tf_compat.v1.layers.dense( last_layer, logits_dimension, kernel_initializer=tf_compat.v1.glorot_uniform_initializer(seed=seed)) summary.scalar("scalar", 3) batch_size = features["x"].get_shape().as_list()[0] summary.image("image", tf.ones([batch_size, 3, 3, 1])) with tf_compat.v1.variable_scope("nested"): summary.scalar("scalar", 5) return Subnetwork( last_layer=last_layer, logits=logits, complexity=1, persisted_tensors={}, ) def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels, iteration_step, summary, previous_ensemble): optimizer = tf_compat.v1.train.GradientDescentOptimizer(learning_rate=.001) return optimizer.minimize(loss, var_list=var_list) class EstimatorSummaryWriterTest(tu.AdanetTestCase): """Test that Tensorboard summaries get written correctly.""" @tf_compat.skip_for_tf1 def test_summaries(self): """Tests that summaries are written to candidate directory.""" run_config = tf.estimator.RunConfig( tf_random_seed=42, log_step_count_steps=2, save_summary_steps=2, model_dir=self.test_subdirectory) subnetwork_generator = SimpleGenerator([_SimpleBuilder("dnn")]) report_materializer = ReportMaterializer( input_fn=tu.dummy_input_fn([[1., 1.]], [[0.]]), steps=1) estimator = Estimator( head=regression_head.RegressionHead( loss_reduction=tf_compat.SUM_OVER_BATCH_SIZE), subnetwork_generator=subnetwork_generator, report_materializer=report_materializer, max_iteration_steps=10, config=run_config) train_input_fn = tu.dummy_input_fn([[1., 0.]], [[1.]]) estimator.train(input_fn=train_input_fn, max_steps=3) ensemble_loss = 1.52950 self.assertAlmostEqual( ensemble_loss, tu.check_eventfile_for_keyword("loss", self.test_subdirectory), places=3) self.assertIsNotNone( tu.check_eventfile_for_keyword("global_step/sec", self.test_subdirectory)) self.assertEqual( 0., tu.check_eventfile_for_keyword("iteration/adanet/iteration", self.test_subdirectory)) subnetwork_subdir = os.path.join(self.test_subdirectory, "subnetwork/t0_dnn") self.assertAlmostEqual( 3., tu.check_eventfile_for_keyword("scalar", subnetwork_subdir), places=3) self.assertEqual((3, 3, 1), tu.check_eventfile_for_keyword("image", subnetwork_subdir)) self.assertAlmostEqual( 5., tu.check_eventfile_for_keyword("nested/scalar", subnetwork_subdir), places=3) ensemble_subdir = os.path.join( self.test_subdirectory, "ensemble/t0_dnn_grow_complexity_regularized") self.assertAlmostEqual( ensemble_loss, tu.check_eventfile_for_keyword( "adanet_loss/adanet/adanet_weighted_ensemble", ensemble_subdir), places=1) self.assertAlmostEqual( 0., tu.check_eventfile_for_keyword( "complexity_regularization/adanet/adanet_weighted_ensemble", ensemble_subdir), places=3) self.assertAlmostEqual( 1., tu.check_eventfile_for_keyword( "mixture_weight_norms/adanet/" "adanet_weighted_ensemble/subnetwork_0", ensemble_subdir), places=3) if __name__ == "__main__": tf.enable_v2_behavior() tf.test.main()
2,507
3,294
#pragma once ///////////////////////////////////////////////////////////////////////////// // CCalendarBar window class CCalendarBar : public CWnd { // Construction public: CCalendarBar(); // Attributes protected: CMonthCalCtrl m_wndCalendar; int m_nMyCalendarsY; CImageList m_Images; // Overrides public: virtual BOOL Create(const RECT& rect, CWnd* pParentWnd, UINT nID = (UINT)-1); // Implementation public: virtual ~CCalendarBar(); protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnPaint(); DECLARE_MESSAGE_MAP() };
236
415
/* * Copyright 2009, 2010 Grove City College * * 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 <iomanip> using std::setprecision; using std::setw; #include <iostream> using std::ios; #include <Common/Utility/Timer.h> namespace Utility { ostream& operator<<(ostream& out, Timer& timer) { double seconds = timer.getElapsed(); int minutes = 0; int hours = 0; if (seconds > 60) { minutes = int(seconds/60.f); seconds -= 60.f*minutes; hours = minutes/60; minutes = minutes%60; } char fill = out.fill('0'); out << setw(2) << hours << ":"; out << setw(2) << minutes << ":"; out.setf(ios::fixed); int precision = out.precision(2); out << setw(5) << seconds; out.precision(precision); out.unsetf(ios::fixed); out.fill(fill); return out; } } // namespace Utility
511
848
<filename>tools/Vitis-AI-Library/segmentation/src/segmentation_imp.cpp /* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "./segmentation_imp.hpp" #include <iostream> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <vector> #include <vitis/ai/profiling.hpp> namespace vitis { namespace ai { using namespace std; using namespace cv; SegmentationImp::SegmentationImp(const std::string& model_name, bool need_preprocess) : vitis::ai::TConfigurableDpuTask<Segmentation>(model_name, need_preprocess) {} SegmentationImp::~SegmentationImp() {} SegmentationResult SegmentationImp::run_8UC1(const cv::Mat& input_image) { cv::Mat image; auto size = cv::Size(getInputWidth(), getInputHeight()); if (size != input_image.size()) { cv::resize(input_image, image, size, 0, 0, cv::INTER_LINEAR); } else { image = input_image; } __TIC__(SEGMENTATION_SET_IMG) if(configurable_dpu_task_->getConfig().order_type() == 1) { configurable_dpu_task_->setInputImageBGR(image); } else if (configurable_dpu_task_->getConfig().order_type() == 2) { configurable_dpu_task_->setInputImageRGB(image); } else { LOG(FATAL) << "unknown image order type"; } __TOC__(SEGMENTATION_SET_IMG) __TIC__(SEGMENTATION_DPU) configurable_dpu_task_->run(0); __TOC__(SEGMENTATION_DPU) __TIC__(post) auto result = segmentation_post_process_8UC1( configurable_dpu_task_->getInputTensor()[0][0], configurable_dpu_task_->getOutputTensor()[0][0]); __TOC__(post) return result[0]; } std::vector<SegmentationResult> SegmentationImp::run_8UC1( const std::vector<cv::Mat>& input_images) { std::vector<cv::Mat> images; auto size = cv::Size(getInputWidth(), getInputHeight()); for (auto i = 0u; i < input_images.size(); i++) { cv::Mat image; if (size != input_images[i].size()) { cv::resize(input_images[i], image, size, 0, 0, cv::INTER_LINEAR); images.push_back(image); } else { images.push_back(input_images[i]); } } __TIC__(SEGMENTATION_SET_IMG) if(configurable_dpu_task_->getConfig().order_type() == 1) { configurable_dpu_task_->setInputImageBGR(images); } else if (configurable_dpu_task_->getConfig().order_type() == 2) { configurable_dpu_task_->setInputImageRGB(images); } else { LOG(FATAL) << "unknown image order type"; } __TOC__(SEGMENTATION_SET_IMG) __TIC__(SEGMENTATION_DPU) configurable_dpu_task_->run(0); __TOC__(SEGMENTATION_DPU) __TIC__(post) auto results = segmentation_post_process_8UC1( configurable_dpu_task_->getInputTensor()[0][0], configurable_dpu_task_->getOutputTensor()[0][0]); __TOC__(post) return results; } SegmentationResult SegmentationImp::run_8UC3(const cv::Mat& input_image) { cv::Mat image; auto size = cv::Size(getInputWidth(), getInputHeight()); if (size != input_image.size()) { cv::resize(input_image, image, size, 0, cv::INTER_NEAREST); } else { image = input_image; } __TIC__(SEGMENTATION_SET_IMG) if(configurable_dpu_task_->getConfig().order_type() == 1) { configurable_dpu_task_->setInputImageBGR(image); } else if (configurable_dpu_task_->getConfig().order_type() == 2) { configurable_dpu_task_->setInputImageRGB(image); } else { LOG(FATAL) << "unknown image order type"; } __TOC__(SEGMENTATION_SET_IMG) __TIC__(SEGMENTATION_DPU) configurable_dpu_task_->run(0); __TOC__(SEGMENTATION_DPU) __TIC__(post) auto result = segmentation_post_process_8UC3( configurable_dpu_task_->getInputTensor()[0][0], configurable_dpu_task_->getOutputTensor()[0][0], configurable_dpu_task_->getConfig()); __TOC__(post) return result[0]; } std::vector<SegmentationResult> SegmentationImp::run_8UC3( const std::vector<cv::Mat>& input_images) { std::vector<cv::Mat> images; auto size = cv::Size(getInputWidth(), getInputHeight()); for (auto i = 0u; i < input_images.size(); i++) { cv::Mat image; if (size != input_images[i].size()) { cv::resize(input_images[i], image, size, 0, 0, cv::INTER_LINEAR); images.push_back(image); } else { images.push_back(input_images[i]); } } __TIC__(SEGMENTATION_SET_IMG) if(configurable_dpu_task_->getConfig().order_type() == 1) { configurable_dpu_task_->setInputImageBGR(images); } else if (configurable_dpu_task_->getConfig().order_type() == 2) { configurable_dpu_task_->setInputImageRGB(images); } else { LOG(FATAL) << "unknown image order type"; } __TOC__(SEGMENTATION_SET_IMG) __TIC__(SEGMENTATION_DPU) configurable_dpu_task_->run(0); __TOC__(SEGMENTATION_DPU) __TIC__(post) auto results = segmentation_post_process_8UC3( configurable_dpu_task_->getInputTensor()[0][0], configurable_dpu_task_->getOutputTensor()[0][0], configurable_dpu_task_->getConfig()); __TOC__(post) return results; } } // namespace ai } // namespace vitis
2,255
310
{ "name": "101", "description": "A digital multimeter.", "url": "https://www.fluke.com/en-sg/product/electrical-testing/digital-multimeters/fluke-101" }
59
879
package org.zstack.compute.vm; public interface VmNicQosConfigBackend { String getVmInstanceType(); void addNicQos(String vmUuid, String vmNicUuid, Long outboundBandwidth, Long inboundBandwidth); void deleteNicQos(String vmUuid, String vmNicUuid,String direction); VmNicQosStruct getNicQos(String vmUuid, String vmNicUuid); void addVmQos(String vmUuid, Long outboundBandwidth, Long inboundBandwidth); void deleteVmQos(String vmUuid, String direction); VmNicQosStruct getVmQos(String vmUuid); }
202
514
#!/usr/bin/env python ############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## """Tool to dump the last few transactions from a FileStorage.""" from __future__ import print_function from ZODB.fstools import prev_txn import binascii import getopt import sys try: from hashlib import sha1 except ImportError: from sha import sha as sha1 def main(path, ntxn): with open(path, "rb") as f: f.seek(0, 2) th = prev_txn(f) i = ntxn while th and i > 0: hash = sha1(th.get_raw_data()).digest() l = len(str(th.get_timestamp())) + 1 th.read_meta() print("%s: hash=%s" % (th.get_timestamp(), binascii.hexlify(hash).decode())) print(("user=%r description=%r length=%d offset=%d (+%d)" % (th.user, th.descr, th.length, th.get_offset(), len(th)))) print() th = th.prev_txn() i -= 1 def Main(): ntxn = 10 opts, args = getopt.getopt(sys.argv[1:], "n:") path, = args for k, v in opts: if k == '-n': ntxn = int(v) main(path, ntxn) if __name__ == "__main__": Main()
746
6,989
<reponame>shawwn/cpython /* Do not renumber the file; these numbers are part of the stable ABI. */ #if defined(Py_LIMITED_API) /* Disabled, see #10181 */ #undef Py_bf_getbuffer #undef Py_bf_releasebuffer #else #define Py_bf_getbuffer 1 #define Py_bf_releasebuffer 2 #endif #define Py_mp_ass_subscript 3 #define Py_mp_length 4 #define Py_mp_subscript 5 #define Py_nb_absolute 6 #define Py_nb_add 7 #define Py_nb_and 8 #define Py_nb_bool 9 #define Py_nb_divmod 10 #define Py_nb_float 11 #define Py_nb_floor_divide 12 #define Py_nb_index 13 #define Py_nb_inplace_add 14 #define Py_nb_inplace_and 15 #define Py_nb_inplace_floor_divide 16 #define Py_nb_inplace_lshift 17 #define Py_nb_inplace_multiply 18 #define Py_nb_inplace_or 19 #define Py_nb_inplace_power 20 #define Py_nb_inplace_remainder 21 #define Py_nb_inplace_rshift 22 #define Py_nb_inplace_subtract 23 #define Py_nb_inplace_true_divide 24 #define Py_nb_inplace_xor 25 #define Py_nb_int 26 #define Py_nb_invert 27 #define Py_nb_lshift 28 #define Py_nb_multiply 29 #define Py_nb_negative 30 #define Py_nb_or 31 #define Py_nb_positive 32 #define Py_nb_power 33 #define Py_nb_remainder 34 #define Py_nb_rshift 35 #define Py_nb_subtract 36 #define Py_nb_true_divide 37 #define Py_nb_xor 38 #define Py_sq_ass_item 39 #define Py_sq_concat 40 #define Py_sq_contains 41 #define Py_sq_inplace_concat 42 #define Py_sq_inplace_repeat 43 #define Py_sq_item 44 #define Py_sq_length 45 #define Py_sq_repeat 46 #define Py_tp_alloc 47 #define Py_tp_base 48 #define Py_tp_bases 49 #define Py_tp_call 50 #define Py_tp_clear 51 #define Py_tp_dealloc 52 #define Py_tp_del 53 #define Py_tp_descr_get 54 #define Py_tp_descr_set 55 #define Py_tp_doc 56 #define Py_tp_getattr 57 #define Py_tp_getattro 58 #define Py_tp_hash 59 #define Py_tp_init 60 #define Py_tp_is_gc 61 #define Py_tp_iter 62 #define Py_tp_iternext 63 #define Py_tp_methods 64 #define Py_tp_new 65 #define Py_tp_repr 66 #define Py_tp_richcompare 67 #define Py_tp_setattr 68 #define Py_tp_setattro 69 #define Py_tp_str 70 #define Py_tp_traverse 71 #define Py_tp_members 72 #define Py_tp_getset 73 #define Py_tp_free 74 #define Py_nb_matrix_multiply 75 #define Py_nb_inplace_matrix_multiply 76 #define Py_am_await 77 #define Py_am_aiter 78 #define Py_am_anext 79 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ #define Py_tp_finalize 80 #endif
965
6,692
<gh_stars>1000+ // Copyright (C) 2014 <NAME> (<EMAIL>) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_TEST_FOR_ODR_VIOLATIONS_CPp_ #define DLIB_TEST_FOR_ODR_VIOLATIONS_CPp_ #include "test_for_odr_violations.h" extern "C" { // The point of this block of code is to cause a link time error that will prevent a user // from compiling part of their application with DLIB_ASSERT enabled and part with them // disabled since doing that would be a violation of C++'s one definition rule. #ifdef ENABLE_ASSERTS const int USER_ERROR__inconsistent_build_configuration__see_dlib_faq_1 = 0; #else const int USER_ERROR__inconsistent_build_configuration__see_dlib_faq_1_ = 0; #endif // The point of this block of code is to cause a link time error if someone builds dlib via // cmake as a separately installable library, and therefore generates a dlib/config.h from // cmake, but then proceeds to use the default unconfigured dlib/config.h from version // control. It should be obvious why this is bad, if it isn't you need to read a book // about C++. Moreover, it can only happen if someone manually copies files around and // messes things up. If instead they run `make install` or `cmake --build . --target // install` things will be setup correctly, which is what they should do. To summarize: DO // NOT BUILD A STANDALONE DLIB AND THEN GO CHERRY PICKING FILES FROM THE BUILD FOLDER AND // MIXING THEM WITH THE SOURCE FROM GITHUB. USE CMAKE'S INSTALL SCRIPTS TO INSTALL DLIB. // Or even better, don't install dlib at all and instead build your program as shown in // examples/CMakeLists.txt #if defined(DLIB_NOT_CONFIGURED) && !defined(DLIB__CMAKE_GENERATED_A_CONFIG_H_FILE) const int USER_ERROR__inconsistent_build_configuration__see_dlib_faq_2 = 0; #endif #ifdef DLIB_CHECK_FOR_VERSION_MISMATCH const int DLIB_CHECK_FOR_VERSION_MISMATCH = 0; #endif } #endif // DLIB_TEST_FOR_ODR_VIOLATIONS_CPp_
703
1,056
/* * 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. */ //placed in this package intentionally: the JavaHintsAnnotationProcessor ignores all annotations outside this package package org.netbeans.spi.java.hints; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * * @author lahvac */ public class TestAnnotations { @Retention(RetentionPolicy.RUNTIME) public @interface TestAnnotation1 { public boolean b1(); public boolean b2() default false; public boolean b3() default false; public int i1(); public int i2() default 1; public int i3() default 1; public String s1(); public String s2() default ""; public String s3() default ""; public TestAnnotation2 a1(); // public TestAnnotation2 a2() default @TestAnnotation2(a1=@TestAnnotation3(as1={"a", "b"}, as3="c")); // public TestAnnotation2 a3() default @TestAnnotation2(a1=@TestAnnotation3(as1={"a2", "b2"}, as3="c2")); public Class<?> c1(); public Class<?> c2() default Void.class; public Class<?> c3() default Void.class; public TestEnum e1(); // public TestEnum e2() default TestEnum.A; public TestEnum e3()/* default TestEnum.A*/; public boolean[] ab1(); public boolean[] ab2() default false; public boolean[] ab3() default false; public int[] ai1(); public int[] ai2() default 1; public int[] ai3() default 1; public String[] as1(); public String[] as2() default ""; public String[] as3() default ""; public TestAnnotation2[] aa1(); // public TestAnnotation2[] aa2() default @TestAnnotation2(a1=@TestAnnotation3(as1={"a", "b"}, as3="c")); // public TestAnnotation2[] aa3() default @TestAnnotation2(a1=@TestAnnotation3(as1={"a2", "b2"}, as3="c2")); public Class<?>[] ac1(); public Class<?>[] ac2() default Void.class; public Class<?>[] ac3() default Void.class; public TestEnum[] ae1(); // public TestEnum[] ae2() default TestEnum.A; public TestEnum[] ae3()/* default TestEnum.A*/; } public @interface TestAnnotation2 { public TestAnnotation3 a1(); // public TestAnnotation3 a2() default @TestAnnotation3(as1={"d", "e"}, as3="f"); // public TestAnnotation3 a3() default @TestAnnotation3(as1={"g", "h"}, as3="i"); } public @interface TestAnnotation3 { public String[] as1(); public String[] as2() default {""}; public String[] as3() default {""}; } public enum TestEnum { A, B, C, D; } }
1,331
351
<reponame>TheSenPie/talos<filename>editor/src/com/talosvfx/talos/editor/addons/shader/nodes/SmoothStepNode.java package com.talosvfx.talos.editor.addons.shader.nodes; import com.talosvfx.talos.runtime.shaders.ShaderBuilder; public class SmoothStepNode extends AbstractShaderNode { public final String INPUT = "inputValue"; public final String OUTPUT = "outputValue"; public final String EDGE_ONE = "edgeOne"; public final String EDGE_TWO = "edgeTwo"; @Override public ShaderBuilder.Type getVarType (String name) { if (name.equals(OUTPUT)) { return getTargetVarType(INPUT, ShaderBuilder.Type.FLOAT); } return super.getVarType(name); } @Override public void prepareDeclarations (ShaderBuilder shaderBuilder) { String input = getExpression(INPUT); String edgeOne = getExpression(EDGE_ONE, null); String edgeTwo = getExpression(EDGE_TWO, null); ShaderBuilder.Type outputType = getVarType(OUTPUT); String expression = "smoothstep(" + edgeOne + ", " + edgeTwo + ", " + input + ")"; shaderBuilder.addLine(outputType.getTypeString() + " smoothStepVar" + getId() + " = " + expression); } @Override public String writeOutputCode (String slotId) { return "smoothStepVar" + getId(); } }
506
1,066
/* * Copyright (c) 2020 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.eatthepath.pushy.apns.proxy; import io.netty.handler.proxy.HttpProxyHandler; import io.netty.handler.proxy.ProxyHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.*; import java.util.List; /** * A concrete {@link ProxyHandlerFactory} implementation that creates {@link HttpProxyHandler} instances. * * @author <a href="https://github.com/jchambers"><NAME></a> * * @since 0.6 */ public class HttpProxyHandlerFactory implements ProxyHandlerFactory { private static final Logger log = LoggerFactory.getLogger(HttpProxyHandlerFactory.class); private final SocketAddress proxyAddress; private final String username; private final String password; private static final String PROXY_USERNAME_PROPERTY_KEY = "http.proxyUser"; private static final String PROXY_PASSWORD_PROPERTY_KEY = "http.proxyPassword"; /** * Constructs an {@code HttpProxyHandlerFactory} that uses the HTTP proxy (if any) specified in Java's standard * <a href="https://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies">proxy system * properties</a>. * * @param apnsHost the APNs host for which to find proxy settings * @return an HTTP proxy factory if a proxy is configured for the given APNs host, or {@code null} if no proxy is * configured for the given host * @throws URISyntaxException if {@code apnsHost} is malformed in some way * * @see <a href="https://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html#Proxies">Java™ Platform, Standard Edition 7 - Networking Properties - Proxies</a> * @since 0.13.11 */ public static HttpProxyHandlerFactory fromSystemProxies(final String apnsHost) throws URISyntaxException { final SocketAddress proxyAddress = getProxyAddressForUri(new URI("https", apnsHost, null, null)); return (proxyAddress != null) ? new HttpProxyHandlerFactory(proxyAddress, System.getProperty(PROXY_USERNAME_PROPERTY_KEY), System.getProperty(PROXY_PASSWORD_PROPERTY_KEY)) : null; } /** * Returns the {@link SocketAddress} for any system-wide HTTP {@link Proxy} for a given {@link URI}. * * @param uri the URI for which to find a system-wide proxy * @return the {@link SocketAddress} of the first HTTP {@link Proxy} found, or {@code null} if there were none * @since 0.13.11 */ private static SocketAddress getProxyAddressForUri(final URI uri) { final ProxySelector defaultProxySelector = ProxySelector.getDefault(); final List<Proxy> proxiesForUri = defaultProxySelector.select(uri); log.debug("Proxies for \"{}\": {}", uri, proxiesForUri); for (final java.net.Proxy proxy : proxiesForUri) { if (proxy.type() == Proxy.Type.HTTP) { InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); if (proxyAddress.isUnresolved()) { proxyAddress = new InetSocketAddress(proxyAddress.getHostString(), proxyAddress.getPort()); } return proxyAddress; } } return null; } /** * Creates a new proxy handler factory that will create HTTP proxy handlers that use the proxy at the given * address and that will not perform authentication. * * @param proxyAddress the address of the HTTP proxy server * * @since 0.6 */ public HttpProxyHandlerFactory(final SocketAddress proxyAddress) { this(proxyAddress, null, null); } /** * Creates a new proxy handler factory that will create HTTP proxy handlers that use the proxy at the given * address and that will authenticate with the given username and password. * * @param proxyAddress the address of the HTTP proxy server * @param username the username to use when connecting to the given proxy server * @param password the password to use when connecting to the given proxy server * * @since 0.6 */ public HttpProxyHandlerFactory(final SocketAddress proxyAddress, final String username, final String password) { this.proxyAddress = proxyAddress; this.username = username; this.password = password; } /* * (non-Javadoc) * @see ProxyHandlerFactory#createProxyHandler() */ @Override public ProxyHandler createProxyHandler() { final HttpProxyHandler handler; // For reasons that are not immediately clear, HttpProxyHandler doesn't allow null usernames/passwords if // specified. If we want them to be null, we have to use the constructor that doesn't take a username/password // at all. if (this.username != null && this.password != null) { handler = new HttpProxyHandler(this.proxyAddress, this.username, this.password); } else { handler = new HttpProxyHandler(this.proxyAddress); } return handler; } // Visible for testing String getUsername() { return this.username; } // Visible for testing String getPassword() { return this.password; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "HttpProxyHandlerFactory {" + "proxyAddress=" + proxyAddress + ", username=" + username + ", password=*****" + "}"; } }
2,305
1,338
#ifndef DEBUG_PARANOIA_CONFIG_H #define DEBUG_PARANOIA_CONFIG_H // enable paranoia checks (0/1) #ifndef ENABLE_PARANOIA_CHECKS # define ENABLE_PARANOIA_CHECKS 0 #endif // number of check slots (should depend on the components for which checks // are enabled) #define PARANOIA_SLOT_COUNT (32 * 1024) // macros that set the paranoia check level for individual components // levels: // * PARANOIA_NAIVE (checks disabled) // * PARANOIA_SUSPICIOUS // * PARANOIA_OBSESSIVE // * PARANOIA_INSANE #define NET_BUFFER_PARANOIA PARANOIA_NAIVE #define OBJECT_CACHE_PARANOIA PARANOIA_NAIVE #endif // DEBUG_PARANOIA_CONFIG_H
244
692
<filename>tests/thread/mutate_set.py # test concurrent mutating access to a shared set object # # MIT license; Copyright (c) 2016 <NAME> on behalf of Pycom Ltd import _thread # the shared set se = set([-1, -2, -3, -4]) # main thread function def th(n, lo, hi): for repeat in range(n): for i in range(lo, hi): se.add(i) assert i in se se.remove(i) assert i not in se with lock: global n_finished n_finished += 1 lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 # spawn threads for i in range(n_thread): _thread.start_new_thread(th, (50, i * 500, (i + 1) * 500)) # busy wait for threads to finish while n_finished < n_thread: pass # check set has correct contents print(sorted(se))
329
333
{ "credentials": { "url": "https://stream.watsonplatform.net/speech-to-text/api", "username": "99999999-4aaa-b333-l335-999999999", "password": "<PASSWORD>" } }
77
613
<gh_stars>100-1000 { "secret": "ngEurope rocks!", "audience": "nodejs-jwt-auth", "issuer": "https://gonto.com" }
52
5,355
package graphql.schema.visibility; import graphql.PublicApi; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLFieldsContainer; import java.util.List; import static graphql.schema.visibility.BlockedFields.newBlock; /** * This field visibility will prevent Introspection queries from being performed. Technically this puts your * system in contravention of the specification - http://facebook.github.io/graphql/#sec-Introspection but some * production systems want this lock down in place. */ @PublicApi public class NoIntrospectionGraphqlFieldVisibility implements GraphqlFieldVisibility { public static NoIntrospectionGraphqlFieldVisibility NO_INTROSPECTION_FIELD_VISIBILITY = new NoIntrospectionGraphqlFieldVisibility(); private final BlockedFields blockedFields; public NoIntrospectionGraphqlFieldVisibility() { blockedFields = newBlock().addPattern("__.*").build(); } @Override public List<GraphQLFieldDefinition> getFieldDefinitions(GraphQLFieldsContainer fieldsContainer) { return blockedFields.getFieldDefinitions(fieldsContainer); } @Override public GraphQLFieldDefinition getFieldDefinition(GraphQLFieldsContainer fieldsContainer, String fieldName) { return blockedFields.getFieldDefinition(fieldsContainer, fieldName); } }
385
759
<reponame>pyecharts/pyecharts_gallery from pyecharts import options as opts from pyecharts.charts import Gauge c = ( Gauge() .add( "", [("完成率", 66.6)], title_label_opts=opts.LabelOpts( font_size=40, color="blue", font_family="Microsoft YaHei" ), ) .set_global_opts(title_opts=opts.TitleOpts(title="Gauge-改变轮盘内的字体")) .render("gauge_label_title_setting.html") )
224
1,144
<reponame>rlourette/TI_SDK_u-boot-2019.01<gh_stars>1000+ // SPDX-License-Identifier: GPL-2.0+ /* * Copyright (C) 2014, <NAME> <<EMAIL>> */ #include <common.h> #include <asm/io.h> #include <asm/pnp_def.h> static void pnp_enter_conf_state(u16 dev) { u16 port = dev >> 8; outb(0x55, port); } static void pnp_exit_conf_state(u16 dev) { u16 port = dev >> 8; outb(0xaa, port); } void lpc47m_enable_serial(uint dev, uint iobase, uint irq) { pnp_enter_conf_state(dev); pnp_set_logical_device(dev); pnp_set_enable(dev, 0); pnp_set_iobase(dev, PNP_IDX_IO0, iobase); pnp_set_irq(dev, PNP_IDX_IRQ0, irq); pnp_set_enable(dev, 1); pnp_exit_conf_state(dev); } void lpc47m_enable_kbc(uint dev, uint irq0, uint irq1) { pnp_enter_conf_state(dev); pnp_set_logical_device(dev); pnp_set_enable(dev, 0); pnp_set_irq(dev, PNP_IDX_IRQ0, irq0); pnp_set_irq(dev, PNP_IDX_IRQ1, irq1); pnp_set_enable(dev, 1); pnp_exit_conf_state(dev); }
473
2,151
<filename>extensions/browser/updater/update_data_provider.cc // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/updater/update_data_provider.h" #include <utility> #include "base/base64.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/optional.h" #include "base/strings/string_util.h" #include "base/task_scheduler/post_task.h" #include "components/update_client/utils.h" #include "content/public/browser/browser_thread.h" #include "crypto/sha2.h" #include "extensions/browser/content_verifier.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/install/crx_install_error.h" #include "extensions/browser/updater/manifest_fetch_data.h" #include "extensions/common/extension.h" namespace extensions { namespace { using UpdateClientCallback = UpdateDataProvider::UpdateClientCallback; void InstallUpdateCallback(content::BrowserContext* context, const std::string& extension_id, const std::string& public_key, const base::FilePath& unpacked_dir, UpdateClientCallback update_client_callback) { // Note that error codes are converted into custom error codes, which are all // based on a constant (see ToInstallerResult). This means that custom codes // from different embedders may collide. However, for any given extension ID, // there should be only one embedder, so this should be OK from Omaha. ExtensionSystem::Get(context)->InstallUpdate( extension_id, public_key, unpacked_dir, base::BindOnce( [](UpdateClientCallback callback, const base::Optional<CrxInstallError>& error) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); update_client::CrxInstaller::Result result(0); if (error.has_value()) { int detail = error->type() == CrxInstallErrorType::SANDBOXED_UNPACKER_FAILURE ? static_cast<int>(error->sandbox_failure_detail()) : static_cast<int>(error->detail()); result = update_client::ToInstallerResult(error->type(), detail); } std::move(callback).Run(result); }, std::move(update_client_callback))); } } // namespace UpdateDataProvider::UpdateDataProvider(content::BrowserContext* browser_context) : browser_context_(browser_context) {} UpdateDataProvider::~UpdateDataProvider() {} void UpdateDataProvider::Shutdown() { browser_context_ = nullptr; } std::vector<std::unique_ptr<update_client::CrxComponent>> UpdateDataProvider::GetData(const ExtensionUpdateDataMap& update_crx_component, const std::vector<std::string>& ids) { std::vector<std::unique_ptr<update_client::CrxComponent>> data; if (!browser_context_) return data; const ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_); const ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(browser_context_); for (const auto& id : ids) { const Extension* extension = registry->GetInstalledExtension(id); data.push_back(extension ? std::make_unique<update_client::CrxComponent>() : nullptr); if (!extension) continue; DCHECK_NE(0u, update_crx_component.count(id)); const ExtensionUpdateData& extension_data = update_crx_component.at(id); update_client::CrxComponent* crx_component = data.back().get(); std::string pubkey_bytes; base::Base64Decode(extension->public_key(), &pubkey_bytes); crx_component->pk_hash.resize(crypto::kSHA256Length, 0); crypto::SHA256HashString(pubkey_bytes, crx_component->pk_hash.data(), crx_component->pk_hash.size()); crx_component->version = extension_data.is_corrupt_reinstall ? base::Version("0.0.0.0") : extension->version(); crx_component->allows_background_download = false; crx_component->requires_network_encryption = true; crx_component->installer = base::MakeRefCounted<ExtensionInstaller>( id, extension->path(), base::BindOnce(&UpdateDataProvider::RunInstallCallback, this)); if (!ExtensionsBrowserClient::Get()->IsExtensionEnabled(id, browser_context_)) { int disabled_reasons = extension_prefs->GetDisableReasons(id); if (disabled_reasons == extensions::disable_reason::DISABLE_NONE || disabled_reasons >= extensions::disable_reason::DISABLE_REASON_LAST) { crx_component->disabled_reasons.push_back(0); } for (int enum_value = 1; enum_value < extensions::disable_reason::DISABLE_REASON_LAST; enum_value <<= 1) { if (disabled_reasons & enum_value) crx_component->disabled_reasons.push_back(enum_value); } } crx_component->install_source = extension_data.install_source; crx_component->install_location = ManifestFetchData::GetSimpleLocationString(extension->location()); } return data; } void UpdateDataProvider::RunInstallCallback( const std::string& extension_id, const std::string& public_key, const base::FilePath& unpacked_dir, UpdateClientCallback update_client_callback) { VLOG(3) << "UpdateDataProvider::RunInstallCallback " << extension_id << " " << public_key; if (!browser_context_) { base::PostTaskWithTraits( FROM_HERE, {base::TaskPriority::BACKGROUND, base::MayBlock()}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), unpacked_dir, true)); return; } content::BrowserThread::GetTaskRunnerForThread(content::BrowserThread::UI) ->PostTask(FROM_HERE, base::BindOnce(InstallUpdateCallback, browser_context_, extension_id, public_key, unpacked_dir, std::move(update_client_callback))); } } // namespace extensions
2,572
790
from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.test.utils import override_settings from django.utils import six from .middleware import RedirectFallbackMiddleware from .models import Redirect @override_settings( APPEND_SLASH=False, MIDDLEWARE_CLASSES=list(settings.MIDDLEWARE_CLASSES) + ['django.contrib.redirects.middleware.RedirectFallbackMiddleware'], SITE_ID=1, ) class RedirectTests(TestCase): def setUp(self): self.site = Site.objects.get(pk=settings.SITE_ID) def test_model(self): r1 = Redirect.objects.create( site=self.site, old_path='/initial', new_path='/new_target') self.assertEqual(six.text_type(r1), "/initial ---> /new_target") def test_redirect(self): Redirect.objects.create( site=self.site, old_path='/initial', new_path='/new_target') response = self.client.get('/initial') self.assertRedirects(response, '/new_target', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash(self): Redirect.objects.create( site=self.site, old_path='/initial/', new_path='/new_target/') response = self.client.get('/initial') self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash_and_query_string(self): Redirect.objects.create( site=self.site, old_path='/initial/?foo', new_path='/new_target/') response = self.client.get('/initial?foo') self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404) def test_response_gone(self): """When the redirect target is '', return a 410""" Redirect.objects.create( site=self.site, old_path='/initial', new_path='') response = self.client.get('/initial') self.assertEqual(response.status_code, 410) @override_settings( INSTALLED_APPS=[app for app in settings.INSTALLED_APPS if app != 'django.contrib.sites']) def test_sites_not_installed(self): with self.assertRaises(ImproperlyConfigured): RedirectFallbackMiddleware()
1,015
5,079
from __future__ import absolute_import, unicode_literals import celery import pytest from celery import uuid from celery import states from django_celery_results.backends.database import DatabaseBackend class SomeClass(object): def __init__(self, data): self.data = data @pytest.mark.django_db() @pytest.mark.usefixtures('depends_on_current_app') class test_DatabaseBackend: @pytest.fixture(autouse=True) def setup_backend(self): self.app.conf.result_serializer = 'json' self.app.conf.result_backend = ( 'django_celery_results.backends:DatabaseBackend') self.b = DatabaseBackend(app=self.app) def test_backend__pickle_serialization(self): self.app.conf.result_serializer = 'pickle' self.app.conf.accept_content = {'pickle', 'json'} self.b = DatabaseBackend(app=self.app) tid2 = uuid() result = {'foo': 'baz', 'bar': SomeClass(12345)} self.b.mark_as_done(tid2, result) # is serialized properly. rindb = self.b.get_result(tid2) assert rindb.get('foo') == 'baz' assert rindb.get('bar').data == 12345 tid3 = uuid() try: raise KeyError('foo') except KeyError as exception: self.b.mark_as_failure(tid3, exception) assert self.b.get_status(tid3) == states.FAILURE assert isinstance(self.b.get_result(tid3), KeyError) def xxx_backend(self): tid = uuid() assert self.b.get_status(tid) == states.PENDING assert self.b.get_result(tid) is None self.b.mark_as_done(tid, 42) assert self.b.get_status(tid) == states.SUCCESS assert self.b.get_result(tid) == 42 tid2 = uuid() try: raise KeyError('foo') except KeyError as exception: self.b.mark_as_failure(tid2, exception) assert self.b.get_status(tid2) == states.FAILURE assert isinstance(self.b.get_result(tid2), KeyError) def test_forget(self): tid = uuid() self.b.mark_as_done(tid, {'foo': 'bar'}) x = self.app.AsyncResult(tid) assert x.result.get('foo') == 'bar' x.forget() if celery.VERSION[0:3] == (3, 1, 10): # bug in 3.1.10 means result did not clear cache after forget. x._cache = None assert x.result is None
1,105
879
package org.zstack.network.service.virtualrouter; import org.zstack.header.core.Completion; public interface AfterAcquireVirtualRouterExtensionPoint { void afterAcquireVirtualRouter(VirtualRouterVmInventory vr, Completion completion); }
72
2,151
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h" #include <memory> #include "base/bind.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/waitable_event.h" #include "base/time/default_tick_clock.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/renderer/platform/scheduler/base/task_queue.h" #include "third_party/blink/renderer/platform/scheduler/child/task_queue_with_task_type.h" #include "third_party/blink/renderer/platform/scheduler/child/worker_scheduler_proxy.h" #include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h" namespace blink { namespace scheduler { WebThreadImplForWorkerScheduler::WebThreadImplForWorkerScheduler( const WebThreadCreationParams& params) : thread_(new base::Thread(params.name ? params.name : std::string())), thread_type_(params.thread_type), worker_scheduler_proxy_( params.frame_scheduler ? std::make_unique<WorkerSchedulerProxy>(params.frame_scheduler) : nullptr) { bool started = thread_->StartWithOptions(params.thread_options); CHECK(started); thread_task_runner_ = thread_->task_runner(); } void WebThreadImplForWorkerScheduler::Init() { base::WaitableEvent completion( base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&WebThreadImplForWorkerScheduler::InitOnThread, base::Unretained(this), &completion)); completion.Wait(); } WebThreadImplForWorkerScheduler::~WebThreadImplForWorkerScheduler() { // We want to avoid blocking main thread when the thread was already // shut down, but calling ShutdownOnThread twice does not cause any problems. if (!was_shutdown_on_thread_.IsSet()) { base::WaitableEvent completion( base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&WebThreadImplForWorkerScheduler::ShutdownOnThread, base::Unretained(this), &completion)); completion.Wait(); } thread_->Stop(); } void WebThreadImplForWorkerScheduler::InitOnThread( base::WaitableEvent* completion) { // TODO(alexclarke): Do we need to unify virtual time for workers and the // main thread? non_main_thread_scheduler_ = CreateNonMainThreadScheduler(); non_main_thread_scheduler_->Init(); task_queue_ = non_main_thread_scheduler_->DefaultTaskQueue(); task_runner_ = TaskQueueWithTaskType::Create( task_queue_, TaskType::kWorkerThreadTaskQueueDefault); idle_task_runner_ = non_main_thread_scheduler_->IdleTaskRunner(); base::MessageLoopCurrent::Get()->AddDestructionObserver(this); completion->Signal(); } void WebThreadImplForWorkerScheduler::ShutdownOnThread( base::WaitableEvent* completion) { was_shutdown_on_thread_.Set(); task_queue_ = nullptr; task_runner_ = nullptr; idle_task_runner_ = nullptr; non_main_thread_scheduler_ = nullptr; if (completion) completion->Signal(); } std::unique_ptr<NonMainThreadScheduler> WebThreadImplForWorkerScheduler::CreateNonMainThreadScheduler() { return NonMainThreadScheduler::Create(thread_type_, worker_scheduler_proxy_.get()); } void WebThreadImplForWorkerScheduler::WillDestroyCurrentMessageLoop() { ShutdownOnThread(nullptr); } blink::PlatformThreadId WebThreadImplForWorkerScheduler::ThreadId() const { return thread_->GetThreadId(); } blink::ThreadScheduler* WebThreadImplForWorkerScheduler::Scheduler() const { return non_main_thread_scheduler_.get(); } SingleThreadIdleTaskRunner* WebThreadImplForWorkerScheduler::GetIdleTaskRunner() const { return idle_task_runner_.get(); } scoped_refptr<base::SingleThreadTaskRunner> WebThreadImplForWorkerScheduler::GetTaskRunner() const { return task_runner_; } void WebThreadImplForWorkerScheduler::AddTaskObserverInternal( base::MessageLoop::TaskObserver* observer) { non_main_thread_scheduler_->AddTaskObserver(observer); } void WebThreadImplForWorkerScheduler::RemoveTaskObserverInternal( base::MessageLoop::TaskObserver* observer) { non_main_thread_scheduler_->RemoveTaskObserver(observer); } } // namespace scheduler } // namespace blink
1,669
335
{ "word": "Rationalize", "definitions": [ "Attempt to explain or justify (behaviour or an attitude) with logical reasons, even if these are not appropriate.", "Make (a company, process, or industry) more efficient, especially by dispensing with superfluous personnel or equipment.", "Reorganize (a process or system) so as to make it more logical and consistent.", "Convert (a function or expression) to a rational form." ], "parts-of-speech": "Verb" }
159
435
<reponame>amaajemyfren/data<filename>pycon-us-2019/videos/steve-dower-python-on-windows-is-okay-actually-pycon-2019.json { "copyright_text": null, "description": "Packages that won't install, encodings that don't work, installers that\nask too many questions, and having to own a PC are all great reasons to\njust ignore Windows. Or they would be, if they were true.\n\nDespite community perception, more than half of Python usage is on\nWindows, including web development, system administration, and data\nscience, just like on Linux and Mac. And for the most part, Python works\nthe same regardless of what operating system you happen to be using.\nStill, many library developers will unnecessarily exclude half of their\npotential audience by not even attempting to be compatible.\n\nThis session will walk through the things to be aware of when creating\ncross-platform libraries. From simple things like using ``pathlib``\nrather than ``bytes``, through to all the ways you can get builds and\ntests running on Windows for free, by the end of this session you will\nhave a checklist of easy tasks for your project that will really enable\nthe whole Python world to benefit from your work.\n", "duration": 1636, "language": "eng", "recorded": "2019-05-05T13:50:00", "related_urls": [ { "label": "Conference schedule", "url": "https://us.pycon.org/2019/schedule/talks/" }, { "label": "Conference slides (github)", "url": "https://github.com/PyCon/2019-slides" }, { "label": "Conference slides (speakerdeck)", "url": "https://speakerdeck.com/pycon2019" }, { "label": "Talk schedule", "url": "https://us.pycon.org/2019/schedule/presentation/212/" } ], "speakers": [ "<NAME>" ], "tags": [ "talk" ], "thumbnail_url": "https://i.ytimg.com/vi/uoI57uMdDD4/maxresdefault.jpg", "title": "Python on Windows is Okay, Actually", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=uoI57uMdDD4" } ] }
702
758
// // TEBackgroundColorView.h // ThemeEngine // // Created by <NAME> on 6/20/15. // Copyright © 2015 <NAME>. All rights reserved. // #import <Cocoa/Cocoa.h> @interface TEBackgroundColorView : NSView @property (nonatomic, strong) IBInspectable NSColor *backgroundColor; @end
96
336
#ifndef __LISTTRIGGER_H__ #define __LISTTRIGGER_H__ class CWndListTrigger : public CListBox { public: CProviderEnum m_proSync; CProviderEnum m_proType; CProviderEnum m_proSource; CProviderNum m_proLevel; CProviderNum m_proTime; CProviderNum m_proHoldoff; CProviderNum m_proTrigPosition; CLPItem m_itmSync; CLPItem m_itmType; CLPItem m_itmSource; CLPItem m_itmLevel; CLPItem m_itmTime; CLPItem m_itmHoldoff; CLPItem m_itmTrigPosition; // DSO does not allow to change the time offset public: void Create( CWnd* pParent ) { CListBox::Create( "Trigger", WsVisible | WsModal, CRect(120, 55, 319, 201), RGB565(404040), pParent ); m_proSync.Create( (const char**)CSettings::Trigger::ppszTextSync, (NATIVEENUM*)&Settings.Trig.Sync, CSettings::Trigger::_SyncMax ); m_proType.Create( (const char**)CSettings::Trigger::ppszTextType, (NATIVEENUM*)&Settings.Trig.Type, CSettings::Trigger::_TypeMax ); m_proSource.Create( (const char**)CSettings::Trigger::ppszTextSource, (NATIVEENUM*)&Settings.Trig.Source, CSettings::Trigger::_SourceMax ); m_proLevel.Create( &Settings.Trig.nLevel, 0, 255 ); m_proTime.Create( &Settings.Trig.nTime, 0, 4096 ); m_proHoldoff.Create( &Settings.Trig.nHoldOff, 0, 4096 ); m_proTrigPosition.Create( &Settings.Trig.nPosition, 0, 4096 ); m_itmSync.Create( "Mode", CWnd::WsVisible, &m_proSync, this ); m_itmType.Create( "Type", CWnd::WsVisible, &m_proType, this ); m_itmSource.Create( "Source", CWnd::WsVisible, &m_proSource, this ); m_itmLevel.Create( "Threshold", CWnd::WsVisible, &m_proLevel, this ); m_itmTime.Create( "Time", CWnd::WsVisible, &m_proTime, this ); m_itmHoldoff.Create( "HoldOff", CWnd::WsVisible, &m_proHoldoff, this ); m_itmTrigPosition.Create( "Trig. pos", CWnd::WsVisible, &m_proTrigPosition, this ); } }; #endif
773
335
{ "word": "Bombardier", "definitions": [ "A rank of non-commissioned officer in certain artillery regiments, equivalent to corporal.", "A member of a bomber crew in the US air force responsible for aiming and releasing bombs." ], "parts-of-speech": "Noun" }
100
1,780
<filename>api/src/main/java/io/seata/samples/api/service/StorageService.java package io.seata.samples.api.service; import java.sql.SQLException; /** * The interface Storage service. * * @author jimin.jm @<EMAIL> * @date 2019 /08/21 */ public interface StorageService extends DataResetService { /** * Deduct. * * @param commodityCode the commodity code * @param count the count * @throws SQLException the sql exception */ void deduct(String commodityCode, int count) throws SQLException; }
200
1,431
/* ==================================================================== 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.poi.sl.usermodel; import org.apache.poi.util.StringUtil; /** * known preset shape geometries in PresentationML */ public enum ShapeType { NOT_PRIMITIVE(-1, 0, "NotPrimitive"), LINE(1, 20, "Line"), LINE_INV(2, -1, null), TRIANGLE(3, 5, "IsocelesTriangle"), RT_TRIANGLE(4, 6, "RightTriangle"), RECT(5, 1, "Rectangle"), DIAMOND(6, 4, "Diamond"), PARALLELOGRAM(7, 7, "Parallelogram"), TRAPEZOID(8, 8, "Trapezoid"), NON_ISOSCELES_TRAPEZOID(9, -1, null), PENTAGON(10, 56, "Pentagon"), HEXAGON(11, 9, "Hexagon"), HEPTAGON(12, -1, null), OCTAGON(13, 10, "Octagon"), DECAGON(14, -1, null), DODECAGON(15, -1, null), STAR_4(16, 187, "Star4"), STAR_5(17, 12, "Star"), // aka star in native STAR_6(18, -1, null), STAR_7(19, -1, null), STAR_8(20, 58, "Star8"), STAR_10(21, -1, null), STAR_12(22, -1, null), STAR_16(23, 59, "Star16"), SEAL(23, 18, "Seal"), // same as star_16, but twice in native STAR_24(24, 92, "Star24"), STAR_32(25, 60, "Star32"), ROUND_RECT(26, 2, "RoundRectangle"), ROUND_1_RECT(27, -1, null), ROUND_2_SAME_RECT(28, -1, null), ROUND_2_DIAG_RECT(29, -1, null), SNIP_ROUND_RECT(30, -1, null), SNIP_1_RECT(31, -1, null), SNIP_2_SAME_RECT(32, -1, null), SNIP_2_DIAG_RECT(33, -1, null), PLAQUE(34, 21, "Plaque"), ELLIPSE(35, 3, "Ellipse"), TEARDROP(36, -1, null), HOME_PLATE(37, 15, "HomePlate"), CHEVRON(38, 55, "Chevron"), PIE_WEDGE(39, -1, null), PIE(40, -1, null), BLOCK_ARC(41, 95, "BlockArc"), DONUT(42, 23, "Donut"), NO_SMOKING(43, 57, "NoSmoking"), RIGHT_ARROW(44, 13, "Arrow"), // aka arrow in native LEFT_ARROW(45, 66, "LeftArrow"), UP_ARROW(46, 68, "UpArrow"), DOWN_ARROW(47, 67, "DownArrow"), STRIPED_RIGHT_ARROW(48, 93, "StripedRightArrow"), NOTCHED_RIGHT_ARROW(49, 94, "NotchedRightArrow"), BENT_UP_ARROW(50, 90, "BentUpArrow"), LEFT_RIGHT_ARROW(51, 69, "LeftRightArrow"), UP_DOWN_ARROW(52, 70, "UpDownArrow"), LEFT_UP_ARROW(53, 89, "LeftUpArrow"), LEFT_RIGHT_UP_ARROW(54, 182, "LeftRightUpArrow"), QUAD_ARROW(55, 76, "QuadArrow"), LEFT_ARROW_CALLOUT(56, 77, "LeftArrowCallout"), RIGHT_ARROW_CALLOUT(57, 78, "RightArrowCallout"), UP_ARROW_CALLOUT(58, 79, "UpArrowCallout"), DOWN_ARROW_CALLOUT(59, 80, "DownArrowCallout"), LEFT_RIGHT_ARROW_CALLOUT(60, 81, "LeftRightArrowCallout"), UP_DOWN_ARROW_CALLOUT(61, 82, "UpDownArrowCallout"), QUAD_ARROW_CALLOUT(62, 83, "QuadArrowCallout"), BENT_ARROW(63, 91, "BentArrow"), UTURN_ARROW(64, 101, "UturnArrow"), CIRCULAR_ARROW(65, 99, "CircularArrow"), LEFT_CIRCULAR_ARROW(66, -1, null), LEFT_RIGHT_CIRCULAR_ARROW(67, -1, null), CURVED_RIGHT_ARROW(68, 102, "CurvedRightArrow"), CURVED_LEFT_ARROW(69, 103, "CurvedLeftArrow"), CURVED_UP_ARROW(70, 104, "CurvedUpArrow"), CURVED_DOWN_ARROW(71, 105, "CurvedDownArrow"), SWOOSH_ARROW(72, -1, null), CUBE(73, 16, "Cube"), CAN(74, 22, "Can"), LIGHTNING_BOLT(75, 73, "LightningBolt"), HEART(76, 74, "Heart"), SUN(77, 183, "Sun"), MOON(78, 184, "Moon"), SMILEY_FACE(79, 96, "SmileyFace"), IRREGULAR_SEAL_1(80, 71, "IrregularSeal1"), IRREGULAR_SEAL_2(81, 72, "IrregularSeal2"), FOLDED_CORNER(82, 65, "FoldedCorner"), BEVEL(83, 84, "Bevel"), FRAME(84, 75, "PictureFrame"), HALF_FRAME(85, -1, null), CORNER(86, -1, null), DIAG_STRIPE(87, -1, null), CHORD(88, -1, null), ARC(89, 19, "Arc"), LEFT_BRACKET(90, 85, "LeftBracket"), RIGHT_BRACKET(91, 86, "RightBracket"), LEFT_BRACE(92, 87, "LeftBrace"), RIGHT_BRACE(93, 88, "RightBrace"), BRACKET_PAIR(94, 185, "BracketPair"), BRACE_PAIR(95, 186, "BracePair"), STRAIGHT_CONNECTOR_1(96, 32, "StraightConnector1"), BENT_CONNECTOR_2(97, 33, "BentConnector2"), BENT_CONNECTOR_3(98, 34, "BentConnector3"), BENT_CONNECTOR_4(99, 35, "BentConnector4"), BENT_CONNECTOR_5(100, 36, "BentConnector5"), CURVED_CONNECTOR_2(101, 37, "CurvedConnector2"), CURVED_CONNECTOR_3(102, 38, "CurvedConnector3"), CURVED_CONNECTOR_4(103, 39, "CurvedConnector4"), CURVED_CONNECTOR_5(104, 40, "CurvedConnector5"), CALLOUT_1(105, 41, "Callout1"), CALLOUT_2(106, 42, "Callout2"), CALLOUT_3(107, 43, "Callout3"), ACCENT_CALLOUT_1(108, 44, "AccentCallout1"), ACCENT_CALLOUT_2(109, 45, "AccentCallout2"), ACCENT_CALLOUT_3(110, 46, "AccentCallout3"), BORDER_CALLOUT_1(111, 47, "BorderCallout1"), BORDER_CALLOUT_2(112, 48, "BorderCallout2"), BORDER_CALLOUT_3(113, 49, "BorderCallout3"), ACCENT_BORDER_CALLOUT_1(114, 50, "AccentBorderCallout1"), ACCENT_BORDER_CALLOUT_2(115, 51, "AccentBorderCallout2"), ACCENT_BORDER_CALLOUT_3(116, 52, "AccentBorderCallout3"), WEDGE_RECT_CALLOUT(117, 61, "WedgeRectCallout"), WEDGE_ROUND_RECT_CALLOUT(118, 62, "WedgeRRectCallout"), WEDGE_ELLIPSE_CALLOUT(119, 63, "WedgeEllipseCallout"), CLOUD_CALLOUT(120, 106, "CloudCallout"), CLOUD(121, -1, null), RIBBON(122, 53, "Ribbon"), RIBBON_2(123, 54, "Ribbon2"), ELLIPSE_RIBBON(124, 107, "EllipseRibbon"), ELLIPSE_RIBBON_2(125, 108, "EllipseRibbon2"), LEFT_RIGHT_RIBBON(126, -1, null), VERTICAL_SCROLL(127, 97, "VerticalScroll"), HORIZONTAL_SCROLL(128, 98, "HorizontalScroll"), WAVE(129, 64, "Wave"), DOUBLE_WAVE(130, 188, "DoubleWave"), PLUS(131, 11, "Plus"), FLOW_CHART_PROCESS(132, 109, "FlowChartProcess"), FLOW_CHART_DECISION(133, 110, "FlowChartDecision"), FLOW_CHART_INPUT_OUTPUT(134, 111, "FlowChartInputOutput"), FLOW_CHART_PREDEFINED_PROCESS(135, 112, "FlowChartPredefinedProcess"), FLOW_CHART_INTERNAL_STORAGE(136, 113, "FlowChartInternalStorage"), FLOW_CHART_DOCUMENT(137, 114, "FlowChartDocument"), FLOW_CHART_MULTIDOCUMENT(138, 115, "FlowChartMultidocument"), FLOW_CHART_TERMINATOR(139, 116, "FlowChartTerminator"), FLOW_CHART_PREPARATION(140, 117, "FlowChartPreparation"), FLOW_CHART_MANUAL_INPUT(141, 118, "FlowChartManualInput"), FLOW_CHART_MANUAL_OPERATION(142, 119, "FlowChartManualOperation"), FLOW_CHART_CONNECTOR(143, 120, "FlowChartConnector"), FLOW_CHART_PUNCHED_CARD(144, 121, "FlowChartPunchedCard"), FLOW_CHART_PUNCHED_TAPE(145, 122, "FlowChartPunchedTape"), FLOW_CHART_SUMMING_JUNCTION(146, 123, "FlowChartSummingJunction"), FLOW_CHART_OR(147, 124, "FlowChartOr"), FLOW_CHART_COLLATE(148, 125, "FlowChartCollate"), FLOW_CHART_SORT(149, 126, "FlowChartSort"), FLOW_CHART_EXTRACT(150, 127, "FlowChartExtract"), FLOW_CHART_MERGE(151, 128, "FlowChartMerge"), FLOW_CHART_OFFLINE_STORAGE(152, 129, "FlowChartOfflineStorage"), FLOW_CHART_ONLINE_STORAGE(153, 130, "FlowChartOnlineStorage"), FLOW_CHART_MAGNETIC_TAPE(154, 131, "FlowChartMagneticTape"), FLOW_CHART_MAGNETIC_DISK(155, 132, "FlowChartMagneticDisk"), FLOW_CHART_MAGNETIC_DRUM(156, 133, "FlowChartMagneticDrum"), FLOW_CHART_DISPLAY(157, 134, "FlowChartDisplay"), FLOW_CHART_DELAY(158, 135, "FlowChartDelay"), FLOW_CHART_ALTERNATE_PROCESS(159, 176, "FlowChartAlternateProcess"), FLOW_CHART_OFFPAGE_CONNECTOR(160, 177, "FlowChartOffpageConnector"), ACTION_BUTTON_BLANK(161, 189, "ActionButtonBlank"), ACTION_BUTTON_HOME(162, 190, "ActionButtonHome"), ACTION_BUTTON_HELP(163, 191, "ActionButtonHelp"), ACTION_BUTTON_INFORMATION(164, 192, "ActionButtonInformation"), ACTION_BUTTON_FORWARD_NEXT(165, 193, "ActionButtonForwardNext"), ACTION_BUTTON_BACK_PREVIOUS(166, 194, "ActionButtonBackPrevious"), ACTION_BUTTON_END(167, 195, "ActionButtonEnd"), ACTION_BUTTON_BEGINNING(168, 196, "ActionButtonBeginning"), ACTION_BUTTON_RETURN(169, 197, "ActionButtonReturn"), ACTION_BUTTON_DOCUMENT(170, 198, "ActionButtonDocument"), ACTION_BUTTON_SOUND(171, 199, "ActionButtonSound"), ACTION_BUTTON_MOVIE(172, 200, "ActionButtonMovie"), GEAR_6(173, -1, null), GEAR_9(174, -1, null), FUNNEL(175, -1, null), MATH_PLUS(176, -1, null), MATH_MINUS(177, -1, null), MATH_MULTIPLY(178, -1, null), MATH_DIVIDE(179, -1, null), MATH_EQUAL(180, -1, null), MATH_NOT_EQUAL(181, -1, null), CORNER_TABS(182, -1, null), SQUARE_TABS(183, -1, null), PLAQUE_TABS(184, -1, null), CHART_X(185, -1, null), CHART_STAR(186, -1, null), CHART_PLUS(187, -1, null), // below are shape types only found in native NOTCHED_CIRCULAR_ARROW(-1, 100, "NotchedCircularArrow"), THICK_ARROW(-1, 14, "ThickArrow"), BALLOON(-1, 17, "Balloon"), TEXT_SIMPLE(-1, 24, "TextSimple"), TEXT_OCTAGON(-1, 25, "TextOctagon"), TEXT_HEXAGON(-1, 26, "TextHexagon"), TEXT_CURVE(-1, 27, "TextCurve"), TEXT_WAVE(-1, 28, "TextWave"), TEXT_RING(-1, 29, "TextRing"), TEXT_ON_CURVE(-1, 30, "TextOnCurve"), TEXT_ON_RING(-1, 31, "TextOnRing"), TEXT_PLAIN_TEXT(-1, 136, "TextPlainText"), TEXT_STOP(-1, 137, "TextStop"), TEXT_TRIANGLE(-1, 138, "TextTriangle"), TEXT_TRIANGLE_INVERTED(-1, 139, "TextTriangleInverted"), TEXT_CHEVRON(-1, 140, "TextChevron"), TEXT_CHEVRON_INVERTED(-1, 141, "TextChevronInverted"), TEXT_RING_INSIDE(-1, 142, "TextRingInside"), TEXT_RING_OUTSIDE(-1, 143, "TextRingOutside"), TEXT_ARCH_UP_CURVE(-1, 144, "TextArchUpCurve"), TEXT_ARCH_DOWN_CURVE(-1, 145, "TextArchDownCurve"), TEXT_CIRCLE_CURVE(-1, 146, "TextCircleCurve"), TEXT_BUTTON_CURVE(-1, 147, "TextButtonCurve"), TEXT_ARCH_UP_POUR(-1, 148, "TextArchUpPour"), TEXT_ARCH_DOWN_POUR(-1, 149, "TextArchDownPour"), TEXT_CIRCLE_POUR(-1, 150, "TextCirclePour"), TEXT_BUTTON_POUR(-1, 151, "TextButtonPour"), TEXT_CURVE_UP(-1, 152, "TextCurveUp"), TEXT_CURVE_DOWN(-1, 153, "TextCurveDown"), TEXT_CASCADE_UP(-1, 154, "TextCascadeUp"), TEXT_CASCADE_DOWN(-1, 155, "TextCascadeDown"), TEXT_WAVE_1(-1, 156, "TextWave1"), TEXT_WAVE_2(-1, 157, "TextWave2"), TEXT_WAVE_3(-1, 158, "TextWave3"), TEXT_WAVE_4(-1, 159, "TextWave4"), TEXT_INFLATE(-1, 160, "TextInflate"), TEXT_DEFLATE(-1, 161, "TextDeflate"), TEXT_INFLATE_BOTTOM(-1, 162, "TextInflateBottom"), TEXT_DEFLATE_BOTTOM(-1, 163, "TextDeflateBottom"), TEXT_INFLATE_TOP(-1, 164, "TextInflateTop"), TEXT_DEFLATE_TOP(-1, 165, "TextDeflateTop"), TEXT_DEFLATE_INFLATE(-1, 166, "TextDeflateInflate"), TEXT_DEFLATE_INFLATE_DEFLATE(-1, 167, "TextDeflateInflateDeflate"), TEXT_FADE_RIGHT(-1, 168, "TextFadeRight"), TEXT_FADE_LEFT(-1, 169, "TextFadeLeft"), TEXT_FADE_UP(-1, 170, "TextFadeUp"), TEXT_FADE_DOWN(-1, 171, "TextFadeDown"), TEXT_SLANT_UP(-1, 172, "TextSlantUp"), TEXT_SLANT_DOWN(-1, 173, "TextSlantDown"), TEXT_CAN_UP(-1, 174, "TextCanUp"), TEXT_CAN_DOWN(-1, 175, "TextCanDown"), CALLOUT_90(-1, 178, "Callout90"), ACCENT_CALLOUT_90(-1, 179, "AccentCallout90"), BORDER_CALLOUT_90(-1, 180, "BorderCallout90"), ACCENT_BORDER_CALLOUT_90(-1, 181, "AccentBorderCallout90"), HOST_CONTROL(-1, 201, "HostControl"), TEXT_BOX(-1, 202, "TextBox") ; /** Preset-ID for XML-based shapes */ public final int ooxmlId; /** Preset-ID for binary-based shapes */ public final int nativeId; /** POI-specific name for the binary-based type */ public final String nativeName; ShapeType(int ooxmlId, int nativeId, String nativeName){ this.ooxmlId = ooxmlId; this.nativeId = nativeId; this.nativeName = nativeName; } /** name of the presetShapeDefinit(i)on entry */ public String getOoxmlName() { if (this == SEAL) return STAR_16.getOoxmlName(); if (ooxmlId == -1) { return (name().startsWith("TEXT")) ? RECT.getOoxmlName() : null; } StringBuilder sb = new StringBuilder(); boolean toLower = true; for (char ch : name().toCharArray()) { if (ch == '_') { toLower = false; continue; } sb.append(toLower ? StringUtil.toLowerCase(ch) : StringUtil.toUpperCase(ch)); toLower = true; } return sb.toString(); } public static ShapeType forId(int id, boolean isOoxmlId){ // exemption for #60294 if (!isOoxmlId && id == 0x0FFF) { return NOT_PRIMITIVE; } for(ShapeType t : values()){ if((isOoxmlId && t.ooxmlId == id) || (!isOoxmlId && t.nativeId == id)) return t; } throw new IllegalArgumentException("Unknown shape type: " + id); } }
6,215
4,505
{ "methodConfig": [{ "name": [{ "service": "google.cloud.clouddms.v1.DataMigrationService" }], "timeout": "60s", "retryPolicy": { "maxAttempts": 5, "initialBackoff": "1s", "maxBackoff": "10s", "backoffMultiplier": 1.3, "retryableStatusCodes": ["UNAVAILABLE"] } }, { "name": [ { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "CreateConnectionProfile" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "GetConnectionProfile" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "ListConnectionProfiles" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "UpdateConnectionProfile" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "DeleteConnectionProfile" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "CreateMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "GetMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "ListMigrationJobs" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "UpdateMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "DeleteMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "StartMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "StopMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "VerifyMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "ResumeMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "RestartMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "PromoteMigrationJob" }, { "service": "google.cloud.clouddms.v1.DataMigrationService", "method": "GenerateSshScript" } ], "timeout": "60s" }] }
832
435
{ "copyright_text": "Standard YouTube License", "description": "Most of us regularly work with Jupyter notebooks, but fail to see obvious productivity gains involving its usage. Did you know that the web interface works like a modal editor such as VIM? Do you know that you can actually profile AND debug code in notebooks? How about setting formulas or use pre-made style settings for visualizations? Let us go through the tricks of the trade together!\n\n**Abstract**\n\nOverview of the Jupyter project + setup to get everyone on board.\nHandling the UI, know the shortcuts\nDifferent type of cells\nExporting notebooks for presentations\nHandling different kernels\nSet styles for visualizations for professional quality\nMod the style of the web interface yourself via CSS\nProfiling code in notebooks, use Cython\nDebugging in notebooks\n\n", "duration": 6239, "language": "eng", "recorded": "2017-06-30", "related_urls": [ { "label": "schedule", "url": "https://pydata.org/berlin2017/schedule/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/b8g-8T0amuk/maxresdefault.jpg", "title": "Leveling up your Jupyter notebook skills", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=b8g-8T0amuk" } ] }
432
354
/* Using ESP32 RMT to read servo pulses sent by radio remote control receiver. Publishes result to a queue of joy_msg. Reference: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/rmt.html Reference: https://github.com/JustinOng/sumo/blob/master/software/sumo/src/configure_rmt.c (via https://www.reddit.com/r/esp32/comments/bivbz1/can_a_esp32_read_the_pwm_signal_of_a_rc_receiver/) Copyright (c) <NAME> MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef INC_JOY_RMT_RC_H #define INC_JOY_RMT_RC_H #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/task.h" #include "driver/rmt.h" #include <joy_msg.h> #include "gpio_assignments.h" #ifdef USE_JOY_RMT_RC /* * @brief Structure to hold RMT configuration information specific to a channel */ typedef struct rmt_rc_channel { rmt_channel_t channel; gpio_num_t pin; } rmt_rc_channel; /* * @brief Array of channel-specific RMT configuration parameters */ static const rmt_rc_channel rc_channels[axis_count] = { // axis_steer { RMT_CHANNEL_0, joy_rmt_rc_steer, }, // axis_speed { RMT_CHANNEL_1, joy_rmt_rc_speed, }, // axis_aux { RMT_CHANNEL_2, joy_rmt_rc_aux, } }; /* * @brief Divide RMT 80MHz by 80 = 1MHz = Each tick is 1us (microsecond) */ static const uint8_t rmt_clock_divider = 80; /* * @brief Go into idle after inaction longer than 7ms = 7000us */ static const uint16_t rmt_idle_threshold = 7000; /* * @brief Signal shorter than 0.25ms = 250us will be ignored as noise */ static const uint8_t rmt_filter_threshold = 250; /* * @brief RC receiver usually sends 1ms = 1000us on the low end */ static const uint16_t rc_receive_min = 1000; /* * @brief RC receiver usually sends 1.5ms = 1500us as center position */ static const uint16_t rc_receive_mid = 1500; /* * @brief RC receiver usually sends 2ms = 2000us on the high end */ static const uint16_t rc_receive_max = 2000; /* * @brief FreeRTOS task which reads servo control signals sent by radio * remote control receiver and translate them to joystick message. * @param pvParam QueueHandle to joy_msg mailbox. */ void joy_rmt_rc_read_task(void* pvParam); #endif // #ifdef USE_JOY_RMT_RC #endif // #ifndef INC_JOY_RMT_RC_H
1,129
2,095
<filename>benchmarks/src/main/java/io/rsocket/metadata/WellKnownMimeTypePerf.java package io.rsocket.metadata; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; @BenchmarkMode(Mode.Throughput) @Fork(value = 1) @Warmup(iterations = 10) @Measurement(iterations = 10) @State(Scope.Thread) public class WellKnownMimeTypePerf { // this is the old values() looping implementation of fromIdentifier private WellKnownMimeType fromIdValuesLoop(int id) { if (id < 0 || id > 127) { return WellKnownMimeType.UNPARSEABLE_MIME_TYPE; } for (WellKnownMimeType value : WellKnownMimeType.values()) { if (value.getIdentifier() == id) { return value; } } return WellKnownMimeType.UNKNOWN_RESERVED_MIME_TYPE; } // this is the core of the old values() looping implementation of fromString private WellKnownMimeType fromStringValuesLoop(String mimeType) { for (WellKnownMimeType value : WellKnownMimeType.values()) { if (mimeType.equals(value.getString())) { return value; } } return WellKnownMimeType.UNPARSEABLE_MIME_TYPE; } @Benchmark public void fromIdArrayLookup(final Blackhole bh) { // negative lookup bh.consume(WellKnownMimeType.fromIdentifier(-10)); bh.consume(WellKnownMimeType.fromIdentifier(-1)); // too large lookup bh.consume(WellKnownMimeType.fromIdentifier(129)); // first lookup bh.consume(WellKnownMimeType.fromIdentifier(0)); // middle lookup bh.consume(WellKnownMimeType.fromIdentifier(37)); // reserved lookup bh.consume(WellKnownMimeType.fromIdentifier(63)); // last lookup bh.consume(WellKnownMimeType.fromIdentifier(127)); } @Benchmark public void fromIdValuesLoopLookup(final Blackhole bh) { // negative lookup bh.consume(fromIdValuesLoop(-10)); bh.consume(fromIdValuesLoop(-1)); // too large lookup bh.consume(fromIdValuesLoop(129)); // first lookup bh.consume(fromIdValuesLoop(0)); // middle lookup bh.consume(fromIdValuesLoop(37)); // reserved lookup bh.consume(fromIdValuesLoop(63)); // last lookup bh.consume(fromIdValuesLoop(127)); } @Benchmark public void fromStringMapLookup(final Blackhole bh) { // unknown lookup bh.consume(WellKnownMimeType.fromString("foo/bar")); // first lookup bh.consume(WellKnownMimeType.fromString(WellKnownMimeType.APPLICATION_AVRO.getString())); // middle lookup bh.consume(WellKnownMimeType.fromString(WellKnownMimeType.VIDEO_VP8.getString())); // last lookup bh.consume( WellKnownMimeType.fromString( WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString())); } @Benchmark public void fromStringValuesLoopLookup(final Blackhole bh) { // unknown lookup bh.consume(fromStringValuesLoop("foo/bar")); // first lookup bh.consume(fromStringValuesLoop(WellKnownMimeType.APPLICATION_AVRO.getString())); // middle lookup bh.consume(fromStringValuesLoop(WellKnownMimeType.VIDEO_VP8.getString())); // last lookup bh.consume( fromStringValuesLoop(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString())); } }
1,239
399
/* * Copyright (c) 2017-2020, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Stringify is a simple utility to convert text files to C string literals. */ #include <fstream> #include <iostream> #include <sstream> #include <string> // Replaces non-alphanumeric characters with '_' and // prepends '_' if the string begins with a digit. std::string sanitize_varname(std::string const& s) { std::string r = s; if (std::isdigit(r[0])) { r = '_' + r; } for (std::string::iterator it = r.begin(); it != r.end(); ++it) { if (!std::isalnum(*it)) { *it = '_'; } } return r; } // Replaces " with \" std::string sanitize_string_literal(std::string const& s) { std::stringstream ss; for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) { if (*it == '"' || *it == '\\') { ss << '\\'; } ss << *it; } return ss.str(); } int main(int argc, char* argv[]) { if (argc <= 1 || argv[1][0] == '-') { std::cout << "Stringify - Converts text files to C string literals" << std::endl; std::cout << "Usage: " << argv[0] << " infile [varname] > outfile" << std::endl; return -1; } char* filename = argv[1]; std::string varname = (argc > 2) ? argv[2] : sanitize_varname(filename); std::ifstream istream(filename); std::ostream& ostream = std::cout; std::string line; // Note: This puts "filename\n" at the beginning of the string, which is // what jitify expects. ostream << "const char* const " << varname << " = " << "\"" << filename << "\\n\"" << std::endl; while (std::getline(istream, line)) { ostream << "\"" << sanitize_string_literal(line) << "\\n\"" << std::endl; } ostream << ";" << std::endl; return 0; }
1,129
1,002
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. // This file was automatically generated. Please do not edit it manually. #include "pch.h" #include "EdgeDetectionEffect.h" #if (defined _WIN32_WINNT_WIN10) && (WINVER >= _WIN32_WINNT_WIN10) namespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace Effects { EdgeDetectionEffect::EdgeDetectionEffect(ICanvasDevice* device, ID2D1Effect* effect) : CanvasEffect(EffectId(), 5, 1, true, device, effect, static_cast<IEdgeDetectionEffect*>(this)) { if (!effect) { // Set default values SetBoxedProperty<float>(D2D1_EDGEDETECTION_PROP_STRENGTH, 0.5f); SetBoxedProperty<float>(D2D1_EDGEDETECTION_PROP_BLUR_RADIUS, 0.0f); SetBoxedProperty<uint32_t>(D2D1_EDGEDETECTION_PROP_MODE, EdgeDetectionEffectMode::Sobel); SetBoxedProperty<boolean>(D2D1_EDGEDETECTION_PROP_OVERLAY_EDGES, static_cast<boolean>(false)); SetBoxedProperty<uint32_t>(D2D1_EDGEDETECTION_PROP_ALPHA_MODE, D2D1_COLORMANAGEMENT_ALPHA_MODE_PREMULTIPLIED); } } IMPLEMENT_EFFECT_PROPERTY_WITH_VALIDATION(EdgeDetectionEffect, Amount, float, float, D2D1_EDGEDETECTION_PROP_STRENGTH, (value >= 0.0f) && (value <= 1.0f)) IMPLEMENT_EFFECT_PROPERTY_WITH_VALIDATION(EdgeDetectionEffect, BlurAmount, float, float, D2D1_EDGEDETECTION_PROP_BLUR_RADIUS, (value >= 0.0f) && (value <= 10.0f)) IMPLEMENT_EFFECT_PROPERTY(EdgeDetectionEffect, Mode, uint32_t, EdgeDetectionEffectMode, D2D1_EDGEDETECTION_PROP_MODE) IMPLEMENT_EFFECT_PROPERTY(EdgeDetectionEffect, OverlayEdges, boolean, boolean, D2D1_EDGEDETECTION_PROP_OVERLAY_EDGES) IMPLEMENT_EFFECT_PROPERTY(EdgeDetectionEffect, AlphaMode, ConvertAlphaMode, CanvasAlphaMode, D2D1_EDGEDETECTION_PROP_ALPHA_MODE) IMPLEMENT_EFFECT_SOURCE_PROPERTY(EdgeDetectionEffect, Source, 0) IMPLEMENT_EFFECT_PROPERTY_MAPPING(EdgeDetectionEffect, { L"Amount", D2D1_EDGEDETECTION_PROP_STRENGTH, GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT }, { L"BlurAmount", D2D1_EDGEDETECTION_PROP_BLUR_RADIUS, GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT }, { L"Mode", D2D1_EDGEDETECTION_PROP_MODE, GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT }, { L"OverlayEdges", D2D1_EDGEDETECTION_PROP_OVERLAY_EDGES, GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT }, { L"AlphaMode", D2D1_EDGEDETECTION_PROP_ALPHA_MODE, GRAPHICS_EFFECT_PROPERTY_MAPPING_COLORMATRIX_ALPHA_MODE }) ActivatableClassWithFactory(EdgeDetectionEffect, ::SimpleAgileActivationFactory<EdgeDetectionEffect>); }}}}} #endif // _WIN32_WINNT_WIN10
1,446
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-p27x-w8mq-85x6", "modified": "2022-05-01T23:42:11Z", "published": "2022-05-01T23:42:11Z", "aliases": [ "CVE-2008-1647" ], "details": "The ChilkatHttp.ChilkatHttp.1 and ChilkatHttp.ChilkatHttpRequest.1 ActiveX controls in ChilkatHttp.dll 2.4.0.0, 2.3.0.0, and earlier in ChilkatHttp ActiveX expose the unsafe SaveLastError method, which allows remote attackers to overwrite arbitrary files. NOTE: some of these details are obtained from third party information.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2008-1647" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/45988" }, { "type": "WEB", "url": "https://www.exploit-db.com/exploits/5338" }, { "type": "WEB", "url": "http://secunia.com/advisories/29581" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/28546" }, { "type": "WEB", "url": "http://www.shinnai.altervista.org/index.php?mod=02_Forum&group=Security&argument=Remote_performed_exploits&topic=1207033569.ff.php" }, { "type": "WEB", "url": "http://www.vupen.com/english/advisories/2008/1050/references" } ], "database_specific": { "cwe_ids": [ "CWE-20" ], "severity": "HIGH", "github_reviewed": false } }
695
1,391
<reponame>newluhux/plan9port /*#pragma varargck argpos editerror 1*/ typedef struct Addr Addr; typedef struct Address Address; typedef struct Cmd Cmd; typedef struct List List; typedef struct String String; struct String { int n; /* excludes NUL */ Rune *r; /* includes NUL */ int nalloc; }; struct Addr { char type; /* # (char addr), l (line addr), / ? . $ + - , ; */ union{ String *re; Addr *left; /* left side of , and ; */ } u; ulong num; Addr *next; /* or right side of , and ; */ }; struct Address { Range r; File *f; }; struct Cmd { Addr *addr; /* address (range of text) */ String *re; /* regular expression for e.g. 'x' */ union{ Cmd *cmd; /* target of x, g, {, etc. */ String *text; /* text of a, c, i; rhs of s */ Addr *mtaddr; /* address for m, t */ } u; Cmd *next; /* pointer to next element in {} */ short num; ushort flag; /* whatever */ ushort cmdc; /* command character; 'x' etc. */ }; extern struct cmdtab{ ushort cmdc; /* command character */ uchar text; /* takes a textual argument? */ uchar regexp; /* takes a regular expression? */ uchar addr; /* takes an address (m or t)? */ uchar defcmd; /* default command; 0==>none */ uchar defaddr; /* default address */ uchar count; /* takes a count e.g. s2/// */ char *token; /* takes text terminated by one of these */ int (*fn)(Text*, Cmd*); /* function to call with parse tree */ }cmdtab[]; #define INCR 25 /* delta when growing list */ struct List /* code depends on a long being able to hold a pointer */ { int nalloc; int nused; union{ void *listptr; void* *ptr; uchar* *ucharptr; String* *stringptr; } u; }; enum Defaddr{ /* default addresses */ aNo, aDot, aAll }; int nl_cmd(Text*, Cmd*), a_cmd(Text*, Cmd*), b_cmd(Text*, Cmd*); int c_cmd(Text*, Cmd*), d_cmd(Text*, Cmd*); int B_cmd(Text*, Cmd*), D_cmd(Text*, Cmd*), e_cmd(Text*, Cmd*); int f_cmd(Text*, Cmd*), g_cmd(Text*, Cmd*), i_cmd(Text*, Cmd*); int k_cmd(Text*, Cmd*), m_cmd(Text*, Cmd*), n_cmd(Text*, Cmd*); int p_cmd(Text*, Cmd*); int s_cmd(Text*, Cmd*), u_cmd(Text*, Cmd*), w_cmd(Text*, Cmd*); int x_cmd(Text*, Cmd*), X_cmd(Text*, Cmd*), pipe_cmd(Text*, Cmd*); int eq_cmd(Text*, Cmd*); String *allocstring(int); void freestring(String*); String *getregexp(int); Addr *newaddr(void); Address cmdaddress(Addr*, Address, int); int cmdexec(Text*, Cmd*); void editerror(char*, ...); int cmdlookup(int); void resetxec(void); void Straddc(String*, int);
1,086
311
<reponame>zcf7822/joyqueue /** * Copyright 2019 The JoyQueue Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joyqueue.broker.kafka.session; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.apache.commons.lang3.StringUtils; import org.joyqueue.broker.kafka.command.ApiVersionsRequest; import org.joyqueue.broker.kafka.command.FetchRequest; import org.joyqueue.broker.kafka.command.FindCoordinatorRequest; import org.joyqueue.broker.kafka.command.ProduceRequest; import org.joyqueue.network.session.Language; import org.joyqueue.network.transport.ChannelTransport; import org.joyqueue.network.transport.TransportHelper; import org.joyqueue.network.transport.command.Command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; /** * kafka连接处理 * * author: gaohaoxiang * date: 2018/7/3 */ @ChannelHandler.Sharable public class KafkaConnectionHandler extends ChannelDuplexHandler { protected static final Logger logger = LoggerFactory.getLogger(KafkaConnectionHandler.class); private KafkaConnectionManager kafkaConnectionManager; public KafkaConnectionHandler(KafkaConnectionManager kafkaConnectionManager) { this.kafkaConnectionManager = kafkaConnectionManager; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof Command) { boolean handleConnection = this.handleConnection(ctx, (Command) msg); if (!handleConnection) { ctx.channel().close(); return; } } super.channelRead(ctx, msg); } protected boolean handleConnection(ChannelHandlerContext ctx, Command command) { Channel channel = ctx.channel(); Object payload = command.getPayload(); ChannelTransport transport = TransportHelper.getTransport(channel); if (payload instanceof FetchRequest) { FetchRequest fetchRequest = (FetchRequest) payload; if (!kafkaConnectionManager.addConnection(transport, fetchRequest.getClientId(), String.valueOf(fetchRequest.getVersion()))) { return false; } for (Map.Entry<String, List<FetchRequest.PartitionRequest>> entry : fetchRequest.getPartitionRequests().entrySet()) { kafkaConnectionManager.addConsumer(transport, entry.getKey()); } } else if (payload instanceof ProduceRequest) { ProduceRequest produceRequest = (ProduceRequest) payload; if (!kafkaConnectionManager.addConnection(transport, produceRequest.getClientId(), String.valueOf(produceRequest.getVersion()))) { return false; } for (Map.Entry<String, List<ProduceRequest.PartitionRequest>> entry : produceRequest.getPartitionRequests().entrySet()) { kafkaConnectionManager.addProducer(transport, entry.getKey()); } } else if (payload instanceof FindCoordinatorRequest) { // FindCoordinatorRequest findCoordinatorRequest = (FindCoordinatorRequest) payload; // kafkaConnectionManager.addGroup(transport, findCoordinatorRequest.getCoordinatorKey()); } else if (payload instanceof ApiVersionsRequest) { ApiVersionsRequest apiVersionsRequest = (ApiVersionsRequest) payload; if (StringUtils.isBlank(apiVersionsRequest.getClientSoftwareVersion())) { return true; } String language = StringUtils.replace(apiVersionsRequest.getClientSoftwareName(), "apache-kafka-", ""); String version = apiVersionsRequest.getClientSoftwareVersion(); if (Language.parse(language).equals(Language.OTHER)) { version = apiVersionsRequest.getClientSoftwareName() + "-" + apiVersionsRequest.getClientSoftwareVersion(); } if (!kafkaConnectionManager.addConnection(transport, apiVersionsRequest.getClientId(), version, Language.parse(language))) { return false; } } return true; } }
1,718
491
<gh_stars>100-1000 package net.andreinc.mockneat.unit.companies; import net.andreinc.mockneat.MockNeat; import net.andreinc.mockneat.abstraction.MockUnitBase; import net.andreinc.mockneat.abstraction.MockUnitString; import java.util.function.Supplier; import static net.andreinc.mockneat.types.enums.DictType.DEPARTMENTS; public class Departments extends MockUnitBase implements MockUnitString { /** * <p>Returns a {@code Departments} object that can be used to generate arbitrary names representing department names from a company.</p> * * @return A re-usable {@code Departments} object. The {@code Departments} class is implementing {@code MockUnitString}. */ public static Departments departments() { return MockNeat.threadLocal().departments(); } protected Departments() { } public Departments(MockNeat mockNeat) { super(mockNeat); } @Override public Supplier<String> supplier() { return mockNeat.dicts().type(DEPARTMENTS).supplier(); } }
362
308
<filename>AppCenterAnalytics/AppCenterAnalytics/include/AppCenterAnalytics.h<gh_stars>100-1000 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #import <Foundation/Foundation.h> #if __has_include(<AppCenterAnalytics/MSACAnalytics.h>) #import <AppCenterAnalytics/MSACAnalytics.h> #import <AppCenterAnalytics/MSACAnalyticsAuthenticationProvider.h> #import <AppCenterAnalytics/MSACAnalyticsAuthenticationProviderDelegate.h> #import <AppCenterAnalytics/MSACAnalyticsTransmissionTarget.h> #import <AppCenterAnalytics/MSACEventLog.h> #import <AppCenterAnalytics/MSACEventProperties.h> #else #import "MSACAnalytics.h" #import "MSACAnalyticsAuthenticationProvider.h" #import "MSACAnalyticsAuthenticationProviderDelegate.h" #import "MSACAnalyticsTransmissionTarget.h" #import "MSACEventLog.h" #import "MSACEventProperties.h" #endif
278
1,379
<filename>src/java/voldemort/utils/ConsistencyCheck.java /* * Copyright 2013 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.utils; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.client.protocol.admin.AdminClient; import voldemort.cluster.Cluster; import voldemort.cluster.Node; import voldemort.routing.RoutingStrategyFactory; import voldemort.store.StoreDefinition; import voldemort.versioning.Occurred; import voldemort.versioning.VectorClock; import voldemort.versioning.Version; import voldemort.versioning.Versioned; public class ConsistencyCheck { private static final String ComparisonTypeArgument = "comparison-type"; private static Logger logger = Logger.getLogger(ConsistencyCheck.class); private final List<String> urls; private final String storeName; private final Integer partitionId; private final ValueFactory valueFactory; private final Reporter reporter; private Integer retentionDays = null; private Integer replicationFactor = 0; private Integer requiredWrites = 0; private List<AdminClient> adminClients; private List<ClusterNode> clusterNodeList = new ArrayList<ClusterNode>(); private final Map<ByteArray, Map<Value, Set<ClusterNode>>> keyValueNodeSetMap = new HashMap<ByteArray, Map<Value, Set<ClusterNode>>>(); private RetentionChecker retentionChecker; private KeyFetchTracker keyFetchTracker; public ConsistencyCheck(List<String> urls, String storeName, int partitionId, Writer badKeyWriter, ComparisonType comparisonType) { this.urls = urls; this.storeName = storeName; this.partitionId = partitionId; this.reporter = new Reporter(badKeyWriter); this.valueFactory = new ValueFactory(comparisonType); } /** * Connect to the clusters using given urls and start fetching process on * correct nodes * * @throws Exception When no such store is found */ public void connect() throws Exception { adminClients = new ArrayList<AdminClient>(urls.size()); // bootstrap from two urls Map<String, Cluster> clusterMap = new HashMap<String, Cluster>(urls.size()); Map<String, StoreDefinition> storeDefinitionMap = new HashMap<String, StoreDefinition>(urls.size()); for(String url: urls) { /* connect to cluster through admin port */ if(logger.isInfoEnabled()) { logger.info("Connecting to bootstrap server: " + url); } AdminClient adminClient = new AdminClient(url); adminClients.add(adminClient); /* get Cluster */ Cluster cluster = adminClient.getAdminClientCluster(); clusterMap.put(url, cluster); Integer nodeId = cluster.getNodeIds().iterator().next(); /* get StoreDefinition */ Versioned<List<StoreDefinition>> storeDefinitions = adminClient.metadataMgmtOps.getRemoteStoreDefList(nodeId); StoreDefinition storeDefinition = StoreDefinitionUtils.getStoreDefinitionWithName(storeDefinitions.getValue(), storeName); storeDefinitionMap.put(url, storeDefinition); } /* confirm same number of partitions in all clusters. */ int partitionCount = 0; for(Entry<String, Cluster> entry: clusterMap.entrySet()) { int currentPartitionCount = entry.getValue().getNumberOfPartitions(); if(partitionCount == 0) { partitionCount = currentPartitionCount; } if(partitionCount != currentPartitionCount) { logger.error("Partition count of different clusters is not the same: " + partitionCount + " vs " + currentPartitionCount); throw new VoldemortException("Will not connect because partition counts differ among clusters."); } } /* calculate nodes to scan */ for(String url: urls) { StoreDefinition storeDefinition = storeDefinitionMap.get(url); Cluster cluster = clusterMap.get(url); Map<Integer, Integer> partitionToNodeMap = cluster.getPartitionIdToNodeIdMap(); /* find list of nodeId hosting partition */ List<Integer> partitionList = new RoutingStrategyFactory().updateRoutingStrategy(storeDefinition, cluster) .getReplicatingPartitionList(partitionId); for(int partition: partitionList) { Integer nodeId = partitionToNodeMap.get(partition); Node node = cluster.getNodeById(nodeId); clusterNodeList.add(new ClusterNode(urls.indexOf(url), node)); } } /* print config info */ if(logger.isInfoEnabled()) { StringBuilder configInfo = new StringBuilder(); configInfo.append("TYPE,Store,PartitionId,Node,ZoneId,BootstrapUrl\n"); for(ClusterNode clusterNode: clusterNodeList) { configInfo.append("CONFIG,"); configInfo.append(storeName + ","); configInfo.append(partitionId + ","); configInfo.append(clusterNode.getNode().getId() + ","); configInfo.append(clusterNode.getNode().getZoneId() + ","); configInfo.append(urls.get(clusterNode.getPrefixId()) + "\n"); } for(String line: configInfo.toString().split("\n")) { logger.info(line); } } /* calculate retention days and more */ for(String url: urls) { StoreDefinition storeDefinition = storeDefinitionMap.get(url); /* retention */ int storeRetentionDays = 0; if(storeDefinition.getRetentionDays() != null) { storeRetentionDays = storeDefinition.getRetentionDays().intValue(); } if(retentionDays == null) { retentionDays = storeRetentionDays; } if(retentionDays != storeRetentionDays) { if(storeRetentionDays != 0 && (storeRetentionDays < retentionDays)) { retentionDays = storeRetentionDays; } logger.warn("Retention-days is not consistent between clusters by urls. Will use the shorter."); } /* replication writes */ replicationFactor += storeDefinition.getReplicationFactor(); /* required writes */ requiredWrites += storeDefinition.getRequiredWrites(); } if(replicationFactor != clusterNodeList.size()) { logger.error("Replication factor is not consistent with number of nodes routed to."); throw new VoldemortException("Will not connect because replication factor does not accord with number of nodes routed to."); } retentionChecker = new RetentionChecker(retentionDays); } /** * Run consistency check on connected key-value iterators * * @return Results in form of ConsistencyCheckStats */ public Reporter execute() throws IOException { Map<ClusterNode, Iterator<Pair<ByteArray, Versioned<byte[]>>>> nodeFetchIteratorMap; nodeFetchIteratorMap = new HashMap<ClusterNode, Iterator<Pair<ByteArray, Versioned<byte[]>>>>(); /* start fetch from each node */ for(ClusterNode clusterNode: clusterNodeList) { AdminClient adminClient = adminClients.get(clusterNode.getPrefixId()); List<Integer> singlePartition = new ArrayList<Integer>(); singlePartition.add(partitionId); if(logger.isDebugEnabled()) { logger.debug("Start fetch request to Node[" + clusterNode.toString() + "] for partition[" + partitionId + "] of store[" + storeName + "]"); } Iterator<Pair<ByteArray, Versioned<byte[]>>> fetchIterator; fetchIterator = adminClient.bulkFetchOps.fetchEntries(clusterNode.getNode().getId(), storeName, singlePartition, null, false); nodeFetchIteratorMap.put(clusterNode, fetchIterator); } keyFetchTracker = new KeyFetchTracker(clusterNodeList.size()); /* start to fetch */ boolean fetchFinished; do { fetchFinished = true; for(Map.Entry<ClusterNode, Iterator<Pair<ByteArray, Versioned<byte[]>>>> nodeFetchIteratorMapEntry: nodeFetchIteratorMap.entrySet()) { ClusterNode clusterNode = nodeFetchIteratorMapEntry.getKey(); Iterator<Pair<ByteArray, Versioned<byte[]>>> fetchIterator = nodeFetchIteratorMapEntry.getValue(); if(fetchIterator.hasNext()) { fetchFinished = false; reporter.recordScans(1); Pair<ByteArray, Versioned<byte[]>> fetchedEntry = fetchIterator.next(); ByteArray key = fetchedEntry.getFirst(); Versioned<byte[]> versioned = fetchedEntry.getSecond(); // record fetch recordFetch(clusterNode, key, versioned); // try sweep last key fetched by this iterator keyFetchTracker.recordFetch(clusterNode, key); if(logger.isTraceEnabled()) { logger.trace("fetched " + new String(key.get())); logger.trace("map has keys: " + keyValueNodeSetMap.size()); } trySweepAll(); if(logger.isTraceEnabled()) { logger.trace("sweeped; keys left: " + keyValueNodeSetMap.size()); } } } // stats reporting if(logger.isInfoEnabled()) { String report = reporter.tryProgressReport(); if(report != null) { for(String line: report.split("\n")) { logger.info(line); } } } } while(!fetchFinished); /* adminClient shutdown */ for(AdminClient adminClient: adminClients) { if(adminClient != null) { adminClient.close(); } } // clean keys not sufficient for write cleanIneligibleKeys(keyValueNodeSetMap, requiredWrites); keyFetchTracker.finishAll(); trySweepAll(); reporter.processInconsistentKeys(storeName, partitionId, keyValueNodeSetMap); return reporter; } public void trySweepAll() { for(ByteArray finishedKey = keyFetchTracker.nextFinished(); finishedKey != null; finishedKey = keyFetchTracker.nextFinished()) { if (keyValueNodeSetMap.containsKey(finishedKey)) { ConsistencyLevel level = determineConsistency(keyValueNodeSetMap.get(finishedKey), replicationFactor); if(level == ConsistencyLevel.FULL || level == ConsistencyLevel.LATEST_CONSISTENT) { keyValueNodeSetMap.remove(finishedKey); reporter.recordGoodKey(1); } } } } public void recordFetch(ClusterNode clusterNode, ByteArray key, Versioned<byte[]> versioned) { Value value = valueFactory.Create(versioned); // skip version if expired if (retentionChecker.isExpired(value)) { reporter.recordExpired(1); return; } // initialize key -> Map<Version, Set<nodeId>> if (!keyValueNodeSetMap.containsKey(key)) { keyValueNodeSetMap.put(key, new HashMap<Value, Set<ClusterNode>>()); } Map<Value, Set<ClusterNode>> versionNodeSetMap = keyValueNodeSetMap.get(key); List<Value> valuesToDiscard = new ArrayList<Value>(); for(Map.Entry<Value, Set<ClusterNode>> versionNode : versionNodeSetMap.entrySet()) { Value existingValue = versionNode.getKey(); // Check for each existing value, if the existing value happened after current. If so the current value can be discarded if(existingValue.compare(value) == Occurred.AFTER) { return; } else if ( value.compare(existingValue) == Occurred.AFTER) { // Check for each existing value, if the current value happened after existing. If so the existing value can be discarded valuesToDiscard.add(existingValue); } } for(Value valueToDiscard: valuesToDiscard) { versionNodeSetMap.remove(valueToDiscard); } if (!versionNodeSetMap.containsKey(value)) { // insert nodeSet into the map versionNodeSetMap.put(value, new HashSet<ClusterNode>()); } // add node to set versionNodeSetMap.get(value).add(clusterNode); } /** * A class to track what keys have been fetched and what keys will not * appear any more. It is used to detect keys that will not show up any more * so that existing versions can be processed. */ protected static class KeyFetchTracker { private final Integer fetcherCount; Map<ByteArray, Set<ClusterNode>> fullyFetchedKeyMap = new HashMap<ByteArray, Set<ClusterNode>>(); Map<ClusterNode, ByteArray> lastFetchedKey = new HashMap<ClusterNode, ByteArray>(); List<ByteArray> fullyFetchedKeys = new LinkedList<ByteArray>(); public KeyFetchTracker(Integer fetcherCount) { this.fetcherCount = fetcherCount; } /** * Record a fetched result * * @param clusterNode The clusterNode from which the key has been * fetched * @param key The key itself */ public void recordFetch(ClusterNode clusterNode, ByteArray key) { if(lastFetchedKey.containsKey(clusterNode)) { ByteArray lastKey = lastFetchedKey.get(clusterNode); if(!key.equals(lastKey)) { if(!fullyFetchedKeyMap.containsKey(lastKey)) { fullyFetchedKeyMap.put(lastKey, new HashSet<ClusterNode>()); } Set<ClusterNode> lastKeyIterSet = fullyFetchedKeyMap.get(lastKey); lastKeyIterSet.add(clusterNode); // sweep if fully fetched by all iterators if(lastKeyIterSet.size() == fetcherCount) { fullyFetchedKeys.add(lastKey); fullyFetchedKeyMap.remove(lastKey); } } } // remember key fetch states lastFetchedKey.put(clusterNode, key); } /** * mark all keys appeared as finished So that they are all in the * finished keys queue */ public void finishAll() { Set<ByteArray> keySet = new HashSet<ByteArray>(); keySet.addAll(fullyFetchedKeyMap.keySet()); keySet.addAll(lastFetchedKey.values()); fullyFetchedKeys.addAll(keySet); fullyFetchedKeyMap.clear(); } /** * Get a key that are completed in fetching * * @return key considered finished; otherwise null */ public ByteArray nextFinished() { if(fullyFetchedKeys.size() > 0) { return fullyFetchedKeys.remove(0); } else { return null; } } } protected enum ConsistencyLevel { FULL, LATEST_CONSISTENT, INCONSISTENT, EXPIRED, INSUFFICIENT_WRITE } public static enum ComparisonType { VERSION, HASH, } /** * Used to track nodes that may share the same nodeId in different clusters * */ protected static class ClusterNode { private final Integer clusterId; private final Node node; /** * @param clusterId a prefix to be associated different clusters * @param node the real node */ public ClusterNode(Integer clusterId, Node node) { this.clusterId = clusterId; this.node = node; } public Integer getPrefixId() { return clusterId; } public Node getNode() { return node; } @Override public boolean equals(Object o) { if(this == o) return true; if(!(o instanceof ClusterNode)) return false; ClusterNode n = (ClusterNode) o; return clusterId.equals(n.getPrefixId()) && node.equals(n.getNode()); } @Override public String toString() { return clusterId + "." + node.getId(); } } /** * A checker to determine if a key is to be cleaned according to retention * policy * */ protected static class RetentionChecker { final private long bufferTimeSeconds = 600; // expire N seconds earlier final private long expiredTimeMs; /** * @param days number of days ago from now to retain keys */ public RetentionChecker(int days) { if(days <= 0) { expiredTimeMs = 0; } else { long nowMs = System.currentTimeMillis(); long expirationTimeS = TimeUnit.DAYS.toSeconds(days) - bufferTimeSeconds; expiredTimeMs = nowMs - TimeUnit.SECONDS.toMillis(expirationTimeS); } } /** * Determine if a version is expired * * @param v version to be checked * @return if the version is expired according to retention policy */ public boolean isExpired(Value v) { return v.isExpired(expiredTimeMs); } } /** * Used to report bad keys, progress, and statistics * */ protected static class Reporter { final Writer badKeyWriter; final long reportPeriodMs; long lastReportTimeMs = 0; long numRecordsScanned = 0; long numRecordsScannedLast = 0; long numExpiredRecords = 0; long numGoodKeys = 0; long numTotalKeys = 0; /** * Will output progress reports every 5 seconds. * * @param badKeyWriter Writer to which to output bad keys. Null is OK. */ public Reporter(Writer badKeyWriter) { this(badKeyWriter, 5000); } /** * @param badKeyWriter Writer to which to output bad keys. Null is OK. * @param intervalMs Milliseconds between progress reports. */ public Reporter(Writer badKeyWriter, long intervalMs) { this.badKeyWriter = badKeyWriter; this.reportPeriodMs = intervalMs; } public void recordScans(long count) { numRecordsScanned += count; } public void recordExpired(long count) { numExpiredRecords += count; } public String tryProgressReport() { if(System.currentTimeMillis() > lastReportTimeMs + reportPeriodMs) { long currentTimeMs = System.currentTimeMillis(); StringBuilder s = new StringBuilder(); s.append("=====Progress=====\n"); s.append("Records Scanned: " + numRecordsScanned + "\n"); s.append("Records Ignored: " + numExpiredRecords + " (Out of Retention)\n"); s.append("Last Fetch Rate: " + (numRecordsScanned - numRecordsScannedLast) / ((currentTimeMs - lastReportTimeMs) / 1000) + " (records/s)\n"); lastReportTimeMs = currentTimeMs; numRecordsScannedLast = numRecordsScanned; return s.toString(); } else { return null; } } public void processInconsistentKeys(String storeName, Integer partitionId, Map<ByteArray, Map<Value, Set<ClusterNode>>> keyVersionNodeSetMap) throws IOException { if(logger.isDebugEnabled()) { logger.debug("TYPE,Store,ParId,Key,ServerSet,VersionTS,VectorClock[,ValueHash]"); } for (Map.Entry<ByteArray, Map<Value, Set<ClusterNode>>> entry : keyVersionNodeSetMap.entrySet()) { ByteArray key = entry.getKey(); if(badKeyWriter != null) { badKeyWriter.write(ByteUtils.toHexString(key.get()) + "\n"); } if(logger.isDebugEnabled()) { Map<Value, Set<ClusterNode>> versionMap = entry.getValue(); logger.debug(keyVersionToString(key, versionMap, storeName, partitionId)); } } recordInconsistentKey(keyVersionNodeSetMap.size()); } public void recordGoodKey(long count) { numGoodKeys += count; numTotalKeys += count; } public void recordInconsistentKey(long count) { numTotalKeys += count; } } /** * Return args parser * * @return program parser * */ private static OptionParser getParser() { /* parse options */ OptionParser parser = new OptionParser(); parser.accepts("help", "print help information"); parser.accepts("urls", "[REQUIRED] bootstrap URLs") .withRequiredArg() .describedAs("bootstrap-url") .withValuesSeparatedBy(',') .ofType(String.class); parser.accepts("partitions", "partition-id") .withRequiredArg() .describedAs("partition-id") .withValuesSeparatedBy(',') .ofType(Integer.class); parser.accepts("store", "store name") .withRequiredArg() .describedAs("store-name") .ofType(String.class); parser.accepts("bad-key-file", "File name to which inconsistent keys are to be written.") .withRequiredArg() .describedAs("badKeyFileOut") .ofType(String.class); parser.accepts(ComparisonTypeArgument, "type of comparison to compare the values for the same key") .withRequiredArg() .describedAs("comparisonType") .ofType(String.class); return parser; } /** * Print Usage to STDOUT */ private static void printUsage() { StringBuilder help = new StringBuilder(); help.append("ConsistencyCheck Tool\n"); help.append(" Scan partitions of a store by bootstrap url(s) for consistency and\n"); help.append(" output inconsistent keys to a file.\n"); help.append("Options:\n"); help.append(" Required:\n"); help.append(" --partitions <partitionId>[,<partitionId>...]\n"); help.append(" --urls <url>[,<url>...]\n"); help.append(" --store <storeName>\n"); help.append(" --bad-key-file <badKeyFileOut>\n"); help.append(" Optional:\n"); help.append(" --comparison-type [version | hash ]\n"); help.append(" --help\n"); help.append(" Note:\n"); help.append(" If you have two or more clusters to scan for consistency across them,\n"); help.append(" You will need to supply multiple bootstrap urls, one for each cluster.\n"); help.append(" When multiple urls are used, all versions are considered as concurrent.\n"); help.append(" Versioned objects from different nodes are identified by value hashes,\n"); help.append(" instead of VectorClocks\n"); help.append(" If specified clusters do not have the same number of partitions, \n"); help.append(" checking will fail.\n"); System.out.print(help.toString()); } /** * Determine the consistency level of a key * * @param versionNodeSetMap A map that maps version to set of PrefixNodes * @param replicationFactor Total replication factor for the set of clusters * @return ConsistencyLevel Enum */ public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap, int replicationFactor) { boolean fullyConsistent = true; Value latestVersion = null; for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) { Value value = versionNodeSetEntry.getKey(); if (latestVersion == null) { latestVersion = value; } else if (value.isTimeStampLaterThan(latestVersion)) { latestVersion = value; } Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue(); fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor); } if (fullyConsistent) { return ConsistencyLevel.FULL; } else { // latest write consistent, effectively consistent if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) { return ConsistencyLevel.LATEST_CONSISTENT; } // all other states inconsistent return ConsistencyLevel.INCONSISTENT; } } /** * Determine if a key version is invalid by comparing the version's * existence and required writes configuration * * @param keyVersionNodeSetMap A map that contains keys mapping to a map * that maps versions to set of PrefixNodes * @param requiredWrite Required Write configuration */ public static void cleanIneligibleKeys(Map<ByteArray, Map<Value, Set<ClusterNode>>> keyVersionNodeSetMap, int requiredWrite) { Set<ByteArray> keysToDelete = new HashSet<ByteArray>(); for (Map.Entry<ByteArray, Map<Value, Set<ClusterNode>>> entry : keyVersionNodeSetMap.entrySet()) { Set<Value> valuesToDelete = new HashSet<Value>(); ByteArray key = entry.getKey(); Map<Value, Set<ClusterNode>> valueNodeSetMap = entry.getValue(); // mark version for deletion if not enough writes for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : valueNodeSetMap.entrySet()) { Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue(); if (nodeSet.size() < requiredWrite) { valuesToDelete.add(versionNodeSetEntry.getKey()); } } // delete versions for (Value v : valuesToDelete) { valueNodeSetMap.remove(v); } // mark key for deletion if no versions left if (valueNodeSetMap.size() == 0) { keysToDelete.add(key); } } // delete keys for (ByteArray k : keysToDelete) { keyVersionNodeSetMap.remove(k); } } @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { OptionSet options = getParser().parse(args); /* validate options */ if (options.hasArgument("help")) { printUsage(); return; } if (!options.hasArgument("urls") || !options.hasArgument("partitions") || !options.hasArgument("store") || !options.hasArgument("bad-key-file")) { printUsage(); return; } List<String> urls = (List<String>) options.valuesOf("urls"); String storeName = (String) options.valueOf("store"); List<Integer> partitionIds = (List<Integer>) options.valuesOf("partitions"); String badKeyFile = (String) options.valueOf("bad-key-file"); ComparisonType comparisonType = ComparisonType.VERSION; if (options.hasArgument(ComparisonTypeArgument)) { String comparisonArgument = (String) options.valueOf(ComparisonTypeArgument); comparisonArgument = comparisonArgument.toUpperCase(); comparisonType = ComparisonType.valueOf(comparisonArgument) ; } BufferedWriter badKeyWriter = null; try { badKeyWriter = new BufferedWriter(new FileWriter(badKeyFile)); } catch (IOException e) { Utils.croak("Failure to open output file : " + e.getMessage()); } Map<Integer, Reporter> partitionStatsMap = new HashMap<Integer, Reporter>(); /* scan each partitions */ try { for (Integer partitionId : partitionIds) { ConsistencyCheck checker = new ConsistencyCheck(urls, storeName, partitionId, badKeyWriter, comparisonType); checker.connect(); Reporter reporter = checker.execute(); partitionStatsMap.put(partitionId, reporter); } } catch (Exception e) { Utils.croak("Exception during consistency checking : " + e.getMessage()); } finally { badKeyWriter.close(); } /* print stats */ StringBuilder statsString = new StringBuilder(); long totalGoodKeys = 0; long totalTotalKeys = 0; // each partition statsString.append("TYPE,Store,PartitionId,KeysConsistent,KeysTotal,Consistency\n"); for (Map.Entry<Integer, Reporter> entry : partitionStatsMap.entrySet()) { Integer partitionId = entry.getKey(); Reporter reporter = entry.getValue(); totalGoodKeys += reporter.numGoodKeys; totalTotalKeys += reporter.numTotalKeys; statsString.append("STATS,"); statsString.append(storeName + ","); statsString.append(partitionId + ","); statsString.append(reporter.numGoodKeys + ","); statsString.append(reporter.numTotalKeys + ","); statsString.append((double) (reporter.numGoodKeys) / (double) reporter.numTotalKeys); statsString.append("\n"); } // all partitions statsString.append("STATS,"); statsString.append(storeName + ","); statsString.append("aggregate,"); statsString.append(totalGoodKeys + ","); statsString.append(totalTotalKeys + ","); statsString.append((double) (totalGoodKeys) / (double) totalTotalKeys); statsString.append("\n"); for (String line : statsString.toString().split("\n")) { logger.info(line); } } /** * Convert a key-version-nodeSet information to string * * @param key The key * @param versionMap mapping versions to set of PrefixNodes * @param storeName store's name * @param partitionId partition scanned * @return a string that describe the information passed in */ public static String keyVersionToString(ByteArray key, Map<Value, Set<ClusterNode>> versionMap, String storeName, Integer partitionId) { StringBuilder record = new StringBuilder(); for (Map.Entry<Value, Set<ClusterNode>> versionSet : versionMap.entrySet()) { Value value = versionSet.getKey(); Set<ClusterNode> nodeSet = versionSet.getValue(); record.append("BAD_KEY,"); record.append(storeName + ","); record.append(partitionId + ","); record.append(ByteUtils.toHexString(key.get()) + ","); record.append(nodeSet.toString().replace(", ", ";") + ","); record.append(value.toString()); } return record.toString(); } public static abstract class Value { abstract Occurred compare(Value v); public abstract boolean equals(Object obj); public abstract int hashCode(); public abstract String toString(); public abstract boolean isExpired(long expiredTimeMs); public abstract boolean isTimeStampLaterThan(Value v); } public static class VersionValue extends Value { protected final Version version; protected VersionValue(Versioned<byte[]> versioned) { this.version = versioned.getVersion(); } public Occurred compare(Value v) { if (!(v instanceof VersionValue)) { throw new VoldemortException(" Expected type VersionValue found type " + v.getClass().getCanonicalName()); } VersionValue other = (VersionValue) v; return version.compare(other.version); } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (!(o instanceof VersionValue)) { return false; } VersionValue other = (VersionValue) o; return version.equals(other.version); } @Override public int hashCode() { return version.hashCode(); } @Override public String toString() { StringBuilder record = new StringBuilder(); record.append(((VectorClock) version).getTimestamp() + ","); record.append(version.toString().replaceAll(", ", ";").replaceAll(" ts:[0-9]*", "") .replaceAll("version\\((.*)\\)", "[$1]")); return record.toString(); } public boolean isExpired(long expiredTimeMs) { return ((VectorClock) version).getTimestamp() < expiredTimeMs; } public boolean isTimeStampLaterThan(Value currentLatest) { if (!(currentLatest instanceof VersionValue)) { throw new VoldemortException( " Expected type VersionValue found type " + currentLatest.getClass().getCanonicalName()); } VersionValue latestVersion = (VersionValue) currentLatest; long latestTimeStamp = ((VectorClock) latestVersion.version).getTimestamp(); long myTimeStamp = ((VectorClock) version).getTimestamp(); return myTimeStamp > latestTimeStamp; } } /** * A class to save version and value hash It is used to compare versions by * the value hash * */ public static class HashedValue extends Value { final private Version innerVersion; final private Integer valueHash; /** * @param versioned Versioned value with version information and value * itself */ public HashedValue(Versioned<byte[]> versioned) { innerVersion = versioned.getVersion(); valueHash = new FnvHashFunction().hash(versioned.getValue()); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (!object.getClass().equals(HashedValue.class)) { return false; } HashedValue hash = (HashedValue) object; boolean result = valueHash.equals(hash.hashCode()); return result; } public Occurred compare(Value v) { // TODO: Return before if they are equal. return Occurred.CONCURRENTLY; // always regard as conflict } @Override public int hashCode() { return valueHash; } public boolean isExpired(long expiredTimeMs) { return ((VectorClock) innerVersion).getTimestamp() < expiredTimeMs; } @Override public String toString() { StringBuilder record = new StringBuilder(); record.append(((VectorClock) innerVersion).getTimestamp() + ","); record.append(innerVersion.toString().replaceAll(", ", ";").replaceAll(" ts:[0-9]*", "") .replaceAll("version\\((.*)\\)", "[$1],")); record.append(valueHash); return record.toString(); } public boolean isTimeStampLaterThan(Value currentLatest) { if (!(currentLatest instanceof HashedValue)) { throw new VoldemortException( " Expected type HashedValue found type " + currentLatest.getClass().getCanonicalName()); } HashedValue latestVersion = (HashedValue) currentLatest; long latestTimeStamp = ((VectorClock) latestVersion.innerVersion).getTimestamp(); long myTimeStamp = ((VectorClock) innerVersion).getTimestamp(); return myTimeStamp > latestTimeStamp; } } public class ValueFactory { private final ComparisonType type; public ValueFactory(ComparisonType type) { this.type = type; } public Value Create(Versioned<byte[]> versioned) { if (type == ComparisonType.HASH) { return new HashedValue(versioned); } else if (type == ComparisonType.VERSION) { return new VersionValue(versioned); } else { throw new VoldemortException("ComparisonType:" + type.name() + " is not handled by ValueFactory"); } } } }
16,833
851
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_VIDEO_CODING_CODECS_VP8_TEMPORAL_LAYERS_H_ #define MODULES_VIDEO_CODING_CODECS_VP8_TEMPORAL_LAYERS_H_ // TODO(webrtc:9012) Remove this file when downstream projects have updated. #include "api/video_codecs/vp8_temporal_layers.h" #endif // MODULES_VIDEO_CODING_CODECS_VP8_TEMPORAL_LAYERS_H_
254
692
#include <stdint.h> #include <stdio.h> #include <assert.h> #include <limits.h> #include <sys/time.h> #include "core/adios_logger.h" #include "core/transforms/adios_transforms_common.h" #include "core/transforms/adios_transforms_write.h" #include "core/transforms/adios_transforms_hooks_write.h" #include "core/transforms/adios_transforms_util.h" #ifdef BZIP2 #include "bzlib.h" int compress_bzip2_pre_allocated(const void* input_data, const uint64_t input_len, void* output_data, uint64_t* output_len, int blockSize100k) { // bzip2 only support input size of 32 bit integer assert(input_data != NULL && input_len > 0 && output_data != NULL && output_len != NULL && *output_len > 0); unsigned int input_len_32 = (unsigned int)input_len; unsigned int output_len_32 = (unsigned int)(*output_len); int bz_rtn = BZ2_bzBuffToBuffCompress((char*)output_data, &output_len_32, (char*)input_data, input_len_32, blockSize100k, 0, 30); if(bz_rtn != BZ_OK) return -1; *output_len = output_len_32; return 0; } uint16_t adios_transform_bzip2_get_metadata_size(struct adios_transform_spec *transform_spec) { return (sizeof(uint64_t) + sizeof(char)); // metadata: original data size (uint64_t) + compression succ flag (char) } void adios_transform_bzip2_transformed_size_growth( const struct adios_var_struct *var, const struct adios_transform_spec *transform_spec, uint64_t *constant_factor, double *linear_factor, double *capped_linear_factor, uint64_t *capped_linear_cap) { // Do nothing (defaults to "no transform effect on data size") } int adios_transform_bzip2_apply(struct adios_file_struct *fd, struct adios_var_struct *var, uint64_t *transformed_len, int use_shared_buffer, int *wrote_to_shared_buffer) { // Get the input data and data length const uint64_t input_size = adios_transform_get_pre_transform_var_size(var); const void *input_buff = var->data; // parse the compressiong parameter /* Pre-specparse code if(var->transform_type_param && strlen(var->transform_type_param) > 0 && is_digit_str(var->transform_type_param)) { compress_level = atoi(var->transform_type_param); if(compress_level > 9 || compress_level < 1) { compress_level = 9; } } */ int compress_level = 9; if (var->transform_spec->param_count > 0) { compress_level = atoi(var->transform_spec->params[0].key); if (compress_level < 1 || compress_level > 9) compress_level = 9; } // decide the output buffer uint64_t output_size = input_size; //adios_transform_bzip2_calc_vars_transformed_size(adios_transform_bzip2, input_size, 1); void* output_buff = NULL; if (use_shared_buffer) // If shared buffer is permitted, serialize to there { *wrote_to_shared_buffer = 1; if (!shared_buffer_reserve(fd, output_size)) { log_error("Out of memory allocating %llu bytes for %s for bzip2 transform\n", output_size, var->name); return 0; } // Write directly to the shared buffer output_buff = fd->buffer + fd->offset; } else // Else, fall back to var->data memory allocation { *wrote_to_shared_buffer = 0; output_buff = malloc(output_size); if (!output_buff) { log_error("Out of memory allocating %llu bytes for %s for bzip2 transform\n", output_size, var->name); return 0; } } uint64_t actual_output_size = output_size; char compress_ok = 1; int rtn = compress_bzip2_pre_allocated(input_buff, input_size, output_buff, &actual_output_size, compress_level); if(0 != rtn // compression failed for some reason, then just copy the buffer || actual_output_size > input_size) // or size after compression is even larger (not likely to happen since compression lib will return non-zero in this case) { // printf("compression failed, fall back to memory copy\n"); memcpy(output_buff, input_buff, input_size); actual_output_size = input_size; compress_ok = 0; // succ sign set to 0 } // Wrap up, depending on buffer mode if (use_shared_buffer) { shared_buffer_mark_written(fd, actual_output_size); } else { var->data = output_buff; var->data_size = actual_output_size; var->free_data = adios_flag_yes; } // copy the metadata, simply the original size before compression if(var->transform_metadata && var->transform_metadata_len > 0) { memcpy((char*)var->transform_metadata, &input_size, sizeof(uint64_t)); memcpy((char*)var->transform_metadata + sizeof(uint64_t), &compress_ok, sizeof(char)); } *transformed_len = actual_output_size; // Return the size of the data buffer return 1; } #else DECLARE_TRANSFORM_WRITE_METHOD_UNIMPL(bzip2) #endif
2,525
6,526
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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 2014 Cloudius Systems */ #pragma once #include <seastar/core/future.hh> #include <seastar/util/std-compat.hh> #include <exception> namespace seastar { /// \addtogroup fiber-module /// @{ /// Exception thrown when a \ref gate object has been closed /// by the \ref gate::close() method. class gate_closed_exception : public std::exception { public: virtual const char* what() const noexcept override { return "gate closed"; } }; /// Facility to stop new requests, and to tell when existing requests are done. /// /// When stopping a service that serves asynchronous requests, we are faced with /// two problems: preventing new requests from coming in, and knowing when existing /// requests have completed. The \c gate class provides a solution. class gate { size_t _count = 0; std::optional<promise<>> _stopped; public: gate() = default; gate(const gate&) = delete; gate(gate&&) = default; gate& operator=(gate&&) = default; ~gate() { assert(!_count && "gate destroyed with outstanding requests"); } /// Tries to register an in-progress request. /// /// If the gate is not closed, the request is registered and the function returns `true`, /// Otherwise the function just returns `false` and has no other effect. bool try_enter() noexcept { bool opened = !_stopped; if (opened) { ++_count; } return opened; } /// Registers an in-progress request. /// /// If the gate is not closed, the request is registered. Otherwise, /// a \ref gate_closed_exception is thrown. void enter() { if (!try_enter()) { throw gate_closed_exception(); } } /// Unregisters an in-progress request. /// /// If the gate is closed, and there are no more in-progress requests, /// the `_stopped` promise will be fulfilled. void leave() noexcept { --_count; if (!_count && _stopped) { _stopped->set_value(); } } /// Potentially stop an in-progress request. /// /// If the gate is already closed, a \ref gate_closed_exception is thrown. /// By using \ref enter() and \ref leave(), the program can ensure that /// no further requests are serviced. However, long-running requests may /// continue to run. The check() method allows such a long operation to /// voluntarily stop itself after the gate is closed, by making calls to /// check() in appropriate places. check() with throw an exception and /// bail out of the long-running code if the gate is closed. void check() { if (_stopped) { throw gate_closed_exception(); } } /// Closes the gate. /// /// Future calls to \ref enter() will fail with an exception, and when /// all current requests call \ref leave(), the returned future will be /// made ready. future<> close() noexcept { assert(!_stopped && "seastar::gate::close() cannot be called more than once"); _stopped = std::make_optional(promise<>()); if (!_count) { _stopped->set_value(); } return _stopped->get_future(); } /// Returns a current number of registered in-progress requests. size_t get_count() const noexcept { return _count; } /// Returns whether the gate is closed. bool is_closed() const noexcept { return bool(_stopped); } /// Facility to hold a gate opened using RAII. /// /// A \ref gate::holder is usually obtained using \ref gate::get_holder. /// /// The \c gate is entered when the \ref gate::holder is constructed, /// And the \c gate is left when the \ref gate::holder is destroyed. /// /// Copying the \ref gate::holder reenters the \c gate to keep an extra reference on it. /// Moving the \ref gate::holder is supported and has no effect on the \c gate itself. class holder { gate* _g; public: /// Construct a default \ref holder, referencing no \ref gate. /// Never throws. holder() noexcept : _g(nullptr) { } /// Construct a \ref holder by entering the \c gate. /// May throw \ref gate_closed_exception if the gate is already closed. explicit holder(gate& g) : _g(&g) { _g->enter(); } /// Construct a \ref holder by copying another \c holder. /// Copying a holder never throws: The original holder has already entered the gate, /// so even if later the gate was \ref close "close()d", the copy of the holder is also allowed to enter too. /// Note that the fiber waiting for the close(), which until now was waiting for the one holder to leave, /// will now wait for both copies to leave. holder(const holder& x) noexcept : _g(x._g) { if (_g) { _g->_count++; } } /// Construct a \ref holder by moving another \c holder. /// The referenced \ref gate is unaffected, and so the /// move-constructor must never throw. holder(holder&& x) noexcept : _g(std::exchange(x._g, nullptr)) { } /// Destroy a \ref holder and leave the referenced \ref gate. ~holder() { release(); } /// Copy-assign another \ref holder. /// \ref leave "Leave()" the current \ref gate before assigning the other one, if they are different. /// Copying a holder never throws: The original holder has already entered the gate, /// so even if later the gate was \ref close "close()d", the copy of the holder is also allowed to enter too. /// Note that the fiber waiting for the close(), which until now was waiting for the one holder to leave, /// will now wait for both copies to leave. holder& operator=(const holder& x) noexcept { if (x._g != _g) { release(); _g = x._g; if (_g) { _g->_count++; } } return *this; } /// Move-assign another \ref holder. /// The other \ref gate is unaffected, /// and so the move-assign operator must always succeed. /// Leave the current \ref gate before assigning the other one. holder& operator=(holder&& x) noexcept { if (&x != this) { release(); _g = std::exchange(x._g, nullptr); } return *this; } /// Leave the held \c gate void release() noexcept { if (_g) { _g->leave(); _g = nullptr; } } }; /// Get a RAII-based gate::holder object that \ref enter "enter()s" /// the gate when constructed and \ref leave "leave()s" it when destroyed. holder hold() { return holder(*this); } }; namespace internal { template <typename Func> inline auto invoke_func_with_gate(gate& g, Func&& func) noexcept { return futurize_invoke(std::forward<Func>(func)).finally([&g] { g.leave(); }); } } // namespace intgernal /// Executes the function \c func making sure the gate \c g is properly entered /// and later on, properly left. /// /// \param func function to be executed /// \param g the gate. Caller must make sure that it outlives this function. /// \returns whatever \c func returns /// /// \relates gate template <typename Func> inline auto with_gate(gate& g, Func&& func) { g.enter(); return internal::invoke_func_with_gate(g, std::forward<Func>(func)); } /// Executes the function \c func if the gate \c g can be entered /// and later on, properly left. /// /// \param func function to be executed /// \param g the gate. Caller must make sure that it outlives this function. /// /// If the gate is already closed, an exception future holding /// \ref gate_closed_exception is returned, otherwise /// \returns whatever \c func returns. /// /// \relates gate template <typename Func> inline auto try_with_gate(gate& g, Func&& func) noexcept { if (!g.try_enter()) { using futurator = futurize<std::result_of_t<Func()>>; return futurator::make_exception_future(gate_closed_exception()); } return internal::invoke_func_with_gate(g, std::forward<Func>(func)); } /// @} }
3,305
435
{ "copyright_text": "This video is licensed under the CC BY-NC-SA 3.0 license: https://creativecommons.org/licenses/by-nc-sa/3.0/\nPlease see our speaker release agreement for details: https://ep2020.europython.eu/events/speaker-release-agreement/\n", "description": "Imagine this school scenario: an entire year group of students aged 11-12, the majority completely new to coding, undergoing 6 hours of compulsory lessons on Python for Scientific Computing. \r\n\r\nNow imagine these outcomes: \r\n\u2022\tStudents wanting to continue coding from the lessons outside of class in their own time \r\n\u2022\tStudents asking to replicate the lesson computing environment at home \r\n\u2022\tStudents disappointed for the lessons to come to an end and asking for more \r\n\u2022\tStudents struggling in Science discovering intrinsic ability in computing, bringing new enjoyment and confidence \r\n\r\nAnd lastly, imagine that all the students are girls! \r\n\r\nThis talk will share this actual case study of a pioneering Python education initiative implemented at a secondary school for girls in London, UK for a cohort of 120 students. \r\n\r\nThe audience will gain actionable insights of the factors that enabled these children to develop basic but working proficiency of a mainstream scientific data stack using typical school IT resources. \r\n\r\nUltimately, this talk aims to increase awareness of Scientific Computing & Data Science as potentially effective and empowering Python education for young people.", "duration": 2069.0, "language": "eng", "recorded": "2020-07-23", "related_urls": [ { "label": "Conference schedule", "url": "https://ep2020.europython.eu/schedule/" }, { "label": "Conference Website", "url": "https://ep2020.europython.eu/" }, { "label": "https://creativecommons.org/licenses/by-nc-sa/3.0/", "url": "https://creativecommons.org/licenses/by-nc-sa/3.0/" }, { "label": "https://ep2020.europython.eu/events/speaker-release-agreement/", "url": "https://ep2020.europython.eu/events/speaker-release-agreement/" }, { "label": "Talk URL", "url": "https://ep2020.europython.eu/schedule/24-july?selected=AEt4Rqo-accessible-python-education-for-schoolgirls-using-avocados-zombies-and-korean" } ], "speakers": [ "<NAME>" ], "tags": [ "europython", "europython-2020", "europython-online", "Case Study", "Data Science", "Education", "Learning", "Scientific Libraries (Numpy/Pandas/SciKit/...)" ], "thumbnail_url": "https://i.ytimg.com/vi/cZlBBGt7GHA/hqdefault.jpg?sqp=-oaymwEZCNACELwBSFXyq4qpAwsIARUAAIhCGAFwAQ==&rs=AOn4CLBSqwuK8fjYQiK2H74ddwR-tmhI3w", "title": "Accessible Python education for schoolgirls using Avocados, Zombies, and Korean!", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=cZlBBGt7GHA" } ] }
1,053
3,263
<filename>value-processor/src/org/immutables/value/processor/meta/SwitcherModel.java /* Copyright 2015 Immutables Authors and Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.immutables.value.processor.meta; import com.google.common.base.CaseFormat; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import org.immutables.generator.Naming; import org.immutables.generator.Naming.Preference; public final class SwitcherModel { private final String defaultName; private final Naming switcherNaming; public final ImmutableList<SwitchOption> options; private final TypeElement containedTypeElement; SwitcherModel(SwitchMirror mirror, Styles.UsingName.AttributeNames names, TypeElement containedTypeElement) { this.switcherNaming = Naming.from(names.raw).requireNonConstant(Preference.SUFFIX); this.containedTypeElement = Preconditions.checkNotNull(containedTypeElement); this.defaultName = mirror.defaultName(); this.options = constructOptions(); } private ImmutableList<SwitchOption> constructOptions() { ImmutableList.Builder<SwitchOption> builder = ImmutableList.builder(); for (Element v : containedTypeElement.getEnclosedElements()) { if (v.getKind() == ElementKind.ENUM_CONSTANT) { String name = v.getSimpleName().toString(); builder.add(new SwitchOption(name, defaultName.equals(name))); } } return builder.build(); } public boolean hasDefault() { return !defaultName.isEmpty(); } public final class SwitchOption { public final boolean isDefault; public final String constantName; public final String switcherName; public SwitchOption(String constantName, boolean isDefault) { this.constantName = constantName; this.switcherName = deriveSwitcherName(constantName); this.isDefault = isDefault; } private String deriveSwitcherName(String constantName) { return switcherNaming.apply( CaseFormat.UPPER_UNDERSCORE.to( CaseFormat.LOWER_CAMEL, constantName)); } } }
855
1,162
package io.digdag.guice.rs.server; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Retention(RUNTIME) @Target({METHOD}) public @interface PreStop { }
98
1,338
<gh_stars>1000+ /* * Copyright 2007-2009, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include "HaikuKernelFileSystem.h" #include <string.h> #include <new> #include <fs_interface.h> #include <AutoLocker.h> #include <block_cache.h> #include <condition_variable.h> #include <file_cache.h> #include "HaikuKernelIORequest.h" #include "HaikuKernelVolume.h" // IORequestHashDefinition struct HaikuKernelFileSystem::IORequestHashDefinition { typedef int32 KeyType; typedef HaikuKernelIORequest ValueType; size_t HashKey(int32 key) const { return key; } size_t Hash(const HaikuKernelIORequest* value) const { return value->id; } bool Compare(int32 key, const HaikuKernelIORequest* value) const { return value->id == key; } HaikuKernelIORequest*& GetLink(HaikuKernelIORequest* value) const { return value->hashLink; } }; // IORequestTable struct HaikuKernelFileSystem::IORequestTable : public BOpenHashTable<IORequestHashDefinition> { typedef int32 KeyType; typedef HaikuKernelIORequest ValueType; size_t HashKey(int32 key) const { return key; } size_t Hash(const HaikuKernelIORequest* value) const { return value->id; } bool Compare(int32 key, const HaikuKernelIORequest* value) const { return value->id == key; } HaikuKernelIORequest*& GetLink(HaikuKernelIORequest* value) const { return value->hashLink; } }; // NodeCapabilitiesHashDefinition struct HaikuKernelFileSystem::NodeCapabilitiesHashDefinition { typedef fs_vnode_ops* KeyType; typedef HaikuKernelNode::Capabilities ValueType; size_t HashKey(fs_vnode_ops* key) const { return (size_t)(addr_t)key; } size_t Hash(const ValueType* value) const { return HashKey(value->ops); } bool Compare(fs_vnode_ops* key, const ValueType* value) const { return value->ops == key; } ValueType*& GetLink(ValueType* value) const { return value->hashLink; } }; // NodeCapabilitiesTable struct HaikuKernelFileSystem::NodeCapabilitiesTable : public BOpenHashTable<NodeCapabilitiesHashDefinition> { }; // constructor HaikuKernelFileSystem::HaikuKernelFileSystem(const char* fsName, file_system_module_info* fsModule) : FileSystem(fsName), fFSModule(fsModule), fIORequests(NULL), fNodeCapabilities(NULL), fLock("HaikuKernelFileSystem") { _InitCapabilities(); } // destructor HaikuKernelFileSystem::~HaikuKernelFileSystem() { // call the kernel module uninitialization if (fFSModule->info.std_ops) fFSModule->info.std_ops(B_MODULE_UNINIT); delete fIORequests; delete fNodeCapabilities; // TODO: Call the cleanup methods (condition vars, block cache)! } // Init status_t HaikuKernelFileSystem::Init() { status_t error = fLock.InitCheck(); if (error != B_OK) RETURN_ERROR(error); // init condition variables condition_variable_init(); // TODO: Call the cleanup methods, if something goes wrong! // init block cache error = block_cache_init(); if (error != B_OK) RETURN_ERROR(error); // init file map error = file_map_init(); if (error != B_OK) RETURN_ERROR(error); // create I/O request map fIORequests = new(std::nothrow) IORequestTable; if (fIORequests == NULL) RETURN_ERROR(B_NO_MEMORY); error = fIORequests->Init(); if (error != B_OK) RETURN_ERROR(error); // create the node capabilites map fNodeCapabilities = new(std::nothrow) NodeCapabilitiesTable; if (fNodeCapabilities == NULL) RETURN_ERROR(B_NO_MEMORY); error = fNodeCapabilities->Init(); if (error != B_OK) RETURN_ERROR(error); // call the kernel module initialization (if any) if (!fFSModule->info.std_ops) return B_OK; error = fFSModule->info.std_ops(B_MODULE_INIT); if (error != B_OK) RETURN_ERROR(error); return B_OK; } // CreateVolume status_t HaikuKernelFileSystem::CreateVolume(Volume** _volume, dev_t id) { // check initialization and parameters if (!fFSModule || !_volume) return B_BAD_VALUE; // create and init the volume HaikuKernelVolume* volume = new(std::nothrow) HaikuKernelVolume(this, id, fFSModule); if (!volume) return B_NO_MEMORY; status_t error = volume->Init(); if (error != B_OK) { delete volume; return error; } *_volume = volume; return B_OK; } // DeleteVolume status_t HaikuKernelFileSystem::DeleteVolume(Volume* volume) { if (!volume || !dynamic_cast<HaikuKernelVolume*>(volume)) return B_BAD_VALUE; delete volume; return B_OK; } // AddIORequest status_t HaikuKernelFileSystem::AddIORequest(HaikuKernelIORequest* request) { AutoLocker<Locker> _(fLock); // check, if a request with that ID is already in the map if (fIORequests->Lookup(request->id) != NULL) RETURN_ERROR(B_BAD_VALUE); fIORequests->Insert(request); return B_OK; } // GetIORequest HaikuKernelIORequest* HaikuKernelFileSystem::GetIORequest(int32 requestID) { AutoLocker<Locker> _(fLock); HaikuKernelIORequest* request = fIORequests->Lookup(requestID); if (request != NULL) request->refCount++; return request; } // PutIORequest void HaikuKernelFileSystem::PutIORequest(HaikuKernelIORequest* request, int32 refCount) { AutoLocker<Locker> locker(fLock); if ((request->refCount -= refCount) <= 0) { fIORequests->Remove(request); locker.Unlock(); delete request; } } // GetVNodeCapabilities HaikuKernelNode::Capabilities* HaikuKernelFileSystem::GetNodeCapabilities(fs_vnode_ops* ops) { AutoLocker<Locker> locker(fLock); // check whether the ops are already known HaikuKernelNode::Capabilities* capabilities = fNodeCapabilities->Lookup(ops); if (capabilities != NULL) { capabilities->refCount++; return capabilities; } // get the capabilities implied by the ops vector FSVNodeCapabilities nodeCapabilities; _InitNodeCapabilities(ops, nodeCapabilities); // create a new object capabilities = new(std::nothrow) HaikuKernelNode::Capabilities(ops, nodeCapabilities); if (capabilities == NULL) return NULL; fNodeCapabilities->Insert(capabilities); return capabilities; } // PutVNodeCapabilities void HaikuKernelFileSystem::PutNodeCapabilities( HaikuKernelNode::Capabilities* capabilities) { AutoLocker<Locker> locker(fLock); if (--capabilities->refCount == 0) { fNodeCapabilities->Remove(capabilities); delete capabilities; } } // _InitCapabilities void HaikuKernelFileSystem::_InitCapabilities() { fCapabilities.ClearAll(); // FS interface type fClientFSType = CLIENT_FS_HAIKU_KERNEL; // FS operations fCapabilities.Set(FS_CAPABILITY_MOUNT, fFSModule->mount); } /*static*/ void HaikuKernelFileSystem::_InitNodeCapabilities(fs_vnode_ops* ops, FSVNodeCapabilities& capabilities) { capabilities.ClearAll(); // vnode operations capabilities.Set(FS_VNODE_CAPABILITY_LOOKUP, ops->lookup); capabilities.Set(FS_VNODE_CAPABILITY_GET_VNODE_NAME, ops->get_vnode_name); capabilities.Set(FS_VNODE_CAPABILITY_PUT_VNODE, ops->put_vnode); capabilities.Set(FS_VNODE_CAPABILITY_REMOVE_VNODE, ops->remove_vnode); // asynchronous I/O capabilities.Set(FS_VNODE_CAPABILITY_IO, ops->io); capabilities.Set(FS_VNODE_CAPABILITY_CANCEL_IO, ops->cancel_io); // cache file access capabilities.Set(FS_VNODE_CAPABILITY_GET_FILE_MAP, ops->get_file_map); // common operations capabilities.Set(FS_VNODE_CAPABILITY_IOCTL, ops->ioctl); capabilities.Set(FS_VNODE_CAPABILITY_SET_FLAGS, ops->set_flags); capabilities.Set(FS_VNODE_CAPABILITY_SELECT, ops->select); capabilities.Set(FS_VNODE_CAPABILITY_DESELECT, ops->deselect); capabilities.Set(FS_VNODE_CAPABILITY_FSYNC, ops->fsync); capabilities.Set(FS_VNODE_CAPABILITY_READ_SYMLINK, ops->read_symlink); capabilities.Set(FS_VNODE_CAPABILITY_CREATE_SYMLINK, ops->create_symlink); capabilities.Set(FS_VNODE_CAPABILITY_LINK, ops->link); capabilities.Set(FS_VNODE_CAPABILITY_UNLINK, ops->unlink); capabilities.Set(FS_VNODE_CAPABILITY_RENAME, ops->rename); capabilities.Set(FS_VNODE_CAPABILITY_ACCESS, ops->access); capabilities.Set(FS_VNODE_CAPABILITY_READ_STAT, ops->read_stat); capabilities.Set(FS_VNODE_CAPABILITY_WRITE_STAT, ops->write_stat); // file operations capabilities.Set(FS_VNODE_CAPABILITY_CREATE, ops->create); capabilities.Set(FS_VNODE_CAPABILITY_OPEN, ops->open); capabilities.Set(FS_VNODE_CAPABILITY_CLOSE, ops->close); capabilities.Set(FS_VNODE_CAPABILITY_FREE_COOKIE, ops->free_cookie); capabilities.Set(FS_VNODE_CAPABILITY_READ, ops->read); capabilities.Set(FS_VNODE_CAPABILITY_WRITE, ops->write); // directory operations capabilities.Set(FS_VNODE_CAPABILITY_CREATE_DIR, ops->create_dir); capabilities.Set(FS_VNODE_CAPABILITY_REMOVE_DIR, ops->remove_dir); capabilities.Set(FS_VNODE_CAPABILITY_OPEN_DIR, ops->open_dir); capabilities.Set(FS_VNODE_CAPABILITY_CLOSE_DIR, ops->close_dir); capabilities.Set(FS_VNODE_CAPABILITY_FREE_DIR_COOKIE, ops->free_dir_cookie); capabilities.Set(FS_VNODE_CAPABILITY_READ_DIR, ops->read_dir); capabilities.Set(FS_VNODE_CAPABILITY_REWIND_DIR, ops->rewind_dir); // attribute directory operations capabilities.Set(FS_VNODE_CAPABILITY_OPEN_ATTR_DIR, ops->open_attr_dir); capabilities.Set(FS_VNODE_CAPABILITY_CLOSE_ATTR_DIR, ops->close_attr_dir); capabilities.Set(FS_VNODE_CAPABILITY_FREE_ATTR_DIR_COOKIE, ops->free_attr_dir_cookie); capabilities.Set(FS_VNODE_CAPABILITY_READ_ATTR_DIR, ops->read_attr_dir); capabilities.Set(FS_VNODE_CAPABILITY_REWIND_ATTR_DIR, ops->rewind_attr_dir); // attribute operations capabilities.Set(FS_VNODE_CAPABILITY_CREATE_ATTR, ops->create_attr); capabilities.Set(FS_VNODE_CAPABILITY_OPEN_ATTR, ops->open_attr); capabilities.Set(FS_VNODE_CAPABILITY_CLOSE_ATTR, ops->close_attr); capabilities.Set(FS_VNODE_CAPABILITY_FREE_ATTR_COOKIE, ops->free_attr_cookie); capabilities.Set(FS_VNODE_CAPABILITY_READ_ATTR, ops->read_attr); capabilities.Set(FS_VNODE_CAPABILITY_WRITE_ATTR, ops->write_attr); capabilities.Set(FS_VNODE_CAPABILITY_READ_ATTR_STAT, ops->read_attr_stat); capabilities.Set(FS_VNODE_CAPABILITY_WRITE_ATTR_STAT, ops->write_attr_stat); capabilities.Set(FS_VNODE_CAPABILITY_RENAME_ATTR, ops->rename_attr); capabilities.Set(FS_VNODE_CAPABILITY_REMOVE_ATTR, ops->remove_attr); // support for node and FS layers capabilities.Set(FS_VNODE_CAPABILITY_CREATE_SPECIAL_NODE, ops->create_special_node); capabilities.Set(FS_VNODE_CAPABILITY_GET_SUPER_VNODE, ops->get_super_vnode); } // #pragma mark - bootstrapping status_t userlandfs_create_file_system(const char* fsName, image_id image, FileSystem** _fileSystem) { // get the modules module_info** modules; status_t error = get_image_symbol(image, "modules", B_SYMBOL_TYPE_DATA, (void**)&modules); if (error != B_OK) RETURN_ERROR(error); // module name must match "file_systems/<name>/v1" char moduleName[B_PATH_NAME_LENGTH]; snprintf(moduleName, sizeof(moduleName), "file_systems/%s/v1", fsName); // find the module file_system_module_info* module = NULL; for (int32 i = 0; modules[i] && modules[i]->name; i++) { if (strcmp(modules[i]->name, moduleName) == 0) { module = (file_system_module_info*)modules[i]; break; } } if (!module) RETURN_ERROR(B_ERROR); // create the file system HaikuKernelFileSystem* fileSystem = new(std::nothrow) HaikuKernelFileSystem(fsName, module); if (!fileSystem) RETURN_ERROR(B_NO_MEMORY); error = fileSystem->Init(); if (error != B_OK) { delete fileSystem; return error; } *_fileSystem = fileSystem; return B_OK; }
4,316
11,868
<gh_stars>1000+ package org.openapitools.api; import java.math.BigDecimal; import org.openapitools.model.TestResponse; import org.openapitools.api.TestHeadersApiService; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import io.swagger.annotations.*; import java.io.InputStream; import org.apache.cxf.jaxrs.ext.PATCH; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import java.util.Map; import java.util.List; import javax.validation.constraints.*; @Path("/test-headers") @RequestScoped @Api(description = "the test-headers API") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSCXFCDIServerCodegen") public class TestHeadersApi { @Context SecurityContext securityContext; @Inject TestHeadersApiService delegate; @GET @Produces({ "application/json" }) @ApiOperation(value = "test headers", notes = "desc", response = TestResponse.class, tags={ "verify-default-value" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "default response", response = TestResponse.class) }) public Response headersTest( @ApiParam(value = "" , defaultValue="11.2")@HeaderParam("headerNumber") BigDecimal headerNumber, @ApiParam(value = "" , defaultValue="qwerty")@HeaderParam("headerString") String headerString, @ApiParam(value = "" , defaultValue="qwerty")@HeaderParam("headerStringWrapped") String headerStringWrapped, @ApiParam(value = "" , defaultValue="qwerty\"with quotes\" test")@HeaderParam("headerStringQuotes") String headerStringQuotes, @ApiParam(value = "" , defaultValue="qwerty\"with quotes\" test")@HeaderParam("headerStringQuotesWrapped") String headerStringQuotesWrapped, @ApiParam(value = "" , defaultValue="true")@HeaderParam("headerBoolean") Boolean headerBoolean) { return delegate.headersTest(headerNumber, headerString, headerStringWrapped, headerStringQuotes, headerStringQuotesWrapped, headerBoolean, securityContext); } }
728
420
#!/usr/bin/env python # encoding: utf-8 # Copyright (c) 2012-2016 Seafile Ltd. import hashlib import random import sys import time # Use the system PRNG if possible try: random = random.SystemRandom() using_sysrandom = True except NotImplementedError: import warnings warnings.warn('A secure pseudo-random number generator is not available ' 'on your system. Falling back to Mersenne Twister.') using_sysrandom = False def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), '')).encode('utf-8') ).digest()) return ''.join(random.choice(allowed_chars) for i in range(length)) if __name__ == "__main__": chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' key = get_random_string(50, chars) if len(sys.argv) == 2: fp = open(sys.argv[1], 'w') fp.write("SECRET_KEY = \"%s\"\n" % key) fp.close() else: print(key)
813
483
/* * Copyright (c) 2017-2020. Nitrite author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dizitart.no2.support; import com.fasterxml.jackson.core.JsonGenerator; import org.apache.commons.codec.binary.Hex; import org.dizitart.no2.Nitrite; import org.dizitart.no2.collection.Document; import org.dizitart.no2.collection.DocumentCursor; import org.dizitart.no2.collection.NitriteCollection; import org.dizitart.no2.common.PersistentCollection; import org.dizitart.no2.exceptions.NitriteIOException; import org.dizitart.no2.index.IndexDescriptor; import org.dizitart.no2.repository.ObjectRepository; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.*; import static org.dizitart.no2.common.Constants.*; import static org.dizitart.no2.common.util.ObjectUtils.getKeyName; import static org.dizitart.no2.common.util.ObjectUtils.getKeyedRepositoryType; /** * @author <NAME> */ class NitriteJsonExporter { private final Nitrite db; private JsonGenerator generator; private ExportOptions options; public NitriteJsonExporter(Nitrite db) { this.db = db; } public void setGenerator(JsonGenerator generator) { this.generator = generator; } public void exportData() throws IOException, ClassNotFoundException { List<PersistentCollection<?>> collections = options.getCollections(); Set<String> collectionNames; Set<String> repositoryNames; Map<String, Set<String>> keyedRepositoryNames; if (collections.isEmpty()) { collectionNames = db.listCollectionNames(); repositoryNames = db.listRepositories(); keyedRepositoryNames = db.listKeyedRepository(); } else { collectionNames = new HashSet<>(); repositoryNames = new HashSet<>(); keyedRepositoryNames = new HashMap<>(); for (PersistentCollection<?> collection : collections) { String name; if (collection instanceof NitriteCollection) { NitriteCollection nitriteCollection = (NitriteCollection) collection; name = nitriteCollection.getName(); collectionNames.add(name); } else if (collection instanceof ObjectRepository) { ObjectRepository<?> repository = (ObjectRepository<?>) collection; name = repository.getDocumentCollection().getName(); if (name.contains(KEY_OBJ_SEPARATOR)) { String key = getKeyName(name); String type = getKeyedRepositoryType(name); Set<String> types; if (keyedRepositoryNames.containsKey(key)) { types = keyedRepositoryNames.get(key); } else { types = new LinkedHashSet<>(); } types.add(type); keyedRepositoryNames.put(key, types); } else { repositoryNames.add(name); } } } } exportData(collectionNames, repositoryNames, keyedRepositoryNames); generator.close(); } private void exportData(Set<String> collectionNames, Set<String> repositoryNames, Map<String, Set<String>> keyedRepositoryNames) throws IOException, ClassNotFoundException { generator.writeStartObject(); generator.writeFieldName(TAG_COLLECTIONS); generator.writeStartArray(); for (String collectionName : collectionNames) { NitriteCollection nitriteCollection = db.getCollection(collectionName); writeCollection(nitriteCollection); } generator.writeEndArray(); generator.writeFieldName(TAG_REPOSITORIES); generator.writeStartArray(); for (String repoName : repositoryNames) { Class<?> type = Class.forName(repoName); ObjectRepository<?> repository = db.getRepository(type); writeRepository(repository); } generator.writeEndArray(); generator.writeFieldName(TAG_KEYED_REPOSITORIES); generator.writeStartArray(); for (Map.Entry<String, Set<String>> entry : keyedRepositoryNames.entrySet()) { String key = entry.getKey(); Set<String> typeNames = entry.getValue(); for (String typeName : typeNames) { Class<?> type = Class.forName(typeName); ObjectRepository<?> repository = db.getRepository(type, key); writeKeyedRepository(key, repository); } } generator.writeEndArray(); generator.writeEndObject(); } private void writeRepository(ObjectRepository<?> repository) throws IOException { generator.writeStartObject(); generator.writeFieldName(TAG_TYPE); generator.writeString(repository.getType().getName()); Collection<IndexDescriptor> indices = repository.listIndices(); writeIndices(indices); DocumentCursor cursor = repository.getDocumentCollection().find(); writeContent(cursor); generator.writeEndObject(); } private void writeKeyedRepository(String key, ObjectRepository<?> repository) throws IOException { generator.writeStartObject(); generator.writeFieldName(TAG_KEY); generator.writeString(key); generator.writeFieldName(TAG_TYPE); generator.writeString(repository.getType().getName()); Collection<IndexDescriptor> indices = repository.listIndices(); writeIndices(indices); DocumentCursor cursor = repository.getDocumentCollection().find(); writeContent(cursor); generator.writeEndObject(); } private void writeCollection(NitriteCollection nitriteCollection) throws IOException { generator.writeStartObject(); generator.writeFieldName(TAG_NAME); generator.writeString(nitriteCollection.getName()); Collection<IndexDescriptor> indices = nitriteCollection.listIndices(); writeIndices(indices); DocumentCursor cursor = nitriteCollection.find(); writeContent(cursor); generator.writeEndObject(); } private void writeIndices(Collection<IndexDescriptor> indices) throws IOException { generator.writeFieldName(TAG_INDICES); generator.writeStartArray(); if (options.isExportIndices()) { for (IndexDescriptor index : indices) { generator.writeStartObject(); generator.writeFieldName(TAG_INDEX); generator.writeObject(writeEncodedObject(index)); generator.writeEndObject(); } } generator.writeEndArray(); } private void writeContent(DocumentCursor cursor) throws IOException { generator.writeFieldName(TAG_DATA); generator.writeStartArray(); if (options.isExportData()) { for (Document document : cursor) { generator.writeStartObject(); generator.writeFieldName(TAG_KEY); generator.writeObject(writeEncodedObject(document.get(DOC_ID))); generator.writeFieldName(TAG_VALUE); generator.writeObject(writeEncodedObject(document)); generator.writeEndObject(); } } generator.writeEndArray(); } public void setOptions(ExportOptions options) { this.options = options; } private String writeEncodedObject(Object object) { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { try (ObjectOutputStream oos = new ObjectOutputStream(os)) { oos.writeObject(object); byte[] data = os.toByteArray(); return Hex.encodeHexString(data); } } catch (IOException e) { throw new NitriteIOException("failed to write object", e); } } }
3,602
535
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Unlimited developers import asyncio from test_framework.util import assert_equal from test_framework.test_framework import BitcoinTestFramework from test_framework.loginit import logging from test_framework.electrumutil import bitcoind_electrum_args, \ ElectrumConnection def versiontuple(v): v = tuple(map(int, (v.split(".")))) if len(v) == 2: v = v + (0,) return v class ElectrumBasicTests(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [bitcoind_electrum_args()] def run_test(self): n = self.nodes[0] # Bump out of IBD n.generate(1) async def async_tests(): electrum_client = ElectrumConnection() await electrum_client.connect() res = await electrum_client.call("server.features") # Keys that the server MUST support assert_equal(n.getblockhash(0), res['genesis_hash']) assert_equal("sha256", res['hash_function']) assert(versiontuple(res['protocol_min']) >= versiontuple("1.4")) assert(versiontuple(res['protocol_max']) >= versiontuple("1.4")) assert(len(res['server_version'])) loop = asyncio.get_event_loop() loop.run_until_complete(async_tests()) if __name__ == '__main__': ElectrumBasicTests().main()
618
460
<filename>kettle-ext/src/main/java/org/flhy/ext/trans/steps/MultiwayMergeJoin.java package org.flhy.ext.trans.steps; import com.mxgraph.model.mxCell; import com.mxgraph.util.mxUtils; import org.flhy.ext.core.PropsUI; import org.flhy.ext.trans.step.AbstractStep; import org.flhy.ext.utils.JSONArray; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.step.StepIOMetaInterface; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.step.errorhandling.Stream; import org.pentaho.di.trans.step.errorhandling.StreamIcon; import org.pentaho.di.trans.step.errorhandling.StreamInterface; import org.pentaho.di.trans.step.errorhandling.StreamInterface.StreamType; import org.pentaho.di.trans.steps.multimerge.MultiMergeJoinMeta; import org.pentaho.metastore.api.IMetaStore; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.List; @Component("MultiwayMergeJoin") @Scope("prototype") public class MultiwayMergeJoin extends AbstractStep { @Override public void decode(StepMetaInterface stepMetaInterface, mxCell cell, List<DatabaseMeta> databases, IMetaStore metaStore) throws Exception { MultiMergeJoinMeta mergeJoinMeta = (MultiMergeJoinMeta) stepMetaInterface; JSONArray jsonArray = JSONArray.fromObject(cell.getAttribute("keys")); String[] keyFields = new String[jsonArray.size()]; for(int i=0; i<jsonArray.size(); i++) keyFields[i] = jsonArray.getString(i); mergeJoinMeta.setKeyFields(keyFields); StepIOMetaInterface stepIOMeta = mergeJoinMeta.getStepIOMeta(); jsonArray = JSONArray.fromObject(cell.getAttribute("stepnames")); for(int i=0; i<jsonArray.size(); i++) { stepIOMeta.addStream(new Stream( StreamType.INFO, null, BaseMessages.getString(MultiMergeJoinMeta.class, "MultiMergeJoin.InfoStream.Description" ), StreamIcon.INFO, null ) ); } String[] inputSteps = new String[jsonArray.size()]; List<StreamInterface> infoStreams = stepIOMeta.getInfoStreams(); for (int i = 0; i < infoStreams.size(); i++) { infoStreams.get(i).setSubject(jsonArray.getString(i)); inputSteps[i] = jsonArray.getString(i); } mergeJoinMeta.setInputSteps(inputSteps); mergeJoinMeta.setJoinType(cell.getAttribute("join_type")); } @Override public Element encode(StepMetaInterface stepMetaInterface) throws Exception { Document doc = mxUtils.createDocument(); Element e = doc.createElement(PropsUI.TRANS_STEP_NAME); MultiMergeJoinMeta mergeJoinMeta = (MultiMergeJoinMeta) stepMetaInterface; e.setAttribute("join_type", mergeJoinMeta.getJoinType()); JSONArray jsonArray = new JSONArray(); List<StreamInterface> infoStreams = mergeJoinMeta.getStepIOMeta().getInfoStreams(); for (int i = 0; i < infoStreams.size(); i++) { jsonArray.add(infoStreams.get(i).getStepname()); } e.setAttribute("stepnames", jsonArray.toString()); jsonArray = new JSONArray(); String[] keyFields = mergeJoinMeta.getKeyFields(); for (int i = 0; i < keyFields.length; i++) { jsonArray.add(keyFields[i]); } e.setAttribute("keys", jsonArray.toString()); return e; } }
1,148
679
<filename>main/dbaccess/source/ext/macromigration/macromigrationwizard.cxx /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbmm.hxx" #include "dbmm_module.hxx" #include "dbmm_global.hrc" #include "macromigrationdialog.hxx" /** === begin UNO includes === **/ #include <com/sun/star/ucb/AlreadyInitializedException.hpp> #include <com/sun/star/sdb/XOfficeDatabaseDocument.hpp> #include <com/sun/star/frame/XStorable.hpp> /** === end UNO includes === **/ #include <comphelper/componentcontext.hxx> #include <svtools/genericunodialog.hxx> //........................................................................ namespace dbmm { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::XInterface; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::uno::UNO_SET_THROW; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::uno::Any; using ::com::sun::star::uno::makeAny; using ::com::sun::star::uno::XComponentContext; using ::com::sun::star::uno::Sequence; using ::com::sun::star::beans::XPropertySetInfo; using ::com::sun::star::beans::Property; using ::com::sun::star::ucb::AlreadyInitializedException; using ::com::sun::star::sdb::XOfficeDatabaseDocument; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::frame::XStorable; /** === end UNO using === **/ //==================================================================== //= MacroMigrationDialogService //==================================================================== class MacroMigrationDialogService; typedef ::svt::OGenericUnoDialog MacroMigrationDialogService_Base; typedef ::comphelper::OPropertyArrayUsageHelper< MacroMigrationDialogService > MacroMigrationDialogService_PBase; class MacroMigrationDialogService :public MacroMigrationDialogService_Base ,public MacroMigrationDialogService_PBase ,public MacroMigrationModuleClient { public: MacroMigrationDialogService( const Reference< XComponentContext >& _rxContext ); // XTypeProvider virtual Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(RuntimeException); virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(RuntimeException); // XInitialization virtual void SAL_CALL initialize( const com::sun::star::uno::Sequence< com::sun::star::uno::Any >& aArguments ) throw(com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException); // XPropertySet virtual Reference< XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(RuntimeException); virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); // OPropertyArrayUsageHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; // helper for factories static Reference< XInterface > SAL_CALL Create( const Reference< XComponentContext >& _rxContext ); static ::rtl::OUString SAL_CALL getImplementationName_static() throw(RuntimeException); static Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_static() throw(RuntimeException); protected: ~MacroMigrationDialogService(); protected: virtual Dialog* createDialog( Window* _pParent ); virtual void destroyDialog(); private: ::comphelper::ComponentContext m_aContext; Reference< XOfficeDatabaseDocument > m_xDocument; }; //==================================================================== //= MacroMigrationDialogService //==================================================================== //-------------------------------------------------------------------- MacroMigrationDialogService::MacroMigrationDialogService( const Reference< XComponentContext >& _rxContext ) :MacroMigrationDialogService_Base( _rxContext ) ,m_aContext( _rxContext ) { m_bNeedInitialization = true; } //-------------------------------------------------------------------- MacroMigrationDialogService::~MacroMigrationDialogService() { // we do this here cause the base class' call to destroyDialog won't reach us anymore : we're within an dtor, // so this virtual-method-call the base class does does not work, we're already dead then ... if ( m_pDialog ) { ::osl::MutexGuard aGuard( m_aMutex ); if ( m_pDialog ) destroyDialog(); } } //-------------------------------------------------------------------- Reference< XInterface > SAL_CALL MacroMigrationDialogService::Create( const Reference< XComponentContext >& _rxContext ) { return *(new MacroMigrationDialogService( _rxContext ) ); } //-------------------------------------------------------------------- Dialog* MacroMigrationDialogService::createDialog( Window* _pParent ) { return new MacroMigrationDialog( _pParent, m_aContext, m_xDocument ); } //-------------------------------------------------------------------- void MacroMigrationDialogService::destroyDialog() { MacroMigrationDialogService_Base::destroyDialog(); } //-------------------------------------------------------------------- Sequence< sal_Int8 > SAL_CALL MacroMigrationDialogService::getImplementationId() throw(RuntimeException) { static ::cppu::OImplementationId* pId = NULL; if ( !pId ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if ( !pId ) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } //-------------------------------------------------------------------- ::rtl::OUString SAL_CALL MacroMigrationDialogService::getImplementationName_static() throw(RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.dbaccess.macromigration.MacroMigrationDialogService" ) ); } //-------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL MacroMigrationDialogService::getSupportedServiceNames_static() throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(1); aServices[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdb.application.MacroMigrationWizard" ) ); return aServices; } //-------------------------------------------------------------------- ::rtl::OUString SAL_CALL MacroMigrationDialogService::getImplementationName() throw(RuntimeException) { return getImplementationName_static(); } //-------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL MacroMigrationDialogService::getSupportedServiceNames() throw(RuntimeException) { return getSupportedServiceNames_static(); } //-------------------------------------------------------------------- void SAL_CALL MacroMigrationDialogService::initialize( const Sequence< Any >& _rArguments ) throw(Exception, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); if ( m_bInitialized ) throw AlreadyInitializedException( ::rtl::OUString(), *this ); if ( _rArguments.getLength() != 1 ) throw IllegalArgumentException( String(MacroMigrationResId(STR_INVALID_NUMBER_ARGS)), *this, 1 ); m_xDocument.set( _rArguments[0], UNO_QUERY ); if ( !m_xDocument.is() ) throw IllegalArgumentException( String(MacroMigrationResId(STR_NO_DATABASE)), *this, 1 ); Reference< XStorable > xDocStor( m_xDocument, UNO_QUERY_THROW ); if ( xDocStor->isReadonly() ) throw IllegalArgumentException( String(MacroMigrationResId(STR_NOT_READONLY)), *this, 1 ); m_bInitialized = true; } //-------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL MacroMigrationDialogService::getPropertySetInfo() throw(RuntimeException) { return createPropertySetInfo( getInfoHelper() ); } //-------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& SAL_CALL MacroMigrationDialogService::getInfoHelper() { return *const_cast< MacroMigrationDialogService* >( this )->getArrayHelper(); } //-------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* MacroMigrationDialogService::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties( aProps ); return new ::cppu::OPropertyArrayHelper( aProps ); } //-------------------------------------------------------------------- void createRegistryInfo_MacroMigrationDialogService() { static OAutoRegistration< MacroMigrationDialogService > aAutoRegistration; } //........................................................................ } // namespace dbmm //........................................................................
3,479
2,139
package org.jruby.ir.operands; import org.jruby.ir.IRVisitor; import org.jruby.ir.persistence.IRReaderDecoder; import org.jruby.ir.persistence.IRWriterEncoder; import org.jruby.ir.runtime.IRRuntimeHelpers; import org.jruby.ir.transformations.inlining.CloneInfo; import org.jruby.parser.StaticScope; import org.jruby.runtime.DynamicScope; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import java.util.List; /** * Represents the script's __FILE__. Isolated as its own operand because we need to be able to replace it when loading * persisted IR from a location different than original script. */ public class Filename extends Operand { public Filename() { super(); } @Override public OperandType getOperandType() { return OperandType.FILENAME; } @Override public boolean hasKnownValue() { return false; } @Override public void encode(IRWriterEncoder e) { // we only do base encoding because filename must be provided while deserializing (#3109) e.encode(getOperandType().getCoded()); } public static Filename decode(IRReaderDecoder d) { return new Filename(); } @Override public void visit(IRVisitor visitor) { visitor.Filename(this); } @Override public Object retrieve(ThreadContext context, IRubyObject self, StaticScope currScope, DynamicScope currDynScope, Object[] temp) { return IRRuntimeHelpers.getFileNameStringFromScope(context, currScope); } @Override public Operand cloneForInlining(CloneInfo ii) { return this; } @Override public void addUsedVariables(List<Variable> l) { /* Do nothing */ } }
618
1,921
def end_reachable(arr): if len(arr) < 2: return True for i in range(2, len(arr) + 1): if arr[len(arr) - i] >= i - 1: return end_reachable(arr[:len(arr) - i + 1]) # Tests assert end_reachable([1, 3, 1, 2, 0, 1]) assert not end_reachable([1, 2, 1, 0, 0])
143
419
{ "PlaceholderDesc_Tale_QuestText": "Text that is added to the quest.", "PlaceholderDesc_Tale_QuestText_LangKey": "Language key for the text that is added to the quest.", "PlaceholderDesc_Tale_QuestText_Preview": "Preview for the textline that is added. All line breaks will be removed and the text will be cut if it is to long. This placeholder is intended to be used in comments to increase the readability of the dialog if language keys are used." }
131
666
package com.renyu.kotlin.chapter3; public class ClassStudyJava { public static void main(String[] args) { ClassParent parent=new ClassChild(12); parent.funParent(); ((ClassChild) parent).funChild(); C.getInstance(); C.getCompanionValue(); } }
119
577
// // PRCommentActionView.h // PlainReader // // Created by guojiubo on 12/11/14. // Copyright (c) 2014 guojiubo. All rights reserved. // #import <UIKit/UIKit.h> #import "PRCellButton.h" #import "PRComment.h" @interface PRCommentActionView : UIView @property (nonatomic, strong) PRCellButton *supportButton; @property (nonatomic, strong) PRCellButton *opposeButton; @property (nonatomic, strong) PRCellButton *replyButton; @property (nonatomic, strong) PRComment *comment; @end
165
1,473
/* * Copyright 2019 NAVER Corp. * * 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.navercorp.pinpoint.hbase.schema.core.command; import com.navercorp.pinpoint.common.hbase.HbaseAdminOperation; import com.navercorp.pinpoint.hbase.schema.reader.InvalidHbaseSchemaException; import com.navercorp.pinpoint.hbase.schema.reader.core.ChangeSet; import com.navercorp.pinpoint.hbase.schema.reader.core.ChangeType; import com.navercorp.pinpoint.hbase.schema.reader.core.ColumnFamilyChange; import com.navercorp.pinpoint.hbase.schema.reader.core.ColumnFamilyConfiguration; import com.navercorp.pinpoint.hbase.schema.reader.core.CreateColumnFamilyChange; import com.navercorp.pinpoint.hbase.schema.reader.core.CreateTableChange; import com.navercorp.pinpoint.hbase.schema.reader.core.ModifyTableChange; import com.navercorp.pinpoint.hbase.schema.reader.core.TableChange; import com.navercorp.pinpoint.hbase.schema.reader.core.TableConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.junit.Test; import org.mockito.Mockito; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author <NAME> */ public class HbaseSchemaCommandManagerTest { @Test public void shouldFilterTablesFromDifferentNamespace() { String namespace = "namespace"; String differentNamespace = "differentNamespace"; String tableName = "table1"; HTableDescriptor sameNamespaceHtd = createHtd(namespace, tableName, "CF1"); HTableDescriptor differentNamespaceHtd = createHtd(differentNamespace, tableName, "CF1"); List<HTableDescriptor> htds = Arrays.asList(sameNamespaceHtd, differentNamespaceHtd); HbaseSchemaCommandManager manager = new HbaseSchemaCommandManager(namespace, null, htds); ColumnFamilyChange createColumnFamilyChange = newColumnFamilyChange("CF2"); TableChange modifyTableChange = newTableChange(ChangeType.MODIFY, tableName, createColumnFamilyChange); ChangeSet modifyTableChangeSet = newChangeSet(modifyTableChange); manager.applyChangeSet(modifyTableChangeSet); List<HTableDescriptor> schemaSnapshot = manager.getSchemaSnapshot(); assertThat(schemaSnapshot, contains(sameNamespaceHtd)); assertThat(schemaSnapshot, not(contains(differentNamespaceHtd))); } @Test(expected = InvalidHbaseSchemaException.class) public void creatingExistingTableShouldFail() { String namespace = "namespace"; String tableName = "table"; HTableDescriptor existingTable = createHtd(namespace, tableName, "CF"); HbaseSchemaCommandManager manager = new HbaseSchemaCommandManager(namespace, null, Arrays.asList(existingTable)); TableChange createTableChange = newTableChange(ChangeType.CREATE, tableName); ChangeSet createTableChangeSet = newChangeSet(createTableChange); manager.applyChangeSet(createTableChangeSet); } @Test(expected = InvalidHbaseSchemaException.class) public void modifyingNonExistingTableShouldFail() { String namespace = "namespace"; String tableName = "table"; String nonExistingTableName = "anotherTable"; HTableDescriptor existingTable = createHtd(namespace, tableName, "CF"); HbaseSchemaCommandManager manager = new HbaseSchemaCommandManager(namespace, null, Arrays.asList(existingTable)); TableChange modifyTableChange = newTableChange(ChangeType.MODIFY, nonExistingTableName); ChangeSet modifyTableChangeSet = newChangeSet(modifyTableChange); manager.applyChangeSet(modifyTableChangeSet); } @Test public void failedChangesShouldNotAffectTheSchema() { String namespace = "namespace"; String tableName = "table"; String columnFamilyName = "CF"; HbaseSchemaCommandManager manager = new HbaseSchemaCommandManager(namespace, null); // initial create table ColumnFamilyChange columnFamilyChange = newColumnFamilyChange(columnFamilyName); TableChange createTableChange = newTableChange(ChangeType.CREATE, tableName, columnFamilyChange); ChangeSet createTableChangeSet = newChangeSet(createTableChange); manager.applyChangeSet(createTableChangeSet); List<HTableDescriptor> initialSnapshot = manager.getSchemaSnapshot(); // modify non-existing table TableChange modifyNonExistingTableChange = newTableChange(ChangeType.MODIFY, "nonExistingTable", newColumnFamilyChange("newCF")); ChangeSet modifyNonExistingTableChangeSet = newChangeSet(modifyNonExistingTableChange); try { manager.applyChangeSet(modifyNonExistingTableChangeSet); fail("Expected an InvalidHbaseSchemaException to be thrown"); } catch (InvalidHbaseSchemaException expected) { List<HTableDescriptor> currentSnapshot = manager.getSchemaSnapshot(); assertThat(currentSnapshot, equalTo(initialSnapshot)); } // create existing table TableChange createExistingTableChange = newTableChange(ChangeType.CREATE, tableName); ChangeSet createExistingTableChangeSet = newChangeSet(createExistingTableChange); try { manager.applyChangeSet(createExistingTableChangeSet); fail("Expected an InvalidHbaseSchemaException to be thrown"); } catch (InvalidHbaseSchemaException expected) { List<HTableDescriptor> currentSnapshot = manager.getSchemaSnapshot(); assertThat(currentSnapshot, equalTo(initialSnapshot)); } // create existing column family ColumnFamilyChange createExistingColumnFamilyChange = newColumnFamilyChange(columnFamilyName); TableChange createExistingColumnFamilyTableChange = newTableChange(ChangeType.MODIFY, tableName, createExistingColumnFamilyChange); ChangeSet createExistingColumnFamilyChangeSet = newChangeSet(createExistingColumnFamilyTableChange); try { manager.applyChangeSet(createExistingColumnFamilyChangeSet); fail("Expected an InvalidHbaseSchemaException to be thrown"); } catch (InvalidHbaseSchemaException expected) { List<HTableDescriptor> currentSnapshot = manager.getSchemaSnapshot(); assertThat(currentSnapshot, equalTo(initialSnapshot)); } } @Test public void modifyingTheSameTableMultipleTimesShouldBeMerged() { String namespace = "namespace"; String tableName = "table"; String existingColumnFamily = "CF"; String newColumnFamily1 = "CF1"; String newColumnFamily2 = "CF2"; HTableDescriptor existingHtd = createHtd(namespace, tableName, existingColumnFamily); HbaseSchemaCommandManager manager = new HbaseSchemaCommandManager(namespace, null, Arrays.asList(new HTableDescriptor(existingHtd))); ChangeSet createColumnFamilyChangeSet1 = newChangeSet(newTableChange(ChangeType.MODIFY, tableName, newColumnFamilyChange(newColumnFamily1))); ChangeSet createColumnFamilyChangeSet2 = newChangeSet(newTableChange(ChangeType.MODIFY, tableName, newColumnFamilyChange(newColumnFamily2))); manager.applyChangeSet(createColumnFamilyChangeSet1); manager.applyChangeSet(createColumnFamilyChangeSet2); // verify schema snapshot List<HTableDescriptor> schemaSnapshot = manager.getSchemaSnapshot(); assertThat(schemaSnapshot.size(), is(1)); HTableDescriptor snapshotTable = schemaSnapshot.get(0); assertThat(snapshotTable.getTableName(), is(TableName.valueOf(namespace, tableName))); List<String> snapshotColumnFamilies = snapshotTable.getFamilies().stream().map(HColumnDescriptor::getNameAsString).collect(Collectors.toList()); assertThat(snapshotColumnFamilies, contains(existingColumnFamily, newColumnFamily1, newColumnFamily2)); // verify command - should add 2 column families HbaseAdminOperation mockHbaseAdminOperation = Mockito.mock(HbaseAdminOperation.class); when(mockHbaseAdminOperation.getTableDescriptor(existingHtd.getTableName())).thenReturn(existingHtd); doNothing().when(mockHbaseAdminOperation).addColumn(any(TableName.class), any(HColumnDescriptor.class)); doNothing().when(mockHbaseAdminOperation).createTable(any(HTableDescriptor.class)); for (TableCommand tableCommand : manager.getCommands()) { tableCommand.execute(mockHbaseAdminOperation); } verify(mockHbaseAdminOperation, times(2)).addColumn(any(TableName.class), any(HColumnDescriptor.class)); verify(mockHbaseAdminOperation, never()).createTable(any(HTableDescriptor.class)); } @Test public void creatingAndModifyingTheSameTableShouldBeMerged() { String namespace = "namespace"; String tableName = "table"; String columnFamily1 = "CF1"; String columnFamily2 = "CF2"; String columnFamily3 = "CF3"; HbaseSchemaCommandManager manager = new HbaseSchemaCommandManager(namespace, null); ChangeSet createTableChangeSet = newChangeSet(newTableChange(ChangeType.CREATE, tableName, newColumnFamilyChange(columnFamily1))); ChangeSet addColumnFamilyChangeSet1 = newChangeSet(newTableChange(ChangeType.MODIFY, tableName, newColumnFamilyChange(columnFamily2))); ChangeSet addColumnFamilyChangeSet2 = newChangeSet(newTableChange(ChangeType.MODIFY, tableName, newColumnFamilyChange(columnFamily3))); manager.applyChangeSet(createTableChangeSet); manager.applyChangeSet(addColumnFamilyChangeSet1); manager.applyChangeSet(addColumnFamilyChangeSet2); // verify schema snapshot List<HTableDescriptor> schemaSnapshot = manager.getSchemaSnapshot(); assertThat(schemaSnapshot.size(), is(1)); HTableDescriptor snapshotTable = schemaSnapshot.get(0); assertThat(snapshotTable.getTableName(), is(TableName.valueOf(namespace, tableName))); List<String> snapshotColumnFamilies = snapshotTable.getFamilies().stream().map(HColumnDescriptor::getNameAsString).collect(Collectors.toList()); assertThat(snapshotColumnFamilies, contains(columnFamily1, columnFamily2, columnFamily3)); // verify command - should create 1 table (with all 3 column families) HbaseAdminOperation mockHbaseAdminOperation = Mockito.mock(HbaseAdminOperation.class); when(mockHbaseAdminOperation.tableExists(TableName.valueOf(namespace, tableName))).thenReturn(false); doNothing().when(mockHbaseAdminOperation).createTable(any(HTableDescriptor.class)); for (TableCommand tableCommand : manager.getCommands()) { tableCommand.execute(mockHbaseAdminOperation); } verify(mockHbaseAdminOperation, times(1)).createTable(any(HTableDescriptor.class)); } private ColumnFamilyChange newColumnFamilyChange(String cfName) { return new CreateColumnFamilyChange(cfName, ColumnFamilyConfiguration.EMPTY_CONFIGURATION); } private TableChange newTableChange(ChangeType changeType, String tableName, ColumnFamilyChange... cfChanges) { List<ColumnFamilyChange> columnFamilyChanges = Arrays.asList(cfChanges); switch (changeType) { case CREATE: return new CreateTableChange(tableName, TableConfiguration.EMPTY_CONFIGURATION, columnFamilyChanges, CreateTableChange.SplitOption.NONE); case MODIFY: return new ModifyTableChange(tableName, TableConfiguration.EMPTY_CONFIGURATION, columnFamilyChanges); default: throw new IllegalArgumentException("changeType : " + changeType + " not supported"); } } private ChangeSet newChangeSet(TableChange... tableChanges) { return new ChangeSet("id", "value", Arrays.asList(tableChanges)); } private HTableDescriptor createHtd(String namespace, String tableQualifier, String... columnFamilyNames) { TableName tableName = TableName.valueOf(namespace, tableQualifier); HTableDescriptor htd = new HTableDescriptor(tableName); for (String columnFamilyName : columnFamilyNames) { htd.addFamily(new HColumnDescriptor(columnFamilyName)); } return htd; } }
4,630
2,151
<reponame>zipated/src<filename>native_client/tests/signal_handler_single_step/regs_step_test_guest.c /* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <assert.h> #include <setjmp.h> #include <stdio.h> #include <string.h> #include "native_client/src/trusted/service_runtime/nacl_config.h" #include "native_client/src/untrusted/nacl/syscall_bindings_trampoline.h" #include "native_client/tests/common/register_set.h" #include "native_client/tests/signal_handler_single_step/step_test_common.h" /* * This test program calls a NaCl syscall in an infinite loop with * callee-saved registers set to known values. These register values * are saved to a memory address for cross-checking by the * trusted-code portion of the test case. */ jmp_buf g_jmp_buf; uint32_t g_regs_should_match; #if defined(__i386__) # define SYSCALL_CALLER(suffix) \ __asm__(".pushsection .text, \"ax\", @progbits\n" \ "SyscallCaller" suffix ":\n" \ "movl $1, g_regs_should_match\n" \ "naclcall %esi\n" \ "SyscallReturnAddress" suffix ":\n" \ "movl $0, g_regs_should_match\n" \ "jmp ReturnFromSyscall\n" \ ".popsection\n"); #elif defined(__x86_64__) # define SYSCALL_CALLER(suffix) \ __asm__(".pushsection .text, \"ax\", @progbits\n" \ "SyscallCaller" suffix ":\n" \ "movl $1, g_regs_should_match(%rip)\n" \ /* Call via a temporary register so as not to modify %r12. */ \ "movl %r12d, %eax\n" \ "naclcall %eax, %r15\n" \ "SyscallReturnAddress" suffix ":\n" \ "movl $0, g_regs_should_match(%rip)\n" \ "jmp ReturnFromSyscall\n" \ ".popsection\n"); #elif defined(__arm__) # define SYSCALL_CALLER(suffix) \ __asm__(".pushsection .text, \"ax\", %progbits\n" \ ".p2align 4\n" \ "SyscallCaller" suffix ":\n" \ /* Set g_regs_should_match = 1. */ \ "bic r5, r5, #0xc0000000\n" \ "str r6, [r5]\n" \ /* Call syscall. */ \ "adr lr, SyscallReturnAddress" suffix "\n" \ "nop\n" /* Pad to bundle-align next instruction */ \ "bic r4, r4, #0xc000000f\n" \ "bx r4\n" \ ".p2align 4\n" \ "SyscallReturnAddress" suffix ":\n" \ /* Set g_regs_should_match = 0. */ \ "bic r5, r5, #0xc0000000\n" \ "str r7, [r5]\n" \ "b ReturnFromSyscall\n" \ ".popsection\n"); #elif defined(__mips__) # define SYSCALL_CALLER(suffix) \ __asm__(".pushsection .text, \"ax\", @progbits\n" \ ".p2align 4\n" \ ".set noreorder\n" \ ".globl SyscallCaller" suffix "\n" \ "SyscallCaller" suffix ":\n" \ /* Set g_regs_should_match = 1. */ \ "sw $s2, 0($s1)\n" \ /* Call syscall. */ \ "jalr $s0\n" \ "nop\n" \ ".p2align 4\n" \ ".globl SyscallReturnAddress" suffix "\n" \ "SyscallReturnAddress" suffix ":\n" \ /* Set g_regs_should_match = 0. */ \ "sw $zero, 0($s1)\n" \ "lui $t9, %hi(ReturnFromSyscall)\n" \ "b ReturnFromSyscall\n" \ "addiu $t9, $t9, %lo(ReturnFromSyscall)\n" \ ".set reorder\n" \ ".popsection\n"); #else # error Unsupported architecture #endif SYSCALL_CALLER("1") SYSCALL_CALLER("2") void SyscallCaller1(void); void SyscallCaller2(void); void SyscallReturnAddress1(void); void SyscallReturnAddress2(void); void ReturnFromSyscall(void) { longjmp(g_jmp_buf, 1); } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Expected 1 argument: <memory-address>\n"); return 1; } char *end; struct RegsTestShm *test_shm = (struct RegsTestShm *) strtoul(argv[1], &end, 0); assert(*end == '\0'); test_shm->regs_should_match = &g_regs_should_match; struct NaClSignalContext call_regs; char stack[0x10000]; int call_count = 0; for (call_count = 0; ; call_count++) { uintptr_t syscall_addr; /* * Test fast-path TLS syscalls. We shoe-horn these in after the * first call to test_syscall_1 has enabled single-stepping. */ if (call_count == 1) { syscall_addr = NACL_SYSCALL_ADDR(NACL_sys_tls_get); } else if (call_count == 2) { syscall_addr = NACL_SYSCALL_ADDR(NACL_sys_second_tls_get); } else { syscall_addr = NACL_SYSCALL_ADDR(NACL_sys_test_syscall_1); } /* * Use different expected register values for each call. * Otherwise, the test could accidentally pass because the * stack_ptr reported during the entry to a syscall can happen to * match the stack_ptr saved by the previous syscall. */ RegsFillTestValues(&call_regs, /* seed= */ call_count); #if defined(__i386__) call_regs.esi = syscall_addr; #elif defined(__x86_64__) call_regs.r12 = syscall_addr; #elif defined(__arm__) call_regs.r4 = syscall_addr; call_regs.r5 = (uintptr_t) &g_regs_should_match; call_regs.r6 = 1; call_regs.r7 = 0; #elif defined(__mips__) call_regs.s0 = syscall_addr; call_regs.s1 = (uintptr_t) &g_regs_should_match; call_regs.s2 = 1; #else # error Unsupported architecture #endif call_regs.prog_ctr = (uintptr_t) (call_count % 2 == 0 ? SyscallReturnAddress1 : SyscallReturnAddress2); call_regs.stack_ptr = (uintptr_t) stack + sizeof(stack) - (call_count % 2) * 0x100; RegsApplySandboxConstraints(&call_regs); RegsUnsetNonCalleeSavedRegisters(&call_regs); test_shm->expected_regs = call_regs; if (!setjmp(g_jmp_buf)) { if (call_count % 2 == 0) { JUMP_WITH_REGS(&call_regs, SyscallCaller1); } else { JUMP_WITH_REGS(&call_regs, SyscallCaller2); } } } }
2,990
703
#include <RendererVulkanPCH.h> #include <RendererVulkan/Device/DeviceVulkan.h> #include <RendererVulkan/RendererVulkanDLL.h> #include <RendererVulkan/Resources/BufferVulkan.h> #include <d3d11.h> ezGALBufferVulkan::ezGALBufferVulkan(const ezGALBufferCreationDescription& Description) : ezGALBuffer(Description) , m_buffer(nullptr) , m_indexType(vk::IndexType::eUint16) { } ezGALBufferVulkan::~ezGALBufferVulkan() {} ezResult ezGALBufferVulkan::InitPlatform(ezGALDevice* pDevice, ezArrayPtr<const ezUInt8> pInitialData) { ezGALDeviceVulkan* pVulkanDevice = static_cast<ezGALDeviceVulkan*>(pDevice); vk::BufferCreateInfo bufferCreateInfo = {}; switch (m_Description.m_BufferType) { case ezGALBufferType::ConstantBuffer: bufferCreateInfo.usage = vk::BufferUsageFlagBits::eUniformBuffer; break; case ezGALBufferType::IndexBuffer: bufferCreateInfo.usage = vk::BufferUsageFlagBits::eIndexBuffer; m_indexType = m_Description.m_uiStructSize == 2 ? vk::IndexType::eUint16 : vk::IndexType::eUint32; break; case ezGALBufferType::VertexBuffer: bufferCreateInfo.usage = vk::BufferUsageFlagBits::eVertexBuffer; break; case ezGALBufferType::Generic: //bufferCreateInfo.usage = 0; // TODO Is this correct for Vulkan? break; default: ezLog::Error("Unknown buffer type supplied to CreateBuffer()!"); return EZ_FAILURE; } if (m_Description.m_bAllowShaderResourceView) bufferCreateInfo.usage |= vk::BufferUsageFlagBits::eStorageBuffer; if (m_Description.m_bAllowUAV) bufferCreateInfo.usage |= vk::BufferUsageFlagBits::eStorageBuffer; if (m_Description.m_bStreamOutputTarget) bufferCreateInfo.usage |= vk::BufferUsageFlagBits::eStorageBuffer; // TODO is this correct for vulkan? bufferCreateInfo.usage |= vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst; // TODO optimize this bufferCreateInfo.pQueueFamilyIndices = pVulkanDevice->GetQueueFamilyIndices().GetPtr(); bufferCreateInfo.queueFamilyIndexCount = pVulkanDevice->GetQueueFamilyIndices().GetCount(); bufferCreateInfo.sharingMode = vk::SharingMode::eExclusive; bufferCreateInfo.size = m_Description.m_uiTotalSize; //BufferDesc.CPUAccessFlags = 0; //BufferDesc.MiscFlags = 0; if (m_Description.m_bUseForIndirectArguments) { // TODO Vulkan? } if (m_Description.m_bAllowRawViews) { // TODO Vulkan? } if (m_Description.m_bUseAsStructuredBuffer) { // TODO Vulkan? } //BufferDesc.StructureByteStride = m_Description.m_uiStructSize; m_buffer = pVulkanDevice->GetVulkanDevice().createBuffer(bufferCreateInfo); if (!m_buffer) { return EZ_FAILURE; } vk::MemoryPropertyFlags bufferMemoryProperties = {}; if (m_Description.m_BufferType == ezGALBufferType::ConstantBuffer) { bufferMemoryProperties |= vk::MemoryPropertyFlagBits::eDeviceLocal; // TODO do we need to use this for vulkan? // If constant buffer: Patch size to be aligned to 64 bytes for easier usability // BufferDesc.ByteWidth = ezMemoryUtils::AlignSize(BufferDesc.ByteWidth, 64u); } else { // TODO is this flag relevant to Vulkan? /*if (m_Description.m_ResourceAccess.IsImmutable()) { // TODO vulkan //BufferDesc.Usage = D3D11_USAGE_IMMUTABLE; } else*/ { // for performance reasons we'll require shader accessed buffers to reside in device // memory. if (m_Description.m_bAllowUAV || m_Description.m_bAllowShaderResourceView || m_Description.m_bStreamOutputTarget || m_Description.m_ResourceAccess.m_bReadBack) { bufferMemoryProperties |= vk::MemoryPropertyFlagBits::eDeviceLocal; } else { bufferMemoryProperties |= vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent; } } } vk::MemoryRequirements bufferMemoryRequirements = pVulkanDevice->GetVulkanDevice().getBufferMemoryRequirements(m_buffer); vk::MemoryAllocateInfo memoryAllocateInfo = {}; memoryAllocateInfo.allocationSize = bufferMemoryRequirements.size; memoryAllocateInfo.memoryTypeIndex = pVulkanDevice->GetMemoryIndex(bufferMemoryProperties, bufferMemoryRequirements); m_memory = pVulkanDevice->GetVulkanDevice().allocateMemory(memoryAllocateInfo); m_memoryOffset = 0; // TODO suballocations if (!m_memory) { pVulkanDevice->GetVulkanDevice().destroyBuffer(m_buffer); m_buffer = nullptr; return EZ_FAILURE; } pVulkanDevice->GetVulkanDevice().bindBufferMemory(m_buffer, m_memory, m_memoryOffset); m_device = pVulkanDevice->GetVulkanDevice(); // TODO remove this // TODO initial data upload return EZ_SUCCESS; } ezResult ezGALBufferVulkan::DeInitPlatform(ezGALDevice* pDevice) { if (m_buffer) { ezGALDeviceVulkan* pVulkanDevice = static_cast<ezGALDeviceVulkan*>(pDevice); pVulkanDevice->GetVulkanDevice().destroyBuffer(m_buffer); pVulkanDevice->GetVulkanDevice().freeMemory(m_memory); m_buffer = nullptr; m_memory = nullptr; m_memoryOffset = 0; } return EZ_SUCCESS; } void ezGALBufferVulkan::SetDebugNamePlatform(const char* szName) const { ezUInt32 uiLength = ezStringUtils::GetStringElementCount(szName); if (m_buffer) { vk::DebugMarkerObjectNameInfoEXT nameInfo = {}; nameInfo.object = (uint64_t)(VkBuffer)m_buffer; nameInfo.objectType = vk::DebugReportObjectTypeEXT::eBuffer; nameInfo.pObjectName = szName; m_device.debugMarkerSetObjectNameEXT(nameInfo); } } EZ_STATICLINK_FILE(RendererVulkan, RendererVulkan_Resources_Implementation_BufferVulkan);
2,088
82,518
<reponame>gujralsanyam22/models # Copyright 2017 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for datum_io, the python interface of DatumProto.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import flags import numpy as np import tensorflow as tf from delf import datum_io FLAGS = flags.FLAGS class DatumIoTest(tf.test.TestCase): def Conversion2dTestWithType(self, dtype): original_data = np.arange(9).reshape(3, 3).astype(dtype) serialized = datum_io.SerializeToString(original_data) retrieved_data = datum_io.ParseFromString(serialized) self.assertTrue(np.array_equal(original_data, retrieved_data)) def Conversion3dTestWithType(self, dtype): original_data = np.arange(24).reshape(2, 3, 4).astype(dtype) serialized = datum_io.SerializeToString(original_data) retrieved_data = datum_io.ParseFromString(serialized) self.assertTrue(np.array_equal(original_data, retrieved_data)) # This test covers the following functions: ArrayToDatum, SerializeToString, # ParseFromString, DatumToArray. def testConversion2dWithType(self): self.Conversion2dTestWithType(np.uint16) self.Conversion2dTestWithType(np.uint32) self.Conversion2dTestWithType(np.uint64) self.Conversion2dTestWithType(np.float16) self.Conversion2dTestWithType(np.float32) self.Conversion2dTestWithType(np.float64) # This test covers the following functions: ArrayToDatum, SerializeToString, # ParseFromString, DatumToArray. def testConversion3dWithType(self): self.Conversion3dTestWithType(np.uint16) self.Conversion3dTestWithType(np.uint32) self.Conversion3dTestWithType(np.uint64) self.Conversion3dTestWithType(np.float16) self.Conversion3dTestWithType(np.float32) self.Conversion3dTestWithType(np.float64) def testConversionWithUnsupportedType(self): with self.assertRaisesRegex(ValueError, 'Unsupported array type'): self.Conversion3dTestWithType(int) # This test covers the following functions: ArrayToDatum, SerializeToString, # WriteToFile, ReadFromFile, ParseFromString, DatumToArray. def testWriteAndReadToFile(self): data = np.array([[[-1.0, 125.0, -2.5], [14.5, 3.5, 0.0]], [[20.0, 0.0, 30.0], [25.5, 36.0, 42.0]]]) filename = os.path.join(FLAGS.test_tmpdir, 'test.datum') datum_io.WriteToFile(data, filename) data_read = datum_io.ReadFromFile(filename) self.assertAllEqual(data_read, data) # This test covers the following functions: ArraysToDatumPair, # SerializePairToString, WritePairToFile, ReadPairFromFile, # ParsePairFromString, DatumPairToArrays. def testWriteAndReadPairToFile(self): data_1 = np.array([[[-1.0, 125.0, -2.5], [14.5, 3.5, 0.0]], [[20.0, 0.0, 30.0], [25.5, 36.0, 42.0]]]) data_2 = np.array( [[[255, 0, 5], [10, 300, 0]], [[20, 1, 100], [255, 360, 420]]], dtype='uint32') filename = os.path.join(FLAGS.test_tmpdir, 'test.datum_pair') datum_io.WritePairToFile(data_1, data_2, filename) data_read_1, data_read_2 = datum_io.ReadPairFromFile(filename) self.assertAllEqual(data_read_1, data_1) self.assertAllEqual(data_read_2, data_2) if __name__ == '__main__': tf.test.main()
1,462
1,319
<filename>PaddleNLP/Research/IJCAI2019-MMPMS/eval.py #!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ import codecs import sys import json from random import shuffle from mmpms.utils.metrics import Metric, bleu, distinct NUM_MULTI_RESPONSES = 5 def evaluate_generation(results): tgt = [result["response"].split(" ") for result in results] tgt_multi = [x for x in tgt for _ in range(NUM_MULTI_RESPONSES)] preds = [ list(map(lambda s: s.split(" "), result["preds"])) for result in results ] # Shuffle predictions for n in range(len(preds)): shuffle(preds[n]) # Single response generation pred = [ps[0] for ps in preds] bleu1, bleu2 = bleu(pred, tgt) dist1, dist2 = distinct(pred) print("Random 1 candidate: " + "BLEU-1/2: {:.3f}/{:.3f} ".format( bleu1, bleu2) + "DIST-1/2: {:.3f}/{:.3f}".format(dist1, dist2)) # Multiple response generation pred = [ps[:5] for ps in preds] pred = [p for ps in pred for p in ps] bleu1, bleu2 = bleu(pred, tgt_multi) dist1, dist2 = distinct(pred) print("Random {} candidates: ".format( NUM_MULTI_RESPONSES) + "BLEU-1/2: {:.3f}/{:.3f} ".format(bleu1, bleu2) + "DIST-1/2: {:.3f}/{:.3f}".format(dist1, dist2)) def main(): result_file = sys.argv[1] with codecs.open(result_file, "r", encoding="utf-8") as fp: results = json.load(fp) evaluate_generation(results) if __name__ == '__main__': main()
829
2,151
// Copyright 2018 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 IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_TOOLS_ITEM_H_ #define IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_TOOLS_ITEM_H_ #import "ios/chrome/browser/ui/popup_menu/cells/popup_menu_item.h" #import "ios/chrome/browser/ui/table_view/cells/table_view_item.h" // Item for a tools menu item. @interface PopupMenuToolsItem : TableViewItem<PopupMenuItem> // The title of the item. @property(nonatomic, copy) NSString* title; // Image to be displayed on the item. @property(nonatomic, strong) UIImage* image; // Whether the cell associated with this item should be enabled. @property(nonatomic, assign) BOOL enabled; // Number to be displayed in the badge. If 0, the badge is hidden. @property(nonatomic, assign) NSInteger badgeNumber; // Text to be displayed in the badge. Set to nil to hide the badge. The text // badge is only displayed if the numbered badge is hidden. @property(nonatomic, copy) NSString* badgeText; // Whether the item is associated with a destructive action. If |YES|, then a // specific styling is applied. @property(nonatomic, assign) BOOL destructiveAction; @end // Associated cell for the PopupMenuToolsItem. @interface PopupMenuToolsCell : UITableViewCell // Image view to display the image. @property(nonatomic, strong, readonly) UIImageView* imageView; // Title label for the cell. @property(nonatomic, strong, readonly) UILabel* titleLabel; // Whether the cell is associated with a destructive action. If |YES|, then a // specific styling is applied. @property(nonatomic, assign) BOOL destructiveAction; // Sets the number on the badge number. - (void)setBadgeNumber:(NSInteger)badgeNumber; // Sets the text of the badge text. Hides the badge text if |badgeText| is nil. - (void)setBadgeText:(NSString*)badgeText; @end #endif // IOS_CHROME_BROWSER_UI_POPUP_MENU_CELLS_POPUP_MENU_TOOLS_ITEM_H_
651
429
<gh_stars>100-1000 /* * (C) Copyright 2019-2021 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ /** * Mocks of dRPC framework functions */ #include "drpc_mocks.h" struct drpc *drpc_connect_return; /* value to be returned */ char drpc_connect_sockaddr[PATH_MAX + 1]; /* saved copy of input */ int drpc_connect(char *sockaddr, struct drpc **drpcp) { strncpy(drpc_connect_sockaddr, sockaddr, PATH_MAX); *drpcp = drpc_connect_return; if (drpc_connect_return) return -DER_SUCCESS; return -DER_BADPATH; } void mock_drpc_connect_setup(void) { D_ALLOC_PTR(drpc_connect_return); memset(drpc_connect_sockaddr, 0, sizeof(drpc_connect_sockaddr)); } void mock_drpc_connect_teardown(void) { free_drpc_connect_return(); } int drpc_call_return; /* value to be returned */ struct drpc *drpc_call_ctx; /* saved input */ int drpc_call_flags; /* saved input */ Drpc__Call drpc_call_msg_content; /* saved copy of input */ /* saved input ptr address (for checking non-NULL) */ Drpc__Call *drpc_call_msg_ptr; /* saved input ptr address (for checking non-NULL) */ Drpc__Response **drpc_call_resp_ptr; /* ptr to content to allocate in response (can be NULL) */ Drpc__Response *drpc_call_resp_return_ptr; /* actual content to allocate in response */ Drpc__Response drpc_call_resp_return_content; int drpc_call(struct drpc *ctx, int flags, Drpc__Call *msg, Drpc__Response **resp) { /* Save off the params passed in */ drpc_call_ctx = ctx; drpc_call_flags = flags; drpc_call_msg_ptr = msg; if (msg != NULL) { memcpy(&drpc_call_msg_content, msg, sizeof(Drpc__Call)); /* Need a copy of the body data, it's separately allocated */ D_ALLOC(drpc_call_msg_content.body.data, msg->body.len); memcpy(drpc_call_msg_content.body.data, msg->body.data, msg->body.len); } drpc_call_resp_ptr = resp; if (resp == NULL) { return drpc_call_return; } /* Fill out the mocked response */ if (drpc_call_resp_return_ptr == NULL) { *resp = NULL; } else { size_t data_len = drpc_call_resp_return_content.body.len; /** * Need to allocate a new copy to return - the * production code will free the returned memory. */ D_ALLOC_PTR(*resp); memcpy(*resp, &drpc_call_resp_return_content, sizeof(Drpc__Response)); D_ALLOC((*resp)->body.data, data_len); memcpy((*resp)->body.data, drpc_call_resp_return_content.body.data, data_len); } return drpc_call_return; } static void init_drpc_call_resp(void) { /* By default, return non-null response */ drpc_call_resp_return_ptr = &drpc_call_resp_return_content; drpc__response__init(&drpc_call_resp_return_content); drpc_call_resp_return_content.status = DRPC__STATUS__SUCCESS; } void mock_drpc_call_setup(void) { drpc_call_return = 0; drpc_call_ctx = NULL; drpc_call_flags = 0; drpc_call_msg_ptr = NULL; memset(&drpc_call_msg_content, 0, sizeof(drpc_call_msg_content)); drpc_call_resp_ptr = NULL; init_drpc_call_resp(); } void mock_drpc_call_teardown(void) { free_drpc_call_msg_body(); free_drpc_call_resp_body(); } int drpc_close_return; /* value to be returned */ struct drpc *drpc_close_ctx; /* saved input ptr */ int drpc_close(struct drpc *ctx) { drpc_close_ctx = ctx; return drpc_close_return; } void mock_drpc_close_setup(void) { drpc_close_return = 0; drpc_close_ctx = NULL; } void free_drpc_connect_return(void) { D_FREE(drpc_connect_return); } void free_drpc_call_msg_body(void) { D_FREE(drpc_call_msg_content.body.data); drpc_call_msg_content.body.len = 0; } void free_drpc_call_resp_body(void) { D_FREE(drpc_call_resp_return_content.body.data); drpc_call_resp_return_content.body.len = 0; } void pack_get_cred_resp_in_drpc_call_resp_body(Auth__GetCredResp *resp) { size_t len = auth__get_cred_resp__get_packed_size(resp); uint8_t *body; D_FREE(drpc_call_resp_return_content.body.data); drpc_call_resp_return_content.body.len = len; D_ALLOC(body, len); auth__get_cred_resp__pack(resp, body); drpc_call_resp_return_content.body.data = body; } void pack_validate_resp_in_drpc_call_resp_body(Auth__ValidateCredResp *resp) { size_t len = auth__validate_cred_resp__get_packed_size(resp); uint8_t *body; D_FREE(drpc_call_resp_return_content.body.data); drpc_call_resp_return_content.body.len = len; D_ALLOC(body, len); auth__validate_cred_resp__pack(resp, body); drpc_call_resp_return_content.body.data = body; }
1,799
585
<reponame>kickers18/caffe2 /** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CAFFE2_OPERATORS_NORMALIZE_L1_OP_H_ #define CAFFE2_OPERATORS_NORMALIZE_L1_OP_H_ #include "caffe2/core/context.h" #include "caffe2/core/operator.h" #include "caffe2/utils/math.h" namespace caffe2 { template <typename T, class Context> class NormalizeL1Op final : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; USE_SIMPLE_CTOR_DTOR(NormalizeL1Op) bool RunOnDevice() override { const auto& x = Input(0); auto* y = Output(0); const auto* xData = x.template data<T>(); y->ResizeLike(x); auto* yData = y->template mutable_data<T>(); const auto canonical_axis = x.canonical_axis_index( OperatorBase::GetSingleArgument<int>("axis", -1)); const int m = x.dim32(canonical_axis); const int n = x.size() / m; const int sf = x.size_from_dim(canonical_axis + 1); DoNormalize(xData, yData, m, n, sf); return true; } private: void DoNormalize(const T* xData, T* yData, const int m, const int n, const int sf); }; } // namespace caffe2 #endif // CAFFE2_OPERATORS_NORMALIZE_L1_OP_H_
620
897
<gh_stars>100-1000 //C++ Program to generate Pythagorean Triples within a user-given limit #include <bits/stdc++.h> using namespace std; //Function for computing Pythagorean Triples void GetTriples(int& l) { //Starting values of m=2, n=1 are mapped to a=3, b=4, c=5, which is the smallest Pythagorean triple int a = 0, b = 0, c = 0, m = 2, n = 1; while (c < l) { //For every m, evaluate a,b,c for all values of n from 1 to m-1 n = 1; while (n < m) { //Evaluating a, b, c using relation between a,b,c and m,n a = (int)(pow(m, 2)) - (int)(pow(n, 2)); b = 2 *m * n; c = (int)(pow(m, 2)) + (int)(pow(n, 2)); //Checking for limit being exceeded if (c > l) break; //Display computed Triple cout << a << " " << b << " " << c << "\n"; n++; } m++; } } //Driver function int main() { int l; //Prompts user for input cout << "Enter limit (>4) :"; cin >> l; GetTriples(l); return 0; } /* Sample I/O: Enter limit: 30 3 4 5 8 6 10 5 12 13 15 8 17 12 16 20 7 24 25 24 10 26 21 20 29 Time Complexity - O(k)[k = number of triples generated] Space Complexity - O(1) References: https://youtu.be/n6vL2KiWrD4 */
506
2,107
<filename>include/spdk/pipe.h /*- * BSD LICENSE * * Copyright (c) Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** \file * A pipe that is intended for buffering data between a source, such as * a socket, and a sink, such as a parser, or vice versa. Any time data * is received in units that differ from the the units it is consumed * in may benefit from using a pipe. * * The pipe is not thread safe. Only a single thread can act as both * the producer (called the writer) and the consumer (called the reader). */ #ifndef SPDK_PIPE_H #define SPDK_PIPE_H #include "spdk/stdinc.h" struct spdk_pipe; /** * Construct a pipe around the given memory buffer. The pipe treats the memory * buffer as a circular ring of bytes. * * The available size for writing will be one less byte than provided. A single * byte must be reserved to distinguish queue full from queue empty conditions. * * \param buf The data buffer that backs this pipe. * \param sz The size of the data buffer. * * \return spdk_pipe. The new pipe. */ struct spdk_pipe *spdk_pipe_create(void *buf, uint32_t sz); /** * Destroys the pipe. This does not release the buffer, but does * make it safe for the user to release the buffer. * * \param pipe The pipe to operate on. */ void spdk_pipe_destroy(struct spdk_pipe *pipe); /** * Acquire memory from the pipe for writing. * * This function will acquire up to sz bytes from the pipe to be used for * writing. It may return fewer total bytes. * * The memory is only marked as consumed upon a call to spdk_pipe_writer_advance(). * Multiple calls to this function without calling advance return the same region * of memory. * * \param pipe The pipe to operate on. * \param sz The size requested. * \param iovs A two element iovec array that will be populated with the requested memory. * * \return The total bytes obtained. May be 0. */ int spdk_pipe_writer_get_buffer(struct spdk_pipe *pipe, uint32_t sz, struct iovec *iovs); /** * Advance the write pointer by the given number of bytes * * The user can obtain memory from the pipe using spdk_pipe_writer_get_buffer(), * but only calling this function marks it as consumed. The user is not required * to advance the same number of bytes as was obtained from spdk_pipe_writer_get_buffer(). * However, upon calling this function, the previous memory region is considered * invalid and the user must call spdk_pipe_writer_get_buffer() again to obtain * additional memory. * * The user cannot advance past the current read location. * * \param pipe The pipe to operate on. * \param count The number of bytes to advance. * * \return On error, a negated errno. On success, 0. */ int spdk_pipe_writer_advance(struct spdk_pipe *pipe, uint32_t count); /** * Get the number of bytes available to read from the pipe. * * \param pipe The pipe to operate on. * * \return The number of bytes available for reading. */ uint32_t spdk_pipe_reader_bytes_available(struct spdk_pipe *pipe); /** * Obtain previously written memory from the pipe for reading. * * This call populates the two element iovec provided with a region * of memory containing the next available data in the pipe. The size * will be up to sz bytes, but may be less. * * Calling this function does not mark the memory as consumed. Calling this function * twice without a call to spdk_pipe_reader_advance in between will return the same * region of memory. * * \param pipe The pipe to operate on. * \param sz The size requested. * \param iovs A two element iovec array that will be populated with the requested memory. * * \return On error, a negated errno. On success, the total number of bytes available. */ int spdk_pipe_reader_get_buffer(struct spdk_pipe *pipe, uint32_t sz, struct iovec *iovs); /** * Mark memory as read, making it available for writing. The user is not required * to advance the same number of byte as was obtained by a previous call to * spdk_pipe_reader_get_buffer(). * * \param pipe The pipe to operate on. * \param count The number of bytes to advance. * * \return On error, a negated errno. On success, 0. */ int spdk_pipe_reader_advance(struct spdk_pipe *pipe, uint32_t count); #endif
1,680
14,668
<reponame>zealoussnow/chromium<gh_stars>1000+ // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/websockets/inspector_websocket_events.h" #include <memory> #include "base/trace_event/trace_event.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/inspector/identifiers_factory.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" #include "third_party/blink/renderer/core/workers/worker_thread.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" namespace blink { void InspectorWebSocketCreateEvent::Data(perfetto::TracedValue context, ExecutionContext* execution_context, uint64_t identifier, const KURL& url, const String& protocol) { auto dict = std::move(context).WriteDictionary(); DCHECK(execution_context->IsContextThread()); dict.Add("identifier", identifier); dict.Add("url", url.GetString()); if (auto* window = DynamicTo<LocalDOMWindow>(execution_context)) { dict.Add("frame", IdentifiersFactory::FrameId(window->GetFrame())); } else if (auto* scope = DynamicTo<WorkerGlobalScope>(execution_context)) { dict.Add("workerId", IdentifiersFactory::IdFromToken( scope->GetThread()->GetDevToolsWorkerToken())); } else { NOTREACHED() << "WebSocket is available only in Window and WorkerGlobalScope"; } if (!protocol.IsNull()) dict.Add("webSocketProtocol", protocol); SetCallStack(dict); } void InspectorWebSocketEvent::Data(perfetto::TracedValue context, ExecutionContext* execution_context, uint64_t identifier) { DCHECK(execution_context->IsContextThread()); auto dict = std::move(context).WriteDictionary(); dict.Add("identifier", identifier); if (auto* window = DynamicTo<LocalDOMWindow>(execution_context)) { dict.Add("frame", IdentifiersFactory::FrameId(window->GetFrame())); } else if (auto* scope = DynamicTo<WorkerGlobalScope>(execution_context)) { dict.Add("workerId", IdentifiersFactory::IdFromToken( scope->GetThread()->GetDevToolsWorkerToken())); } else { NOTREACHED() << "WebSocket is available only in Window and WorkerGlobalScope"; } SetCallStack(dict); } } // namespace blink
1,100
366
<gh_stars>100-1000 package com.hi.dhl.algorithms.other.concurrency._1195; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.IntConsumer; /** * <pre> * author: dhl * date : 2020/11/6 * desc : * </pre> */ class FizzBuzzLock { private int n; private Lock lock = new ReentrantLock(); private Condition conNumber = lock.newCondition(); private Condition conFizz = lock.newCondition(); private Condition conBuzz = lock.newCondition(); private Condition conFizzBuzz = lock.newCondition(); public FizzBuzzLock(int n) { this.n = n; } // printFizz.run() outputs "fizz". public void fizz(Runnable printFizz) throws InterruptedException { try { lock.lock(); for (int i = 3; i <= n; i += 3) { if (i % 5 != 0) { conFizz.await(); printFizz.run(); conNumber.signalAll(); } } } finally { lock.unlock(); } } // printBuzz.run() outputs "buzz". public void buzz(Runnable printBuzz) throws InterruptedException { try { lock.lock(); for (int i = 5; i <= n; i += 5) { if (i % 3 != 0) { conBuzz.await(); printBuzz.run(); conNumber.signalAll(); } } } finally { lock.unlock(); } } // printFizzBuzz.run() outputs "fizzbuzz". public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException { try { lock.lock(); for (int i = 15; i <= n; i += 15) { conFizzBuzz.await(); printFizzBuzz.run(); conNumber.signalAll(); } } finally { lock.unlock(); } } // printNumber.accept(x) outputs "x", where x is an integer. public void number(IntConsumer printNumber) throws InterruptedException { try { lock.lock(); for (int i = 1; i <= n; i++) { if (i % 3 == 0 && i % 5 == 0) { conFizzBuzz.signalAll(); conNumber.await(); } else if (i % 3 == 0) { conFizz.signalAll(); conNumber.await(); } else if (i % 5 == 0) { conBuzz.signalAll(); conNumber.await(); } else { printNumber.accept(i); } } } finally { lock.unlock(); } } public static void main(String... args) { FizzBuzzLock fizzBuzzLock = new FizzBuzzLock(15); Thread thd = new Thread(() -> { try { fizzBuzzLock.number(value -> System.out.print(value + " ")); } catch (Exception e) { e.printStackTrace(); } }); Thread tha = new Thread(() -> { try { fizzBuzzLock.fizz(() -> System.out.print("fizz ")); } catch (Exception e) { } }); Thread thb = new Thread(() -> { try { fizzBuzzLock.buzz(() -> System.out.print("buzz ")); } catch (Exception e) { } }); Thread thc = new Thread(() -> { try { fizzBuzzLock.fizzbuzz(() -> System.out.print("buzz ")); } catch (Exception e) { } }); tha.start(); thb.start(); thc.start(); thd.start(); } }
2,033
312
// copyright <NAME> 2015 #ifndef PURINE_INNER #define PURINE_INNER #include "caffeine/caffeine.hpp" #include "caffeine/math_functions.hpp" #include "operations/operation.hpp" namespace purine { /** * { bottom, weight } >> op >> { top } */ class Inner : public Operation { public: typedef tuple<> param_tuple; explicit Inner(const vector<Tensor*>& inputs, const vector<Tensor*>& outputs, const param_tuple& args); virtual void compute_gpu(const vector<bool>& add); virtual void compute_cpu(const vector<bool>& add); }; /** * { top_diff, weight } >> op >> { bottom_diff } */ class InnerDown : public Operation { public: typedef tuple<> param_tuple; explicit InnerDown(const vector<Tensor*>& inputs, const vector<Tensor*>& outputs, const param_tuple& args); virtual void compute_gpu(const vector<bool>& add); virtual void compute_cpu(const vector<bool>& add); }; /** * { top_diff, bottom } >> op >> { weight_diff } */ class InnerWeight : public Operation { public: typedef tuple<> param_tuple; explicit InnerWeight(const vector<Tensor*>& inputs, const vector<Tensor*>& outputs, const param_tuple& args); virtual void compute_gpu(const vector<bool>& add); virtual void compute_cpu(const vector<bool>& add); }; } #endif
435
2,483
package com.tekartik.sqflite; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class FileUtils { public static String convertStreamToString(InputStream is) throws IOException { // http://www.java2s.com/Code/Java/File-Input-Output/ConvertInputStreamtoString.htm BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; Boolean firstLine = true; while ((line = reader.readLine()) != null) { if (firstLine) { sb.append(line); firstLine = false; } else { sb.append("\n").append(line); } } reader.close(); return sb.toString(); } public static String getStringFromFile(File file) throws IOException { FileInputStream fin = new FileInputStream(file); String ret = convertStreamToString(fin); //Make sure you close all streams. fin.close(); return ret; } }
486
349
<gh_stars>100-1000 /******************************************************************************* * Copyright 2011, 2012, 2013 fanfou.com, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.fanfou.app.opensource.util; import android.content.Context; import android.content.SharedPreferences.Editor; import com.fanfou.app.opensource.AppContext; import com.fanfou.app.opensource.R; import com.fanfou.app.opensource.api.bean.User; import com.fanfou.app.opensource.auth.OAuthToken; /** * @author mcxiaoke * @version 1.0 2011.06.01 * @version 1.1 2011.10.10 * @version 1.2 2011.10.26 * @version 2.0 2011.12.06 * @version 3.0 2011.12.26 * */ public final class OptionHelper { public final static void clearSettings() { final Editor sp = AppContext.getPreferences().edit(); sp.clear(); sp.commit(); } public final static int parseInt(final Context context, final int resId) { final String res = AppContext.getPreferences().getString( context.getString(resId), "-1"); return Integer.parseInt(res); } public final static int parseInt(final Context context, final int resId, final String defaultValue) { final String res = AppContext.getPreferences().getString( context.getString(resId), defaultValue); return Integer.parseInt(res); } public final static int parseInt(final String key) { final String res = AppContext.getPreferences().getString(key, "-1"); return Integer.parseInt(res); } public final static int parseInt(final String key, final String defaultValue) { final String res = AppContext.getPreferences().getString(key, defaultValue); return Integer.parseInt(res); } public final static boolean readBoolean(final Context context, final int resId, final boolean defValue) { final boolean res = AppContext.getPreferences().getBoolean( context.getString(resId), defValue); return res; } public final static boolean readBoolean(final String key, final boolean defValue) { final boolean res = AppContext.getPreferences().getBoolean(key, defValue); return res; } public final static int readInt(final Context context, final int resId, final int defValue) { final int res = AppContext.getPreferences().getInt( context.getString(resId), defValue); return res; } public final static int readInt(final String key, final int defValue) { final int res = AppContext.getPreferences().getInt(key, defValue); return res; } public final static long readLong(final Context context, final int resId, final long defValue) { final long res = AppContext.getPreferences().getLong( context.getString(resId), defValue); return res; } public final static long readLong(final String key, final int defValue) { final long res = AppContext.getPreferences().getLong(key, defValue); return res; } public final static String readString(final Context context, final int resId, final String defValue) { final String res = AppContext.getPreferences().getString( context.getString(resId), defValue); return res; } public final static String readString(final String key, final String defValue) { final String res = AppContext.getPreferences().getString(key, defValue); return res; } public final static void remove(final Context context, final int resId) { final Editor sp = AppContext.getPreferences().edit(); sp.remove(context.getString(resId)); sp.commit(); } public final static void remove(final String key) { final Editor sp = AppContext.getPreferences().edit(); sp.remove(key); sp.commit(); } public final static void removeAccountInfo(final Context context) { final Editor editor = AppContext.getPreferences().edit(); editor.remove(context.getString(R.string.option_userid)); editor.remove(context.getString(R.string.option_username)); editor.remove(context.getString(R.string.option_profile_image)); editor.remove(context.getString(R.string.option_oauth_token)); editor.remove(context.getString(R.string.option_oauth_token_secret)); editor.commit(); } public final static void saveBoolean(final Context context, final int resId, final boolean value) { final Editor sp = AppContext.getPreferences().edit(); sp.putBoolean(context.getString(resId), value); sp.commit(); } public final static void saveBoolean(final String key, final boolean value) { final Editor sp = AppContext.getPreferences().edit(); sp.putBoolean(key, value); sp.commit(); } public final static void saveInt(final Context context, final int resId, final int value) { final Editor sp = AppContext.getPreferences().edit(); sp.putInt(context.getString(resId), value); sp.commit(); } public final static void saveInt(final String key, final int value) { final Editor sp = AppContext.getPreferences().edit(); sp.putInt(key, value); sp.commit(); } public final static void saveLong(final Context context, final int resId, final long value) { final Editor sp = AppContext.getPreferences().edit(); sp.putLong(context.getString(resId), value); sp.commit(); } public final static void saveLong(final String key, final long value) { final Editor sp = AppContext.getPreferences().edit(); sp.putLong(key, value); sp.commit(); } public final static void saveString(final Context context, final int resId, final String value) { final Editor sp = AppContext.getPreferences().edit(); sp.putString(context.getString(resId), value); sp.commit(); } public final static void saveString(final String key, final String value) { final Editor sp = AppContext.getPreferences().edit(); sp.putString(key, value); sp.commit(); } public final static void updateAccountInfo(final Context context, final User u, final OAuthToken otoken) { final Editor editor = AppContext.getPreferences().edit(); editor.putString(context.getString(R.string.option_userid), u.id); editor.putString(context.getString(R.string.option_username), u.screenName); editor.putString(context.getString(R.string.option_profile_image), u.profileImageUrl); editor.putString(context.getString(R.string.option_oauth_token), otoken.getToken()); editor.putString(context.getString(R.string.option_oauth_token_secret), otoken.getTokenSecret()); editor.commit(); } public final static void updateUserInfo(final Context context, final User u) { final Editor editor = AppContext.getPreferences().edit(); editor.putString(context.getString(R.string.option_userid), u.id); editor.putString(context.getString(R.string.option_username), u.screenName); editor.putString(context.getString(R.string.option_profile_image), u.profileImageUrl); editor.commit(); } }
3,020
1,513
<filename>src/db/wiredtiger/wiredtiger_engine.hpp /* *Copyright (c) 2013-2016, yinqiwen <<EMAIL>> *All rights reserved. * *Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS *BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF *THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WIREDTIGER_ENGINE_HPP_ #define WIREDTIGER_ENGINE_HPP_ #include "db/engine.hpp" #include "util/config_helper.hpp" #include "thread/thread.hpp" #include "thread/thread_local.hpp" #include "thread/thread_mutex_lock.hpp" #include "thread/spin_rwlock.hpp" #include <stack> #include <wiredtiger.h> namespace ardb { class WiredTigerEngine; class WiredTigerIterator: public Iterator { private: WiredTigerEngine* m_engine; WT_CURSOR* m_cursor; Data m_ns; KeyObject m_key; ValueObject m_value; KeyObject m_iterate_upper_bound_key; void DoJump(const KeyObject& next); bool m_valid; bool Valid(); void Next(); void Prev(); void Jump(const KeyObject& next); void JumpToFirst(); void JumpToLast(); KeyObject& Key(bool clone_str); ValueObject& Value(bool clone_str); Slice RawKey(); Slice RawValue(); void Del(); void ClearState(); void CheckBound(); void SetCursor(WT_CURSOR* c) { m_cursor = c; } KeyObject& IterateUpperBoundKey() { return m_iterate_upper_bound_key; } friend class WiredTigerEngine; public: WiredTigerIterator(WiredTigerEngine * e, const Data& ns) : m_engine(e), m_cursor(NULL), m_ns(ns), m_valid(true) { } void MarkValid(bool valid) { m_valid = valid; } ~WiredTigerIterator(); }; class WiredTigerLocalContext; class WiredTigerEngine: public Engine { private: WT_CONNECTION* m_db; DataSet m_nss; SpinRWLock m_lock; friend class WiredTigerIterator; friend class WiredTigerLocalContext; //bool ContNamespace bool GetTable(const Data& ns, bool create_if_missing); WT_CONNECTION* GetWTConn() { return m_db; } void Close(); public: WiredTigerEngine(); ~WiredTigerEngine(); int Init(const std::string& dir, const std::string& options); int Repair(const std::string& dir); int Put(Context& ctx, const KeyObject& key, const ValueObject& value); int PutRaw(Context& ctx, const Data& ns, const Slice& key, const Slice& value); int Get(Context& ctx, const KeyObject& key, ValueObject& value); int MultiGet(Context& ctx, const KeyObjectArray& keys, ValueObjectArray& values, ErrCodeArray& errs); int Del(Context& ctx, const KeyObject& key); int Merge(Context& ctx, const KeyObject& key, uint16_t op, const DataArray& args); bool Exists(Context& ctx, const KeyObject& key,ValueObject& val); int BeginWriteBatch(Context& ctx); int CommitWriteBatch(Context& ctx); int DiscardWriteBatch(Context& ctx); int Compact(Context& ctx, const KeyObject& start, const KeyObject& end); int ListNameSpaces(Context& ctx, DataArray& nss); int DropNameSpace(Context& ctx, const Data& ns); void Stats(Context& ctx, std::string& str); int64_t EstimateKeysNum(Context& ctx, const Data& ns); Iterator* Find(Context& ctx, const KeyObject& key); const std::string GetErrorReason(int err); const FeatureSet GetFeatureSet() { FeatureSet features; features.support_compactfilter = 0; features.support_namespace = 1; features.support_merge = 0; return features; } int MaxOpenFiles(); }; } #endif
2,453
3,102
<filename>clang/test/Modules/Inputs/libc-libcxx/sysroot/usr/include/util.h #ifndef DARWIN_UTIL_H #define DARWIN_UTIL_H #include <stdio.h> #endif
68
351
package org.antlr.intellij.plugin.templates; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.antlr.intellij.plugin.parser.ANTLRv4Parser; import org.antlr.intellij.plugin.parsing.ParsingUtils; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Token; import org.jetbrains.annotations.NotNull; public class OutsideRuleContext extends ANTLRLiveTemplateContext { public OutsideRuleContext() { super("ANTLR_OUTSIDE", "Outside rule", ANTLRGenericContext.class); } @Override public boolean isInContext(@NotNull PsiFile file, PsiElement element, int offset) { CommonTokenStream tokens = ParsingUtils.tokenizeANTLRGrammar(file.getText()); Token tokenUnderCursor = ParsingUtils.getTokenUnderCursor(tokens, offset); if ( tokenUnderCursor==null ) { return false; // sometimes happens at the eof } int tokenIndex = tokenUnderCursor.getTokenIndex(); Token nextRealToken = ParsingUtils.nextRealToken(tokens, tokenIndex); Token previousRealToken = ParsingUtils.previousRealToken(tokens, tokenIndex); if ( nextRealToken==null || previousRealToken==null ) { return false; } int previousRealTokenType = previousRealToken.getType(); int nextRealTokenType = nextRealToken.getType(); if ( previousRealTokenType== ANTLRv4Parser.BEGIN_ACTION ) { // make sure we're not in a rule; has to be @lexer::header {...} stuff Token prevPrevRealToken = ParsingUtils.previousRealToken(tokens, previousRealToken.getTokenIndex()); if ( prevPrevRealToken==null ) { return false; } Token prevPrevPrevRealToken = ParsingUtils.previousRealToken(tokens, prevPrevRealToken.getTokenIndex()); if ( prevPrevPrevRealToken==null ) { return false; } if ( prevPrevPrevRealToken.getType()!=ANTLRv4Parser.AT && prevPrevPrevRealToken.getType()!=ANTLRv4Parser.COLONCOLON ) { return false; } } boolean okBefore = previousRealTokenType == ANTLRv4Parser.RBRACE || previousRealTokenType == ANTLRv4Parser.SEMI || previousRealTokenType == ANTLRv4Parser.BEGIN_ACTION; boolean okAfter = nextRealTokenType == ANTLRv4Parser.TOKEN_REF || nextRealTokenType == ANTLRv4Parser.RULE_REF || nextRealTokenType == Token.EOF; return okBefore && okAfter; } }
822
6,989
#pragma once #include <catboost/libs/data/data_provider.h> #include <util/generic/fwd.h> #include <util/generic/vector.h> class TFullModel; namespace NPar { class ILocalExecutor; } struct TRocPoint { double Boundary = 0.0; double FalseNegativeRate = 0.0; double FalsePositiveRate = 0.0; public: TRocPoint() = default; TRocPoint( double boundary, double falseNegativeRate, double falsePositiveRate ) : Boundary(boundary) , FalseNegativeRate(falseNegativeRate) , FalsePositiveRate(falsePositiveRate) { } }; struct TRocCurve { constexpr static double EPS = 1e-13; // for comparisons of probabilities and coordinates public: TRocCurve(const TFullModel& model, const TVector<NCB::TDataProviderPtr>& datasets, int threadCount = 1); TRocCurve( const TVector<TVector<double>>& approxes, const TVector<TConstArrayRef<float>>& labels, int threadCount ); TRocCurve(const TVector<TRocPoint>& points); TRocCurve() = default; double SelectDecisionBoundaryByFalsePositiveRate(double falsePositiveRate); double SelectDecisionBoundaryByFalseNegativeRate(double falseNegativeRate); double SelectDecisionBoundaryByIntersection(); TVector<TRocPoint> GetCurvePoints(); void OutputRocCurve(const TString& outputPath); private: TVector<TRocPoint> Points; // Points are sorted by Boundary from higher to lower size_t RateCurvesIntersection; private: void BuildCurve( const TVector<TVector<double>>& approxes, // [poolId][docId] const TVector<TConstArrayRef<float>>& labels, // [poolId][docId] NPar::ILocalExecutor* localExecutor ); static TRocPoint IntersectSegments(const TRocPoint& leftEnds, const TRocPoint& rightEnds); void AddPoint(double newBoundary, double newFnr, double newFpr); };
711
778
// // Project Name: KratosPoromechanicsApplication $ // Created by: $Author: JMCarbonell $ // Last modified by: $Co-Author: $ // Date: $Date: July 2013 $ // Revision: $Revision: 0.0 $ // // // System includes // External includes // Project includes #include "custom_constitutive/custom_flow_rules/flow_rule.hpp" namespace Kratos { KRATOS_CREATE_LOCAL_FLAG( FlowRule, IMPLEX_ACTIVE, 0 ); KRATOS_CREATE_LOCAL_FLAG( FlowRule, PLASTIC_REGION, 1 ); KRATOS_CREATE_LOCAL_FLAG( FlowRule, PLASTIC_RATE_REGION, 2 ); KRATOS_CREATE_LOCAL_FLAG( FlowRule, RETURN_MAPPING_COMPUTED, 3 ); } // namespace Kratos.
408
701
<gh_stars>100-1000 #include "InstantRadiosityGameState.h" #include "CameraController.h" #include "GraphicsSystem.h" #include "OgreSceneManager.h" #include "OgreItem.h" #include "OgreMeshManager.h" #include "OgreMeshManager2.h" #include "OgreMesh2.h" #include "OgreCamera.h" #include "OgreHlmsPbsDatablock.h" #include "OgreRoot.h" #include "OgreHlmsManager.h" #include "OgreHlmsPbs.h" #include "OgreLwString.h" #include "../LocalCubemaps/LocalCubemapScene.h" #include "InstantRadiosity/OgreInstantRadiosity.h" #include "OgreIrradianceVolume.h" #include "OgreForward3D.h" #include "OgreTextureGpu.h" #include "OgreTextureGpuManager.h" using namespace Demo; namespace Demo { InstantRadiosityGameState::InstantRadiosityGameState( const Ogre::String &helpDescription ) : TutorialGameState( helpDescription ), mLightNode( 0 ), mLight( 0 ), mCurrentType( Ogre::Light::LT_SPOTLIGHT ), mInstantRadiosity( 0 ), mIrradianceVolume( 0 ), mIrradianceCellSize(1.5f) { mDisplayHelpMode = 2; mNumDisplayHelpModes = 3; } //----------------------------------------------------------------------------------- void InstantRadiosityGameState::createLight() { Ogre::SceneManager *sceneManager = mGraphicsSystem->getSceneManager(); Ogre::SceneNode *rootNode = sceneManager->getRootSceneNode(); if( mLight ) { sceneManager->destroyLight( mLight ); mLight = 0; mLightNode->getParentSceneNode()->removeAndDestroyChild( mLightNode ); mLightNode = 0; } mLight = sceneManager->createLight(); mLightNode = rootNode->createChildSceneNode(); mLightNode->attachObject( mLight ); mLight->setPowerScale( Ogre::Math::PI ); switch( mCurrentType ) { default: case Ogre::Light::LT_SPOTLIGHT: mLight->setType( Ogre::Light::LT_SPOTLIGHT ); mLight->setDirection( Ogre::Vector3( -1, -1, -1 ).normalisedCopy() ); mLightNode->setPosition( Ogre::Vector3( -0.505, 3.400016, 5.423867 ) ); mLight->setAttenuation( 23.0f, 0.5f, 0.0f, 0.5f ); break; case Ogre::Light::LT_POINT: mLight->setType( Ogre::Light::LT_POINT ); mLightNode->setPosition( Ogre::Vector3( -0.505, 3.400016, 5.423867 ) ); mLight->setAttenuation( 23.0f, 0.5f, 0.0f, 0.5f ); break; case Ogre::Light::LT_DIRECTIONAL: mLight->setType( Ogre::Light::LT_DIRECTIONAL ); mLight->setDirection( Ogre::Vector3( 1, -1, -1 ).normalisedCopy() ); mLight->setAttenuation( std::numeric_limits<Ogre::Real>::max(), 1.0f, 0, 0 ); break; } mInstantRadiosity->build(); } //----------------------------------------------------------------------------------- void InstantRadiosityGameState::updateIrradianceVolume() { Ogre::HlmsManager *hlmsManager = mGraphicsSystem->getRoot()->getHlmsManager(); assert( dynamic_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms( Ogre::HLMS_PBS ) ) ); Ogre::HlmsPbs *hlmsPbs = static_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms(Ogre::HLMS_PBS) ); if( !hlmsPbs->getIrradianceVolume() ) return; Ogre::Vector3 volumeOrigin; Ogre::Real lightMaxPower; Ogre::uint32 numBlocksX, numBlocksY, numBlocksZ; mInstantRadiosity->suggestIrradianceVolumeParameters( Ogre::Vector3( mIrradianceCellSize ), volumeOrigin, lightMaxPower, numBlocksX, numBlocksY, numBlocksZ); mIrradianceVolume->createIrradianceVolumeTexture(numBlocksX, numBlocksY, numBlocksZ); mInstantRadiosity->fillIrradianceVolume( mIrradianceVolume, Ogre::Vector3(mIrradianceCellSize), volumeOrigin, lightMaxPower, false ); } //----------------------------------------------------------------------------------- void InstantRadiosityGameState::createScene01() { //Setup a scene similar to that of PBS sample, except //we apply the cubemap to everything via C++ code Ogre::SceneManager *sceneManager = mGraphicsSystem->getSceneManager(); Ogre::v1::MeshPtr planeMeshV1 = Ogre::v1::MeshManager::getSingleton().createPlane( "Plane v1", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::Plane( Ogre::Vector3::UNIT_Y, 1.0f ), 50.0f, 50.0f, 1, 1, true, 1, 4.0f, 4.0f, Ogre::Vector3::UNIT_Z, Ogre::v1::HardwareBuffer::HBU_STATIC, Ogre::v1::HardwareBuffer::HBU_STATIC ); Ogre::MeshPtr planeMesh = Ogre::MeshManager::getSingleton().createByImportingV1( "Plane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, planeMeshV1.get(), true, true, true ); { Ogre::HlmsManager *hlmsManager = mGraphicsSystem->getRoot()->getHlmsManager(); assert( dynamic_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms( Ogre::HLMS_PBS ) ) ); Ogre::HlmsPbs *hlmsPbs = static_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms(Ogre::HLMS_PBS) ); Ogre::HlmsBlendblock blendblock; Ogre::HlmsMacroblock macroblock; struct DemoMaterials { Ogre::String matName; Ogre::ColourValue colour; }; DemoMaterials materials[4] = { { "Red", Ogre::ColourValue::Red }, { "Green", Ogre::ColourValue::Green }, { "Blue", Ogre::ColourValue::Blue }, { "Cream", Ogre::ColourValue::White }, }; for( int i=0; i<4; ++i ) { Ogre::String finalName = materials[i].matName; Ogre::HlmsPbsDatablock *datablock; datablock = static_cast<Ogre::HlmsPbsDatablock*>( hlmsPbs->createDatablock( finalName, finalName, macroblock, blendblock, Ogre::HlmsParamVec() ) ); datablock->setBackgroundDiffuse( materials[i].colour ); datablock->setFresnel( Ogre::Vector3( 0.1f ), false ); datablock->setRoughness( 0.02 ); } } generateScene( sceneManager ); Ogre::HlmsManager *hlmsManager = mGraphicsSystem->getRoot()->getHlmsManager(); mInstantRadiosity = new Ogre::InstantRadiosity( sceneManager, hlmsManager ); mInstantRadiosity->mVplThreshold = 0.0005f; //Guide where to shoot the rays for directional lights the 3 windows + the //hole in the ceiling). We use a sphere radius of 30 to ensure when the directional //light's dir is towards -X, we actually hit walls (instead of going through these //walls and generating incorrect results). mInstantRadiosity->mAoI.push_back( Ogre::InstantRadiosity::AreaOfInterest( Ogre::Aabb( Ogre::Vector3( -0.746887f, 7.543859f, 5.499001f ), Ogre::Vector3( 2.876101f, 2.716137f, 6.059607f ) * 0.5f ), 30.0f ) ); mInstantRadiosity->mAoI.push_back( Ogre::InstantRadiosity::AreaOfInterest( Ogre::Aabb( Ogre::Vector3( -6.26f, 3.969576f, 6.628003f ), Ogre::Vector3( 1.673888f, 6.04f, 1.3284f ) * 0.5f ), 30.0f ) ); mInstantRadiosity->mAoI.push_back( Ogre::InstantRadiosity::AreaOfInterest( Ogre::Aabb( Ogre::Vector3( -6.26f, 3.969576f, 3.083399f ), Ogre::Vector3( 1.673888f, 6.04f, 1.3284f ) * 0.5f ), 30.0f ) ); mInstantRadiosity->mAoI.push_back( Ogre::InstantRadiosity::AreaOfInterest( Ogre::Aabb( Ogre::Vector3( -6.26f, 3.969576f, -0.415852f ), Ogre::Vector3( 1.673888f, 6.04f, 1.3284f ) * 0.5f ), 30.0f ) ); createLight(); mCameraController = new CameraController( mGraphicsSystem, false ); mCameraController->mCameraBaseSpeed = 1.0f; mCameraController->mCameraSpeedBoost = 10.0f; sceneManager->setForwardClustered( true, 16, 8, 24, 96, 0, 0, 2, 50 ); //Required by InstantRadiosity sceneManager->getForwardPlus()->setEnableVpls( true ); mIrradianceVolume = new Ogre::IrradianceVolume(hlmsManager); TutorialGameState::createScene01(); } //----------------------------------------------------------------------------------- void InstantRadiosityGameState::destroyScene() { // Ogre::HlmsManager *hlmsManager = mGraphicsSystem->getRoot()->getHlmsManager(); // assert( dynamic_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms( Ogre::HLMS_PBS ) ) ); // Ogre::HlmsPbs *hlmsPbs = static_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms(Ogre::HLMS_PBS) ); // hlmsPbs->setParallaxCorrectedCubemap( 0 ); delete mInstantRadiosity; mInstantRadiosity = 0; } //----------------------------------------------------------------------------------- void InstantRadiosityGameState::update( float timeSinceLast ) { /*if( mAnimateObjects ) { for( int i=0; i<16; ++i ) mSceneNode[i]->yaw( Ogre::Radian(timeSinceLast * i * 0.125f) ); }*/ std::map<SDL_Keycode, SDL_Keysym>::const_iterator itor = mKeysHold.begin(); std::map<SDL_Keycode, SDL_Keysym>::const_iterator end = mKeysHold.end(); bool needsIrradianceVolumeRebuild = false; bool changedVplSetting = false; bool needsRebuild = false; while( itor != end ) { const SDL_Keysym &keySym = itor->second; const bool reverse = (keySym.mod & (KMOD_LSHIFT|KMOD_RSHIFT)) != 0; const float modPerFrame = reverse ? -timeSinceLast : timeSinceLast; if( keySym.scancode == SDL_SCANCODE_H ) { mInstantRadiosity->mCellSize += modPerFrame; mInstantRadiosity->mCellSize = std::max( mInstantRadiosity->mCellSize, Ogre::Real(0.001f) ); needsRebuild = true; } if( keySym.scancode == SDL_SCANCODE_J ) { mInstantRadiosity->mBias += modPerFrame; mInstantRadiosity->mBias = Ogre::Math::Clamp( mInstantRadiosity->mBias, Ogre::Real(0.0f), Ogre::Real(1.0f) ); needsRebuild = true; } if( keySym.scancode == SDL_SCANCODE_U ) { mInstantRadiosity->mVplMaxRange += modPerFrame * 4.0f; changedVplSetting = true; needsIrradianceVolumeRebuild = true; } if( keySym.scancode == SDL_SCANCODE_I ) { mInstantRadiosity->mVplPowerBoost += modPerFrame * 2.0f; changedVplSetting = true; needsIrradianceVolumeRebuild = true; } if( keySym.scancode == SDL_SCANCODE_O ) { mInstantRadiosity->mVplThreshold += modPerFrame * 0.05f; changedVplSetting = true; } if( keySym.scancode == SDL_SCANCODE_P ) { mInstantRadiosity->mVplIntensityRangeMultiplier += modPerFrame * 10.0; mInstantRadiosity->mVplIntensityRangeMultiplier = std::max( mInstantRadiosity->mVplIntensityRangeMultiplier, 0.01 ); changedVplSetting = true; needsIrradianceVolumeRebuild = true; } if( keySym.scancode == SDL_SCANCODE_M ) { mIrradianceCellSize += modPerFrame * 10.0f; mIrradianceCellSize = std::max( mIrradianceCellSize, Ogre::Real(0.1f) ); needsIrradianceVolumeRebuild = true; } ++itor; } if( changedVplSetting && !needsRebuild ) mInstantRadiosity->updateExistingVpls(); if( needsRebuild ) mInstantRadiosity->build(); if( needsIrradianceVolumeRebuild || needsRebuild ) updateIrradianceVolume(); TutorialGameState::update( timeSinceLast ); } //----------------------------------------------------------------------------------- void InstantRadiosityGameState::generateDebugText( float timeSinceLast, Ogre::String &outText ) { TutorialGameState::generateDebugText( timeSinceLast, outText ); if( mDisplayHelpMode != 2 ) return; Ogre::HlmsManager *hlmsManager = mGraphicsSystem->getRoot()->getHlmsManager(); assert( dynamic_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms( Ogre::HLMS_PBS ) ) ); Ogre::HlmsPbs *hlmsPbs = static_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms(Ogre::HLMS_PBS) ); outText += "\nF2 to toggle debug VPL markers "; outText += mInstantRadiosity->getEnableDebugMarkers() ? "[On]" : "[Off]"; outText += "\nF3 to change light type "; switch( mCurrentType ) { default: case Ogre::Light::LT_SPOTLIGHT: outText += "[Spot]"; break; case Ogre::Light::LT_POINT: outText += "[Point]"; break; case Ogre::Light::LT_DIRECTIONAL: outText += "[Directional]"; break; } outText += "\nF4 to toggle intensity for max range "; outText += mInstantRadiosity->mVplUseIntensityForMaxRange ? "[On]" : "[Off]"; outText += "\nF5 to use Irradiance Volumes instead of VPLs "; outText += hlmsPbs->getIrradianceVolume() ? "[Irradiance]" : "[VPL]"; outText += "\nHold [Shift] to change value in opposite direction"; outText += "\nVPL Max range [U]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mVplMaxRange ); outText += "\nVPL Power Boost [I]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mVplPowerBoost ); outText += "\nVPL Threshold [O]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mVplThreshold ); if( mInstantRadiosity->mVplUseIntensityForMaxRange ) { outText += "\nVPL Intensity Range Multiplier [P]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mVplIntensityRangeMultiplier ); } outText += "\nNum Rays [G]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mNumRays ); outText += "\nCluster size [H]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mCellSize ); outText += "\nBias [J]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mBias ); outText += "\nSpread Iterations [K]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mNumSpreadIterations ); outText += "\nNum bounces [L]: "; outText += Ogre::StringConverter::toString( mInstantRadiosity->mNumRayBounces ); if( hlmsPbs->getIrradianceVolume() ) { outText += "\nIrradiance Cell Size [M]: "; outText += Ogre::StringConverter::toString( mIrradianceCellSize ); } Ogre::Camera *camera = mGraphicsSystem->getCamera(); outText += "\nCamera: "; outText += Ogre::StringConverter::toString( camera->getPosition().x ) + ", " + Ogre::StringConverter::toString( camera->getPosition().y ) + ", " + Ogre::StringConverter::toString( camera->getPosition().z ); } //----------------------------------------------------------------------------------- void InstantRadiosityGameState::keyPressed( const SDL_KeyboardEvent &arg ) { mKeysHold[arg.keysym.scancode] = arg.keysym; TutorialGameState::keyPressed( arg ); } //----------------------------------------------------------------------------------- void InstantRadiosityGameState::keyReleased( const SDL_KeyboardEvent &arg ) { mKeysHold.erase( arg.keysym.scancode ); if( (arg.keysym.mod & ~(KMOD_NUM|KMOD_CAPS|KMOD_LSHIFT|KMOD_RSHIFT)) != 0 ) { TutorialGameState::keyReleased( arg ); return; } if( arg.keysym.scancode == SDL_SCANCODE_F2 ) { mInstantRadiosity->setEnableDebugMarkers( !mInstantRadiosity->getEnableDebugMarkers() ); } else if( arg.keysym.scancode == SDL_SCANCODE_F3 ) { mCurrentType = static_cast<Ogre::Light::LightTypes>( (mCurrentType + 1) % Ogre::Light::LT_VPL ); createLight(); updateIrradianceVolume(); } else if( arg.keysym.scancode == SDL_SCANCODE_F4 ) { mInstantRadiosity->mVplUseIntensityForMaxRange = !mInstantRadiosity->mVplUseIntensityForMaxRange; mInstantRadiosity->updateExistingVpls(); updateIrradianceVolume(); } else if( arg.keysym.scancode == SDL_SCANCODE_F5 ) { Ogre::HlmsManager *hlmsManager = mGraphicsSystem->getRoot()->getHlmsManager(); assert( dynamic_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms( Ogre::HLMS_PBS ) ) ); Ogre::HlmsPbs *hlmsPbs = static_cast<Ogre::HlmsPbs*>( hlmsManager->getHlms(Ogre::HLMS_PBS) ); if( !hlmsPbs->getIrradianceVolume() ) { hlmsPbs->setIrradianceVolume( mIrradianceVolume ); updateIrradianceVolume(); mInstantRadiosity->setUseIrradianceVolume(true); } else { hlmsPbs->setIrradianceVolume( 0 ); mInstantRadiosity->setUseIrradianceVolume(false); } } else if( arg.keysym.scancode == SDL_SCANCODE_G ) { const bool reverse = (arg.keysym.mod & (KMOD_LSHIFT|KMOD_RSHIFT)) != 0; if( reverse ) mInstantRadiosity->mNumRays >>= 1u; else mInstantRadiosity->mNumRays <<= 1u; //Too many rays and the app will become unresponsive mInstantRadiosity->mNumRays = std::max<size_t>( mInstantRadiosity->mNumRays, 1u ); mInstantRadiosity->mNumRays = std::min<size_t>( mInstantRadiosity->mNumRays, 32768u ); mInstantRadiosity->build(); updateIrradianceVolume(); } else if( arg.keysym.scancode == SDL_SCANCODE_K ) { const bool reverse = (arg.keysym.mod & (KMOD_LSHIFT|KMOD_RSHIFT)) != 0; if( reverse ) { if( mInstantRadiosity->mNumSpreadIterations ) --mInstantRadiosity->mNumSpreadIterations; } else { if( mInstantRadiosity->mNumSpreadIterations < 10 ) ++mInstantRadiosity->mNumSpreadIterations; } mInstantRadiosity->build(); updateIrradianceVolume(); } else if( arg.keysym.scancode == SDL_SCANCODE_L ) { const bool reverse = (arg.keysym.mod & (KMOD_LSHIFT|KMOD_RSHIFT)) != 0; if( reverse ) { if( mInstantRadiosity->mNumRayBounces ) --mInstantRadiosity->mNumRayBounces; } else { if( mInstantRadiosity->mNumRayBounces < 5 ) ++mInstantRadiosity->mNumRayBounces; } mInstantRadiosity->build(); updateIrradianceVolume(); } else { TutorialGameState::keyReleased( arg ); } } }
9,854
1,144
<reponame>dram/metasfresh<gh_stars>1000+ package de.metas.vertical.pharma.securpharm.client; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyStore; import javax.net.ssl.SSLContext; import org.adempiere.exceptions.AdempiereException; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import de.metas.vertical.pharma.securpharm.client.schema.JsonAuthResponse; import de.metas.vertical.pharma.securpharm.config.SecurPharmConfig; import lombok.NonNull; /* * #%L * metasfresh-pharma.securpharm * %% * Copyright (C) 2019 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ final class SecurPharmClientAuthenticator { public static SecurPharmClientAuthenticator ofConfig(@NonNull final SecurPharmConfig config) { return new SecurPharmClientAuthenticator(config); } private static final String AUTH_PARAM_CLIENT_ID_VALUE = "securPharm"; private static final String AUTH_PARAM_GRANT_TYPE = "grant_type"; private static final String AUTH_PARAM_GRANT_TYPE_VALUE = "password"; private static final String AUTH_PARAM_CLIENT_ID = "client_id"; private static final String AUTH_RELATIVE_PATH = "/auth/realms/testentity/protocol/openid-connect/token"; private static final String AUTHORIZATION_TYPE_BEARER = "Bearer "; private static final String MSG_AUTHORIZATION_FAILED = "Authorization failed"; @NonNull private final SecurPharmConfig config; private JsonAuthResponse _authResponse; // lazy private SecurPharmClientAuthenticator(@NonNull final SecurPharmConfig config) { this.config = config; } public String getAuthorizationHttpHeader() { return AUTHORIZATION_TYPE_BEARER + getAccessToken(); } private String getAccessToken() { return getAuthResponse().getAccessToken(); } private synchronized JsonAuthResponse getAuthResponse() { JsonAuthResponse authResponse = _authResponse; if (authResponse == null || authResponse.isExpired()) { authResponse = _authResponse = authenticate(config); } return authResponse; } public void authenticate() { getAuthResponse(); } private static JsonAuthResponse authenticate(@NonNull final SecurPharmConfig config) { try { final SSLContext sslContext = createSSLContext(config); final HttpClient client = HttpClients.custom() .setSSLContext(sslContext) .build(); final RestTemplate restTemplate = new RestTemplate(); restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(client)); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); final MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add(AUTH_PARAM_GRANT_TYPE, AUTH_PARAM_GRANT_TYPE_VALUE); params.add(AUTH_PARAM_CLIENT_ID, AUTH_PARAM_CLIENT_ID_VALUE); final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers); final ResponseEntity<JsonAuthResponse> response = restTemplate.postForEntity(config.getAuthBaseUrl() + AUTH_RELATIVE_PATH, request, JsonAuthResponse.class); final JsonAuthResponse authResponse = response.getBody(); if (response.getStatusCode() == HttpStatus.OK) { return authResponse; } else { throw new AdempiereException(MSG_AUTHORIZATION_FAILED) .appendParametersToMessage() .setParameter("HTTPStatus", response.getStatusCode()) .setParameter("error", authResponse.getError()) .setParameter("errorDescription", authResponse.getErrorDescription()); } } catch (final AdempiereException ex) { throw ex; } catch (final Exception ex) { final Throwable cause = AdempiereException.extractCause(ex); throw new AdempiereException(MSG_AUTHORIZATION_FAILED, cause); } } private static SSLContext createSSLContext(final SecurPharmConfig config) { try { final char[] password = config.getKeystorePassword().toCharArray(); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); final File key = new File(config.getCertificatePath()); try (final InputStream in = new FileInputStream(key)) { keyStore.load(in, password); } return SSLContextBuilder.create() .loadKeyMaterial(keyStore, password) .loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); } catch (final Exception ex) { throw new AdempiereException("Failed creating SSL context " + ex.getLocalizedMessage(), ex) .appendParametersToMessage() .setParameter("config", config); } } }
1,888
370
<reponame>Kronuz/Xapiand /* * Copyright (c) 2015-2019 Dubalu LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <dirent.h> // for DIR, readdir, opendir, closedir #include <string> // for std::string #include <string_view> // for std::string_view #include <vector> // for std::vector struct File_ptr { struct dirent *ent; File_ptr() : ent(nullptr) { } }; void delete_files(std::string_view path, const std::vector<std::string>& patterns = {"*"}); void quarantine_files(std::string_view path, const std::vector<std::string>& patterns = {"*"}, std::string_view template_suffix = ".quarantine.XXXXXX"); void move_files(std::string_view src, std::string_view dst); bool exists(std::string_view path); bool mkdir(std::string_view path); bool mkdirs(std::string_view path); bool build_path_index(std::string_view path_index); DIR* opendir(std::string_view path, bool create = false); void find_file_dir(DIR* dir, File_ptr& fptr, std::string_view pattern, bool pre_suf_fix); // Copy all directory if file_name and new_name are empty int copy_file(std::string_view src, std::string_view dst, bool create = true, std::string_view file_name = "", std::string_view new_name = ""); std::string normalize_path(std::string_view src, bool slashed = false, bool keep_slash = false);
760
810
<reponame>FreeYeti/tilemill { "name": "carto", "description": "Carto syntax reference for editing.", "engines": {"tilemill":"*"}, "private": true }
64
343
/* $Id$ $Revision$ */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #ifdef __cplusplus extern "C" { #endif /* : : generated from features/align.c by iffe version 1999-08-11 : : */ #ifndef _def_align_ast #define _def_align_ast 1 typedef unsigned long ALIGN_INTEGRAL; #define ALIGN_CHUNK 8192 #define ALIGN_INTEGRAL long #define ALIGN_INTEGER(x) ((ALIGN_INTEGRAL)(x)) #define ALIGN_POINTER(x) ((char*)(x)) #define ALIGN_ROUND(x,y) ALIGN_POINTER(ALIGN_INTEGER((x)+(y)-1)&~((y)-1)) #define ALIGN_BOUND ALIGN_BOUND2 #define ALIGN_ALIGN(x) ALIGN_ALIGN2(x) #define ALIGN_TRUNC(x) ALIGN_TRUNC2(x) #define ALIGN_BIT1 0x1 #define ALIGN_BOUND1 ALIGN_BOUND2 #define ALIGN_ALIGN1(x) ALIGN_ALIGN2(x) #define ALIGN_TRUNC1(x) ALIGN_TRUNC2(x) #define ALIGN_CLRBIT1(x) ALIGN_POINTER(ALIGN_INTEGER(x)&0xfffffffe) #define ALIGN_SETBIT1(x) ALIGN_POINTER(ALIGN_INTEGER(x)|0x1) #define ALIGN_TSTBIT1(x) ALIGN_POINTER(ALIGN_INTEGER(x)&0x1) #define ALIGN_BIT2 0x2 #define ALIGN_BOUND2 8 #define ALIGN_ALIGN2(x) ALIGN_TRUNC2((x)+7) #define ALIGN_TRUNC2(x) ALIGN_POINTER(ALIGN_INTEGER(x)&0xfffffff8) #define ALIGN_CLRBIT2(x) ALIGN_POINTER(ALIGN_INTEGER(x)&0xfffffffd) #define ALIGN_SETBIT2(x) ALIGN_POINTER(ALIGN_INTEGER(x)|0x2) #define ALIGN_TSTBIT2(x) ALIGN_POINTER(ALIGN_INTEGER(x)&0x2) #endif #ifdef __cplusplus } #endif
774
2,313
/* * Copyright (c) 2017-2021 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef ARM_COMPUTE_NEDIRECTCONVOLUTIONDETAIL_H #define ARM_COMPUTE_NEDIRECTCONVOLUTIONDETAIL_H #include "src/core/NEON/NEFixedPoint.h" #include "src/core/NEON/wrapper/wrapper.h" #include "support/Requires.h" #include <arm_neon.h> namespace arm_compute { namespace detail { /** Loads a 3x3 matrix as a row (float). * * @param[in] ptr Pointer to a float 3x3 matrix. * @param[in] weights_offset (Optional) Weights quantization offset. * * @return The loaded matrix. */ inline float32x4x3_t load_matrix_row(const float *ptr, int weights_offset = 0) { ARM_COMPUTE_UNUSED(weights_offset); const float32x4x3_t r = { { vld1q_dup_f32(ptr), vld1q_dup_f32(1 + ptr), vld1q_dup_f32(2 + ptr) } }; return r; } /** Loads a 3x3 matrix as a row (uint8_t/int8_t). * * @param[in] ptr Pointer to a uint8_t/int8_t 3x3 matrix. * @param[in] weights_offset (Optional) Weights quantization offset. * * @return The loaded matrix. */ template < typename T, ARM_COMPUTE_REQUIRES_TA(std::is_same<T, uint8_t>::value || std::is_same<T, int8_t>::value) > inline int32x4x3_t load_matrix_row(const T *ptr, int weights_offset = 0) { const int32x4_t v_weights_offset = vdupq_n_s32(weights_offset); /* ptr is a pointer to a row in a 3x3 matrix, the function returns 3 vectors holding exactly the same value in all lanes: r.val[0] contains the first element, r.val[1] the second element and r.val[2] the third element (in all lanes) */ int32x4x3_t r = { { vaddq_s32(v_weights_offset, vdupq_n_s32(*ptr)), vaddq_s32(v_weights_offset, vdupq_n_s32(*(ptr + 1))), vaddq_s32(v_weights_offset, vdupq_n_s32(*(ptr + 2))) } }; return r; } /** Stores a float32x4x2_t array into a memory location. * * @param[in] buffer Pointer to the memory location where the values will be stored. * @param[in] values Values that will be stored. * */ template <unsigned int stridex> void store_results(float *buffer, const float32x4x2_t &values); template <> inline void store_results<1>(float *buffer, const float32x4x2_t &values) { vst1q_f32(buffer, values.val[0]); vst1q_f32(buffer + 4, values.val[1]); } template <> inline void store_results<2>(float *buffer, const float32x4x2_t &values) { vst1q_f32(buffer, values.val[0]); } template <> inline void store_results<3>(float *buffer, const float32x4x2_t &values) { vst1_f32(buffer, vget_low_f32(values.val[0])); } /** Stores a uint32_t array into a memory location. * * @param[in] buffer Pointer to the memory location where the values will be stored. * @param[in] values Values that will be stored. * */ template <unsigned int stridex> void store_results(int32_t *buffer, const int32x4x2_t &values); template <> inline void store_results<1>(int32_t *buffer, const int32x4x2_t &values) { vst1q_s32(buffer, values.val[0]); vst1q_s32(buffer + 4, values.val[1]); } template <> inline void store_results<2>(int32_t *buffer, const int32x4x2_t &values) { vst1q_s32(buffer, values.val[0]); } template <> inline void store_results<3>(int32_t *buffer, const int32x4x2_t &values) { vst1_s32(buffer, vget_low_s32(values.val[0])); } template <unsigned int stridex> inline void accumulate_results(float *buffer, const float32x4x2_t &values); template <> inline void accumulate_results<1>(float *buffer, const float32x4x2_t &values) { vst1q_f32(buffer, vaddq_f32(vld1q_f32(buffer), values.val[0])); vst1q_f32(buffer + 4, vaddq_f32(vld1q_f32(buffer + 4), values.val[1])); } template <> inline void accumulate_results<2>(float *buffer, const float32x4x2_t &values) { vst1q_f32(buffer, vaddq_f32(vld1q_f32(buffer), values.val[0])); } template <> inline void accumulate_results<3>(float *buffer, const float32x4x2_t &values) { vst1_f32(buffer, vadd_f32(vld1_f32(buffer), vget_low_f32(values.val[0]))); } template <unsigned int stridex> void accumulate_results(int32_t *buffer, const int32x4x2_t &values); template <> inline void accumulate_results<1>(int32_t *buffer, const int32x4x2_t &values) { vst1q_s32(buffer, vaddq_s32(vld1q_s32(buffer), values.val[0])); vst1q_s32(buffer + 4, vaddq_s32(vld1q_s32(buffer + 4), values.val[1])); } template <> inline void accumulate_results<2>(int32_t *buffer, const int32x4x2_t &values) { vst1q_s32(buffer, vaddq_s32(vld1q_s32(buffer), values.val[0])); } template <> inline void accumulate_results<3>(int32_t *buffer, const int32x4x2_t &values) { vst1_s32(buffer, vadd_s32(vld1_s32(buffer), vget_low_s32(values.val[0]))); } #ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC /** Stores a float16x8x2_t array into a memory location. * * @param[in] buffer Pointer to the memory location where the values will be stored. * @param[in] values Values that will be stored. * */ template <unsigned int stridex> void store_results(float16_t *buffer, const float16x8x2_t &values); template <> inline void store_results<1>(float16_t *buffer, const float16x8x2_t &values) { vst1q_f16(buffer, values.val[0]); vst1q_f16(buffer + 8, values.val[1]); } template <> inline void store_results<2>(float16_t *buffer, const float16x8x2_t &values) { vst1q_f16(buffer, values.val[0]); } template <> inline void store_results<3>(float16_t *buffer, const float16x8x2_t &values) { vst1_f16(buffer, vget_low_f16(values.val[0])); } template <unsigned int stridex> inline void accumulate_results(float16_t *buffer, const float16x8x2_t &values); template <> inline void accumulate_results<1>(float16_t *buffer, const float16x8x2_t &values) { vst1q_f16(buffer, vaddq_f16(vld1q_f16(buffer), values.val[0])); vst1q_f16(buffer + 8, vaddq_f16(vld1q_f16(buffer + 8), values.val[1])); } template <> inline void accumulate_results<2>(float16_t *buffer, const float16x8x2_t &values) { vst1q_f16(buffer, vaddq_f16(vld1q_f16(buffer), values.val[0])); } template <> inline void accumulate_results<3>(float16_t *buffer, const float16x8x2_t &values) { vst1_f16(buffer, vadd_f16(vld1_f16(buffer), vget_low_f16(values.val[0]))); } #endif /* __ARM_FEATURE_FP16_VECTOR_ARITHMETIC */ /** Perform a 3x3 convolution for 4 consecutive elements on float32 when dilation.x() or dilation.y() is not 1. * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] dilation_x Dilation, in elements across x. * @param[in] input_offset (Optional) Input quantization offset. * */ inline float32x4_t single_convolve_3x3_dilation(const float *in_top, const float *in_mid, const float *in_low, const float32x4x3_t &m0, const float32x4x3_t &m1, const float32x4x3_t &m2, const size_t dilation_x, int input_offset) { ARM_COMPUTE_UNUSED(input_offset); const float32x4x3_t vtop = { { vld1q_f32(in_top), vld1q_f32(in_top + dilation_x), vld1q_f32(in_top + 2 * dilation_x) } }; const float32x4x3_t vmid = { { vld1q_f32(in_mid), vld1q_f32(in_mid + dilation_x), vld1q_f32(in_mid + 2 * dilation_x) } }; const float32x4x3_t vlow = { { vld1q_f32(in_low), vld1q_f32(in_low + dilation_x), vld1q_f32(in_low + 2 * dilation_x) } }; float32x4_t out = vmulq_f32(vtop.val[0], m0.val[0]); out = vmlaq_f32(out, vtop.val[1], m0.val[1]); out = vmlaq_f32(out, vtop.val[2], m0.val[2]); out = vmlaq_f32(out, vmid.val[0], m1.val[0]); out = vmlaq_f32(out, vmid.val[1], m1.val[1]); out = vmlaq_f32(out, vmid.val[2], m1.val[2]); out = vmlaq_f32(out, vlow.val[0], m2.val[0]); out = vmlaq_f32(out, vlow.val[1], m2.val[1]); out = vmlaq_f32(out, vlow.val[2], m2.val[2]); return out; } /** Perform a 3x3 convolution for 8 consecutive elements on float32 when dilation.x() or dilation.y() is not 1. * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] dilation_x Dilation, in elements across x. * @param[in] stridex Stride value in elements across x. * @param[in] input_offset (Optional) Input quantization offset. * */ inline float32x4x2_t convolve_3x3_dilation(const float *in_top, const float *in_mid, const float *in_low, const float32x4x3_t &m0, const float32x4x3_t &m1, const float32x4x3_t &m2, const size_t dilation_x, unsigned int stridex, int input_offset = 0) { ARM_COMPUTE_ERROR_ON(stridex > 3); float32x4x2_t out = { { single_convolve_3x3_dilation(in_top, in_mid, in_low, m0, m1, m2, dilation_x, input_offset), single_convolve_3x3_dilation(in_top + 4, in_mid + 4, in_low + 4, m0, m1, m2, dilation_x, input_offset) } }; if(stridex == 2) { out.val[0] = vsetq_lane_f32(vgetq_lane_f32(out.val[0], 2), out.val[0], 1); out.val[0] = vsetq_lane_f32(vgetq_lane_f32(out.val[1], 0), out.val[0], 2); out.val[0] = vsetq_lane_f32(vgetq_lane_f32(out.val[1], 2), out.val[0], 3); } else if(stridex == 3) { out.val[0] = vsetq_lane_f32(vgetq_lane_f32(out.val[0], 3), out.val[0], 1); } return out; } /** Perform a convolve3x3 on float32. * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[out] out_ptr Pointer to the output. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] stridex Stride value in elements across x. * @param[in] input_offset (Optional) Input quantization offset. * */ template <bool accumulate> void convolve_3x3(const float *in_top, const float *in_mid, const float *in_low, float *out_ptr, const float32x4x3_t &m0, const float32x4x3_t &m1, const float32x4x3_t &m2, unsigned int stridex, int input_offset = 0); template <bool accumulate> inline void convolve_3x3(const float *in_top, const float *in_mid, const float *in_low, float *out_ptr, const float32x4x3_t &m0, const float32x4x3_t &m1, const float32x4x3_t &m2, unsigned int stridex, int input_offset) { ARM_COMPUTE_UNUSED(input_offset); ARM_COMPUTE_ERROR_ON(stridex > 3); float32x4x2_t out = { { vdupq_n_f32(0.f), vdupq_n_f32(0.f) } }; if(stridex == 2) { const float32x4x2_t vtop = vld2q_f32(in_top); const float32x4x2_t vmid = vld2q_f32(in_mid); const float32x4x2_t vlow = vld2q_f32(in_low); const float32x4_t vtop_end = vld1q_f32(in_top + 8); const float32x4_t vmid_end = vld1q_f32(in_mid + 8); const float32x4_t vlow_end = vld1q_f32(in_low + 8); out.val[0] = vmulq_f32(vtop.val[0], m0.val[0]); out.val[0] = vmlaq_f32(out.val[0], vtop.val[1], m0.val[1]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vtop.val[0], vtop_end, 1), m0.val[2]); out.val[0] = vmlaq_f32(out.val[0], vmid.val[0], m1.val[0]); out.val[0] = vmlaq_f32(out.val[0], vmid.val[1], m1.val[1]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vmid.val[0], vmid_end, 1), m1.val[2]); out.val[0] = vmlaq_f32(out.val[0], vlow.val[0], m2.val[0]); out.val[0] = vmlaq_f32(out.val[0], vlow.val[1], m2.val[1]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vlow.val[0], vlow_end, 1), m2.val[2]); accumulate ? accumulate_results<2>(out_ptr, out) : store_results<2>(out_ptr, out); } else { const float32x4x3_t vtop = { { vld1q_f32(in_top), vld1q_f32(in_top + 4), vld1q_f32(in_top + 8) } }; const float32x4x3_t vmid = { { vld1q_f32(in_mid), vld1q_f32(in_mid + 4), vld1q_f32(in_mid + 8) } }; const float32x4x3_t vlow = { { vld1q_f32(in_low), vld1q_f32(in_low + 4), vld1q_f32(in_low + 8) } }; out.val[0] = vmulq_f32(vtop.val[0], m0.val[0]); out.val[1] = vmulq_f32(vtop.val[1], m0.val[0]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vtop.val[0], vtop.val[1], 1), m0.val[1]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vtop.val[0], vtop.val[1], 2), m0.val[2]); out.val[0] = vmlaq_f32(out.val[0], vmid.val[0], m1.val[0]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vmid.val[0], vmid.val[1], 1), m1.val[1]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vmid.val[0], vmid.val[1], 2), m1.val[2]); out.val[0] = vmlaq_f32(out.val[0], vlow.val[0], m2.val[0]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vlow.val[0], vlow.val[1], 1), m2.val[1]); out.val[0] = vmlaq_f32(out.val[0], vextq_f32(vlow.val[0], vlow.val[1], 2), m2.val[2]); out.val[1] = vmlaq_f32(out.val[1], vextq_f32(vtop.val[1], vtop.val[2], 1), m0.val[1]); out.val[1] = vmlaq_f32(out.val[1], vextq_f32(vtop.val[1], vtop.val[2], 2), m0.val[2]); out.val[1] = vmlaq_f32(out.val[1], vmid.val[1], m1.val[0]); out.val[1] = vmlaq_f32(out.val[1], vextq_f32(vmid.val[1], vmid.val[2], 1), m1.val[1]); out.val[1] = vmlaq_f32(out.val[1], vextq_f32(vmid.val[1], vmid.val[2], 2), m1.val[2]); out.val[1] = vmlaq_f32(out.val[1], vlow.val[1], m2.val[0]); out.val[1] = vmlaq_f32(out.val[1], vextq_f32(vlow.val[1], vlow.val[2], 1), m2.val[1]); out.val[1] = vmlaq_f32(out.val[1], vextq_f32(vlow.val[1], vlow.val[2], 2), m2.val[2]); if(stridex == 3) { out.val[0] = vsetq_lane_f32(vgetq_lane_f32(out.val[0], 3), out.val[0], 1); accumulate ? accumulate_results<3>(out_ptr, out) : store_results<3>(out_ptr, out); } else { accumulate ? accumulate_results<1>(out_ptr, out) : store_results<1>(out_ptr, out); } } } /** Perform a 3x3 convolution for 4 consecutive 8-bit elements when dilation.x() or dilation.y() is not 1. * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] dilation_x Dilation, in elements across x. * @param[in] input_offset Input quantization offset. * */ template < typename T, ARM_COMPUTE_REQUIRES_TA(std::is_same<T, uint8_t>::value || std::is_same<T, int8_t>::value) > inline int32x4_t single_convolve_3x3_dilation(const T *in_top, const T *in_mid, const T *in_low, const int32x4x3_t &m0, const int32x4x3_t &m1, const int32x4x3_t &m2, size_t dilation_x, int32_t input_offset) { using VectorType = typename std::conditional<std::is_same<T, uint8_t>::value, uint8x8x3_t, int8x8x3_t>::type; using OutputTagType = typename wrapper::traits::neon_bitvector_tag_t<int32_t, wrapper::traits::BitWidth::W128>; const int32x4_t v_input_offset = wrapper::vdup_n(input_offset, OutputTagType{}); const VectorType vtop = { { wrapper::vload(in_top), wrapper::vload(in_top + dilation_x), wrapper::vload(in_top + 2 * dilation_x) } }; const VectorType vmid = { { wrapper::vload(in_mid), wrapper::vload(in_mid + dilation_x), wrapper::vload(in_mid + 2 * dilation_x) } }; const VectorType vlow = { { wrapper::vload(in_low), wrapper::vload(in_low + dilation_x), wrapper::vload(in_low + 2 * dilation_x) } }; const int32x4x3_t vtop_s32 = { { wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vtop.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vtop.val[1])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vtop.val[2])))), } }; const int32x4x3_t vmid_s32 = { { wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vmid.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vmid.val[1])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vmid.val[2])))), } }; const int32x4x3_t vlow_s32 = { { wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vlow.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vlow.val[1])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vlow.val[2])))), } }; int32x4_t out = wrapper::vmul(vtop_s32.val[0], m0.val[0]); out = wrapper::vmla(out, vtop_s32.val[1], m0.val[1]); out = wrapper::vmla(out, vtop_s32.val[2], m0.val[2]); out = wrapper::vmla(out, vmid_s32.val[0], m1.val[0]); out = wrapper::vmla(out, vmid_s32.val[1], m1.val[1]); out = wrapper::vmla(out, vmid_s32.val[2], m1.val[2]); out = wrapper::vmla(out, vlow_s32.val[0], m2.val[0]); out = wrapper::vmla(out, vlow_s32.val[1], m2.val[1]); out = wrapper::vmla(out, vlow_s32.val[2], m2.val[2]); return out; } /** Perform a 3x3 convolution for 4 consecutive 8-bit elements when dilation.x() or dilation.y() is not 1. * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] dilation_x Dilation, in elements across x. * @param[in] stridex Stride value in elements across x. * @param[in] input_offset Input quantization offset. * */ template < typename T, ARM_COMPUTE_REQUIRES_TA(std::is_same<T, uint8_t>::value || std::is_same<T, int8_t>::value) > inline int32x4x2_t convolve_3x3_dilation(const T *in_top, const T *in_mid, const T *in_low, const int32x4x3_t &m0, const int32x4x3_t &m1, const int32x4x3_t &m2, const size_t dilation_x, unsigned int stridex, int input_offset) { ARM_COMPUTE_ERROR_ON(stridex > 3); int32x4x2_t out = { { single_convolve_3x3_dilation(in_top, in_mid, in_low, m0, m1, m2, dilation_x, input_offset), single_convolve_3x3_dilation(in_top + 4, in_mid + 4, in_low + 4, m0, m1, m2, dilation_x, input_offset) } }; if(stridex == 2) { out.val[0] = wrapper::vsetlane(wrapper::vgetlane(out.val[0], 2), out.val[0], 1); out.val[0] = wrapper::vsetlane(wrapper::vgetlane(out.val[1], 0), out.val[0], 2); out.val[0] = wrapper::vsetlane(wrapper::vgetlane(out.val[1], 2), out.val[0], 3); } else if(stridex == 3) { out.val[0] = wrapper::vsetlane(wrapper::vgetlane(out.val[0], 3), out.val[0], 1); } return out; } /** Perform a convolve3x3 on 8-bit elements * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[out] out_ptr Pointer to the output. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] stridex Stride value in elements across x. * @param[in] input_offset Input quantization offset. * */ template < bool accumulate, typename T1, typename T2, ARM_COMPUTE_REQUIRES_TA(std::is_same<T1, uint8_t>::value || std::is_same<T1, int8_t>::value) > void convolve_3x3(const T1 *in_top, const T1 *in_mid, const T1 *in_low, T2 *out_ptr, const int32x4x3_t &m0, const int32x4x3_t &m1, const int32x4x3_t &m2, unsigned int stridex, int32_t input_offset) { ARM_COMPUTE_ERROR_ON(stridex > 3); using VectorType = typename std::conditional<std::is_same<T1, uint8_t>::value, uint8x8x2_t, int8x8x2_t>::type; using OutputTagType = typename wrapper::traits::neon_bitvector_tag_t<int32_t, wrapper::traits::BitWidth::W128>; const int32x4_t v_input_offset = wrapper::vdup_n(input_offset, OutputTagType{}); const VectorType vtop = { { wrapper::vload(in_top), wrapper::vload(in_top + 8) } }; const VectorType vmid = { { wrapper::vload(in_mid), wrapper::vload(in_mid + 8) } }; const VectorType vlow = { { wrapper::vload(in_low), wrapper::vload(in_low + 8) } }; const int32x4x3_t vtop_s32 = { { wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vtop.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgethigh(wrapper::vmovl(vtop.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vtop.val[1])))), } }; const int32x4x3_t vmid_s32 = { { wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vmid.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgethigh(wrapper::vmovl(vmid.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vmid.val[1])))), } }; const int32x4x3_t vlow_s32 = { { wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vlow.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgethigh(wrapper::vmovl(vlow.val[0])))), wrapper::vaddw(v_input_offset, wrapper::vreinterpret(wrapper::vgetlow(wrapper::vmovl(vlow.val[1])))), } }; int32x4x2_t out { { wrapper::vdup_n(static_cast<int32_t>(0), OutputTagType{}), wrapper::vdup_n(static_cast<int32_t>(0), OutputTagType{}), } }; // 0 out.val[0] = wrapper::vmla(out.val[0], vtop_s32.val[0], m0.val[0]); out.val[0] = wrapper::vmla(out.val[0], wrapper::vext_1(vtop_s32.val[0], vtop_s32.val[1]), m0.val[1]); out.val[0] = wrapper::vmla(out.val[0], wrapper::vext_2(vtop_s32.val[0], vtop_s32.val[1]), m0.val[2]); out.val[0] = wrapper::vmla(out.val[0], vmid_s32.val[0], m1.val[0]); out.val[0] = wrapper::vmla(out.val[0], wrapper::vext_1(vmid_s32.val[0], vmid_s32.val[1]), m1.val[1]); out.val[0] = wrapper::vmla(out.val[0], wrapper::vext_2(vmid_s32.val[0], vmid_s32.val[1]), m1.val[2]); out.val[0] = wrapper::vmla(out.val[0], vlow_s32.val[0], m2.val[0]); out.val[0] = wrapper::vmla(out.val[0], wrapper::vext_1(vlow_s32.val[0], vlow_s32.val[1]), m2.val[1]); out.val[0] = wrapper::vmla(out.val[0], wrapper::vext_2(vlow_s32.val[0], vlow_s32.val[1]), m2.val[2]); // 1 out.val[1] = wrapper::vmla(out.val[1], vtop_s32.val[1], m0.val[0]); out.val[1] = wrapper::vmla(out.val[1], wrapper::vext_1(vtop_s32.val[1], vtop_s32.val[2]), m0.val[1]); out.val[1] = wrapper::vmla(out.val[1], wrapper::vext_2(vtop_s32.val[1], vtop_s32.val[2]), m0.val[2]); out.val[1] = wrapper::vmla(out.val[1], vmid_s32.val[1], m1.val[0]); out.val[1] = wrapper::vmla(out.val[1], wrapper::vext_1(vmid_s32.val[1], vmid_s32.val[2]), m1.val[1]); out.val[1] = wrapper::vmla(out.val[1], wrapper::vext_2(vmid_s32.val[1], vmid_s32.val[2]), m1.val[2]); out.val[1] = wrapper::vmla(out.val[1], vlow_s32.val[1], m2.val[0]); out.val[1] = wrapper::vmla(out.val[1], wrapper::vext_1(vlow_s32.val[1], vlow_s32.val[2]), m2.val[1]); out.val[1] = wrapper::vmla(out.val[1], wrapper::vext_2(vlow_s32.val[1], vlow_s32.val[2]), m2.val[2]); if(stridex == 1) { accumulate ? accumulate_results<1>(out_ptr, out) : store_results<1>(out_ptr, out); } else if(stridex == 2) { out.val[0] = wrapper::vsetlane(wrapper::vgetlane(out.val[0], 2), out.val[0], 1); out.val[0] = wrapper::vsetlane(wrapper::vgetlane(out.val[1], 0), out.val[0], 2); out.val[0] = wrapper::vsetlane(wrapper::vgetlane(out.val[1], 2), out.val[0], 3); accumulate ? accumulate_results<2>(out_ptr, out) : store_results<2>(out_ptr, out); } else if(stridex == 3) { out.val[0] = wrapper::vsetlane(wrapper::vgetlane(out.val[0], 3), out.val[0], 1); accumulate ? accumulate_results<3>(out_ptr, out) : store_results<3>(out_ptr, out); } } #ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC /** Loads a 3x3 matrix as a row (float16_t). * * @param[in] ptr Pointer to a float 3x3 matrix. * * @return The loaded matrix. */ inline float16x8x3_t load_matrix_row(const float16_t *ptr, int weights_offset = 0) { ARM_COMPUTE_UNUSED(weights_offset); /* ptr is a pointer to a row in a 3x3 matrix, the function returns 3 vectors holding exactly the same value in all lanes: r.val[0] contains the first element, r.val[1] the second element and r.val[2] the third element (in all lanes) */ const float16x8x3_t r = { { vld1q_dup_f16(ptr), vld1q_dup_f16(1 + ptr), vld1q_dup_f16(2 + ptr) } }; return r; } /** Perform a 3x3 convolution for 8 consecutive elements on float16 when dilation.x() or dilation.y() is not 1. * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] dilation_x Dilation, in elements across x. * @param[in] input_offset (Optional)Input quantization offset. * */ inline float16x8_t single_convolve_3x3_dilation(const float16_t *in_top, const float16_t *in_mid, const float16_t *in_low, const float16x8x3_t &m0, const float16x8x3_t &m1, const float16x8x3_t &m2, const size_t dilation_x, int input_offset = 0) { ARM_COMPUTE_UNUSED(input_offset); const float16x8x3_t vtop = { { vld1q_f16(in_top), vld1q_f16(in_top + dilation_x), vld1q_f16(in_top + 2 * dilation_x) } }; const float16x8x3_t vmid = { { vld1q_f16(in_mid), vld1q_f16(in_mid + dilation_x), vld1q_f16(in_mid + 2 * dilation_x) } }; const float16x8x3_t vlow = { { vld1q_f16(in_low), vld1q_f16(in_low + dilation_x), vld1q_f16(in_low + 2 * dilation_x) } }; float16x8_t out = vmulq_f16(vtop.val[0], m0.val[0]); out = vaddq_f16(out, vmulq_f16(vtop.val[1], m0.val[1])); out = vaddq_f16(out, vmulq_f16(vtop.val[2], m0.val[2])); out = vaddq_f16(out, vmulq_f16(vmid.val[0], m1.val[0])); out = vaddq_f16(out, vmulq_f16(vmid.val[1], m1.val[1])); out = vaddq_f16(out, vmulq_f16(vmid.val[2], m1.val[2])); out = vaddq_f16(out, vmulq_f16(vlow.val[0], m2.val[0])); out = vaddq_f16(out, vmulq_f16(vlow.val[1], m2.val[1])); out = vaddq_f16(out, vmulq_f16(vlow.val[2], m2.val[2])); return out; } /** Perform a 3x3 convolution for 16 consecutive elements on float16 when dilation.x() or dilation.y() is not 1. * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] dilation_x Dilation, in elements across x. * @param[in] stridex Stride value in elements across x. * @param[in] input_offset (Optional) Input quantization offset. * */ inline float16x8x2_t convolve_3x3_dilation(const float16_t *in_top, const float16_t *in_mid, const float16_t *in_low, const float16x8x3_t &m0, const float16x8x3_t &m1, const float16x8x3_t &m2, const size_t dilation_x, unsigned int stridex, int input_offset = 0) { float16x8x2_t out = { { single_convolve_3x3_dilation(in_top, in_mid, in_low, m0, m1, m2, dilation_x, input_offset), single_convolve_3x3_dilation(in_top + 8, in_mid + 8, in_low + 8, m0, m1, m2, dilation_x, input_offset) } }; if(stridex == 2) { out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[0], 2), out.val[0], 1); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[0], 4), out.val[0], 2); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[0], 6), out.val[0], 3); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[1], 0), out.val[0], 4); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[1], 2), out.val[0], 5); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[1], 4), out.val[0], 6); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[1], 6), out.val[0], 7); } else if(stridex == 3) { out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[0], 3), out.val[0], 1); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[0], 6), out.val[0], 2); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[1], 1), out.val[0], 3); } return out; } /** Perform a convolve3x3 on float16. * * @param[in] in_top Pointer to the first row of the input. * @param[in] in_mid Pointer to the second row of the input. * @param[in] in_low Pointer to the third row of the input. * @param[out] out_ptr Pointer to the output. * @param[in] m0 First row of the filter. * @param[in] m1 Second row of the filter. * @param[in] m2 Third row of the filter. * @param[in] stridex Stride value in elements across x. * @param[in] input_offset (Optional) Input quantization offset. * */ template <bool accumulate> inline void convolve_3x3(const float16_t *in_top, const float16_t *in_mid, const float16_t *in_low, float16_t *out_ptr, const float16x8x3_t &m0, const float16x8x3_t &m1, const float16x8x3_t &m2, unsigned int stridex, int input_offset = 0) { ARM_COMPUTE_UNUSED(input_offset); float16x8x2_t out = { { vdupq_n_f16(0), vdupq_n_f16(0) } }; if(stridex == 2) { const float16x8x2_t vtop = vld2q_f16(in_top); const float16x8x2_t vmid = vld2q_f16(in_mid); const float16x8x2_t vlow = vld2q_f16(in_low); const float16x8_t vtop_end = vld1q_f16(in_top + 16); const float16x8_t vmid_end = vld1q_f16(in_mid + 16); const float16x8_t vlow_end = vld1q_f16(in_low + 16); out.val[0] = vmulq_f16(vtop.val[0], m0.val[0]); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vtop.val[1], m0.val[1])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vtop.val[0], vtop_end, 1), m0.val[2])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vmid.val[0], m1.val[0])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vmid.val[1], m1.val[1])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vmid.val[0], vmid_end, 1), m1.val[2])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vlow.val[0], m2.val[0])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vlow.val[1], m2.val[1])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vlow.val[0], vlow_end, 1), m2.val[2])); accumulate ? accumulate_results<2>(out_ptr, out) : store_results<2>(out_ptr, out); } else { const float16x8x3_t vtop = { { vld1q_f16(in_top), vld1q_f16(in_top + 8), vld1q_f16(in_top + 16) } }; const float16x8x3_t vmid = { { vld1q_f16(in_mid), vld1q_f16(in_mid + 8), vld1q_f16(in_mid + 16) } }; const float16x8x3_t vlow = { { vld1q_f16(in_low), vld1q_f16(in_low + 8), vld1q_f16(in_low + 16) } }; out.val[0] = vmulq_f16(vtop.val[0], m0.val[0]); out.val[1] = vmulq_f16(vtop.val[1], m0.val[0]); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vtop.val[0], vtop.val[1], 1), m0.val[1])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vtop.val[0], vtop.val[1], 2), m0.val[2])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vmid.val[0], m1.val[0])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vmid.val[0], vmid.val[1], 1), m1.val[1])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vmid.val[0], vmid.val[1], 2), m1.val[2])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vlow.val[0], m2.val[0])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vlow.val[0], vlow.val[1], 1), m2.val[1])); out.val[0] = vaddq_f16(out.val[0], vmulq_f16(vextq_f16(vlow.val[0], vlow.val[1], 2), m2.val[2])); out.val[1] = vaddq_f16(out.val[1], vmulq_f16(vextq_f16(vtop.val[1], vtop.val[2], 1), m0.val[1])); out.val[1] = vaddq_f16(out.val[1], vmulq_f16(vextq_f16(vtop.val[1], vtop.val[2], 2), m0.val[2])); out.val[1] = vaddq_f16(out.val[1], vmulq_f16(vmid.val[1], m1.val[0])); out.val[1] = vaddq_f16(out.val[1], vmulq_f16(vextq_f16(vmid.val[1], vmid.val[2], 1), m1.val[1])); out.val[1] = vaddq_f16(out.val[1], vmulq_f16(vextq_f16(vmid.val[1], vmid.val[2], 2), m1.val[2])); out.val[1] = vaddq_f16(out.val[1], vmulq_f16(vlow.val[1], m2.val[0])); out.val[1] = vaddq_f16(out.val[1], vmulq_f16(vextq_f16(vlow.val[1], vlow.val[2], 1), m2.val[1])); out.val[1] = vaddq_f16(out.val[1], vmulq_f16(vextq_f16(vlow.val[1], vlow.val[2], 2), m2.val[2])); if(stridex == 3) { out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[0], 3), out.val[0], 1); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[0], 6), out.val[0], 2); out.val[0] = vsetq_lane_f16(vgetq_lane_f16(out.val[1], 1), out.val[0], 3); accumulate ? accumulate_results<3>(out_ptr, out) : store_results<3>(out_ptr, out); } else { accumulate ? accumulate_results<1>(out_ptr, out) : store_results<1>(out_ptr, out); } } } #endif /** __ARM_FEATURE_FP16_VECTOR_ARITHMETIC **/ /** Get the number of elements processed on 3x3 convolution. * * @param[in] num_elems_written_per_iteration Number of elements written per iteration on 3x3 convolution. * @param[in] stridex Stride value in elements across x. * * @return The number of elements processed. */ inline int get_input_num_elems_processed(unsigned int num_elems_written_per_iteration, unsigned int stridex) { switch(stridex) { case 1: return num_elems_written_per_iteration; case 2: return num_elems_written_per_iteration << 1; case 3: return num_elems_written_per_iteration * 3; default: ARM_COMPUTE_ERROR("stridex not supported"); return 0; } } } } // namespace arm_compute #endif /* ARM_COMPUTE_NEDIRECTCONVOLUTIONDETAIL_H */
19,547
335
{ "word": "Sabotage", "definitions": [ "to damage or destroy equipment, weapons, or buildings in order to prevent the success of an enemy or competitor", "to intentionally prevent the success of a plan or action" ], "parts-of-speech": "Verb" }
96
6,717
<filename>tools/AppInsights/src/core/contracts/Internal.cpp<gh_stars>1000+ #include "Internal.h" using namespace ApplicationInsights::core; Internal::Internal() { } Internal::~Internal() { } void Internal::Serialize(Serializer& serializer) const { if (m_sdkVersion.HasValue()) { serializer.WritePropertyName(L"ai.internal.sdkVersion"); serializer.WriteStringValue(m_sdkVersion.GetValue()); } if (m_agentVersion.HasValue()) { serializer.WritePropertyName(L"ai.internal.agentVersion"); serializer.WriteStringValue(m_agentVersion.GetValue()); } }
235
679
/************************************************************** * * 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. * *************************************************************/ #ifndef CONNECTIVITY_PREDICATEINPUT_HXX #define CONNECTIVITY_PREDICATEINPUT_HXX #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/sdbc/XConnection.hpp> #include <com/sun/star/util/XNumberFormatter.hpp> #include <com/sun/star/i18n/XLocaleData.hpp> #include <connectivity/sqlparse.hxx> #include "connectivity/dbtoolsdllapi.hxx" //......................................................................... namespace dbtools { //......................................................................... //===================================================================== //= OPredicateInputController //===================================================================== /** A class which allows input of an SQL predicate for a row set column into a edit field. */ class OOO_DLLPUBLIC_DBTOOLS OPredicateInputController { private: ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB; ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection; ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XLocaleData > m_xLocaleData; ::connectivity::OSQLParser m_aParser; public: OPredicateInputController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const ::connectivity::IParseContext* _pParseContext = NULL ); /** transforms a "raw" predicate value (usually obtained from a user input) into a valid predicate for the given column @param _rPredicateValue The text to normalize. @param _rxField The field for which the text should be a predicate value. @param _pErrorMessage If not <NULL/>, and a parsing error occurs, the error message will be copied to the string the argument points to. */ sal_Bool normalizePredicateString( ::rtl::OUString& _rPredicateValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxField, ::rtl::OUString* _pErrorMessage = NULL ) const; /** get's a value of the predicate which can be used in a WHERE clause. @param _rPredicateValue the value which has been normalized using normalizePredicateString @param _rxField is the field for which a predicate is to be entered @param _bForStatementUse If <TRUE/>, the returned value can be used in an SQL statement. If <FALSE/>, it can be used for instance for setting parameter values. @param _pErrorMessage If not <NULL/>, and a parsing error occurs, the error message will be copied to the string the argument points to. @see normalizePredicateString */ ::rtl::OUString getPredicateValue( const ::rtl::OUString& _rPredicateValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & _rxField, sal_Bool _bForStatementUse, ::rtl::OUString* _pErrorMessage = NULL ) const; ::rtl::OUString getPredicateValue( const ::rtl::OUString& _sField , const ::rtl::OUString& _rPredicateValue , sal_Bool _bForStatementUse , ::rtl::OUString* _pErrorMessage = NULL) const; private: ::connectivity::OSQLParseNode* implPredicateTree( ::rtl::OUString& _rErrorMessage, const ::rtl::OUString& _rStatement, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > & _rxField ) const; sal_Bool getSeparatorChars( const ::com::sun::star::lang::Locale& _rLocale, sal_Unicode& _rDecSep, sal_Unicode& _rThdSep ) const; ::rtl::OUString implParseNode(::connectivity::OSQLParseNode* pParseNode,sal_Bool _bForStatementUse) const; }; //......................................................................... } // namespace dbtools //......................................................................... #endif // CONNECTIVITY_PREDICATEINPUT_HXX
1,610
1,367
<filename>app/controller/render.py<gh_stars>1000+ import json from django.http import HttpResponse def render_json(dictionary=None): dictionary = {} if dictionary is None else dictionary response = HttpResponse(json.dumps(dictionary), content_type="application/json") response['Access-Control-Allow-Origin'] = '*' response["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type" response["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS" return response
162
3,651
package com.orientechnologies.orient.client.remote.message; import com.orientechnologies.orient.client.binary.OBinaryRequestExecutor; import com.orientechnologies.orient.client.remote.OBinaryRequest; import com.orientechnologies.orient.client.remote.OBinaryResponse; import com.orientechnologies.orient.client.remote.OStorageRemoteSession; import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; import com.orientechnologies.orient.enterprise.channel.binary.OChannelDataInput; import com.orientechnologies.orient.enterprise.channel.binary.OChannelDataOutput; import java.io.IOException; /** Created by tglman on 19/06/17. */ public class OUnsubscribeLiveQueryRequest implements OBinaryRequest<OUnsubscribLiveQueryResponse> { private int monitorId; public OUnsubscribeLiveQueryRequest() {} public OUnsubscribeLiveQueryRequest(int monitorId) { this.monitorId = monitorId; } @Override public void write(OChannelDataOutput network, OStorageRemoteSession session) throws IOException { network.writeInt(monitorId); } @Override public void read(OChannelDataInput channel, int protocolVersion, ORecordSerializer serializer) throws IOException { monitorId = channel.readInt(); } @Override public byte getCommand() { return OChannelBinaryProtocol.UNSUBSCRIBE_PUSH_LIVE_QUERY; } @Override public OUnsubscribLiveQueryResponse createResponse() { return new OUnsubscribLiveQueryResponse(); } @Override public OBinaryResponse execute(OBinaryRequestExecutor executor) { return executor.executeUnsubscribeLiveQuery(this); } public int getMonitorId() { return monitorId; } @Override public String getDescription() { return "unsubscribe from live query"; } }
557
2,322
<gh_stars>1000+ /* Wine Vulkan ICD implementation * * Copyright 2017 <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include "vulkan_loader.h" #include "winreg.h" #include "ntuser.h" #include "initguid.h" #include "devguid.h" #include "setupapi.h" WINE_DEFAULT_DEBUG_CHANNEL(vulkan); /* For now default to 4 as it felt like a reasonable version feature wise to support. * Version 5 adds more extensive version checks. Something to tackle later. */ #define WINE_VULKAN_ICD_VERSION 4 DEFINE_DEVPROPKEY(DEVPROPKEY_GPU_LUID, 0x60b193cb, 0x5276, 0x4d0f, 0x96, 0xfc, 0xf1, 0x73, 0xab, 0xad, 0x3e, 0xc6, 2); DEFINE_DEVPROPKEY(WINE_DEVPROPKEY_GPU_VULKAN_UUID, 0x233a9ef3, 0xafc4, 0x4abd, 0xb5, 0x64, 0xc3, 0x2f, 0x21, 0xf1, 0x53, 0x5c, 2); const struct unix_funcs *unix_funcs; unixlib_handle_t unix_handle; static HINSTANCE hinstance; static void *wine_vk_get_global_proc_addr(const char *name); #define wine_vk_find_struct(s, t) wine_vk_find_struct_((void *)s, VK_STRUCTURE_TYPE_##t) static void *wine_vk_find_struct_(void *s, VkStructureType t) { VkBaseOutStructure *header; for (header = s; header; header = header->pNext) { if (header->sType == t) return header; } return NULL; } VkResult WINAPI vkEnumerateInstanceLayerProperties(uint32_t *count, VkLayerProperties *properties) { TRACE("%p, %p\n", count, properties); *count = 0; return VK_SUCCESS; } static const struct vulkan_func vk_global_dispatch_table[] = { /* These functions must call wine_vk_init_once() before accessing vk_funcs. */ {"vkCreateInstance", &vkCreateInstance}, {"vkEnumerateInstanceExtensionProperties", &vkEnumerateInstanceExtensionProperties}, {"vkEnumerateInstanceLayerProperties", &vkEnumerateInstanceLayerProperties}, {"vkEnumerateInstanceVersion", &vkEnumerateInstanceVersion}, {"vkGetInstanceProcAddr", &vkGetInstanceProcAddr}, }; static void *wine_vk_get_global_proc_addr(const char *name) { unsigned int i; for (i = 0; i < ARRAY_SIZE(vk_global_dispatch_table); i++) { if (strcmp(name, vk_global_dispatch_table[i].name) == 0) { TRACE("Found name=%s in global table\n", debugstr_a(name)); return vk_global_dispatch_table[i].func; } } return NULL; } PFN_vkVoidFunction WINAPI vkGetInstanceProcAddr(VkInstance instance, const char *name) { void *func; TRACE("%p, %s\n", instance, debugstr_a(name)); if (!name) return NULL; /* vkGetInstanceProcAddr can load most Vulkan functions when an instance is passed in, however * for a NULL instance it can only load global functions. */ func = wine_vk_get_global_proc_addr(name); if (func) { return func; } if (!instance) { WARN("Global function %s not found.\n", debugstr_a(name)); return NULL; } if (!unix_funcs->p_is_available_instance_function(instance, name)) return NULL; func = wine_vk_get_instance_proc_addr(name); if (func) return func; func = wine_vk_get_phys_dev_proc_addr(name); if (func) return func; /* vkGetInstanceProcAddr also loads any children of instance, so device functions as well. */ func = wine_vk_get_device_proc_addr(name); if (func) return func; WARN("Unsupported device or instance function: %s.\n", debugstr_a(name)); return NULL; } PFN_vkVoidFunction WINAPI vkGetDeviceProcAddr(VkDevice device, const char *name) { void *func; TRACE("%p, %s\n", device, debugstr_a(name)); /* The spec leaves return value undefined for a NULL device, let's just return NULL. */ if (!device || !name) return NULL; /* Per the spec, we are only supposed to return device functions as in functions * for which the first parameter is vkDevice or a child of vkDevice like a * vkCommandBuffer or vkQueue. * Loader takes care of filtering of extensions which are enabled or not. */ if (unix_funcs->p_is_available_device_function(device, name)) { func = wine_vk_get_device_proc_addr(name); if (func) return func; } /* vkGetDeviceProcAddr was intended for loading device and subdevice functions. * idTech 6 titles such as Doom and Wolfenstein II, however use it also for * loading of instance functions. This is undefined behavior as the specification * disallows using any of the returned function pointers outside of device / * subdevice objects. The games don't actually use the function pointers and if they * did, they would crash as VkInstance / VkPhysicalDevice parameters need unwrapping. * Khronos clarified behavior in the Vulkan spec and expects drivers to get updated, * however it would require both driver and game fixes. * https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/issues/2323 * https://github.com/KhronosGroup/Vulkan-Docs/issues/655 */ if (((struct wine_vk_device_base *)device)->quirks & WINEVULKAN_QUIRK_GET_DEVICE_PROC_ADDR && ((func = wine_vk_get_instance_proc_addr(name)) || (func = wine_vk_get_phys_dev_proc_addr(name)))) { WARN("Returning instance function %s.\n", debugstr_a(name)); return func; } WARN("Unsupported device function: %s.\n", debugstr_a(name)); return NULL; } void * WINAPI vk_icdGetPhysicalDeviceProcAddr(VkInstance instance, const char *name) { TRACE("%p, %s\n", instance, debugstr_a(name)); if (!unix_funcs->p_is_available_instance_function(instance, name)) return NULL; return wine_vk_get_phys_dev_proc_addr(name); } void * WINAPI vk_icdGetInstanceProcAddr(VkInstance instance, const char *name) { TRACE("%p, %s\n", instance, debugstr_a(name)); /* Initial version of the Vulkan ICD spec required vkGetInstanceProcAddr to be * exported. vk_icdGetInstanceProcAddr was added later to separate ICD calls from * Vulkan API. One of them in our case should forward to the other, so just forward * to the older vkGetInstanceProcAddr. */ return vkGetInstanceProcAddr(instance, name); } VkResult WINAPI vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *supported_version) { uint32_t req_version; TRACE("%p\n", supported_version); /* The spec is not clear how to handle this. Mesa drivers don't check, but it * is probably best to not explode. VK_INCOMPLETE seems to be the closest value. */ if (!supported_version) return VK_INCOMPLETE; req_version = *supported_version; *supported_version = min(req_version, WINE_VULKAN_ICD_VERSION); TRACE("Loader requested ICD version %u, returning %u\n", req_version, *supported_version); return VK_SUCCESS; } static BOOL WINAPI wine_vk_init(INIT_ONCE *once, void *param, void **context) { const void *driver; driver = __wine_get_vulkan_driver(WINE_VULKAN_DRIVER_VERSION); if (!driver) { ERR("Failed to load Wine graphics driver supporting Vulkan.\n"); return FALSE; } if (NtQueryVirtualMemory(GetCurrentProcess(), hinstance, MemoryWineUnixFuncs, &unix_handle, sizeof(unix_handle), NULL)) return FALSE; if (vk_unix_call(unix_init, &driver) || !driver) return FALSE; unix_funcs = driver; return TRUE; } static BOOL wine_vk_init_once(void) { static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT; return InitOnceExecuteOnce(&init_once, wine_vk_init, NULL, NULL); } VkResult WINAPI vkCreateInstance(const VkInstanceCreateInfo *create_info, const VkAllocationCallbacks *allocator, VkInstance *instance) { struct vkCreateInstance_params params; TRACE("create_info %p, allocator %p, instance %p\n", create_info, allocator, instance); if(!wine_vk_init_once()) return VK_ERROR_INITIALIZATION_FAILED; params.pCreateInfo = create_info; params.pAllocator = allocator; params.pInstance = instance; return unix_funcs->p_vk_call(unix_vkCreateInstance, &params); } VkResult WINAPI vkEnumerateInstanceExtensionProperties(const char *layer_name, uint32_t *count, VkExtensionProperties *properties) { struct vkEnumerateInstanceExtensionProperties_params params; TRACE("%p, %p, %p\n", layer_name, count, properties); if (layer_name) { WARN("Layer enumeration not supported from ICD.\n"); return VK_ERROR_LAYER_NOT_PRESENT; } if (!wine_vk_init_once()) { *count = 0; return VK_SUCCESS; } params.pLayerName = layer_name; params.pPropertyCount = count; params.pProperties = properties; return unix_funcs->p_vk_call(unix_vkEnumerateInstanceExtensionProperties, &params); } VkResult WINAPI vkEnumerateInstanceVersion(uint32_t *version) { struct vkEnumerateInstanceVersion_params params; TRACE("%p\n", version); if (!wine_vk_init_once()) { *version = VK_API_VERSION_1_0; return VK_SUCCESS; } params.pApiVersion = version; return unix_funcs->p_vk_call(unix_vkEnumerateInstanceVersion, &params); } static HANDLE get_display_device_init_mutex(void) { HANDLE mutex = CreateMutexW(NULL, FALSE, L"display_device_init"); WaitForSingleObject(mutex, INFINITE); return mutex; } static void release_display_device_init_mutex(HANDLE mutex) { ReleaseMutex(mutex); CloseHandle(mutex); } /* Wait until graphics driver is loaded by explorer */ static void wait_graphics_driver_ready(void) { static BOOL ready = FALSE; if (!ready) { SendMessageW(GetDesktopWindow(), WM_NULL, 0, 0); ready = TRUE; } } static void fill_luid_property(VkPhysicalDeviceProperties2 *properties2) { VkPhysicalDeviceIDProperties *id; SP_DEVINFO_DATA device_data; DWORD type, device_idx = 0; HDEVINFO devinfo; HANDLE mutex; GUID uuid; LUID luid; if (!(id = wine_vk_find_struct(properties2, PHYSICAL_DEVICE_ID_PROPERTIES))) return; wait_graphics_driver_ready(); mutex = get_display_device_init_mutex(); devinfo = SetupDiGetClassDevsW(&GUID_DEVCLASS_DISPLAY, L"PCI", NULL, 0); device_data.cbSize = sizeof(device_data); while (SetupDiEnumDeviceInfo(devinfo, device_idx++, &device_data)) { if (!SetupDiGetDevicePropertyW(devinfo, &device_data, &WINE_DEVPROPKEY_GPU_VULKAN_UUID, &type, (BYTE *)&uuid, sizeof(uuid), NULL, 0)) continue; if (!IsEqualGUID(&uuid, id->deviceUUID)) continue; if (SetupDiGetDevicePropertyW(devinfo, &device_data, &DEVPROPKEY_GPU_LUID, &type, (BYTE *)&luid, sizeof(luid), NULL, 0)) { memcpy(&id->deviceLUID, &luid, sizeof(id->deviceLUID)); id->deviceLUIDValid = VK_TRUE; id->deviceNodeMask = 1; break; } } SetupDiDestroyDeviceInfoList(devinfo); release_display_device_init_mutex(mutex); TRACE("deviceName:%s deviceLUIDValid:%d LUID:%08x:%08x deviceNodeMask:%#x.\n", properties2->properties.deviceName, id->deviceLUIDValid, luid.HighPart, luid.LowPart, id->deviceNodeMask); } void WINAPI vkGetPhysicalDeviceProperties2(VkPhysicalDevice phys_dev, VkPhysicalDeviceProperties2 *properties2) { struct vkGetPhysicalDeviceProperties2_params params; TRACE("%p, %p\n", phys_dev, properties2); params.physicalDevice = phys_dev; params.pProperties = properties2; vk_unix_call(unix_vkGetPhysicalDeviceProperties2, &params); fill_luid_property(properties2); } void WINAPI vkGetPhysicalDeviceProperties2KHR(VkPhysicalDevice phys_dev, VkPhysicalDeviceProperties2 *properties2) { struct vkGetPhysicalDeviceProperties2KHR_params params; TRACE("%p, %p\n", phys_dev, properties2); params.physicalDevice = phys_dev; params.pProperties = properties2; vk_unix_call(unix_vkGetPhysicalDeviceProperties2KHR, &params); fill_luid_property(properties2); } static BOOL WINAPI call_vulkan_debug_report_callback( struct wine_vk_debug_report_params *params, ULONG size ) { return params->user_callback(params->flags, params->object_type, params->object_handle, params->location, params->code, params->layer_prefix, params->message, params->user_data); } static BOOL WINAPI call_vulkan_debug_utils_callback( struct wine_vk_debug_utils_params *params, ULONG size ) { return params->user_callback(params->severity, params->message_types, &params->data, params->user_data); } BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, void *reserved) { void **kernel_callback_table; TRACE("%p, %u, %p\n", hinst, reason, reserved); switch (reason) { case DLL_PROCESS_ATTACH: hinstance = hinst; DisableThreadLibraryCalls(hinst); kernel_callback_table = NtCurrentTeb()->Peb->KernelCallbackTable; kernel_callback_table[NtUserCallVulkanDebugReportCallback] = call_vulkan_debug_report_callback; kernel_callback_table[NtUserCallVulkanDebugUtilsCallback] = call_vulkan_debug_utils_callback; break; } return TRUE; } static const WCHAR winevulkan_json_pathW[] = L"\\winevulkan.json"; static const WCHAR vulkan_driversW[] = L"Software\\Khronos\\Vulkan\\Drivers"; HRESULT WINAPI DllRegisterServer(void) { WCHAR json_path[MAX_PATH]; HRSRC rsrc; const char *data; DWORD datalen, written, zero = 0; HANDLE file; HKEY key; /* Create the JSON manifest and registry key to register this ICD with the official Vulkan loader. */ TRACE("\n"); rsrc = FindResourceW(hinstance, L"winevulkan_json", (const WCHAR *)RT_RCDATA); data = LockResource(LoadResource(hinstance, rsrc)); datalen = SizeofResource(hinstance, rsrc); GetSystemDirectoryW(json_path, ARRAY_SIZE(json_path)); lstrcatW(json_path, winevulkan_json_pathW); file = CreateFileW(json_path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) { ERR("Unable to create JSON manifest.\n"); return E_UNEXPECTED; } WriteFile(file, data, datalen, &written, NULL); CloseHandle(file); if (!RegCreateKeyExW(HKEY_LOCAL_MACHINE, vulkan_driversW, 0, NULL, 0, KEY_SET_VALUE, NULL, &key, NULL)) { RegSetValueExW(key, json_path, 0, REG_DWORD, (const BYTE *)&zero, sizeof(zero)); RegCloseKey(key); } return S_OK; } HRESULT WINAPI DllUnregisterServer(void) { WCHAR json_path[MAX_PATH]; HKEY key; /* Remove the JSON manifest and registry key */ TRACE("\n"); GetSystemDirectoryW(json_path, ARRAY_SIZE(json_path)); lstrcatW(json_path, winevulkan_json_pathW); DeleteFileW(json_path); if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, vulkan_driversW, 0, KEY_SET_VALUE, &key) == ERROR_SUCCESS) { RegDeleteValueW(key, json_path); RegCloseKey(key); } return S_OK; }
6,257
971
<gh_stars>100-1000 #include "optimizer/statistics/value_condition.h" #include <memory> #include <string> #include <utility> #include "catalog/catalog_defs.h" #include "execution/sql/value.h" #include "gtest/gtest.h" #include "parser/expression/constant_value_expression.h" namespace noisepage::optimizer { // NOLINTNEXTLINE TEST(ValueConditionTests, GetColumnIDTest) { auto val = std::make_unique<parser::ConstantValueExpression>(execution::sql::SqlTypeId::Integer, execution::sql::Integer(1)); ValueCondition v(catalog::col_oid_t(1), "", parser::ExpressionType::INVALID, std::move(val)); EXPECT_EQ(catalog::col_oid_t(1), v.GetColumnID()); } // NOLINTNEXTLINE TEST(ValueConditionTests, GetColumnNameTest) { auto val = std::make_unique<parser::ConstantValueExpression>(execution::sql::SqlTypeId::Integer, execution::sql::Integer(1)); ValueCondition v(catalog::col_oid_t(1), "", parser::ExpressionType::INVALID, std::move(val)); EXPECT_EQ("", v.GetColumnName()); } // NOLINTNEXTLINE TEST(ValueConditionTests, GetTypeTest) { auto val = std::make_unique<parser::ConstantValueExpression>(execution::sql::SqlTypeId::Integer, execution::sql::Integer(1)); ValueCondition v(catalog::col_oid_t(1), "", parser::ExpressionType::INVALID, std::move(val)); EXPECT_EQ(parser::ExpressionType::INVALID, v.GetType()); } // NOLINTNEXTLINE TEST(ValueConditionTests, GetPointerToValueTest) { auto val = std::make_unique<parser::ConstantValueExpression>(execution::sql::SqlTypeId::Integer, execution::sql::Integer(1)); ValueCondition v(catalog::col_oid_t(1), "", parser::ExpressionType::INVALID, std::move(val)); EXPECT_EQ(parser::ConstantValueExpression(execution::sql::SqlTypeId::Integer, execution::sql::Integer(1)), *v.GetPointerToValue()); } } // namespace noisepage::optimizer
671
309
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- import math import vtk def main(): nx, ny, nz = get_program_parameters() colors = vtk.vtkNamedColors() angle = 0 r1 = 50 r2 = 30 centerX = 10.0 centerY = 5.0 points = vtk.vtkPoints() idx = 0 while angle <= 2.0 * vtk.vtkMath.Pi() + (vtk.vtkMath.Pi() / 60.0): points.InsertNextPoint(r1 * math.cos(angle) + centerX, r2 * math.sin(angle) + centerY, 0.0) angle = angle + (vtk.vtkMath.Pi() / 60.0) idx += 1 line = vtk.vtkPolyLine() line.GetPointIds().SetNumberOfIds(idx) for i in range(0, idx): line.GetPointIds().SetId(i, i) lines = vtk.vtkCellArray() lines.InsertNextCell(line) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetLines(lines) extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputData(polyData) extrude.SetExtrusionTypeToNormalExtrusion() extrude.SetVector(nx, ny, nz) extrude.Update() # Create an oriented arrow startPoint = [0.0] * 3 endPoint = [0.0] * 3 startPoint[0] = centerX startPoint[1] = centerY startPoint[2] = 0.0 endPoint[0] = startPoint[0] + extrude.GetVector()[0] endPoint[1] = startPoint[1] + extrude.GetVector()[1] endPoint[2] = startPoint[2] + extrude.GetVector()[2] # Compute a basis normalizedX = [0.0] * 3 normalizedY = [0.0] * 3 normalizedZ = [0.0] * 3 # The X axis is a vector from start to end vtk.vtkMath.Subtract(endPoint, startPoint, normalizedX) length = vtk.vtkMath.Norm(normalizedX) vtk.vtkMath.Normalize(normalizedX) # The Z axis is an arbitrary vector cross X arbitrary = [0.0] * 3 arbitrary[0] = vtk.vtkMath.Random(-10, 10) arbitrary[1] = vtk.vtkMath.Random(-10, 10) arbitrary[2] = vtk.vtkMath.Random(-10, 10) vtk.vtkMath.Cross(normalizedX, arbitrary, normalizedZ) vtk.vtkMath.Normalize(normalizedZ) # The Y axis is Z cross X vtk.vtkMath.Cross(normalizedZ, normalizedX, normalizedY) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(0, 3): matrix.SetElement(i, 0, normalizedX[i]) matrix.SetElement(i, 1, normalizedY[i]) matrix.SetElement(i, 2, normalizedZ[i]) # Apply the transforms transform = vtk.vtkTransform() transform.Translate(startPoint) transform.Concatenate(matrix) transform.Scale(length, length, length) arrowSource = vtk.vtkArrowSource() arrowSource.SetTipResolution(31) arrowSource.SetShaftResolution(21) # Transform the polydata transformPD = vtk.vtkTransformPolyDataFilter() transformPD.SetTransform(transform) transformPD.SetInputConnection(arrowSource.GetOutputPort()) # Create a mapper and actor for the arrow arrowMapper = vtk.vtkPolyDataMapper() arrowMapper.SetInputConnection(transformPD.GetOutputPort()) arrowActor = vtk.vtkActor() arrowActor.SetMapper(arrowMapper) arrowActor.GetProperty().SetColor(colors.GetColor3d("Tomato")) tubes = vtk.vtkTubeFilter() tubes.SetInputData(polyData) tubes.SetRadius(2.0) tubes.SetNumberOfSides(21) lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputConnection(tubes.GetOutputPort()) lineActor = vtk.vtkActor() lineActor.SetMapper(lineMapper) lineActor.GetProperty().SetColor(colors.GetColor3d("Peacock")) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(extrude.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d("Banana")) actor.GetProperty().SetOpacity(.7) ren = vtk.vtkRenderer() ren.SetBackground(colors.GetColor3d("SlateGray")) ren.AddActor(actor) ren.AddActor(lineActor) ren.AddActor(arrowActor) renWin = vtk.vtkRenderWindow() renWin.SetWindowName("Elliptical Cylinder Demo") renWin.AddRenderer(ren) renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) camera = vtk.vtkCamera() camera.SetPosition(0, 1, 0) camera.SetFocalPoint(0, 0, 0) camera.SetViewUp(0, 0, 1) camera.Azimuth(30) camera.Elevation(30) ren.SetActiveCamera(camera) ren.ResetCamera() ren.ResetCameraClippingRange() renWin.Render() iren.Start() def get_program_parameters(): import argparse description = 'Elliptical Cylinder Demo.' epilogue = ''' The example shows the vtkPolyLine that forms the base of the elliptical cylinder and an oriented arrow that represents the vector that vtkLinearExtrusionFilter uses to create the cylinder. The example takes an optional triple that defines the vector for the filter. The length of the vector is the height of the cylinder. ''' parser = argparse.ArgumentParser(description=description, epilog=epilogue, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-nx', nargs='?', const=0.0, default=0.0, type=float) parser.add_argument('-ny', nargs='?', const=0.0, default=0.0, type=float) parser.add_argument('-nz', nargs='?', const=100.0, default=100.0, type=float) args = parser.parse_args() return args.nx, args.ny, args.nz if __name__ == '__main__': main()
2,293
381
<filename>rpython/jit/backend/arm/test/test_virtualizable.py import py from rpython.jit.metainterp.test.test_virtualizable import ImplicitVirtualizableTests from rpython.jit.backend.arm.test.support import JitARMMixin class TestVirtualizable(JitARMMixin, ImplicitVirtualizableTests): def test_blackhole_should_not_reenter(self): py.test.skip("Assertion error & llinterp mess")
137
335
{ "word": "Fix", "definitions": [ "Fasten (something) securely in a particular place or position.", "Direct one's eyes, mind, or attention steadily or unwaveringly towards.", "(of a person's eyes, attention, or mind) be directed steadily or unwaveringly towards.", "Look at someone unwaveringly.", "Decide or settle on (a specific price, date, course of action, etc.)", "Arrange (something) on a permanent basis.", "Establish the exact location of (something) by using radar or visual bearings or astronomical observation.", "Settle the form of (a language).", "Assign or determine (a person's liability or responsibility) for legal purposes.", "Mend or repair.", "Put (a bad or unwelcome situation) right.", "Do the necessary work to improve or adapt something.", "Tidy or neaten (something, especially one's hair, clothes, or make-up)", "Make arrangements for (something); organize.", "Arrange for someone to have something; provide someone with something.", "Prepare or arrange for the provision of (food or drink)", "Be intending or planning to do something.", "Make (a dye, photographic image, or drawing) permanent.", "Preserve or stabilize (a specimen) with a chemical substance prior to microscopy or other examination.", "(of a plant or microorganism) assimilate (nitrogen or carbon dioxide) by forming a non-gaseous compound.", "Influence the outcome of (something, especially a race, match, or election) by illegal or underhand means.", "Take revenge on or punish (someone)", "Take an injection of a narcotic drug.", "Castrate or spay (an animal); neuter." ], "parts-of-speech": "Verb" }
588