max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
388
/////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2008-2012 <NAME> (Tonkikh) <<EMAIL>> // // See accompanying file COPYING.TXT file for licensing details. // /////////////////////////////////////////////////////////////////////////////// #define CPPCMS_SOURCE #include <cppcms/mount_point.h> #include <booster/regex.h> namespace cppcms { struct mount_point::_data {}; mount_point::mount_point() : group_(0), selection_(match_path_info) { } mount_point::mount_point(std::string const &path,int group) : path_info_(path), group_(group), selection_(match_path_info) { } mount_point::mount_point(std::string const &script) : script_name_(script), group_(0), selection_(match_path_info) { } mount_point::mount_point(std::string const &script,std::string const &path,int group) : script_name_(script), path_info_(path), group_(group), selection_(match_path_info) { } mount_point::mount_point(mount_point::selection_type sel,std::string const &selected,int group) : group_(group), selection_(sel) { if(sel == match_path_info) path_info_ = booster::regex(selected); else script_name_ = booster::regex(selected); } mount_point::mount_point(mount_point::selection_type sel,std::string const &non,std::string const &selected,int group) : group_(group), selection_(sel) { if(sel == match_path_info) { path_info_ = booster::regex(selected); script_name_ = booster::regex(non); } else { script_name_ = booster::regex(selected); path_info_ = booster::regex(non); } } mount_point::mount_point(mount_point::selection_type sel,std::string const &non) : group_(0), selection_(sel) { if(sel == match_path_info) { script_name_ = booster::regex(non); } else { path_info_ = booster::regex(non); } } mount_point::mount_point( selection_type sel, booster::regex const &http_host, booster::regex const &script, booster::regex const &path, int group) : host_(http_host), script_name_(script), path_info_(path), group_(group), selection_(sel) { } mount_point::~mount_point() { } mount_point::mount_point(mount_point const &other) : host_(other.host_), script_name_(other.script_name_), path_info_(other.path_info_), group_(other.group_), selection_(other.selection_) { } mount_point const &mount_point::operator=(mount_point const &other) { if(this!=&other) { host_ = other.host_; script_name_ = other.script_name_; path_info_ = other.path_info_; group_ = other.group_; selection_ = other.selection_; } return *this; } void mount_point::host(booster::regex const &h) { host_ = h; } void mount_point::script_name(booster::regex const &s) { script_name_ = s; } void mount_point::path_info(booster::regex const &p) { path_info_ = p; } void mount_point::group(int g) { group_ = g; } void mount_point::selection(mount_point::selection_type s) { selection_ = s; } booster::regex mount_point::host() const { return host_; } booster::regex mount_point::script_name() const { return script_name_; } booster::regex mount_point::path_info() const { return path_info_; } int mount_point::group() const { return group_; } mount_point::selection_type mount_point::selection() const { return selection_; } std::pair<bool,std::string> mount_point::match(std::string const &h,std::string const &s,std::string const &p) const { return match(h.c_str(),s.c_str(),p.c_str()); } std::pair<bool,std::string> mount_point::match(char const *h,char const *s,char const *p) const { std::pair<bool,std::string> res; res.first = false; if(!host_.empty() && !booster::regex_match(h,host_)) return res; if(selection_ == match_path_info) { if(!script_name_.empty() && !booster::regex_match(s,script_name_)) return res; if(path_info_.empty()) { res.second = p; res.first = true; return res; } if(group_ == 0) { if(!booster::regex_match(p,path_info_)) return res; res.second=p; res.first=true; return res; } else { booster::cmatch m; if(!booster::regex_match(p,m,path_info_)) return res; res.second=m[group_]; res.first = true; return res; } } else { if(!path_info_.empty() && !booster::regex_match(p,path_info_)) return res; if(script_name_.empty()) { res.second=s; res.first = true; return res; } if(group_ == 0) { if(!booster::regex_match(s,script_name_)) return res; res.second=s; res.first = true; return res; } else { booster::cmatch m; if(!booster::regex_match(s,m,script_name_)) return res; res.second=m[group_]; res.first = true; return res; } } } } // cppcms
2,031
1,056
<gh_stars>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.netbeans.modules.db.dataview.table; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import org.netbeans.modules.db.dataview.meta.DBColumn; import org.netbeans.modules.db.dataview.util.DBReadWriteHelper; import org.netbeans.modules.db.dataview.util.DataViewUtils; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; /** * @author <NAME> */ public class ResultSetTableModel extends AbstractTableModel { private boolean editable = false; private DBColumn[] columns; private final List<Object[]> data = new ArrayList<Object[]>(); private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); protected static Class<? extends Object> getTypeClass(DBColumn col) { int colType = col.getJdbcType(); if (colType == Types.BIT && col.getPrecision() <= 1) { colType = Types.BOOLEAN; } switch (colType) { case Types.BOOLEAN: return Boolean.class; case Types.TIME: return Time.class; case Types.DATE: return Date.class; case Types.TIMESTAMP: case DBReadWriteHelper.SQL_TYPE_ORACLE_TIMESTAMP: case DBReadWriteHelper.SQL_TYPE_ORACLE_TIMESTAMP_WITH_TZ: return Timestamp.class; case Types.BIGINT: return BigInteger.class; case Types.DOUBLE: return Double.class; case Types.FLOAT: case Types.REAL: return Float.class; case Types.DECIMAL: case Types.NUMERIC: return BigDecimal.class; case Types.INTEGER: case Types.SMALLINT: case Types.TINYINT: return Long.class; case Types.CHAR: case Types.VARCHAR: case Types.NCHAR: case Types.NVARCHAR: case Types.ROWID: return String.class; case Types.BIT: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: return Blob.class; case Types.LONGVARCHAR: case Types.LONGNVARCHAR: case Types.CLOB: case Types.NCLOB: /*NCLOB */ return Clob.class; case Types.OTHER: default: return Object.class; } } @SuppressWarnings("rawtypes") public ResultSetTableModel(DBColumn[] columns) { super(); this.columns = columns; } public void setColumns(DBColumn[] columns) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; this.data.clear(); this.columns = columns; fireTableStructureChanged(); } public DBColumn[] getColumns() { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; return Arrays.copyOf(columns, columns.length); } public void setEditable(boolean editable) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; boolean old = this.editable; this.editable = editable; pcs.firePropertyChange("editable", old, editable); } public boolean isEditable() { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; return editable; } @Override public boolean isCellEditable(int row, int column) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; if (!editable) { return false; } DBColumn col = this.columns[column]; return (!col.isGenerated()) && col.isEditable(); } @Override public void setValueAt(Object value, int row, int col) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; Object oldVal = getValueAt(row, col); if (noUpdateRequired(oldVal, value)) { return; } try { if (!DataViewUtils.isSQLConstantString(value, columns[col])) { value = DBReadWriteHelper.validate(value, columns[col]); } data.get(row)[col] = value; fireTableCellUpdated(row, col); } catch (Exception dbe) { NotifyDescriptor nd = new NotifyDescriptor.Message(dbe.getMessage(), NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } @Override @SuppressWarnings("unchecked") public Class<? extends Object> getColumnClass(int columnIndex) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; if (columns[columnIndex] == null) { return super.getColumnClass(columnIndex); } else { return getTypeClass(columns[columnIndex]); } } public DBColumn getColumn(int columnIndex) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; return columns[columnIndex]; } @Override public int getColumnCount() { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; return columns.length; } public String getColumnTooltip(int columnIndex) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; return DataViewUtils.getColumnToolTip(columns[columnIndex]); } @Override public String getColumnName(int columnIndex) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; String displayName = columns[columnIndex].getDisplayName(); return displayName != null ? displayName : "COL_" + columnIndex; } protected boolean noUpdateRequired(Object oldVal, Object value) { if (oldVal == null && value == null) { return true; } else if (oldVal != null) { return oldVal.equals(value); } return false; } @Override public int getRowCount() { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; return data.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; Object[] dataRow = data.get(rowIndex); return dataRow[columnIndex]; } public Object[] getRowData(int rowIndex) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; Object[] dataRow = data.get(rowIndex); return Arrays.copyOf(dataRow, dataRow.length); } public void setData(List<Object[]> data) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; this.data.clear(); for (Object[] dataRow : data) { this.data.add(Arrays.copyOf(dataRow, dataRow.length)); } fireTableDataChanged(); } public List<Object[]> getData() { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; ArrayList<Object[]> result = new ArrayList<Object[]>(); for (Object[] dataRow : this.data) { result.add(Arrays.copyOf(dataRow, dataRow.length)); } return result; } public void addRow(Object[] dataRow) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; int addedRowIndex = this.data.size(); this.data.add(Arrays.copyOf(dataRow, dataRow.length)); fireTableRowsInserted(addedRowIndex, addedRowIndex); } public void removeRow(int row) { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; this.data.remove(row); fireTableRowsDeleted(row, row); } public void clear() { assert SwingUtilities.isEventDispatchThread() : "Not on EDT"; this.data.clear(); fireTableDataChanged(); } public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.addPropertyChangeListener(propertyName, listener); } public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { pcs.removePropertyChangeListener(propertyName, listener); } }
3,944
323
<gh_stars>100-1000 import argparse import parsl from parsl.app.app import python_app from parsl.tests.configs.local_threads import config @python_app def get_num(first, second): return first + second def test_fibonacci(num=3): x1 = 0 x2 = 1 counter = 0 results = [] results.append(0) results.append(1) while counter < num - 2: counter += 1 results.append(get_num(x1, x2)) temp = x2 x2 = get_num(x1, x2) x1 = temp for i in range(len(results)): if isinstance(results[i], int): print(results[i]) else: print(results[i].result()) if __name__ == '__main__': parsl.clear() parsl.load(config) parser = argparse.ArgumentParser() parser.add_argument("-a", "--num", default="5", action="store", dest="a", type=int) args = parser.parse_args() test_fibonacci(args.a)
432
2,504
<gh_stars>1000+ //********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* // OpenCVHelper.h #pragma once #include <opencv2\core\core.hpp> #include <opencv2\imgproc\imgproc.hpp> #include <opencv2\video.hpp> namespace OpenCVBridge { public ref class OpenCVHelper sealed { public: OpenCVHelper(); // Image processing operators void Blur( Windows::Graphics::Imaging::SoftwareBitmap^ input, Windows::Graphics::Imaging::SoftwareBitmap^ output); void HoughLines( Windows::Graphics::Imaging::SoftwareBitmap^ input, Windows::Graphics::Imaging::SoftwareBitmap^ output); void Contours( Windows::Graphics::Imaging::SoftwareBitmap^ input, Windows::Graphics::Imaging::SoftwareBitmap^ output); void Histogram( Windows::Graphics::Imaging::SoftwareBitmap^ input, Windows::Graphics::Imaging::SoftwareBitmap^ output); void MotionDetector( Windows::Graphics::Imaging::SoftwareBitmap^ input, Windows::Graphics::Imaging::SoftwareBitmap^ output); private: // used only for the background subtraction operation cv::Mat fgMaskMOG2; cv::Ptr<cv::BackgroundSubtractor> pMOG2; // helper functions for getting a cv::Mat from SoftwareBitmap bool GetPointerToPixelData(Windows::Graphics::Imaging::SoftwareBitmap^ bitmap, unsigned char** pPixelData, unsigned int* capacity); bool TryConvert(Windows::Graphics::Imaging::SoftwareBitmap^ from, cv::Mat& convertedMat); }; }
785
674
<filename>libs/rison/__init__.py from decoder import loads from encoder import dumps
26
973
#ifndef OPENGL_GEN_CORE_REM1_3_HPP #define OPENGL_GEN_CORE_REM1_3_HPP #include "_int_load_test.hpp" namespace gl { enum { ADD_SIGNED = 0x8574, CLIENT_ACTIVE_TEXTURE = 0x84E1, COMBINE = 0x8570, COMBINE_ALPHA = 0x8572, COMBINE_RGB = 0x8571, COMPRESSED_ALPHA = 0x84E9, COMPRESSED_INTENSITY = 0x84EC, COMPRESSED_LUMINANCE = 0x84EA, COMPRESSED_LUMINANCE_ALPHA = 0x84EB, CONSTANT = 0x8576, DOT3_RGB = 0x86AE, DOT3_RGBA = 0x86AF, INTERPOLATE = 0x8575, MAX_TEXTURE_UNITS = 0x84E2, MULTISAMPLE_BIT = 0x20000000, NORMAL_MAP = 0x8511, OPERAND0_ALPHA = 0x8598, OPERAND0_RGB = 0x8590, OPERAND1_ALPHA = 0x8599, OPERAND1_RGB = 0x8591, OPERAND2_ALPHA = 0x859A, OPERAND2_RGB = 0x8592, PREVIOUS = 0x8578, REFLECTION_MAP = 0x8512, RGB_SCALE = 0x8573, SOURCE0_ALPHA = 0x8588, SOURCE0_RGB = 0x8580, SOURCE1_ALPHA = 0x8589, SOURCE1_RGB = 0x8581, SOURCE2_ALPHA = 0x858A, SOURCE2_RGB = 0x8582, SUBTRACT = 0x84E7, TRANSPOSE_COLOR_MATRIX = 0x84E6, TRANSPOSE_MODELVIEW_MATRIX = 0x84E3, TRANSPOSE_PROJECTION_MATRIX = 0x84E4, TRANSPOSE_TEXTURE_MATRIX = 0x84E5, }; namespace _detail { typedef void (CODEGEN_FUNCPTR * Proc_glClientActiveTexture)(GLenum texture); typedef void (CODEGEN_FUNCPTR * Proc_glLoadTransposeMatrixd)(const GLdouble * m); typedef void (CODEGEN_FUNCPTR * Proc_glLoadTransposeMatrixf)(const GLfloat * m); typedef void (CODEGEN_FUNCPTR * Proc_glMultTransposeMatrixd)(const GLdouble * m); typedef void (CODEGEN_FUNCPTR * Proc_glMultTransposeMatrixf)(const GLfloat * m); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord1d)(GLenum target, GLdouble s); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord1dv)(GLenum target, const GLdouble * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord1f)(GLenum target, GLfloat s); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord1fv)(GLenum target, const GLfloat * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord1i)(GLenum target, GLint s); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord1iv)(GLenum target, const GLint * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord1s)(GLenum target, GLshort s); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord1sv)(GLenum target, const GLshort * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord2d)(GLenum target, GLdouble s, GLdouble t); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord2dv)(GLenum target, const GLdouble * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord2f)(GLenum target, GLfloat s, GLfloat t); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord2fv)(GLenum target, const GLfloat * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord2i)(GLenum target, GLint s, GLint t); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord2iv)(GLenum target, const GLint * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord2s)(GLenum target, GLshort s, GLshort t); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord2sv)(GLenum target, const GLshort * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord3d)(GLenum target, GLdouble s, GLdouble t, GLdouble r); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord3dv)(GLenum target, const GLdouble * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord3f)(GLenum target, GLfloat s, GLfloat t, GLfloat r); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord3fv)(GLenum target, const GLfloat * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord3i)(GLenum target, GLint s, GLint t, GLint r); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord3iv)(GLenum target, const GLint * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord3s)(GLenum target, GLshort s, GLshort t, GLshort r); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord3sv)(GLenum target, const GLshort * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord4d)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord4dv)(GLenum target, const GLdouble * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord4f)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord4fv)(GLenum target, const GLfloat * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord4i)(GLenum target, GLint s, GLint t, GLint r, GLint q); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord4iv)(GLenum target, const GLint * v); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord4s)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); typedef void (CODEGEN_FUNCPTR * Proc_glMultiTexCoord4sv)(GLenum target, const GLshort * v); } extern _detail::Proc_glClientActiveTexture ClientActiveTexture; extern _detail::Proc_glLoadTransposeMatrixd LoadTransposeMatrixd; extern _detail::Proc_glLoadTransposeMatrixf LoadTransposeMatrixf; extern _detail::Proc_glMultTransposeMatrixd MultTransposeMatrixd; extern _detail::Proc_glMultTransposeMatrixf MultTransposeMatrixf; extern _detail::Proc_glMultiTexCoord1d MultiTexCoord1d; extern _detail::Proc_glMultiTexCoord1dv MultiTexCoord1dv; extern _detail::Proc_glMultiTexCoord1f MultiTexCoord1f; extern _detail::Proc_glMultiTexCoord1fv MultiTexCoord1fv; extern _detail::Proc_glMultiTexCoord1i MultiTexCoord1i; extern _detail::Proc_glMultiTexCoord1iv MultiTexCoord1iv; extern _detail::Proc_glMultiTexCoord1s MultiTexCoord1s; extern _detail::Proc_glMultiTexCoord1sv MultiTexCoord1sv; extern _detail::Proc_glMultiTexCoord2d MultiTexCoord2d; extern _detail::Proc_glMultiTexCoord2dv MultiTexCoord2dv; extern _detail::Proc_glMultiTexCoord2f MultiTexCoord2f; extern _detail::Proc_glMultiTexCoord2fv MultiTexCoord2fv; extern _detail::Proc_glMultiTexCoord2i MultiTexCoord2i; extern _detail::Proc_glMultiTexCoord2iv MultiTexCoord2iv; extern _detail::Proc_glMultiTexCoord2s MultiTexCoord2s; extern _detail::Proc_glMultiTexCoord2sv MultiTexCoord2sv; extern _detail::Proc_glMultiTexCoord3d MultiTexCoord3d; extern _detail::Proc_glMultiTexCoord3dv MultiTexCoord3dv; extern _detail::Proc_glMultiTexCoord3f MultiTexCoord3f; extern _detail::Proc_glMultiTexCoord3fv MultiTexCoord3fv; extern _detail::Proc_glMultiTexCoord3i MultiTexCoord3i; extern _detail::Proc_glMultiTexCoord3iv MultiTexCoord3iv; extern _detail::Proc_glMultiTexCoord3s MultiTexCoord3s; extern _detail::Proc_glMultiTexCoord3sv MultiTexCoord3sv; extern _detail::Proc_glMultiTexCoord4d MultiTexCoord4d; extern _detail::Proc_glMultiTexCoord4dv MultiTexCoord4dv; extern _detail::Proc_glMultiTexCoord4f MultiTexCoord4f; extern _detail::Proc_glMultiTexCoord4fv MultiTexCoord4fv; extern _detail::Proc_glMultiTexCoord4i MultiTexCoord4i; extern _detail::Proc_glMultiTexCoord4iv MultiTexCoord4iv; extern _detail::Proc_glMultiTexCoord4s MultiTexCoord4s; extern _detail::Proc_glMultiTexCoord4sv MultiTexCoord4sv; } #endif /*OPENGL_GEN_CORE_REM1_3_HPP*/
3,606
8,851
from django.core.exceptions import ValidationError from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from wagtail.core import blocks from wagtail.embeds.format import embed_to_frontend_html class EmbedValue: """ Native value of an EmbedBlock. Should, at minimum, have a 'url' property and render as the embed HTML when rendered in a template. NB We don't use a wagtailembeds.model.Embed object for this, because we want to be able to do {% embed value.url 500 %} without doing a redundant fetch of the embed at the default width. """ def __init__(self, url, max_width=None, max_height=None): self.url = url self.max_width = max_width self.max_height = max_height @cached_property def html(self): return embed_to_frontend_html(self.url, self.max_width, self.max_height) def __str__(self): return self.html class EmbedBlock(blocks.URLBlock): def get_default(self): # Allow specifying the default for an EmbedBlock as either an EmbedValue or a string (or None). if not self.meta.default: return None elif isinstance(self.meta.default, EmbedValue): return self.meta.default else: # assume default has been passed as a string return EmbedValue(self.meta.default, getattr(self.meta, 'max_width', None), getattr(self.meta, 'max_height', None)) def to_python(self, value): # The JSON representation of an EmbedBlock's value is a URL string; # this should be converted to an EmbedValue (or None). if not value: return None else: return EmbedValue(value, getattr(self.meta, 'max_width', None), getattr(self.meta, 'max_height', None)) def get_prep_value(self, value): # serialisable value should be a URL string if value is None: return '' else: return value.url def value_for_form(self, value): # the value to be handled by the URLField is a plain URL string (or the empty string) if value is None: return '' else: return value.url def value_from_form(self, value): # convert the value returned from the form (a URL string) to an EmbedValue (or None) if not value: return None else: return EmbedValue(value, getattr(self.meta, 'max_width', None), getattr(self.meta, 'max_height', None)) def clean(self, value): if isinstance(value, EmbedValue) and not value.html: raise ValidationError(_("Cannot find an embed for this URL.")) return super().clean(value) class Meta: icon = "media"
1,093
4,391
<reponame>sasano8/pyright # This sample tests that the type checker flags certain values # that cannot be deleted or assigned to. # This should generate an error True = 3 # This should generate an error False = 4 # This should generate an error None = True # This should generate an error __debug__ = 4 # This should generate an error del True # This should generate an error del None # This should generate an error -3 = 2 # This should generate an error [4] = [2] # This should generate an error [True] = [3] # This should generate an error (True) = 3 # This should generate an error del -3 # This should generate an error 3 + 4 = 2 # This should generate an error del 3 + 4 # This should generate an error del -(4) # This should generate an error del __debug__ # This should generate an error del {} # This should generate an error ... = 3 # This should generate an error del ... # This should generate an error (...) = 3 # This should generate an error del ...
292
1,093
import argparse import os import time import math import collections from tqdm import tqdm import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import numpy as np import pandas as pd from reparameterization import apply_weight_norm, remove_weight_norm from model import SentimentClassifier from configure_data import configure_data from arguments import add_general_args, add_model_args, add_classifier_model_args, add_run_classifier_args def get_data_and_args(): parser = argparse.ArgumentParser(description='PyTorch Sentiment Discovery Classification') parser = add_general_args(parser) parser = add_model_args(parser) parser = add_classifier_model_args(parser) data_config, data_parser, run_classifier_parser, parser = add_run_classifier_args(parser) args = parser.parse_args() args.cuda = torch.cuda.is_available() args.shuffle=False if args.seed is not -1: torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) (train_data, val_data, test_data), tokenizer = data_config.apply(args) args.data_size = tokenizer.num_tokens args.padding_idx = tokenizer.command_name_map['pad'].Id return (train_data, val_data, test_data), tokenizer, args def get_model(args): sd = None model_args = args if args.load is not None and args.load != '': sd = torch.load(args.load) if 'args' in sd: model_args = sd['args'] if 'sd' in sd: sd = sd['sd'] ntokens = model_args.data_size concat_pools = model_args.concat_max, model_args.concat_min, model_args.concat_mean if args.model == 'transformer': model = SentimentClassifier(model_args.model, ntokens, None, None, None, model_args.classifier_hidden_layers, model_args.classifier_dropout, None, concat_pools, False, model_args) else: model = SentimentClassifier(model_args.model, ntokens, model_args.emsize, model_args.nhid, model_args.nlayers, model_args.classifier_hidden_layers, model_args.classifier_dropout, model_args.all_layers, concat_pools, False, model_args) args.heads_per_class = model_args.heads_per_class args.use_softmax = model_args.use_softmax try: args.classes = list(model_args.classes) except: args.classes = [args.label_key] try: args.dual_thresh = model_args.dual_thresh and not model_args.joint_binary_train except: args.dual_thresh = False if args.cuda: model.cuda() if args.fp16: model.half() if sd is not None: try: model.load_state_dict(sd) except: # if state dict has weight normalized parameters apply and remove weight norm to model while loading sd if hasattr(model.lm_encoder, 'rnn'): apply_weight_norm(model.lm_encoder.rnn) else: apply_weight_norm(model.lm_encoder) model.lm_encoder.load_state_dict(sd) remove_weight_norm(model) if args.neurons > 0: print('WARNING. Setting neurons %s' % str(args.neurons)) model.set_neurons(args.neurons) return model # uses similar function as transform from transfer.py def classify(model, text, args): # Make sure to set *both* parts of the model to .eval() mode. model.lm_encoder.eval() model.classifier.eval() # Initialize data, append results stds = np.array([]) labels = np.array([]) label_probs = np.array([]) first_label = True heads_per_class = args.heads_per_class def get_batch(batch): text = batch['text'][0] timesteps = batch['length'] labels = batch['label'] text = Variable(text).long() timesteps = Variable(timesteps).long() labels = Variable(labels).long() if args.max_seq_len is not None: text = text[:, :args.max_seq_len] timesteps = torch.clamp(timesteps, max=args.max_seq_len) if args.cuda: text, timesteps, labels = text.cuda(), timesteps.cuda(), labels.cuda() return text.t(), labels, timesteps-1 def get_outs(text_batch, length_batch): if args.model.lower() == 'transformer': class_out, (lm_or_encoder_out, state) = model(text_batch, length_batch, args.get_hidden) else: model.lm_encoder.rnn.reset_hidden(args.batch_size) for _ in range(1 + args.num_hidden_warmup): class_out, (lm_or_encoder_out, state) = model(text_batch, length_batch, args.get_hidden) if args.use_softmax and args.heads_per_class == 1: class_out = F.softmax(class_out, -1) return class_out, (lm_or_encoder_out, state) tstart = start = time.time() n = 0 len_ds = len(text) with torch.no_grad(): for i, data in tqdm(enumerate(text), total=len(text)): text_batch, labels_batch, length_batch = get_batch(data) size = text_batch.size(1) n += size # get predicted probabilities given transposed text and lengths of text probs, _ = get_outs(text_batch, length_batch) # probs = model(text_batch, length_batch) if first_label: first_label = False labels = [] label_probs = [] if heads_per_class > 1: stds = [] # Save variances, and predictions # TODO: Handle multi-head [multiple classes out] if heads_per_class > 1: _, probs, std, preds = probs stds.append(std.data.cpu().numpy()) else: probs, preds = probs if args.use_softmax: probs = F.softmax(probs, -1) labels.append(preds.data.cpu().numpy()) label_probs.append(probs.data.cpu().numpy()) num_char = length_batch.sum().item() end = time.time() elapsed_time = end - start total_time = end - tstart start = end s_per_batch = total_time / (i+1) timeleft = (len_ds - (i+1)) * s_per_batch ch_per_s = float(num_char) / elapsed_time if not first_label: labels = (np.concatenate(labels)) #.flatten()) label_probs = (np.concatenate(label_probs)) #.flatten()) if heads_per_class > 1: stds = (np.concatenate(stds)) else: stds = np.zeros_like(labels) print('%0.3f seconds to transform %d examples' % (time.time() - tstart, n)) return labels, label_probs, stds def make_header(classes, heads_per_class=1, softmax=False, dual_thresh=False): header = [] if softmax: header.append('prediction') for cls in classes: if not softmax: header.append(cls + ' pred') header.append(cls + ' prob') if heads_per_class > 1: header.append(cls + ' std') if dual_thresh: header.append('neutral pred') header.append('neutral prob') return header def get_row(pred, prob, std, classes, heads_per_class=1, softmax=False, dual_thresh=False): row = [] if softmax: row.append(pred[0]) for i in range(len(classes)): if not softmax: row.append(pred[i]) row.append(prob[i]) if heads_per_class > 1: row.append(std[i]) if dual_thresh: row.append(pred[2]) row.append(prob[2]) return row def get_writer(preds, probs, stds, classes, heads_per_class=1, softmax=False, dual_thresh=False): header = make_header(classes, heads_per_class, softmax, dual_thresh) yield header for pred, prob, std in zip(preds, probs, stds): yield get_row(pred, prob, std, classes, heads_per_class, softmax, dual_thresh) def main(): (train_data, val_data, test_data), tokenizer, args = get_data_and_args() model = get_model(args) ypred, yprob, ystd = classify(model, train_data, args) save_root = '' save_root = os.path.join(save_root, args.save_probs) print('saving predicted probabilities to '+save_root) np.save(save_root, ypred) np.save(save_root+'.prob', yprob) np.save(save_root+'.std', ystd) if args.write_results is None or args.write_results == '': exit() print('writing results to '+args.write_results) writer = get_writer(ypred, yprob, ystd, args.classes, args.heads_per_class, args.use_softmax, args.dual_thresh) train_data.dataset.write(writer, path=args.write_results) if __name__ == '__main__': main()
4,223
980
<gh_stars>100-1000 package org.jcodec.codecs.vpx.vp8.data; import org.jcodec.codecs.vpx.vp8.CommonUtils; import org.jcodec.codecs.vpx.vp8.enums.MVReferenceFrame; import org.jcodec.codecs.vpx.vp8.pointerhelper.FullAccessIntArrPointer; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License. * * The class is a direct java port of libvpx's * (https://github.com/webmproject/libvpx) relevant VP8 code with significant * java oriented refactoring. * * @author The JCodec project * */ public class CodingContext { int kf_indicated; int frames_since_key; int frames_since_golden; short filter_level; int frames_till_gf_update_due; int[] recent_ref_frame_usage = new int[MVReferenceFrame.count]; MVContext[] mvc = new MVContext[2]; FullAccessIntArrPointer[] mvcosts = new FullAccessIntArrPointer[2]; FullAccessIntArrPointer ymode_prob = new FullAccessIntArrPointer(EntropyMode.vp8_ymode_prob.size()); FullAccessIntArrPointer uv_mode_prob = new FullAccessIntArrPointer( EntropyMode.vp8_uv_mode_prob.size()); /* interframe intra mode probs */ short[] kf_ymode_prob = new short[4], kf_uv_mode_prob = new short[3]; /* keyframe "" */ int[] ymode_count = new int[5], uv_mode_count = new int[4]; /* intra MB type cts this frame */ int[] count_mb_ref_frame_usage = new int[MVReferenceFrame.count]; int this_frame_percent_intra; int last_frame_percent_intra; public void vp8_save_coding_context(Compressor cpi) { /* * Stores a snapshot of key state variables which can subsequently be restored * with a call to vp8_restore_coding_context. These functions are intended for * use in a re-code loop in vp8_compress_frame where the quantizer value is * adjusted between loop iterations. */ frames_since_key = cpi.frames_since_key; filter_level = cpi.common.filter_level; frames_till_gf_update_due = cpi.frames_till_gf_update_due; frames_since_golden = cpi.frames_since_golden; mvc[0] = new MVContext(cpi.common.fc.mvc[0]); mvc[1] = new MVContext(cpi.common.fc.mvc[1]); mvcosts[0] = cpi.rd_costs.mvcosts[0].deepCopy(); mvcosts[1] = cpi.rd_costs.mvcosts[1].deepCopy(); CommonUtils.vp8_copy(cpi.common.fc.ymode_prob, ymode_prob); CommonUtils.vp8_copy(cpi.common.fc.uv_mode_prob, uv_mode_prob); CommonUtils.vp8_copy(cpi.mb.ymode_count, ymode_count); CommonUtils.vp8_copy(cpi.mb.uv_mode_count, uv_mode_count); /* Stats */ this_frame_percent_intra = cpi.this_frame_percent_intra; } public void vp8_restore_coding_context(Compressor cpi) { /* * Restore key state variables to the snapshot state stored in the previous call * to vp8_save_coding_context. */ cpi.frames_since_key = frames_since_key; cpi.common.filter_level = filter_level; cpi.frames_till_gf_update_due = frames_till_gf_update_due; cpi.frames_since_golden = frames_since_golden; cpi.common.fc.mvc[0] = new MVContext(mvc[0]); cpi.common.fc.mvc[1] = new MVContext(mvc[1]); cpi.rd_costs.mvcosts[0] = mvcosts[0].deepCopy(); cpi.rd_costs.mvcosts[1] = mvcosts[1].deepCopy(); CommonUtils.vp8_copy(ymode_prob, cpi.common.fc.ymode_prob); CommonUtils.vp8_copy(uv_mode_prob, cpi.common.fc.uv_mode_prob); CommonUtils.vp8_copy(ymode_count, cpi.mb.ymode_count); CommonUtils.vp8_copy(uv_mode_count, cpi.mb.uv_mode_count); /* Stats */ cpi.this_frame_percent_intra = this_frame_percent_intra; } }
1,644
1,909
<reponame>grmkris/XChange package org.knowm.xchange.kucoin.dto.response; import java.math.BigDecimal; import lombok.Data; @Data public class AllTickersTickerResponse { private String symbol; private BigDecimal high; private BigDecimal vol; private BigDecimal last; private BigDecimal low; private BigDecimal buy; private BigDecimal sell; private BigDecimal changePrice; private BigDecimal changeRate; private BigDecimal volValue; }
146
1,094
/*********************************************************************************************************************************** Azure Storage Read ***********************************************************************************************************************************/ #include "build.auto.h" #include "common/debug.h" #include "common/io/http/client.h" #include "common/log.h" #include "common/type/object.h" #include "storage/azure/read.h" #include "storage/read.intern.h" /*********************************************************************************************************************************** Object type ***********************************************************************************************************************************/ typedef struct StorageReadAzure { StorageReadInterface interface; // Interface StorageAzure *storage; // Storage that created this object HttpResponse *httpResponse; // HTTP response } StorageReadAzure; /*********************************************************************************************************************************** Macros for function logging ***********************************************************************************************************************************/ #define FUNCTION_LOG_STORAGE_READ_AZURE_TYPE \ StorageReadAzure * #define FUNCTION_LOG_STORAGE_READ_AZURE_FORMAT(value, buffer, bufferSize) \ objToLog(value, "StorageReadAzure", buffer, bufferSize) /*********************************************************************************************************************************** Open the file ***********************************************************************************************************************************/ static bool storageReadAzureOpen(THIS_VOID) { THIS(StorageReadAzure); FUNCTION_LOG_BEGIN(logLevelTrace); FUNCTION_LOG_PARAM(STORAGE_READ_AZURE, this); FUNCTION_LOG_END(); ASSERT(this != NULL); ASSERT(this->httpResponse == NULL); bool result = false; // Request the file MEM_CONTEXT_BEGIN(THIS_MEM_CONTEXT()) { this->httpResponse = storageAzureRequestP( this->storage, HTTP_VERB_GET_STR, .path = this->interface.name, .allowMissing = true, .contentIo = true); } MEM_CONTEXT_END(); if (httpResponseCodeOk(this->httpResponse)) { result = true; } // Else error unless ignore missing else if (!this->interface.ignoreMissing) THROW_FMT(FileMissingError, STORAGE_ERROR_READ_MISSING, strZ(this->interface.name)); FUNCTION_LOG_RETURN(BOOL, result); } /*********************************************************************************************************************************** Read from a file ***********************************************************************************************************************************/ static size_t storageReadAzure(THIS_VOID, Buffer *buffer, bool block) { THIS(StorageReadAzure); FUNCTION_LOG_BEGIN(logLevelTrace); FUNCTION_LOG_PARAM(STORAGE_READ_AZURE, this); FUNCTION_LOG_PARAM(BUFFER, buffer); FUNCTION_LOG_PARAM(BOOL, block); FUNCTION_LOG_END(); ASSERT(this != NULL && this->httpResponse != NULL); ASSERT(httpResponseIoRead(this->httpResponse) != NULL); ASSERT(buffer != NULL && !bufFull(buffer)); FUNCTION_LOG_RETURN(SIZE, ioRead(httpResponseIoRead(this->httpResponse), buffer)); } /*********************************************************************************************************************************** Has file reached EOF? ***********************************************************************************************************************************/ static bool storageReadAzureEof(THIS_VOID) { THIS(StorageReadAzure); FUNCTION_TEST_BEGIN(); FUNCTION_TEST_PARAM(STORAGE_READ_AZURE, this); FUNCTION_TEST_END(); ASSERT(this != NULL && this->httpResponse != NULL); ASSERT(httpResponseIoRead(this->httpResponse) != NULL); FUNCTION_TEST_RETURN(ioReadEof(httpResponseIoRead(this->httpResponse))); } /**********************************************************************************************************************************/ StorageRead * storageReadAzureNew(StorageAzure *storage, const String *name, bool ignoreMissing) { FUNCTION_LOG_BEGIN(logLevelTrace); FUNCTION_LOG_PARAM(STORAGE_AZURE, storage); FUNCTION_LOG_PARAM(STRING, name); FUNCTION_LOG_PARAM(BOOL, ignoreMissing); FUNCTION_LOG_END(); ASSERT(storage != NULL); ASSERT(name != NULL); StorageRead *this = NULL; OBJ_NEW_BEGIN(StorageReadAzure) { StorageReadAzure *driver = OBJ_NEW_ALLOC(); *driver = (StorageReadAzure) { .storage = storage, .interface = (StorageReadInterface) { .type = STORAGE_AZURE_TYPE, .name = strDup(name), .ignoreMissing = ignoreMissing, .ioInterface = (IoReadInterface) { .eof = storageReadAzureEof, .open = storageReadAzureOpen, .read = storageReadAzure, }, }, }; this = storageReadNew(driver, &driver->interface); } OBJ_NEW_END(); FUNCTION_LOG_RETURN(STORAGE_READ, this); }
1,927
432
<reponame>LiamChis/OpenmHealthClone /* * Copyright 2017 Open mHealth * * 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.openmhealth.shim.withings.mapper; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.openmhealth.schema.domain.omh.Measure; import org.openmhealth.shim.common.mapper.DataPointMapperUnitTests; import org.openmhealth.shim.common.mapper.JsonNodeMappingException; import org.openmhealth.shim.withings.domain.WithingsBodyMeasureType; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; /** * @author <NAME> * @author <NAME> */ public abstract class WithingsBodyMeasureDataPointMapperUnitTests<T extends Measure> extends DataPointMapperUnitTests { private static final ObjectMapper objectMapper = new ObjectMapper(); protected JsonNode responseNode; protected abstract WithingsBodyMeasureDataPointMapper<T> getMapper(); protected abstract WithingsBodyMeasureType getBodyMeasureType(); @BeforeMethod public void initializeResponseNode() throws IOException { responseNode = asJsonNode("org/openmhealth/shim/withings/mapper/withings-body-measures.json"); } @Test(expectedExceptions = JsonNodeMappingException.class) public void getValueForMeasureTypeShouldThrowExceptionOnDuplicateMeasureTypes() throws Exception { JsonNode measuresNode = objectMapper.readTree("[\n" + " {\n" + " \"type\": " + getBodyMeasureType().getMagicNumber() + ",\n" + " \"unit\": 0,\n" + " \"value\": 68\n" + " },\n" + " {\n" + " \"type\": " + getBodyMeasureType().getMagicNumber() + ",\n" + " \"unit\": 0,\n" + " \"value\": 104\n" + " }\n" + "]"); getMapper().getValueForMeasureType(measuresNode, getBodyMeasureType()); } }
967
5,169
{ "name": "ZappingKit", "version": "0.1.3", "summary": "Provide zapping UI.", "description": "Provide zapping UI. Support navigation controllre life cycle.", "homepage": "https://github.com/noppefoxwolf/ZappingKit", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/noppefoxwolf/ZappingKit.git", "tag": "0.1.3" }, "social_media_url": "https://twitter.com/noppefoxwolf", "platforms": { "ios": "8.0" }, "source_files": "ZappingKit/Classes/**/*" }
243
916
''' ModernGL: High performance rendering for Python 3 ''' from .error import * from .buffer import * from .compute_shader import * from .conditional_render import * from .context import * from .framebuffer import * from .program import * from .program_members import * from .query import * from .renderbuffer import * from .scope import * from .texture import * from .texture_3d import * from .texture_array import * from .texture_cube import * from .vertex_array import * from .sampler import * __version__ = '5.7.0'
157
663
/* * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.github.blindpirate.gogradle.core.dependency.tree; import com.github.blindpirate.gogradle.GogradleGlobal; import com.github.blindpirate.gogradle.core.dependency.GolangDependency; import com.github.blindpirate.gogradle.core.dependency.GolangDependencySet; import com.github.blindpirate.gogradle.core.dependency.ResolvedDependency; import com.github.blindpirate.gogradle.util.Assert; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class DependencyTreeNode implements Comparable<DependencyTreeNode>, Serializable { private String name; private boolean star; private ResolvedDependency originalDependency; private ResolvedDependency finalDependency; private List<DependencyTreeNode> children = new ArrayList<>(); private DependencyTreeNode(ResolvedDependency originalDependency, ResolvedDependency finalDependency, boolean star) { this.originalDependency = originalDependency; this.finalDependency = finalDependency; this.name = originalDependency.getName(); this.star = star; } public static DependencyTreeNode withOriginalAndFinal(ResolvedDependency original, ResolvedDependency finalResult, boolean star) { return new DependencyTreeNode(original, finalResult, star); } public DependencyTreeNode addChild(DependencyTreeNode child) { children.add(child); Collections.sort(children); return this; } public String output() { return print("", true, true); } private String print(String prefix, boolean isTail, boolean isRoot) { StringBuilder sb = new StringBuilder(); sb.append(prefix) .append(branch(isRoot, isTail)) .append(format(isRoot)) .append("\n"); String prefixOfChildren = prefix + padding(isRoot, isTail); for (int i = 0; i < children.size() - 1; i++) { sb.append(children.get(i).print(prefixOfChildren, false, false)); } if (children.size() > 0) { sb.append(children.get(children.size() - 1) .print(prefixOfChildren, true, false)); } return sb.toString(); } private String padding(boolean isRoot, boolean isTail) { if (isRoot) { return ""; } return isTail ? " " : "| "; } private String branch(boolean isRoot, boolean isTail) { if (isRoot) { return ""; } return isTail ? "\\-- " : "|-- "; } private String format(boolean isRoot) { if (isRoot) { return name; } else if (originalDependency.equals(finalDependency)) { return withName() + star(); } else { return withArrow() + star(); } } private String star() { return star ? " (*)" : ""; } private String withArrow() { return finalDependency.getName() + ":" + formatVersion(originalDependency) + " -> " + formatVersion(finalDependency); } private String formatVersion(ResolvedDependency dependency) { if (dependency.getSubpackages().contains(GolangDependency.ALL_DESCENDANTS)) { return dependency.formatVersion(); } else { return dependency.formatVersion() + " " + dependency.getSubpackages(); } } private String withName() { return finalDependency.getName() + ":" + formatVersion(finalDependency); } public GolangDependencySet flatten() { GolangDependencySet result = new GolangDependencySet(); dfs(result, 0); return result; } private void dfs(GolangDependencySet result, int depth) { Assert.isTrue(depth < GogradleGlobal.MAX_DFS_DEPTH); for (DependencyTreeNode child : children) { result.add(child.finalDependency); child.dfs(result, depth + 1); } } @SuppressFBWarnings("EQ_COMPARETO_USE_OBJECT_EQUALS") @Override public int compareTo(DependencyTreeNode o) { return this.name.compareTo(o.name); } @Override public String toString() { return "" + originalDependency + " -> " + finalDependency; } }
2,140
5,133
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.injectionstrategy.jsr330.field; import org.mapstruct.InjectionStrategy; import org.mapstruct.MapperConfig; import org.mapstruct.MappingConstants; /** * @author <NAME> */ @MapperConfig(componentModel = MappingConstants.ComponentModel.JSR330, injectionStrategy = InjectionStrategy.FIELD) public interface FieldJsr330Config { }
158
1,428
<gh_stars>1000+ package com.digitalocean.hacktoberfest; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; public class HelloWorld { public static void main(String[] args) throws Exception { // Input stream + lexing ANTLRInputStream antlrInputStream = new ANTLRInputStream("hello hacktoberfest"); HelloWorldLexer helloWorldLexer = new HelloWorldLexer(antlrInputStream); CommonTokenStream tokens = new CommonTokenStream(helloWorldLexer); // Parsing HelloWorldParser helloWorldParser = new HelloWorldParser(tokens); ParseTree tree = helloWorldParser.helloWorld(); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(new HelloWalker(), tree); } }
222
892
<filename>advisories/unreviewed/2022/05/GHSA-h2w7-383r-23p4/GHSA-h2w7-383r-23p4.json { "schema_version": "1.2.0", "id": "GHSA-h2w7-383r-23p4", "modified": "2022-05-13T01:50:37Z", "published": "2022-05-13T01:50:37Z", "aliases": [ "CVE-2018-18202" ], "details": "The QLogic 4Gb Fibre Channel 5.5.2.6.0 and 4/8Gb SAN 172.16.31.10.0 modules for IBM BladeCenter have an undocumented support account with a support password, an undocumented diags account with a diags password, and an undocumented prom account with a prom password.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-18202" }, { "type": "WEB", "url": "http://misteralfa-hack.blogspot.com/2018/10/ibm-bladecenter-qlogic-4g-fibre-channel.html" } ], "database_specific": { "cwe_ids": [ ], "severity": "CRITICAL", "github_reviewed": false } }
505
1,060
/* Copyright <NAME> 2011-2015 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef MSGPACK_PREDEF_ARCHITECTURE_CONVEX_H #define MSGPACK_PREDEF_ARCHITECTURE_CONVEX_H #include <msgpack/predef/version_number.h> #include <msgpack/predef/make.h> /*` [heading `MSGPACK_ARCH_CONVEX`] [@http://en.wikipedia.org/wiki/Convex_Computer Convex Computer] architecture. [table [[__predef_symbol__] [__predef_version__]] [[`__convex__`] [__predef_detection__]] [[`__convex_c1__`] [1.0.0]] [[`__convex_c2__`] [2.0.0]] [[`__convex_c32__`] [3.2.0]] [[`__convex_c34__`] [3.4.0]] [[`__convex_c38__`] [3.8.0]] ] */ #define MSGPACK_ARCH_CONVEX MSGPACK_VERSION_NUMBER_NOT_AVAILABLE #if defined(__convex__) # undef MSGPACK_ARCH_CONVEX # if !defined(MSGPACK_ARCH_CONVEX) && defined(__convex_c1__) # define MSGPACK_ARCH_CONVEX MSGPACK_VERSION_NUMBER(1,0,0) # endif # if !defined(MSGPACK_ARCH_CONVEX) && defined(__convex_c2__) # define MSGPACK_ARCH_CONVEX MSGPACK_VERSION_NUMBER(2,0,0) # endif # if !defined(MSGPACK_ARCH_CONVEX) && defined(__convex_c32__) # define MSGPACK_ARCH_CONVEX MSGPACK_VERSION_NUMBER(3,2,0) # endif # if !defined(MSGPACK_ARCH_CONVEX) && defined(__convex_c34__) # define MSGPACK_ARCH_CONVEX MSGPACK_VERSION_NUMBER(3,4,0) # endif # if !defined(MSGPACK_ARCH_CONVEX) && defined(__convex_c38__) # define MSGPACK_ARCH_CONVEX MSGPACK_VERSION_NUMBER(3,8,0) # endif # if !defined(MSGPACK_ARCH_CONVEX) # define MSGPACK_ARCH_CONVEX MSGPACK_VERSION_NUMBER_AVAILABLE # endif #endif #if MSGPACK_ARCH_CONVEX # define MSGPACK_ARCH_CONVEX_AVAILABLE #endif #define MSGPACK_ARCH_CONVEX_NAME "Convex Computer" #endif #include <msgpack/predef/detail/test.h> MSGPACK_PREDEF_DECLARE_TEST(MSGPACK_ARCH_CONVEX,MSGPACK_ARCH_CONVEX_NAME)
918
355
r''' Euler angle rotations and their conversions for Tait-Bryan zyx convention See :mod:`euler` for general discussion of Euler angles and conventions. This module has specialized implementations of the extrinsic Z axis, Y axis, X axis rotation convention. The conventions in this module are therefore: * axes $i, j, k$ are the $z, y, x$ axes respectively. Thus an Euler angle vector $[ \alpha, \beta, \gamma ]$ in our convention implies a $\alpha$ radian rotation around the $z$ axis, followed by a $\beta$ rotation around the $y$ axis, followed by a $\gamma$ rotation around the $x$ axis. * the rotation matrix applies on the left, to column vectors on the right, so if ``R`` is the rotation matrix, and ``v`` is a 3 x N matrix with N column vectors, the transformed vector set ``vdash`` is given by ``vdash = np.dot(R, v)``. * extrinsic rotations - the axes are fixed, and do not move with the rotations. * a right-handed coordinate system The convention of rotation around ``z``, followed by rotation around ``y``, followed by rotation around ``x``, is known (confusingly) as "xyz", pitch-roll-yaw, Cardan angles, or Tait-Bryan angles. Terms used in function names: * *mat* : array shape (3, 3) (3D non-homogenous coordinates) * *euler* : (sequence of) rotation angles about the z, y, x axes (in that order) * *axangle* : rotations encoded by axis vector and angle scalar * *quat* : quaternion shape (4,) ''' import math from functools import reduce import numpy as np from .axangles import axangle2mat _FLOAT_EPS_4 = np.finfo(float).eps * 4.0 def euler2mat(z, y, x): ''' Return matrix for rotations around z, y and x axes Uses the convention of static-frame rotation around the z, then y, then x axis. Parameters ---------- z : scalar Rotation angle in radians around z-axis (performed first) y : scalar Rotation angle in radians around y-axis x : scalar Rotation angle in radians around x-axis (performed last) Returns ------- M : array shape (3,3) Rotation matrix giving same rotation as for given angles Examples -------- >>> zrot = 1.3 # radians >>> yrot = -0.1 >>> xrot = 0.2 >>> M = euler2mat(zrot, yrot, xrot) >>> M.shape == (3, 3) True The output rotation matrix is equal to the composition of the individual rotations >>> M1 = euler2mat(zrot, 0, 0) >>> M2 = euler2mat(0, yrot, 0) >>> M3 = euler2mat(0, 0, xrot) >>> composed_M = np.dot(M3, np.dot(M2, M1)) >>> np.allclose(M, composed_M) True When applying M to a vector, the vector should column vector to the right of M. If the right hand side is a 2D array rather than a vector, then each column of the 2D array represents a vector. >>> vec = np.array([1, 0, 0]).reshape((3,1)) >>> v2 = np.dot(M, vec) >>> vecs = np.array([[1, 0, 0],[0, 1, 0]]).T # giving 3x2 array >>> vecs2 = np.dot(M, vecs) Rotations are counter-clockwise. >>> zred = np.dot(euler2mat(np.pi/2, 0, 0), np.eye(3)) >>> np.allclose(zred, [[0, -1, 0],[1, 0, 0], [0, 0, 1]]) True >>> yred = np.dot(euler2mat(0, np.pi/2, 0), np.eye(3)) >>> np.allclose(yred, [[0, 0, 1],[0, 1, 0], [-1, 0, 0]]) True >>> xred = np.dot(euler2mat(0, 0, np.pi/2), np.eye(3)) >>> np.allclose(xred, [[1, 0, 0],[0, 0, -1], [0, 1, 0]]) True Notes ----- The direction of rotation is given by the right-hand rule. Orient the thumb of the right hand along the axis around which the rotation occurs, with the end of the thumb at the positive end of the axis; curl your fingers; the direction your fingers curl is the direction of rotation. Therefore, the rotations are counterclockwise if looking along the axis of rotation from positive to negative. ''' Ms = [] if z: cosz = math.cos(z) sinz = math.sin(z) Ms.append(np.array( [[cosz, -sinz, 0], [sinz, cosz, 0], [0, 0, 1]])) if y: cosy = math.cos(y) siny = math.sin(y) Ms.append(np.array( [[cosy, 0, siny], [0, 1, 0], [-siny, 0, cosy]])) if x: cosx = math.cos(x) sinx = math.sin(x) Ms.append(np.array( [[1, 0, 0], [0, cosx, -sinx], [0, sinx, cosx]])) if Ms: return reduce(np.dot, Ms[::-1]) return np.eye(3) def mat2euler(M, cy_thresh=None): ''' Discover Euler angle vector from 3x3 matrix Uses the conventions above. Parameters ---------- M : array-like, shape (3,3) cy_thresh : None or scalar, optional threshold below which to give up on straightforward arctan for estimating x rotation. If None (default), estimate from precision of input. Returns ------- z : scalar y : scalar x : scalar Rotations in radians around z, y, x axes, respectively Notes ----- If there was no numerical error, the routine could be derived using Sympy expression for z then y then x rotation matrix, (see ``eulerangles.py`` in ``derivations`` subdirectory):: [ cos(y)*cos(z), -cos(y)*sin(z), sin(y)], [cos(x)*sin(z) + cos(z)*sin(x)*sin(y), cos(x)*cos(z) - sin(x)*sin(y)*sin(z), -cos(y)*sin(x)], [sin(x)*sin(z) - cos(x)*cos(z)*sin(y), cos(z)*sin(x) + cos(x)*sin(y)*sin(z), cos(x)*cos(y)] This gives the following solutions for ``[z, y, x]``:: z = atan2(-r12, r11) y = asin(r13) x = atan2(-r23, r33) Problems arise when ``cos(y)`` is close to zero, because both of:: z = atan2(cos(y)*sin(z), cos(y)*cos(z)) x = atan2(cos(y)*sin(x), cos(x)*cos(y)) will be close to ``atan2(0, 0)``, and highly unstable. The ``cy`` fix for numerical instability in this code is from: *Euler Angle Conversion* by <NAME>, p222-9 ; in: *Graphics Gems IV*, <NAME> (editor), Academic Press, 1994, ISBN: 0123361559. Specifically it comes from ``EulerAngles.c`` and deals with the case where cos(y) is close to zero: * http://www.graphicsgems.org/ * https://github.com/erich666/GraphicsGems/blob/master/gemsiv/euler_angle/EulerAngles.c#L68 The code appears to be licensed (from the website) as "can be used without restrictions". ''' M = np.asarray(M) if cy_thresh is None: try: cy_thresh = np.finfo(M.dtype).eps * 4 except ValueError: cy_thresh = _FLOAT_EPS_4 r11, r12, r13, r21, r22, r23, r31, r32, r33 = M.flat # (-cos(y)*sin(x))**2 + (cos(x)*cos(y))**2) = # (cos(y)**2)(sin(x)**2 + cos(x)**2) ==> (Pythagoras) # cos(y) = sqrt((-cos(y)*sin(x))**2 + (cos(x)*cos(y))**2) cy = math.sqrt(r23 * r23 + r33 * r33) if cy > cy_thresh: # cos(y) not close to zero, standard form z = math.atan2(-r12, r11) # atan2(cos(y)*sin(z), cos(y)*cos(z)) y = math.atan2(r13, cy) # atan2(sin(y), cy) x = math.atan2(-r23, r33) # atan2(cos(y)*sin(x), cos(x)*cos(y)) else: # cos(y) (close to) zero, so x -> 0.0 (see above) # so r21 -> sin(z), r22 -> cos(z) and z = math.atan2(r21, r22) y = math.atan2(r13, cy) # atan2(sin(y), cy) x = 0.0 return z, y, x def euler2quat(z, y, x): ''' Return quaternion corresponding to these Euler angles Uses the z, then y, then x convention above Parameters ---------- z : scalar Rotation angle in radians around z-axis (performed first) y : scalar Rotation angle in radians around y-axis x : scalar Rotation angle in radians around x-axis (performed last) Returns ------- quat : array shape (4,) Quaternion in w, x, y z (real, then vector) format Notes ----- Formula from Sympy - see ``eulerangles.py`` in ``derivations`` subdirectory ''' z = z/2.0 y = y/2.0 x = x/2.0 cz = math.cos(z) sz = math.sin(z) cy = math.cos(y) sy = math.sin(y) cx = math.cos(x) sx = math.sin(x) return np.array([ cx*cy*cz - sx*sy*sz, cx*sy*sz + cy*cz*sx, cx*cz*sy - sx*cy*sz, cx*cy*sz + sx*cz*sy]) def quat2euler(q): ''' Return Euler angles corresponding to quaternion `q` Parameters ---------- q : 4 element sequence w, x, y, z of quaternion Returns ------- z : scalar Rotation angle in radians around z-axis (performed first) y : scalar Rotation angle in radians around y-axis x : scalar Rotation angle in radians around x-axis (performed last) Notes ----- It's possible to reduce the amount of calculation a little, by combining parts of the ``quat2mat`` and ``mat2euler`` functions, but the reduction in computation is small, and the code repetition is large. ''' # delayed import to avoid cyclic dependencies from . import quaternions as nq return mat2euler(nq.quat2mat(q)) def euler2axangle(z, y, x): ''' Return angle, axis corresponding to these Euler angles Uses the z, then y, then x convention above Parameters ---------- z : scalar Rotation angle in radians around z-axis (performed first) y : scalar Rotation angle in radians around y-axis x : scalar Rotation angle in radians around x-axis (performed last) Returns ------- vector : array shape (3,) axis around which rotation occurs theta : scalar angle of rotation Examples -------- >>> vec, theta = euler2axangle(0, 1.5, 0) >>> np.allclose(vec, [0, 1, 0]) True >>> theta 1.5 ''' # delayed import to avoid cyclic dependencies from . import quaternions as nq return nq.quat2axangle(euler2quat(z, y, x)) def axangle2euler(vector, theta): ''' Convert axis, angle pair to Euler angles Parameters ---------- vector : 3 element sequence vector specifying axis for rotation. theta : scalar angle of rotation Returns ------- z : scalar y : scalar x : scalar Rotations in radians around z, y, x axes, respectively Examples -------- >>> z, y, x = axangle2euler([1, 0, 0], 0) >>> np.allclose((z, y, x), 0) True Notes ----- It's possible to reduce the amount of calculation a little, by combining parts of the ``angle_axis2mat`` and ``mat2euler`` functions, but the reduction in computation is small, and the code repetition is large. ''' return mat2euler(axangle2mat(vector, theta))
4,558
4,283
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.spi.tenantcontrol; import com.hazelcast.config.Config; import com.hazelcast.internal.util.AdditionalServiceClassLoader; import com.hazelcast.internal.util.concurrent.BackoffIdleStrategy; import com.hazelcast.internal.util.concurrent.IdleStrategy; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.test.HazelcastTestSupport; import javax.annotation.Nonnull; import java.io.IOException; import java.net.URL; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static java.util.concurrent.TimeUnit.MILLISECONDS; public abstract class TenantControlTestSupport extends HazelcastTestSupport { protected static final ThreadLocal<TenantControl> savedTenant = new ThreadLocal<>(); protected static final AtomicBoolean tenantFactoryInitialized = new AtomicBoolean(); protected static final AtomicInteger setTenantCount = new AtomicInteger(); protected static final AtomicInteger closeTenantCount = new AtomicInteger(); protected static final AtomicInteger registerTenantCount = new AtomicInteger(); protected static final AtomicInteger unregisterTenantCount = new AtomicInteger(); protected static final AtomicInteger clearedThreadInfoCount = new AtomicInteger(); protected static final AtomicInteger tenantAvailableCount = new AtomicInteger(); protected static final AtomicBoolean tenantAvailable = new AtomicBoolean(); protected static final AtomicReference<DestroyEventContext> destroyEventContext = new AtomicReference<>(null); protected static volatile boolean classesAlwaysAvailable; protected void initState() { tenantFactoryInitialized.set(false); savedTenant.remove(); setTenantCount.set(0); closeTenantCount.set(0); registerTenantCount.set(0); unregisterTenantCount.set(0); clearedThreadInfoCount.set(0); tenantAvailable.set(true); classesAlwaysAvailable = false; } protected Config newConfig() { return newConfig(true, TenantControlTest.class.getClassLoader()); } protected Config newConfig(boolean hasTenantControl, ClassLoader testClassLoader) { Config config = smallInstanceConfig(); if (hasTenantControl) { ClassLoader configClassLoader = new AdditionalServiceClassLoader(new URL[0], testClassLoader); config.setClassLoader(configClassLoader); } config.getCacheConfig("*"); return config; } public static class CountingTenantControlFactory implements TenantControlFactory { @Override public TenantControl saveCurrentTenant() { if (tenantFactoryInitialized.compareAndSet(false, true)) { TenantControl tenantControl; if (savedTenant.get() == null) { tenantControl = new CountingTenantControl(); savedTenant.set(tenantControl); } else { tenantControl = savedTenant.get(); } return tenantControl; } else if (savedTenant.get() != null) { return savedTenant.get(); } else { return TenantControl.NOOP_TENANT_CONTROL; } } @Override public boolean isClassesAlwaysAvailable() { return false; } } public static class CountingTenantControl implements TenantControl { private final IdleStrategy idleStrategy = new BackoffIdleStrategy(1, 1, MILLISECONDS.toNanos(1), MILLISECONDS.toNanos(100)); private int idleCount = 0; @Override public Closeable setTenant() { if (!isAvailable(null)) { throw new IllegalStateException("Tenant Not Available"); } setTenantCount.incrementAndGet(); return closeTenantCount::incrementAndGet; } @Override public void registerObject(@Nonnull DestroyEventContext event) { destroyEventContext.set(event); registerTenantCount.incrementAndGet(); } @Override public void unregisterObject() { unregisterTenantCount.incrementAndGet(); } @Override public void writeData(ObjectDataOutput out) throws IOException { } @Override public void readData(ObjectDataInput in) throws IOException { } @Override public boolean isAvailable(@Nonnull Tenantable tenantable) { tenantAvailableCount.incrementAndGet(); boolean available = tenantAvailable.get(); if (!available) { idleStrategy.idle(idleCount++); } else { idleCount = 0; } return available; } @Override public void clearThreadContext() { clearedThreadInfoCount.incrementAndGet(); } } }
2,134
669
""" Copyright (c) Facebook, Inc. and its affiliates. """ from droidlet.shared_data_structs import ErrorWithResponse from droidlet.interpreter import interpret_relative_direction from word2number.w2n import word_to_num def number_from_span(span): # this will fail in many cases.... words = span.split() degrees = None for w in words: try: degrees = int(w) except: pass if not degrees: try: degrees = word_to_num(span) except: pass return degrees class FacingInterpreter: def __call__(self, interpreter, speaker, d): self_mem = interpreter.memory.get_mem_by_id(interpreter.memory.self_memid) current_yaw, current_pitch = self_mem.get_yaw_pitch() if d.get("yaw_pitch"): span = d["yaw_pitch"] # for now assumed in (yaw, pitch) or yaw, pitch or yaw pitch formats yp = span.replace("(", "").replace(")", "").split() return {"head_yaw_pitch": (int(yp[0]), int(yp[1]))} elif d.get("yaw"): # for now assumed span is yaw as word or number w = d["yaw"].strip(" degrees").strip(" degree") return {"head_yaw_pitch": (word_to_num(w), current_pitch)} elif d.get("pitch"): # for now assumed span is pitch as word or number w = d["pitch"].strip(" degrees").strip(" degree") return {"head_yaw_pitch": (current_yaw, word_to_num(w))} elif d.get("relative_yaw"): # TODO in the task use turn angle if "left" in d["relative_yaw"] or "right" in d["relative_yaw"]: left = "left" in d["relative_yaw"] or "leave" in d["relative_yaw"] # lemmatizer :) degrees = number_from_span(d["relative_yaw"]) or 90 if degrees > 0 and left: return {"relative_yaw": -degrees} else: return {"relative_yaw": degrees} else: try: degrees = int(number_from_span(d["relative_yaw"])) return {"relative_yaw": degrees} except: pass elif d.get("relative_pitch"): if "down" in d["relative_pitch"] or "up" in d["relative_pitch"]: down = "down" in d["relative_pitch"] degrees = number_from_span(d["relative_pitch"]) or 90 if degrees > 0 and down: return {"relative_pitch": -degrees} else: return {"relative_pitch": degrees} else: # TODO in the task make this relative! try: deg = int(number_from_span(d["relative_pitch"])) return {"relative_pitch": deg} except: pass elif d.get("location"): mems = interpreter.subinterpret["reference_locations"]( interpreter, speaker, d["location"] ) steps, reldir = interpret_relative_direction(interpreter, d["location"]) loc, _ = interpreter.subinterpret["specify_locations"]( interpreter, speaker, mems, steps, reldir ) return {"head_xyz": loc} else: raise ErrorWithResponse("I am not sure where you want me to turn")
1,702
6,989
<gh_stars>1000+ #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/plugin.h> #include <google/protobuf/stubs/common.h> namespace NProtobuf::NCompiler::NPlugins { class TCppStyleGuideExtensionGenerator : public google::protobuf::compiler::CodeGenerator { public: bool Generate(const google::protobuf::FileDescriptor* file, const TProtoStringType& parameter, google::protobuf::compiler::OutputDirectory* output_directory, TProtoStringType* error ) const override; uint64_t GetSupportedFeatures() const override { return FEATURE_PROTO3_OPTIONAL; } }; } // namespace NProtobuf::NCompiler::NPlugins
253
12,278
// Copyright <NAME> 2013-2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #ifndef BOOST_HANA_TEST_AUTO_AP_HPP #define BOOST_HANA_TEST_AUTO_AP_HPP #include <boost/hana/assert.hpp> #include <boost/hana/ap.hpp> #include <boost/hana/equal.hpp> #include "test_case.hpp" #include <laws/base.hpp> TestCase test_ap{[]{ namespace hana = boost::hana; using hana::test::ct_eq; hana::test::_injection<0> f{}; hana::test::_injection<1> g{}; BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(), MAKE_TUPLE()), MAKE_TUPLE() )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(), MAKE_TUPLE(ct_eq<0>{})), MAKE_TUPLE() )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(), MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{})), MAKE_TUPLE() )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(), MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})), MAKE_TUPLE() )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(f), MAKE_TUPLE()), MAKE_TUPLE() )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(f), MAKE_TUPLE(ct_eq<0>{})), MAKE_TUPLE(f(ct_eq<0>{})) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(f), MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{})), MAKE_TUPLE(f(ct_eq<0>{}), f(ct_eq<1>{})) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(f), MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})), MAKE_TUPLE(f(ct_eq<0>{}), f(ct_eq<1>{}), f(ct_eq<2>{})) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(f, g), MAKE_TUPLE()), MAKE_TUPLE() )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(f, g), MAKE_TUPLE(ct_eq<0>{})), MAKE_TUPLE(f(ct_eq<0>{}), g(ct_eq<0>{})) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(f, g), MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{})), MAKE_TUPLE(f(ct_eq<0>{}), f(ct_eq<1>{}), g(ct_eq<0>{}), g(ct_eq<1>{})) )); BOOST_HANA_CONSTANT_CHECK(hana::equal( hana::ap(MAKE_TUPLE(f, g), MAKE_TUPLE(ct_eq<0>{}, ct_eq<1>{}, ct_eq<2>{})), MAKE_TUPLE(f(ct_eq<0>{}), f(ct_eq<1>{}), f(ct_eq<2>{}), g(ct_eq<0>{}), g(ct_eq<1>{}), g(ct_eq<2>{})) )); }}; #endif // !BOOST_HANA_TEST_AUTO_AP_HPP
1,471
476
### # Copyright (c) 2015-2021, The Limnoria Contributors # 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 the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # 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. ### from supybot.test import * import supybot.utils.minisix as minisix import supybot.gpg as gpg PRIVATE_KEY = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG v1.4.12 (GNU/Linux) lQHYBFD7GxQBBACeu7bj/wgnnv5NkfHImZJVJLaq2cwKYc3rErv7pqLXpxXZbDOI jP+5eSmTLhPUK67aRD6gG0wQ9iAhYR03weOmyjDGh0eF7kLYhu/4Il56Y/YbB8ll Imz/pep/Hi72ShcW8AtifDup/KeHjaWa1yF2WThHbX/0N2ghSxbJnatpBwARAQAB AAP6Arf7le7FD3ZhGZvIBkPr25qca6i0Qxb5XpOinV7jLcoycZriJ9Xofmhda9UO xhNVppMvs/ofI/m0umnR4GLKtRKnJSc8Edxi4YKyqLehfBTF20R/kBYPZ772FkNW Kzo5yCpP1jpOc0+QqBuU7OmrG4QhQzTLXIUgw4XheORncEECAMGkvR47PslJqzbY VRIzWEv297r1Jxqy6qgcuCJn3RWYJbEZ/qdTYy+MgHGmaNFQ7yhfIzkBueq0RWZp Z4PfJn8CANHZGj6AJZcvb+VclNtc5VNfnKjYD+qQOh2IS8NhE/0umGMKz3frH1TH yCbh2LlPR89cqNcd4QvbHKA/UmzISXkB/37MbUnxXTpS9Y4HNpQCh/6SYlB0lucV QN0cgjfhd6nBrb6uO6+u40nBzgynWcEpPMNfN0AtQeA4Dx+WrnK6kZqfd7QMU3Vw eWJvdCB0ZXN0iLgEEwECACIFAlD7GxQCGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4B AheAAAoJEMnTMjwgrwErV3AD/0kRq8UWPlkc6nyiIR6qiT3EoBNHKIi4cz68Wa1u F2M6einrRR0HolrxonynTGsdr1u2f3egOS4fNfGhTNAowSefYR9q5kIYiYE2DL5G YnjJKNfmnRxZM9YqmEnN50rgu2cifSRehp61fXdTtmOAR3js+9wb73dwbYzr3kIc 3WH1 =UBcd -----END PGP PRIVATE KEY BLOCK----- """ WRONG_TOKEN_SIGNATURE = """ -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 {a95dc112-780e-47f7-a83a-c6f3820d7dc3} -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.12 (GNU/Linux) iJwEAQECAAYFAlD7Jb0ACgkQydMyPCCvASv9HgQAhQf/oFMWcKwGncH0hjXC3QYz 7ck3chgL3S1pPAvS69viz6i2bwYZYD8fhzHNJ/qtw/rx6thO6PwT4SpdhKerap+I kdem3LjM4fAGHRunHZYP39obNKMn1xv+f26mEAAWxdv/W/BLAFqxi3RijJywRkXm zo5GUl844kpnV+uk0Xk= =z2Cz -----END PGP SIGNATURE----- """ FINGERPRINT = '2CF3E41500218D30F0B654F5C9D3323C20AF012B' class GPGTestCase(PluginTestCase): plugins = ('GPG', 'User') def setUp(self): super(GPGTestCase, self).setUp() gpg.loadKeyring() if gpg.available and network: def testGpgAddRemove(self): self.assertNotError('register foo bar') self.assertError('gpg key add 51E516F0B0C5CE6A pgp.mit.edu') self.assertResponse('gpg key add EB17F1E0CEB63930 pgp.mit.edu', '1 key imported, 0 unchanged, 0 not imported.') self.assertNotError( 'gpg key remove F88ECDE235846FA8652DAF5FEB17F1E0CEB63930') self.assertResponse('gpg key add EB17F1E0CEB63930 pgp.mit.edu', '1 key imported, 0 unchanged, 0 not imported.') self.assertResponse('gpg key add EB17F1E0CEB63930 pgp.mit.edu', 'Error: This key is already associated with your account.') if gpg.available: def testGpgAuth(self): self.assertNotError('register spam egg') gpg.keyring.import_keys(PRIVATE_KEY).__dict__ (id, user) = list(ircdb.users.items())[0] user.gpgkeys.append(FINGERPRINT) msg = self.getMsg('gpg signing gettoken').args[-1] match = re.search('is: ({.*}).', msg) assert match, repr(msg) token = match.group(1) def fakeGetUrlFd(*args, **kwargs): fd.geturl = lambda :None return fd (utils.web.getUrlFd, realGetUrlFd) = (fakeGetUrlFd, utils.web.getUrlFd) fd = minisix.io.StringIO() fd.write('foo') fd.seek(0) self.assertResponse('gpg signing auth http://foo.bar/baz.gpg', 'Error: Signature or token not found.') fd = minisix.io.StringIO() fd.write(token) fd.seek(0) self.assertResponse('gpg signing auth http://foo.bar/baz.gpg', 'Error: Signature or token not found.') fd = minisix.io.StringIO() fd.write(WRONG_TOKEN_SIGNATURE) fd.seek(0) self.assertRegexp('gpg signing auth http://foo.bar/baz.gpg', 'Error: Unknown token.*') fd = minisix.io.StringIO() fd.write(str(gpg.keyring.sign(token))) fd.seek(0) self.assertResponse('gpg signing auth http://foo.bar/baz.gpg', 'You are now authenticated as spam.') utils.web.getUrlFd = realGetUrlFd # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
2,913
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _LIFETIME_HXX #define _LIFETIME_HXX #include <osl/mutex.hxx> #include <osl/conditn.hxx> #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HDL_ #include <com/sun/star/uno/Exception.hdl> #endif #include <cppuhelper/interfacecontainer.hxx> #include <com/sun/star/util/XCloseListener.hpp> #include <com/sun/star/util/XCloseable.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <cppuhelper/weakref.hxx> #include "charttoolsdllapi.hxx" namespace apphelper { class LifeTimeGuard; class LifeTimeManager { friend class LifeTimeGuard; protected: mutable ::osl::Mutex m_aAccessMutex; public: OOO_DLLPUBLIC_CHARTTOOLS LifeTimeManager( ::com::sun::star::lang::XComponent* pComponent, sal_Bool bLongLastingCallsCancelable = sal_False ); OOO_DLLPUBLIC_CHARTTOOLS virtual ~LifeTimeManager(); OOO_DLLPUBLIC_CHARTTOOLS bool impl_isDisposed( bool bAssert=true ); OOO_DLLPUBLIC_CHARTTOOLS sal_Bool dispose() throw(::com::sun::star::uno::RuntimeException); public: ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; protected: virtual sal_Bool impl_canStartApiCall(); virtual void impl_apiCallCountReachedNull(){} void impl_registerApiCall(sal_Bool bLongLastingCall); void impl_unregisterApiCall(sal_Bool bLongLastingCall); void impl_init(); protected: ::com::sun::star::lang::XComponent* m_pComponent; ::osl::Condition m_aNoAccessCountCondition; sal_Int32 volatile m_nAccessCount; sal_Bool volatile m_bDisposed; sal_Bool volatile m_bInDispose; // sal_Bool m_bLongLastingCallsCancelable; ::osl::Condition m_aNoLongLastingCallCountCondition; sal_Int32 volatile m_nLongLastingCallCount; }; class CloseableLifeTimeManager : public LifeTimeManager { protected: ::com::sun::star::util::XCloseable* m_pCloseable; ::osl::Condition m_aEndTryClosingCondition; sal_Bool volatile m_bClosed; sal_Bool volatile m_bInTryClose; //the ownership between model and controller is not clear at first //each controller might consider him as owner of the model first //at start the model is not considered as owner of itself sal_Bool volatile m_bOwnership; //with a XCloseable::close call and during XCloseListener::queryClosing //the ownership can be regulated more explicit, //if so the ownership is considered to be well known sal_Bool volatile m_bOwnershipIsWellKnown; public: OOO_DLLPUBLIC_CHARTTOOLS CloseableLifeTimeManager( ::com::sun::star::util::XCloseable* pCloseable , ::com::sun::star::lang::XComponent* pComponent , sal_Bool bLongLastingCallsCancelable = sal_False ); OOO_DLLPUBLIC_CHARTTOOLS virtual ~CloseableLifeTimeManager(); OOO_DLLPUBLIC_CHARTTOOLS bool impl_isDisposedOrClosed( bool bAssert=true ); OOO_DLLPUBLIC_CHARTTOOLS sal_Bool g_close_startTryClose(sal_Bool bDeliverOwnership) throw ( ::com::sun::star::uno::Exception ); OOO_DLLPUBLIC_CHARTTOOLS sal_Bool g_close_isNeedToCancelLongLastingCalls( sal_Bool bDeliverOwnership, ::com::sun::star::util::CloseVetoException& ex ) throw ( ::com::sun::star::util::CloseVetoException ); OOO_DLLPUBLIC_CHARTTOOLS void g_close_endTryClose(sal_Bool bDeliverOwnership, sal_Bool bMyVeto ); OOO_DLLPUBLIC_CHARTTOOLS void g_close_endTryClose_doClose(); OOO_DLLPUBLIC_CHARTTOOLS sal_Bool g_addCloseListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseListener > & xListener ) throw(::com::sun::star::uno::RuntimeException); protected: virtual sal_Bool impl_canStartApiCall(); virtual void impl_apiCallCountReachedNull(); void impl_setOwnership( sal_Bool bDeliverOwnership, sal_Bool bMyVeto ); sal_Bool impl_shouldCloseAtNextChance(); void impl_doClose(); void impl_init() { m_bClosed = sal_False; m_bInTryClose = sal_False; m_bOwnership = sal_False; m_bOwnershipIsWellKnown = sal_False; m_aEndTryClosingCondition.set(); } }; //----------------------------------------------------------------- /* Use this Guard in your apicalls to protect access on resources which will be released in dispose. It's guarantied, that the release of resources only starts if your guarded call has finished. ! It's only partly guaranteed that this resources will not change during the call. See the example for details. This class is to be used as described in the example. If this guard is used in all api calls of an XCloseable object it's guarantied, that the closeable will close itself after finishing the last call if it should do so. ::ApiCall { //hold no mutex!!! LifeTimeGuard aLifeTimeGuard(m_aLifeTimeManager); //mutex is acquired; call is not registered if(!aLifeTimeGuard.startApiCall()) return ; //behave as passive as possible, if disposed or closed //mutex is acquired, call is registered { //you might access some private members here //but than you need to protect access to these members always like this //never call to the outside here } aLifeTimeGuard.clear(); //!!! //Mutex is released, the running call is still registered //this call will finish before the 'release-section' in dispose is allowed to start { //you might access some private members here guarded with your own mutex //but release your mutex at the end of this block } //you can call to the outside (without holding the mutex) without becoming disposed //End of method -> ~LifeTimeGuard //-> call is unregistered //-> this object might be disposed now } your XComponent::dispose method has to be implemented in the following way: ::dispose() { //hold no mutex!!! if( !m_aLifeTimeManager.dispose() ) return; //--release all resources and references //... } */ //----------------------------------------------------------------- class OOO_DLLPUBLIC_CHARTTOOLS LifeTimeGuard { public: LifeTimeGuard( LifeTimeManager& rManager ) : m_guard( rManager.m_aAccessMutex ) , m_rManager(rManager) , m_bCallRegistered(sal_False) , m_bLongLastingCallRegistered(sal_False) { } sal_Bool startApiCall(sal_Bool bLongLastingCall=sal_False); ~LifeTimeGuard(); void clear() { m_guard.clear(); } private: osl::ClearableMutexGuard m_guard; LifeTimeManager& m_rManager; sal_Bool m_bCallRegistered; sal_Bool m_bLongLastingCallRegistered; private: // these make no sense LifeTimeGuard( ::osl::Mutex& rMutex ); LifeTimeGuard( const LifeTimeGuard& ); LifeTimeGuard& operator= ( const LifeTimeGuard& ); }; template<class T> class NegativeGuard { protected: T * m_pT; public: NegativeGuard(T * pT) : m_pT(pT) { m_pT->release(); } NegativeGuard(T & t) : m_pT(&t) { m_pT->release(); } ~NegativeGuard() { m_pT->acquire(); } }; }//end namespace apphelper #endif
2,601
1,403
<reponame>codingric/dynmap<gh_stars>1000+ package org.dynmap.web; import org.dynmap.DynmapCore; import org.dynmap.Log; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashSet; import java.util.Set; public class BanIPFilter implements Filter { private DynmapCore core; private Set<String> banned_ips = null; private HashSet<String> banned_ips_notified = new HashSet<String>(); private long last_loaded = 0; private static final long BANNED_RELOAD_INTERVAL = 15000; /* Every 15 seconds */ public BanIPFilter(DynmapCore core) { this.core = core; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse resp = (HttpServletResponse)response; String ipaddr = request.getRemoteAddr(); if (isIpBanned(ipaddr)) { Log.info("Rejected connection by banned IP address - " + ipaddr); resp.sendError(403); } else { chain.doFilter(request, response); } } private void loadBannedIPs() { banned_ips_notified.clear(); banned_ips = core.getIPBans(); } /* Return true if address is banned */ public boolean isIpBanned(String ipaddr) { long t = System.currentTimeMillis(); if((t < last_loaded) || ((t-last_loaded) > BANNED_RELOAD_INTERVAL)) { loadBannedIPs(); last_loaded = t; } if(banned_ips.contains(ipaddr)) { if(!banned_ips_notified.contains(ipaddr)) { banned_ips_notified.add(ipaddr); } return true; } return false; } @Override public void destroy() { } }
792
1,056
<filename>java/maven/src/org/netbeans/modules/maven/output/SiteOutputProcessor.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.maven.output; import java.io.File; import java.net.MalformedURLException; import org.netbeans.api.project.Project; import org.netbeans.modules.maven.api.output.OutputProcessor; import org.netbeans.modules.maven.api.output.OutputVisitor; import static org.netbeans.modules.maven.output.Bundle.*; import org.openide.awt.HtmlBrowser; import org.openide.awt.StatusDisplayer; import org.openide.filesystems.FileUtil; import org.openide.util.NbBundle.Messages; import org.openide.util.Utilities; import org.openide.windows.OutputEvent; import org.openide.windows.OutputListener; /** * * @author mkleint */ public class SiteOutputProcessor implements OutputProcessor { private static final String[] SITEGOALS = new String[] { "mojo-execute#site:site" //NOI18N }; private Project project; /** Creates a new instance of SiteOutputProcessor */ public SiteOutputProcessor(Project prj) { this.project = prj; } @Override public String[] getRegisteredOutputSequences() { return SITEGOALS; } @Override public void processLine(String line, OutputVisitor visitor) { } @Override public void sequenceStart(String sequenceId, OutputVisitor visitor) { } @Override public void sequenceEnd(String sequenceId, OutputVisitor visitor) { //now that in m3 site plugin embeds other plugin's execution, the eventspy will report site as started and within the site execution report other sequences // (maybe) ideally we would only let site plugin to process output and start/end sequences not owned by child executions. if ("mojo-execute#site:site".equals(sequenceId)) { visitor.setLine(" View Generated Project Site"); //NOI18N shows up in maven output. OutputVisitor.Context con = visitor.getContext(); if (con != null && con.getCurrentProject() != null) { visitor.setOutputListener(new Listener(con.getCurrentProject()), false); } else { //hope for the best, but generally the root project might not be the right project to use. visitor.setOutputListener(new Listener(project), false); } } } @Override public void sequenceFail(String sequenceId, OutputVisitor visitor) { } private static class Listener implements OutputListener { private final Project prj; private Listener(Project prj) { this.prj = prj; } @Override public void outputLineSelected(OutputEvent arg0) { } @Messages({"# {0} - file name", "SiteOutputProcessor.not_found=No site index created at {0}"}) @Override public void outputLineAction(OutputEvent arg0) { File html = new File(FileUtil.toFile(prj.getProjectDirectory()), "target/site/index.html"); if (html.isFile()) { try { HtmlBrowser.URLDisplayer.getDefault().showURL(Utilities.toURI(html).toURL()); } catch (MalformedURLException x) { assert false : x; } } else { StatusDisplayer.getDefault().setStatusText(SiteOutputProcessor_not_found(html)); } } @Override public void outputLineCleared(OutputEvent arg0) { } } }
1,621
1,306
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * JNI method invocation. This is used to call a C/C++ JNI method. The * argument list has to be pushed onto the native stack according to * local calling conventions. * * This version supports the MIPS O32 ABI. */ /* TODO: this is candidate for consolidation of similar code from ARM. */ #include "Dalvik.h" #include "libdex/DexClass.h" #include <stdlib.h> #include <stddef.h> #include <sys/stat.h> /* * The class loader will associate with each method a 32-bit info word * (jniArgInfo) to support JNI calls. The high order 4 bits of this word * are the same for all targets, while the lower 28 are used for hints to * allow accelerated JNI bridge transfers. * * jniArgInfo (32-bit int) layout: * * SRRRHHHH HHHHHHHH HHHHHHHH HHHHHHHH * * S - if set, ignore the hints and do things the hard way (scan signature) * R - return-type enumeration * H - target-specific hints (see below for details) * * This function produces mips-specific hints - specifically a description * of padding required to keep all 64-bit parameters properly aligned. * * MIPS JNI hint format(Same as ARM) * * LLLL FFFFFFFF FFFFFFFF FFFFFFFF * * L - number of double-words of storage required on the stack (0-30 words) * F - pad flag -- if set, the stack increases 8 bytes, else the stack increases 4 bytes * after copying 32 bits args into stack. (little different from ARM) * * If there are too many arguments to construct valid hints, this function will * return a result with the S bit set. */ u4 dvmPlatformInvokeHints(const DexProto* proto) { const char* sig = dexProtoGetShorty(proto); int padFlags, jniHints; char sigByte; int stackOffset, padMask, hints; stackOffset = padFlags = 0; padMask = 0x00000001; /* Skip past the return type */ sig++; while (true) { sigByte = *(sig++); if (sigByte == '\0') break; if (sigByte == 'D' || sigByte == 'J') { if ((stackOffset & 1) != 0) { padFlags |= padMask; stackOffset++; padMask <<= 1; } stackOffset += 2; padMask <<= 2; } else { stackOffset++; padMask <<= 1; } } jniHints = 0; if (stackOffset > DALVIK_JNI_COUNT_SHIFT) { /* too big for "fast" version */ jniHints = DALVIK_JNI_NO_ARG_INFO; } else { assert((padFlags & (0xffffffff << DALVIK_JNI_COUNT_SHIFT)) == 0); /* * StackOffset includes the space for a2/a3. However we have reserved * 16 bytes on stack in CallO32.S, so we should subtract 2 from stackOffset. */ stackOffset -= 2; if (stackOffset < 0) stackOffset = 0; jniHints |= ((stackOffset+1) / 2) << DALVIK_JNI_COUNT_SHIFT; jniHints |= padFlags; } return jniHints; }
1,346
395
package timely.auth; import java.io.InputStream; import java.nio.charset.Charset; import java.security.Key; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.*; import java.util.stream.Collectors; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.guava.GuavaModule; import io.jsonwebtoken.*; import org.apache.accumulo.core.client.ClientConfiguration; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.Instance; import org.apache.accumulo.core.client.ZooKeeperInstance; import org.apache.accumulo.core.client.security.tokens.PasswordToken; import org.apache.accumulo.core.security.Authorizations; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; import timely.configuration.Accumulo; import timely.configuration.Security; /** * Converts between a String encoded JSON Web Token and a collection of * {@link TimelyUser}s. */ public class JWTTokenHandler { private static final Logger logger = LoggerFactory.getLogger(JWTTokenHandler.class); private static Key signatureCheckKey; private static ObjectMapper objectMapper; private static Collection<String> accumuloAuths = new TreeSet<>(); public static void init(Security security, Accumulo accumulo) { if (StringUtils.isNotBlank(security.getJwtCheckKeyStore())) { try { String type = security.getJwtCheckKeyType(); if (type != null && type.equals("X.509")) { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream is = ResourceUtils.getURL(security.getJwtCheckKeyStore()).openStream(); X509Certificate certificate = (X509Certificate) factory.generateCertificate(is); JWTTokenHandler.signatureCheckKey = certificate.getPublicKey(); } else { KeyStore keyStore = KeyStore.getInstance(type == null ? "JKS" : type); char[] keyPassword = security.getJwtCheckKeyPassword() == null ? null : security.getJwtCheckKeyPassword().toCharArray(); keyStore.load(ResourceUtils.getURL(security.getJwtCheckKeyStore()).openStream(), keyPassword); String alias = keyStore.aliases().nextElement(); Certificate cert = keyStore.getCertificate(alias); JWTTokenHandler.signatureCheckKey = cert.getPublicKey(); } } catch (Exception e) { throw new IllegalStateException("Invalid SSL configuration.", e); } } JWTTokenHandler.objectMapper = new ObjectMapper(); JWTTokenHandler.objectMapper.registerModule(new GuavaModule()); if (accumulo != null) { try { final Map<String, String> properties = new HashMap<>(); properties.put("instance.name", accumulo.getInstanceName()); properties.put("instance.zookeeper.host", accumulo.getZookeepers()); properties.put("instance.zookeeper.timeout", accumulo.getZookeeperTimeout()); final ClientConfiguration aconf = ClientConfiguration.fromMap(properties); final Instance instance = new ZooKeeperInstance(aconf); Connector connector = instance.getConnector(accumulo.getUsername(), new PasswordToken(<PASSWORD>())); Authorizations currentAccumuloAuths = connector.securityOperations() .getUserAuthorizations(connector.whoami()); currentAccumuloAuths.iterator() .forEachRemaining(a -> accumuloAuths.add(new String(a, Charset.forName("UTF-8")))); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public static Collection<TimelyUser> createUsersFromToken(String token, String claimName) { logger.trace("Attempting to parse JWT {}", token); Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signatureCheckKey).parseClaimsJws(token); Claims claims = claimsJws.getBody(); logger.trace("Resulting claims: {}", claims); List<?> principalsClaim = claims.get(claimName, List.class); if (principalsClaim == null || principalsClaim.isEmpty()) { throw new IllegalArgumentException( "JWT for " + claims.getSubject() + " does not contain any proxied principals."); } // convert to TimelyUser and downgrade auths to contain only what the // accumuloUser has return principalsClaim.stream().map(obj -> objectMapper.convertValue(obj, TimelyUser.class)).map(u -> { Collection<String> intersectedAuths = new ArrayList<>(u.getAuths()); intersectedAuths.removeIf(a -> !accumuloAuths.contains(a)); return new TimelyUser(u.getDn(), u.getUserType(), u.getEmail(), intersectedAuths, u.getRoles(), u.getRoleToAuthMapping(), u.getCreationTime(), u.getExpirationTime()); }).collect(Collectors.toList()); } }
2,172
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzTest/GemTestEnvironment.h> #include <Mocks/ISystemMock.h> #include <AzCore/UserSettings/UserSettingsComponent.h> #include <AzFramework/IO/LocalFileIO.h> #include <AzToolsFramework/Application/ToolsApplication.h> #include <System/FabricCooker.h> #include <System/TangentSpaceHelper.h> #include <System/SystemComponent.h> #include <Components/ClothComponent.h> #include <Components/EditorClothComponent.h> #include <Pipeline/SceneAPIExt/ClothRuleBehavior.h> #include <Pipeline/RCExt/CgfClothExporter.h> #include <Editor/PropertyTypes.h> namespace UnitTest { //! Sets up gem test environment, required components, and shared objects used by cloth (e.g. FabricCooker) for all test cases. class NvClothEditorTestEnvironment : public AZ::Test::GemTestEnvironment { public: // AZ::Test::GemTestEnvironment overrides ... void AddGemsAndComponents() override; void PreCreateApplication() override; void PostDestroyApplication() override; void SetupEnvironment() override; void TeardownEnvironment() override; AZ::ComponentApplication* CreateApplicationInstance() override; private: AZStd::unique_ptr<NvCloth::FabricCooker> m_fabricCooker; AZStd::unique_ptr<NvCloth::TangentSpaceHelper> m_tangentSpaceHelper; AZStd::unique_ptr<AZ::IO::LocalFileIO> m_fileIO; using PropertyHandlers = AZStd::vector<AzToolsFramework::PropertyHandlerBase*>; AZStd::unique_ptr<PropertyHandlers> m_propertyHandlers; }; void NvClothEditorTestEnvironment::AddGemsAndComponents() { AddDynamicModulePaths({ "Gem.LmbrCentral.Editor.ff06785f7145416b9d46fde39098cb0c.v0.1.0", "Gem.EMotionFX.Editor.044a63ea67d04479aa5daf62ded9d9ca.v0.1.0" }); AddComponentDescriptors({ NvCloth::SystemComponent::CreateDescriptor(), NvCloth::ClothComponent::CreateDescriptor(), NvCloth::EditorClothComponent::CreateDescriptor(), NvCloth::Pipeline::ClothRuleBehavior::CreateDescriptor(), NvCloth::Pipeline::CgfClothExporter::CreateDescriptor(), }); AddRequiredComponents({ NvCloth::SystemComponent::TYPEINFO_Uuid(), }); } void NvClothEditorTestEnvironment::PreCreateApplication() { NvCloth::SystemComponent::InitializeNvClothLibrary(); // SystemAllocator creation must come before this call. m_fabricCooker = AZStd::make_unique<NvCloth::FabricCooker>(); m_tangentSpaceHelper = AZStd::make_unique<NvCloth::TangentSpaceHelper>(); // EMotionFX SystemComponent activation requires a valid AZ::IO::LocalFileIO m_fileIO = AZStd::make_unique<AZ::IO::LocalFileIO>(); AZ::IO::FileIOBase::SetInstance(m_fileIO.get()); } void NvClothEditorTestEnvironment::PostDestroyApplication() { AZ::IO::FileIOBase::SetInstance(nullptr); m_fileIO.reset(); m_tangentSpaceHelper.reset(); m_fabricCooker.reset(); NvCloth::SystemComponent::TearDownNvClothLibrary(); // SystemAllocator destruction must come after this call. } void NvClothEditorTestEnvironment::SetupEnvironment() { AZ::Test::GemTestEnvironment::SetupEnvironment(); m_propertyHandlers = AZStd::make_unique<PropertyHandlers>(); *m_propertyHandlers = NvCloth::Editor::RegisterPropertyTypes(); if (CrySystemEvents* systemComponent = m_gemEntity->FindComponent<NvCloth::SystemComponent>()) { ::testing::NiceMock<SystemMock> crySystemMock; systemComponent->OnCrySystemInitialized(crySystemMock, {}); } } void NvClothEditorTestEnvironment::TeardownEnvironment() { if (CrySystemEvents* systemComponent = m_gemEntity->FindComponent<NvCloth::SystemComponent>()) { ::testing::NiceMock<SystemMock> crySystemMock; systemComponent->OnCrySystemShutdown(crySystemMock); } NvCloth::Editor::UnregisterPropertyTypes(*m_propertyHandlers); m_propertyHandlers.reset(); AZ::Test::GemTestEnvironment::TeardownEnvironment(); } AZ::ComponentApplication* NvClothEditorTestEnvironment::CreateApplicationInstance() { auto* application = aznew AzToolsFramework::ToolsApplication; application->CalculateAppRoot(); return application; } } // namespace UnitTest AZ_UNIT_TEST_HOOK(new UnitTest::NvClothEditorTestEnvironment);
1,928
1,072
#ifndef _HEADERS_STABS_H #define _HEADERS_STABS_H /* These are some macros for handling of symboltable information */ /* linker can use symbol b for symbol a if a is not defined */ #define ALIAS(a,b) asm(".stabs \"_" #a "\",11,0,0,0;.stabs \"_" #b "\",1,0,0,0") /* add symbol a to list b (type c (22=text 24=data 26=bss)) */ #define ADD2LIST(a,b,c) asm(".stabs \"_" #b "\"," #c ",0,0,_" #a ) /* Install private constructors and destructors pri MUST be -127<=pri<=127 */ #define ADD2INIT(a,pri) ADD2LIST(a,__INIT_LIST__,22); \ asm(".stabs \"___INIT_LIST__\",20,0,0," #pri "+128") #define ADD2EXIT(a,pri) ADD2LIST(a,__EXIT_LIST__,22); \ asm(".stabs \"___EXIT_LIST__\",20,0,0," #pri "+128") /* Add to library list */ #define ADD2LIB(a) ADD2LIST(a,__LIB_LIST__,24) /* This one does not really handle symbol tables * it's just pointless to write a header file for one macro * * define a as a label for an absolute address b */ #define ABSDEF(a,b) asm("_" #a "=" #b ";.globl _" #a ) /* Generate assembler stub for a shared library entry * and add it to the jump table * ADDTABL_X(name,...) means function with X arguments * ADDTABL_END() ends the list * Usage: ADDTABL_2(AddHead,a0,a1); * No more than 4 arguments supported, use structures! */ #define _ADDTABL_START(name) \ asm(".globl ___" #name); \ asm("___" #name ":\tmovel a4,sp@-") #define _ADDTABL_ARG(arg) \ asm("\tmovel " #arg ",sp@-") #define _ADDTABL_CALL(name) \ asm("\tmovel a6@(40:W),a4"); \ asm("\tbsr _" #name) #define _ADDTABL_END0(name,numargs) \ asm("\tmovel sp@+,a4"); \ asm("\trts"); \ ADD2LIST(__##name,__FuncTable__,22) #define _ADDTABL_END2(name,numargs) \ asm("\taddqw #4*" #numargs ",sp"); \ asm("\tmovel sp@+,a4"); \ asm("\trts"); \ ADD2LIST(__##name,__FuncTable__,22) #define _ADDTABL_ENDN(name,numargs) \ asm("\taddaw #4*" #numargs ",sp"); \ asm("\tmovel sp@+,a4"); \ asm("\trts"); \ ADD2LIST(__##name,__FuncTable__,22) #define ADDTABL_0(name) \ _ADDTABL_START(name); \ _ADDTABL_CALL(name); \ _ADDTABL_END0(name,0) #define ADDTABL_1(name,arg1) \ _ADDTABL_START(name); \ _ADDTABL_ARG(arg1); \ _ADDTABL_CALL(name); \ _ADDTABL_END2(name,1) #define ADDTABL_2(name,arg1,arg2) \ _ADDTABL_START(name); \ _ADDTABL_ARG(arg2); \ _ADDTABL_ARG(arg1); \ _ADDTABL_CALL(name); \ _ADDTABL_END2(name,2) #define ADDTABL_3(name,arg1,arg2,arg3) \ _ADDTABL_START(name); \ _ADDTABL_ARG(arg3); \ _ADDTABL_ARG(arg2); \ _ADDTABL_ARG(arg1); \ _ADDTABL_CALL(name); \ _ADDTABL_ENDN(name,3) #define ADDTABL_4(name,arg1,arg2,arg3,arg4) \ _ADDTABL_START(name); \ _ADDTABL_ARG(arg4); \ _ADDTABL_ARG(arg3); \ _ADDTABL_ARG(arg2); \ _ADDTABL_ARG(arg1); \ _ADDTABL_CALL(name); \ _ADDTABL_ENDN(name,4) #define ADDTABL_END() asm(".stabs \"___FuncTable__\",20,0,0,-1") #endif /* _HEADERS_STABS_H */
1,426
2,702
<filename>api/src/test/java/keywhiz/api/automation/v2/SecretContentsResponseV2Test.java<gh_stars>1000+ /* * Copyright (C) 2015 Square, 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 keywhiz.api.automation.v2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.Test; import static keywhiz.testing.JsonHelpers.asJson; import static keywhiz.testing.JsonHelpers.fromJson; import static keywhiz.testing.JsonHelpers.jsonFixture; import static org.assertj.core.api.Assertions.assertThat; public class SecretContentsResponseV2Test { private SecretContentsResponseV2 secretContentsResponse = SecretContentsResponseV2.builder() .successSecrets( ImmutableMap.of("secret1", "supersecretcontent1", "secret2", "supersecretcontent2")) .missingSecrets(ImmutableList.of("secret3")) .build(); @Test public void roundTripSerialization() throws Exception { assertThat(fromJson(asJson(secretContentsResponse), SecretContentsResponseV2.class)).isEqualTo( secretContentsResponse); } @Test public void deserializesCorrectly() throws Exception { assertThat(fromJson( jsonFixture("fixtures/v2/secretContentsResponse.json"), SecretContentsResponseV2.class)) .isEqualTo(secretContentsResponse); } }
575
8,315
<reponame>linhvnguyen9/epoxy-exoplayer package com.airbnb.epoxy.integrationtest; import com.airbnb.epoxy.AutoModel; import com.airbnb.epoxy.EpoxyController; public class BasicAutoModelsAdapter extends EpoxyController { @AutoModel Model_ model1; @AutoModel Model_ model2; @Override protected void buildModels() { add(model1.id(1)); add(model2.id(2)); } }
140
711
<filename>java110-bean/src/main/java/com/java110/entity/center/DataFlowLinksCost.java package com.java110.entity.center; import java.util.Date; /** * Created by wuxw on 2018/4/13. */ public class DataFlowLinksCost { //环节编码 private String LinksCode; private String LinksName; private Date startDate; private Date endDate; public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getLinksCode() { return LinksCode; } public void setLinksCode(String linksCode) { LinksCode = linksCode; } public String getLinksName() { return LinksName; } public void setLinksName(String linksName) { LinksName = linksName; } public DataFlowLinksCost builder(String LinksCode, String LinksName, Date startDate, Date endDate){ this.LinksCode = LinksCode; this.LinksName = LinksName; this.startDate = startDate; this.endDate = endDate; return this; } }
493
811
{ "description": "Selectors - NEGATED :nth-last-child() pseudo-class (css3-modsel-74b)", "selectors": { ".green": "css3-modsel-74b.expected0.html", "ul > li:not(:nth-last-child(odd))": "css3-modsel-74b.expected1.html", "ol > li:not(:nth-last-child(even))": "css3-modsel-74b.expected2.html", "table.t1 tr:not(:nth-last-child(-n+4))": "css3-modsel-74b.expected3.html", "table.t2 td:not(:nth-last-child(3n+1))": "css3-modsel-74b.expected4.html", "table.t1 td, table.t2 td": "css3-modsel-74b.expected5.html" }, "src": "css3-modsel-74b.src.html" }
276
545
#include <iostream> #include "String.h" void print(const String &s) { std::cout << "<" << &s << ">:<" << s.str() << "> size: " << s.size() << " capacity: " << s.capacity() << std::endl; } int main() { String s1; print(s1); s1.pop_back(); print(s1); s1.push_back('a'); print(s1); s1.push_back('b'); print(s1); s1.push_back('c'); print(s1); s1.push_back('d'); print(s1); { String s2 = "s2"; print(s2); s2 = "s3"; print(s2); char *cs = "def"; s2 = cs; print(s2); s2 = s1; print(s2); } print(s1); s1.pop_back(); print(s1); s1.reserve(s1.capacity() / 2); print(s1); s1.reserve(s1.capacity() * 2); print(s1); s1.resize(s1.size() + 6); print(s1); s1.resize(s1.size() + 6, 'x'); print(s1); s1.resize(s1.size() - 6); print(s1); s1.resize(s1.size() - 6, 'x'); print(s1); String s2 { 'm', 'n', 'p', 'q', 'r' }; print(s2); String s3 = { 'm', 'n', 'p', 'q', 'r' }; print(s3); return 0; }
479
511
//****************************************************************** // // Copyright 2016 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include "RemoteSceneAction.h" #include <cassert> #include "SceneCommons.h" #include "SceneMemberResourceRequestor.h" namespace OIC { namespace Service { RemoteSceneAction::RemoteSceneAction( SceneMemberResourceRequestor::Ptr requestor, const std::string &sceneName, const RCSResourceAttributes &attrs) : m_sceneName{ sceneName }, m_attributes{ attrs }, m_requestor{ requestor } { assert(requestor); } RemoteSceneAction::RemoteSceneAction( SceneMemberResourceRequestor::Ptr requestor, const std::string &sceneName, const std::string &key, const RCSResourceAttributes::Value &value) : m_sceneName{ sceneName }, m_requestor{ requestor } { assert(requestor); m_attributes[key] = value; } void RemoteSceneAction::resetExecutionParameter(const std::string &key, const RCSResourceAttributes::Value &value, ResetExecutionParameterCallback clientCB) { RCSResourceAttributes attr; attr[key] = RCSResourceAttributes::Value(value); resetExecutionParameter(attr, std::move(clientCB)); } void RemoteSceneAction::resetExecutionParameter(const RCSResourceAttributes &attr, ResetExecutionParameterCallback clientCB) { if (!clientCB) { throw RCSInvalidParameterException{ "resetExecutionParameter : Callback is NULL" }; } SceneMemberResourceRequestor::InternalAddSceneActionCallback internalCB = std::bind(&RemoteSceneAction::onExecutionParameterSet, this, std::placeholders::_1, attr, std::move(clientCB)); m_requestor->requestSceneActionCreation( m_sceneName, attr, internalCB); } RCSResourceAttributes RemoteSceneAction::getExecutionParameter() const { std::lock_guard< std::mutex > lock(m_attributeLock); return m_attributes; } RCSRemoteResourceObject::Ptr RemoteSceneAction::getRemoteResourceObject() const { return m_requestor->getRemoteResourceObject(); } void RemoteSceneAction::onExecutionParameterSet(int eCode, const RCSResourceAttributes &attr, const ResetExecutionParameterCallback &clientCB) { int result = SCENE_CLIENT_BADREQUEST; if (eCode == SCENE_RESPONSE_SUCCESS) { std::lock_guard< std::mutex > lock(m_attributeLock); m_attributes = attr; result = SCENE_RESPONSE_SUCCESS; } clientCB(result); } } }
1,466
1,044
<gh_stars>1000+ { "Prelude": { "abs": ["positive", "magnitude", "absoluteValue"], "acos": ["arccos"], "activityOf": ["interactionOf"], "arc": [ { "value": "semicircle", "explanation": "Hint: A semicircle is an arc with the start and end angles 180 degrees apart." } ], "asin": ["arcsin"], "atan": ["arctan"], "mixed": ["blend"], "assortedColors": ["colors"], "closedCurve": ["loop", "oval"], "cos": ["cosine"], "lettering": ["text"], "PointerMovement": ["MouseMovement"], "PointerPress": ["MousePress", "MouseClick", "PointerClick"], "PointerRelease": ["MouseRelease"], "polygon": [ { "value": "triangle", "explanation": "Hint: A triangle is a polygon with three vertices." }, { "value": "quadrilateral", "explanation": "Hint: A quadrilateral is a polygon with four vertices." }, { "value": "parallelogram", "explanation": "Hint: A parallelogram is a polygon with four vertices and parallel sides." }, { "value": "trapezoid", "explanation": "Hint: A trapezoid is a polygon with four vertices and one pair of parallel sides." }, { "value": "rhombus", "explanation": "Hint: A rhombus is a polygon with four vertices and equal side lengths." }, { "value": "pentagon", "explanation": "Hint: A pentagon is a polygon with five vertices." }, { "value": "hexagon", "explanation": "Hint: A hexagon is a polygon with six vertices." }, { "value": "heptagon", "explanation": "Hint: A heptagon is a polygon with seven vertices." }, { "value": "octagon", "explanation": "Hint: An octagon is a polygon with eight vertices." } ], "polyline": ["line"], "program": ["main"], "rectangle": [ { "value": "square", "explanation": "Hint: A square is a rectangle with the height and width equal." } ], "reflected": ["mirror", "flip"], "rotated": ["turn", "flip"], "scaled": [ "stretch", { "value": "ellipse", "explanation": "Hint: An ellipse is a scaled circle." } ], "sector": ["solidArc", "pie"], "sin": ["sine"], "solidClosedCurve": ["solidCurve", "solidLoop", "solidOval"], "solidPolygon": [ "solidTriangle", "solidQuadrilateral", "solidParallelogram", "solidTrapezoid", "solidRhombus", "solidPentagon", "solidHexagon", "solidHeptagon", "solidOctagon" ], "solidRectangle": ["solidSquare"], "sqrt": ["root", "radical", "squareRoot"], "tan": ["tangent"], "thickClosedCurve": ["thickLoop", "thickOval"], "thickPolygon": [ "thickTriangle", "thickQuadrilateral", "thickParallelogram", "thickTrapezoid", "thickRhombus", "thickPentagon", "thickHexagon", "thickHeptagon", "thickOctagon" ], "thickPolyline": ["thickLine"], "thickRectangle": ["thickSquare"], "translated": ["move", "shift", "position"] } }
1,462
375
<gh_stars>100-1000 /* * Copyright 2015 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.rf.ide.core.testdata.text.read; import org.rf.ide.core.environment.RobotVersion; public class VersionAvailabilityInfo { private final String representation; private final RobotVersion availableFrom; private final RobotVersion deprecatedFrom; private final RobotVersion removedFrom; private VersionAvailabilityInfo(final String representation, final RobotVersion availableFrom, final RobotVersion deprecatedFrom, final RobotVersion removedFrom) { this.representation = representation; this.availableFrom = availableFrom; this.deprecatedFrom = deprecatedFrom; this.removedFrom = removedFrom; } public String getRepresentation() { return representation; } public RobotVersion getAvailableFrom() { return availableFrom; } public RobotVersion getDeprecatedFrom() { return deprecatedFrom; } public RobotVersion getRemovedFrom() { return removedFrom; } public static class VersionAvailabilityInfoBuilder { private String representation; private RobotVersion availableFrom; private RobotVersion deprecatedFrom; private RobotVersion removedFrom; private VersionAvailabilityInfoBuilder() { } public static VersionAvailabilityInfoBuilder create() { return new VersionAvailabilityInfoBuilder(); } public VersionAvailabilityInfoBuilder addRepresentation(final String representation) { this.representation = representation; return this; } public VersionAvailabilityInfoBuilder availableFrom(final String availableFrom) { this.availableFrom = RobotVersion.from(availableFrom); return this; } public VersionAvailabilityInfoBuilder deprecatedFrom(final String deprecatedFrom) { this.deprecatedFrom = RobotVersion.from(deprecatedFrom); return this; } public VersionAvailabilityInfoBuilder removedFrom(final String removedFrom) { this.removedFrom = RobotVersion.from(removedFrom); return this; } public VersionAvailabilityInfo build() { RobotVersion available = availableFrom; if (available == null) { available = new RobotVersion(0, 0); } RobotVersion deprecated = deprecatedFrom; if (deprecated == null) { deprecated = new RobotVersion(Integer.MAX_VALUE, Integer.MAX_VALUE); } RobotVersion removed = removedFrom; if (removed == null) { removed = new RobotVersion(Integer.MAX_VALUE, Integer.MAX_VALUE); } return new VersionAvailabilityInfo(representation, available, deprecated, removed); } } }
1,081
890
<filename>asylo/identity/attestation/sgx/internal/fake_pce.cc<gh_stars>100-1000 /* * * Copyright 2020 Asylo 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. * */ #include "asylo/identity/attestation/sgx/internal/fake_pce.h" #include <memory> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "asylo/crypto/algorithms.pb.h" #include "asylo/crypto/ecdsa_p256_sha256_signing_key.h" #include "asylo/crypto/keys.pb.h" #include "asylo/crypto/rsa_oaep_encryption_key.h" #include "asylo/crypto/util/byte_container_util.h" #include "asylo/crypto/util/bytes.h" #include "asylo/crypto/util/trivial_object_util.h" #include "asylo/identity/attestation/sgx/internal/pce_util.h" #include "asylo/identity/platform/sgx/internal/identity_key_management_structs.h" #include "asylo/identity/platform/sgx/internal/sgx_identity_util_internal.h" #include "asylo/identity/platform/sgx/sgx_identity_util.h" #include "asylo/identity/provisioning/sgx/internal/fake_sgx_pki.h" namespace asylo { namespace sgx { constexpr uint16_t FakePce::kPceSvn; constexpr uint16_t FakePce::kPceId; const UnsafeBytes<kPpidSize> FakePce::kPpid = UnsafeBytes<kPpidSize>("123456abcdef1234"); FakePce::FakePce(std::unique_ptr<SigningKey> pck, uint16_t pce_svn, uint16_t pce_id, UnsafeBytes<kPpidSize> ppid) : pck_(std::move(pck)), pce_svn_(pce_svn), pce_id_(pce_id), ppid_(ppid) {} StatusOr<std::unique_ptr<FakePce>> FakePce::CreateFromFakePki() { std::unique_ptr<EcdsaP256Sha256SigningKey> pck; ASYLO_ASSIGN_OR_RETURN(pck, EcdsaP256Sha256SigningKey::CreateFromPem( kFakeSgxPck.signing_key_pem)); return absl::make_unique<FakePce>(std::move(pck), kPceSvn, kPceId, kPpid); } Status FakePce::SetPckCertificateChain(const CertificateChain &chain) { return absl::OkStatus(); } Status FakePce::SetEnclaveDir(const std::string &path) { return absl::OkStatus(); } Status FakePce::GetPceTargetinfo(Targetinfo *targetinfo, uint16_t *pce_svn) { // Use a well-formed Targetinfo (all reserved fields are cleared and all // required bits are set). SetTargetinfoFromSelfIdentity(targetinfo); targetinfo->attributes = SecsAttributeSet::GetMustBeSetBits(); targetinfo->miscselect = 0; *pce_svn = pce_svn_; return absl::OkStatus(); } Status FakePce::PceSignReport(const Report &report, uint16_t /*target_pce_svn*/, UnsafeBytes<kCpusvnSize> /*target_cpu_svn*/, std::string *signature) { Signature pck_signature; ASYLO_RETURN_IF_ERROR(pck_->Sign( ByteContainerView(&report.body, sizeof(report.body)), &pck_signature)); const EcdsaSignature &ecdsa_signature = pck_signature.ecdsa_signature(); *signature = absl::StrCat(ecdsa_signature.r(), ecdsa_signature.s()); return absl::OkStatus(); } Status FakePce::GetPceInfo(const Report &report, absl::Span<const uint8_t> ppid_encryption_key, AsymmetricEncryptionScheme ppid_encryption_scheme, std::string *ppid_encrypted, uint16_t *pce_svn, uint16_t *pce_id, SignatureScheme *signature_scheme) { if (ppid_encryption_scheme != RSA3072_OAEP) { return absl::InvalidArgumentError("Unsupported PPID encryption scheme"); } bssl::UniquePtr<RSA> ppidek_rsa; ASYLO_ASSIGN_OR_RETURN(ppidek_rsa, ParseRsa3072PublicKey(ppid_encryption_key)); std::unique_ptr<RsaOaepEncryptionKey> ppidek; ASYLO_ASSIGN_OR_RETURN( ppidek, RsaOaepEncryptionKey::Create(std::move(ppidek_rsa), SHA256)); std::vector<uint8_t> encrypted_ppid; ASYLO_RETURN_IF_ERROR(ppidek->Encrypt(ppid_, &encrypted_ppid)); *ppid_encrypted = CopyToByteContainer<std::string>(encrypted_ppid); *pce_svn = pce_svn_; *pce_id = pce_id_; *signature_scheme = pck_->GetSignatureScheme(); return absl::OkStatus(); } StatusOr<Targetinfo> FakePce::GetQeTargetinfo() { return Status(absl::StatusCode::kUnimplemented, "Not implemented"); } StatusOr<std::vector<uint8_t>> FakePce::GetQeQuote(const Report &report) { return Status(absl::StatusCode::kUnimplemented, "Not implemented"); } } // namespace sgx } // namespace asylo
2,047
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Plovan","circ":"7ème circonscription","dpt":"Finistère","inscrits":632,"abs":240,"votants":392,"blancs":4,"nuls":2,"exp":386,"res":[{"nuance":"REM","nom":"<NAME>","voix":138},{"nuance":"FI","nom":"M. <NAME>","voix":61},{"nuance":"LR","nom":"<NAME>","voix":50},{"nuance":"SOC","nom":"Mme <NAME>","voix":40},{"nuance":"FN","nom":"Mme <NAME>","voix":26},{"nuance":"ECO","nom":"<NAME>","voix":26},{"nuance":"UDI","nom":"M. <NAME>","voix":25},{"nuance":"REG","nom":"Mme <NAME>","voix":9},{"nuance":"REG","nom":"M. <NAME>","voix":4},{"nuance":"DVG","nom":"Mme <NAME>","voix":4},{"nuance":"EXG","nom":"Mme <NAME>","voix":3},{"nuance":"DIV","nom":"M. <NAME>","voix":0}]}
291
17,481
<filename>java/dagger/internal/codegen/base/Util.java<gh_stars>1000+ /* * Copyright (C) 2013 The Dagger 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 dagger.internal.codegen.base; import java.util.Map; import java.util.function.Function; /** General utilities for the annotation processor. */ public final class Util { /** * A version of {@link Map#computeIfAbsent(Object, Function)} that allows {@code mappingFunction} * to update {@code map}. */ public static <K, V> V reentrantComputeIfAbsent( Map<K, V> map, K key, Function<? super K, ? extends V> mappingFunction) { V value = map.get(key); if (value == null) { value = mappingFunction.apply(key); if (value != null) { map.put(key, value); } } return value; } private Util() {} }
425
379
<gh_stars>100-1000 # Copyright (c) 2020 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. """ MNIST Demo """ import sys import os import errno import numpy as np import time import paddle import paddle.fluid as fluid import paddle_fl.mpc as pfl_mpc from paddle_fl.mpc.data_utils.data_utils import get_datautils mpc_protocol_name = 'aby3' mpc_du= get_datautils(mpc_protocol_name) role, server, port = sys.argv[1], sys.argv[2], sys.argv[3] # modify host(localhost). pfl_mpc.init(mpc_protocol_name, int(role), "localhost", server, int(port)) role = int(role) # data preprocessing BATCH_SIZE = 128 epoch_num = 2 # network x = pfl_mpc.data(name='x', shape=[BATCH_SIZE, 784], dtype='int64') y = pfl_mpc.data(name='y', shape=[BATCH_SIZE, 1], dtype='int64') y_pre = pfl_mpc.layers.fc(input=x, size=1) cost = pfl_mpc.layers.sigmoid_cross_entropy_with_logits(y_pre, y) infer_program = fluid.default_main_program().clone(for_test=False) avg_loss = pfl_mpc.layers.mean(cost) optimizer = pfl_mpc.optimizer.SGD(learning_rate=0.001) optimizer.minimize(avg_loss) mpc_data_dir = "./mpc_data/" if not os.path.exists(mpc_data_dir): raise ValueError("mpc_data_dir is not found. Please prepare encrypted data.") # train_reader feature_reader = mpc_du.load_shares(mpc_data_dir + "mnist2_feature", id=role, shape=(784,)) label_reader = mpc_du.load_shares(mpc_data_dir + "mnist2_label", id=role, shape=(1,)) batch_feature = mpc_du.batch(feature_reader, BATCH_SIZE, drop_last=True) batch_label = mpc_du.batch(label_reader, BATCH_SIZE, drop_last=True) # test_reader test_feature_reader = mpc_du.load_shares(mpc_data_dir + "mnist2_test_feature", id=role, shape=(784,)) test_label_reader = mpc_du.load_shares(mpc_data_dir + "mnist2_test_label", id=role, shape=(1,)) test_batch_feature = mpc_du.batch(test_feature_reader, BATCH_SIZE, drop_last=True) test_batch_label = mpc_du.batch(test_label_reader, BATCH_SIZE, drop_last=True) place = fluid.CPUPlace() # async data loader loader = fluid.io.DataLoader.from_generator(feed_list=[x, y], capacity=BATCH_SIZE) batch_sample = paddle.reader.compose(batch_feature, batch_label) loader.set_batch_generator(batch_sample, places=place) test_loader = fluid.io.DataLoader.from_generator(feed_list=[x, y], capacity=BATCH_SIZE) test_batch_sample = paddle.reader.compose(test_batch_feature, test_batch_label) test_loader.set_batch_generator(test_batch_sample, places=place) # loss file # loss_file = "/tmp/mnist_output_loss.part{}".format(role) # train exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) start_time = time.time() step = 0 for epoch_id in range(epoch_num): # feed data via loader for sample in loader(): step += 1 exe.run(feed=sample, fetch_list=[cost.name]) batch_end = time.time() if step % 50 == 0: print('Epoch={}, Step={}'.format(epoch_id, step)) end_time = time.time() print('Mpc Training of Epoch={} Batch_size={}, epoch_cost={:.4f} s' .format(epoch_num, BATCH_SIZE, (end_time - start_time))) # prediction mpc_infer_data_dir = "./mpc_infer_data/" if not os.path.exists(mpc_infer_data_dir): try: os.mkdir(mpc_infer_data_dir) except OSError as e: if e.errno != errno.EEXIST: raise prediction_file = mpc_infer_data_dir + "mnist_debug_prediction.part{}".format(role) if os.path.exists(prediction_file): os.remove(prediction_file) for sample in test_loader(): prediction = exe.run(program=infer_program, feed=sample, fetch_list=[cost]) with open(prediction_file, 'ab') as f: f.write(np.array(prediction).tostring())
1,604
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. */ package org.netbeans.api.annotations.common; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker for a constant representing a static resource. * The annotated field must be a compile-time {@code String} constant whose value denotes a resource path. * For example, the resource might be an icon path intended for {@code ImageUtilities.loadImage}. * The primary purpose of the annotation is for its processor, which will signal a compile-time error * if the resource does not in fact exist - ensuring that at least this usage will not be accidentally * broken by moving, renaming, or deleting the resource. * @since 1.13 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.SOURCE) @Documented public @interface StaticResource { /** * If true, permit the resource to be in the classpath. * By default, it may only be in the sourcepath. */ boolean searchClasspath() default false; /** * If true, consider the resource path to be relative to the current package. * ({@code ../} sequences are permitted.) * By default, it must be an absolute path (not starting with {@code /}). */ boolean relative() default false; }
578
1,144
<gh_stars>1000+ package de.metas.pricing.exceptions; import java.time.LocalDate; import javax.annotation.Nullable; import org.adempiere.exceptions.AdempiereException; import de.metas.bpartner.BPartnerId; import de.metas.bpartner.service.IBPartnerBL; import de.metas.i18n.AdMessageKey; import de.metas.i18n.ITranslatableString; import de.metas.i18n.TranslatableStringBuilder; import de.metas.i18n.TranslatableStrings; import de.metas.location.CountryId; import de.metas.location.ICountryDAO; import de.metas.pricing.IPricingContext; import de.metas.pricing.PriceListId; import de.metas.pricing.PricingSystemId; import de.metas.pricing.service.IPriceListDAO; import de.metas.product.IProductBL; import de.metas.product.ProductId; import de.metas.util.Services; import lombok.Builder; @SuppressWarnings("serial") public class ProductNotOnPriceListException extends AdempiereException { public static final AdMessageKey AD_Message = AdMessageKey.of("ProductNotOnPriceList"); public ProductNotOnPriceListException(final IPricingContext pricingCtx) { this(pricingCtx, -1, // documentLineNo (ProductId)null); } public ProductNotOnPriceListException(final IPricingContext pricingCtx, final int documentLineNo) { this(pricingCtx, documentLineNo, (ProductId)null); } @Builder private ProductNotOnPriceListException( final IPricingContext pricingCtx, final int documentLineNo, final ProductId productId) { super(buildMessage(pricingCtx, documentLineNo, productId)); setParameter("pricingCtx", pricingCtx); if (documentLineNo > 0) { setParameter("documentLineNo", documentLineNo); } } private static ITranslatableString buildMessage( @Nullable final IPricingContext pricingCtx, final int documentLineNo, final ProductId productId) { final TranslatableStringBuilder sb = TranslatableStrings.builder(); if (documentLineNo > 0) { if (!sb.isEmpty()) { sb.append(", "); } sb.appendADElement("Line").append(": ").append(documentLineNo); } ProductId productIdEffective = null; if (productId != null) { productIdEffective = productId; } else if (pricingCtx != null) { productIdEffective = pricingCtx.getProductId(); } if (productIdEffective != null) { final String productName = Services.get(IProductBL.class).getProductValueAndName(productIdEffective); if (!sb.isEmpty()) { sb.append(", "); } sb.appendADElement("M_Product_ID").append(": ").append(productName); } final PricingSystemId pricingSystemId = pricingCtx == null ? null : pricingCtx.getPricingSystemId(); final PriceListId priceListId = pricingCtx == null ? null : pricingCtx.getPriceListId(); if (priceListId != null) { final String priceListName = Services.get(IPriceListDAO.class).getPriceListName(priceListId); if (!sb.isEmpty()) { sb.append(", "); } sb.appendADElement("M_PriceList_ID").append(": ").append(priceListName); } else if (pricingSystemId != null) { final String pricingSystemName = Services.get(IPriceListDAO.class).getPricingSystemName(pricingSystemId); if (!sb.isEmpty()) { sb.append(", "); } sb.appendADElement("M_PricingSystem_ID").append(": ").append(pricingSystemName); } final BPartnerId bpartnerId = pricingCtx == null ? null : pricingCtx.getBPartnerId(); if (bpartnerId != null) { String bpartnerName = Services.get(IBPartnerBL.class).getBPartnerValueAndName(bpartnerId); if (!sb.isEmpty()) { sb.append(", "); } sb.appendADElement("C_BPartner_ID").append(": ").append(bpartnerName); } final CountryId countryId = pricingCtx == null ? null : pricingCtx.getCountryId(); if (countryId != null) { final ITranslatableString countryName = Services.get(ICountryDAO.class).getCountryNameById(countryId); if (!sb.isEmpty()) { sb.append(", "); } sb.appendADElement("C_Country_ID").append(": ").append(countryName); } final LocalDate priceDate = pricingCtx == null ? null : pricingCtx.getPriceDate(); if (priceDate != null) { if (!sb.isEmpty()) { sb.append(", "); } sb.appendADElement("Date").append(": ").appendDate(priceDate); } // sb.insertFirst(" - "); sb.insertFirstADMessage(AD_Message); return sb.build(); } }
1,626
340
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "unit/algo/algo_test.hpp" #include <eve/algo/transform.hpp> #include <eve/function/sqrt.hpp> #include <eve/algo/reverse.hpp> #include <eve/algo/swap_ranges.hpp> #include <eve/algo/fill.hpp> #include <eve/views/zip.hpp> TTS_CASE("eve.algo.transform different type works") { std::vector<int> in{1, 4, 9, 16}; std::vector<short> out; out.resize(4); std::vector<short> expected{1, 2, 3, 4}; eve::algo::transform_to(in, out, [](auto x) { // I know we support ints, it's a test auto doubles = eve::convert(x, eve::as<double>{}); return eve::sqrt(doubles); }); TTS_EQUAL(out, expected); // For completness out.clear(); out.resize(4); eve::algo::transform_to(in, out, eve::sqrt); TTS_EQUAL(out, expected); }; TTS_CASE("eve.algo.reverse_copy, different types") { std::vector<int> in {1, 2, 3, 4}; std::vector<short> out (in.size()); eve::algo::reverse_copy(in, out); std::vector<short> expected {4, 3, 2, 1}; TTS_EQUAL(out, expected); }; TTS_CASE("eve.algo.swap_ranges, different types") { std::vector<int> a { 1, 2, 3, 4}; std::vector<short> b { -1, -2, -3, -4}; eve::algo::swap_ranges(a, b); std::vector<int> expected_a { -1, -2, -3, -4}; std::vector<short> expected_b { 1, 2, 3, 4}; TTS_EQUAL(a, expected_a); TTS_EQUAL(b, expected_b); }; TTS_CASE("eve.algo.fill, tuples") { std::vector<int> a {1, 2, 3}; std::vector<std::uint8_t> b {1, 2, 3}; std::vector<double> c {1, 2, 3}; std::vector<int> expected_a{ 0, 0, 0 }; std::vector<std::uint8_t> expected_b{ 1, 1, 1 }; std::vector<double> expected_c{ 2.0, 2.0, 2.0 }; eve::algo::fill(eve::views::zip(a, b, c), kumi::tuple{0, std::uint8_t{1}, 2.0}); TTS_EQUAL(a, expected_a); TTS_EQUAL(b, expected_b); TTS_EQUAL(c, expected_c); };
911
532
import threading import time import pytest import torch from torchgpipe.microbatch import Batch from torchgpipe.stream import CPUStream from torchgpipe.worker import Task, spawn_workers class fake_device: """A test double for :class:`torch.device`. Every fake device is different with each other. """ type = 'fake' index = None def test_join_running_workers(): count = 0 def counter(): nonlocal count time.sleep(0.1) count += 1 return Batch(()) with spawn_workers([fake_device() for _ in range(10)]) as (in_queues, out_queues): def call_in_worker(i, f): task = Task(CPUStream, compute=f, finalize=None) in_queues[i].put(task) for i in range(10): call_in_worker(i, counter) # There's no nondeterminism because 'spawn_workers' joins all running # workers. assert count == 10 def test_join_running_workers_with_exception(): class ExpectedException(Exception): pass count = 0 def counter(): nonlocal count time.sleep(0.1) count += 1 return Batch(()) with pytest.raises(ExpectedException): with spawn_workers([fake_device() for _ in range(10)]) as (in_queues, out_queues): def call_in_worker(i, f): task = Task(CPUStream, compute=f, finalize=None) in_queues[i].put(task) for i in range(10): call_in_worker(i, counter) raise ExpectedException # There's no nondeterminism because only 1 task can be placed in input # queues. assert count == 10 def test_compute_multithreading(): """Task.compute should be executed on multiple threads.""" thread_ids = set() def log_thread_id(): thread_id = threading.current_thread().ident thread_ids.add(thread_id) return Batch(()) with spawn_workers([fake_device() for _ in range(2)]) as (in_queues, out_queues): for i in range(2): t = Task(CPUStream, compute=log_thread_id, finalize=None) in_queues[i].put(t) for i in range(2): out_queues[i].get() assert len(thread_ids) == 2 def test_compute_success(): """Task.compute returns (True, (task, batch)) on success.""" def _42(): return Batch(torch.tensor(42)) with spawn_workers([torch.device('cpu')]) as (in_queues, out_queues): t = Task(CPUStream, compute=_42, finalize=None) in_queues[0].put(t) ok, (task, batch) = out_queues[0].get() assert ok assert task is t assert isinstance(batch, Batch) assert batch[0].item() == 42 def test_compute_exception(): """Task.compute returns (False, exc_info) on failure.""" def zero_div(): 0/0 with spawn_workers([torch.device('cpu')]) as (in_queues, out_queues): t = Task(CPUStream, compute=zero_div, finalize=None) in_queues[0].put(t) ok, exc_info = out_queues[0].get() assert not ok assert isinstance(exc_info, tuple) assert issubclass(exc_info[0], ZeroDivisionError) @pytest.mark.parametrize('grad_mode', [True, False]) def test_grad_mode(grad_mode): def detect_grad_enabled(): x = torch.rand(1, requires_grad=torch.is_grad_enabled()) return Batch(x) with torch.set_grad_enabled(grad_mode): with spawn_workers([torch.device('cpu')]) as (in_queues, out_queues): task = Task(CPUStream, compute=detect_grad_enabled, finalize=None) in_queues[0].put(task) ok, (_, batch) = out_queues[0].get() assert ok assert batch[0].requires_grad == grad_mode def test_worker_per_device(): cpu = torch.device('cpu') cpu0 = torch.device('cpu', index=0) fake1 = fake_device() fake2 = fake_device() with spawn_workers([cpu, cpu, cpu0, fake1, fake2]) as (in_queues, out_queues): assert len(in_queues) == len(out_queues) == 5 # 0: cpu, 1: cpu, 2: cpu0 assert in_queues[0] is in_queues[1] is in_queues[2] assert out_queues[0] is out_queues[1] is out_queues[2] # 3: fake1, 4: fake2 assert in_queues[3] is not in_queues[4] assert out_queues[3] is not out_queues[4]
1,895
1,936
<reponame>AdronTech/maplab #include <random> #include <gtest/gtest.h> #include <maplab-common/test/testing-entrypoint.h> #include <maplab-common/test/testing-predicates.h> #include <vi-map/test/vi-map-generator.h> namespace map_optimization_legacy { class RemoveVertexEdgeTest : public testing::Test { protected: RemoveVertexEdgeTest() : map_(), generator_(map_, kRandomSeed) {} virtual void SetUp() { // Verify if constants make sense. static_assert( kNumRandomVertexIndex < kNumVertices, "Random vertex index should be smaller than the total " "number of vertices"); addPosegraph(); addLandmarks(); generator_.generateMap(); } void addPosegraph() { pose::Transformation T_G_V; pose::Transformation T_G_M; mission_ = generator_.createMission(T_G_M); vertices_.resize(kNumVertices); // Create first mission vertices. for (size_t i = 0; i < kNumVertices; ++i) { vertices_[i] = generator_.createVertex(mission_, T_G_V); } } void addLandmarks() { CHECK(!vertices_.empty()); // Just a random landmark position that will be visible from the // default vertex (keyframe) positions. Eigen::Vector3d p_G_fi(0, 0, 1); std::mt19937 gen(kRandomSeed); std::uniform_int_distribution<> dis(0, kNumVertices - 1); for (size_t i = 0; i < kNumLandmarks; ++i) { const size_t vertex_index = dis(gen); CHECK_LT(vertex_index, vertices_.size()); pose_graph::VertexIdList observer_vertices( vertices_.begin(), vertices_.end()); for (size_t j = 0; j < observer_vertices.size(); ++j) { if (observer_vertices[j] == vertices_[vertex_index]) { observer_vertices.erase(observer_vertices.begin() + j); break; } } generator_.createLandmark( p_G_fi, vertices_[vertex_index], observer_vertices); } } void addResource(size_t vertex_index) { CHECK_LT(vertex_index, vertices_.size()); vi_map::Vertex& vertex = map_.getVertex(vertices_[vertex_index]); backend::ResourceId resource_id; common::generateId(&resource_id); static constexpr size_t kFrameIndex = 0; vertex.addFrameResourceIdOfType( kFrameIndex, backend::ResourceType::kRawImage, resource_id); } void removeStoreLandmarksOfVertex(size_t vertex_index) { CHECK_LT(vertex_index, vertices_.size()); vi_map::Vertex& vertex = map_.getVertex(vertices_[vertex_index]); vi_map::LandmarkIdList store_landmarks; vertex.getStoredLandmarkIdList(&store_landmarks); for (const vi_map::LandmarkId& landmark_id : store_landmarks) { map_.removeLandmark(landmark_id); } } void removeObservedLandmarksOfVertex(size_t vertex_index) { CHECK_LT(vertex_index, vertices_.size()); vi_map::Vertex& vertex = map_.getVertex(vertices_[vertex_index]); vi_map::LandmarkId invalid_global_landmark_id; for (unsigned int frame_idx = 0; frame_idx < vertex.numFrames(); ++frame_idx) { vi_map::LandmarkIdList frame_landmark_ids; vertex.getFrameObservedLandmarkIds(frame_idx, &frame_landmark_ids); for (size_t keypoint_idx = 0; keypoint_idx < frame_landmark_ids.size(); ++keypoint_idx) { if (frame_landmark_ids[keypoint_idx].isValid()) { vi_map::Landmark& landmark = map_.getLandmark(frame_landmark_ids[keypoint_idx]); // Dereference on the landmark side. landmark.removeAllObservationsOfVertexAndFrame( vertices_[vertex_index], frame_idx); // Dereference on the vertex side. vertex.setObservedLandmarkId( frame_idx, keypoint_idx, invalid_global_landmark_id); } } } } void removeEdgesOfVertex(size_t vertex_index) { CHECK_LT(vertex_index, vertices_.size()); vi_map::Vertex& vertex = map_.getVertex(vertices_[vertex_index]); pose_graph::EdgeIdSet edges; vertex.getAllEdges(&edges); for (const pose_graph::EdgeId& edge_id : edges) { map_.removeEdge(edge_id); } } pose_graph::VertexIdList vertices_; vi_map::MissionId mission_; vi_map::VIMap map_; // Some random vertex in the middle of the posegraph. static constexpr size_t kNumRandomVertexIndex = 16; private: vi_map::VIMapGenerator generator_; static constexpr size_t kNumVertices = 30; static constexpr size_t kNumLandmarks = 300; static constexpr size_t kRandomSeed = 9; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; TEST_F(RemoveVertexEdgeTest, RemoveEdge) { pose_graph::EdgeIdList edges; map_.getAllEdgeIds(&edges); ASSERT_FALSE(edges.empty()); pose_graph::EdgeId edge_to_be_deleted = *edges.begin(); EXPECT_TRUE(map_.hasEdge(edge_to_be_deleted)); map_.removeEdge(edge_to_be_deleted); EXPECT_FALSE(map_.hasEdge(edge_to_be_deleted)); } TEST_F(RemoveVertexEdgeTest, RemoveVertex) { removeStoreLandmarksOfVertex(kNumRandomVertexIndex); removeObservedLandmarksOfVertex(kNumRandomVertexIndex); removeEdgesOfVertex(kNumRandomVertexIndex); EXPECT_TRUE(map_.hasVertex(vertices_[kNumRandomVertexIndex])); map_.removeVertex(vertices_[kNumRandomVertexIndex]); EXPECT_FALSE(map_.hasVertex(vertices_[kNumRandomVertexIndex])); } TEST_F(RemoveVertexEdgeTest, RemoveVertexWithEdge) { removeStoreLandmarksOfVertex(kNumRandomVertexIndex); removeObservedLandmarksOfVertex(kNumRandomVertexIndex); EXPECT_TRUE(map_.hasVertex(vertices_[kNumRandomVertexIndex])); EXPECT_DEATH(map_.removeVertex(vertices_[kNumRandomVertexIndex]), "edge"); } TEST_F(RemoveVertexEdgeTest, RemoveVertexWithLandmarks) { removeObservedLandmarksOfVertex(kNumRandomVertexIndex); removeEdgesOfVertex(kNumRandomVertexIndex); EXPECT_TRUE(map_.hasVertex(vertices_[kNumRandomVertexIndex])); EXPECT_DEATH( map_.removeVertex(vertices_[kNumRandomVertexIndex]), "landmarks"); } TEST_F(RemoveVertexEdgeTest, RemoveVertexWithLandmarkObservations) { removeStoreLandmarksOfVertex(kNumRandomVertexIndex); removeEdgesOfVertex(kNumRandomVertexIndex); EXPECT_TRUE(map_.hasVertex(vertices_[kNumRandomVertexIndex])); EXPECT_DEATH( map_.removeVertex(vertices_[kNumRandomVertexIndex]), "references"); } TEST_F(RemoveVertexEdgeTest, RemoveVertexWithResources) { removeStoreLandmarksOfVertex(kNumRandomVertexIndex); removeObservedLandmarksOfVertex(kNumRandomVertexIndex); removeEdgesOfVertex(kNumRandomVertexIndex); addResource(kNumRandomVertexIndex); EXPECT_TRUE(map_.hasVertex(vertices_[kNumRandomVertexIndex])); EXPECT_DEATH(map_.removeVertex(vertices_[kNumRandomVertexIndex]), "resource"); } } // namespace map_optimization_legacy MAPLAB_UNITTEST_ENTRYPOINT
2,628
930
# Import Module from tkinter import * from tkhtmlview import HTMLLabel from tkinter import ttk from tkinter import font as tkFont import requests from bs4 import BeautifulSoup import urllib3 import shutil # Function to save image to the users file system def saveImage(): file_name = search_box.get().replace(" ","") image_file = getImage() http = urllib3.PoolManager() with open(file_name, 'wb') as out: r = http.request('GET', image_file, preload_content=False) shutil.copyfileobj(r, out) # Function to scrape image source from bing def getImage(): search = search_box.get() url = "https://www.bing.com/images/search?q={}".format(search.replace(' ','?')) page = requests.get(url) # Start scraping resultant html data soup = BeautifulSoup(page.content, 'html.parser') images_div = soup.find('div',{'id':'mmComponent_images_2'}) images_ul = images_div.find('ul') image = images_ul.find("li") link = image.find('img').get('src') return link # Function to show image in the GUI def showImage(): link = getImage() str_value = '<img src="{}">'.format(link) my_label.set_html(str_value) # Create tkinter Object root = Tk() # Set Geomerty of window root.geometry("400x500") root.title("Image viewer and downloader") # Set styles style = ttk.Style() style.theme_use('alt') style.map('my.TButton', background=[('active','white')]) style.configure('my.TButton', font=('Helvetica', 16, 'bold')) style.configure('my.TButton', background='white') style.configure('my.TButton', foreground='orange') style.configure('my.TFrame', background='white') # Add labels and buttons my_label = HTMLLabel(root) search_box = Entry(root, font=("Helvetica 15"), bd = 2, width=60) search_box.pack(side = TOP, pady=5, padx=15, ipadx=5) search_btn = ttk.Button(text="Scrape Image!",command=showImage,style='my.TButton') search_btn.pack(side=TOP) save_btn = ttk.Button(text="Download Image!",command=saveImage,style='my.TButton') save_btn.pack(side=TOP) my_label.pack(pady=20, padx=20) # Execute Tkinter root.mainloop()
771
5,133
<reponame>Saljack/mapstruct /* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.bugs._955.dto; import java.util.HashMap; import java.util.Map; /** * * @author <NAME> */ public class SuperCar { private Map<String, Person> persons = new HashMap<String, Person>(); public Map<String, Person> getPersons() { return persons; } public void setPersons(Map<String, Person> persons) { this.persons = persons; } }
209
23,901
<filename>saccader/visual_attention/dram_test.py # coding=utf-8 # Copyright 2021 The Google Research 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. """Unit test for DRAM model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np import tensorflow.compat.v1 as tf from saccader.visual_attention import dram from saccader.visual_attention import dram_config class DramTest(tf.test.TestCase, parameterized.TestCase): def test_import(self): self.assertIsNotNone(dram) @parameterized.named_parameters(("training mode", True), ("inference mode", False)) def test_build(self, is_training): config = dram_config.get_config() num_times = 2 image_shape = (28, 28, 1) num_classes = 10 config.num_classes = num_classes config.num_units_rnn_layers = [10, 10,] config.num_times = num_times batch_size = 3 images = tf.constant( np.random.rand(*((batch_size,) + image_shape)), dtype=tf.float32) model = dram.DRAMNetwork(config) logits_t = model(images, num_times=num_times, is_training=is_training)[0] init_op = model.init_op self.evaluate(init_op) self.assertEqual((batch_size, num_classes), self.evaluate(logits_t[-1]).shape) if __name__ == "__main__": tf.test.main()
674
575
<gh_stars>100-1000 // 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. #ifndef IOS_CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_FACTORY_H_ #define IOS_CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_FACTORY_H_ #include <memory> #include "base/macros.h" #include "base/no_destructor.h" #include "components/keyed_service/ios/browser_state_keyed_service_factory.h" class ChromeBrowserState; namespace syncer { class ProfileSyncService; class SyncService; } // namespace syncer // Singleton that owns all SyncServices and associates them with // ChromeBrowserState. class ProfileSyncServiceFactory : public BrowserStateKeyedServiceFactory { public: static syncer::SyncService* GetForBrowserState( ChromeBrowserState* browser_state); static syncer::SyncService* GetForBrowserStateIfExists( ChromeBrowserState* browser_state); static syncer::ProfileSyncService* GetAsProfileSyncServiceForBrowserState( ChromeBrowserState* browser_state); static syncer::ProfileSyncService* GetAsProfileSyncServiceForBrowserStateIfExists( ChromeBrowserState* browser_state); static ProfileSyncServiceFactory* GetInstance(); private: friend class base::NoDestructor<ProfileSyncServiceFactory>; ProfileSyncServiceFactory(); ~ProfileSyncServiceFactory() override; // BrowserStateKeyedServiceFactory implementation. std::unique_ptr<KeyedService> BuildServiceInstanceFor( web::BrowserState* context) const override; }; #endif // IOS_CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_FACTORY_H_
503
892
{ "schema_version": "1.2.0", "id": "GHSA-93c3-hgqg-2fpr", "modified": "2021-12-09T00:01:36Z", "published": "2021-12-08T00:01:17Z", "aliases": [ "CVE-2021-37065" ], "details": "There is a Integer Overflow or Wraparound vulnerability in Huawei Smartphone.Successful exploitation of this vulnerability may lead to Confidentiality or Availability impacted.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37065" }, { "type": "WEB", "url": "https://device.harmonyos.com/en/docs/security/update/security-bulletins-202109-0000001196270727" } ], "database_specific": { "cwe_ids": [ "CWE-190" ], "severity": "CRITICAL", "github_reviewed": false } }
357
563
# Automatically generated by the Fast Binary Encoding compiler, do not modify! # https://github.com/chronoxor/FastBinaryEncoding # Source: FBE # Version: 1.8.0.0
51
1,305
<filename>src/org/example/source/javax/swing/PopupFactory.java /* * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing; import sun.awt.EmbeddedFrame; import sun.awt.OSInfo; import java.applet.Applet; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.security.AccessController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static javax.swing.ClientPropertyKey.PopupFactory_FORCE_HEAVYWEIGHT_POPUP; /** * <code>PopupFactory</code>, as the name implies, is used to obtain * instances of <code>Popup</code>s. <code>Popup</code>s are used to * display a <code>Component</code> above all other <code>Component</code>s * in a particular containment hierarchy. The general contract is that * once you have obtained a <code>Popup</code> from a * <code>PopupFactory</code>, you must invoke <code>hide</code> on the * <code>Popup</code>. The typical usage is: * <pre> * PopupFactory factory = PopupFactory.getSharedInstance(); * Popup popup = factory.getPopup(owner, contents, x, y); * popup.show(); * ... * popup.hide(); * </pre> * * @see Popup * * @since 1.4 */ public class PopupFactory { /** * The shared instanceof <code>PopupFactory</code> is per * <code>AppContext</code>. This is the key used in the * <code>AppContext</code> to locate the <code>PopupFactory</code>. */ private static final Object SharedInstanceKey = new StringBuffer("PopupFactory.SharedInstanceKey"); /** * Max number of items to store in any one particular cache. */ private static final int MAX_CACHE_SIZE = 5; /** * Key used to indicate a light weight popup should be used. */ static final int LIGHT_WEIGHT_POPUP = 0; /** * Key used to indicate a medium weight Popup should be used. */ static final int MEDIUM_WEIGHT_POPUP = 1; /* * Key used to indicate a heavy weight Popup should be used. */ static final int HEAVY_WEIGHT_POPUP = 2; /** * Default type of Popup to create. */ private int popupType = LIGHT_WEIGHT_POPUP; /** * Sets the <code>PopupFactory</code> that will be used to obtain * <code>Popup</code>s. * This will throw an <code>IllegalArgumentException</code> if * <code>factory</code> is null. * * @param factory Shared PopupFactory * @exception IllegalArgumentException if <code>factory</code> is null * @see #getPopup */ public static void setSharedInstance(PopupFactory factory) { if (factory == null) { throw new IllegalArgumentException("PopupFactory can not be null"); } SwingUtilities.appContextPut(SharedInstanceKey, factory); } /** * Returns the shared <code>PopupFactory</code> which can be used * to obtain <code>Popup</code>s. * * @return Shared PopupFactory */ public static PopupFactory getSharedInstance() { PopupFactory factory = (PopupFactory)SwingUtilities.appContextGet( SharedInstanceKey); if (factory == null) { factory = new PopupFactory(); setSharedInstance(factory); } return factory; } /** * Provides a hint as to the type of <code>Popup</code> that should * be created. */ void setPopupType(int type) { popupType = type; } /** * Returns the preferred type of Popup to create. */ int getPopupType() { return popupType; } /** * Creates a <code>Popup</code> for the Component <code>owner</code> * containing the Component <code>contents</code>. <code>owner</code> * is used to determine which <code>Window</code> the new * <code>Popup</code> will parent the <code>Component</code> the * <code>Popup</code> creates to. A null <code>owner</code> implies there * is no valid parent. <code>x</code> and * <code>y</code> specify the preferred initial location to place * the <code>Popup</code> at. Based on screen size, or other paramaters, * the <code>Popup</code> may not display at <code>x</code> and * <code>y</code>. * * @param owner Component mouse coordinates are relative to, may be null * @param contents Contents of the Popup * @param x Initial x screen coordinate * @param y Initial y screen coordinate * @exception IllegalArgumentException if contents is null * @return Popup containing Contents */ public Popup getPopup(Component owner, Component contents, int x, int y) throws IllegalArgumentException { if (contents == null) { throw new IllegalArgumentException( "Popup.getPopup must be passed non-null contents"); } int popupType = getPopupType(owner, contents, x, y); Popup popup = getPopup(owner, contents, x, y, popupType); if (popup == null) { // Didn't fit, force to heavy. popup = getPopup(owner, contents, x, y, HEAVY_WEIGHT_POPUP); } return popup; } /** * Returns the popup type to use for the specified parameters. */ private int getPopupType(Component owner, Component contents, int ownerX, int ownerY) { int popupType = getPopupType(); if (owner == null || invokerInHeavyWeightPopup(owner)) { popupType = HEAVY_WEIGHT_POPUP; } else if (popupType == LIGHT_WEIGHT_POPUP && !(contents instanceof JToolTip) && !(contents instanceof JPopupMenu)) { popupType = MEDIUM_WEIGHT_POPUP; } // Check if the parent component is an option pane. If so we need to // force a heavy weight popup in order to have event dispatching work // correctly. Component c = owner; while (c != null) { if (c instanceof JComponent) { if (((JComponent)c).getClientProperty( PopupFactory_FORCE_HEAVYWEIGHT_POPUP) == Boolean.TRUE) { popupType = HEAVY_WEIGHT_POPUP; break; } } c = c.getParent(); } return popupType; } /** * Obtains the appropriate <code>Popup</code> based on * <code>popupType</code>. */ private Popup getPopup(Component owner, Component contents, int ownerX, int ownerY, int popupType) { if (GraphicsEnvironment.isHeadless()) { return getHeadlessPopup(owner, contents, ownerX, ownerY); } switch(popupType) { case LIGHT_WEIGHT_POPUP: return getLightWeightPopup(owner, contents, ownerX, ownerY); case MEDIUM_WEIGHT_POPUP: return getMediumWeightPopup(owner, contents, ownerX, ownerY); case HEAVY_WEIGHT_POPUP: Popup popup = getHeavyWeightPopup(owner, contents, ownerX, ownerY); if ((AccessController.doPrivileged(OSInfo.getOSTypeAction()) == OSInfo.OSType.MACOSX) && (owner != null) && (EmbeddedFrame.getAppletIfAncestorOf(owner) != null)) { ((HeavyWeightPopup)popup).setCacheEnabled(false); } return popup; } return null; } /** * Creates a headless popup */ private Popup getHeadlessPopup(Component owner, Component contents, int ownerX, int ownerY) { return HeadlessPopup.getHeadlessPopup(owner, contents, ownerX, ownerY); } /** * Creates a light weight popup. */ private Popup getLightWeightPopup(Component owner, Component contents, int ownerX, int ownerY) { return LightWeightPopup.getLightWeightPopup(owner, contents, ownerX, ownerY); } /** * Creates a medium weight popup. */ private Popup getMediumWeightPopup(Component owner, Component contents, int ownerX, int ownerY) { return MediumWeightPopup.getMediumWeightPopup(owner, contents, ownerX, ownerY); } /** * Creates a heavy weight popup. */ private Popup getHeavyWeightPopup(Component owner, Component contents, int ownerX, int ownerY) { if (GraphicsEnvironment.isHeadless()) { return getMediumWeightPopup(owner, contents, ownerX, ownerY); } return HeavyWeightPopup.getHeavyWeightPopup(owner, contents, ownerX, ownerY); } /** * Returns true if the Component <code>i</code> inside a heavy weight * <code>Popup</code>. */ private boolean invokerInHeavyWeightPopup(Component i) { if (i != null) { Container parent; for(parent = i.getParent() ; parent != null ; parent = parent.getParent()) { if (parent instanceof Popup.HeavyWeightWindow) { return true; } } } return false; } /** * Popup implementation that uses a Window as the popup. */ private static class HeavyWeightPopup extends Popup { private static final Object heavyWeightPopupCacheKey = new StringBuffer("PopupFactory.heavyWeightPopupCache"); private volatile boolean isCacheEnabled = true; /** * Returns either a new or recycled <code>Popup</code> containing * the specified children. */ static Popup getHeavyWeightPopup(Component owner, Component contents, int ownerX, int ownerY) { Window window = (owner != null) ? SwingUtilities. getWindowAncestor(owner) : null; HeavyWeightPopup popup = null; if (window != null) { popup = getRecycledHeavyWeightPopup(window); } boolean focusPopup = false; if(contents != null && contents.isFocusable()) { if(contents instanceof JPopupMenu) { JPopupMenu jpm = (JPopupMenu) contents; Component popComps[] = jpm.getComponents(); for (Component popComp : popComps) { if (!(popComp instanceof MenuElement) && !(popComp instanceof JSeparator)) { focusPopup = true; break; } } } } if (popup == null || ((JWindow) popup.getComponent()) .getFocusableWindowState() != focusPopup) { if(popup != null) { // The recycled popup can't serve us well // dispose it and create new one popup._dispose(); } popup = new HeavyWeightPopup(); } popup.reset(owner, contents, ownerX, ownerY); if(focusPopup) { JWindow wnd = (JWindow) popup.getComponent(); wnd.setFocusableWindowState(true); // Set window name. We need this in BasicPopupMenuUI // to identify focusable popup window. wnd.setName("###focusableSwingPopup###"); } return popup; } /** * Returns a previously disposed heavy weight <code>Popup</code> * associated with <code>window</code>. This will return null if * there is no <code>HeavyWeightPopup</code> associated with * <code>window</code>. */ private static HeavyWeightPopup getRecycledHeavyWeightPopup(Window w) { synchronized (HeavyWeightPopup.class) { List<HeavyWeightPopup> cache; Map<Window, List<HeavyWeightPopup>> heavyPopupCache = getHeavyWeightPopupCache(); if (heavyPopupCache.containsKey(w)) { cache = heavyPopupCache.get(w); } else { return null; } if (cache.size() > 0) { HeavyWeightPopup r = cache.get(0); cache.remove(0); return r; } return null; } } /** * Returns the cache to use for heavy weight popups. Maps from * <code>Window</code> to a <code>List</code> of * <code>HeavyWeightPopup</code>s. */ private static Map<Window, List<HeavyWeightPopup>> getHeavyWeightPopupCache() { synchronized (HeavyWeightPopup.class) { Map<Window, List<HeavyWeightPopup>> cache = (Map<Window, List<HeavyWeightPopup>>)SwingUtilities.appContextGet( heavyWeightPopupCacheKey); if (cache == null) { cache = new HashMap<Window, List<HeavyWeightPopup>>(2); SwingUtilities.appContextPut(heavyWeightPopupCacheKey, cache); } return cache; } } /** * Recycles the passed in <code>HeavyWeightPopup</code>. */ private static void recycleHeavyWeightPopup(HeavyWeightPopup popup) { synchronized (HeavyWeightPopup.class) { List<HeavyWeightPopup> cache; Window window = SwingUtilities.getWindowAncestor( popup.getComponent()); Map<Window, List<HeavyWeightPopup>> heavyPopupCache = getHeavyWeightPopupCache(); if (window instanceof Popup.DefaultFrame || !window.isVisible()) { // If the Window isn't visible, we don't cache it as we // likely won't ever get a windowClosed event to clean up. // We also don't cache DefaultFrames as this indicates // there wasn't a valid Window parent, and thus we don't // know when to clean up. popup._dispose(); return; } else if (heavyPopupCache.containsKey(window)) { cache = heavyPopupCache.get(window); } else { cache = new ArrayList<HeavyWeightPopup>(); heavyPopupCache.put(window, cache); // Clean up if the Window is closed final Window w = window; w.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { List<HeavyWeightPopup> popups; synchronized(HeavyWeightPopup.class) { Map<Window, List<HeavyWeightPopup>> heavyPopupCache2 = getHeavyWeightPopupCache(); popups = heavyPopupCache2.remove(w); } if (popups != null) { for (int counter = popups.size() - 1; counter >= 0; counter--) { popups.get(counter)._dispose(); } } } }); } if(cache.size() < MAX_CACHE_SIZE) { cache.add(popup); } else { popup._dispose(); } } } /** * Enables or disables cache for current object. */ void setCacheEnabled(boolean enable) { isCacheEnabled = enable; } // // Popup methods // public void hide() { super.hide(); if (isCacheEnabled) { recycleHeavyWeightPopup(this); } else { this._dispose(); } } /** * As we recycle the <code>Window</code>, we don't want to dispose it, * thus this method does nothing, instead use <code>_dipose</code> * which will handle the disposing. */ void dispose() { } void _dispose() { super.dispose(); } } /** * ContainerPopup consolidates the common code used in the light/medium * weight implementations of <code>Popup</code>. */ private static class ContainerPopup extends Popup { /** Component we are to be added to. */ Component owner; /** Desired x location. */ int x; /** Desired y location. */ int y; public void hide() { Component component = getComponent(); if (component != null) { Container parent = component.getParent(); if (parent != null) { Rectangle bounds = component.getBounds(); parent.remove(component); parent.repaint(bounds.x, bounds.y, bounds.width, bounds.height); } } owner = null; } public void pack() { Component component = getComponent(); if (component != null) { component.setSize(component.getPreferredSize()); } } void reset(Component owner, Component contents, int ownerX, int ownerY) { if ((owner instanceof JFrame) || (owner instanceof JDialog) || (owner instanceof JWindow)) { // Force the content to be added to the layered pane, otherwise // we'll get an exception when adding to the RootPaneContainer. owner = ((RootPaneContainer)owner).getLayeredPane(); } super.reset(owner, contents, ownerX, ownerY); x = ownerX; y = ownerY; this.owner = owner; } boolean overlappedByOwnedWindow() { Component component = getComponent(); if(owner != null && component != null) { Window w = SwingUtilities.getWindowAncestor(owner); if (w == null) { return false; } Window[] ownedWindows = w.getOwnedWindows(); if(ownedWindows != null) { Rectangle bnd = component.getBounds(); for (Window window : ownedWindows) { if (window.isVisible() && bnd.intersects(window.getBounds())) { return true; } } } } return false; } /** * Returns true if popup can fit the screen and the owner's top parent. * It determines can popup be lightweight or mediumweight. */ boolean fitsOnScreen() { boolean result = false; Component component = getComponent(); if (owner != null && component != null) { int popupWidth = component.getWidth(); int popupHeight = component.getHeight(); Container parent = (Container) SwingUtilities.getRoot(owner); if (parent instanceof JFrame || parent instanceof JDialog || parent instanceof JWindow) { Rectangle parentBounds = parent.getBounds(); Insets i = parent.getInsets(); parentBounds.x += i.left; parentBounds.y += i.top; parentBounds.width -= i.left + i.right; parentBounds.height -= i.top + i.bottom; if (JPopupMenu.canPopupOverlapTaskBar()) { GraphicsConfiguration gc = parent.getGraphicsConfiguration(); Rectangle popupArea = getContainerPopupArea(gc); result = parentBounds.intersection(popupArea) .contains(x, y, popupWidth, popupHeight); } else { result = parentBounds .contains(x, y, popupWidth, popupHeight); } } else if (parent instanceof JApplet) { Rectangle parentBounds = parent.getBounds(); Point p = parent.getLocationOnScreen(); parentBounds.x = p.x; parentBounds.y = p.y; result = parentBounds.contains(x, y, popupWidth, popupHeight); } } return result; } Rectangle getContainerPopupArea(GraphicsConfiguration gc) { Rectangle screenBounds; Toolkit toolkit = Toolkit.getDefaultToolkit(); Insets insets; if(gc != null) { // If we have GraphicsConfiguration use it // to get screen bounds screenBounds = gc.getBounds(); insets = toolkit.getScreenInsets(gc); } else { // If we don't have GraphicsConfiguration use primary screen screenBounds = new Rectangle(toolkit.getScreenSize()); insets = new Insets(0, 0, 0, 0); } // Take insets into account screenBounds.x += insets.left; screenBounds.y += insets.top; screenBounds.width -= (insets.left + insets.right); screenBounds.height -= (insets.top + insets.bottom); return screenBounds; } } /** * Popup implementation that is used in headless environment. */ private static class HeadlessPopup extends ContainerPopup { static Popup getHeadlessPopup(Component owner, Component contents, int ownerX, int ownerY) { HeadlessPopup popup = new HeadlessPopup(); popup.reset(owner, contents, ownerX, ownerY); return popup; } Component createComponent(Component owner) { return new Panel(new BorderLayout()); } public void show() { } public void hide() { } } /** * Popup implementation that uses a JPanel as the popup. */ private static class LightWeightPopup extends ContainerPopup { private static final Object lightWeightPopupCacheKey = new StringBuffer("PopupFactory.lightPopupCache"); /** * Returns a light weight <code>Popup</code> implementation. If * the <code>Popup</code> needs more space that in available in * <code>owner</code>, this will return null. */ static Popup getLightWeightPopup(Component owner, Component contents, int ownerX, int ownerY) { LightWeightPopup popup = getRecycledLightWeightPopup(); if (popup == null) { popup = new LightWeightPopup(); } popup.reset(owner, contents, ownerX, ownerY); if (!popup.fitsOnScreen() || popup.overlappedByOwnedWindow()) { popup.hide(); return null; } return popup; } /** * Returns the cache to use for heavy weight popups. */ private static List<LightWeightPopup> getLightWeightPopupCache() { List<LightWeightPopup> cache = (List<LightWeightPopup>)SwingUtilities.appContextGet( lightWeightPopupCacheKey); if (cache == null) { cache = new ArrayList<LightWeightPopup>(); SwingUtilities.appContextPut(lightWeightPopupCacheKey, cache); } return cache; } /** * Recycles the LightWeightPopup <code>popup</code>. */ private static void recycleLightWeightPopup(LightWeightPopup popup) { synchronized (LightWeightPopup.class) { List<LightWeightPopup> lightPopupCache = getLightWeightPopupCache(); if (lightPopupCache.size() < MAX_CACHE_SIZE) { lightPopupCache.add(popup); } } } /** * Returns a previously used <code>LightWeightPopup</code>, or null * if none of the popups have been recycled. */ private static LightWeightPopup getRecycledLightWeightPopup() { synchronized (LightWeightPopup.class) { List<LightWeightPopup> lightPopupCache = getLightWeightPopupCache(); if (lightPopupCache.size() > 0) { LightWeightPopup r = lightPopupCache.get(0); lightPopupCache.remove(0); return r; } return null; } } // // Popup methods // public void hide() { super.hide(); Container component = (Container)getComponent(); component.removeAll(); recycleLightWeightPopup(this); } public void show() { Container parent = null; if (owner != null) { parent = (owner instanceof Container? (Container)owner : owner.getParent()); } // Try to find a JLayeredPane and Window to add for (Container p = parent; p != null; p = p.getParent()) { if (p instanceof JRootPane) { if (p.getParent() instanceof JInternalFrame) { continue; } parent = ((JRootPane)p).getLayeredPane(); // Continue, so that if there is a higher JRootPane, we'll // pick it up. } else if(p instanceof Window) { if (parent == null) { parent = p; } break; } else if (p instanceof JApplet) { // Painting code stops at Applets, we don't want // to add to a Component above an Applet otherwise // you'll never see it painted. break; } } Point p = SwingUtilities.convertScreenLocationToParent(parent, x, y); Component component = getComponent(); component.setLocation(p.x, p.y); if (parent instanceof JLayeredPane) { parent.add(component, JLayeredPane.POPUP_LAYER, 0); } else { parent.add(component); } } Component createComponent(Component owner) { JComponent component = new JPanel(new BorderLayout(), true); component.setOpaque(true); return component; } // // Local methods // /** * Resets the <code>Popup</code> to an initial state. */ void reset(Component owner, Component contents, int ownerX, int ownerY) { super.reset(owner, contents, ownerX, ownerY); JComponent component = (JComponent)getComponent(); component.setOpaque(contents.isOpaque()); component.setLocation(ownerX, ownerY); component.add(contents, BorderLayout.CENTER); contents.invalidate(); pack(); } } /** * Popup implementation that uses a Panel as the popup. */ private static class MediumWeightPopup extends ContainerPopup { private static final Object mediumWeightPopupCacheKey = new StringBuffer("PopupFactory.mediumPopupCache"); /** Child of the panel. The contents are added to this. */ private JRootPane rootPane; /** * Returns a medium weight <code>Popup</code> implementation. If * the <code>Popup</code> needs more space that in available in * <code>owner</code>, this will return null. */ static Popup getMediumWeightPopup(Component owner, Component contents, int ownerX, int ownerY) { MediumWeightPopup popup = getRecycledMediumWeightPopup(); if (popup == null) { popup = new MediumWeightPopup(); } popup.reset(owner, contents, ownerX, ownerY); if (!popup.fitsOnScreen() || popup.overlappedByOwnedWindow()) { popup.hide(); return null; } return popup; } /** * Returns the cache to use for medium weight popups. */ private static List<MediumWeightPopup> getMediumWeightPopupCache() { List<MediumWeightPopup> cache = (List<MediumWeightPopup>)SwingUtilities.appContextGet( mediumWeightPopupCacheKey); if (cache == null) { cache = new ArrayList<MediumWeightPopup>(); SwingUtilities.appContextPut(mediumWeightPopupCacheKey, cache); } return cache; } /** * Recycles the MediumWeightPopup <code>popup</code>. */ private static void recycleMediumWeightPopup(MediumWeightPopup popup) { synchronized (MediumWeightPopup.class) { List<MediumWeightPopup> mediumPopupCache = getMediumWeightPopupCache(); if (mediumPopupCache.size() < MAX_CACHE_SIZE) { mediumPopupCache.add(popup); } } } /** * Returns a previously used <code>MediumWeightPopup</code>, or null * if none of the popups have been recycled. */ private static MediumWeightPopup getRecycledMediumWeightPopup() { synchronized (MediumWeightPopup.class) { List<MediumWeightPopup> mediumPopupCache = getMediumWeightPopupCache(); if (mediumPopupCache.size() > 0) { MediumWeightPopup r = mediumPopupCache.get(0); mediumPopupCache.remove(0); return r; } return null; } } // // Popup // public void hide() { super.hide(); rootPane.getContentPane().removeAll(); recycleMediumWeightPopup(this); } public void show() { Component component = getComponent(); Container parent = null; if (owner != null) { parent = owner.getParent(); } /* Find the top level window, if it has a layered pane, add to that, otherwise add to the window. */ while (!(parent instanceof Window || parent instanceof Applet) && (parent!=null)) { parent = parent.getParent(); } // Set the visibility to false before adding to workaround a // bug in Solaris in which the Popup gets added at the wrong // location, which will result in a mouseExit, which will then // result in the ToolTip being removed. if (parent instanceof RootPaneContainer) { parent = ((RootPaneContainer)parent).getLayeredPane(); Point p = SwingUtilities.convertScreenLocationToParent(parent, x, y); component.setVisible(false); component.setLocation(p.x, p.y); parent.add(component, JLayeredPane.POPUP_LAYER, 0); } else { Point p = SwingUtilities.convertScreenLocationToParent(parent, x, y); component.setLocation(p.x, p.y); component.setVisible(false); parent.add(component); } component.setVisible(true); } Component createComponent(Component owner) { Panel component = new MediumWeightComponent(); rootPane = new JRootPane(); // NOTE: this uses setOpaque vs LookAndFeel.installProperty as // there is NO reason for the RootPane not to be opaque. For // painting to work the contentPane must be opaque, therefor the // RootPane can also be opaque. rootPane.setOpaque(true); component.add(rootPane, BorderLayout.CENTER); return component; } /** * Resets the <code>Popup</code> to an initial state. */ void reset(Component owner, Component contents, int ownerX, int ownerY) { super.reset(owner, contents, ownerX, ownerY); Component component = getComponent(); component.setLocation(ownerX, ownerY); rootPane.getContentPane().add(contents, BorderLayout.CENTER); contents.invalidate(); component.validate(); pack(); } // This implements SwingHeavyWeight so that repaints on it // are processed by the RepaintManager and SwingPaintEventDispatcher. private static class MediumWeightComponent extends Panel implements SwingHeavyWeight { MediumWeightComponent() { super(new BorderLayout()); } } } }
17,181
8,805
<reponame>rudylee/expo //---------------------------------------------------------------------------// // Copyright (c) 2013 <NAME> <<EMAIL>> // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://boostorg.github.com/compute for more information. //---------------------------------------------------------------------------// #ifndef BOOST_COMPUTE_FUNCTIONAL_FIELD_HPP #define BOOST_COMPUTE_FUNCTIONAL_FIELD_HPP #include <string> namespace boost { namespace compute { namespace detail { template<class T, class Arg> struct invoked_field { typedef T result_type; invoked_field(const Arg &arg, const std::string &field) : m_arg(arg), m_field(field) { } Arg m_arg; std::string m_field; }; } // end detail namespace /// Returns the named field from a value. /// /// The template-type \c T specifies the field's value type. Note /// that the value type must match the actual type of the field /// otherwise runtime compilation or logic errors may occur. /// /// For example, to access the \c second field in a /// \c std::pair<int, float> object: /// \code /// field<float>("second"); /// \endcode /// /// This can also be used with vector types to access individual /// components as well as perform swizzle operations. /// /// For example, to access the first and third components of an /// \c int vector type (e.g. \c int4): /// \code /// field<int2_>("xz"); /// \endcode /// /// \see \ref get "get<N>" template<class T> class field { public: /// Result type. typedef T result_type; /// Creates a new field functor with \p field. field(const std::string &field) : m_field(field) { } /// \internal_ template<class Arg> detail::invoked_field<T, Arg> operator()(const Arg &arg) const { return detail::invoked_field<T, Arg>(arg, m_field); } private: std::string m_field; }; } // end compute namespace } // end boost namespace #endif // BOOST_COMPUTE_FUNCTIONAL_FIELD_HPP
795
5,169
<gh_stars>1000+ { "name": "CLHelper", "version": "1.0.2", "summary": "A Classic way to manage Core Location Jobs", "description": "'CLHelper is a helper file which will help in managing all your Core Location related task in a neat way with closures.'", "homepage": "https://github.com/greenSyntax/CLHelper", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/greenSyntax/CLHelper.git", "tag": "1.0.2" }, "social_media_url": "https://twitter.com/greenSyntax", "platforms": { "ios": "9.0" }, "source_files": "CLHelper/Classes/**/*" }
255
2,151
<filename>chrome/browser/installable/installable_data.h // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_INSTALLABLE_INSTALLABLE_DATA_H_ #define CHROME_BROWSER_INSTALLABLE_INSTALLABLE_DATA_H_ #include "chrome/browser/installable/installable_logging.h" #include "third_party/blink/public/common/manifest/manifest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "url/gurl.h" // This struct is passed to an InstallableCallback when the InstallableManager // has finished working. Each reference is owned by InstallableManager, and // callers should copy any objects which they wish to use later. Non-requested // fields will be set to null, empty, or false. struct InstallableData { InstallableData(InstallableStatusCode error_code, GURL manifest_url, const blink::Manifest* manifest, GURL primary_icon_url, const SkBitmap* primary_icon, GURL badge_icon_url, const SkBitmap* badge_icon, bool valid_manifest, bool has_worker); ~InstallableData(); // NO_ERROR_DETECTED if there were no issues. const InstallableStatusCode error_code = NO_ERROR_DETECTED; // Empty if the site has no <link rel="manifest"> tag. const GURL manifest_url; // Empty if the site has an unparseable manifest. const blink::Manifest* manifest; // Empty if no primary_icon was requested. const GURL primary_icon_url; // nullptr if the most appropriate primary icon couldn't be determined or // downloaded. The underlying primary icon is owned by the InstallableManager; // clients must copy the bitmap if they want to to use it. If // valid_primary_icon was true and a primary icon could not be retrieved, the // reason will be in error_code. const SkBitmap* primary_icon; // Empty if no badge_icon was requested. const GURL badge_icon_url; // nullptr if the most appropriate badge icon couldn't be determined or // downloaded. The underlying badge icon is owned by the InstallableManager; // clients must copy the bitmap if they want to to use it. Since the badge // icon is optional, no error code is set if it cannot be fetched, and clients // specifying valid_badge_icon must check that the bitmap exists before using // it. const SkBitmap* badge_icon; // true if the site has a viable web app manifest. If valid_manifest or // has_worker was true and the site isn't installable, the reason will be in // error_code. const bool valid_manifest = false; // true if the site has a service worker with a fetch handler. If has_worker // was true and the site isn't installable, the reason will be in error_code. const bool has_worker = false; }; using InstallableCallback = base::Callback<void(const InstallableData&)>; #endif // CHROME_BROWSER_INSTALLABLE_INSTALLABLE_DATA_H_
971
9,959
package com.sun.tools.javac.parser; import java.nio.CharBuffer; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; public class JavaTokenizer { // used before java 16 protected UnicodeReader reader; // used before java 16 protected JavaTokenizer(ScannerFactory fac, UnicodeReader reader) { } public com.sun.tools.javac.parser.Tokens.Token readToken() { return null; } protected Comment processComment(int pos, int endPos, CommentStyle style) { return null; } // used in java 16 protected JavaTokenizer(ScannerFactory fac, char[] buf, int inputLength) { } // used in java 16 protected JavaTokenizer(ScannerFactory fac, CharBuffer buf) { } // introduced in java 16 protected int position() { return -1; } }
265
628
def copy_files(src, target_node, parent=None, name=None): """Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """ assert not parent or not parent.is_file, 'Parent must be a folder' renaming = src.name != name cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region and most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent attach_versions(cloned, fileversions[1:], src) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() attach_versions(cloned, [new_fileversion], src) else: attach_versions(cloned, src.versions.all(), src) if renaming: latest_version = cloned.versions.first() node_file_version = latest_version.get_basefilenode_version(cloned) # If this is a copy and a rename, update the name on the through table node_file_version.version_name = cloned.name node_file_version.save() # copy over file metadata records if cloned.provider == 'osfstorage': for record in cloned.records.all(): record.metadata = src.records.get(schema__name=record.schema.name).metadata record.save() if not src.is_file: for child in src.children: copy_files(child, target_node, parent=cloned) return cloned def attach_versions(file, versions_list, src=None): """ Loops through all versions in the versions list and attaches them to the file. Fetches the name associated with the versions on the original src, if copying. """ for version in versions_list: original_version = version.get_basefilenode_version(src) name = original_version.version_name if original_version else None file.add_version(version, name)
977
14,668
<reponame>chromium/chromium // Copyright 2017 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 "components/open_from_clipboard/clipboard_recent_content_generic.h" #include <string> #include "base/bind.h" #include "base/strings/string_util.h" #include "build/build_config.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/data_transfer_policy/data_transfer_endpoint.h" #include "url/url_util.h" #if defined(OS_ANDROID) #include "ui/base/clipboard/clipboard_android.h" #endif namespace { // Schemes appropriate for suggestion by ClipboardRecentContent. const char* kAuthorizedSchemes[] = { url::kAboutScheme, url::kDataScheme, url::kHttpScheme, url::kHttpsScheme, // TODO(mpearson): add support for chrome:// URLs. Right now the scheme // for that lives in content and is accessible via // GetEmbedderRepresentationOfAboutScheme() or content::kChromeUIScheme // TODO(mpearson): when adding desktop support, add kFileScheme, kFtpScheme. }; void OnGetRecentImageFromClipboard( ClipboardRecentContent::GetRecentImageCallback callback, const std::vector<uint8_t>& png_data) { if (png_data.empty()) { std::move(callback).Run(absl::nullopt); return; } std::move(callback).Run( gfx::Image::CreateFrom1xPNGBytes(png_data.data(), png_data.size())); } bool HasRecentURLFromClipboard() { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::DataTransferEndpoint data_dst = ui::DataTransferEndpoint( ui::EndpointType::kDefault, /*notify_if_restricted=*/false); return clipboard->IsFormatAvailable(ui::ClipboardFormatType::UrlType(), ui::ClipboardBuffer::kCopyPaste, &data_dst); } bool HasRecentTextFromClipboard() { ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::DataTransferEndpoint data_dst = ui::DataTransferEndpoint( ui::EndpointType::kDefault, /*notify_if_restricted=*/false); return clipboard->IsFormatAvailable(ui::ClipboardFormatType::PlainTextType(), ui::ClipboardBuffer::kCopyPaste, &data_dst); } } // namespace ClipboardRecentContentGeneric::ClipboardRecentContentGeneric() = default; ClipboardRecentContentGeneric::~ClipboardRecentContentGeneric() = default; absl::optional<GURL> ClipboardRecentContentGeneric::GetRecentURLFromClipboard() { if (GetClipboardContentAge() > MaximumAgeOfClipboard()) return absl::nullopt; // Get and clean up the clipboard before processing. std::string gurl_string; ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); ui::DataTransferEndpoint data_dst = ui::DataTransferEndpoint( ui::EndpointType::kDefault, /*notify_if_restricted=*/false); #if defined(OS_ANDROID) clipboard->ReadBookmark(&data_dst, nullptr, &gurl_string); #else clipboard->ReadAsciiText(ui::ClipboardBuffer::kCopyPaste, &data_dst, &gurl_string); #endif // #if defined(OS_ANDROID) base::TrimWhitespaceASCII(gurl_string, base::TrimPositions::TRIM_ALL, &gurl_string); // Interpret the clipboard as a URL if possible. GURL url; // If there is mid-string whitespace, don't attempt to interpret the string // as a URL. (Otherwise gurl will happily try to convert // "http://example.com extra words" into "http://example.com%20extra%20words", // which is not likely to be a useful or intended destination.) if (gurl_string.find_first_of(base::kWhitespaceASCII) != std::string::npos) return absl::nullopt; if (!gurl_string.empty()) { url = GURL(gurl_string); } else { // Fall back to unicode / UTF16, as some URLs may use international domain // names, not punycode. std::u16string gurl_string16; clipboard->ReadText(ui::ClipboardBuffer::kCopyPaste, &data_dst, &gurl_string16); base::TrimWhitespace(gurl_string16, base::TrimPositions::TRIM_ALL, &gurl_string16); if (gurl_string16.find_first_of(base::kWhitespaceUTF16) != std::string::npos) return absl::nullopt; if (!gurl_string16.empty()) url = GURL(gurl_string16); } if (!url.is_valid() || !IsAppropriateSuggestion(url)) { return absl::nullopt; } return url; } absl::optional<std::u16string> ClipboardRecentContentGeneric::GetRecentTextFromClipboard() { if (GetClipboardContentAge() > MaximumAgeOfClipboard()) return absl::nullopt; std::u16string text_from_clipboard; ui::DataTransferEndpoint data_dst = ui::DataTransferEndpoint( ui::EndpointType::kDefault, /*notify_if_restricted=*/false); ui::Clipboard::GetForCurrentThread()->ReadText( ui::ClipboardBuffer::kCopyPaste, &data_dst, &text_from_clipboard); base::TrimWhitespace(text_from_clipboard, base::TrimPositions::TRIM_ALL, &text_from_clipboard); if (text_from_clipboard.empty()) { return absl::nullopt; } return text_from_clipboard; } void ClipboardRecentContentGeneric::GetRecentImageFromClipboard( GetRecentImageCallback callback) { if (GetClipboardContentAge() > MaximumAgeOfClipboard()) return; ui::DataTransferEndpoint data_dst = ui::DataTransferEndpoint( ui::EndpointType::kDefault, /*notify_if_restricted=*/false); ui::Clipboard::GetForCurrentThread()->ReadPng( ui::ClipboardBuffer::kCopyPaste, &data_dst, base::BindOnce(&OnGetRecentImageFromClipboard, std::move(callback))); } absl::optional<std::set<ClipboardContentType>> ClipboardRecentContentGeneric::GetCachedClipboardContentTypes() { if (GetClipboardContentAge() > MaximumAgeOfClipboard()) { return absl::nullopt; } std::set<ClipboardContentType> clipboard_content_types; if (HasRecentURLFromClipboard()) { clipboard_content_types.insert(ClipboardContentType::URL); } if (HasRecentTextFromClipboard()) { clipboard_content_types.insert(ClipboardContentType::Text); } if (HasRecentImageFromClipboard()) { clipboard_content_types.insert(ClipboardContentType::Image); } return clipboard_content_types; } bool ClipboardRecentContentGeneric::HasRecentImageFromClipboard() { if (GetClipboardContentAge() > MaximumAgeOfClipboard()) return false; ui::DataTransferEndpoint data_dst = ui::DataTransferEndpoint( ui::EndpointType::kDefault, /*notify_if_restricted=*/false); return ui::Clipboard::GetForCurrentThread()->IsFormatAvailable( ui::ClipboardFormatType::PngType(), ui::ClipboardBuffer::kCopyPaste, &data_dst); } void ClipboardRecentContentGeneric::HasRecentContentFromClipboard( std::set<ClipboardContentType> types, HasDataCallback callback) { std::set<ClipboardContentType> matching_types; if (GetClipboardContentAge() > MaximumAgeOfClipboard()) { std::move(callback).Run(matching_types); return; } for (ClipboardContentType type : types) { switch (type) { case ClipboardContentType::URL: if (HasRecentURLFromClipboard()) { matching_types.insert(ClipboardContentType::URL); } break; case ClipboardContentType::Text: if (HasRecentTextFromClipboard()) { matching_types.insert(ClipboardContentType::Text); } break; case ClipboardContentType::Image: if (HasRecentImageFromClipboard()) { matching_types.insert(ClipboardContentType::Image); } break; } } std::move(callback).Run(matching_types); } void ClipboardRecentContentGeneric::GetRecentURLFromClipboard( GetRecentURLCallback callback) { std::move(callback).Run(GetRecentURLFromClipboard()); } void ClipboardRecentContentGeneric::GetRecentTextFromClipboard( GetRecentTextCallback callback) { std::move(callback).Run(GetRecentTextFromClipboard()); } base::TimeDelta ClipboardRecentContentGeneric::GetClipboardContentAge() const { const base::Time last_modified_time = ui::Clipboard::GetForCurrentThread()->GetLastModifiedTime(); const base::Time now = base::Time::Now(); // In case of system clock change, assume the last modified time is now. // (Don't return a negative age, i.e., a time in the future.) if (last_modified_time > now) return base::TimeDelta(); return now - last_modified_time; } void ClipboardRecentContentGeneric::SuppressClipboardContent() { // User cleared the user data. The pasteboard entry must be removed from the // omnibox list. Do this by pretending the current clipboard is ancient, // not recent. ui::Clipboard::GetForCurrentThread()->ClearLastModifiedTime(); } void ClipboardRecentContentGeneric::ClearClipboardContent() { ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardBuffer::kCopyPaste); } // static bool ClipboardRecentContentGeneric::IsAppropriateSuggestion(const GURL& url) { // Check to make sure it's a scheme we're willing to suggest. for (const auto* authorized_scheme : kAuthorizedSchemes) { if (url.SchemeIs(authorized_scheme)) return true; } // Check if the schemes is an application-defined scheme. std::vector<std::string> standard_schemes = url::GetStandardSchemes(); for (const auto& standard_scheme : standard_schemes) { if (url.SchemeIs(standard_scheme)) return true; } // Not a scheme we're allowed to return. return false; }
3,507
5,939
<reponame>xuwei-k/finagle package com.twitter.finagle.example.java.http; import com.twitter.finagle.Service; import com.twitter.finagle.SimpleFilter; import com.twitter.finagle.http.Request; import com.twitter.finagle.http.Response; import com.twitter.finagle.http.Status; import com.twitter.util.ExceptionalFunction; import com.twitter.util.Future; /** * A simple Finagle filter that intercepts Exceptions and converts them to a more comprehensible HTTP Response. */ public final class HandleErrors extends SimpleFilter<Request, Response> { @Override public Future<Response> apply(Request req, Service<Request, Response> service) { return service.apply(req).handle(new ExceptionalFunction<Throwable, Response>() { @Override public Response applyE(Throwable in) { Response resp = Response.apply(); if (in instanceof NumberFormatException) { resp.status(Status.BadRequest()); resp.setContentString(in.getMessage()); return resp; } resp.status(Status.InternalServerError()); resp.setContentString(in.getMessage()); return resp; } }); } }
502
5,169
<gh_stars>1000+ { "name": "Visibility", "version": "1.0.0", "summary": "Handle a view visibility in the window", "description": "`Visibility` makes it easy to determine if the view in the window is visible.", "homepage": "https://github.com/darquro/Visibility", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "darquro": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/darquro/Visibility.git", "tag": "1.0.0" }, "source_files": "Visibility/**/*.{h,m,swift}", "swift_version": "4.1" }
247
724
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # noqa import numpy as np # noqa from pandas_ml import ConfusionMatrix # noqa import itertools # noqa def plot_confusion_matrix(cm, classes, title, normalize=False, cmap=plt.cm.Oranges, path="confusion_matrix.png"): """ This function plots the confusion matrix. Normalization can be applied by setting `normalize=True`. 'cmap' controls the color plot. colors: https://matplotlib.org/1.3.1/examples/color/colormaps_reference.html :param cm: confusion matrix :type cm: np array :param classes: number of classes :type classes: int :param title: image title :type title: str :param cmap: plt color map :type cmap: plt.cm :param path: path to save image :type path: str """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.figure(figsize=(9, 9)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title, fontsize=24, fontweight='bold') plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label', fontweight='bold') plt.xlabel('Predicted label', fontweight='bold') plt.savefig(path) def plotconfusion(truth, predictions, path, label_dict, classes): """ This function plots the confusion matrix and also prints useful statistics. :param truth: true labels :type truth: np array :param predictions: model predictions :type predictions: np array :param path: path to save image :type path: str :param label_dict: dict to transform int to str :type label_dict: dict :param classes: number of classes :type classes: int """ acc = np.array(truth) == np.array(predictions) size = float(acc.shape[0]) acc = np.sum(acc.astype("int32")) / size truth = [label_dict[i] for i in truth] predictions = [label_dict[i] for i in predictions] cm = ConfusionMatrix(truth, predictions) cm_array = cm.to_array() cm_diag = np.diag(cm_array) sizes_per_cat = [] for n in range(cm_array.shape[0]): sizes_per_cat.append(np.sum(cm_array[n])) sizes_per_cat = np.array(sizes_per_cat) sizes_per_cat = sizes_per_cat.astype(np.float32) ** -1 recall = np.multiply(cm_diag, sizes_per_cat) print("\nRecall:{}".format(recall)) print("\nRecall stats: mean = {0:.6f}, std = {1:.6f}\n".format(np.mean(recall), # noqa np.std(recall))) # noqa title = "Confusion matrix of {0} examples\n accuracy = {1:.6f}".format(int(size), # noqa acc) plot_confusion_matrix(cm_array, classes, title=title, path=path) cm.print_stats()
1,509
2,027
<filename>test/analytics.py class FakeMixpanel(object): def track(*args, **kwargs): pass def init_app(app): return FakeMixpanel()
58
921
<gh_stars>100-1000 // Copyright (c) 2017-2020 <NAME> <<EMAIL>> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.flex.psi.index; import com.intellij.psi.stubs.StubIndexKey; import com.vladsch.md.nav.flex.psi.FlexmarkExampleOption; import com.vladsch.md.nav.psi.index.MdStubIndexExtension; import org.jetbrains.annotations.NotNull; public class FlexmarkExampleOptionIndex extends MdStubIndexExtension<FlexmarkExampleOption> { public static final StubIndexKey<String, FlexmarkExampleOption> KEY = StubIndexKey.createIndexKey("markdown.flexmark.example.option.index"); private static final FlexmarkExampleOptionIndex ourInstance = new FlexmarkExampleOptionIndex(); public static FlexmarkExampleOptionIndex getInstance() { return ourInstance; } @NotNull public StubIndexKey<String, FlexmarkExampleOption> getKey() { return KEY; } }
314
302
#ifndef GRIDTABLEHEADERMODEL_H #define GRIDTABLEHEADERMODEL_H #include "tableheaderitem.h" #include <QAbstractTableModel> class GridTableHeaderModel : public QAbstractTableModel { Q_OBJECT public: enum HeaderRole { ColumnSpanRole = Qt::UserRole + 1, RowSpanRole, }; GridTableHeaderModel(int row, int column, QObject *parent = 0); ~GridTableHeaderModel(); QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; Qt::ItemFlags flags(const QModelIndex &index) const; QVariant data(const QModelIndex &index, int role) const; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); private: int _row; int _column; TableHeaderItem *rootItem; }; #endif // GRIDTABLEHEADERMODEL_H
336
370
<filename>ndbench-web/src/test/java/com/test/Log4jConfigurationTest.java package com.test; import org.apache.commons.io.FileUtils; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; public class Log4jConfigurationTest { static { try { File temp = File.createTempFile("temp-file-name", ".log"); temp.deleteOnExit(); FileUtils.writeStringToFile(temp, "log4j.logger.com.test=TRACE"); System.setProperty( "log4j.configuration", "file:///" + temp.getAbsolutePath()); } catch (IOException e) { throw new RuntimeException(e); } } @Test public void verifyLog4jPropertiesConfigurationWorksAsExpected() throws Exception { final Logger logger = LoggerFactory.getLogger(Log4jConfigurationTest .class); if (! logger.isTraceEnabled()) { throw new RuntimeException("slf4j seems not to be bound to a log4j implementation. check depdendencies!"); } } }
468
367
/******************************************************************************* * Copyright 2014 <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.github.katjahahn.tools.sigscanner; import static org.testng.Assert.*; import java.io.File; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.annotations.Test; import com.github.katjahahn.TestreportsReader; public class Jar2ExeScannerTest { @SuppressWarnings("unused") private static final Logger logger = LogManager .getLogger(Jar2ExeScannerTest.class.getName()); @Test public void scanResultTest() { Jar2ExeScanner scanner = new Jar2ExeScanner(new File( TestreportsReader.RESOURCE_DIR + "/testfiles/launch4jwrapped.exe")); List<MatchedSignature> result = scanner.scan(); assertTrue(contains(result, "[Launch4j]")); } private boolean contains(List<MatchedSignature> siglist, String name) { for (MatchedSignature sig : siglist) { if (sig.getName().equals(name)) return true; } return false; } }
582
346
<reponame>rhyep/Python_tutorials public class EqualityOperators { public static void main(String[] args) { System.out.println( 2 == 2 ); } }
52
933
<filename>3rdparty/openssl-win32/openssl/txt_db.h #include "../../openssl/crypto/txt_db/txt_db.h"
44
622
/* * Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. * See LICENSE in the project root for license information. */ package com.linkedin.flashback.matchrules; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Transform that returns a map containing only the keys absent from the blacklist * @author dvinegra */ public class MatchRuleBlacklistTransform implements MatchRuleMapTransform { private final Set<String> _blackList; public MatchRuleBlacklistTransform(Set<String> blackList) { if (blackList != null) { _blackList = blackList; } else { _blackList = Collections.EMPTY_SET; } } @Override public Map<String, String> transform(Map<String, String> map) { return map.keySet().stream().filter(k -> !_blackList.contains(k)) .collect(Collectors.toMap(k -> k, k -> map.get(k), (k, v) -> { throw new RuntimeException("Duplicate key " + k); }, LinkedHashMap::new)); } }
359
526
/* SPDX-License-Identifier: Apache 2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.viewservices.serverauthor.initialization; import org.odpi.openmetadata.adminservices.configuration.registration.ViewServiceDescription; import org.odpi.openmetadata.commonservices.multitenant.OMVSServiceInstanceHandler; import org.odpi.openmetadata.frameworks.connectors.ffdc.InvalidParameterException; import org.odpi.openmetadata.frameworks.connectors.ffdc.PropertyServerException; import org.odpi.openmetadata.frameworks.connectors.ffdc.UserNotAuthorizedException; import org.odpi.openmetadata.viewservices.serverauthor.handlers.ServerAuthorViewHandler; /** * ServerAuthorViewInstanceHandler retrieves information from the instance map for the * view service instances. The instance map is thread-safe. Instances are added * and removed by the ServerAuthorViewAdmin class. */ public class ServerAuthorViewInstanceHandler extends OMVSServiceInstanceHandler { /** * Default constructor registers the view service */ public ServerAuthorViewInstanceHandler() { super(ViewServiceDescription.SERVER_AUTHOR.getViewServiceName()); ServerAuthorViewRegistration.registerViewService(); } /** * The getServerAuthorViewHandler method retrieves the handler from the ServerAuthorViewServicesInstance and returns it. * * @param userId the user performing the operation * @param serverName the name of the server running the view-service * @param serviceOperationName the operation to be performed * @return ServerAuthorViewHandler * @throws InvalidParameterException - the server name is not recognized * @throws UserNotAuthorizedException - the user id not permitted to perform the requested operation * @throws PropertyServerException - the service name is not known - indicating a logic error */ public ServerAuthorViewHandler getServerAuthorViewHandler(String userId, String serverName, String serviceOperationName) throws InvalidParameterException, UserNotAuthorizedException, PropertyServerException { /* * Get the ServerAuthorViewServicesInstance. This is an instance associated with the UI servername (tenant). */ ServerAuthorViewServicesInstance instance = (ServerAuthorViewServicesInstance) super.getServerServiceInstance(userId, serverName, serviceOperationName); if (instance != null) { return instance.getServerAuthorViewHandler(); } return null; } }
1,008
582
// Copyright (C) 2010-2016 <NAME> // Distributed under the MIT license, see the LICENSE file for details. #ifndef CHROMAPRINT_AUDIO_PROCESSOR_H_ #define CHROMAPRINT_AUDIO_PROCESSOR_H_ #include "utils.h" #include "audio_consumer.h" #include <vector> struct AVResampleContext; namespace chromaprint { class AudioProcessor : public AudioConsumer { public: AudioProcessor(int sample_rate, AudioConsumer *consumer); virtual ~AudioProcessor(); int target_sample_rate() const { return m_target_sample_rate; } void set_target_sample_rate(int sample_rate) { m_target_sample_rate = sample_rate; } AudioConsumer *consumer() const { return m_consumer; } void set_consumer(AudioConsumer *consumer) { m_consumer = consumer; } //! Prepare for a new audio stream bool Reset(int sample_rate, int num_channels); //! Process a chunk of data from the audio stream void Consume(const int16_t *input, int length); //! Process any buffered input that was not processed before and clear buffers void Flush(); private: CHROMAPRINT_DISABLE_COPY(AudioProcessor); int Load(const int16_t *input, int length); void LoadMono(const int16_t *input, int length); void LoadStereo(const int16_t *input, int length); void LoadMultiChannel(const int16_t *input, int length); void Resample(); std::vector<int16_t> m_buffer; size_t m_buffer_offset; std::vector<int16_t> m_resample_buffer; int m_target_sample_rate; int m_num_channels; AudioConsumer *m_consumer; struct AVResampleContext *m_resample_ctx; }; }; #endif
582
435
<gh_stars>100-1000 { "description": "DjangoCon Europe 2020 (Virtual)\nSeptember 19, 2020 - 09h15 (GMT+1)\n\n\"Ceci n'est pas un job\" by <NAME>\n\nMore than once I have had the pleasure of being informed that my job (which by the way, is also the job of quite a few members of the DjangoCon audience) is not a \u201creal\u201d job. In this talk I will try to discover what a \u201creal job\u201d is. I will also find out more about what is \u201creal\u201d, and what is a \u201cjob\u201d. As a person who allegedly does not have a real job, and who comes from a country (Belgium) whose reality some people also doubt, I am ideally placed to make these discoveries. I will enlist the assistance of some famous Belgians, including the famous philosopher-actor <NAME> (not a real actor, according to some; not a real philosopher, according to others) and the artist Ren\u00e9 Magritte. I plan to show that being a web developer is not really a job - it\u2019s much more important than that.", "duration": 1463, "language": "eng", "recorded": "2020-09-19", "speakers": [ "<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/bMsr8tZQm9w/hqdefault.jpg", "related_urls": [ { "label": "Talk announcement", "url": "https://cfp.2020.djangocon.eu/porto/talk/NK7DRT/" } ], "title": "Ceci n'est pas un job - <NAME>", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=bMsr8tZQm9w" } ] }
587
675
/* * Copyright (c) 2020 Bitdefender * SPDX-License-Identifier: Apache-2.0 */ #include "include/nd_crt.h" // // nd_strcat_s // char * nd_strcat_s( char *dst, size_t dst_size, const char *src ) { char *p; size_t available; p = dst; available = dst_size; while (available > 0 && *p != 0) { p++; available--; } if (available == 0) { nd_memzero(dst, dst_size); return NULL; } while ((*p++ = *src++) != 0 && --available > 0); if (available == 0) { nd_memzero(dst, dst_size); return NULL; } return dst; } #if !defined(BDDISASM_NO_FORMAT) && defined(BDDISASM_HAS_VSNPRINTF) #include <stdio.h> int nd_vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr) { UNREFERENCED_PARAMETER(count); return vsnprintf(buffer, sizeOfBuffer, format, argptr); } #endif // !defined(BDDISASM_NO_FORMAT) && defined(BDDISASM_HAS_VSNPRINTF) #if !defined(BDDISASM_NO_FORMAT) && defined(BDDISASM_HAS_MEMSET) #include <string.h> void *nd_memset(void *s, int c, size_t n) { return memset(s, c, n); } #endif // !defined(BDDISASM_NO_FORMAT) && defined(BDDISASM_HAS_MEMSET)
584
617
from numpy.testing import assert_array_equal import numpy as np from scipy.sparse import csr_matrix from seqlearn._utils import safe_add def test_safe_add(): X1 = np.zeros((4, 13), dtype=np.float64) X2 = X1.copy() Y = csr_matrix(np.arange(4 * 13, dtype=np.float64).reshape(4, 13) % 4) X1 += Y safe_add(X2, Y) assert_array_equal(X1, X2) X = np.zeros((13, 4), dtype=np.float64) YT = Y.T safe_add(X, YT) assert_array_equal(X1, X.T)
228
6,726
<filename>android/src/main/java/com/facebook/flipper/plugins/inspector/descriptors/utils/stethocopies/FragmentManagerAccessor.java /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.flipper.plugins.inspector.descriptors.utils.stethocopies; import java.util.List; import javax.annotation.Nullable; public interface FragmentManagerAccessor<FRAGMENT_MANAGER, FRAGMENT> { @Nullable List<FRAGMENT> getAddedFragments(FRAGMENT_MANAGER fragmentManager); }
194
1,609
// Copyright 2018 The Gemmlowp 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. // kernel_msa.h: a collection of MSA optimized kernels. // Check in kernel_default.h which one(s) are actually used by default. // Others are mere experiments; they are still covered by tests // in case they might be useful some day. #ifndef GEMMLOWP_INTERNAL_KERNEL_MSA_H_ #define GEMMLOWP_INTERNAL_KERNEL_MSA_H_ #include "kernel.h" #include <msa.h> #include <cassert> namespace gemmlowp { #ifdef GEMMLOWP_MSA // Some convenience macros to hide differences between MIPS32 and MIPS64. #ifdef GEMMLOWP_MIPS_64 #define GEMMLOWP_MIPS_XADDU "daddu" #define GEMMLOWP_MIPS_XADDIU "daddiu" #define GEMMLOWP_MIPS_XSLL "dsll" #else #define GEMMLOWP_MIPS_XADDU "addu" #define GEMMLOWP_MIPS_XADDIU "addiu" #define GEMMLOWP_MIPS_XSLL "sll" #endif // Our main GEMM kernel. struct MSA_Kernel12x8Depth2 : KernelBase { typedef KernelFormat<KernelSideFormat<CellFormat<4, 2, CellOrder::WidthMajor>, 3>, KernelSideFormat<CellFormat<4, 2, CellOrder::WidthMajor>, 2> > Format; const char* Name() const override { return "MSA, 12x8, depth 2"; } // TODO(benoitjacob): reorder function arguments so dst comes last void Run(std::int32_t* dst_ptr, std::size_t dst_row_stride, std::size_t dst_col_stride, const std::uint8_t* lhs_ptr, const std::uint8_t* rhs_ptr, std::size_t start_depth, std::size_t run_depth) const override { ScopedProfilingLabel label("optimized kernel (MSA 12x8)"); // See comments above for why we need local numerical labels in our asm. #define GEMMLOWP_LABEL_CLEAR_ACCUMULATORS "1" #define GEMMLOWP_LABEL_BEFORE_LOOP "2" #define GEMMLOWP_LABEL_LOOP "3" #define GEMMLOWP_LABEL_AFTER_LOOP "4" assert(dst_row_stride == 1); asm volatile( // Multiply dst_col_stride by 4 == sizeof(int32) to use // it as a byte offset below. GEMMLOWP_MIPS_XSLL " %[dst_col_stride], %[dst_col_stride], 2\n" // Check if start_depth==0 to decide whether we will clear // accumulators or load existing accumulators. "beqz %[start_depth], " GEMMLOWP_LABEL_CLEAR_ACCUMULATORS "f\n" // Load accumulators (start_depth != 0). GEMMLOWP_MIPS_XADDU " $a0, %[dst_ptr], %[dst_col_stride]\n" "ld.w $w0, (0*16)(%[dst_ptr])\n" "ld.w $w4, (1*16)(%[dst_ptr])\n" "ld.w $w8, (2*16)(%[dst_ptr])\n" GEMMLOWP_MIPS_XADDU " $a1, $a0, %[dst_col_stride]\n" "ld.w $w1, (0*16)($a0)\n" "ld.w $w5, (1*16)($a0)\n" "ld.w $w9, (2*16)($a0)\n" GEMMLOWP_MIPS_XADDU " $a0, $a1, %[dst_col_stride]\n" "ld.w $w2, (0*16)($a1)\n" "ld.w $w6, (1*16)($a1)\n" "ld.w $w10, (2*16)($a1)\n" GEMMLOWP_MIPS_XADDU " $a1, $a0, %[dst_col_stride]\n" "ld.w $w3, (0*16)($a0)\n" "ld.w $w7, (1*16)($a0)\n" "ld.w $w11, (2*16)($a0)\n" GEMMLOWP_MIPS_XADDU " $a0, $a1, %[dst_col_stride]\n" "ld.w $w12, (0*16)($a1)\n" "ld.w $w16, (1*16)($a1)\n" "ld.w $w20, (2*16)($a1)\n" GEMMLOWP_MIPS_XADDU " $a1, $a0, %[dst_col_stride]\n" "ld.w $w13, (0*16)($a0)\n" "ld.w $w17, (1*16)($a0)\n" "ld.w $w21, (2*16)($a0)\n" GEMMLOWP_MIPS_XADDU " $a0, $a1, %[dst_col_stride]\n" "ld.w $w14, (0*16)($a1)\n" "ld.w $w18, (1*16)($a1)\n" "ld.w $w22, (2*16)($a1)\n" "ld.w $w15, (0*16)($a0)\n" "ld.w $w19, (1*16)($a0)\n" "ld.w $w23, (2*16)($a0)\n" "b " GEMMLOWP_LABEL_BEFORE_LOOP "f\n" GEMMLOWP_LABEL_CLEAR_ACCUMULATORS ":\n" // Clear accumulators (start_depth == 0). "ldi.w $w0, 0\n" "ldi.w $w4, 0\n" "ldi.w $w8, 0\n" "ldi.w $w1, 0\n" "ldi.w $w5, 0\n" "ldi.w $w9, 0\n" "ldi.w $w2, 0\n" "ldi.w $w6, 0\n" "ldi.w $w10, 0\n" "ldi.w $w3, 0\n" "ldi.w $w7, 0\n" "ldi.w $w11, 0\n" "ldi.w $w12, 0\n" "ldi.w $w16, 0\n" "ldi.w $w20, 0\n" "ldi.w $w13, 0\n" "ldi.w $w17, 0\n" "ldi.w $w21, 0\n" "ldi.w $w14, 0\n" "ldi.w $w18, 0\n" "ldi.w $w22, 0\n" "ldi.w $w15, 0\n" "ldi.w $w19, 0\n" "ldi.w $w23, 0\n" GEMMLOWP_LABEL_BEFORE_LOOP ":\n" GEMMLOWP_LABEL_LOOP ":\n" // Overview of register layout: // // A half of the 2 2x4 cells of Rhs is stored in 16bit in w28-w31 // (each register contains 4 replicas of a pair of elements). // A 12x2 block of 3 4x2 cells Lhs is stored in 16bit in w24-w26. // A 12x8 block of accumulators is stored in 32bit in w0-w23. // // +------+------+------+------+ // Rhs |w28 |w29 |w30 |w31 | // +------+------+------+------+ // // | | | | | // // Lhs | | | | | // // +---+ - - - - +------+------+------+------+ // |w24| |w0/12 |w1/13 |w2/14 |w3/15 | // |w24| |w0/12 |w1/13 |w2/14 |w3/15 | // |w24| |w0/12 |w1/13 |w2/14 |w3/15 | // |w24| |w0/12 |w1/13 |w2/14 |w3/15 | // +---+ - - - - +------+------+------+------+ // |w25| |w4/16 |w5/17 |w6/18 |w7/19 | // |w25| |w4/16 |w5/17 |w6/18 |w7/19 | // |w25| |w4/16 |w5/17 |w6/18 |w7/19 | // |w25| |w4/16 |w5/17 |w6/18 |w7/19 | // +---+ - - - - +------+------+------+------+ // |w26| |w8/20 |w9/21 |w10/22|w11/23| // |w26| |w8/20 |w9/21 |w10/22|w11/23| // |w26| |w8/20 |w9/21 |w10/22|w11/23| // |w26| |w8/20 |w9/21 |w10/22|w11/23| // +---+ - - - - +------+------+------+------+ // // Accumulators // Load 3 x 8 bytes of lhs[] with 2 16-byte overlapped loads. "ld.b $w24, 0(%[lhs_ptr])\n" "ld.b $w25, 8(%[lhs_ptr])\n" // Load 2 x 8 bytes of rhs[]. "ld.b $w27, 0(%[rhs_ptr])\n" // Zero-extend 8-bit elements of lhs[] to 16 bits. "ldi.b $w31, 0\n" "ilvr.b $w24, $w31, $w24\n" "ilvl.b $w26, $w31, $w25\n" "ilvr.b $w25, $w31, $w25\n" // First half of depths 0 and 1. // Zero-extend 8-bit elements of rhs[] to 16 bits. "ilvr.b $w31, $w31, $w27\n" // Make 4 replicas of every pair of rhs[] elements. "splati.w $w28, $w31[0]\n" "splati.w $w29, $w31[1]\n" "splati.w $w30, $w31[2]\n" "splati.w $w31, $w31[3]\n" // Dot-product-(and)-add doubles multiplicand width. "dpadd_u.w $w0, $w24, $w28\n" "dpadd_u.w $w4, $w25, $w28\n" "dpadd_u.w $w8, $w26, $w28\n" "dpadd_u.w $w1, $w24, $w29\n" "dpadd_u.w $w5, $w25, $w29\n" "dpadd_u.w $w9, $w26, $w29\n" "dpadd_u.w $w2, $w24, $w30\n" "dpadd_u.w $w6, $w25, $w30\n" "dpadd_u.w $w10, $w26, $w30\n" "dpadd_u.w $w3, $w24, $w31\n" "dpadd_u.w $w7, $w25, $w31\n" "dpadd_u.w $w11, $w26, $w31\n" // Second half of depths 0 and 1. // Zero-extend 8-bit elements of rhs[] to 16 bits. "ldi.b $w31, 0\n" "ilvl.b $w31, $w31, $w27\n" // Make 4 replicas of every pair of rhs[] elements. "splati.w $w28, $w31[0]\n" "splati.w $w29, $w31[1]\n" "splati.w $w30, $w31[2]\n" "splati.w $w31, $w31[3]\n" // Dot-product-(and)-add doubles multiplicand width. "dpadd_u.w $w12, $w24, $w28\n" "dpadd_u.w $w16, $w25, $w28\n" "dpadd_u.w $w20, $w26, $w28\n" "dpadd_u.w $w13, $w24, $w29\n" "dpadd_u.w $w17, $w25, $w29\n" "dpadd_u.w $w21, $w26, $w29\n" "dpadd_u.w $w14, $w24, $w30\n" "dpadd_u.w $w18, $w25, $w30\n" "dpadd_u.w $w22, $w26, $w30\n" "dpadd_u.w $w15, $w24, $w31\n" "dpadd_u.w $w19, $w25, $w31\n" "dpadd_u.w $w23, $w26, $w31\n" GEMMLOWP_MIPS_XADDIU " %[run_depth], -2\n" GEMMLOWP_MIPS_XADDIU " %[lhs_ptr], 24\n" GEMMLOWP_MIPS_XADDIU " %[rhs_ptr], 16\n" "bnez %[run_depth]," GEMMLOWP_LABEL_LOOP "b\n" GEMMLOWP_LABEL_AFTER_LOOP ":\n" // Store accumulators. GEMMLOWP_MIPS_XADDU " $a0, %[dst_ptr], %[dst_col_stride]\n" "st.w $w0, (0*16)(%[dst_ptr])\n" "st.w $w4, (1*16)(%[dst_ptr])\n" "st.w $w8, (2*16)(%[dst_ptr])\n" GEMMLOWP_MIPS_XADDU " $a1, $a0, %[dst_col_stride]\n" "st.w $w1, (0*16)($a0)\n" "st.w $w5, (1*16)($a0)\n" "st.w $w9, (2*16)($a0)\n" GEMMLOWP_MIPS_XADDU " $a0, $a1, %[dst_col_stride]\n" "st.w $w2, (0*16)($a1)\n" "st.w $w6, (1*16)($a1)\n" "st.w $w10, (2*16)($a1)\n" GEMMLOWP_MIPS_XADDU " $a1, $a0, %[dst_col_stride]\n" "st.w $w3, (0*16)($a0)\n" "st.w $w7, (1*16)($a0)\n" "st.w $w11, (2*16)($a0)\n" GEMMLOWP_MIPS_XADDU " $a0, $a1, %[dst_col_stride]\n" "st.w $w12, (0*16)($a1)\n" "st.w $w16, (1*16)($a1)\n" "st.w $w20, (2*16)($a1)\n" GEMMLOWP_MIPS_XADDU " $a1, $a0, %[dst_col_stride]\n" "st.w $w13, (0*16)($a0)\n" "st.w $w17, (1*16)($a0)\n" "st.w $w21, (2*16)($a0)\n" GEMMLOWP_MIPS_XADDU " $a0, $a1, %[dst_col_stride]\n" "st.w $w14, (0*16)($a1)\n" "st.w $w18, (1*16)($a1)\n" "st.w $w22, (2*16)($a1)\n" "st.w $w15, (0*16)($a0)\n" "st.w $w19, (1*16)($a0)\n" "st.w $w23, (2*16)($a0)\n" : // outputs [lhs_ptr] "+r"(lhs_ptr), [rhs_ptr] "+r"(rhs_ptr), [run_depth] "+r"(run_depth), [dst_col_stride] "+r"(dst_col_stride) : // inputs [dst_ptr] "r"(dst_ptr), [start_depth] "r"(start_depth) : // clobbers "memory", "a0", "a1", "$f0", "$f1", "$f2", "$f3", "$f4", "$f5", "$f6", "$f7", "$f8", "$f9", "$f10", "$f11", "$f12", "$f13", "$f14", "$f15", "$f16", "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23", "$f24", "$f25", "$f26", "$f27", "$f28", "$f29", "$f30", "$f31"); #undef GEMMLOWP_LABEL_CLEAR_ACCUMULATORS #undef GEMMLOWP_LABEL_BEFORE_LOOP #undef GEMMLOWP_LABEL_LOOP #undef GEMMLOWP_LABEL_AFTER_LOOP } }; // Fast kernel operating on int8 operands. // It is assumed that one of the two int8 operands only takes values // in [-127, 127], while the other may freely range in [-128, 127]. // The issue with both operands taking the value -128 is that: // -128*-128 + -128*-128 == -32768 overflows int16. // Every other expression a*b + c*d, for any int8 a,b,c,d, fits in int16 // range. That is the basic idea of this kernel. struct MSA_GEMM_Int8Operands_LhsNonzero : KernelBase { typedef KernelFormat< KernelSideFormatInt8<CellFormat<4, 16, CellOrder::WidthMajor>, 1>, KernelSideFormatInt8<CellFormat<4, 16, CellOrder::WidthMajor>, 1> > Format; const char* Name() const override { return "MSA, 4x4, depth 16, accumulating two within signed int16"; } // TODO(benoitjacob): reorder function arguments so dst comes last void Run(std::int32_t* dst_ptr, std::size_t dst_row_stride, std::size_t dst_col_stride, const std::uint8_t* lhs_ptr, const std::uint8_t* rhs_ptr, std::size_t start_depth, std::size_t run_depth) const override { (void)dst_row_stride; #define GEMMLOWP_LABEL_AFTER_LOOP_LAST16 "1" #define GEMMLOWP_LABEL_LOOP "2" #define GEMMLOWP_LABEL_ACCUMULATE_EXISTING_DST_VALUES "3" #define GEMMLOWP_LABEL_STORE "4" asm volatile( GEMMLOWP_MIPS_XADDIU " %[run_depth], -16\n" // Load lhs[] and rhs[], zero out internal accumulators. "ld.b $w16, 0(%[lhs_ptr])\n" "ldi.b $w0, 0\n" "ld.b $w20, 0(%[rhs_ptr])\n" "ldi.b $w1, 0\n" "ld.b $w17, 16(%[lhs_ptr])\n" "ldi.b $w2, 0\n" "ld.b $w21, 16(%[rhs_ptr])\n" "ldi.b $w3, 0\n" "ld.b $w18, 32(%[lhs_ptr])\n" "ldi.b $w4, 0\n" "ld.b $w19, 48(%[lhs_ptr])\n" "ldi.b $w5, 0\n" "ld.b $w22, 32(%[rhs_ptr])\n" "ldi.b $w6, 0\n" "ld.b $w23, 48(%[rhs_ptr])\n" "ldi.b $w7, 0\n" "ldi.b $w8, 0\n" "ldi.b $w9, 0\n" "ldi.b $w10, 0\n" "ldi.b $w11, 0\n" "ldi.b $w12, 0\n" "ldi.b $w13, 0\n" "ldi.b $w14, 0\n" "ldi.b $w15, 0\n" "ldi.h $w31, 1\n" // If the loop depth is only 16, then we can skip the general loop // and go straight to the final part of the code. "beqz %[run_depth], " GEMMLOWP_LABEL_AFTER_LOOP_LAST16 "f\n" GEMMLOWP_LABEL_LOOP ":\n" // Overview of register layout: // // A 4x16 block of Rhs is stored in 8 bit in w16-w19. // A 4x16 block of Lhs is stored in 8 bit in w20-w23. // // A 4x4 block of accumulators is stored in w0-w15 (as 4x32 bit // components which need to be horizontally added at the end). // // Dot products of Lhs and Rhs are 16-bit values, which can't // immediately be accumulated in 32-bit accumulators by that // same instruction that calculates them. // For example, "dotp_s.h $w25, $w16, $w20" produces 8 16-bit // sums in w25 (note, the 16 sums have already been reduced to 8 // by the horizontal addition of the dotp instruction). // They are then sign-extended to 32 bits, horizontally added // (again) to form 4 32-bit sums and then they are finally added // to the 32-bit accumulators, all by "dpadd_s.w $w0, $w25, $w31". // // +-----+-----+-----+-----+ // Rhs | w20 | w21 | w22 | w23 | // +-----+-----+-----+-----+ // // | | | | | // // Lhs | | | | | // // +---+ - - - - +-----+-----+-----+-----+ // |w16| | w0 | w4 | w8 | w12 | // |w17| | w1 | w5 | w9 | w13 | // |w18| | w2 | w6 | w10 | w14 | // |w19| | w3 | w7 | w11 | w15 | // +---+ - - - - +-----+-----+-----+-----+ // // Accumulators // Calculate the results for 16 depths and load // lhs[] and rhs[] for the next iteration. GEMMLOWP_MIPS_XADDIU " %[lhs_ptr], 64\n" GEMMLOWP_MIPS_XADDIU " %[rhs_ptr], 64\n" GEMMLOWP_MIPS_XADDIU " %[run_depth], -16\n" // Dot product: multiply-add pairs of adjacent int8 elements. // Each dot product takes 16*2 int8 values in and produces 8 int16 sums. "dotp_s.h $w25, $w16, $w20\n" "dotp_s.h $w26, $w17, $w20\n" "dotp_s.h $w27, $w16, $w21\n" "dotp_s.h $w28, $w17, $w21\n" "dotp_s.h $w29, $w18, $w20\n" // Horizontal add of pairs of adjacent int16 sums into internal int32 // accumulators. "dpadd_s.w $w0, $w25, $w31\n" "dpadd_s.w $w1, $w26, $w31\n" "dpadd_s.w $w4, $w27, $w31\n" "dpadd_s.w $w5, $w28, $w31\n" "dpadd_s.w $w2, $w29, $w31\n" // Dot product: multiply-add pairs of adjacent int8 elements. // Each dot product takes 16*2 int8 values in and produces 8 int16 sums. "dotp_s.h $w24, $w16, $w22\n" "dotp_s.h $w25, $w19, $w20\n" "dotp_s.h $w26, $w16, $w23\n" "dotp_s.h $w27, $w17, $w22\n" "ld.b $w20, 0(%[rhs_ptr])\n" "dotp_s.h $w28, $w17, $w23\n" "ld.b $w16, 0(%[lhs_ptr])\n" "dotp_s.h $w29, $w18, $w21\n" "ld.b $w17, 16(%[lhs_ptr])\n" // Horizontal add of pairs of adjacent int16 sums into internal int32 // accumulators. "dpadd_s.w $w8, $w24, $w31\n" "dpadd_s.w $w3, $w25, $w31\n" "dpadd_s.w $w12, $w26, $w31\n" "dpadd_s.w $w9, $w27, $w31\n" "dpadd_s.w $w13, $w28, $w31\n" "dpadd_s.w $w6, $w29, $w31\n" // Dot product: multiply-add pairs of adjacent int8 elements. // Each dot product takes 16*2 int8 values in and produces 8 int16 sums. "dotp_s.h $w25, $w19, $w21\n" "dotp_s.h $w26, $w18, $w22\n" "dotp_s.h $w27, $w18, $w23\n" "ld.b $w21, 16(%[rhs_ptr])\n" "dotp_s.h $w28, $w19, $w22\n" "ld.b $w18, 32(%[lhs_ptr])\n" "dotp_s.h $w29, $w19, $w23\n" "ld.b $w22, 32(%[rhs_ptr])\n" // Horizontal add of pairs of adjacent int16 sums into internal int32 // accumulators. "dpadd_s.w $w7, $w25, $w31\n" "ld.b $w19, 48(%[lhs_ptr])\n" "dpadd_s.w $w10, $w26, $w31\n" "ld.b $w23, 48(%[rhs_ptr])\n" "dpadd_s.w $w14, $w27, $w31\n" "dpadd_s.w $w11, $w28, $w31\n" "dpadd_s.w $w15, $w29, $w31\n" "bnez %[run_depth], " GEMMLOWP_LABEL_LOOP "b\n" GEMMLOWP_LABEL_AFTER_LOOP_LAST16 ":\n" // Calculate the results for the last 16 depths. // Dot product: multiply-add pairs of adjacent int8 elements. // Each dot product takes 16*2 int8 values in and produces 8 int16 sums. "dotp_s.h $w25, $w16, $w20\n" "dotp_s.h $w26, $w17, $w20\n" "dotp_s.h $w27, $w16, $w21\n" "dotp_s.h $w28, $w17, $w21\n" "dotp_s.h $w29, $w18, $w20\n" // Horizontal add of pairs of adjacent int16 sums into internal int32 // accumulators. "dpadd_s.w $w0, $w25, $w31\n" "dpadd_s.w $w1, $w26, $w31\n" "dpadd_s.w $w4, $w27, $w31\n" "dpadd_s.w $w5, $w28, $w31\n" "dpadd_s.w $w2, $w29, $w31\n" // Dot product: multiply-add pairs of adjacent int8 elements. // Each dot product takes 16*2 int8 values in and produces 8 int16 sums. "dotp_s.h $w24, $w16, $w22\n" "dotp_s.h $w25, $w19, $w20\n" "dotp_s.h $w26, $w16, $w23\n" "dotp_s.h $w27, $w17, $w22\n" "dotp_s.h $w28, $w17, $w23\n" "dotp_s.h $w29, $w18, $w21\n" // Horizontal add of pairs of adjacent int16 sums into internal int32 // accumulators. "dpadd_s.w $w8, $w24, $w31\n" "dpadd_s.w $w3, $w25, $w31\n" "dpadd_s.w $w12, $w26, $w31\n" "dpadd_s.w $w9, $w27, $w31\n" "dpadd_s.w $w13, $w28, $w31\n" "dpadd_s.w $w6, $w29, $w31\n" // Dot product: multiply-add pairs of adjacent int8 elements. // Each dot product takes 16*2 int8 values in and produces 8 int16 sums. "dotp_s.h $w25, $w19, $w21\n" "dotp_s.h $w26, $w18, $w22\n" "dotp_s.h $w27, $w18, $w23\n" "dotp_s.h $w28, $w19, $w22\n" "dotp_s.h $w29, $w19, $w23\n" // Horizontal add of pairs of adjacent int16 sums into internal int32 // accumulators. "dpadd_s.w $w7, $w25, $w31\n" "dpadd_s.w $w10, $w26, $w31\n" "dpadd_s.w $w14, $w27, $w31\n" "dpadd_s.w $w11, $w28, $w31\n" "dpadd_s.w $w15, $w29, $w31\n" // Horizontal-add internal accumulators. "hadd_s.d $w0, $w0, $w0\n" "hadd_s.d $w1, $w1, $w1\n" "hadd_s.d $w2, $w2, $w2\n" "hadd_s.d $w3, $w3, $w3\n" "hadd_s.d $w4, $w4, $w4\n" "hadd_s.d $w5, $w5, $w5\n" "hadd_s.d $w6, $w6, $w6\n" "hadd_s.d $w7, $w7, $w7\n" "hadd_s.d $w8, $w8, $w8\n" "hadd_s.d $w9, $w9, $w9\n" "hadd_s.d $w10, $w10, $w10\n" "hadd_s.d $w11, $w11, $w11\n" "hadd_s.d $w12, $w12, $w12\n" "hadd_s.d $w13, $w13, $w13\n" "hadd_s.d $w14, $w14, $w14\n" "hadd_s.d $w15, $w15, $w15\n" "pckev.w $w0, $w1, $w0\n" "pckev.w $w2, $w3, $w2\n" "pckev.w $w4, $w5, $w4\n" "pckev.w $w6, $w7, $w6\n" "pckev.w $w8, $w9, $w8\n" "pckev.w $w10, $w11, $w10\n" "pckev.w $w12, $w13, $w12\n" "pckev.w $w14, $w15, $w14\n" "hadd_s.d $w0, $w0, $w0\n" "hadd_s.d $w2, $w2, $w2\n" "hadd_s.d $w4, $w4, $w4\n" "hadd_s.d $w6, $w6, $w6\n" "hadd_s.d $w8, $w8, $w8\n" "hadd_s.d $w10, $w10, $w10\n" "hadd_s.d $w12, $w12, $w12\n" "hadd_s.d $w14, $w14, $w14\n" // 4 more pckev instructions follow in both paths below. // Check if start_depth==0 to decide whether we will load // existing accumulators from memory. "bnez %[start_depth], " GEMMLOWP_LABEL_ACCUMULATE_EXISTING_DST_VALUES "f\n" "pckev.w $w0, $w2, $w0\n" "pckev.w $w1, $w6, $w4\n" "pckev.w $w2, $w10, $w8\n" "pckev.w $w3, $w14, $w12\n" "b " GEMMLOWP_LABEL_STORE "f\n" GEMMLOWP_LABEL_ACCUMULATE_EXISTING_DST_VALUES ":\n" // Load accumulators from memory. "ld.w $w16, 0(%[dst_ptr0])\n" "pckev.w $w0, $w2, $w0\n" "ld.w $w17, 0(%[dst_ptr1])\n" "pckev.w $w1, $w6, $w4\n" "ld.w $w18, 0(%[dst_ptr2])\n" "pckev.w $w2, $w10, $w8\n" "ld.w $w19, 0(%[dst_ptr3])\n" "pckev.w $w3, $w14, $w12\n" // Add them to internal accumulators. "addv.w $w0, $w0, $w16\n" "addv.w $w1, $w1, $w17\n" "addv.w $w2, $w2, $w18\n" "addv.w $w3, $w3, $w19\n" GEMMLOWP_LABEL_STORE ":\n" // Store accumulators. "st.w $w0, 0(%[dst_ptr0])\n" "st.w $w1, 0(%[dst_ptr1])\n" "st.w $w2, 0(%[dst_ptr2])\n" "st.w $w3, 0(%[dst_ptr3])\n" : // outputs [lhs_ptr] "+r"(lhs_ptr), [rhs_ptr] "+r"(rhs_ptr), [run_depth] "+r"(run_depth) : // inputs [dst_ptr0] "r"(dst_ptr), [dst_ptr1] "r"(dst_ptr + dst_col_stride), [dst_ptr2] "r"(dst_ptr + dst_col_stride * 2), [dst_ptr3] "r"(dst_ptr + dst_col_stride * 3), [start_depth] "r"(start_depth) : // clobbers "memory", "$f0", "$f1", "$f2", "$f3", "$f4", "$f5", "$f6", "$f7", "$f8", "$f9", "$f10", "$f11", "$f12", "$f13", "$f14", "$f15", "$f16", "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23", "$f24", "$f25", "$f26", "$f27", "$f28", "$f29", "$f30", "$f31"); #undef GEMMLOWP_LABEL_LOOP #undef GEMMLOWP_LABEL_AFTER_LOOP_LAST16 #undef GEMMLOWP_LABEL_ACCUMULATE_EXISTING_DST_VALUES #undef GEMMLOWP_LABEL_STORE } }; #undef GEMMLOWP_MIPS_XADDU #undef GEMMLOWP_MIPS_XADDIU #undef GEMMLOWP_MIPS_XSLL #endif // GEMMLOWP_MSA } // namespace gemmlowp #endif // GEMMLOWP_INTERNAL_KERNEL_MSA_H_
14,504
582
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.diagram.policies; import org.eclipse.gef.commands.Command; import org.eclipse.gef.editpolicies.ComponentEditPolicy; import org.eclipse.gef.requests.GroupRequest; import com.archimatetool.editor.diagram.commands.DiagramCommandFactory; import com.archimatetool.model.IDiagramModelObject; import com.archimatetool.model.ILockable; /** * Policy for Deleting and Orphaning Parts * * @author <NAME> */ public class PartComponentEditPolicy extends ComponentEditPolicy { @Override protected Command createDeleteCommand(GroupRequest request) { IDiagramModelObject object = (IDiagramModelObject)getHost().getModel(); boolean isLocked = object instanceof ILockable && ((ILockable)object).isLocked(); return isLocked ? null : DiagramCommandFactory.createDeleteDiagramObjectCommand(object); } }
348
412
// -*- Mode: objc; Coding: utf-8; indent-tabs-mode: nil; -*- @import Cocoa; #import "ServerClientProtocol.h" @interface ServerForUserspace : NSObject <ServerClientProtocol> - (BOOL)registerService; - (void)setup; @end
86
348
{"nom":"Tallone","circ":"2ème circonscription","dpt":"Haute-Corse","inscrits":253,"abs":155,"votants":98,"blancs":7,"nuls":1,"exp":90,"res":[{"nuance":"REG","nom":"<NAME>","voix":51},{"nuance":"REM","nom":"<NAME>","voix":39}]}
91
4,538
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_IMAGEENHAN_MODEL_IMAGEBLINDCHARACTERWATERMARKREQUEST_H_ #define ALIBABACLOUD_IMAGEENHAN_MODEL_IMAGEBLINDCHARACTERWATERMARKREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/imageenhan/ImageenhanExport.h> namespace AlibabaCloud { namespace Imageenhan { namespace Model { class ALIBABACLOUD_IMAGEENHAN_EXPORT ImageBlindCharacterWatermarkRequest : public RpcServiceRequest { public: ImageBlindCharacterWatermarkRequest(); ~ImageBlindCharacterWatermarkRequest(); std::string getWatermarkImageURL()const; void setWatermarkImageURL(const std::string& watermarkImageURL); int getQualityFactor()const; void setQualityFactor(int qualityFactor); std::string getFunctionType()const; void setFunctionType(const std::string& functionType); std::string getOutputFileType()const; void setOutputFileType(const std::string& outputFileType); std::string getOriginImageURL()const; void setOriginImageURL(const std::string& originImageURL); std::string getText()const; void setText(const std::string& text); private: std::string watermarkImageURL_; int qualityFactor_; std::string functionType_; std::string outputFileType_; std::string originImageURL_; std::string text_; }; } } } #endif // !ALIBABACLOUD_IMAGEENHAN_MODEL_IMAGEBLINDCHARACTERWATERMARKREQUEST_H_
745
310
{ "name": "AEB10E", "description": "An acoustic bass guitar.", "url": "https://www.ibanez.com/usa/products/detail/aeb10e_2y_08.html" }
60
2,151
// Copyright 2017 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 "mojo/edk/system/channel.h" #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/threading/thread.h" #include "mojo/edk/embedder/platform_channel_pair.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace mojo { namespace edk { namespace { class TestChannel : public Channel { public: TestChannel(Channel::Delegate* delegate) : Channel(delegate) {} char* GetReadBufferTest(size_t* buffer_capacity) { return GetReadBuffer(buffer_capacity); } bool OnReadCompleteTest(size_t bytes_read, size_t* next_read_size_hint) { return OnReadComplete(bytes_read, next_read_size_hint); } MOCK_METHOD4(GetReadInternalPlatformHandles, bool(size_t num_handles, const void* extra_header, size_t extra_header_size, std::vector<ScopedInternalPlatformHandle>* handles)); MOCK_METHOD0(Start, void()); MOCK_METHOD0(ShutDownImpl, void()); MOCK_METHOD0(LeakHandle, void()); void Write(MessagePtr message) override {} protected: ~TestChannel() override {} }; // Not using GMock as I don't think it supports movable types. class MockChannelDelegate : public Channel::Delegate { public: MockChannelDelegate() {} size_t GetReceivedPayloadSize() const { return payload_size_; } const void* GetReceivedPayload() const { return payload_.get(); } protected: void OnChannelMessage( const void* payload, size_t payload_size, std::vector<ScopedInternalPlatformHandle> handles) override { payload_.reset(new char[payload_size]); memcpy(payload_.get(), payload, payload_size); payload_size_ = payload_size; } // Notify that an error has occured and the Channel will cease operation. void OnChannelError(Channel::Error error) override {} private: size_t payload_size_ = 0; std::unique_ptr<char[]> payload_; }; Channel::MessagePtr CreateDefaultMessage(bool legacy_message) { const size_t payload_size = 100; Channel::MessagePtr message = std::make_unique<Channel::Message>( payload_size, 0, legacy_message ? Channel::Message::MessageType::NORMAL_LEGACY : Channel::Message::MessageType::NORMAL); char* payload = static_cast<char*>(message->mutable_payload()); for (size_t i = 0; i < payload_size; i++) { payload[i] = static_cast<char>(i); } return message; } void TestMemoryEqual(const void* data1, size_t data1_size, const void* data2, size_t data2_size) { ASSERT_EQ(data1_size, data2_size); const unsigned char* data1_char = static_cast<const unsigned char*>(data1); const unsigned char* data2_char = static_cast<const unsigned char*>(data2); for (size_t i = 0; i < data1_size; i++) { // ASSERT so we don't log tons of errors if the data is different. ASSERT_EQ(data1_char[i], data2_char[i]); } } void TestMessagesAreEqual(Channel::Message* message1, Channel::Message* message2, bool legacy_messages) { // If any of the message is null, this is probably not what you wanted to // test. ASSERT_NE(nullptr, message1); ASSERT_NE(nullptr, message2); ASSERT_EQ(message1->payload_size(), message2->payload_size()); EXPECT_EQ(message1->has_handles(), message2->has_handles()); TestMemoryEqual(message1->payload(), message1->payload_size(), message2->payload(), message2->payload_size()); if (legacy_messages) return; ASSERT_EQ(message1->extra_header_size(), message2->extra_header_size()); TestMemoryEqual(message1->extra_header(), message1->extra_header_size(), message2->extra_header(), message2->extra_header_size()); } TEST(ChannelTest, LegacyMessageDeserialization) { Channel::MessagePtr message = CreateDefaultMessage(true /* legacy_message */); Channel::MessagePtr deserialized_message = Channel::Message::Deserialize(message->data(), message->data_num_bytes()); TestMessagesAreEqual(message.get(), deserialized_message.get(), true /* legacy_message */); } TEST(ChannelTest, NonLegacyMessageDeserialization) { Channel::MessagePtr message = CreateDefaultMessage(false /* legacy_message */); Channel::MessagePtr deserialized_message = Channel::Message::Deserialize(message->data(), message->data_num_bytes()); TestMessagesAreEqual(message.get(), deserialized_message.get(), false /* legacy_message */); } TEST(ChannelTest, OnReadLegacyMessage) { size_t buffer_size = 100 * 1024; Channel::MessagePtr message = CreateDefaultMessage(true /* legacy_message */); MockChannelDelegate channel_delegate; scoped_refptr<TestChannel> channel = new TestChannel(&channel_delegate); char* read_buffer = channel->GetReadBufferTest(&buffer_size); ASSERT_LT(message->data_num_bytes(), buffer_size); // Bad test. Increase buffer // size. memcpy(read_buffer, message->data(), message->data_num_bytes()); size_t next_read_size_hint = 0; EXPECT_TRUE(channel->OnReadCompleteTest(message->data_num_bytes(), &next_read_size_hint)); TestMemoryEqual(message->payload(), message->payload_size(), channel_delegate.GetReceivedPayload(), channel_delegate.GetReceivedPayloadSize()); } TEST(ChannelTest, OnReadNonLegacyMessage) { size_t buffer_size = 100 * 1024; Channel::MessagePtr message = CreateDefaultMessage(false /* legacy_message */); MockChannelDelegate channel_delegate; scoped_refptr<TestChannel> channel = new TestChannel(&channel_delegate); char* read_buffer = channel->GetReadBufferTest(&buffer_size); ASSERT_LT(message->data_num_bytes(), buffer_size); // Bad test. Increase buffer // size. memcpy(read_buffer, message->data(), message->data_num_bytes()); size_t next_read_size_hint = 0; EXPECT_TRUE(channel->OnReadCompleteTest(message->data_num_bytes(), &next_read_size_hint)); TestMemoryEqual(message->payload(), message->payload_size(), channel_delegate.GetReceivedPayload(), channel_delegate.GetReceivedPayloadSize()); } class ChannelTestShutdownAndWriteDelegate : public Channel::Delegate { public: ChannelTestShutdownAndWriteDelegate( ScopedInternalPlatformHandle handle, scoped_refptr<base::TaskRunner> task_runner, scoped_refptr<Channel> client_channel, std::unique_ptr<base::Thread> client_thread, base::RepeatingClosure quit_closure) : quit_closure_(std::move(quit_closure)), client_channel_(std::move(client_channel)), client_thread_(std::move(client_thread)) { channel_ = Channel::Create( this, ConnectionParams(TransportProtocol::kLegacy, std::move(handle)), std::move(task_runner)); channel_->Start(); } ~ChannelTestShutdownAndWriteDelegate() override { channel_->ShutDown(); } // Channel::Delegate implementation void OnChannelMessage( const void* payload, size_t payload_size, std::vector<ScopedInternalPlatformHandle> handles) override { ++message_count_; // If |client_channel_| exists then close it and its thread. if (client_channel_) { // Write a fresh message, making our channel readable again. Channel::MessagePtr message = CreateDefaultMessage(false); client_thread_->task_runner()->PostTask( FROM_HERE, base::BindOnce(&Channel::Write, client_channel_, base::Passed(&message))); // Close the channel and wait for it to shutdown. client_channel_->ShutDown(); client_channel_ = nullptr; client_thread_->Stop(); client_thread_ = nullptr; } // Write a message to the channel, to verify whether this triggers an // OnChannelError callback before all messages were read. Channel::MessagePtr message = CreateDefaultMessage(false); channel_->Write(std::move(message)); } void OnChannelError(Channel::Error error) override { EXPECT_EQ(2, message_count_); quit_closure_.Run(); } base::RepeatingClosure quit_closure_; int message_count_ = 0; scoped_refptr<Channel> channel_; scoped_refptr<Channel> client_channel_; std::unique_ptr<base::Thread> client_thread_; }; TEST(ChannelTest, PeerShutdownDuringRead) { base::MessageLoop message_loop(base::MessageLoop::TYPE_IO); PlatformChannelPair channel_pair; // Create a "client" Channel with one end of the pipe, and Start() it. std::unique_ptr<base::Thread> client_thread = std::make_unique<base::Thread>("clientio_thread"); client_thread->StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); scoped_refptr<Channel> client_channel = Channel::Create(nullptr, ConnectionParams(TransportProtocol::kLegacy, channel_pair.PassClientHandle()), client_thread->task_runner()); client_channel->Start(); // On the "client" IO thread, create and write a message. Channel::MessagePtr message = CreateDefaultMessage(false); client_thread->task_runner()->PostTask( FROM_HERE, base::BindOnce(&Channel::Write, client_channel, base::Passed(&message))); // Create a "server" Channel with the other end of the pipe, and process the // messages from it. The |server_delegate| will ShutDown the client end of // the pipe after the first message, and quit the RunLoop when OnChannelError // is received. base::RunLoop run_loop; ChannelTestShutdownAndWriteDelegate server_delegate( channel_pair.PassServerHandle(), message_loop.task_runner(), std::move(client_channel), std::move(client_thread), run_loop.QuitClosure()); run_loop.Run(); } } // namespace } // namespace edk } // namespace mojo
3,786
448
<filename>FileDownloader/src/main/java/org/wlf/filedownloader/db/BaseContentDbDao.java package org.wlf.filedownloader.db; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * base dao impl * <br/> * 基本的ContentDbDao实现封装 * * @author wlf(Andy) * @email <EMAIL> */ public abstract class BaseContentDbDao implements ContentDbDao, DatabaseCallback { /** * default id field name */ public static final String DEFAULT_TABLE_ID_FIELD_NAME = "_id"; private SQLiteOpenHelper mDbHelper; private String mTableName; private String mTableIdFieldName = DEFAULT_TABLE_ID_FIELD_NAME; public BaseContentDbDao(SQLiteOpenHelper dbHelper, String tableName, String tableIdFieldName) { super(); this.mDbHelper = dbHelper; this.mTableName = tableName; this.mTableIdFieldName = tableIdFieldName; } @Override public long insert(ContentValues values) { long id = -1; SQLiteDatabase database = null; try { database = mDbHelper.getWritableDatabase(); id = database.insert(mTableName, null, values); } catch (Exception e) { e.printStackTrace(); } finally { // if (database != null) { // database.close(); // } } return id; } @Override public int delete(String selection, String[] selectionArgs) { int count = -1; SQLiteDatabase database = null; try { database = mDbHelper.getWritableDatabase(); count = database.delete(mTableName, selection, selectionArgs); } catch (Exception e) { e.printStackTrace(); } finally { // if (database != null) { // database.close(); // } } return count; } @Override public int update(ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase database = null; int count = -1; try { database = mDbHelper.getWritableDatabase(); count = database.update(mTableName, values, selection, selectionArgs); } catch (Exception e) { e.printStackTrace(); } finally { // if (database != null) { // database.close(); // } } return count; } @Override public Cursor query(String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase database = null; Cursor cursor = null; try { database = mDbHelper.getReadableDatabase(); cursor = database.query(true, mTableName, null, selection, selectionArgs, null, null, sortOrder, null); } catch (Exception e) { e.printStackTrace(); } finally { // if (database != null) { // database.close(); // } } return cursor; } @Override public String getTableName() { return mTableName; } @Override public String getTableIdFieldName() { return mTableIdFieldName; } }
1,533
892
{ "schema_version": "1.2.0", "id": "GHSA-4wvx-qq9g-8hh9", "modified": "2022-05-13T01:49:56Z", "published": "2022-05-13T01:49:56Z", "aliases": [ "CVE-2018-14345" ], "details": "An issue was discovered in SDDM through 0.17.0. If configured with ReuseSession=true, the password is not checked for users with an already existing session. Any user with access to the system D-Bus can therefore unlock any graphical session. This is related to daemon/Display.cpp and helper/backend/PamBackend.cpp.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-14345" }, { "type": "WEB", "url": "https://github.com/sddm/sddm/commit/147cec383892d143b5e02daa70f1e7def50f5d98" }, { "type": "WEB", "url": "https://bugzilla.suse.com/show_bug.cgi?id=1101450" } ], "database_specific": { "cwe_ids": [ "CWE-287" ], "severity": "HIGH", "github_reviewed": false } }
535
1,014
package com.github.neuralnetworks.input; import java.util.Arrays; import com.github.neuralnetworks.calculation.OutputError; import com.github.neuralnetworks.tensor.Matrix; import com.github.neuralnetworks.tensor.Tensor; public class MultipleNeuronsSimpleOutputError implements OutputError { private static final long serialVersionUID = 1L; private int correct; private int incorrect; public MultipleNeuronsSimpleOutputError() { super(); reset(); } @Override public void addItem(Tensor newtorkOutput, Tensor targetOutput) { Matrix target = (Matrix) targetOutput; Matrix actual = (Matrix) newtorkOutput; if (!Arrays.equals(actual.getDimensions(), target.getDimensions())) { throw new IllegalArgumentException("Dimensions don't match"); } for (int i = 0; i < target.getRows(); i++) { boolean hasDifferentValues = false; for (int j = 0; j < actual.getColumns(); j++) { if (actual.get(i, j) != actual.get(i, 0)) { hasDifferentValues = true; break; } } if (hasDifferentValues) { int targetPos = 0; for (int j = 0; j < target.getColumns(); j++) { if (target.get(i, j) == 1) { targetPos = j; break; } } int outputPos = 0; float max = actual.get(i, 0); for (int j = 0; j < actual.getColumns(); j++) { if (actual.get(i, j) > max) { max = actual.get(i, j); outputPos = j; } } if (targetPos == outputPos) { correct++; } else { incorrect++; } } else { incorrect++; } } } @Override public float getTotalNetworkError() { return getTotalInputSize() > 0 ? ((float) getTotalErrorSamples()) / getTotalInputSize() : 0; } @Override public int getTotalErrorSamples() { return incorrect; } @Override public int getTotalInputSize() { return incorrect + correct; } @Override public void reset() { correct = incorrect = 0; } }
819
1,778
<reponame>cicidi/spring-security-oauth package com.baeldung.opaque; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import com.baeldung.opaque.resource.Bar; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; /** * This Live Test requires: * - the Authorization Server to be running * - the Resource Server to be running * */ public class OpaqueResourceServerLiveTest { private final String redirectUrl = "http://localhost:8080/"; private final String authorizeUrlPattern = "http://localhost:8083/auth/realms/baeldung/protocol/openid-connect/auth?response_type=code&client_id=barClient&scope=%s&redirect_uri=" + redirectUrl; private final String tokenUrl = "http://localhost:8083/auth/realms/baeldung/protocol/openid-connect/token"; private final String resourceUrl = "http://localhost:8082/resource-server-opaque/bars"; @SuppressWarnings("unchecked") @Test public void givenUserWithReadScope_whenGetBarResource_thenSuccess() { String accessToken = obtainAccessToken("read"); // Access resources using access token Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .get(resourceUrl); System.out.println(response.asString()); assertThat(response.as(List.class)).hasSizeGreaterThan(0); } @Test public void givenUserWithReadScope_whenPostNewBarResource_thenForbidden() { String accessToken = obtainAccessToken("read"); Bar newBar = new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .body(newBar) .post(resourceUrl); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN.value()); } @Test public void givenUserWithWriteScope_whenPostNewBarResource_thenCreated() { String accessToken = obtainAccessToken("read write"); Bar newBar = new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); Response response = RestAssured.given() .contentType(ContentType.JSON) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .body(newBar) .log() .all() .post(resourceUrl); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED.value()); } private String obtainAccessToken(String scopes) { // obtain authentication url with custom codes Response response = RestAssured.given() .redirects() .follow(false) .get(String.format(authorizeUrlPattern, scopes)); String authSessionId = response.getCookie("AUTH_SESSION_ID"); String kcPostAuthenticationUrl = response.asString() .split("action=\"")[1].split("\"")[0].replace("&amp;", "&"); // obtain authentication code and state response = RestAssured.given() .redirects() .follow(false) .cookie("AUTH_SESSION_ID", authSessionId) .formParams("username", "<EMAIL>", "password", "<PASSWORD>", "credentialId", "") .post(kcPostAuthenticationUrl); assertThat(HttpStatus.FOUND.value()).isEqualTo(response.getStatusCode()); // extract authorization code String location = response.getHeader(HttpHeaders.LOCATION); String code = location.split("code=")[1].split("&")[0]; // get access token Map<String, String> params = new HashMap<String, String>(); params.put("grant_type", "authorization_code"); params.put("code", code); params.put("client_id", "barClient"); params.put("redirect_uri", redirectUrl); params.put("client_secret", "barClientSecret"); response = RestAssured.given() .formParams(params) .post(tokenUrl); return response.jsonPath() .getString("access_token"); } }
1,722
1,444
<gh_stars>1000+ package org.mage.test.cards.single.tsp; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * @author TheElk801 */ public class GauntletOfPowerTest extends CardTestPlayerBase { private static final String gauntlet = "Gauntlet of Power"; private static final String red = "Red"; private static final String maaka = "Feral Maaka"; private static final String myr = "Hovermyr"; @Test public void testBoost() { addCard(Zone.BATTLEFIELD, playerA, "Mountain", 5); addCard(Zone.BATTLEFIELD, playerA, maaka); addCard(Zone.BATTLEFIELD, playerA, myr); addCard(Zone.HAND, playerA, gauntlet); setChoice(playerA, red); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, gauntlet); setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); assertAllCommandsUsed(); assertPowerToughness(playerA, maaka, 2 + 1, 2 + 1); assertPowerToughness(playerA, myr, 1, 2); } @Test public void testControllerMana() { addCard(Zone.BATTLEFIELD, playerA, "Mountain", 6); addCard(Zone.HAND, playerA, gauntlet); addCard(Zone.HAND, playerA, maaka); setChoice(playerA, red); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, gauntlet); castSpell(1, PhaseStep.POSTCOMBAT_MAIN, playerA, maaka); setStrictChooseMode(true); setStopAt(1, PhaseStep.END_TURN); execute(); assertAllCommandsUsed(); assertPowerToughness(playerA, maaka, 2 + 1, 2 + 1); } @Test public void testNotControllerMana() { addCard(Zone.BATTLEFIELD, playerA, "Mountain", 5); addCard(Zone.HAND, playerA, gauntlet); addCard(Zone.BATTLEFIELD, playerB, "Mountain"); addCard(Zone.HAND, playerB, maaka); setChoice(playerA, red); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, gauntlet); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerB, maaka); setStrictChooseMode(true); setStopAt(2, PhaseStep.END_TURN); execute(); assertAllCommandsUsed(); assertPowerToughness(playerB, maaka, 2 + 1, 2 + 1); } }
976
799
GET_ALERTS_CONTEXT = [ {'ack': 'no', 'action': 'notified', 'alertUrl': 'https://FireEyeEX/emps/eanalysis?e_id=9&type=url', 'applianceId': 'appid', 'attackTime': '2021-02-14 09:42:43 +0000', 'dst': {'smtpTo': '<EMAIL>'}, 'explanation': {'malwareDetected': {'malware': [{'md5Sum': '271c1bcd28d01c6863fdb5b5c5d94e73', 'name': 'FETestEvent', 'sha256': 'abebb5862eea61a3d0a1c75bf5a2e2abcd6c4ee6a6ad086e1d518445594970fc'}]}, 'osChanges': []}, 'id': 1, 'malicious': 'yes', 'name': 'MALWARE_OBJECT', 'occurred': '2021-02-14 09:42:47 +0000', 'product': 'EMAIL_MPS', 'scVersion': '1115.212', 'severity': 'MAJR', 'smtpMessage': {'subject': 'test'}, 'src': {'smtpMailFrom': '<EMAIL>'}, 'uuid': 'uuid', 'vlan': 0}, {'ack': 'no', 'action': 'notified', 'alertUrl': 'https://FireEyeEX/emps/eanalysis?e_id=10&type=url', 'applianceId': 'appid', 'attackTime': '2021-02-14 09:43:51 +0000', 'dst': {'smtpTo': '<EMAIL>'}, 'explanation': {'malwareDetected': {'malware': [{'md5Sum': '6efaa05d0d98711416f7d902639155fb', 'name': 'FETestEvent', 'sha256': '340d367ebe68ad833ea055cea7678463a896d03eae86f7816cc0c836b9508fa8'}]}, 'osChanges': []}, 'id': 2, 'malicious': 'yes', 'name': 'MALWARE_OBJECT', 'occurred': '2021-02-14 09:43:55 +0000', 'product': 'EMAIL_MPS', 'scVersion': '1115.212', 'severity': 'MAJR', 'smtpMessage': {'subject': 'test'}, 'src': {'smtpMailFrom': '<EMAIL>'}, 'uuid': 'uuid', 'vlan': 0}] GET_ALERTS_DETAILS_CONTEXT = [ {'ack': 'no', 'action': 'notified', 'alertUrl': 'https://FireEyeEX/emps/eanalysis?e_id=12&type=url', 'applianceId': 'appid', 'attackTime': '2021-02-14 09:45:55 +0000', 'dst': {'smtpTo': '<EMAIL>'}, 'explanation': { 'malwareDetected': {'malware': [{'md5Sum': 'a705075df02f217e8bfc9ac5ec2ffee2', 'name': 'Malicious.LIVE.DTI.URL', 'sha256': 'd1eeadbb4e3d1c57af5a069a0886aa2b4f71484721aafe5c90708b66b8d0090a'}]}, 'osChanges': []}, 'id': 3, 'malicious': 'yes', 'name': 'MALWARE_OBJECT', 'occurred': '2021-02-14 09:45:58 +0000', 'product': 'EMAIL_MPS', 'scVersion': '1115.212', 'severity': 'MAJR', 'smtpMessage': {'subject': 'test'}, 'src': {'smtpMailFrom': '<EMAIL>'}, 'uuid': 'uuid', 'vlan': 0}] GET_ARTIFACTS_METADATA_CONTEXT = { "artifactsInfoList": [ { "artifactName": "name", "artifactSize": "269", "artifactType": "original_email" } ], "uuid": "uuid" } QUARANTINED_EMAILS_CONTEXT = [ { 'completed_at': '2021-06-14T16:01:15', 'email_uuid': 'email_uuid', 'from': 'undisclosed_sender', 'message_id': 'queue-id-queue@no-message-id', 'quarantine_path': '/data/email-analysis/quarantine2/2021-06-14/16/queue', 'queue_id': 'queue', 'subject': 'test' }, { 'completed_at': '2021-06-14T16:01:15', 'email_uuid': 'email_uuid', 'from': 'undisclosed_sender', 'message_id': 'queue-id-queue@no-message-id', 'quarantine_path': '/data/email-analysis/quarantine2/2021-06-14/16/queue', 'queue_id': 'queue', 'subject': 'test' } ] ALLOWEDLIST = [ { "created_at": "2021/06/14 10:41:31", "matches": 7, "name": "www.demisto.com" }, { "created_at": "2021/06/14 10:43:13", "matches": 2, "name": "www.demisto2.com" } ] BLOCKEDLIST = [ { "created_at": "2021/04/19 14:22:06", "matches": 0, "name": "<EMAIL>" }, { "created_at": "2021/04/19 14:27:35", "matches": 0, "name": "www.blocksite1.net/path/test.html" } ]
2,371
2,542
<gh_stars>1000+ // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Naming { class StoreService::ProcessUpdateServiceRequestAsyncOperation : public ProcessRequestAsyncOperation { public: ProcessUpdateServiceRequestAsyncOperation( Transport::MessageUPtr && request, __in NamingStore &, __in StoreServiceProperties &, Common::TimeSpan timeout, Common::AsyncCallback const & callback, Common::AsyncOperationSPtr const & root); protected: __declspec(property(get=get_RequestBody, put=set_RequestBody)) UpdateServiceRequestBody const & RequestBody; UpdateServiceRequestBody const & get_RequestBody() const { return body_; } void set_RequestBody(UpdateServiceRequestBody && value) { body_ = value; } void OnCompleted(); DEFINE_PERF_COUNTERS ( AOUpdateService ) Common::ErrorCode HarvestRequestMessage(Transport::MessageUPtr &&); void PerformRequest(Common::AsyncOperationSPtr const &); private: // ****************************************** // Please refer to comments for name creation // // The AO drives consistency of the update operation, so // a ServiceUpdateDescription is persisted on the AO // until the operation completes successfully at the NO. // // While the update operation is pending, the UserServiceState // on the hierarchy name is marked Updating (the tentative // state for an update operation). The state is set back // to Created and the persisted ServiceUpdateDescription is // deleted once the NO returns success. // // The NO does *not* set any tentative state while // the update request is pending at the FM. The // updated ServiceDescription is only persisted // by the NO after the FM returns success. This is so // that GetServiceDescription can continue to return the // old ServiceDescription while an update is pending. // // From the client's perspective, you do not expect to // read the new ServiceDescription from Naming until // the update request completes successfully. Even then, // the various caches around the cluster may take some // time to update after the FM starts acting on the // updated ServiceDescription. // // ****************************************** void OnNamedLockAcquireComplete(Common::AsyncOperationSPtr const &, bool expectedCompletedSynchronously); void StartUpdateService(Common::AsyncOperationSPtr const & thisSPtr); void OnTentativeUpdateComplete(Common::AsyncOperationSPtr const &, bool expectedCompletedSynchronously); void StartResolveNameOwner(Common::AsyncOperationSPtr const &); void OnResolveNameOwnerComplete(Common::AsyncOperationSPtr const &, bool expectedCompletedSynchronously); void StartRequestToNameOwner(Common::AsyncOperationSPtr const &); void OnRequestReplyToPeerComplete(Common::AsyncOperationSPtr const &, bool expectedCompletedSynchronously); void FinishUpdateService(Common::AsyncOperationSPtr const &); void OnUpdateServiceComplete(Common::AsyncOperationSPtr const &, bool expectedCompletedSynchronously); UpdateServiceRequestBody body_; bool hasNamedLock_; SystemServices::SystemServiceLocation nameOwnerLocation_; Common::ErrorCode validationError_; }; }
1,210
6,036
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "gtest/gtest.h" #include "test/providers/provider_test_utils.h" namespace onnxruntime { namespace test { template <typename T> void RunTypedTest() { // Skip tensorrt for INT8 tests bool exclude_tensorrt = std::is_same<T, int8_t>::value; // int32_t indices - axis 0 OpTester test1("GatherElements", 11); test1.AddAttribute<int64_t>("axis", 0LL); test1.AddInput<T>("data", {2, 3}, {0, 1, 2, 3, 4, 5}); test1.AddInput<int32_t>("indices", {1, 2}, {0, 1}); test1.AddOutput<T>("output", {1, 2}, {0, 4}); if (exclude_tensorrt) { test1.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); } else { test1.Run(); } // int32_t indices - axis 1 OpTester test2("GatherElements", 11); test2.AddAttribute<int64_t>("axis", 1LL); test2.AddInput<T>("data", {2, 2}, {1, 2, 3, 4}); test2.AddInput<int32_t>("indices", {2, 2}, {0, 0, 1, 0}); test2.AddOutput<T>("output", {2, 2}, {1, 1, 4, 3}); if (exclude_tensorrt) { test2.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); } else { test2.Run(); } // int64_t indices - axis 1 OpTester test3("GatherElements", 11); test3.AddAttribute<int64_t>("axis", 1LL); test3.AddInput<T>("data", {2, 2}, {1, 2, 3, 4}); test3.AddInput<int64_t>("indices", {2, 2}, {0, 0, 1, 0}); test3.AddOutput<T>("output", {2, 2}, {1, 1, 4, 3}); if (exclude_tensorrt) { test3.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); } else { test3.Run(); } // negative indices - axis 1 OpTester test4("GatherElements", 11); test4.AddAttribute<int64_t>("axis", 1LL); test4.AddInput<T>("data", {2, 2}, {1, 2, 3, 4}); test4.AddInput<int64_t>("indices", {2, 2}, {0, 0, -1, -1}); test4.AddOutput<T>("output", {2, 2}, {1, 1, 4, 4}); // skip TensorRT because it doesn't support negative indices test4.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); // indices out of bounds OpTester test5("GatherElements", 11); test5.AddAttribute<int64_t>("axis", 1LL); test5.AddInput<T>("data", {2, 2}, {1, 2, 3, 4}); test5.AddInput<int64_t>("indices", {2, 2}, {0, 0, 2, 2}); test5.AddOutput<T>("output", {2, 2}, {1, 1, 4, 4}); // skip nuphar, which will not throw error message but will ensure no out-of-bound access // skip cuda as the cuda kernel won't throw the error message // skip openvino which will not throw error message but will ensure no out-of-bound access // skip TensorRT because it doesn't support out of bounds indices test5.Run(OpTester::ExpectResult::kExpectFailure, "GatherElements op: Value in indices must be within bounds [-2 , 1]. Actual value is 2", {kNupharExecutionProvider, kCudaExecutionProvider, kRocmExecutionProvider, kOpenVINOExecutionProvider, kTensorrtExecutionProvider}); // 3D input - axis 1 OpTester test6("GatherElements", 11); test6.AddAttribute<int64_t>("axis", 1LL); test6.AddInput<T>("data", {2, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8}); test6.AddInput<int64_t>("indices", {1, 2, 1}, {0, 1}); test6.AddOutput<T>("output", {1, 2, 1}, {1, 3}); if (exclude_tensorrt) { test6.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); } else { test6.Run(); } // 3D input - axis 2 OpTester test7("GatherElements", 11); test7.AddAttribute<int64_t>("axis", 2LL); test7.AddInput<T>("data", {2, 2, 2}, {1, 2, 3, 4, 5, 6, 7, 8}); test7.AddInput<int64_t>("indices", {1, 2, 1}, {0, 1}); test7.AddOutput<T>("output", {1, 2, 1}, {1, 4}); if (exclude_tensorrt) { test7.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); } else { test7.Run(); } // 2D input - axis 1 OpTester test8("GatherElements", 11); test8.AddAttribute<int64_t>("axis", 1LL); test8.AddInput<T>("data", {3, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); test8.AddInput<int64_t>("indices", {3, 2}, {1, 0, 0, 1, 0, 1}); test8.AddOutput<T>("output", {3, 2}, {2, 1, 4, 5, 7, 8}); if (exclude_tensorrt) { test8.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); } else { test8.Run(); } // 2D input - axis 1 OpTester test9("GatherElements", 11); test9.AddAttribute<int64_t>("axis", 0LL); test9.AddInput<T>("data", {3, 3}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); test9.AddInput<int64_t>("indices", {3, 2}, {1, 0, 0, 1, 0, 1}); test9.AddOutput<T>("output", {3, 2}, {4, 2, 1, 5, 1, 5}); if (exclude_tensorrt) { test9.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); } else { test9.Run(); } // 1D input - axis 0 OpTester test10("GatherElements", 11); test10.AddAttribute<int64_t>("axis", 0LL); test10.AddInput<T>("data", {3}, {1, 2, 3}); test10.AddInput<int64_t>("indices", {2}, {1, 0}); test10.AddOutput<T>("output", {2}, {2, 1}); if (exclude_tensorrt) { test10.Run(OpTester::ExpectResult::kExpectSuccess, "", {kTensorrtExecutionProvider}); } else { test10.Run(); } } template <> void RunTypedTest<bool>() { // 3D input - axis 2 OpTester test1("GatherElements", 11); test1.AddAttribute<int64_t>("axis", 2LL); test1.AddInput<bool>("data", {2, 2, 2}, {true, false, true, false, true, false, true, false}); test1.AddInput<int64_t>("indices", {1, 2, 1}, {0, 1}); test1.AddOutput<bool>("output", {1, 2, 1}, {true, false}); test1.Run(); } template <> void RunTypedTest<std::string>() { // int32_t indices - axis 0 OpTester test1("GatherElements", 11); test1.AddAttribute<int64_t>("axis", 0LL); test1.AddInput<std::string>("data", {2, 3}, {"a", "b", "c", "d", "e", "f"}); test1.AddInput<int32_t>("indices", {1, 2}, {0, 1}); test1.AddOutput<std::string>("output", {1, 2}, {"a", "e"}); test1.Run(); // int32_t indices - axis 1 OpTester test2("GatherElements", 11); test2.AddAttribute<int64_t>("axis", 1LL); test2.AddInput<std::string>("data", {2, 2}, {"a", "b", "c", "d"}); test2.AddInput<int32_t>("indices", {2, 2}, {0, 0, 1, 0}); test2.AddOutput<std::string>("output", {2, 2}, {"a", "a", "d", "c"}); test2.Run(); // negative indices - axis 1 OpTester test3("GatherElements", 11); test3.AddAttribute<int64_t>("axis", 1LL); test3.AddInput<std::string>("data", {2, 2}, {"a", "b", "c", "d"}); test3.AddInput<int32_t>("indices", {2, 2}, {0, 0, -1, -1}); test3.AddOutput<std::string>("output", {2, 2}, {"a", "a", "d", "d"}); test3.Run(); // indices out of bounds OpTester test4("GatherElements", 11); test4.AddAttribute<int64_t>("axis", 1LL); test4.AddInput<std::string>("data", {2, 2}, {"a", "b", "c", "d"}); test4.AddInput<int32_t>("indices", {2, 2}, {0, 0, -3, -3}); test4.AddOutput<std::string>("output", {2, 2}, {"a", "a", "d", "d"}); // skip nuphar, which will not throw error message but will ensure no out-of-bound access // skip Openvino, which will not throw error message but will ensure no out-of-bound access test4.Run(OpTester::ExpectResult::kExpectFailure, "GatherElements op: Value in indices must be within bounds [-2 , 1]. Actual value is -3", {kNupharExecutionProvider, kOpenVINOExecutionProvider}); // 3D input - axis 1 OpTester test5("GatherElements", 11); test5.AddAttribute<int64_t>("axis", 1LL); test5.AddInput<std::string>("data", {2, 2, 2}, {"a", "b", "c", "d", "e", "f", "g", "h"}); test5.AddInput<int32_t>("indices", {1, 2, 1}, {0, 1}); test5.AddOutput<std::string>("output", {1, 2, 1}, {"a", "c"}); test5.Run(); // 3D input - axis 2 OpTester test6("GatherElements", 11); test6.AddAttribute<int64_t>("axis", 2LL); test6.AddInput<std::string>("data", {2, 2, 2}, {"a", "b", "c", "d", "e", "f", "g", "h"}); test6.AddInput<int32_t>("indices", {1, 2, 1}, {0, 1}); test6.AddOutput<std::string>("output", {1, 2, 1}, {"a", "d"}); test6.Run(); // 2D input - axis 1 OpTester test7("GatherElements", 11); test7.AddAttribute<int64_t>("axis", 1LL); test7.AddInput<std::string>("data", {3, 3}, {"a", "b", "c", "d", "e", "f", "g", "h", "i"}); test7.AddInput<int64_t>("indices", {3, 2}, {1, 0, 0, 1, 0, 1}); test7.AddOutput<std::string>("output", {3, 2}, {"b", "a", "d", "e", "g", "h"}); test7.Run(); // 2D input - axis 2 OpTester test8("GatherElements", 11); test8.AddAttribute<int64_t>("axis", 0LL); test8.AddInput<std::string>("data", {3, 3}, {"a", "b", "c", "d", "e", "f", "g", "h", "i"}); test8.AddInput<int64_t>("indices", {3, 2}, {1, 0, 0, 1, 0, 1}); test8.AddOutput<std::string>("output", {3, 2}, {"d", "b", "a", "e", "a", "e"}); test8.Run(); } // Disable TensorRT due to missing int8 calibrator TEST(GatherElementsOpTest, int8_t) { RunTypedTest<int8_t>(); } TEST(GatherElementsOpTest, int16_t) { RunTypedTest<int16_t>(); } TEST(GatherElementsOpTest, int32_t) { RunTypedTest<int32_t>(); } TEST(GatherElementsOpTest, int64_t) { RunTypedTest<int64_t>(); } TEST(GatherElementsOpTest, uint8_t) { RunTypedTest<uint8_t>(); } TEST(GatherElementsOpTest, uint16_t) { RunTypedTest<uint16_t>(); } TEST(GatherElementsOpTest, uint32_t) { RunTypedTest<uint32_t>(); } TEST(GatherElementsOpTest, uint64_t) { RunTypedTest<uint64_t>(); } TEST(GatherElementsOpTest, float) { RunTypedTest<float>(); } TEST(GatherElementsOpTest, double) { RunTypedTest<double>(); } TEST(GatherElementsOpTest, bool) { RunTypedTest<bool>(); } TEST(GatherElementsOpTest, string) { RunTypedTest<std::string>(); } TEST(GatherElementsOpTest, BigIndices) { // int32_t indices - axis 0 OpTester test1("GatherElements", 11); test1.AddAttribute<int64_t>("axis", 0LL); const int kNumIndices = 10 * 1000; // must be >= kParallelizationThreshold in gather_elements.cc std::vector<float> input(2 * kNumIndices); std::iota(std::begin(input), std::end(input), 0.f); test1.AddInput<float>("data", {2, kNumIndices}, input); std::vector<int32_t> indices(kNumIndices, 0); std::vector<float> output(kNumIndices); std::iota(std::begin(output), std::end(output), 0.f); test1.AddInput<int32_t>("indices", {1, kNumIndices}, indices); test1.AddOutput<float>("output", {1, kNumIndices}, output); test1.Run(); } } // namespace test } // namespace onnxruntime
6,734
6,320
/* * * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.aws.janitor.rule.generic; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.janitor.Rule; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * A rule for excluding resources that contain the provided tags (name and value). * * If a resource contains the tag and the appropriate value, it will be excluded from any * other janitor rules and will not be cleaned. * */ public class TagValueExclusionRule implements Rule { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(TagValueExclusionRule.class); private final Map<String,String> tags; /** * Constructor for TagValueExclusionRule. * * @param tags * Set of tags and values to match for exclusion */ public TagValueExclusionRule(Map<String, String> tags) { this.tags = tags; } /** * Constructor for TagValueExclusionRule. Use this constructor to pass names and values as separate args. * This is intended for convenience when specifying tag names/values in property files. * * Each tag[i] = (name[i], value[i]) * * @param names * Set of names to match for exclusion. Size of names must match size of values. * @param values * Set of values to match for exclusion. Size of names must match size of values. */ public TagValueExclusionRule(String[] names, String[] values) { tags = new HashMap<String,String>(); int i = 0; for(String name : names) { tags.put(name, values[i]); i++; } } @Override public boolean isValid(Resource resource) { Validate.notNull(resource); for (String tagName : tags.keySet()) { String resourceValue = resource.getTag(tagName); if (resourceValue != null && resourceValue.equals(tags.get(tagName))) { LOGGER.debug(String.format("The resource %s has the exclusion tag %s with value %s", resource.getId(), tagName, resourceValue)); return true; } } return false; } }
1,051
1,248
#!/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. import logging import getpass from apache_atlas.client.base_client import AtlasClient from typedef_example import TypeDefExample from entity_example import EntityExample from lineage_example import LineageExample from glossary_example import GlossaryExample from discovery_example import DiscoveryExample from utils import METRIC_CLASSIFICATION, NAME LOG = logging.getLogger('sample-example') class SampleApp: def __init__(self): self.created_entity = None def main(self): # Python3 global input try: input = raw_input except NameError: pass url = input('Enter Atlas URL: ') username = input('Enter username: ') password = getpass.getpass('Enter password: ') client = AtlasClient(url, (username, password)) self.__typedef_example(client) self.__entity_example(client) self.__lineage_example(client) self.__discovery_example(client) self.__glossary_example(client) self.__entity_cleanup() def __typedef_example(self, client): LOG.info("\n---------- Creating Sample Types -----------") typedefExample = TypeDefExample(client) typedefExample.create_type_def() def __entity_example(self, client): LOG.info("\n---------- Creating Sample Entities -----------") self.entityExample = EntityExample(client) self.entityExample.create_entities() self.created_entity = self.entityExample.get_table_entity() if self.created_entity and self.created_entity.guid: self.entityExample.get_entity_by_guid(self.created_entity.guid) def __lineage_example(self, client): LOG.info("\n---------- Lineage example -----------") lineage = LineageExample(client) if self.created_entity: lineage.lineage(self.created_entity.guid) else: LOG.info("Create entity first to get lineage info") def __discovery_example(self, client): LOG.info("\n---------- Search example -----------") discovery = DiscoveryExample(client) discovery.dsl_search() if not self.created_entity: LOG.info("Create entity first to get search info") return discovery.quick_search(self.created_entity.typeName) discovery.basic_search(self.created_entity.typeName, METRIC_CLASSIFICATION, self.created_entity.attributes[NAME]) def __glossary_example(self, client): LOG.info("\n---------- Glossary Example -----------") glossary = GlossaryExample(client) glossary_obj = glossary.create_glossary() if not glossary_obj: LOG.info("Create glossary first") return glossary.create_glossary_term() glossary.get_glossary_detail() glossary.create_glossary_category() glossary.delete_glossary() def __entity_cleanup(self): LOG.info("\n---------- Deleting Entities -----------") self.entityExample.remove_entities() if __name__ == "__main__": SampleApp().main()
1,500
1,436
<gh_stars>1000+ // // NTESSessionListViewController.h // DemoApplication // // Created by chris on 2017/10/16. // Copyright © 2017年 chrisRay. All rights reserved. // #import <NIMKit/NIMKit.h> @interface NTESSessionListViewController : NIMSessionListViewController @end
96
429
#include <wchar.h> #include <stdio.h> wchar_t * wcscat(wchar_t *dest, const wchar_t *src) { wchar_t * end = dest; while (*end != 0) { ++end; } while (*src) { *end = *src; end++; src++; } *end = 0; return dest; } wchar_t * wcsncat(wchar_t *dest, const wchar_t * src, size_t n) { wchar_t * end = dest; size_t c = 0; while (*end != 0) { ++end; } while (*src && c < n) { *end = *src; end++; src++; c++; } *end = 0; return dest; }
241
468
<gh_stars>100-1000 #define GLI_INCLUDE_WGL_NV_VIDEO_OUTPUT enum Main { WGL_BIND_TO_VIDEO_RGB_NV = 0x20C0, WGL_BIND_TO_VIDEO_RGBA_NV = 0x20C1, WGL_BIND_TO_VIDEO_RGB_AND_DEPTH_NV = 0x20C2, WGL_VIDEO_OUT_COLOR_NV = 0x20C3, WGL_VIDEO_OUT_ALPHA_NV = 0x20C4, WGL_VIDEO_OUT_DEPTH_NV = 0x20C5, WGL_VIDEO_OUT_COLOR_AND_ALPHA_NV = 0x20C6, WGL_VIDEO_OUT_COLOR_AND_DEPTH_NV = 0x20C7, WGL_VIDEO_OUT_FRAME = 0x20C8, WGL_VIDEO_OUT_FIELD_1 = 0x20C9, WGL_VIDEO_OUT_FIELD_2 = 0x20CA, WGL_VIDEO_OUT_STACKED_FIELDS_1_2 = 0x20CB, WGL_VIDEO_OUT_STACKED_FIELDS_2_1 = 0x20CC, }; GLboolean wglGetVideoDeviceNV(void* hDC, GLint numDevices, void* * hVideoDevice); GLboolean wglReleaseVideoDeviceNV(void* hVideoDevice); GLboolean wglBindVideoImageNV(void* hVideoDevice, void* hPbuffer, GLint iVideoBuffer); GLboolean wglReleaseVideoImageNV(void* hPbuffer, GLint iVideoBuffer); GLboolean wglSendPbufferToVideoNV(void* hPbuffer, GLint iBufferType, GLuint * pulCounterPbuffer, GLboolean bBlock); GLboolean wglGetVideoInfoNV(void* hpVideoDevice, GLuint * pulCounterOutputPbuffer, GLuint * pulCounterOutputVideo);
680