max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,657
<reponame>mens-artis/Auto-PyTorch from autoPyTorch.core.autonet_classes.autonet_feature_data import AutoNetFeatureData class AutoNetMultilabel(AutoNetFeatureData): preset_folder_name = "feature_multilabel" # OVERRIDE @staticmethod def _apply_default_pipeline_settings(pipeline): from autoPyTorch.pipeline.nodes.network_selector import NetworkSelector from autoPyTorch.pipeline.nodes.loss_module_selector import LossModuleSelector from autoPyTorch.pipeline.nodes.metric_selector import MetricSelector from autoPyTorch.pipeline.nodes.train_node import TrainNode from autoPyTorch.pipeline.nodes.cross_validation import CrossValidation import torch.nn as nn from autoPyTorch.components.metrics import multilabel_accuracy, auc_metric, pac_metric from autoPyTorch.components.preprocessing.loss_weight_strategies import LossWeightStrategyWeightedBinary AutoNetFeatureData._apply_default_pipeline_settings(pipeline) net_selector = pipeline[NetworkSelector.get_name()] net_selector.add_final_activation('sigmoid', nn.Sigmoid()) loss_selector = pipeline[LossModuleSelector.get_name()] loss_selector.add_loss_module('bce_with_logits', nn.BCEWithLogitsLoss, None, False) loss_selector.add_loss_module('bce_with_logits_weighted', nn.BCEWithLogitsLoss, LossWeightStrategyWeightedBinary(), False) metric_selector = pipeline[MetricSelector.get_name()] metric_selector.add_metric('multilabel_accuracy', multilabel_accuracy, loss_transform=True, requires_target_class_labels=True) metric_selector.add_metric('auc_metric', auc_metric, loss_transform=True, requires_target_class_labels=False) metric_selector.add_metric('pac_metric', pac_metric, loss_transform=True, requires_target_class_labels=False) train_node = pipeline[TrainNode.get_name()] train_node.default_minimize_value = False cv = pipeline[CrossValidation.get_name()] cv.use_stratified_cv_split_default = False
902
765
<gh_stars>100-1000 # TestObjCImportedTypes.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ------------------------------------------------------------------------------ """n Test that we are able to deal with ObjC-imported types """ import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * import lldbsuite.test.lldbutil as lldbutil import os import unittest2 class TestSwiftObjCImportedTypes(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) @swiftTest @skipUnlessDarwin def test_swift_objc_imported_types(self): """Test that we are able to deal with ObjC-imported types""" self.build() lldbutil.run_to_source_breakpoint( self, 'Set breakpoint here', lldb.SBFileSpec('main.swift')) nss = self.frame().FindVariable("nss") nsn = self.frame().FindVariable("nsn") nsmo = self.frame().FindVariable("nsmo") nsmd = self.frame().FindVariable("nsmd") lldbutil.check_variable( self, nss, use_dynamic=False, typename="Foundation.NSString") lldbutil.check_variable( self, nsn, use_dynamic=False, typename="Foundation.NSNumber") lldbutil.check_variable( self, nsmo, use_dynamic=False, typename="CoreData.NSManagedObject") lldbutil.check_variable( self, nsmd, use_dynamic=False, typename="Foundation.NSMutableDictionary") lldbutil.check_variable(self, nss, use_dynamic=True, summary='"abc"') lldbutil.check_variable(self, nsn, use_dynamic=True, summary='Int64(3)') lldbutil.check_variable( self, nsmo, use_dynamic=True, typename='CoreData.NSManagedObject') lldbutil.check_variable( self, nsmd, use_dynamic=True, summary='1 key/value pair') if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lldb.SBDebugger.Terminate) unittest2.main()
1,143
2,177
package org.nutz.castor.model; import java.io.Serializable; import java.util.List; import java.util.Map; /** * create by zhouwenqing 2017/7/26 . */ @SuppressWarnings("rawtypes") public class User extends BaseTreeEntity<Long, User> implements Serializable { private static final long serialVersionUID = -1943438256837838021L; private String userName; private Integer age; private Map params; private List list; public List getList() { return list; } public void setList(List list) { this.list = list; } public Map getParams() { return params; } public void setParams(Map params) { this.params = params; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
389
17,104
// Tencent is pleased to support the open source community by making Mars available. // Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. // Licensed under the MIT License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://opensource.org/licenses/MIT // 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. /* * zombie_task_manager.h * * Created on: 2014-6-19 * Author: yerungui * Copyright (c) 2013-2015 Tencent. All rights reserved. * */ #ifndef STN_SRC_ZOMBIE_TASK_MANAGER_H_ #define STN_SRC_ZOMBIE_TASK_MANAGER_H_ #include <list> #include <stdint.h> #include "boost/function.hpp" #include "mars/comm/messagequeue/message_queue.h" #include "mars/stn/stn.h" struct ZombieTask; namespace mars { namespace stn { class ZombieTaskManager { public: boost::function<void (const Task& _task)> fun_start_task_; boost::function<int (ErrCmdType _errtype, int _errcode, int _fail_handle, const Task& _task, unsigned int _taskcosttime)> fun_callback_; public: ZombieTaskManager(comm::MessageQueue::MessageQueue_t _messagequeueid); ~ZombieTaskManager(); bool SaveTask(const Task& _task, unsigned int _taskcosttime /*ms*/); bool StopTask(uint32_t _taskid); bool HasTask(uint32_t _taskid) const; void ClearTasks(); void RedoTasks(); void OnNetCoreStartTask(); private: ZombieTaskManager(const ZombieTaskManager&); ZombieTaskManager& operator=(const ZombieTaskManager&); private: void __StartTask(); void __TimerChecker(); private: comm::MessageQueue::ScopeRegister asyncreg_; std::list<ZombieTask> lsttask_; uint64_t net_core_last_start_task_time_; }; } } #endif // STN_SRC_ZOMBIE_TASK_MANAGER_H_
715
3,442
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.sip.communicator.impl.gui.main.call; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.plugin.desktoputil.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * Represents an UI means to park (the <tt>Call</tt> of) an associated * <tt>CallParticipant</tt>. * * @author <NAME> */ public class ParkCallButton extends CallToolBarButton { /** * Our class logger. */ private static final Logger logger = Logger.getLogger(ParkCallButton.class); /** * The <tt>Call</tt> to be parked. */ private final Call call; /** * Initializes a new <tt>ParkCallButton</tt> instance which is to * park (the <tt>Call</tt> of) a specific * <tt>CallPeer</tt>. * * @param c the <tt>Call</tt> to be associated with the new instance and * to be parked */ public ParkCallButton(Call c) { super( ImageLoader.getImage(ImageLoader.PARK_CALL_BUTTON), GuiActivator.getResources().getI18NString( "service.gui.PARK_BUTTON_TOOL_TIP")); this.call = c; addActionListener(new ActionListener() { /** * Invoked when an action occurs. * * @param evt the <tt>ActionEvent</tt> instance containing the * data associated with the action and the act of its performing */ public void actionPerformed(ActionEvent evt) { parkCall(); } }); } /** * Parks the given <tt>callPeer</tt>. */ private void parkCall() { OperationSetTelephonyPark parkOpSet = call.getProtocolProvider() .getOperationSet(OperationSetTelephonyPark.class); // If the park operation set is null we have nothing more to // do here. if (parkOpSet == null) return; // We support park for one-to-one calls only. CallPeer peer = call.getCallPeers().next(); JPopupMenu parkMenu = createParkMenu(peer); Point location = new Point(getX(), getY() + getHeight()); SwingUtilities.convertPointToScreen(location, getParent()); parkMenu.setLocation(location); parkMenu.setVisible(true); } /** * Creates the menu responsible for parking slot input. * * @return the created popup menu */ private JPopupMenu createParkMenu(final CallPeer peer) { final SIPCommTextField textField = new SIPCommTextField(""); textField.setColumns(10); final JPopupMenu popupMenu = new SIPCommPopupMenu() { @Override public void setVisible(boolean b) { super.setVisible(b); if(b) textField.requestFocus(); } }; popupMenu.setInvoker(this); popupMenu.setFocusable(true); TransparentPanel content = new TransparentPanel(); JLabel parkingSlot = new JLabel(GuiActivator.getResources() .getI18NString("service.gui.PARKING_SLOT")); content.add(parkingSlot); content.add(textField); textField.requestFocus(); JButton button = new JButton(GuiActivator.getResources() .getI18NString("service.gui.PARK")); content.add(button); popupMenu.add(content); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { popupMenu.setVisible(false); OperationSetTelephonyPark parkOpSet = call.getProtocolProvider() .getOperationSet(OperationSetTelephonyPark.class); try { parkOpSet.parkCall(textField.getText(), peer); } catch (OperationFailedException ex) { logger.error("Failed to park " + peer.getAddress() + " to " + textField.getText(), ex); } } }); return popupMenu; } }
2,191
4,071
/* Copyright (C) 2016-2018 Alibaba Group Holding Limited 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 TDM_SERVING_MODEL_BLAZE_BLAZE_PREDICT_CONTEXT_H_ #define TDM_SERVING_MODEL_BLAZE_BLAZE_PREDICT_CONTEXT_H_ #include "model/predict_context.h" #include "blaze/include/predictor.h" namespace tdm_serving { class BlazePredictContext : public PredictContext { public: BlazePredictContext() : predictor_(NULL) {} virtual ~BlazePredictContext() { delete predictor_; } void set_predictor(blaze::Predictor* predictor) { predictor_ = predictor; } blaze::Predictor* predictor() const { return predictor_; } private: // blaze object, stores session data and predicts score blaze::Predictor* predictor_; }; } // namespace tdm_serving #endif // TDM_SERVING_MODEL_BLAZE_BLAZE_PREDICT_CONTEXT_H_
431
349
package com.jakewharton.rx; import io.reactivex.Notification; import io.reactivex.Observable; import io.reactivex.functions.Function; import io.reactivex.observables.GroupedObservable; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; public final class WindowIfChangedTest { private final Function<Message, String> userSelector = new Function<Message, String>() { @Override public String apply(Message message) { return message.user; } }; @Test public void splits() { Observable<Message> messages = Observable.just( // new Message("Bob", "Hello"), // new Message("Bob", "World"), // new Message("Alice", "Hey"), // new Message("Bob", "What's"), // new Message("Bob", "Up?"), // new Message("Eve", "Hey") // ); final AtomicInteger seen = new AtomicInteger(); WindowIfChanged.create(messages, userSelector) .switchMap( new Function<GroupedObservable<String, Message>, Observable<Notification<String>>>() { @Override public Observable<Notification<String>> apply( GroupedObservable<String, Message> group) { final int count = seen.incrementAndGet(); return group.map(new Function<Message, String>() { @Override public String apply(Message message) throws Exception { return count + " " + message; } }).materialize(); } }) .test() .assertValues( // Notification.createOnNext("1 Bob Hello"), // Notification.createOnNext("1 Bob World"), // Notification.<String>createOnComplete(), // Notification.createOnNext("2 Alice Hey"), // Notification.<String>createOnComplete(), // Notification.createOnNext("3 Bob What's"), // Notification.createOnNext("3 Bob Up?"), // Notification.<String>createOnComplete(), // Notification.createOnNext("4 Eve Hey"), // Notification.<String>createOnComplete()); // } @Test public void completeCompletesInner() { Observable<Message> messages = Observable.just(new Message("Bob", "Hello")); final AtomicInteger seen = new AtomicInteger(); WindowIfChanged.create(messages, userSelector) .switchMap( new Function<GroupedObservable<String, Message>, Observable<Notification<String>>>() { @Override public Observable<Notification<String>> apply( GroupedObservable<String, Message> group) { final int count = seen.incrementAndGet(); return group.map(new Function<Message, String>() { @Override public String apply(Message message) throws Exception { return count + " " + message; } }).materialize(); } }) .test() .assertValues( // Notification.createOnNext("1 Bob Hello"), // Notification.<String>createOnComplete()) // .assertComplete(); } @Test public void errorCompletesInner() { RuntimeException error = new RuntimeException("boom!"); Observable<Message> messages = Observable.just( // Notification.createOnNext(new Message("Bob", "Hello")), Notification.createOnError(error) ).dematerialize(); final AtomicInteger seen = new AtomicInteger(); WindowIfChanged.create(messages, userSelector) .switchMap( new Function<GroupedObservable<String, Message>, Observable<Notification<String>>>() { @Override public Observable<Notification<String>> apply( GroupedObservable<String, Message> group) { final int count = seen.incrementAndGet(); return group.map(new Function<Message, String>() { @Override public String apply(Message message) throws Exception { return count + " " + message; } }).materialize(); } }) .test() .assertValues( // Notification.createOnNext("1 Bob Hello"), // Notification.<String>createOnComplete()) // .assertError(error); } }
1,801
1,603
<gh_stars>1000+ package com.linkedin.datahub.graphql.types.dataprocessinst.mappers; import com.linkedin.datahub.graphql.generated.DataProcessInstanceRunResultType; import com.linkedin.datahub.graphql.types.mappers.ModelMapper; import com.linkedin.dataprocess.DataProcessInstanceRunResult; import javax.annotation.Nonnull; public class DataProcessInstanceRunResultMapper implements ModelMapper< DataProcessInstanceRunResult, com.linkedin.datahub.graphql.generated.DataProcessInstanceRunResult> { public static final DataProcessInstanceRunResultMapper INSTANCE = new DataProcessInstanceRunResultMapper(); public static com.linkedin.datahub.graphql.generated.DataProcessInstanceRunResult map(@Nonnull final DataProcessInstanceRunResult input) { return INSTANCE.apply(input); } @Override public com.linkedin.datahub.graphql.generated.DataProcessInstanceRunResult apply(@Nonnull final DataProcessInstanceRunResult input) { final com.linkedin.datahub.graphql.generated.DataProcessInstanceRunResult result = new com.linkedin.datahub.graphql.generated.DataProcessInstanceRunResult(); if (input.hasType()) { result.setResultType(DataProcessInstanceRunResultType.valueOf(input.getType().toString())); } if (input.hasNativeResultType()) { result.setNativeResultType(input.getNativeResultType()); } return result; } }
487
575
// Copyright 2020 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_CHROMEOS_ARC_ACCESSIBILITY_GEOMETRY_UTIL_H_ #define CHROME_BROWSER_CHROMEOS_ARC_ACCESSIBILITY_GEOMETRY_UTIL_H_ #include "chrome/browser/ash/arc/accessibility/geometry_util.h" #include "components/exo/wm_helper.h" #include "ui/aura/window.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/views/widget/widget.h" namespace arc { gfx::RectF ScaleAndroidPxToChromePx(const gfx::Rect& android_bounds, aura::Window* window) { DCHECK(exo::WMHelper::HasInstance()); DCHECK(window); const float chrome_dsf = window->GetToplevelWindow()->layer()->device_scale_factor(); const float android_dsf = exo::WMHelper::GetInstance()->GetDeviceScaleFactorForWindow(window); if (chrome_dsf == android_dsf) return gfx::RectF(android_bounds); gfx::RectF chrome_bounds(android_bounds); chrome_bounds.Scale(chrome_dsf / android_dsf); return chrome_bounds; } int GetChromeWindowHeightOffsetInDip(aura::Window* window) { // On Android side, content is rendered without considering height of // caption bar when it's maximized, e.g. Content is rendered at y:0 instead of // y:32 where 32 is height of caption bar. views::Widget* widget = views::Widget::GetWidgetForNativeView(window); if (!widget->IsMaximized()) return 0; return widget->non_client_view()->frame_view()->GetBoundsForClientView().y(); } } // namespace arc #endif // CHROME_BROWSER_CHROMEOS_ARC_ACCESSIBILITY_GEOMETRY_UTIL_H_
625
1,818
// // TencentWeibo.h // ShareService // // Created by QFish on 8/8/13. // Copyright (c) 2013 com.bee-framework. All rights reserved. // #import "TencentWeiboApi.h" @interface TencentWeibo : NSObject AS_SINGLETON( TencentWeibo ); @property (nonatomic, retain) NSString * text; @property (nonatomic, retain) NSObject * image; @property (nonatomic, copy) ServiceShareBlock begin; @property (nonatomic, copy) ServiceShareBlock cancel; @property (nonatomic, copy) ServiceShareBlock success; @property (nonatomic, copy) ServiceShareBlockError failure; - (void)share; - (void)authorize; - (void)unauthorize; - (BOOL)isLogin; + (void)configWithAppKey:(NSString *)appKey appSecret:(NSString *)appSecret redirectUri:(NSString *)redirectUri; @end
299
995
<filename>core/src/main/java/zemberek/core/IndexedItem.java<gh_stars>100-1000 package zemberek.core; /** * An item with an index. This is useful when we want to keep track of a sequence of items processed * by a system that would change the processing order. */ public class IndexedItem<T> implements Comparable<IndexedItem> { public final T item; public final int index; public IndexedItem(T item, int index) { this.item = item; this.index = index; } @Override public int compareTo(IndexedItem o) { if (o.index > index) { return 1; } else if (o.index < index) { return -1; } return 0; } @Override public String toString() { return index + ":" + item.toString(); } }
259
883
<reponame>RakhithJK/andriller<gh_stars>100-1000 import os import re import base64 import logging import pathlib import sqlite3 import datetime import functools import xml.etree.ElementTree from contextlib import suppress from . import config from . import engines from .config import SQLITE_MAGIC logger = logging.getLogger(__name__) def sqlite_error_retry(method): @functools.wraps(method) def decorator(*args, **kwargs): try: return method(*args, **kwargs) except sqlite3.OperationalError as err: if 'UTF-8' in str(err): return method(*args, **kwargs, cursor_kw={'text_factory': AndroidDecoder.decode_safe}) raise err return decorator class AndroidDecoder: """ Main decoder class for Android databases. It's subclasses are also used in the Registry. TARGET (str): database name, eg: 'my_database.db' RETARGET (str): a regex-like string, where the database name is not static, eg: 'store_91237635238734535.db' NAMESPACE (str): package namespace options are: db|r|f|sp; 'db' is for 'databases', 'sp' is for 'shared_preferences', etc. PACKAGE (str): package name for the application, eg: 'my_app.example.com' EXTRAS (List[str]): extra support files needed for decoding. """ TARGET = None RETARGET = None NAMESPACE = None # db|r|f|sp PACKAGE = None EXTRAS = [] exclude_from_menus = False exclude_from_registry = False exclude_from_decoding = False # For ambitious target names (eg: '*.db') target_is_db = None title = None template_name = None # HTML template headers = {} # {<key for XLSX>: <Title name for HTML>} def __init__(self, work_dir, input_file, stage=False, **kwargs): """ Contructor options: work_dir (str|Path): directory where to output reports. input_file (str|Path): input file (as intended self.TARGET) locally on the system. stage (bool): if True, the decoder will initialise but won't run decoding. """ self.work_dir = work_dir self.input_file = input_file self.logger = kwargs.get('logger', logger) if not stage: self.logger.debug(f'decoder:{type(self).__name__}') self.logger.debug(f'work_dir:{work_dir}') self.logger.debug(f'input_file:{input_file}') self.DATA = [] # main storage for decoded data self.main() @property def conf(self): if not hasattr(self, '_conf'): self._conf = config.Config() return self._conf def main(self): """ Make the magic happen here populate `self.DATA` list with decoded objects """ pass @property def target_path_ab(self): return self.gen_target_path(self, is_ab=True) @property def target_path_root(self): return self.gen_target_path(self) @property def target_path_posix(self): return self.gen_target_path(self, is_posix=True) @staticmethod def gen_target_path(cls, is_posix=False, is_ab=False): if all([cls.PACKAGE, cls.NAMESPACE, cls.TARGET]): BASE = '' if is_posix else 'apps/' if is_ab else '/data/data/' NS = '*' if is_posix else cls.NAMESPACE if is_ab else cls.get_namespace(cls.NAMESPACE) return f'{BASE}{cls.PACKAGE}/{NS}/{cls.RETARGET or cls.TARGET}' @staticmethod def get_namespace(name): return { 'db': 'databases', 'f': 'files', 'r': 'resources', 'sp': 'shared_prefs', }.get(name, name) def get_artifact(self, path_property): # Pass path property, such as `self.root_path` or `self.ab_path` SQLITE_SUFFIXES = ['', '-shm', '-wal', '-journal'] if self.NAMESPACE == 'db' or self.target_is_db: return [f'{path_property}{suf}' for suf in SQLITE_SUFFIXES] return [path_property] def get_neighbour(self, neighbour, **kwargs): input_dir = os.path.dirname(self.input_file) if neighbour in os.listdir(input_dir): neighbour = os.path.join(input_dir, neighbour) if os.path.isfile(neighbour): return neighbour return False def add_extra(self, namespace, target): class Extra(AndroidDecoder): TARGET = target NAMESPACE = namespace PACKAGE = self.PACKAGE self.EXTRAS.append(Extra) def get_extras(self, **kwargs): return [self.gen_target_path(xtr, **kwargs) for xtr in self.EXTRAS] @staticmethod def name_val(d, key='name', value='value'): return {d[key]: d[value]} @classmethod def staged(cls): return cls(None, None, stage=True) # ----------------------------------------------------------------------------- def check_sqlite_magic(self): if os.path.isfile(self.input_file): with open(self.input_file, 'rb') as R: if R.read(len(SQLITE_MAGIC)) == SQLITE_MAGIC: return True msg = f'Target file `{os.path.basename(self.input_file)}` is not an SQLite database or it is encrypted!' self.logger.error(msg) raise DecoderError(msg) @property def sqlite_readonly(self): self.check_sqlite_magic() input_file = pathlib.PurePath(os.path.abspath(self.input_file)) return f'{input_file.as_uri()}?mode=ro' @staticmethod def zipper(row: sqlite3.Row): return dict(zip(row.keys(), row)) def get_cursor(self, row_factory=None, text_factory=None): with sqlite3.connect(self.sqlite_readonly, uri=True) as conn: if row_factory: conn.row_factory = row_factory if text_factory: conn.text_factory = text_factory return conn.cursor() def get_sql_tables(self, cursor_kw={}): cur = self.get_cursor(**cursor_kw) return tuple(x[0] for x in cur.execute("SELECT name FROM sqlite_master WHERE type='table'")) def get_table_columns(self, table_name, cursor_kw={}): cur = self.get_cursor(**cursor_kw) return tuple(x[1] for x in cur.execute(f"PRAGMA table_info({table_name})")) @sqlite_error_retry def sql_table_as_dict(self, table, columns='*', order_by=None, order="DESC", where={}, cursor_kw={}): cur = self.get_cursor(row_factory=sqlite3.Row, **cursor_kw) # table_names = tuple(x[1] for x in c.execute(f"PRAGMA table_info({table})")) # if (order_by is not None) and (order_by not in table_names): # raise NameError(f"Column `{order_by}` is not in `{table}` table") query = f"SELECT {','.join(columns)} FROM {table}" if where: query += f' WHERE {self.where(where)}' if order_by: query += f" ORDER BY {order_by} {order}" self.logger.debug(f"SQL> {query}") return [*map(self.zipper, cur.execute(query))] def sql_table_rows(self, table, columns='*', where={}, cursor_kw={}): cur = self.get_cursor(**cursor_kw) query = f"SELECT {','.join(columns)} FROM {table}" if where: query += f' WHERE {self.where(where)}' self.logger.debug(f"SQL> {query}") return cur.execute(query).fetchall() @staticmethod def where(params: dict): where_all = [] keyval = lambda k, v: f"{k}='{v}'" # noqa: E731 for key, vals in params.items(): sep = 'OR' if key.startswith('!'): key = key.replace('!', 'NOT ') sep = 'AND' if isinstance(vals, (list, set, tuple)): group = f' {sep} '.join([keyval(key, v) for v in vals]) where_all.append(f'({group})') else: where_all.append(keyval(key, vals)) return ' AND '.join(where_all) def get_head_foot(self): return { 'header': self.conf('custom_header'), 'footer': self.conf('custom_footer'), } def report_html(self): env = engines.get_engine() template = env.get_template(self.template_name) report_file = os.path.join(self.work_dir, f'{self.title}.html') with open(report_file, 'w', encoding='UTF-8') as W: W.write(template.render( DATA=self.DATA, title=self.title, headers=self.headers.values(), **self.get_head_foot())) return os.path.relpath(report_file, self.work_dir) def report_xlsx(self, workbook=None, to_close=False): if not workbook: to_close = True workbook = engines.Workbook(self.work_dir, self.title) sheet = workbook.add_sheet(self.title) col_vals, col_names = zip(*self.headers.items()) workbook.write_header(sheet, col_names) for row, data in enumerate(self.DATA, start=1): data['_id'] = data.get('_id', row) row_vals = (data.get(k) for k in col_vals) sheet.write_row(row, 0, row_vals) if to_close: workbook.close() return os.path.relpath(workbook.file_path, self.work_dir) @staticmethod def duration(value): return f'{str(datetime.timedelta(seconds=value)):0>8}' def unix_to_time(self, unix_stamp: int) -> str: if int(unix_stamp) > 0: d = datetime.datetime.fromtimestamp(int(unix_stamp), self.conf.tzone) return d.strftime(self.conf.date_format) def unix_to_time_ms(self, unix_stamp: int) -> str: if int(unix_stamp) > 0: d = datetime.datetime.fromtimestamp(int(unix_stamp) // 1000, self.conf.tzone) return d.strftime(self.conf.date_format) def webkit_to_time(self, webkit_stamp: int) -> str: if int(webkit_stamp) > 0: epoch = datetime.datetime(1601, 1, 1, tzinfo=self.conf.tzone) d = datetime.timedelta(microseconds=int(webkit_stamp)) return (epoch + d).strftime(self.conf.date_format) @staticmethod def to_chars(data) -> str: if not data: return '' if isinstance(data, bytes): with suppress(Exception): return data.decode('utf-8') if isinstance(data, str): data = data.encode() return ''.join(map(chr, data)) @staticmethod def decode_safe(data: bytes) -> str: return data.decode('utf-8', errors='ignore') @classmethod def safe_str(cls, value): if isinstance(value, (str, float, int)): return value with suppress(AttributeError, UnicodeDecodeError): return value.decode() return cls.to_chars(value) @staticmethod def b64e(data: bytes) -> str: return base64.b64encode(data).decode() @staticmethod def call_type(value): call_types = { 1: 'Received', 2: 'Dialled', 3: 'Missed', 4: 'Voicemail', 5: 'Rejected', 6: 'Blocked', } return call_types.get(value, f'Unknown({value})') @staticmethod def sms_type(value): sms_types = { 1: 'Inbox', 2: 'Sent', 3: 'Draft', # 4: '', # Outgoing? 5: 'Sending failed', 6: 'Sent', } return sms_types.get(value, f'Unknown({value})') @staticmethod def skype_msg_type(value): msg_types = { 1: 'Unsent', 2: 'Sent', 3: 'Unread', 4: 'Read' } return msg_types.get(value, f'Unknown({value})') @staticmethod def skype_call_type(value): return { 5: 'Incoming', 6: 'Outgoing', }.get(value, f'Unknown({value})') @staticmethod def http_status(status): return { 190: 'Pending', 192: 'Running', 193: 'Paused', 200: 'Success', 201: 'Created', 202: 'Accepted', 204: 'No Content', 301: 'Redirected', 302: 'Found', 400: 'Bad Request', 401: 'Unauthorized', 403: 'Not Permitted', 404: 'Not Found', 406: 'Not Acceptable', 488: 'Already Exists', 489: 'Cannot Resume', 490: 'Cancelled', 500: 'Server Error', 502: 'Bad Gateway', 503: 'Unavailable', 504: 'Gateway Timeout', }.get(status, f'Code({status})') @staticmethod def parse_number(value): if not value: return '' value = re.sub(r'(?<=\d)\s(?=\d)', '', str(value)) num_types = {'-2': 'WITHHELD', '-1': 'UNKNOWN'} return num_types.get(value, value) @staticmethod def xml_root(file_path): tree = xml.etree.ElementTree.parse(file_path) return tree.getroot() @classmethod def xml_get_tag_text(cls, file_path, tag, attr, value): root = cls.xml_root(file_path) for t in root.findall(tag): attrib = t.attrib if attr in attrib and value in attrib.values(): return t.text @classmethod def get_subclasses(cls): for sub in cls.__subclasses__(): for ssub in sub.get_subclasses(): yield ssub yield sub # ----------------------------------------------------------------------------- class DecoderError(Exception): pass
6,468
8,569
<reponame>junglerobba/sway #include <libevdev/libevdev.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include "sway/commands.h" #include "sway/config.h" #include "sway/input/cursor.h" #include "list.h" #include "log.h" #include "stringop.h" static struct cmd_results *binding_add(struct bar_binding *binding, list_t *mode_bindings) { const char *name = get_mouse_button_name(binding->button); bool overwritten = false; for (int i = 0; i < mode_bindings->length; i++) { struct bar_binding *other = mode_bindings->items[i]; if (other->button == binding->button && other->release == binding->release) { overwritten = true; mode_bindings->items[i] = binding; free_bar_binding(other); sway_log(SWAY_DEBUG, "[bar %s] Updated binding for %u (%s)%s", config->current_bar->id, binding->button, name, binding->release ? " - release" : ""); break; } } if (!overwritten) { list_add(mode_bindings, binding); sway_log(SWAY_DEBUG, "[bar %s] Added binding for %u (%s)%s", config->current_bar->id, binding->button, name, binding->release ? " - release" : ""); } return cmd_results_new(CMD_SUCCESS, NULL); } static struct cmd_results *binding_remove(struct bar_binding *binding, list_t *mode_bindings) { const char *name = get_mouse_button_name(binding->button); for (int i = 0; i < mode_bindings->length; i++) { struct bar_binding *other = mode_bindings->items[i]; if (other->button == binding->button && other->release == binding->release) { sway_log(SWAY_DEBUG, "[bar %s] Unbound binding for %u (%s)%s", config->current_bar->id, binding->button, name, binding->release ? " - release" : ""); free_bar_binding(other); free_bar_binding(binding); list_del(mode_bindings, i); return cmd_results_new(CMD_SUCCESS, NULL); } } struct cmd_results *error = cmd_results_new(CMD_FAILURE, "Could not " "find binding for [bar %s]" " Button %u (%s)%s", config->current_bar->id, binding->button, name, binding->release ? " - release" : ""); free_bar_binding(binding); return error; } static struct cmd_results *bar_cmd_bind(int argc, char **argv, bool code, bool unbind) { int minargs = 2; const char *command; if (unbind) { minargs--; command = code ? "bar unbindcode" : "bar unbindsym"; } else { command = code ? "bar bindcode" : "bar bindsym"; } struct cmd_results *error = NULL; if ((error = checkarg(argc, command, EXPECTED_AT_LEAST, minargs))) { return error; } struct bar_binding *binding = calloc(1, sizeof(struct bar_binding)); if (!binding) { return cmd_results_new(CMD_FAILURE, "Unable to allocate bar binding"); } binding->release = false; if (strcmp("--release", argv[0]) == 0) { binding->release = true; argv++; argc--; } char *message = NULL; if (code) { binding->button = get_mouse_bindcode(argv[0], &message); } else { binding->button = get_mouse_bindsym(argv[0], &message); } if (message) { free_bar_binding(binding); error = cmd_results_new(CMD_INVALID, message); free(message); return error; } else if (!binding->button) { free_bar_binding(binding); return cmd_results_new(CMD_INVALID, "Unknown button %s", argv[0]); } list_t *bindings = config->current_bar->bindings; if (unbind) { return binding_remove(binding, bindings); } binding->command = join_args(argv + 1, argc - 1); return binding_add(binding, bindings); } struct cmd_results *bar_cmd_bindcode(int argc, char **argv) { return bar_cmd_bind(argc, argv, true, false); } struct cmd_results *bar_cmd_bindsym(int argc, char **argv) { return bar_cmd_bind(argc, argv, false, false); } struct cmd_results *bar_cmd_unbindcode(int argc, char **argv) { return bar_cmd_bind(argc, argv, true, true); } struct cmd_results *bar_cmd_unbindsym(int argc, char **argv) { return bar_cmd_bind(argc, argv, false, true); }
1,510
303
<reponame>1443213244/small-package // // main.c // DaoNet // // Created by realityone on 15/9/27. // Copyright ยฉ 2015ๅนด realityone. All rights reserved. // #include <stdio.h> #include <sys/types.h> #include <getopt.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> #include "frame.h" #include "netutils.h" #include "netkeeper.h" #ifndef HEARTBEAT_NK4 static const char short_opts[] = "u:p:i:v:I:k:t:P:h"; static struct option long_options[] = { {"username", required_argument, NULL, 'u'}, {"password", required_argument, NULL, 'p'}, {"ip", required_argument, NULL, 'i'}, {"version", required_argument, NULL, 'v'}, {"interval", required_argument, NULL, 'I'}, {"target", required_argument, NULL, 't'}, {"port", required_argument, NULL, 'P'}, {"aeskey", required_argument, NULL, 'k'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; #else static const char short_opts[] = "u:i:v:I:k:t:P:h:m"; static struct option long_options[] = { {"username", required_argument, NULL, 'u'}, {"ip", required_argument, NULL, 'i'}, {"version", required_argument, NULL, 'v'}, {"interval", required_argument, NULL, 'I'}, {"target", required_argument, NULL, 't'}, {"port", required_argument, NULL, 'P'}, {"aeskey", required_argument, NULL, 'k'}, {"macaddress" , required_argument , NULL , 'm'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; #endif static struct UserConfig { const char username[32]; const char password[16]; const char ipaddress[16]; const char version[16]; const char aes_key[20]; const char target[16]; const char macaddr[19]; int port; int interval; }user_config; #ifdef HEARTBEAT_NK4 /* * NetKeeper ็š„HTTPๅฟƒ่ทณๅฐฑๅˆซๆƒณไบ†๏ผŒnaive * * ่ฎฉๆˆ‘ๆฅ็œ‹็œ‹ๆœ‰ๅคšๅฐ‘ๅ‚ปๅŠไผšๆ‹ฟ็€่ฟ™ไปฝไธœ่ฅฟๅ‡บๅŽปๆžไบ‹ๆƒ…ใ€‚ * * aes key = <KEY> */ static dao_param dao_params_array[] = { {"USER_NAME", user_config.username}, {"PASSWORD", "<PASSWORD>"}, {"IP", user_config.ipaddress}, {"MAC", user_config.macaddr}, //should be like 01-23-45-67-89-10 {"DRIVER", "NULL"}, {"VERSION_NUMBER", user_config.version}, {"PIN", "0"}, {NULL, NULL} }; #elif defined( HEARTBEAT_HUBEI ) //Hubei Telecom Heartbeat using MAC Version //SVR = 192.168.3.11 PORT = 443 //KEY = xinli_zhejiang12 // //ๆน–ๅŒ—็š„ไบ‘ๅฟƒ่ทณ็š„ๅ‚ป้€ผไปฌ๏ผŒ่ฟ™ๆ˜ฏไฝ ไปฌๆœ€ๅŽ็š„็‹‚ๆฌข //่ฏทๅฐฝๆƒ…ๅฑ•็Žฐไฝ ไปฌๆœ€ไธ่ฆ่„ธใ€ๆœ€ๅฏ่€ปใ€ไธบไบ†้‡‘้’ฑไธงๅฟƒ็—…็‹‚ๆ— ๆ‰€ไธไฝœ็š„ไธ€้ขๅง //ๅ‘ตๅ‘ตใ€‚ // static dao_param dao_params_array[] = { {"USER_NAME", user_config.username}, {"PASSWORD", user_config.password}, {"IP", user_config.ipaddress}, {"MAC", "00%2D00%2D00%2D00%2D00%2D00"}, {"DRIVER", "1"}, {"VERSION_NUMBER", "2.0.4"}, {"PIN", "MAC_TEST"}, {NULL, NULL} }; #else static dao_param dao_params_array[] = { {"USER_NAME", user_config.username}, {"PASSWORD", user_config.password}, {"IP", user_config.ipaddress}, {"MAC", "00%2D00%2D00%2D00%2D00%2D00"}, {"DRIVER", "1"}, {"VERSION_NUMBER", user_config.version}, {"HOOK", ""}, {"IP2", user_config.ipaddress}, {NULL, NULL} }; #endif void print_usage() { fprintf(stdout, "Usage: daonet [OPTIONS]\n"); fprintf(stdout, "Options:\n"); fprintf(stdout, " --username, -u: Username.\n"); #ifndef HEARTBEAT_NK4 fprintf(stdout, " --password, -p: Password.\n"); #else fprintf(stdout, " --mac_address, -m: Mac Address of Interface.\n"); #endif fprintf(stdout, " --ipaddress, -i: IP Address.\n"); fprintf(stdout, " --version, -v: Version.\n"); fprintf(stdout, " --aeskey, -k: Aes key.\n"); fprintf(stdout, " --interval, -I: Interval.\n"); fprintf(stdout, " --target, -t: Target.\n"); fprintf(stdout, " --port, -P: Port.\n"); fprintf(stdout, " --help, -h: Help.\n"); exit(0); } void validate_config() { if (!strlen(user_config.username) || #ifndef HEARTBEAT_NK4 !strlen(user_config.password) || #else !strlen(user_config.macaddr) || #endif !strlen(user_config.ipaddress) || !strlen(user_config.version) || !strlen(user_config.target) || !strlen(user_config.aes_key) || !user_config.port || !user_config.interval) { fprintf(stderr, "Missing arguments.\n"); print_usage(); } } void parse_args(int argc, const char * argv[]) { int opt; while ((opt = getopt_long(argc, (char *const *)argv, short_opts, long_options, NULL)) != -1) { switch (opt) { case 'h': print_usage(); break; case 'u': strcpy((char *)user_config.username, optarg); break; #ifndef HEARTBEAT_NK4 case 'p': strcpy((char *)user_config.password, optarg); break; #else case 'm': strcpy((char *)user_config.macaddr, optarg); break; #endif case 'i': strcpy((char *)user_config.ipaddress, optarg); break; case 'v': strcpy((char *)user_config.version, optarg); break; case 't': strcpy((char *)user_config.target, optarg); break; case 'k': strcpy((char *)user_config.aes_key, optarg); break; case 'P': user_config.port = atoi(optarg); break; case 'I': user_config.interval = atoi(optarg); break; default: print_usage(); break; } } validate_config(); } size_t generate_packet(dao_param *dao_params_array, const char *key, const char *aes_key, u_char *output) { int i; size_t frame_data_len; size_t content_data_len; u_char buffer[256]; dao_frame HR30; dao_aes_ctx aes; dao_protocol procotol; dao_frame_init(&HR30, "HEARTBEAT"); for (i = 0; dao_params_array[i].key && dao_params_array[i].value; i++) { dao_frame_update(&HR30, &dao_params_array[i]); } if (key != NULL) { strcpy(dao_key, key); } frame_data_len = dao_frame_to_data(&HR30, buffer); dao_aes_setup(&aes, DAO_AES_ENCRYPT, aes_key); frame_data_len = dao_aes_padding(buffer, frame_data_len, buffer); content_data_len = dao_aes_encrypt(&aes, buffer, frame_data_len, buffer); #if defined(HEARTBEAT_HUBEI) dao_protocol_init(&procotol, 20, 0x05); #elif defined(HEARTBEAT_NK4) dao_protocol_init(&procotol, 70, 0x05); #else dao_protocol_init(&procotol, 30, 0x05); #endif dao_protocol_set_content(&procotol, buffer, content_data_len); return dao_protocol_generate_data(&procotol, output); } size_t parse_packet(u_char *rcv_data, size_t length) { char *substring; u_char decrypt_buff[256]; dao_aes_ctx aes; dao_aes_setup(&aes, DAO_AES_DECRYPT, user_config.aes_key); dao_aes_decrypt(&aes, rcv_data, length, decrypt_buff); if ((substring = strstr((char *)decrypt_buff, "KEY"))) { bzero(dao_key, 8); memcpy(dao_key, substring, 6); } return 6; } void main_loop(int argc, const char * argv[]) { int times; int sockfd; int result; size_t packet_len; struct sockaddr_in target_addr; struct timeval timeout = {2, 0}; u_char packet_buffer[256]; parse_args(argc, argv); bzero(packet_buffer, 256); sockfd = udp_init(user_config.target, user_config.port, &target_addr); udp_set_timeout(sockfd, timeout); times = 0; while (1) { times += 1; packet_len = generate_packet(dao_params_array, NULL, user_config.aes_key, packet_buffer); if ((result = (int)udp_sendto(sockfd, &target_addr, packet_buffer, packet_len)) > 0) { fprintf(stdout, "INFO: Send packet succeed.\n"); bzero(packet_buffer, 256); if ((result = (int)udp_rcvfrom(sockfd, packet_buffer, packet_len)) > 0) { fprintf(stdout, "INFO: Recv packet succeed.\n"); parse_packet(packet_buffer, result); } else { fprintf(stderr, "ERROR: Wait for packet timeout.\n"); } } else { fprintf(stderr, "ERROR: Send packet failed.\n"); } fprintf(stdout, "INFO: Wait %d seconds.\n", user_config.interval); sleep(user_config.interval); } } int main(int argc, const char * argv[]) { fprintf(stdout, "WARRNING: Support for ShanXi Netkeeper temporary.\n"); main_loop(argc, argv); return 0; }
4,483
318
<gh_stars>100-1000 /* Copyright 2017 <NAME> <p> 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 <p> http://www.apache.org/licenses/LICENSE-2.0 <p> 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.crazysunj.domain.util; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author: sunjian * created on: 2018/5/10 ไธŠๅˆ9:59 * description: https://github.com/crazysunj/CrazyDaily */ public class ThreadManager { private static volatile ThreadManager sThreadManager; private ExecutorService mExecutor; private ThreadManager() { } public static ThreadManager get() { if (sThreadManager == null) { synchronized (ThreadManager.class) { if (sThreadManager == null) { sThreadManager = new ThreadManager(); } } } return sThreadManager; } public static ExecutorService single() { return get().singleInternal(); } public static void shutdown() { get().shutdownInternal(); } private ExecutorService singleInternal() { if (mExecutor == null) { mExecutor = Executors.newSingleThreadExecutor(); } mExecutor.isShutdown(); return mExecutor; } private void shutdownInternal() { if (mExecutor != null && !mExecutor.isShutdown()) { mExecutor.shutdown(); } mExecutor = null; } }
703
692
#define lin1_N 11 /* can be anything >= p */ #define lin1_P 5 #define lin1_NTRIES 3 static double lin1_x0[lin1_P] = { 1.0, 1.0, 1.0, 1.0, 1.0 }; static double lin1_epsrel = 1.0e-10; static void lin1_checksol(const double x[], const double sumsq, const double epsrel, const char *sname, const char *pname) { size_t i; const double sumsq_exact = (double) (lin1_N - lin1_P); gsl_test_rel(sumsq, sumsq_exact, epsrel, "%s/%s sumsq", sname, pname); for (i = 0; i < lin1_P; ++i) { gsl_test_rel(x[i], -1.0, epsrel, "%s/%s i=%zu", sname, pname, i); } } static int lin1_f (const gsl_vector * x, void *params, gsl_vector * f) { size_t i, j; for (i = 0; i < lin1_N; ++i) { double fi = 0.0; for (j = 0; j < lin1_P; ++j) { double xj = gsl_vector_get(x, j); double Aij = (i == j) ? 1.0 : 0.0; Aij -= 2.0 / lin1_N; fi += Aij * xj; } fi -= 1.0; gsl_vector_set(f, i, fi); } return GSL_SUCCESS; } static int lin1_df (const gsl_vector * x, void *params, gsl_matrix * J) { size_t i, j; for (i = 0; i < lin1_N; ++i) { for (j = 0; j < lin1_P; ++j) { double Jij = (i == j) ? 1.0 : 0.0; Jij -= 2.0 / lin1_N; gsl_matrix_set(J, i, j, Jij); } } return GSL_SUCCESS; } static gsl_multifit_function_fdf lin1_func = { &lin1_f, &lin1_df, NULL, lin1_N, lin1_P, NULL, 0, 0 }; static test_fdf_problem lin1_problem = { "linear_full", lin1_x0, NULL, &lin1_epsrel, lin1_NTRIES, &lin1_checksol, &lin1_func };
944
4,020
<reponame>CrackerCat/Recaf package me.coley.recaf.workspace; import me.coley.recaf.util.IOUtil; import me.coley.recaf.util.NetworkUtil; import java.io.IOException; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Importable online resource. * * @author Matt */ public class UrlResource extends DeferringResource { private final URL url; /** * Constructs a URL resource. * * @param url * The URL to pull content from. Should reference a class or jar file. * * @throws IOException * When the content of the URL cannot be resolved. */ public UrlResource(URL url) throws IOException { super(ResourceKind.URL); this.url = url; verify(); detectUrlKind(); } /** * @return The URL imported from. */ public URL getUrl() { return url; } /** * Verify that the URL points to a valid location. * * @throws IOException * When the url times out or there is no content at the URL. */ private void verify() throws IOException { NetworkUtil.verifyUrlContent(url); } /** * Analyze the URL to determine which backing JavaResource implementation to use. */ private void detectUrlKind() throws IOException { String name = url.toString().toLowerCase(); Path path; if (name.endsWith(".class")) { try { if (name.startsWith("file:")) path = Paths.get(url.toURI()); else { path = IOUtil.createTempFile("recaf", "temp.class"); try (OutputStream os = Files.newOutputStream(path)) { IOUtil.transfer(url, os); } } setBacking(new ClassResource(path)); } catch(IOException | URISyntaxException ex) { throw new IOException("Failed to import class from URL '" + name + "'", ex); } } else if (name.endsWith(".jar")) { try { if (name.startsWith("file:")) path = Paths.get(url.toURI()); else { path = IOUtil.createTempFile("recaf", "temp.jar"); try (OutputStream os = Files.newOutputStream(path)) { IOUtil.transfer(url, os); } } setBacking(new JarResource(path)); } catch(IOException | URISyntaxException ex) { throw new IOException("Failed to import jar from URL '" + name + "'", ex); } } else if (name.endsWith(".war")) { try { if (name.startsWith("file:")) path = Paths.get(url.toURI()); else { path = IOUtil.createTempFile("recaf", "temp.war"); try (OutputStream os = Files.newOutputStream(path)) { IOUtil.transfer(url, os); } } setBacking(new WarResource(path)); } catch(IOException | URISyntaxException ex) { throw new IOException("Failed to import war from URL '" + name + "'", ex); } } else { // Invalid URL throw new IOException("URLs must end in a '.class' or '.jar', found '" + name + "'"); } } }
1,112
440
{ "name": "jpillora/jquery.rest", "version": "1.0.2", "main": "dist/1/jquery.rest.js", "description": "A jQuery plugin for easy consumption of REST APIs", "license": "MIT", "ignore": [ "*", "!bower.json", "!dist/1/jquery.rest.js", "!dist/1/jquery.rest.min.js" ], "dependencies": {}, "devDependencies": {} }
151
1,002
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. #pragma once #include "StubStorageFileStatics.h" namespace canvas { class StubFontManagerAdapter : public CustomFontManagerAdapter { public: ComPtr<StubStorageFileStatics> StorageFileStatics; StubFontManagerAdapter() : StorageFileStatics(Make<StubStorageFileStatics>()) { } virtual ComPtr<IDWriteFactory> CreateDWriteFactory(DWRITE_FACTORY_TYPE type) override { ComPtr<IDWriteFactory> factory; ThrowIfFailed(DWriteCreateFactory(type, __uuidof(factory), &factory)); return factory; } virtual IStorageFileStatics* GetStorageFileStatics() override { return StorageFileStatics.Get(); } }; }
370
384
# -*- coding: utf-8 -*- # Copyright JS Foundation and other contributors, https://js.foundation/ # # 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. # # 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 <COPYRIGHT HOLDER> 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 __future__ import absolute_import, unicode_literals from .nodes import Node from .jsx_syntax import JSXSyntax class JSXClosingElement(Node): def __init__(self, name): self.type = JSXSyntax.JSXClosingElement self.name = name class JSXElement(Node): def __init__(self, openingElement, children, closingElement): self.type = JSXSyntax.JSXElement self.openingElement = openingElement self.children = children self.closingElement = closingElement class JSXEmptyExpression(Node): def __init__(self): self.type = JSXSyntax.JSXEmptyExpression class JSXExpressionContainer(Node): def __init__(self, expression): self.type = JSXSyntax.JSXExpressionContainer self.expression = expression class JSXIdentifier(Node): def __init__(self, name): self.type = JSXSyntax.JSXIdentifier self.name = name class JSXMemberExpression(Node): def __init__(self, object, property): self.type = JSXSyntax.JSXMemberExpression self.object = object self.property = property class JSXAttribute(Node): def __init__(self, name, value): self.type = JSXSyntax.JSXAttribute self.name = name self.value = value class JSXNamespacedName(Node): def __init__(self, namespace, name): self.type = JSXSyntax.JSXNamespacedName self.namespace = namespace self.name = name class JSXOpeningElement(Node): def __init__(self, name, selfClosing, attributes): self.type = JSXSyntax.JSXOpeningElement self.name = name self.selfClosing = selfClosing self.attributes = attributes class JSXSpreadAttribute(Node): def __init__(self, argument): self.type = JSXSyntax.JSXSpreadAttribute self.argument = argument class JSXText(Node): def __init__(self, value, raw): self.type = JSXSyntax.JSXText self.value = value self.raw = raw
1,185
4,551
<reponame>quipper/robolectric package org.robolectric.shadows.testing; import android.telecom.Connection; import android.telecom.ConnectionRequest; import android.telecom.ConnectionService; import android.telecom.PhoneAccountHandle; import javax.annotation.Nullable; /** A fake {@link ConnectionService} implementation for testing. */ public class TestConnectionService extends ConnectionService { /** Listens for calls to {@link TestConnectionService} methods. */ public interface Listener { @Nullable default Connection onCreateIncomingConnection( PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) { return null; } default void onCreateIncomingConnectionFailed( PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {} @Nullable default Connection onCreateOutgoingConnection( PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) { return null; } default void onCreateOutgoingConnectionFailed( PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {} } private static Listener listener = new Listener() {}; public static void setListener(Listener listener) { TestConnectionService.listener = listener == null ? new Listener() {} : listener; } @Override @Nullable public Connection onCreateIncomingConnection( PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) { return listener.onCreateIncomingConnection(connectionManagerPhoneAccount, request); } @Override public void onCreateIncomingConnectionFailed( PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) { listener.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request); } @Override @Nullable public Connection onCreateOutgoingConnection( PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) { return listener.onCreateOutgoingConnection(connectionManagerPhoneAccount, request); } @Override public void onCreateOutgoingConnectionFailed( PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) { listener.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request); } }
606
1,134
<filename>SLPagingView/Categories/UIColor+SLAddition.h // // UIColor+SLAddition.h // TinderLike // // Created by <NAME> on 15/1/14. // Copyright (c) 2015ๅนด <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface UIColor (SLAddition) + (UIColor *)gradient:(double)percent top:(double)topX bottom:(double)bottomX init:(UIColor*)init goal:(UIColor*)goal; @end
145
590
package com.mploed.dddwithspring.creditsalesfunnel.model.realEstate; public enum ParkingSpace { NOT_PRESENT("Not present"), CARPORT("Carport"), GARAGE("Garage"); private final String displayName; ParkingSpace(String displayName) { this.displayName = displayName; } public String getDisplayName() { return displayName; } }
114
663
from import4 import * g = globals() if "_sym1" not in g: # Assume __all__ is not supported. Perform sanity check before # before finishing with SKIP. assert "sym2" in g assert "sym3" in g print("SKIP") raise SystemExit else: print(_sym1) print(sym2) print("sym3" in g)
124
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.peering.models; import com.azure.core.management.Region; import com.azure.core.util.Context; import com.azure.resourcemanager.peering.fluent.models.PeeringServiceInner; import java.util.Map; /** An immutable client-side representation of PeeringService. */ public interface PeeringService { /** * Gets the id property: Fully qualified resource Id for the resource. * * @return the id value. */ String id(); /** * Gets the name property: The name of the resource. * * @return the name value. */ String name(); /** * Gets the type property: The type of the resource. * * @return the type value. */ String type(); /** * Gets the sku property: The SKU that defines the type of the peering service. * * @return the sku value. */ PeeringServiceSku sku(); /** * Gets the location property: The location of the resource. * * @return the location value. */ String location(); /** * Gets the tags property: The resource tags. * * @return the tags value. */ Map<String, String> tags(); /** * Gets the peeringServiceLocation property: The location (state/province) of the customer. * * @return the peeringServiceLocation value. */ String peeringServiceLocation(); /** * Gets the peeringServiceProvider property: The name of the service provider. * * @return the peeringServiceProvider value. */ String peeringServiceProvider(); /** * Gets the provisioningState property: The provisioning state of the resource. * * @return the provisioningState value. */ ProvisioningState provisioningState(); /** * Gets the providerPrimaryPeeringLocation property: The primary peering (Microsoft/service provider) location to be * used for customer traffic. * * @return the providerPrimaryPeeringLocation value. */ String providerPrimaryPeeringLocation(); /** * Gets the providerBackupPeeringLocation property: The backup peering (Microsoft/service provider) location to be * used for customer traffic. * * @return the providerBackupPeeringLocation value. */ String providerBackupPeeringLocation(); /** * Gets the region of the resource. * * @return the region of the resource. */ Region region(); /** * Gets the name of the resource region. * * @return the name of the resource region. */ String regionName(); /** * Gets the inner com.azure.resourcemanager.peering.fluent.models.PeeringServiceInner object. * * @return the inner object. */ PeeringServiceInner innerModel(); /** The entirety of the PeeringService definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithLocation, DefinitionStages.WithResourceGroup, DefinitionStages.WithCreate { } /** The PeeringService definition stages. */ interface DefinitionStages { /** The first stage of the PeeringService definition. */ interface Blank extends WithLocation { } /** The stage of the PeeringService definition allowing to specify location. */ interface WithLocation { /** * Specifies the region for the resource. * * @param location The location of the resource. * @return the next definition stage. */ WithResourceGroup withRegion(Region location); /** * Specifies the region for the resource. * * @param location The location of the resource. * @return the next definition stage. */ WithResourceGroup withRegion(String location); } /** The stage of the PeeringService definition allowing to specify parent resource. */ interface WithResourceGroup { /** * Specifies resourceGroupName. * * @param resourceGroupName The name of the resource group. * @return the next definition stage. */ WithCreate withExistingResourceGroup(String resourceGroupName); } /** * The stage of the PeeringService definition which contains all the minimum required properties for the * resource to be created, but also allows for any other optional properties to be specified. */ interface WithCreate extends DefinitionStages.WithTags, DefinitionStages.WithSku, DefinitionStages.WithPeeringServiceLocation, DefinitionStages.WithPeeringServiceProvider, DefinitionStages.WithProviderPrimaryPeeringLocation, DefinitionStages.WithProviderBackupPeeringLocation { /** * Executes the create request. * * @return the created resource. */ PeeringService create(); /** * Executes the create request. * * @param context The context to associate with this operation. * @return the created resource. */ PeeringService create(Context context); } /** The stage of the PeeringService definition allowing to specify tags. */ interface WithTags { /** * Specifies the tags property: The resource tags.. * * @param tags The resource tags. * @return the next definition stage. */ WithCreate withTags(Map<String, String> tags); } /** The stage of the PeeringService definition allowing to specify sku. */ interface WithSku { /** * Specifies the sku property: The SKU that defines the type of the peering service.. * * @param sku The SKU that defines the type of the peering service. * @return the next definition stage. */ WithCreate withSku(PeeringServiceSku sku); } /** The stage of the PeeringService definition allowing to specify peeringServiceLocation. */ interface WithPeeringServiceLocation { /** * Specifies the peeringServiceLocation property: The location (state/province) of the customer.. * * @param peeringServiceLocation The location (state/province) of the customer. * @return the next definition stage. */ WithCreate withPeeringServiceLocation(String peeringServiceLocation); } /** The stage of the PeeringService definition allowing to specify peeringServiceProvider. */ interface WithPeeringServiceProvider { /** * Specifies the peeringServiceProvider property: The name of the service provider.. * * @param peeringServiceProvider The name of the service provider. * @return the next definition stage. */ WithCreate withPeeringServiceProvider(String peeringServiceProvider); } /** The stage of the PeeringService definition allowing to specify providerPrimaryPeeringLocation. */ interface WithProviderPrimaryPeeringLocation { /** * Specifies the providerPrimaryPeeringLocation property: The primary peering (Microsoft/service provider) * location to be used for customer traffic.. * * @param providerPrimaryPeeringLocation The primary peering (Microsoft/service provider) location to be * used for customer traffic. * @return the next definition stage. */ WithCreate withProviderPrimaryPeeringLocation(String providerPrimaryPeeringLocation); } /** The stage of the PeeringService definition allowing to specify providerBackupPeeringLocation. */ interface WithProviderBackupPeeringLocation { /** * Specifies the providerBackupPeeringLocation property: The backup peering (Microsoft/service provider) * location to be used for customer traffic.. * * @param providerBackupPeeringLocation The backup peering (Microsoft/service provider) location to be used * for customer traffic. * @return the next definition stage. */ WithCreate withProviderBackupPeeringLocation(String providerBackupPeeringLocation); } } /** * Begins update for the PeeringService resource. * * @return the stage of resource update. */ PeeringService.Update update(); /** The template for PeeringService update. */ interface Update extends UpdateStages.WithTags { /** * Executes the update request. * * @return the updated resource. */ PeeringService apply(); /** * Executes the update request. * * @param context The context to associate with this operation. * @return the updated resource. */ PeeringService apply(Context context); } /** The PeeringService update stages. */ interface UpdateStages { /** The stage of the PeeringService update allowing to specify tags. */ interface WithTags { /** * Specifies the tags property: Gets or sets the tags, a dictionary of descriptors arm object. * * @param tags Gets or sets the tags, a dictionary of descriptors arm object. * @return the next definition stage. */ Update withTags(Map<String, String> tags); } } /** * Refreshes the resource to sync with Azure. * * @return the refreshed resource. */ PeeringService refresh(); /** * Refreshes the resource to sync with Azure. * * @param context The context to associate with this operation. * @return the refreshed resource. */ PeeringService refresh(Context context); }
4,032
330
package com.alphawallet.app.entity; import com.alphawallet.token.entity.Signable; public interface DAppFunction { void DAppError(Throwable error, Signable message); void DAppReturn(byte[] data, Signable message); }
75
790
#!/usr/bin/python2 # convert snap to mtx import sys import random def convert(inputFile, outputFile, outputExt): commentDelimiter = '%' outputFile.write('%%MatrixMarket matrix coordinate pattern symmetric'+'\n') firstDataLine = True while 1: line = inputFile.readline() if not line: return if line.startswith('%'): outputFile.write(commentDelimiter + line[1:]) elif line.startswith('#'): outputFile.write(commentDelimiter + line[1:]) else: src, dst = line.split()[:2] #any edge values are thrown #adjust for matrix format's 1-based indexing src = int(src) dst = int(dst) src = src + 1 dst = dst + 1 if src != dst: outputFile.write('%d %d\n' % (dst, src)) if __name__ == '__main__': if len(sys.argv) != 3: print('Usage: snap2matrix.py input.edges output.mtx') sys.exit(1) inputName, outputName = sys.argv[1:] outputExt = outputName.split('.')[-1] if outputExt != 'mtx': print('Unknown extension: ', outputExt) sys.exit(1) input = open(inputName) output = open(outputName, 'w') convert(input, output, outputExt)
464
350
{ "short_name": "Aptos", "name": "Aptos Wallet", "version": "0.0.1", "manifest_version": 2, "browser_action": { "default_popup": "index.html" }, "content_scripts": [{ "matches": ["<all_urls>"], "js": [ "contentscript.js" ], "run_at": "document_start" }], "web_accessible_resources": [ "inpage.js" ], "background": { "scripts": ["background.js"], "persistent": true } }
197
14,668
<filename>ui/gl/direct_composition_child_surface_win.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 UI_GL_DIRECT_COMPOSITION_CHILD_SURFACE_WIN_H_ #define UI_GL_DIRECT_COMPOSITION_CHILD_SURFACE_WIN_H_ #include <windows.h> #include <d3d11.h> #include <dcomp.h> #include <wrl/client.h> #include "base/callback.h" #include "base/containers/circular_deque.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/synchronization/lock.h" #include "base/time/time.h" #include "ui/gl/gl_export.h" #include "ui/gl/gl_surface_egl.h" #include "ui/gl/vsync_observer.h" namespace base { class SequencedTaskRunner; } // namespace base namespace gl { class VSyncThreadWin; class GL_EXPORT DirectCompositionChildSurfaceWin : public GLSurfaceEGL, public VSyncObserver { public: using VSyncCallback = base::RepeatingCallback<void(base::TimeTicks, base::TimeDelta)>; DirectCompositionChildSurfaceWin(VSyncCallback vsync_callback, bool use_angle_texture_offset, size_t max_pending_frames, bool force_full_damage, bool force_full_damage_always); DirectCompositionChildSurfaceWin(const DirectCompositionChildSurfaceWin&) = delete; DirectCompositionChildSurfaceWin& operator=( const DirectCompositionChildSurfaceWin&) = delete; // GLSurfaceEGL implementation. bool Initialize(GLSurfaceFormat format) override; void Destroy() override; gfx::Size GetSize() override; bool IsOffscreen() override; void* GetHandle() override; gfx::SwapResult SwapBuffers(PresentationCallback callback) override; gfx::SurfaceOrigin GetOrigin() const override; bool SupportsPostSubBuffer() override; bool OnMakeCurrent(GLContext* context) override; bool SupportsDCLayers() const override; bool SetDrawRectangle(const gfx::Rect& rect) override; gfx::Vector2d GetDrawOffset() const override; void SetVSyncEnabled(bool enabled) override; bool Resize(const gfx::Size& size, float scale_factor, const gfx::ColorSpace& color_space, bool has_alpha) override; bool SetEnableDCLayers(bool enable) override; gfx::VSyncProvider* GetVSyncProvider() override; bool SupportsGpuVSync() const override; void SetGpuVSyncEnabled(bool enabled) override; // VSyncObserver implementation. void OnVSync(base::TimeTicks vsync_time, base::TimeDelta interval) override; static bool IsDirectCompositionSwapChainFailed(); const Microsoft::WRL::ComPtr<IDCompositionSurface>& dcomp_surface() const { return dcomp_surface_; } const Microsoft::WRL::ComPtr<IDXGISwapChain1>& swap_chain() const { return swap_chain_; } uint64_t dcomp_surface_serial() const { return dcomp_surface_serial_; } void SetDCompSurfaceForTesting( Microsoft::WRL::ComPtr<IDCompositionSurface> surface); protected: ~DirectCompositionChildSurfaceWin() override; private: struct PendingFrame { PendingFrame(Microsoft::WRL::ComPtr<ID3D11Query> query, PresentationCallback callback); PendingFrame(PendingFrame&& other); ~PendingFrame(); PendingFrame& operator=(PendingFrame&& other); // Event query issued after frame is presented. Microsoft::WRL::ComPtr<ID3D11Query> query; // Presentation callback enqueued in SwapBuffers(). PresentationCallback callback; }; void EnqueuePendingFrame(PresentationCallback callback); void CheckPendingFrames(); void StartOrStopVSyncThread(); bool VSyncCallbackEnabled() const; void HandleVSyncOnMainThread(base::TimeTicks vsync_time, base::TimeDelta interval); // Release the texture that's currently being drawn to. If will_discard is // true then the surface should be discarded without swapping any contents // to it. Returns false if this fails. bool ReleaseDrawTexture(bool will_discard); gfx::Size size_ = gfx::Size(1, 1); bool enable_dc_layers_ = false; bool has_alpha_ = true; bool vsync_enabled_ = true; gfx::ColorSpace color_space_; // This is a placeholder surface used when not rendering to the // DirectComposition surface. EGLSurface default_surface_ = 0; // This is the real surface representing the backbuffer. It may be null // outside of a BeginDraw/EndDraw pair. EGLSurface real_surface_ = 0; bool first_swap_ = true; gfx::Rect swap_rect_; gfx::Vector2d draw_offset_; // This is a number that increments once for every EndDraw on a surface, and // is used to determine when the contents have changed so Commit() needs to // be called on the device. uint64_t dcomp_surface_serial_ = 0; Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_; Microsoft::WRL::ComPtr<IDCompositionDevice2> dcomp_device_; Microsoft::WRL::ComPtr<IDCompositionSurface> dcomp_surface_; Microsoft::WRL::ComPtr<IDXGISwapChain1> swap_chain_; Microsoft::WRL::ComPtr<ID3D11Texture2D> draw_texture_; const VSyncCallback vsync_callback_; const bool use_angle_texture_offset_; const size_t max_pending_frames_; const bool force_full_damage_; const bool force_full_damage_always_; const raw_ptr<VSyncThreadWin> vsync_thread_; scoped_refptr<base::SequencedTaskRunner> task_runner_; bool vsync_thread_started_ = false; bool vsync_callback_enabled_ GUARDED_BY(vsync_callback_enabled_lock_) = false; mutable base::Lock vsync_callback_enabled_lock_; // Queue of pending presentation callbacks. base::circular_deque<PendingFrame> pending_frames_; base::TimeTicks last_vsync_time_; base::TimeDelta last_vsync_interval_; base::WeakPtrFactory<DirectCompositionChildSurfaceWin> weak_factory_{this}; }; } // namespace gl #endif // UI_GL_DIRECT_COMPOSITION_CHILD_SURFACE_WIN_H_
2,144
1,779
// // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "zetasql/scripting/serialization_helpers.h" #include "absl/status/statusor.h" namespace zetasql { absl::Status SerializeVariableProto( const VariableMap& variables, const VariableTypeParametersMap& type_params, google::protobuf::RepeatedPtrField<VariableProto>* variables_proto) { for (const auto& pair : variables) { const IdString name = pair.first; const Value& value = pair.second; VariableProto* variable_proto = variables_proto->Add(); variable_proto->set_name(name.ToString()); ZETASQL_RETURN_IF_ERROR(value.Serialize(variable_proto->mutable_value())); // TODO: Use SerializeToProtoAndFileDescriptors to serialize a // type with a deduplicated collection of FileDescriptorProtos. ZETASQL_RETURN_IF_ERROR(value.type()->SerializeToSelfContainedProto( variable_proto->mutable_type())); auto it = type_params.find(name); if (it != type_params.end()) { ZETASQL_RETURN_IF_ERROR( it->second.Serialize(variable_proto->mutable_type_params())); } } return absl::OkStatus(); } absl::Status DeserializeVariableProto( const google::protobuf::RepeatedPtrField<VariableProto>& variables_proto, VariableMap* variables, VariableTypeParametersMap* variable_type_params, google::protobuf::DescriptorPool* descriptor_pool, IdStringPool* id_string_pool, TypeFactory* type_factory) { for (const VariableProto& variable_proto : variables_proto) { IdString var_name = id_string_pool->Make(variable_proto.name()); ZETASQL_RET_CHECK(!zetasql_base::ContainsKey(*variables, var_name)) << "Duplicate variable " << var_name.ToStringView(); const Type* type; ZETASQL_RETURN_IF_ERROR(type_factory->DeserializeFromSelfContainedProto( variable_proto.type(), descriptor_pool, &type)); ZETASQL_ASSIGN_OR_RETURN(zetasql::Value value, zetasql::Value::Deserialize( variable_proto.value(), type)); zetasql_base::InsertOrDie(variables, var_name, value); if (variable_proto.has_type_params()) { ZETASQL_ASSIGN_OR_RETURN( TypeParameters type_params, TypeParameters::Deserialize(variable_proto.type_params())); zetasql_base::InsertOrDie(variable_type_params, var_name, type_params); } } return absl::OkStatus(); } // static absl::StatusOr<std::unique_ptr<ProcedureDefinition>> DeserializeProcedureDefinitionProto( const ScriptExecutorStateProto::ProcedureDefinition& proto, const std::vector<const google::protobuf::DescriptorPool*>& pools, TypeFactory* factory) { std::unique_ptr<FunctionSignature> function_signature; ZETASQL_RETURN_IF_ERROR(FunctionSignature::Deserialize(proto.signature(), pools, factory, &function_signature)); if (proto.is_dynamic_sql()) { return absl::make_unique<ProcedureDefinition>(*function_signature, proto.body()); } else { std::vector<std::string> argument_name_list( proto.argument_name_list().begin(), proto.argument_name_list().end()); return absl::make_unique<ProcedureDefinition>( proto.name(), *function_signature, std::move(argument_name_list), proto.body()); } } absl::Status SerializeProcedureDefinitionProto( const ProcedureDefinition& procedure_definition, ScriptExecutorStateProto::ProcedureDefinition* proto, FileDescriptorSetMap* file_descriptor_set_map) { proto->set_name(procedure_definition.name()); ZETASQL_RETURN_IF_ERROR(procedure_definition.signature().Serialize( file_descriptor_set_map, proto->mutable_signature())); *proto->mutable_argument_name_list() = { procedure_definition.argument_name_list().begin(), procedure_definition.argument_name_list().end()}; proto->set_body(procedure_definition.body()); proto->set_is_dynamic_sql(procedure_definition.is_dynamic_sql()); return absl::OkStatus(); } absl::Status SerializeParametersProto( const absl::optional<absl::variant<ParameterValueList, ParameterValueMap>>& parameters, ParametersProto* parameters_proto) { if (!parameters) { parameters_proto->set_mode(ParametersProto::NONE); } else if (absl::holds_alternative<ParameterValueMap>(*parameters)) { parameters_proto->set_mode(ParametersProto::NAMED); for (const auto& [name, value] : absl::get<ParameterValueMap>(*parameters)) { VariableProto* variable_proto = parameters_proto->mutable_variables()->Add(); variable_proto->set_name(name); ZETASQL_RETURN_IF_ERROR(value.Serialize(variable_proto->mutable_value())); ZETASQL_RETURN_IF_ERROR(value.type()->SerializeToSelfContainedProto( variable_proto->mutable_type())); } } else { parameters_proto->set_mode(ParametersProto::POSITIONAL); for (const Value& value : absl::get<ParameterValueList>(*parameters)) { VariableProto* variable_proto = parameters_proto->mutable_variables()->Add(); ZETASQL_RETURN_IF_ERROR(value.Serialize(variable_proto->mutable_value())); ZETASQL_RETURN_IF_ERROR(value.type()->SerializeToSelfContainedProto( variable_proto->mutable_type())); } } return absl::OkStatus(); } absl::Status DeserializeParametersProto( const ParametersProto& parameters_proto, absl::optional<absl::variant<ParameterValueList, ParameterValueMap>>* parameters, google::protobuf::DescriptorPool* descriptor_pool, IdStringPool* id_string_pool, TypeFactory* type_factory) { if (parameters_proto.mode() == ParametersProto::NONE) { *parameters = {}; } else if (parameters_proto.mode() == ParametersProto::NAMED) { ParameterValueMap map; for (const VariableProto& variable_proto : parameters_proto.variables()) { ZETASQL_RET_CHECK(!zetasql_base::ContainsKey(map, variable_proto.name())) << "Duplicate variable " << variable_proto.name(); const Type* type; ZETASQL_RETURN_IF_ERROR(type_factory->DeserializeFromSelfContainedProto( variable_proto.type(), descriptor_pool, &type)); ZETASQL_ASSIGN_OR_RETURN( zetasql::Value value, zetasql::Value::Deserialize(variable_proto.value(), type)); zetasql_base::InsertOrDie(&map, variable_proto.name(), value); } *parameters = map; } else { ParameterValueList list; for (const VariableProto& variable_proto : parameters_proto.variables()) { const Type* type; ZETASQL_RETURN_IF_ERROR(type_factory->DeserializeFromSelfContainedProto( variable_proto.type(), descriptor_pool, &type)); ZETASQL_ASSIGN_OR_RETURN( zetasql::Value value, zetasql::Value::Deserialize(variable_proto.value(), type)); list.push_back(value); } *parameters = list; } return absl::OkStatus(); } } // namespace zetasql
2,882
6,989
#line 1 "numpy/core/src/umath/loops.h.src" /* ***************************************************************************** ** This file was autogenerated from a template DO NOT EDIT!!!! ** ** Changes should be made to the original source (.src) file ** ***************************************************************************** */ #line 1 /* -*- c -*- */ /* * vim:syntax=c */ #ifndef _NPY_UMATH_LOOPS_H_ #define _NPY_UMATH_LOOPS_H_ #define BOOL_invert BOOL_logical_not #define BOOL_negative BOOL_logical_not #define BOOL_add BOOL_logical_or #define BOOL_bitwise_and BOOL_logical_and #define BOOL_bitwise_or BOOL_logical_or #define BOOL_logical_xor BOOL_not_equal #define BOOL_bitwise_xor BOOL_logical_xor #define BOOL_multiply BOOL_logical_and #define BOOL_subtract BOOL_logical_xor #define BOOL_maximum BOOL_logical_or #define BOOL_minimum BOOL_logical_and #define BOOL_fmax BOOL_maximum #define BOOL_fmin BOOL_minimum /* ***************************************************************************** ** BOOLEAN LOOPS ** ***************************************************************************** */ #line 34 NPY_NO_EXPORT void BOOL_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 34 NPY_NO_EXPORT void BOOL_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BOOL__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); /* ***************************************************************************** ** INTEGER LOOPS ***************************************************************************** */ #line 50 #line 56 #define BYTE_floor_divide BYTE_divide #define BYTE_fmax BYTE_maximum #define BYTE_fmin BYTE_minimum NPY_NO_EXPORT void BYTE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void BYTE_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void BYTE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void BYTE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void BYTE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void BYTE_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void BYTE_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void BYTE_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void BYTE_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void BYTE_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void BYTE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void BYTE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void BYTE_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 56 #define UBYTE_floor_divide UBYTE_divide #define UBYTE_fmax UBYTE_maximum #define UBYTE_fmin UBYTE_minimum NPY_NO_EXPORT void UBYTE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UBYTE_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void UBYTE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UBYTE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UBYTE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void UBYTE_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UBYTE_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UBYTE_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UBYTE_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UBYTE_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void UBYTE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void UBYTE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UBYTE_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 50 #line 56 #define SHORT_floor_divide SHORT_divide #define SHORT_fmax SHORT_maximum #define SHORT_fmin SHORT_minimum NPY_NO_EXPORT void SHORT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void SHORT_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void SHORT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void SHORT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void SHORT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void SHORT_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void SHORT_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void SHORT_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void SHORT_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void SHORT_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void SHORT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void SHORT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void SHORT_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 56 #define USHORT_floor_divide USHORT_divide #define USHORT_fmax USHORT_maximum #define USHORT_fmin USHORT_minimum NPY_NO_EXPORT void USHORT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void USHORT_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void USHORT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void USHORT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void USHORT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void USHORT_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void USHORT_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void USHORT_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void USHORT_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void USHORT_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void USHORT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void USHORT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void USHORT_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 50 #line 56 #define INT_floor_divide INT_divide #define INT_fmax INT_maximum #define INT_fmin INT_minimum NPY_NO_EXPORT void INT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void INT_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void INT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void INT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void INT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void INT_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void INT_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void INT_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void INT_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void INT_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void INT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void INT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void INT_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 56 #define UINT_floor_divide UINT_divide #define UINT_fmax UINT_maximum #define UINT_fmin UINT_minimum NPY_NO_EXPORT void UINT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UINT_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void UINT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UINT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UINT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void UINT_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UINT_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void UINT_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void UINT_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void UINT_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void UINT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void UINT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void UINT_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 50 #line 56 #define LONG_floor_divide LONG_divide #define LONG_fmax LONG_maximum #define LONG_fmin LONG_minimum NPY_NO_EXPORT void LONG__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONG_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void LONG_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONG_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONG_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void LONG_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONG_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONG_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONG_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONG_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void LONG_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void LONG_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONG_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 56 #define ULONG_floor_divide ULONG_divide #define ULONG_fmax ULONG_maximum #define ULONG_fmin ULONG_minimum NPY_NO_EXPORT void ULONG__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONG_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void ULONG_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONG_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONG_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void ULONG_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONG_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONG_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONG_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONG_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void ULONG_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void ULONG_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONG_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 50 #line 56 #define LONGLONG_floor_divide LONGLONG_divide #define LONGLONG_fmax LONGLONG_maximum #define LONGLONG_fmin LONGLONG_minimum NPY_NO_EXPORT void LONGLONG__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONGLONG_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void LONGLONG_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONGLONG_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONGLONG_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void LONGLONG_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONGLONG_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONGLONG_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void LONGLONG_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void LONGLONG_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void LONGLONG_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void LONGLONG_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGLONG_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 56 #define ULONGLONG_floor_divide ULONGLONG_divide #define ULONGLONG_fmax ULONGLONG_maximum #define ULONGLONG_fmin ULONGLONG_minimum NPY_NO_EXPORT void ULONGLONG__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONGLONG_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void ULONGLONG_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONGLONG_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONGLONG_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_invert(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_bitwise_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_bitwise_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_bitwise_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_left_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_right_shift(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 70 NPY_NO_EXPORT void ULONGLONG_square_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONGLONG_reciprocal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void ULONGLONG_conjugate_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_negative_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_logical_not_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_invert_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_add_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_subtract_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_multiply_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_bitwise_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_bitwise_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_bitwise_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_left_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 95 NPY_NO_EXPORT void ULONGLONG_right_shift_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_not_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_greater_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_greater_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_less_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_less_equal_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_logical_and_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 105 NPY_NO_EXPORT void ULONGLONG_logical_or_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_logical_xor_avx2(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void ULONGLONG_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 118 NPY_NO_EXPORT void ULONGLONG_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_power(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_fmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void ULONGLONG_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); /* ***************************************************************************** ** FLOAT LOOPS ** ***************************************************************************** */ #line 162 NPY_NO_EXPORT void FLOAT_sqrt(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 162 NPY_NO_EXPORT void DOUBLE_sqrt(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 172 #line 179 NPY_NO_EXPORT void HALF_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void HALF_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void HALF_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void HALF_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void HALF_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void HALF_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void HALF_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void HALF_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void HALF_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void HALF_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void HALF_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void HALF_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void HALF_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void HALF_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void HALF_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void HALF_signbit(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void HALF_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void HALF_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void HALF_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 210 NPY_NO_EXPORT void HALF_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 210 NPY_NO_EXPORT void HALF_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 218 NPY_NO_EXPORT void HALF_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 218 NPY_NO_EXPORT void HALF_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void HALF_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void HALF__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void HALF_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void HALF_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #define HALF_true_divide HALF_divide #line 172 #line 179 NPY_NO_EXPORT void FLOAT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void FLOAT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void FLOAT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void FLOAT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void FLOAT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void FLOAT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void FLOAT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void FLOAT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void FLOAT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void FLOAT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void FLOAT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void FLOAT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void FLOAT_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void FLOAT_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void FLOAT_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void FLOAT_signbit(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void FLOAT_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void FLOAT_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void FLOAT_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 210 NPY_NO_EXPORT void FLOAT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 210 NPY_NO_EXPORT void FLOAT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 218 NPY_NO_EXPORT void FLOAT_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 218 NPY_NO_EXPORT void FLOAT_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void FLOAT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void FLOAT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void FLOAT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void FLOAT_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #define FLOAT_true_divide FLOAT_divide #line 172 #line 179 NPY_NO_EXPORT void DOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void DOUBLE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void DOUBLE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void DOUBLE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void DOUBLE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void DOUBLE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void DOUBLE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void DOUBLE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void DOUBLE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void DOUBLE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void DOUBLE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void DOUBLE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void DOUBLE_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void DOUBLE_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void DOUBLE_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void DOUBLE_signbit(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void DOUBLE_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void DOUBLE_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void DOUBLE_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 210 NPY_NO_EXPORT void DOUBLE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 210 NPY_NO_EXPORT void DOUBLE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 218 NPY_NO_EXPORT void DOUBLE_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 218 NPY_NO_EXPORT void DOUBLE_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void DOUBLE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void DOUBLE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void DOUBLE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DOUBLE_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #define DOUBLE_true_divide DOUBLE_divide #line 172 #line 179 NPY_NO_EXPORT void LONGDOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void LONGDOUBLE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void LONGDOUBLE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 179 NPY_NO_EXPORT void LONGDOUBLE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void LONGDOUBLE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void LONGDOUBLE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void LONGDOUBLE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void LONGDOUBLE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void LONGDOUBLE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void LONGDOUBLE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void LONGDOUBLE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 188 NPY_NO_EXPORT void LONGDOUBLE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void LONGDOUBLE_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void LONGDOUBLE_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void LONGDOUBLE_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void LONGDOUBLE_signbit(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void LONGDOUBLE_copysign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void LONGDOUBLE_nextafter(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 202 NPY_NO_EXPORT void LONGDOUBLE_spacing(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 210 NPY_NO_EXPORT void LONGDOUBLE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 210 NPY_NO_EXPORT void LONGDOUBLE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 218 NPY_NO_EXPORT void LONGDOUBLE_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 218 NPY_NO_EXPORT void LONGDOUBLE_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONGDOUBLE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONGDOUBLE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void LONGDOUBLE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_modf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_frexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_ldexp(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void LONGDOUBLE_ldexp_long(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #define LONGDOUBLE_true_divide LONGDOUBLE_divide /* ***************************************************************************** ** COMPLEX LOOPS ** ***************************************************************************** */ #define CGE(xr,xi,yr,yi) (xr > yr || (xr == yr && xi >= yi)); #define CLE(xr,xi,yr,yi) (xr < yr || (xr == yr && xi <= yi)); #define CGT(xr,xi,yr,yi) (xr > yr || (xr == yr && xi > yi)); #define CLT(xr,xi,yr,yi) (xr < yr || (xr == yr && xi < yi)); #define CEQ(xr,xi,yr,yi) (xr == yr && xi == yi); #define CNE(xr,xi,yr,yi) (xr != yr || xi != yi); #line 292 #line 298 NPY_NO_EXPORT void CFLOAT_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 298 NPY_NO_EXPORT void CFLOAT_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CFLOAT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CFLOAT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CFLOAT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CFLOAT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CFLOAT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CFLOAT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 325 NPY_NO_EXPORT void CFLOAT_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 325 NPY_NO_EXPORT void CFLOAT_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CFLOAT_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CFLOAT_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CFLOAT_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CFLOAT_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CFLOAT__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CFLOAT_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT__arg(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CFLOAT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 368 NPY_NO_EXPORT void CFLOAT_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 368 NPY_NO_EXPORT void CFLOAT_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 376 NPY_NO_EXPORT void CFLOAT_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 376 NPY_NO_EXPORT void CFLOAT_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #define CFLOAT_true_divide CFLOAT_divide #line 292 #line 298 NPY_NO_EXPORT void CDOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 298 NPY_NO_EXPORT void CDOUBLE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CDOUBLE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CDOUBLE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CDOUBLE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CDOUBLE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CDOUBLE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CDOUBLE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 325 NPY_NO_EXPORT void CDOUBLE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 325 NPY_NO_EXPORT void CDOUBLE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CDOUBLE_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CDOUBLE_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CDOUBLE_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CDOUBLE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CDOUBLE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CDOUBLE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE__arg(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CDOUBLE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 368 NPY_NO_EXPORT void CDOUBLE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 368 NPY_NO_EXPORT void CDOUBLE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 376 NPY_NO_EXPORT void CDOUBLE_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 376 NPY_NO_EXPORT void CDOUBLE_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #define CDOUBLE_true_divide CDOUBLE_divide #line 292 #line 298 NPY_NO_EXPORT void CLONGDOUBLE_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 298 NPY_NO_EXPORT void CLONGDOUBLE_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CLONGDOUBLE_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CLONGDOUBLE_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CLONGDOUBLE_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CLONGDOUBLE_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CLONGDOUBLE_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 316 NPY_NO_EXPORT void CLONGDOUBLE_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 325 NPY_NO_EXPORT void CLONGDOUBLE_logical_and(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 325 NPY_NO_EXPORT void CLONGDOUBLE_logical_or(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE_logical_xor(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE_logical_not(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CLONGDOUBLE_isnan(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CLONGDOUBLE_isinf(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 339 NPY_NO_EXPORT void CLONGDOUBLE_isfinite(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE_square(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CLONGDOUBLE_reciprocal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CLONGDOUBLE__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void CLONGDOUBLE_conjugate(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE__arg(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void CLONGDOUBLE_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 368 NPY_NO_EXPORT void CLONGDOUBLE_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 368 NPY_NO_EXPORT void CLONGDOUBLE_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 376 NPY_NO_EXPORT void CLONGDOUBLE_fmax(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 376 NPY_NO_EXPORT void CLONGDOUBLE_fmin(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #define CLONGDOUBLE_true_divide CLONGDOUBLE_divide #undef CGE #undef CLE #undef CGT #undef CLT #undef CEQ #undef CNE /* ***************************************************************************** ** DATETIME LOOPS ** ***************************************************************************** */ NPY_NO_EXPORT void TIMEDELTA_negative(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_positive(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_absolute(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 412 NPY_NO_EXPORT void DATETIME_isnat(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DATETIME__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); #line 423 NPY_NO_EXPORT void DATETIME_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void DATETIME_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void DATETIME_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void DATETIME_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void DATETIME_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void DATETIME_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 431 NPY_NO_EXPORT void DATETIME_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 431 NPY_NO_EXPORT void DATETIME_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 412 NPY_NO_EXPORT void TIMEDELTA_isnat(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA__ones_like(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); #line 423 NPY_NO_EXPORT void TIMEDELTA_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void TIMEDELTA_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void TIMEDELTA_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void TIMEDELTA_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void TIMEDELTA_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 423 NPY_NO_EXPORT void TIMEDELTA_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 431 NPY_NO_EXPORT void TIMEDELTA_maximum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 431 NPY_NO_EXPORT void TIMEDELTA_minimum(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DATETIME_Mm_M_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(data)); NPY_NO_EXPORT void DATETIME_mM_M_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_mm_m_add(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DATETIME_Mm_M_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void DATETIME_MM_m_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_mm_m_subtract(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_mq_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_qm_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_md_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_dm_m_multiply(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_mq_m_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_md_m_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_mm_d_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_mm_q_floor_divide(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_mm_m_remainder(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void TIMEDELTA_mm_qm_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); /* Special case equivalents to above functions */ #define TIMEDELTA_mq_m_true_divide TIMEDELTA_mq_m_divide #define TIMEDELTA_md_m_true_divide TIMEDELTA_md_m_divide #define TIMEDELTA_mm_d_true_divide TIMEDELTA_mm_d_divide #define TIMEDELTA_mq_m_floor_divide TIMEDELTA_mq_m_divide #define TIMEDELTA_md_m_floor_divide TIMEDELTA_md_m_divide /* #define TIMEDELTA_mm_d_floor_divide TIMEDELTA_mm_d_divide */ #define TIMEDELTA_fmin TIMEDELTA_minimum #define TIMEDELTA_fmax TIMEDELTA_maximum #define DATETIME_fmin DATETIME_minimum #define DATETIME_fmax DATETIME_maximum /* ***************************************************************************** ** OBJECT LOOPS ** ***************************************************************************** */ #line 508 #line 511 NPY_NO_EXPORT void OBJECT_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 511 NPY_NO_EXPORT void OBJECT_OO_O_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 508 #line 511 NPY_NO_EXPORT void OBJECT_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 511 NPY_NO_EXPORT void OBJECT_OO_O_not_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 508 #line 511 NPY_NO_EXPORT void OBJECT_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 511 NPY_NO_EXPORT void OBJECT_OO_O_greater(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 508 #line 511 NPY_NO_EXPORT void OBJECT_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 511 NPY_NO_EXPORT void OBJECT_OO_O_greater_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 508 #line 511 NPY_NO_EXPORT void OBJECT_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 511 NPY_NO_EXPORT void OBJECT_OO_O_less(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 508 #line 511 NPY_NO_EXPORT void OBJECT_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); #line 511 NPY_NO_EXPORT void OBJECT_OO_O_less_equal(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); NPY_NO_EXPORT void OBJECT_sign(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func)); /* ***************************************************************************** ** END LOOPS ** ***************************************************************************** */ #endif
50,825
828
/* * Copyright 2008-2009 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 net.hasor.registry.boot.launcher; /** * Telnetๆ‰ฉๅฑ•ๆŒ‡ไปค,ๅชๆœ‰้€š่ฟ‡ start.sh ๅฝขๅผๅฏๅŠจๆ—ถๆ‰ๅฏไปฅไฝฟ็”จ่ฟ™ไธชๆŒ‡ไปคใ€‚ * @version : 2016ๅนด3ๆœˆ29ๆ—ฅ * @author ่ตตๆฐธๆ˜ฅ (<EMAIL>) *//* public class CenterAppShutdownInstruct implements CommandExecutor { protected static Logger logger = LoggerFactory.getLogger(CenterAppShutdownInstruct.class); @Override public String helpInfo() { return "shutdown center."; } @Override public boolean inputMultiLine(CmdRequest request) { return false; } @Override public String doCommand(CmdRequest request) throws Throwable { boolean killSelfValue = Boolean.valueOf((String) request.getSessionAttr("open_kill_self")); if (!killSelfValue) { return "center can't quit, please run command."; } // logger.error("A valid shutdown command was received via the shutdown port. Stopping the Server instance."); request.writeMessageLine("detail Message:"); int i = 5; for (; ; ) { logger.error("after {} seconds to kill self.", i); request.writeMessageLine("after " + i + " seconds to kill self."); try { Thread.sleep(1000); } catch (Exception e) { /** / } i--; if (i == 0) { break; } } //ๅปถ่ฟŸ3็ง’๏ผŒshutdown final AppContext appContext = request.getFinder().getAppContext(); Thread thread = new Thread() { public void run() { try { Thread.sleep(1000); } catch (Exception e) {/** /} appContext.shutdown(); System.exit(1); } ; }; // request.writeMessageLine("shutdown center now."); thread.setDaemon(true); thread.setName("Shutdown"); thread.start(); return "do shutdown center."; } }*/
1,076
5,683
{ "usingComponents": { "mp-halfScreenDialog": "weui-miniprogram/half-screen-dialog/half-screen-dialog" }, "navigationBarTitleText": "half-screen-dialog" }
65
778
import os import KratosMultiphysics as Kratos from KratosMultiphysics import Logger Logger.GetDefaultOutput().SetSeverity(Logger.Severity.WARNING) import KratosMultiphysics.KratosUnittest as KratosUnittest import KratosMultiphysics.DEMApplication.DEM_analysis_stage import KratosMultiphysics.kratos_utilities as kratos_utils import auxiliary_functions_for_tests this_working_dir_backup = os.getcwd() print(os.getpid()) def GetFilePath(fileName): return os.path.join(os.path.dirname(os.path.realpath(__file__)), fileName) class ConstitutiveLawsTestSolution(KratosMultiphysics.DEMApplication.DEM_analysis_stage.DEMAnalysisStage, KratosUnittest.TestCase): @classmethod def GetMainPath(self): return os.path.join(os.path.dirname(os.path.realpath(__file__)), "constitutive_laws_tests_files") def GetProblemNameWithPath(self): return os.path.join(self.main_path, self.DEM_parameters["problem_name"].GetString()) def Finalize(self): self.PrintDebugGraphs() super().Finalize() def PrintDebugGraphs(self): import matplotlib.pyplot as plt import matplotlib.backends.backend_pdf pdf_name = self.GetProblemTypeFileName() + '.pdf' pdf = matplotlib.backends.backend_pdf.PdfPages(pdf_name) small = 5; medium = 10; large = 12 plt.rc('figure', titlesize=small); plt.rc('font', size=small); plt.rc('axes', titlesize=small); plt.rc('axes', labelsize=small) plt.rc('xtick', labelsize=small); plt.rc('ytick', labelsize=small); plt.rc('legend', fontsize=small) '''left = 0.4 # the left side of the subplots of the figure right = 0.5 # the right side of the subplots of the figure bottom = 0.4 # the bottom of the subplots of the figure top = 0.5 # the top of the subplots of the figure''' wspace = 0.3 # the amount of width reserved for blank space between subplots hspace = 0.3 # the amount of height reserved for white space between subplots #plt.subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace) #plt.tight_layout(pad=6.0) #plt.subplots_adjust(left=0.125, bottom=0.3, right=0.9, top=0.9, wspace=0.4, hspace=0.6) #Normal forces X, Y1, Y2, Y3, Y4, Y5, Y6 = [], [], [], [], [], [], [] Y7, Y8, Y9, Y10, Y11, Y12 = [], [], [], [], [], [] Y13, Y14, Y15, Y16, Y17, Y18 = [], [], [], [], [], [] Y19, Y20, Y21, Y22 = [], [], [], [] with open(os.path.join(self.GetMainPath(), 'nl.txt'), 'r') as normal: for line in normal: values = [float(s) for s in line.split()] X.append(values[0]) Y1.append(values[1]); Y2.append(values[2]); Y3.append(values[3]); Y4.append(values[4]); Y5.append(values[5]); Y6.append(values[6]) Y7.append(values[7]); Y8.append(values[8]); Y9.append(values[9]); Y10.append(values[10]); Y11.append(values[11]); Y12.append(values[12]) Y13.append(values[13]); Y14.append(values[14]); Y15.append(values[15]); Y16.append(values[16]); Y17.append(values[17]); Y18.append(values[18]) Y19.append(values[19]); Y20.append(values[20]); Y21.append(values[21]); Y22.append(values[22]) plt.figure(1) plt.subplot(3, 2, 1); plt.plot(X, Y1, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('indentation'); plt.grid() plt.subplot(3, 2, 2); plt.plot(X, Y2, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('LocalElasticContactForce[2]'); plt.grid() plt.subplot(3, 2, 3); plt.plot(X, Y3, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('limit_force'); plt.grid() plt.subplot(3, 2, 4); plt.plot(X, Y4, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('delta_accumulated'); plt.grid() plt.subplot(3, 2, 5); plt.plot(X, Y5, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('returned_by_mapping_force'); plt.grid() plt.subplot(3, 2, 6); plt.plot(X, Y6, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('kn_updated'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(1) plt.figure(2) plt.subplot(3, 2, 1); plt.plot(X, Y7, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mDamageNormal'); plt.grid() plt.subplot(3, 2, 2); plt.plot(X, Y8, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('failure_type'); plt.grid() plt.subplot(3, 2, 3); plt.plot(X, Y9, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('current_normal_force_module'); plt.grid() plt.subplot(3, 2, 4); plt.plot(X, Y10, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mDamageTangential'); plt.grid() plt.subplot(3, 2, 5); plt.plot(X, Y11, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('BondedLocalElasticContactForce2'); plt.grid() plt.subplot(3, 2, 6); plt.plot(X, Y12, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mUnbondedLocalElasticContactForce2'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(2) plt.figure(3) plt.subplot(3, 2, 1); plt.plot(X, Y13, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('kn_el'); plt.grid() plt.subplot(3, 2, 2); plt.plot(X, Y14, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mDamageEnergyCoeff'); plt.grid() plt.subplot(3, 2, 3); plt.plot(X, Y15, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('initial_limit_force'); plt.grid() plt.subplot(3, 2, 4); plt.plot(X, Y16, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mUnbondedNormalElasticConstant'); plt.grid() plt.subplot(3, 2, 5); plt.plot(X, Y17, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('LocalElasticContactTension'); plt.grid() plt.subplot(3, 2, 6); plt.plot(X, Y18, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('limit_tension'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(3) plt.figure(4) plt.subplot(2, 2, 1); plt.plot(X, Y19, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('returned_by_mapping_tension'); plt.grid() plt.subplot(2, 2, 2); plt.plot(X, Y20, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('current_normal_tension_module'); plt.grid() plt.subplot(2, 2, 3); plt.plot(X, Y21, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('BondedLocalElasticContactTension2'); plt.grid() plt.subplot(2, 2, 4); plt.plot(X, Y22, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('initial_limit_tension'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(4) #Tangential forces X, Y1, Y2, Y3, Y4, Y5, Y6 = [], [], [], [], [], [], [] Y7, Y8, Y9, Y10, Y11, Y12 = [], [], [], [], [], [] Y13, Y14, Y15, Y16, Y17, Y18 = [], [], [], [], [], [] Y19, Y20, Y21, Y22, Y23, Y24 = [], [], [], [], [], [] Y25, Y26, Y27, Y33, Y34, Y35 = [], [], [], [], [], [] with open(os.path.join(self.GetMainPath(), 'tg.txt'), 'r') as tangential: for line in tangential: values = [float(s) for s in line.split()] X.append(values[0]) Y1.append(values[1]); Y2.append(values[2]); Y3.append(values[3]); Y4.append(values[4]); Y5.append(values[5]); Y6.append(values[6]) Y7.append(values[7]); Y8.append(values[8]); Y9.append(values[9]); Y10.append(values[10]); Y11.append(values[11]); Y12.append(values[12]) Y13.append(values[13]); Y14.append(values[14]); Y15.append(values[15]); Y16.append(values[16]); Y17.append(values[17]); Y18.append(values[18]) Y19.append(values[19]); Y20.append(values[20]); Y21.append(values[21]); Y22.append(values[22]); Y23.append(values[23]); Y24.append(values[24]) Y25.append(values[25]); Y26.append(values[26]); Y27.append(values[27]); Y33.append(values[33]); Y34.append(values[34]); Y35.append(values[35]) plt.figure(5) plt.subplot(3, 2, 1); plt.plot(X, Y1, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('failure_type'); plt.grid() plt.subplot(3, 2, 2); plt.plot(X, Y2, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('tau_strength'); plt.grid() plt.subplot(3, 2, 3); plt.plot(X, Y3, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('kt_updated'); plt.grid() plt.subplot(3, 2, 4); plt.plot(X, Y4, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('sliding'); plt.grid() plt.subplot(3, 2, 5); plt.plot(X, Y5, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('contact_sigma'); plt.grid() plt.subplot(3, 2, 6); plt.plot(X, Y6, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mDamageNormal'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(5) plt.figure(6) plt.subplot(3, 2, 1); plt.plot(X, Y7, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('contact_tau'); plt.grid() plt.subplot(3, 2, 2); plt.plot(X, Y8, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('max_admissible_shear_force'); plt.grid() plt.subplot(3, 2, 3); plt.plot(X, Y9, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mDamageTangential'); plt.grid() plt.subplot(3, 2, 4); plt.plot(X, Y10, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('LocalElasticContactForce[0]'); plt.grid() plt.subplot(3, 2, 5); plt.plot(X, Y11, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('OldBondedLocalElasticContactForce[0]'); plt.grid() plt.subplot(3, 2, 6); plt.plot(X, Y12, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mUnbondedLocalElasticContactForce2'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(6) plt.figure(7) plt.subplot(3, 2, 1); plt.plot(X, Y13, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('BondedLocalElasticContactForce[0]'); plt.grid() plt.subplot(3, 2, 2); plt.plot(X, Y14, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mBondedScalingFactor'); plt.grid() plt.subplot(3, 2, 3); plt.plot(X, Y15, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('UnbondedLocalElasticContactForce[0]'); plt.grid() plt.subplot(3, 2, 4); plt.plot(X, Y16, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('LocalDeltDisp[0]'); plt.grid() plt.subplot(3, 2, 5); plt.plot(X, Y17, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mUnbondedScalingFactor'); plt.grid() plt.subplot(3, 2, 6); plt.plot(X, Y18, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('OldLocalElasticContactForce[0]'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(7) plt.figure(8) plt.subplot(3, 2, 1); plt.plot(X, Y19, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('LocalDeltDisp[1]'); plt.grid() plt.subplot(3, 2, 2); plt.plot(X, Y20, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('LocalElasticContactForce[1]'); plt.grid() plt.subplot(3, 2, 3); plt.plot(X, Y21, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('BondedLocalElasticContactForce[1]'); plt.grid() plt.subplot(3, 2, 4); plt.plot(X, Y22, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('UnbondedLocalElasticContactForce[1]'); plt.grid() plt.subplot(3, 2, 5); plt.plot(X, Y23, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('OldBondedLocalElasticContactForce[1]'); plt.grid() plt.subplot(3, 2, 6); plt.plot(X, Y24, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('OldUnbondedLocalElasticContactForce[1]'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(8) plt.figure(9) plt.subplot(3, 2, 1); plt.plot(X, Y25, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('delta_accumulated'); plt.grid() plt.subplot(3, 2, 2); plt.plot(X, Y26, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('current_tangential_force_module'); plt.grid() plt.subplot(3, 2, 3); plt.plot(X, Y27, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('returned_by_mapping_force'); plt.grid() plt.subplot(3, 2, 4); plt.plot(X, Y33, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('mDamageEnergyCoeff'); plt.grid() plt.subplot(3, 2, 5); plt.plot(X, Y34, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('LocalElasticContactForce[2]'); plt.grid() plt.subplot(3, 2, 6); plt.plot(X, Y35, '-', color='blue'); plt.xlabel('time (s)'); plt.ylabel('indentation'); plt.grid() plt.subplots_adjust(wspace=wspace, hspace=hspace) pdf.savefig(9) pdf.close() plt.close('all') class TestConstitutiveLaws(KratosUnittest.TestCase): def setUp(self): pass @classmethod def test_ConstitutiveLaws1(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "constitutive_laws_tests_files") os.chdir(path) parameters_file_name = os.path.join(path, "ProjectParametersDEM1.json") model = Kratos.Model() auxiliary_functions_for_tests.CreateAndRunStageInSelectedNumberOfOpenMPThreads(ConstitutiveLawsTestSolution, model, parameters_file_name, 1) @classmethod def test_ConstitutiveLaws2(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "constitutive_laws_tests_files") os.chdir(path) parameters_file_name = os.path.join(path, "ProjectParametersDEM2.json") model = Kratos.Model() auxiliary_functions_for_tests.CreateAndRunStageInSelectedNumberOfOpenMPThreads(ConstitutiveLawsTestSolution, model, parameters_file_name, 1) @classmethod def test_ConstitutiveLaws3(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "constitutive_laws_tests_files") os.chdir(path) parameters_file_name = os.path.join(path, "ProjectParametersDEM3.json") model = Kratos.Model() auxiliary_functions_for_tests.CreateAndRunStageInSelectedNumberOfOpenMPThreads(ConstitutiveLawsTestSolution, model, parameters_file_name, 1) def tearDown(self): file_to_remove = os.path.join("constitutive_laws_tests_files", "TimesPartialRelease") kratos_utils.DeleteFileIfExisting(GetFilePath(file_to_remove)) file_to_remove = os.path.join(this_working_dir_backup, "constitutive_laws_tests_files", "nl.txt") os.remove(file_to_remove) file_to_remove = os.path.join(this_working_dir_backup, "constitutive_laws_tests_files", "tg.txt") os.remove(file_to_remove) os.chdir(this_working_dir_backup) if __name__ == "__main__": Kratos.Logger.GetDefaultOutput().SetSeverity(Logger.Severity.WARNING) KratosUnittest.main()
6,998
1,144
<reponame>bingchunjin/1806_SDK /* * swlib.h: Switch configuration API (user space part) * * Copyright (C) 2008-2009 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * Usage of the library functions: The main datastructure for a switch is the struct switch_device To get started, you first need to use switch_connect() to probe for switches and allocate an instance of this struct. There are two possible usage modes: dev = switch_connect("eth0"); - this call will look for a switch registered for the linux device "eth0" and only allocate a switch_device for this particular switch. dev = switch_connect(NULL) - this will return one switch_device struct for each available switch. The switch_device structs are chained with by ->next pointer Then to query a switch for all available attributes, use: swlib_scan(dev); All allocated datastructures for the switch_device struct can be freed with swlib_free(dev); or swlib_free_all(dev); The latter traverses a whole chain of switch_device structs and frees them all Switch attributes (struct switch_attr) are divided into three groups: dev->ops: - global settings dev->port_ops: - per-port settings dev->vlan_ops: - per-vlan settings switch_lookup_attr() is a small helper function to locate attributes by name. switch_set_attr() and switch_get_attr() can alter or request the values of attributes. Usage of the switch_attr struct: ->atype: attribute group, one of: - SWLIB_ATTR_GROUP_GLOBAL - SWLIB_ATTR_GROUP_VLAN - SWLIB_ATTR_GROUP_PORT ->id: identifier for the attribute ->type: data type, one of: - SWITCH_TYPE_INT - SWITCH_TYPE_STRING - SWITCH_TYPE_PORT ->name: short name of the attribute ->description: longer description ->next: pointer to the next attribute of the current group Usage of the switch_val struct: When setting attributes, following members of the struct switch_val need to be set up: ->len (for attr->type == SWITCH_TYPE_PORT) ->port_vlan: - port number (for attr->atype == SWLIB_ATTR_GROUP_PORT), or: - vlan number (for attr->atype == SWLIB_ATTR_GROUP_VLAN) ->value.i (for attr->type == SWITCH_TYPE_INT) ->value.s (for attr->type == SWITCH_TYPE_STRING) - owned by the caller, not stored in the library internally ->value.ports (for attr->type == SWITCH_TYPE_PORT) - must point to an array of at lest val->len * sizeof(struct switch_port) When getting string attributes, val->value.s must be freed by the caller When getting port list attributes, an internal static buffer is used, which changes from call to call. */ #ifndef __SWLIB_H #define __SWLIB_H enum swlib_attr_group { SWLIB_ATTR_GROUP_GLOBAL, SWLIB_ATTR_GROUP_VLAN, SWLIB_ATTR_GROUP_PORT, }; enum swlib_port_flags { SWLIB_PORT_FLAG_TAGGED = (1 << 0), }; enum swlib_link_flags { SWLIB_LINK_FLAG_EEE_100BASET = (1 << 0), SWLIB_LINK_FLAG_EEE_1000BASET = (1 << 1), }; struct switch_dev; struct switch_attr; struct switch_port; struct switch_port_map; struct switch_port_link; struct switch_val; struct uci_package; struct switch_dev { int id; char dev_name[IFNAMSIZ]; char *name; char *alias; int ports; int vlans; int cpu_port; struct switch_attr *ops; struct switch_attr *port_ops; struct switch_attr *vlan_ops; struct switch_portmap *maps; struct switch_dev *next; void *priv; }; struct switch_val { struct switch_attr *attr; int len; int err; int port_vlan; union { char *s; int i; struct switch_port *ports; struct switch_port_link *link; } value; }; struct switch_attr { struct switch_dev *dev; int atype; int id; int type; char *name; char *description; struct switch_attr *next; }; struct switch_port { unsigned int id; unsigned int flags; }; struct switch_portmap { unsigned int virt; char *segment; }; struct switch_port_link { int link:1; int duplex:1; int aneg:1; int tx_flow:1; int rx_flow:1; int speed; /* in ethtool adv_t format */ uint32_t eee; }; /** * swlib_list: list all switches */ void swlib_list(void); /** * swlib_print_portmap: get portmap * @dev: switch device struct */ void swlib_print_portmap(struct switch_dev *dev, char *segment); /** * swlib_connect: connect to the switch through netlink * @name: name of the ethernet interface, * * if name is NULL, it connect and builds a chain of all switches */ struct switch_dev *swlib_connect(const char *name); /** * swlib_free: free all dynamically allocated data for the switch connection * @dev: switch device struct * * all members of a switch device chain (generated by swlib_connect(NULL)) * must be freed individually */ void swlib_free(struct switch_dev *dev); /** * swlib_free_all: run swlib_free on all devices in the chain * @dev: switch device struct */ void swlib_free_all(struct switch_dev *dev); /** * swlib_scan: probe the switch driver for available commands/attributes * @dev: switch device struct */ int swlib_scan(struct switch_dev *dev); /** * swlib_lookup_attr: look up a switch attribute * @dev: switch device struct * @type: global, port or vlan * @name: name of the attribute */ struct switch_attr *swlib_lookup_attr(struct switch_dev *dev, enum swlib_attr_group atype, const char *name); /** * swlib_set_attr: set the value for an attribute * @dev: switch device struct * @attr: switch attribute struct * @val: attribute value pointer * returns 0 on success */ int swlib_set_attr(struct switch_dev *dev, struct switch_attr *attr, struct switch_val *val); /** * swlib_set_attr_string: set the value for an attribute with type conversion * @dev: switch device struct * @attr: switch attribute struct * @port_vlan: port or vlan (if applicable) * @str: string value * returns 0 on success */ int swlib_set_attr_string(struct switch_dev *dev, struct switch_attr *attr, int port_vlan, const char *str); /** * swlib_get_attr: get the value for an attribute * @dev: switch device struct * @attr: switch attribute struct * @val: attribute value pointer * returns 0 on success * for string attributes, the result string must be freed by the caller */ int swlib_get_attr(struct switch_dev *dev, struct switch_attr *attr, struct switch_val *val); /** * swlib_apply_from_uci: set up the switch from a uci configuration * @dev: switch device struct * @p: uci package which contains the desired global config */ int swlib_apply_from_uci(struct switch_dev *dev, struct uci_package *p); #endif
2,299
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.modules.quicksearch; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FontMetrics; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences; import javax.swing.JComponent; import javax.swing.JLayeredPane; import javax.swing.JList; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import org.netbeans.modules.quicksearch.ProviderModel.Category; import org.netbeans.modules.quicksearch.recent.RecentSearches; import org.netbeans.modules.quicksearch.ResultsModel.ItemResult; import org.openide.util.NbBundle; import org.openide.util.NbPreferences; import org.openide.util.RequestProcessor; import org.openide.util.Task; import org.openide.util.TaskListener; /** * Component representing drop down for quick search * @author <NAME> */ public class QuickSearchPopup extends javax.swing.JPanel implements ListDataListener, ActionListener, TaskListener, Runnable { private static final String CUSTOM_WIDTH = "customWidth"; //NOI18N private static final int RESIZE_AREA_WIDTH = 5; private AbstractQuickSearchComboBar comboBar; private ResultsModel rModel; /* Rect to store repetitive bounds computation */ private Rectangle popupBounds = new Rectangle(); private Timer updateTimer; private static final int COALESCE_TIME = 300; /** text to search for */ private String searchedText; private int catWidth; private int resultWidth; private int defaultResultWidth = -1; private int customWidth = -1; private int longestText = -1; private boolean canResize = false; private Task evalTask; private Task saveTask; private static final RequestProcessor RP = new RequestProcessor(QuickSearchPopup.class); private static final RequestProcessor evaluatorRP = new RequestProcessor(QuickSearchPopup.class + ".evaluator"); //NOI18N private static final Logger LOG = Logger.getLogger(QuickSearchPopup.class.getName()); public QuickSearchPopup (AbstractQuickSearchComboBar comboBar) { this.comboBar = comboBar; initComponents(); loadSettings(); makeResizable(); rModel = ResultsModel.getInstance(); jList1.setModel(rModel); jList1.setCellRenderer(new SearchResultRender(this)); rModel.addListDataListener(this); if( "Aqua".equals(UIManager.getLookAndFeel().getID()) ) //NOI18N jList1.setBackground(QuickSearchComboBar.getResultBackground()); updateStatusPanel(evalTask != null); setVisible(false); } void invoke() { ItemResult result = ((ItemResult) jList1.getModel().getElementAt(jList1.getSelectedIndex())); if (result != null) { RecentSearches.getDefault().add(result); result.getAction().run(); if (comboBar.getCommand().isFocusOwner()) { // Needed in case the focus couldn't be returned to the caller, // see #228668. comboBar.getCommand().setText(""); //NOI18N } clearModel(); } } void selectNext() { int oldSel = jList1.getSelectedIndex(); if (oldSel >= 0 && oldSel < jList1.getModel().getSize() - 1) { jList1.setSelectedIndex(oldSel + 1); } if (jList1.getModel().getSize() > 0) { setVisible(true); } } void selectPrev() { int oldSel = jList1.getSelectedIndex(); if (oldSel > 0) { jList1.setSelectedIndex(oldSel - 1); } if (jList1.getModel().getSize() > 0) { setVisible(true); } } public JList getList() { return jList1; } public void clearModel () { rModel.setContent(null); longestText = -1; } public void maybeEvaluate (String text) { this.searchedText = text; if (text.length()>0) { updateStatusPanel(true); updatePopup(true); } if (updateTimer == null) { updateTimer = new Timer(COALESCE_TIME, this); } if (!updateTimer.isRunning()) { // first change in possible flurry, start timer updateTimer.start(); } else { // text change came too fast, let's wait until user calms down :) updateTimer.restart(); } } /** implementation of ActionListener, called by timer, * actually runs search */ @Override public void actionPerformed(ActionEvent e) { updateTimer.stop(); // search only if we are not cancelled already if (comboBar.getCommand().isFocusOwner()) { evaluatorRP.post(new Runnable() { @Override public void run() { if (evalTask != null) { evalTask.removeTaskListener(QuickSearchPopup.this); } evalTask = CommandEvaluator.evaluate(searchedText, rModel); evalTask.addTaskListener(QuickSearchPopup.this); // start waiting on all providers execution RP.post(evalTask); } }); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jScrollPane1 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList(); statusPanel = new javax.swing.JPanel(); searchingSep = new javax.swing.JSeparator(); searchingLabel = new javax.swing.JLabel(); noResultsLabel = new javax.swing.JLabel(); hintSep = new javax.swing.JSeparator(); hintLabel = new javax.swing.JLabel(); setBorder(javax.swing.BorderFactory.createLineBorder(QuickSearchComboBar.getPopupBorderColor())); setLayout(new java.awt.BorderLayout()); jScrollPane1.setBorder(null); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); jList1.setFocusable(false); jList1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jList1MouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jList1MousePressed(evt); } }); jList1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { jList1MouseDragged(evt); } public void mouseMoved(java.awt.event.MouseEvent evt) { jList1MouseMoved(evt); } }); jScrollPane1.setViewportView(jList1); add(jScrollPane1, java.awt.BorderLayout.CENTER); statusPanel.setBackground(QuickSearchComboBar.getResultBackground()); statusPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; statusPanel.add(searchingSep, gridBagConstraints); searchingLabel.setText(org.openide.util.NbBundle.getMessage(QuickSearchPopup.class, "QuickSearchPopup.searchingLabel.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; statusPanel.add(searchingLabel, gridBagConstraints); noResultsLabel.setForeground(java.awt.Color.red); noResultsLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); noResultsLabel.setText(org.openide.util.NbBundle.getMessage(QuickSearchPopup.class, "QuickSearchPopup.noResultsLabel.text")); // NOI18N noResultsLabel.setFocusable(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; statusPanel.add(noResultsLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; statusPanel.add(hintSep, gridBagConstraints); hintLabel.setBackground(QuickSearchComboBar.getResultBackground()); hintLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; statusPanel.add(hintLabel, gridBagConstraints); add(statusPanel, java.awt.BorderLayout.PAGE_END); }// </editor-fold>//GEN-END:initComponents private void jList1MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseMoved // toggle resize/default cursor if (evt.getX() < RESIZE_AREA_WIDTH) { QuickSearchPopup.this.setCursor(Cursor.getPredefinedCursor( Cursor.W_RESIZE_CURSOR)); } else { QuickSearchPopup.this.setCursor(Cursor.getDefaultCursor()); } // selection follows mouse move Point loc = evt.getPoint(); int index = jList1.locationToIndex(loc); if (index == -1) { return; } Rectangle rect = jList1.getCellBounds(index, index); if (rect != null && rect.contains(loc)) { jList1.setSelectedIndex(index); } }//GEN-LAST:event_jList1MouseMoved private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked if (!SwingUtilities.isLeftMouseButton(evt)) { return; } // mouse left button click works the same as pressing Enter key comboBar.invokeSelectedItem(); }//GEN-LAST:event_jList1MouseClicked private void jList1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseDragged QuickSearchPopup.this.processMouseMotionEvent(evt); }//GEN-LAST:event_jList1MouseDragged private void jList1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MousePressed QuickSearchPopup.this.processMouseEvent(evt); }//GEN-LAST:event_jList1MousePressed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel hintLabel; private javax.swing.JSeparator hintSep; private javax.swing.JList jList1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel noResultsLabel; private javax.swing.JLabel searchingLabel; private javax.swing.JSeparator searchingSep; private javax.swing.JPanel statusPanel; // End of variables declaration//GEN-END:variables /*** impl of reactions to results data change */ public void intervalAdded(ListDataEvent e) { updatePopup(evalTask != null); } public void intervalRemoved(ListDataEvent e) { updatePopup(evalTask != null); } public void contentsChanged(ListDataEvent e) { if (customWidth < 0) { if (rModel.getContent() == null) { longestText = -1; resultWidth = -1; } else { for (CategoryResult r : rModel.getContent()) { for (ItemResult i : r.getItems()) { int l = i.getDisplayName().length(); if (l > longestText) { longestText = l; resultWidth = -1; } } } } } updatePopup(evalTask != null); } /** * Updates size and visibility of this panel according to model content */ public void updatePopup (boolean isInProgress) { updatePopup(isInProgress, true); } private void updatePopup (boolean isInProgress, boolean canRetry) { int modelSize = rModel.getSize(); if (modelSize > 0 && jList1.getSelectedIndex()<0) { jList1.setSelectedIndex(0); } // plug this popup into layered pane if needed JLayeredPane lPane = JLayeredPane.getLayeredPaneAbove(comboBar); if (lPane == null) { // #162075 - return when comboBar not yet seeded in AWT hierarchy return; } if (!isDisplayable()) { lPane.add(this, new Integer(JLayeredPane.POPUP_LAYER + 1) ); } boolean statusVisible = updateStatusPanel(isInProgress); try { computePopupBounds(popupBounds, lPane, modelSize); } catch (Exception e) { //sometimes the hack in computePopupBounds fails LOG.log(canRetry ? Level.INFO : Level.SEVERE, null, e); retryUpdatePopup(canRetry, isInProgress); return; } setBounds(popupBounds); // popup visibility constraints if ((modelSize > 0 || statusVisible) && comboBar.getCommand().isFocusOwner()) { if (modelSize > 0 && !isVisible()) { jList1.setSelectedIndex(0); } if (jList1.getSelectedIndex() >= modelSize) { jList1.setSelectedIndex(modelSize - 1); } if (explicitlyInvoked || !searchedText.isEmpty()) { setVisible(true); } } else { setVisible(false); } explicitlyInvoked = false; // needed on JDK 1.5.x to repaint correctly revalidate(); } /** * Retry to update popup if something went wrong, but only if it is allowed. * See bug 205356. */ private void retryUpdatePopup(boolean canRetry, final boolean isInProgress) { if (canRetry) { EventQueue.invokeLater(new Runnable() { @Override public void run() { updatePopup(isInProgress, false); // do not retry again } }); } } private boolean explicitlyInvoked = false; /** User actually pressed Ctrl-I; display popup even just for Recent Searches. */ void explicitlyInvoked() { explicitlyInvoked = true; } public int getCategoryWidth () { if (catWidth <= 0) { catWidth = computeWidth(jList1, 20, 30); } return catWidth; } public int getResultWidth () { if (customWidth > 0) { return Math.max(customWidth, getDefaultResultWidth()); } else { if (resultWidth <= 0) { resultWidth = computeWidth( jList1, limit(longestText, 42, 128), 50); } return resultWidth; } } private int getDefaultResultWidth() { if (defaultResultWidth <= 0) { defaultResultWidth = computeWidth(jList1, 42, 50); } return defaultResultWidth; } private int limit(int value, int min, int max) { assert min <= max; return Math.min(max, Math.max(min, value)); } public int getPopupWidth() { int maxWidth = this.getParent() == null ? Integer.MAX_VALUE : this.getParent().getWidth() - 10; return Math.min(getCategoryWidth() + getResultWidth() + 3, maxWidth); } /** Implementation of TaskListener, listen to when providers are finished * with their searching work */ public void taskFinished(Task task) { evalTask = null; // update UI in ED thread if (SwingUtilities.isEventDispatchThread()) { run(); } else { SwingUtilities.invokeLater(this); } } /** Runnable implementation, updates popup */ public void run() { updatePopup(evalTask != null); } private void computePopupBounds (Rectangle result, JLayeredPane lPane, int modelSize) { Dimension cSize = comboBar.getSize(); int width = getPopupWidth(); Point location = new Point(cSize.width - width - 1, comboBar.getBottomLineY() - 1); if (SwingUtilities.getWindowAncestor(comboBar) != null) { location = SwingUtilities.convertPoint(comboBar, location, lPane); } result.setLocation(location); // hack to make jList.getpreferredSize work correctly // JList is listening on ResultsModel same as us and order of listeners // is undefined, so we have to force update of JList's layout data jList1.setFixedCellHeight(15); jList1.setFixedCellHeight(-1); // end of hack jList1.setVisibleRowCount(modelSize); Dimension preferredSize = jList1.getPreferredSize(); preferredSize.width = width; preferredSize.height += statusPanel.getPreferredSize().height + 3; result.setSize(preferredSize); } /** Computes width of string up to maxCharCount, with font of given JComponent * and with maximum percentage of owning Window that can be taken */ private static int computeWidth (JComponent comp, int maxCharCount, int percent) { FontMetrics fm = comp.getFontMetrics(comp.getFont()); int charW = fm.charWidth('X'); int result = charW * maxCharCount; // limit width to 50% of containing window Window w = SwingUtilities.windowForComponent(comp); if (w != null) { result = Math.min(result, w.getWidth() * percent / 100); } return result; } /** Updates visibility and content of status labels. * * @return true when update panel should be visible (some its part is visible), * false otherwise */ private boolean updateStatusPanel (boolean isInProgress) { boolean shouldBeVisible = false; searchingSep.setVisible(isInProgress); searchingLabel.setVisible(isInProgress); if (comboBar instanceof QuickSearchComboBar) { if (isInProgress) { ((QuickSearchComboBar) comboBar).startProgressAnimation(); } else { ((QuickSearchComboBar) comboBar).stopProgressAnimation(); } } shouldBeVisible = shouldBeVisible || isInProgress; boolean searchedNotEmpty = searchedText != null && searchedText.trim().length() > 0; boolean areNoResults = rModel.getSize() <= 0 && searchedNotEmpty && !isInProgress; noResultsLabel.setVisible(areNoResults); comboBar.setNoResults(areNoResults); shouldBeVisible = shouldBeVisible || areNoResults; hintLabel.setText(getHintText()); boolean isNarrowed = CommandEvaluator.isTemporaryCatSpecified() && searchedNotEmpty; hintSep.setVisible(isNarrowed); hintLabel.setVisible(isNarrowed); shouldBeVisible = shouldBeVisible || isNarrowed; return shouldBeVisible; } private String getHintText () { Category temp = CommandEvaluator.getTemporaryCat(); if (temp != null) { return NbBundle.getMessage(QuickSearchPopup.class, "QuickSearchPopup.hintLabel.text", //NOI18N temp.getDisplayName(), SearchResultRender.getKeyStrokeAsText( comboBar.getKeyStroke())); } else { return null; } } /** * Register listeners that make this pop-up resizable. */ private void makeResizable() { this.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { if (canResize) { customWidth = Math.max(1, getResultWidth() - e.getX()); run(); saveSettings(); } } }); this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { canResize = e.getX() < RESIZE_AREA_WIDTH; } }); } /** * Load settings from preferences file. */ private void loadSettings() { RP.post(new Runnable() { @Override public void run() { Preferences p = NbPreferences.forModule(QuickSearchPopup.class); customWidth = p.getInt(CUSTOM_WIDTH, -1); } }); } /** * Save settings to preferences file. Do nothing if this operation is * already scheduled. */ private synchronized void saveSettings() { if (saveTask == null) { saveTask = RP.create(new Runnable() { @Override public void run() { Preferences p = NbPreferences.forModule( QuickSearchPopup.class); p.putInt(CUSTOM_WIDTH, customWidth); synchronized (QuickSearchPopup.this) { saveTask = null; } } }); RP.post(saveTask, 1000); } } }
9,981
1,609
package com.mossle.humantask.rule; import java.util.List; import com.mossle.api.org.OrgConnector; import com.mossle.core.spring.ApplicationContextHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; /** * ่Žทๅพ—้ƒจ้—จๆœ€ๆŽฅ่ฟ‘็š„ๅฏนๅบ”็š„ๅฒ—ไฝ็š„ไบบ็š„ไฟกๆฏ. * */ public class PositionAssigneeRule implements AssigneeRule { private static Logger logger = LoggerFactory .getLogger(PositionAssigneeRule.class); private JdbcTemplate jdbcTemplate; private OrgConnector orgConnector; public List<String> process(String value, String initiator) { return ApplicationContextHelper.getBean(OrgConnector.class) .getPositionUserIds(initiator, value); } public String process(String initiator) { return null; } }
330
5,937
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*************************************************************************** * module: TTFTABLE.C * * * aRoutines to read true type tables and table information from * a true type file buffer * **************************************************************************/ /* Inclusions ----------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "typedefs.h" #include "ttff.h" /* true type font file def's */ #include "ttfacc.h" #include "ttftable.h" #include "ttftabl1.h" #include "ttfcntrl.h" #include "ttmem.h" #include "util.h" #include "ttfdelta.h" /* for Dont care info */ #include "ttferror.h" #include "ttfdcnfg.h" /* ---------------------------------------------------------------------- */ PRIVATE int CRTCB AscendingTagCompare( CONST void *arg1, CONST void *arg2 ) { if (((DIRECTORY *)(arg1))->tag == ((DIRECTORY *)(arg2))->tag) /* they're the same */ return 0; if (((DIRECTORY *)(arg1))->tag < ((DIRECTORY *)(arg2))->tag) return -1; return 1; } /* ---------------------------------------------------------------------- */ PRIVATE int CRTCB AscendingOffsetCompare( CONST void *arg1, CONST void *arg2 ) { if (((DIRECTORY *)(arg1))->offset == ((DIRECTORY *)(arg2))->offset) /* they're the same */ return 0; if (((DIRECTORY *)(arg1))->offset < ((DIRECTORY *)(arg2))->offset) return -1; return 1; } /* ---------------------------------------------------------------------- */ /* this routine sorts an array of directory entries by tag value using a qsort */ /* ---------------------------------------------------------------------- */ void SortByTag( DIRECTORY * aDirectory, uint16 usnDirs ) { if (aDirectory == NULL || usnDirs == 0) return; qsort (aDirectory, usnDirs, sizeof(*aDirectory),AscendingTagCompare); } /* ---------------------------------------------------------------------- */ /* this routine sorts an array of directory entries by offset value using a qsort */ /* ---------------------------------------------------------------------- */ void SortByOffset( DIRECTORY * aDirectory, uint16 usnDirs ) { if (aDirectory == NULL || usnDirs == 0) return; qsort (aDirectory, usnDirs, sizeof(*aDirectory),AscendingOffsetCompare); } /* ---------------------------------------------------------------------- */ /* this routine marks a font file table for deletion. To do so, it sets the tag to something unrecognizable so it will be filtered out by the compress tables operation at the end of program execution. */ /* ---------------------------------------------------------------------- */ void MarkTableForDeletion( TTFACC_FILEBUFFERINFO * pOutputBufferInfo, __in_bcount(4) const char * szDirTag ) { DIRECTORY Directory; uint32 ulOffset; uint16 usBytesMoved; /* read existing directory entry */ ulOffset = GetTTDirectory( pOutputBufferInfo, szDirTag, &Directory ); if ( ulOffset == DIRECTORY_ERROR ) return; /* set bad directory tag using an arbitrary, nonsensical value */ Directory.tag = DELETETABLETAG; /* write new directory entry */ if (WriteGeneric( pOutputBufferInfo, (uint8 *) &Directory, SIZEOF_DIRECTORY, DIRECTORY_CONTROL, ulOffset, &usBytesMoved ) != NO_ERROR) { // We just readed from the very same place. assert(FALSE); }; } /* MarkTableForDeletion() */ /* ---------------------------------------------------------------------- */ uint32 FindCmapSubtable( TTFACC_FILEBUFFERINFO * pOutputBufferInfo, uint16 usDesiredPlatform, uint16 usDesiredEncodingID, uint16 *pusFoundEncoding ) { int16 i; CMAP_HEADER CmapHeader; CMAP_TABLELOC CmapTableLoc; BOOL fFound; int16 nCmapTables; uint16 usBytesRead; uint32 ulOffset; uint32 ulCmapOffset; uint32 ulFoundOffset; /* Read header of the 'cmap' table */ if (!(ulCmapOffset = TTTableOffset( pOutputBufferInfo, CMAP_TAG ))) return (0L); if (ReadGeneric( pOutputBufferInfo, (uint8 *) &CmapHeader, SIZEOF_CMAP_HEADER, CMAP_HEADER_CONTROL, ulCmapOffset, &usBytesRead) != NO_ERROR) return (0L); /* read directory entries to find the desired encoding table. The directory entries for subtables give the offset from the beginning of the 'cmap' table to where the desired table begins. */ fFound = FALSE; ulFoundOffset = 0; ulOffset = ulCmapOffset + usBytesRead; nCmapTables = CmapHeader.numTables; if (usDesiredPlatform == TTFSUB_MS_PLATFORMID && usDesiredEncodingID == TTFSUB_DONT_CARE) { for (i = 0; i < nCmapTables; ++i, ulOffset += usBytesRead) { if (ReadGeneric( pOutputBufferInfo, (uint8 *) &CmapTableLoc, SIZEOF_CMAP_TABLELOC, CMAP_TABLELOC_CONTROL, ulOffset, &usBytesRead) != NO_ERROR) return (0L); if ( CmapTableLoc.platformID == TTFSUB_MS_PLATFORMID ) { if (CmapTableLoc.encodingID == TTFSUB_SURROGATE_CHAR_SET) { ulFoundOffset = CmapTableLoc.offset; *pusFoundEncoding = CmapTableLoc.encodingID; fFound = TRUE; } else if (CmapTableLoc.encodingID == TTFSUB_UNICODE_CHAR_SET && (!fFound || *pusFoundEncoding!=TTFSUB_SURROGATE_CHAR_SET)) { ulFoundOffset = CmapTableLoc.offset; *pusFoundEncoding = CmapTableLoc.encodingID; fFound = TRUE; } else if (CmapTableLoc.encodingID == TTFSUB_SYMBOL_CHAR_SET && !fFound) { ulFoundOffset = CmapTableLoc.offset; *pusFoundEncoding = CmapTableLoc.encodingID; fFound = TRUE; } } } } else { for (i = 0; i < nCmapTables && !fFound ; ++i, ulOffset += usBytesRead) { if (ReadGeneric( pOutputBufferInfo, (uint8 *) &CmapTableLoc, SIZEOF_CMAP_TABLELOC, CMAP_TABLELOC_CONTROL, ulOffset, &usBytesRead) != NO_ERROR) return (0L); if ( CmapTableLoc.platformID == usDesiredPlatform && ( CmapTableLoc.encodingID == usDesiredEncodingID || usDesiredEncodingID == TTFSUB_DONT_CARE ) ) { ulFoundOffset = CmapTableLoc.offset; fFound = TRUE; *pusFoundEncoding = CmapTableLoc.encodingID; } } } if ( fFound == FALSE ) return( 0L ); /* return address of cmap subtable relative to start of file */ return( ulCmapOffset + ulFoundOffset ); } /* FindCmapSubtable() */ /* ---------------------------------------------------------------------- */ PRIVATE uint16 GuessNumCmapGlyphIds( uint16 usnSegments, FORMAT4_SEGMENTS * Format4Segments ) { /* this routine guesses the approximate number of entries in the GlyphId array of the format 4 cmap table. This guessing is necessary because there is nothing in the format 4 table that explicitly indicates the number of GlyphId entries, and it is not valid to assume any particular number, such as one based on the number of glyphs or the size of the format 4 cmap table. */ int32 sIdIdx; uint16 usCharCode; uint16 i; uint16 usMaxGlyphIdIdx; /* zip through cmap entries, checking each entry to see if it indexes into the GlyphId array. If it does, determine the array index, and keep track of the maximum array index used. The maximum used then becomes the guess as to the number of GlyphIds. */ usMaxGlyphIdIdx = 0; for ( i = 0; i < usnSegments; i++ ) { if ( Format4Segments[i].idRangeOffset == 0 ) continue; for ( usCharCode = Format4Segments[ i ].startCount; usCharCode <= Format4Segments[ i ].endCount && Format4Segments[ i ].endCount != INVALID_CHAR_CODE; usCharCode++ ) { sIdIdx = (uint16) i - (uint16) usnSegments; sIdIdx += (uint16) (Format4Segments[i].idRangeOffset / 2) + usCharCode - Format4Segments[i].startCount; usMaxGlyphIdIdx = max( usMaxGlyphIdIdx, (uint16) (sIdIdx+1) ); } } return( usMaxGlyphIdIdx ); } /* ---------------------------------------------------------------------- */ /* special case, need to read long or short repeatedly into long buffer */ /* buffer must have been allocated large enough for the number of glyphs */ uint32 GetLoca( TTFACC_FILEBUFFERINFO *pInputBufferInfo, __out_ecount(ulAllocedCount) uint32 *pulLoca, __range(1, USHORT_MAX + 1) uint32 ulAllocedCount ) { uint32 ulOffset = 0; uint16 usOffset; HEAD Head; uint16 usIdxToLocFmt; uint32 ulGlyphCount; uint32 i; uint32 ulBytesRead; if ( ! GetHead( pInputBufferInfo, &Head )) return( 0L ); usIdxToLocFmt = Head.indexToLocFormat; ulGlyphCount = GetNumGlyphs(pInputBufferInfo ); if (ulAllocedCount < ulGlyphCount + 1) /* not enough room to read this */ return 0L; if (!(ulOffset = TTTableOffset( pInputBufferInfo, LOCA_TAG ))) return 0L; if ( usIdxToLocFmt == SHORT_OFFSETS ) { for (i = 0; i <= ulGlyphCount; ++i) { if (ReadWord( pInputBufferInfo, &usOffset, ulOffset + (i*sizeof(uint16))) != NO_ERROR) return 0L; pulLoca[i] = (int32) usOffset * 2L; } } else { if (ReadGenericRepeat(pInputBufferInfo, (uint8 *)pulLoca, LONG_CONTROL, ulOffset, &ulBytesRead, (uint16) (ulGlyphCount + 1), sizeof(uint32)) != NO_ERROR) return 0L; } return( ulOffset ); } PRIVATE int CRTCB CompareSegments(const void *elem1, const void *elem2) { if ((((FORMAT4_SEGMENTS *)(elem1))->endCount <= ((FORMAT4_SEGMENTS *)(elem2))->endCount) /* it is within this range */ && (((FORMAT4_SEGMENTS *)(elem1))->startCount >= ((FORMAT4_SEGMENTS *)(elem2))->startCount)) return 0; if (((FORMAT4_SEGMENTS *)(elem1))->startCount < ((FORMAT4_SEGMENTS *)(elem2))->startCount) return -1; return 1; } /* ---------------------------------------------------------------------- */ uint16 GetGlyphIdx( uint16 usCharCode, FORMAT4_SEGMENTS * Format4Segments, uint16 usnSegments, GLYPH_ID * GlyphId, uint16 usnGlyphs) { uint16 usGlyphIdx; int32 sIDIdx; FORMAT4_SEGMENTS *pFormat4Segment; FORMAT4_SEGMENTS KeySegment; KeySegment.startCount = usCharCode; KeySegment.endCount = usCharCode; /* find segment containing the character code */ pFormat4Segment = (FORMAT4_SEGMENTS *)bsearch(&KeySegment, Format4Segments, usnSegments, sizeof(*Format4Segments), CompareSegments); if ( pFormat4Segment == NULL ) return( INVALID_GLYPH_INDEX ); /* calculate the glyph index */ if ( pFormat4Segment->idRangeOffset == 0 ) usGlyphIdx = usCharCode + pFormat4Segment->idDelta; else { sIDIdx = (int32)(pFormat4Segment - (Format4Segments + usnSegments)); /* sIDIdx = (uint16) i - (uint16) usnSegments; */ sIDIdx += (int32) (pFormat4Segment->idRangeOffset / 2) + usCharCode - pFormat4Segment->startCount; /* check against bounds */ if (sIDIdx >= usnGlyphs) return INVALID_GLYPH_INDEX; usGlyphIdx = GlyphId[ sIDIdx ]; if (usGlyphIdx) /* Only add in idDelta if we've really got a glyph! */ usGlyphIdx = (uint16)(usGlyphIdx + pFormat4Segment->idDelta); } return( usGlyphIdx ); } /* GetGlyphIdx */ /* ---------------------------------------------------------------------- */ uint32 GetGlyphIdx12( uint32 ulCharCode, FORMAT12_GROUPS * pFormat12Groups, uint32 ulnGroups ) { uint32 i; uint32 ulGlyphIdx = INVALID_GLYPH_INDEX_LONG; /* should we do a binary search here, i.e. are the groups sorted? */ for ( i=0; i < ulnGroups; i++) { if (pFormat12Groups[i].startCharCode <= ulCharCode && pFormat12Groups[i].endCharCode >= ulCharCode) ulGlyphIdx = pFormat12Groups[i].startGlyphCode + (ulCharCode - pFormat12Groups[i].startCharCode); } return( ulGlyphIdx ); } /* GetGlyphIdx12 */ /* ---------------------------------------------------------------------- */ void FreeCmapFormat4Ids( GLYPH_ID *GlyphId ) { Mem_Free( GlyphId ); } /* ---------------------------------------------------------------------- */ void FreeCmapFormat4Segs( FORMAT4_SEGMENTS *Format4Segments) { Mem_Free( Format4Segments ); } /* ---------------------------------------------------------------------- */ void FreeCmapFormat4( FORMAT4_SEGMENTS *Format4Segments, GLYPH_ID *GlyphId ) { FreeCmapFormat4Segs( Format4Segments ); FreeCmapFormat4Ids( GlyphId ); } /* ---------------------------------------------------------------------- */ int16 ReadAllocCmapFormat4Ids( TTFACC_FILEBUFFERINFO * pInputBufferInfo, uint16 usSegCount, FORMAT4_SEGMENTS * Format4Segments, GLYPH_ID ** ppGlyphId, uint16 * pusnIds, uint32 ulOffset, uint32 *pulBytesRead ) { uint16 i; int16 errCode; /* calc number of glyph indexes while making sure the start and end count numbers used to calc the number of indexes is reasonable */ *ppGlyphId = NULL; for ( i=0; i < usSegCount; i++ ) { /* check for reasonable start and end counts */ if ( Format4Segments[i].endCount < Format4Segments[i].startCount ) return(ERR_INVALID_CMAP); } /* set the return value for number of glyph Ids. As of this writing (9/20/90), there was no reliable way to calculate the size of the ppGlyphId array, so here we just read a lot of values and assume that it will be enough. */ *pusnIds = GuessNumCmapGlyphIds( usSegCount, Format4Segments ); /* allocate memory for GlyphID array */ if ( *pusnIds == 0 ) return(NO_ERROR); *ppGlyphId = (GLYPH_ID *)Mem_Alloc(*pusnIds * sizeof( (*ppGlyphId)[0] )); if ( *ppGlyphId == NULL ) return(ERR_MEM); /* read glyph index array */ if ((errCode = ReadGenericRepeat( pInputBufferInfo, (uint8 *) *ppGlyphId, WORD_CONTROL, ulOffset, pulBytesRead, *pusnIds, sizeof( (*ppGlyphId)[0] ))) != NO_ERROR) { Mem_Free(*ppGlyphId); *ppGlyphId = NULL; return (errCode); } return(NO_ERROR ); } /* ReadAllocCmapFormat4Ids() */ /* ---------------------------------------------------------------------- */ int16 ReadAllocCmapFormat4Segs( TTFACC_FILEBUFFERINFO * pInputBufferInfo, uint16 usSegCount, FORMAT4_SEGMENTS ** Format4Segments, uint32 ulOffset, uint32 *pulBytesRead) { uint16 i; uint16 usReservedPad; uint16 usWordSize; uint32 ulCurrentOffset = ulOffset; int16 errCode; uint32 ulBytesRead; /* allocate memory for variable length part of table */ *Format4Segments = (FORMAT4_SEGMENTS *)Mem_Alloc( usSegCount * SIZEOF_FORMAT4_SEGMENTS); if ( *Format4Segments == NULL ) return( ERR_MEM ); usWordSize = sizeof(uint16); // Check that we have no iteger overflow if (ulCurrentOffset + (4 * usSegCount + 1) * usWordSize < ulCurrentOffset) { return ERR_READOUTOFBOUNDS; } for ( i = 0; i < usSegCount; i++ ) if ((errCode = ReadWord( pInputBufferInfo, &(*Format4Segments)[i].endCount, ulCurrentOffset+(i*usWordSize))) != NO_ERROR) { Mem_Free( *Format4Segments); *Format4Segments = NULL; return errCode; } ulCurrentOffset += usSegCount * usWordSize; if ((errCode = ReadWord( pInputBufferInfo, &usReservedPad,ulCurrentOffset)) != NO_ERROR) { Mem_Free( *Format4Segments); *Format4Segments = NULL; return errCode; } ulCurrentOffset += usWordSize; for ( i = 0; i < usSegCount; i++ ) if ((errCode = ReadWord( pInputBufferInfo, &(*Format4Segments)[i].startCount, ulCurrentOffset+(i*usWordSize))) != NO_ERROR) { Mem_Free( *Format4Segments); *Format4Segments = NULL; return errCode; } ulCurrentOffset += usWordSize * usSegCount; for ( i = 0; i < usSegCount; i++ ) if ((errCode = ReadWord( pInputBufferInfo, (uint16 *)&(*Format4Segments)[i].idDelta, ulCurrentOffset+(i*usWordSize))) != NO_ERROR) { Mem_Free( *Format4Segments); *Format4Segments = NULL; return errCode; } ulCurrentOffset += usWordSize * usSegCount; for ( i = 0; i < usSegCount; i++ ) if ((errCode = ReadWord( pInputBufferInfo, &(*Format4Segments)[i].idRangeOffset, ulCurrentOffset+(i*usWordSize))) != NO_ERROR) { Mem_Free( *Format4Segments); *Format4Segments = NULL; return errCode; } ulCurrentOffset += usWordSize * usSegCount; ulBytesRead = ( ulCurrentOffset - ulOffset); /* this is defined to fit into an unsigned short */ // claudebe 2/25/00, we are shipping FE fonts with cmap subtable format 4 that have a lenght that doesn't fit in a USHORT // commenting out the test *pulBytesRead = ulBytesRead; // if (*pulBytesRead != ulBytesRead) /* overrun the unsigned short */ // return(ERR_INVALID_CMAP); return( NO_ERROR ); } /* ReadAllocCmapFormat4Segs( ) */ /* ---------------------------------------------------------------------- */ int16 ReadCmapLength( TTFACC_FILEBUFFERINFO * pInputBufferInfo, CMAP_SUBHEADER_GEN * pCmapSubHeader, uint32 ulStartOffset, uint16 * pusBytesRead ) { int16 errCode = NO_ERROR; uint32 ulOffset; ulOffset = ulStartOffset; /* Read the format */ if ((errCode = ReadWord( pInputBufferInfo, (uint16 *) &pCmapSubHeader->format, ulOffset)) != NO_ERROR) return(errCode); ulOffset += sizeof(uint16); /* Read the length depending on format */ switch (pCmapSubHeader->format) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: { /* older cmap sub table header, with length as short */ uint16 usLen; if ((errCode = ReadWord( pInputBufferInfo, (uint16 *) &usLen, ulOffset)) != NO_ERROR) return(errCode); pCmapSubHeader->length = (uint32)usLen; ulOffset += sizeof(uint16); /* skip version */ ulOffset += sizeof(uint16); } break; case 14: { /* newer cmap sub table header, w/ length as long */ /* Note: Format 14 does NOT have a USHORT reserved field before length as in the default case */ if ((errCode = ReadLong( pInputBufferInfo, (uint32 *) &pCmapSubHeader->length, ulOffset)) != NO_ERROR) return(errCode); ulOffset += sizeof(uint32); } break; default: { /* newer cmap sub table header, w/ length as long */ ulOffset += sizeof(uint16); if ((errCode = ReadLong( pInputBufferInfo, (uint32 *) &pCmapSubHeader->length, ulOffset)) != NO_ERROR) return(errCode); ulOffset += sizeof(uint32); } } if (pusBytesRead) *pusBytesRead = (uint16)(ulOffset-ulStartOffset); return errCode; } /* ---------------------------------------------------------------------- */ int16 ReadAllocCmapFormat4( TTFACC_FILEBUFFERINFO * pInputBufferInfo, CONST uint16 usPlatform, CONST uint16 usEncoding, uint16 *pusFoundEncoding, CMAP_FORMAT4 * pCmapFormat4, FORMAT4_SEGMENTS ** ppFormat4Segments, GLYPH_ID ** ppGlyphId, uint16 * pusnIds ) { uint32 ulOffset; uint16 usSegCount; uint16 usBytesRead; uint32 ulBytesRead; int16 errCode; CMAP_SUBHEADER_GEN CmapSubHeader; /* find Format4 part of 'cmap' table */ *ppFormat4Segments = NULL; /* in case of error */ *ppGlyphId = NULL; *pusnIds = 0; ulOffset = FindCmapSubtable( pInputBufferInfo, usPlatform, usEncoding, pusFoundEncoding ); if ( ulOffset == 0 ) return( ERR_FORMAT ); if ((errCode = ReadCmapLength( pInputBufferInfo, &CmapSubHeader, ulOffset, &usBytesRead)) != NO_ERROR) return errCode; if (CmapSubHeader.format != FORMAT4_CMAP_FORMAT) return( ERR_FORMAT ); /* OK, it really is format 4, read the whole thing */ if ((errCode = ReadGeneric( pInputBufferInfo, (uint8 *) pCmapFormat4, SIZEOF_CMAP_FORMAT4, CMAP_FORMAT4_CONTROL, ulOffset, &usBytesRead )) != NO_ERROR) return(errCode); usSegCount = pCmapFormat4->segCountX2 / 2; /* read variable length part */ ulOffset += usBytesRead; if ((errCode = ReadAllocCmapFormat4Segs( pInputBufferInfo, usSegCount, ppFormat4Segments, ulOffset, &ulBytesRead )) != NO_ERROR) return(errCode); if ( ulBytesRead == 0) /* 0 could mean okey dokey */ return( NO_ERROR ); ulOffset += ulBytesRead; if ((errCode = ReadAllocCmapFormat4Ids( pInputBufferInfo, usSegCount, *ppFormat4Segments, ppGlyphId, pusnIds, ulOffset, &ulBytesRead )) != NO_ERROR) { FreeCmapFormat4( *ppFormat4Segments, *ppGlyphId ); *ppFormat4Segments = NULL; *ppGlyphId = NULL; *pusnIds = 0; return( errCode ); } return( NO_ERROR ); } /* ReadAllocCmapFormat4() */ /* ---------------------------------------------------------------------- */ void FreeCmapFormat6( uint16 * glyphIndexArray) { Mem_Free( glyphIndexArray ); } /* ---------------------------------------------------------------------- */ int16 ReadAllocCmapFormat6( TTFACC_FILEBUFFERINFO * pInputBufferInfo, CONST uint16 usPlatform, CONST uint16 usEncoding, uint16 *pusFoundEncoding, CMAP_FORMAT6 * pCmap, uint16 ** glyphIndexArray) { uint32 ulOffset; uint16 usBytesRead; uint32 ulBytesRead; int16 errCode; /* locate the cmap subtable */ ulOffset = FindCmapSubtable( pInputBufferInfo, usPlatform, usEncoding, pusFoundEncoding ); if ( ulOffset == 0 ) return( ERR_FORMAT ); /* Read cmap table */ if ((errCode = ReadGeneric( pInputBufferInfo, (uint8 *) pCmap, SIZEOF_CMAP_FORMAT6, CMAP_FORMAT6_CONTROL, ulOffset, &usBytesRead)) != NO_ERROR) return (errCode); if (pCmap->format != FORMAT6_CMAP_FORMAT) return( ERR_FORMAT ); *glyphIndexArray = (uint16 *)Mem_Alloc( pCmap->entryCount * sizeof( uint16 )); if ( *glyphIndexArray == NULL ) return( ERR_MEM ); if ((errCode = ReadGenericRepeat( pInputBufferInfo, (uint8 *) *glyphIndexArray, WORD_CONTROL, ulOffset + usBytesRead, &ulBytesRead, pCmap->entryCount, sizeof(uint16))) != NO_ERROR) { Mem_Free(*glyphIndexArray); *glyphIndexArray = NULL; return(errCode); } return( NO_ERROR ); } /* ---------------------------------------------------------------------- */ int16 ReadCmapFormat0( TTFACC_FILEBUFFERINFO * pInputBufferInfo, CONST uint16 usPlatform, CONST uint16 usEncoding, uint16 *pusFoundEncoding, CMAP_FORMAT0 *pCmap) { uint32 ulOffset; uint16 usBytesRead; uint32 ulBytesRead; int16 errCode; /* locate the cmap subtable */ ulOffset = FindCmapSubtable( pInputBufferInfo, usPlatform, usEncoding, pusFoundEncoding ); if ( ulOffset == 0L ) return( ERR_FORMAT ); /* Read cmap table */ if ((errCode = ReadGeneric( pInputBufferInfo, (uint8 *) pCmap, SIZEOF_CMAP_FORMAT0, CMAP_FORMAT0_CONTROL, ulOffset, &usBytesRead)) != NO_ERROR) return (errCode); if (pCmap->format != FORMAT0_CMAP_FORMAT) return( ERR_FORMAT ); if ((errCode = ReadGenericRepeat( pInputBufferInfo, (uint8 *) &(pCmap->glyphIndexArray), BYTE_CONTROL, ulOffset + usBytesRead, &ulBytesRead, CMAP_FORMAT0_ARRAYCOUNT, sizeof(uint8))) != NO_ERROR) return(errCode); return( NO_ERROR ); } /* ---------------------------------------------------------------------- */ int16 ReadAllocCmapFormat12( TTFACC_FILEBUFFERINFO * pInputBufferInfo, uint32 ulSubOffset, CMAP_FORMAT12 * pCmapFormat12, FORMAT12_GROUPS ** ppFormat12Groups ) { uint32 ulOffset; uint32 ulGroups; uint32 i; uint16 usBytesRead; int16 errCode; ulOffset = ulSubOffset; *ppFormat12Groups = NULL; /* in case of error */ if ((errCode = ReadGeneric( pInputBufferInfo, (uint8 *) pCmapFormat12, SIZEOF_CMAP_FORMAT12, CMAP_FORMAT12_CONTROL, ulOffset, &usBytesRead )) != NO_ERROR) return(errCode); ulOffset += usBytesRead; /* increment */ ulGroups = pCmapFormat12->nGroups; /* allocate mem for the groups */ if (ulGroups > (0xFFFFFFFF / SIZEOF_FORMAT12_GROUPS)) { //Font is obviously broken. ulGroups * SIZEOF_FORMAT12_GROUPS should fit into font table. return ERR_MEM; } *ppFormat12Groups = (FORMAT12_GROUPS *)Mem_Alloc( ulGroups * SIZEOF_FORMAT12_GROUPS); if ( *ppFormat12Groups == NULL ) return( ERR_MEM ); /* read them */ for ( i = 0; i < ulGroups; i++ ) { if ((errCode = ReadGeneric( pInputBufferInfo, (uint8 *) &((*ppFormat12Groups)[i]), SIZEOF_FORMAT12_GROUPS, FORMAT12_GROUPS_CONTROL, ulOffset, &usBytesRead )) != NO_ERROR) { Mem_Free( *ppFormat12Groups); *ppFormat12Groups = NULL; return(errCode); } ulOffset += usBytesRead; } return( NO_ERROR ); } /* ReadAllocCmapFormat12() */ /* ---------------------------------------------------------------------- */ void FreeCmapFormat12Groups( FORMAT12_GROUPS *pFormat12Groups) { Mem_Free( pFormat12Groups ); } /* ---------------------------------------------------------------------- */ int16 GetGlyphHeader( TTFACC_FILEBUFFERINFO * pInputBufferInfo, uint16 GlyfIdx, uint16 usIdxToLocFmt, uint32 ulLocaOffset, uint32 ulGlyfOffset, GLYF_HEADER * pGlyfHeader, uint32 * pulOffset, uint16 * pusLength ) { uint16 usOffset; uint32 ulOffset; uint32 ulNextOffset; uint16 usNextOffset; uint16 usBytesRead; int16 errCode; /* determine location of glyph data */ if ( usIdxToLocFmt == SHORT_OFFSETS ) { ulLocaOffset += GlyfIdx * sizeof( uint16 ); if ((errCode = ReadWord( pInputBufferInfo, &usOffset, ulLocaOffset)) != NO_ERROR) return(errCode); if ((errCode = ReadWord( pInputBufferInfo, &usNextOffset, ulLocaOffset + sizeof(uint16) )) != NO_ERROR) return(errCode); ulOffset = usOffset * 2L; ulNextOffset = usNextOffset * 2L; } else { ulLocaOffset += GlyfIdx * sizeof( uint32 ); if ((errCode = ReadLong( pInputBufferInfo, &ulOffset, ulLocaOffset)) != NO_ERROR) return(errCode); if ((errCode = ReadLong( pInputBufferInfo, &ulNextOffset, ulLocaOffset + sizeof(uint32))) != NO_ERROR) return(errCode); } /* read glyph header, unless it's non-existent, in which case set GlyphHeader to null and return */ *pusLength = (uint16) (ulNextOffset - ulOffset); if ( *pusLength == 0 ) { memset( pGlyfHeader, 0, SIZEOF_GLYF_HEADER ); *pulOffset = ulGlyfOffset; return NO_ERROR; } *pulOffset = ulGlyfOffset + ulOffset; return ReadGeneric( pInputBufferInfo, (uint8 *) pGlyfHeader, SIZEOF_GLYF_HEADER, GLYF_HEADER_CONTROL, ulGlyfOffset + ulOffset, &usBytesRead ); } /* GetGlyphHeader() */ /* ---------------------------------------------------------------------- */ /* Recursive!! */ /* It is possible that this function could run out of stack */ /* if the font defines a VERY deep component tree. */ /* ---------------------------------------------------------------------- */ int16 GetComponentGlyphList( TTFACC_FILEBUFFERINFO * pInputBufferInfo, uint16 usCompositeGlyphIdx, uint16 * pusnGlyphs, uint16 * ausGlyphIdxs, uint16 cMaxGlyphs, /* number of elements allocated in ausGlyphIdx array */ uint16 *pusnComponentDepth, uint16 usLevelValue, /* level of recursion we are at */ uint16 usIdxToLocFmt, uint32 ulLocaOffset, uint32 ulGlyfOffset) { uint16 usFlags; uint16 usComponentGlyphIdx; uint32 ulCrntOffset; GLYF_HEADER GlyfHeader; uint32 ulOffset; uint16 usLength; uint16 usnGlyphs; int16 errCode; /* check if this is a composite glyph */ *pusnGlyphs = 0; /* number of glyphs at this level and below */ if ((errCode = GetGlyphHeader( pInputBufferInfo, usCompositeGlyphIdx, usIdxToLocFmt, ulLocaOffset, ulGlyfOffset, &GlyfHeader, &ulOffset, &usLength )) != NO_ERROR) return(errCode); if (*pusnComponentDepth < usLevelValue) *pusnComponentDepth = usLevelValue; /* keep track of this */ if ( GlyfHeader.numberOfContours >= 0 ) return NO_ERROR; /* this is not a composite, just a glyph */ /* move to beginning of composite glyph description */ ulCrntOffset = ulOffset + GetGenericSize( GLYF_HEADER_CONTROL ); /* read composite glyph components, adding each component's reference */ do { if (*pusnGlyphs >= cMaxGlyphs) /* cannot do. the maxp table lied to us about maxdepth or maxelements! */ return ERR_INVALID_MAXP; /* read flag word and glyph component */ if ((errCode = ReadWord( pInputBufferInfo, &usFlags, ulCrntOffset)) != NO_ERROR) return(errCode); ulCrntOffset += sizeof( uint16 ); if ((errCode = ReadWord( pInputBufferInfo, &usComponentGlyphIdx, ulCrntOffset)) != NO_ERROR) return(errCode); ulCrntOffset += sizeof( uint16 ); ausGlyphIdxs[ *pusnGlyphs ] = usComponentGlyphIdx; (*pusnGlyphs)++; /* navigate through rest of entry to get to next glyph component */ if ( usFlags & ARG_1_AND_2_ARE_WORDS ) ulCrntOffset += 2 * sizeof( uint16 ); else ulCrntOffset += sizeof( uint16 ); if ( usFlags & WE_HAVE_A_SCALE ) ulCrntOffset += sizeof( uint16 ); else if ( usFlags & WE_HAVE_AN_X_AND_Y_SCALE ) ulCrntOffset += 2 * sizeof( uint16 ); else if ( usFlags & WE_HAVE_A_TWO_BY_TWO ) ulCrntOffset += 4 * sizeof( uint16 ); /* now deal with any components of this component */ if ((errCode = GetComponentGlyphList(pInputBufferInfo, usComponentGlyphIdx, &usnGlyphs, &(ausGlyphIdxs[*pusnGlyphs]), (uint16) (cMaxGlyphs - *pusnGlyphs), pusnComponentDepth, (uint16) (usLevelValue + 1), usIdxToLocFmt, ulLocaOffset, ulGlyfOffset)) != NO_ERROR) return(errCode); if (usnGlyphs > 0) *pusnGlyphs = (uint16)(*pusnGlyphs + usnGlyphs); /* increment count by number of sub components */ } while ( usFlags & MORE_COMPONENTS); return(NO_ERROR); } /* GetComponentGlyphList() */ /* ------------------------------------------------------------------- */ /* support for Cmap Modifying and merging */ /* ------------------------------------------------------------------- */ PRIVATE int CRTCB AscendingCodeCompare( CONST void *arg1, CONST void *arg2 ) { if (((PCHAR_GLYPH_MAP_LIST)(arg1))->usCharCode == ((PCHAR_GLYPH_MAP_LIST)(arg2))->usCharCode) /* they're the same */ return 0; if (((PCHAR_GLYPH_MAP_LIST)(arg1))->usCharCode < ((PCHAR_GLYPH_MAP_LIST)(arg2))->usCharCode) return -1; return 1; } /* ------------------------------------------------------------------- */ PRIVATE void SortCodeList( PCHAR_GLYPH_MAP_LIST pCharGlyphMapList, uint16 *pusnCharMapListLength ) { uint16 i, j; /* sort list of character codes to keep using an insertion sort */ if (pCharGlyphMapList == NULL || *pusnCharMapListLength == 0) return; qsort(pCharGlyphMapList, *pusnCharMapListLength, sizeof(*pCharGlyphMapList), AscendingCodeCompare); /* now remove duplicates */ for (i = 0, j = 1 ; j < *pusnCharMapListLength ; ++j) { if (pCharGlyphMapList[i].usCharCode != pCharGlyphMapList[j].usCharCode) /* not a duplicate, keep it */ { if (j > i+1) /* we have removed one */ pCharGlyphMapList[i+1] = pCharGlyphMapList[j]; /* copy it down */ ++i; /* go to next one */ } /* otherwise, we stay where we are on i, and go look at the next j */ } *pusnCharMapListLength = i+1; /* the last good i value */ } /* ------------------------------------------------------------------- */ PRIVATE int CRTCB AscendingCodeCompareEx( CONST void *arg1, CONST void *arg2 ) { if (((PCHAR_GLYPH_MAP_LIST_EX)(arg1))->ulCharCode == ((PCHAR_GLYPH_MAP_LIST_EX)(arg2))->ulCharCode) /* they're the same */ return 0; if (((PCHAR_GLYPH_MAP_LIST_EX)(arg1))->ulCharCode < ((PCHAR_GLYPH_MAP_LIST_EX)(arg2))->ulCharCode) return -1; return 1; } PRIVATE void SortCodeListEx( PCHAR_GLYPH_MAP_LIST_EX pCharGlyphMapList, uint32 *pulnCharMapListLength ) { uint32 i, j; /* sort list of character codes to keep using an insertion sort */ if (pCharGlyphMapList == NULL || *pulnCharMapListLength == 0) return; qsort(pCharGlyphMapList, *pulnCharMapListLength, sizeof(*pCharGlyphMapList), AscendingCodeCompareEx); /* now remove duplicates */ for (i = 0, j = 1 ; j < *pulnCharMapListLength ; ++j) { if (pCharGlyphMapList[i].ulCharCode != pCharGlyphMapList[j].ulCharCode) /* not a duplicate, keep it */ { if (j > i+1) /* we have removed one */ pCharGlyphMapList[i+1] = pCharGlyphMapList[j]; /* copy it down */ ++i; /* go to next one */ } /* otherwise, we stay where we are on i, and go look at the next j */ } *pulnCharMapListLength = i+1; /* the last good i value */ } /* ------------------------------------------------------------------- */ void FreeFormat4CharCodes(PCHAR_GLYPH_MAP_LIST pusCharCodeList) { Mem_Free(pusCharCodeList); } /* ---------------------------------------------------------------------- */ /* create a list of character codes to keep, based on the glyph list */ int16 ReadAllocFormat4CharGlyphMapList(TTFACC_FILEBUFFERINFO * pInputBufferInfo, CONST uint16 usPlatform, CONST uint16 usEncoding, __in_ecount(usGlyphCount) uint8 *puchKeepGlyphList, /* glyphs to keep - boolean */ uint16 usGlyphCount, /* count of puchKeepGlyphList */ PCHAR_GLYPH_MAP_LIST *ppCharGlyphMapList, uint16 *pusnCharGlyphMapListCount) { uint16 usSegCount; FORMAT4_SEGMENTS * pFormat4Segments; GLYPH_ID * pFormat4GlyphIdArray; uint16 usnFormat4Glyphs; /* count of elements in pFormat4GlyphIdArray */ CMAP_FORMAT4 CmapFormat4; uint16 i; uint16 usCharCodeValue; uint16 usCharCodeCount; uint16 usCharCodeIndex; uint16 usGlyphIndex; uint16 usFoundEncoding; int32 sIDIdx; int16 errCode = NO_ERROR; /* allocate memory for variable length part of table */ *ppCharGlyphMapList = NULL; *pusnCharGlyphMapListCount = 0; errCode = ReadAllocCmapFormat4( pInputBufferInfo, usPlatform, usEncoding, &usFoundEncoding, &CmapFormat4, &pFormat4Segments, &pFormat4GlyphIdArray, &usnFormat4Glyphs); if (errCode != NO_ERROR) return errCode; usSegCount = CmapFormat4.segCountX2 / 2; /* zip through cmap entries,counting the char code entries */ usCharCodeCount = 0; for ( i = 0; i < usSegCount; i++ ) { if (pFormat4Segments[ i ].endCount == INVALID_CHAR_CODE) continue; if (pFormat4Segments[ i ].endCount < pFormat4Segments[ i ].startCount) continue; usCharCodeCount += (pFormat4Segments[ i ].endCount - pFormat4Segments[ i ].startCount + 1); } *ppCharGlyphMapList = (PCHAR_GLYPH_MAP_LIST)Mem_Alloc(usCharCodeCount * sizeof(**ppCharGlyphMapList)); if (*ppCharGlyphMapList == NULL) { FreeCmapFormat4(pFormat4Segments, pFormat4GlyphIdArray); return ERR_MEM; } *pusnCharGlyphMapListCount = usCharCodeCount; usCharCodeIndex = 0; for ( i = 0; i < usSegCount; i++ ) { if (pFormat4Segments[ i ].endCount == INVALID_CHAR_CODE) continue; if (pFormat4Segments[ i ].endCount < pFormat4Segments[ i ].startCount) continue; #pragma warning (suppress : 22019) /* reviewed - safe to suppress this warning */ for (usCharCodeValue = pFormat4Segments[ i ].startCount; usCharCodeValue <= pFormat4Segments[ i ].endCount; ++usCharCodeValue) { /* grab this from GetGlyphIndex to speed things up */ if ( pFormat4Segments[ i ].idRangeOffset == 0 ) usGlyphIndex = usCharCodeValue + pFormat4Segments[ i ].idDelta; else { sIDIdx = (uint16) i - (uint16) usSegCount; sIDIdx += (uint16) (pFormat4Segments[i].idRangeOffset / 2) + usCharCodeValue - pFormat4Segments[i].startCount; /* check bounds */ if (sIDIdx < usnFormat4Glyphs) { usGlyphIndex = pFormat4GlyphIdArray[ sIDIdx ]; if (usGlyphIndex) /* Only add in idDelta if we've really got a glyph! */ usGlyphIndex = (uint16)(usGlyphIndex + pFormat4Segments[i].idDelta); } else { usGlyphIndex = INVALID_GLYPH_INDEX; } } /* check to see if this glyphIndex is supported */ /* usGlyphIndex = GetGlyphIdx( usCharCodeValue, pFormat4Segments, usSegCount, pFormat4GlyphIdArray ); */ if (usGlyphIndex != 0 && usGlyphIndex != INVALID_GLYPH_INDEX && usGlyphIndex < usGlyphCount) if (puchKeepGlyphList[ usGlyphIndex ]) { (*ppCharGlyphMapList)[usCharCodeIndex].usCharCode = usCharCodeValue; /* assign the Character code */ (*ppCharGlyphMapList)[usCharCodeIndex++].usGlyphIndex = usGlyphIndex; /* assign the GlyphIndex */ } } } *pusnCharGlyphMapListCount = usCharCodeIndex; FreeCmapFormat4(pFormat4Segments, pFormat4GlyphIdArray); SortCodeList(*ppCharGlyphMapList, pusnCharGlyphMapListCount); return( errCode ); } /* ------------------------------------------------------------------- */ void FreeFormat12CharCodes(PCHAR_GLYPH_MAP_LIST_EX pulCharCodeList) { Mem_Free(pulCharCodeList); } /* ---------------------------------------------------------------------- */ /* create a list of character codes to keep, based on the glyph list */ int16 ReadAllocFormat12CharGlyphMapList(TTFACC_FILEBUFFERINFO * pInputBufferInfo, uint32 ulOffset, uint8 *puchKeepGlyphList, /* glyphs to keep - boolean */ uint16 usGlyphCount, /* count of puchKeepGlyphList */ PCHAR_GLYPH_MAP_LIST_EX *ppCharGlyphMapList, uint32 *pulnCharGlyphMapListCount) { uint32 ulnGroups; uint32 ulCharCodeCount; uint32 ulCharCodeValue; uint32 ulCharCodeIndex; uint32 ulGlyphIndex; uint16 usGlyphIndex; FORMAT12_GROUPS * pFormat12Groups; CMAP_FORMAT12 CmapFormat12; uint32 i; int16 errCode = NO_ERROR; /* allocate memory for variable length part of table */ *ppCharGlyphMapList = NULL; *pulnCharGlyphMapListCount = 0; errCode = ReadAllocCmapFormat12( pInputBufferInfo, ulOffset, &CmapFormat12, &pFormat12Groups); if (errCode != NO_ERROR) return errCode; ulnGroups = CmapFormat12.nGroups; /* zip through cmap entries,counting the char code entries */ ulCharCodeCount = 0; for ( i = 0; i < ulnGroups; i++ ) { if (pFormat12Groups[ i ].endCharCode < pFormat12Groups[ i ].startCharCode) continue; ulCharCodeCount += (pFormat12Groups[ i ].endCharCode - pFormat12Groups[ i ].startCharCode + 1); } *ppCharGlyphMapList = (PCHAR_GLYPH_MAP_LIST_EX)Mem_Alloc(ulCharCodeCount * sizeof(**ppCharGlyphMapList)); if (*ppCharGlyphMapList == NULL) { FreeCmapFormat12Groups( pFormat12Groups ); return ERR_MEM; } *pulnCharGlyphMapListCount = ulCharCodeCount; ulCharCodeIndex = 0; for ( i = 0; i < ulnGroups; i++ ) { if (pFormat12Groups[ i ].endCharCode < pFormat12Groups[ i ].startCharCode) continue; for (ulCharCodeValue = pFormat12Groups[ i ].startCharCode; ulCharCodeValue <= pFormat12Groups[ i ].endCharCode; ++ulCharCodeValue) { ulGlyphIndex = pFormat12Groups[ i ].startGlyphCode + (ulCharCodeValue - pFormat12Groups[ i ].startCharCode); usGlyphIndex = (uint16)ulGlyphIndex; if (usGlyphIndex != 0 && ulGlyphIndex < (uint32)usGlyphCount && puchKeepGlyphList[usGlyphIndex]) { ((*ppCharGlyphMapList)[ulCharCodeIndex]).ulCharCode = ulCharCodeValue; /* assign the Character code */ ((*ppCharGlyphMapList)[ulCharCodeIndex]).ulGlyphIndex = ulGlyphIndex; /* assign the GlyphIndex */ ulCharCodeIndex++; } } } *pulnCharGlyphMapListCount = ulCharCodeIndex; FreeCmapFormat12Groups( pFormat12Groups ); SortCodeListEx(*ppCharGlyphMapList, pulnCharGlyphMapListCount); return( errCode ); } /* ------------------------------------------------------------------- */ PRIVATE uint32 Format4CmapLength( uint16 usnSegments, uint16 usnGlyphIdxs ) { return( GetGenericSize( CMAP_FORMAT4_CONTROL ) + usnSegments * GetGenericSize( FORMAT4_SEGMENTS_CONTROL ) + usnGlyphIdxs * sizeof(int16) + sizeof( uint16 )); } /* ------------------------------------------------------------------- */ /* this routine computes new values for the format 4 cmap table based on a list of character codes and corresponding glyph indexes. */ /* ------------------------------------------------------------------- */ void ComputeFormat4CmapData( CMAP_FORMAT4 * pCmapFormat4, /* to be set by this routine */ FORMAT4_SEGMENTS * NewFormat4Segments, /* to be set by this routine */ uint16 * pusnSegment, /* count of NewFormat4Segments - returned */ GLYPH_ID * NewFormat4GlyphIdArray, /* to be set by this routine */ uint16 * psnFormat4GlyphIdArray, /* count of NewFormat4GlyphIdArray - returned */ PCHAR_GLYPH_MAP_LIST pCharGlyphMapList, /* input - map of CharCode to GlyphIndex */ uint16 usnCharGlyphMapListCount) /* input */ { uint16 i; uint16 j; uint16 usFormat4GlyphIdArrayIndex; BOOL bUseIdDelta; uint16 usStartIndex; uint16 usEndIndex; /* compute new format 4 data */ i = 0; *pusnSegment = 0; *psnFormat4GlyphIdArray = 0; while ( i < usnCharGlyphMapListCount ) { /* find the number of consecutive entries */ usStartIndex = i; while ( i < usnCharGlyphMapListCount-1 && pCharGlyphMapList[ i ].usCharCode + 1 == pCharGlyphMapList[ i+1 ].usCharCode ) i++; usEndIndex = i; i++; /* determine whether to use idDelta or idRangeOffset representation. Default is to use idDelta if all glyphId's are also consecutive because that is more space-efficient. A second pass is made through the data later to compute idRangeOffset values. */ bUseIdDelta = TRUE; for ( j = usStartIndex; j < usEndIndex && bUseIdDelta; j++ ) { if ( pCharGlyphMapList[ j ].usGlyphIndex + 1 != pCharGlyphMapList[ j + 1 ].usGlyphIndex ) bUseIdDelta = FALSE; } /* save cmap data */ NewFormat4Segments[ *pusnSegment ].startCount = pCharGlyphMapList[ usStartIndex ].usCharCode; NewFormat4Segments[ *pusnSegment ].endCount = pCharGlyphMapList[ usEndIndex ].usCharCode; if ( bUseIdDelta ) { NewFormat4Segments[ *pusnSegment ].idDelta = pCharGlyphMapList[ usStartIndex ].usGlyphIndex - pCharGlyphMapList[ usStartIndex ].usCharCode; NewFormat4Segments[ *pusnSegment ].idRangeOffset = FALSE; /* This is mis-used temporarily, but will be set below to the proper value */ } else { NewFormat4Segments[ *pusnSegment ].idDelta = 0; NewFormat4Segments[ *pusnSegment ].idRangeOffset = TRUE; /* This is mis-used temporarily, but will be set below to the proper value */ } (*pusnSegment)++; } /* make pass through data to compute idRangeOffset info. This is deferred to this point because we need to know the number of segments before we can compute the idRangeOffset entries. */ usFormat4GlyphIdArrayIndex = 0; for ( i = 0; i < *pusnSegment; i++ ) { if ( NewFormat4Segments[ i ].idRangeOffset == FALSE ) { /* We've done it all with sequential glyph ranges... */ usFormat4GlyphIdArrayIndex += NewFormat4Segments[ i ].endCount - NewFormat4Segments[ i ].startCount + 1; NewFormat4Segments[ i ].idRangeOffset = 0; } else /* Non-sequential glyph range: compute idRangeOffset for the segment */ { NewFormat4Segments[ i ].idRangeOffset = (*pusnSegment + 1 - i + *psnFormat4GlyphIdArray) * 2; /* insert glyph indices into the GlyphId array */ for ( j = NewFormat4Segments[ i ].startCount ; j <= NewFormat4Segments[ i ].endCount ; j++ ) NewFormat4GlyphIdArray[ (*psnFormat4GlyphIdArray)++ ] = pCharGlyphMapList[ usFormat4GlyphIdArrayIndex++ ].usGlyphIndex; } } /* add the final, required 0xFFFF entry */ NewFormat4Segments[ *pusnSegment ].idRangeOffset = 0; NewFormat4Segments[ *pusnSegment ].idDelta = 1; NewFormat4Segments[ *pusnSegment ].endCount = INVALID_CHAR_CODE; NewFormat4Segments[ *pusnSegment ].startCount = INVALID_CHAR_CODE; (*pusnSegment)++; /* modify format 4 header data and write out the data */ pCmapFormat4->format = FORMAT4_CMAP_FORMAT; pCmapFormat4->revision = 0; pCmapFormat4->length = (uint16) Format4CmapLength( *pusnSegment, *psnFormat4GlyphIdArray ); pCmapFormat4->segCountX2 = *pusnSegment * 2; pCmapFormat4->searchRange = 0x0001 << ( log2( *pusnSegment ) + 1 ); pCmapFormat4->entrySelector = log2( (uint16)(pCmapFormat4->searchRange / 2) ); pCmapFormat4->rangeShift = 2 * *pusnSegment - pCmapFormat4->searchRange; } /* ------------------------------------------------------------------- */ /* this routine writes out the cmap data after it has been reconstructed around the missing glyphs. It assumes that there is already enough space allocated to hold the new format 4 subtable. */ /* ------------------------------------------------------------------- */ int16 WriteOutFormat4CmapData( TTFACC_FILEBUFFERINFO * pOutputBufferInfo, CMAP_FORMAT4 *pCmapFormat4, /* created by ComputeNewFormat4Data */ FORMAT4_SEGMENTS * NewFormat4Segments, /* created by ComputeNewFormat4Data */ GLYPH_ID * NewFormat4GlyphIdArray, /* created by ComputeNewFormat4Data */ uint16 usnSegment, /* number of NewFormat4Segments elements */ uint16 snFormat4GlyphIdArray, /* number of NewFormat4GlyphIdArray elements */ uint32 ulNewOffset, /* where to write the table */ uint32 *pulBytesWritten) /* number of bytes written to table */ { uint16 i; uint16 usBytesWritten; int16 errCode; uint32 ulOffset; ulOffset = ulNewOffset; if ((errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) pCmapFormat4, SIZEOF_CMAP_FORMAT4, CMAP_FORMAT4_CONTROL, ulOffset, &usBytesWritten )) != NO_ERROR) return errCode; ulOffset += usBytesWritten; /* write out modified cmap arrays */ for ( i = 0; i < usnSegment; i++ ) if ((errCode = WriteWord( pOutputBufferInfo, NewFormat4Segments[ i ].endCount, ulOffset + (i * sizeof(uint16)) )) != NO_ERROR) return errCode; ulOffset += usnSegment*sizeof(uint16); if ((errCode = WriteWord( pOutputBufferInfo, (uint16) 0, ulOffset )) != NO_ERROR) /* pad word */ return errCode; ulOffset += sizeof(uint16); for ( i = 0; i < usnSegment; i++ ) if ((errCode = WriteWord( pOutputBufferInfo, NewFormat4Segments[ i ].startCount, ulOffset + (i * sizeof(uint16)) )) != NO_ERROR) return errCode; ulOffset += usnSegment*sizeof(uint16); for ( i = 0; i < usnSegment; i++ ) if ((errCode = WriteWord( pOutputBufferInfo, NewFormat4Segments[ i ].idDelta, ulOffset + (i * sizeof(uint16)) )) != NO_ERROR) return errCode; ulOffset += usnSegment*sizeof(uint16); for ( i = 0; i < usnSegment; i++ ) if ((errCode = WriteWord( pOutputBufferInfo, NewFormat4Segments[ i ].idRangeOffset, ulOffset + (i * sizeof(uint16)) )) != NO_ERROR) return errCode; ulOffset += usnSegment*sizeof(uint16); /* write out glyph id array */ for ( i = 0; i < snFormat4GlyphIdArray; i++ ) if ((errCode = WriteWord( pOutputBufferInfo, NewFormat4GlyphIdArray[ i ], ulOffset + (i * sizeof(uint16)) )) != NO_ERROR) return errCode; ulOffset += snFormat4GlyphIdArray * sizeof(uint16); *pulBytesWritten = ulOffset - ulNewOffset; return NO_ERROR; } /* ------------------------------------------------------------------- */ /* this routine computes new values for the format 12 cmap table based on a list of character codes and corresponding glyph indexes. */ /* ------------------------------------------------------------------- */ void ComputeFormat12CmapData( CMAP_FORMAT12 * pCmapFormat12, /* to be set by this routine */ FORMAT12_GROUPS * NewFormat12Groups, /* to be set by this routine */ uint32 * pulnGroups, /* count of NewFormat12Groups - returned */ PCHAR_GLYPH_MAP_LIST_EX pCharGlyphMapList, /* input - map of CharCode to GlyphIndex */ uint32 ulnCharGlyphMapListCount) /* input */ { uint32 i; uint32 ulStartIndex; uint32 ulEndIndex; /* compute new format 12 data */ i = 0; *pulnGroups = 0; while ( i < ulnCharGlyphMapListCount ) { /* find the number of consecutive entries */ ulStartIndex = i; while ( i < ulnCharGlyphMapListCount-1 && pCharGlyphMapList[ i ].ulCharCode + 1 == pCharGlyphMapList[ i+1 ].ulCharCode && pCharGlyphMapList[ i ].ulGlyphIndex+1 == pCharGlyphMapList[ i+1 ].ulGlyphIndex ) i++; ulEndIndex = i; i++; /* Set this group and move on to next */ NewFormat12Groups[*pulnGroups].startCharCode = pCharGlyphMapList[ulStartIndex].ulCharCode; NewFormat12Groups[*pulnGroups].endCharCode = pCharGlyphMapList[ulEndIndex].ulCharCode; NewFormat12Groups[*pulnGroups].startGlyphCode = pCharGlyphMapList[ulStartIndex].ulGlyphIndex; (*pulnGroups)++; } /* modify format 12 header data */ pCmapFormat12->format = FORMAT12_CMAP_FORMAT; pCmapFormat12->revision = 0; pCmapFormat12->length = GetGenericSize( CMAP_FORMAT12_CONTROL ) + (*pulnGroups) * GetGenericSize( FORMAT12_GROUPS_CONTROL ); pCmapFormat12->nGroups = *pulnGroups; } /* ------------------------------------------------------------------- */ /* this routine writes out the cmap data after it has been reconstructed around the missing glyphs. It assumes that there is already enough space allocated to hold the new format 12 subtable. */ /* ------------------------------------------------------------------- */ int16 WriteOutFormat12CmapData( TTFACC_FILEBUFFERINFO * pOutputBufferInfo, CMAP_FORMAT12 *pCmapFormat12, /* created by ComputeNewFormat12Data */ FORMAT12_GROUPS * NewFormat12Groups, /* created by ComputeNewFormat12Data */ uint32 ulnGroups, /* number of NewFormat12Groups elements */ uint32 ulNewOffset, /* where to write the table */ uint32 *pulBytesWritten) /* number of bytes written to table */ { uint32 i; uint16 usBytesWritten; int16 errCode; uint32 ulOffset; ulOffset = ulNewOffset; if ((errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) pCmapFormat12, SIZEOF_CMAP_FORMAT12, CMAP_FORMAT12_CONTROL, ulOffset, &usBytesWritten )) != NO_ERROR) return errCode; ulOffset += usBytesWritten; /* write out modified cmap arrays */ for ( i = 0; i < ulnGroups; i++ ) { if ((errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) &NewFormat12Groups[i], SIZEOF_FORMAT12_GROUPS, FORMAT12_GROUPS_CONTROL, ulOffset, &usBytesWritten )) != NO_ERROR) return errCode; ulOffset += usBytesWritten; } /* set number of bytes written */ *pulBytesWritten = ulOffset - ulNewOffset; return NO_ERROR; } /* ---------------------------------------------------------------------- */ /* This function will allocate memory and read into that memory an array of NAMERECORD structures. */ /* note this structure is defined in the .h file for this module, and is similar, but not identical */ /* to the NAME_RECORD structure as described in TTFF.H. The first 6 elements are the same, but extra */ /* data is needed for these functions. When this function returns NO_ERROR, the *ppNameRecordArray */ /* will point to the allocated array and the *pNameRecordCount value will be set to the number of */ /* records in the array. */ /* ---------------------------------------------------------------------- */ int16 ReadAllocNameRecords(TTFACC_FILEBUFFERINFO * pInputBufferInfo, PNAMERECORD *ppNameRecordArray, /* allocated by this function */ uint16 *pNameRecordCount, /* number of records in array */ CFP_ALLOCPROC lfpnAllocate, /* how to allocate array, and strings */ CFP_FREEPROC lfpnFree) /* how to free in case of error */ { NAME_HEADER NameHeader; int16 errCode; uint32 ulNameOffset; uint32 ulNameLength; uint32 ulOffset; uint16 usBytesRead; uint16 i; *ppNameRecordArray = NULL; *pNameRecordCount = 0; ulNameOffset = TTTableOffset( pInputBufferInfo, NAME_TAG ); if ( ulNameOffset == DIRECTORY_ERROR ) return ERR_MISSING_NAME; /* no table there */ ulNameLength = TTTableLength( pInputBufferInfo, NAME_TAG ); if ( ulNameLength == DIRECTORY_ERROR ) return ERR_INVALID_NAME; if ((errCode = ReadGeneric( pInputBufferInfo, (uint8 *) &NameHeader, SIZEOF_NAME_HEADER, NAME_HEADER_CONTROL, ulNameOffset, &usBytesRead )) != NO_ERROR) return errCode; ulOffset = ulNameOffset + usBytesRead; *ppNameRecordArray = (PNAMERECORD) lfpnAllocate(NameHeader.numNameRecords * sizeof(**ppNameRecordArray)); if (*ppNameRecordArray == NULL) return ERR_MEM; *pNameRecordCount = NameHeader.numNameRecords; for (i = 0; i < *pNameRecordCount; ++i) { /* This read into NAMERECORD instead of NAME_RECORD works because the first 6 elements are the same */ if ((errCode = ReadGeneric( pInputBufferInfo, (uint8 *) &((*ppNameRecordArray)[i]), SIZEOF_NAME_RECORD, NAME_RECORD_CONTROL, ulOffset, &usBytesRead )) != NO_ERROR) break; ulOffset += usBytesRead; if ((*ppNameRecordArray)[i].stringLength == INVALID_NAME_STRING_LENGTH) /* will get removed upon write */ continue; (*ppNameRecordArray)[i].pNameString = (char *)lfpnAllocate((*ppNameRecordArray)[i].stringLength); if ((*ppNameRecordArray)[i].pNameString == NULL) { errCode = ERR_MEM; break; } if ((errCode = ReadBytes( pInputBufferInfo, (uint8 *)((*ppNameRecordArray)[i].pNameString), ulNameOffset + NameHeader.offsetToStringStorage + (*ppNameRecordArray)[i].stringOffset, (*ppNameRecordArray)[i].stringLength)) != NO_ERROR) break; (*ppNameRecordArray)[i].pNewNameString = NULL; (*ppNameRecordArray)[i].bStringWritten = FALSE; (*ppNameRecordArray)[i].bDeleteString = FALSE; } if (errCode != NO_ERROR) /* need to free up allocated stuff */ { FreeNameRecords(*ppNameRecordArray, *pNameRecordCount, lfpnFree); *ppNameRecordArray = NULL; *pNameRecordCount = 0; } return errCode; } /* ---------------------------------------------------------------------- */ uint32 CalcMaxNameTableLength(PNAMERECORD pNameRecordArray, uint16 NameRecordCount) { uint16 i; uint32 ulNameTableLength= 0; uint16 ValidNameRecordCount = 0; if (pNameRecordArray == NULL || NameRecordCount == 0) return 0L; /* add in all the space for the strings */ for (i = 0; i < NameRecordCount; ++i) { if (pNameRecordArray[i].stringLength != INVALID_NAME_STRING_LENGTH) ++ValidNameRecordCount; ulNameTableLength += pNameRecordArray[i].stringLength; } /* now add in the array */ ulNameTableLength += (GetGenericSize(NAME_HEADER_CONTROL) + GetGenericSize(NAME_RECORD_CONTROL) * ValidNameRecordCount); return ulNameTableLength; } /* ---------------------------------------------------------------------- */ /* Local structure to be made into an array with a 1 to 1 correspondence with the NameRecordArray */ /* this array will be used to sort the records by string length, and then later by NameRecordIndex */ /* without actually changing the order of the NameRecordArray elements */ /* ---------------------------------------------------------------------- */ typedef struct namerecordstrings NAMERECORDSTRINGS; struct namerecordstrings { uint16 usNameRecordIndex; /* index into name record array */ uint16 usNameRecordStringLength; /* length of that string */ uint16 usNameRecordStringIndex; /* index of Name record who's string this should use*/ uint16 usNameRecordStringCharIndex; /* index into string referenced by StringIndex of where this string starts */ }; /* ---------------------------------------------------------------------- */ PRIVATE int CRTCB DescendingStringLengthCompare( CONST void *arg1, CONST void *arg2 ) { if (((NAMERECORDSTRINGS *)(arg1))->usNameRecordStringLength == ((NAMERECORDSTRINGS *)(arg2))->usNameRecordStringLength) /* they're the same */ return 0; if (((NAMERECORDSTRINGS *)(arg1))->usNameRecordStringLength < ((NAMERECORDSTRINGS *)(arg2))->usNameRecordStringLength) return 1; /* reversed because we want descending order */ return -1; } /* ---------------------------------------------------------------------- */ PRIVATE int CRTCB AscendingRecordIndexCompare( CONST void *arg1, CONST void *arg2 ) { if (((NAMERECORDSTRINGS *)(arg1))->usNameRecordIndex == ((NAMERECORDSTRINGS *)(arg2))->usNameRecordIndex) /* they're the same */ return 0; if (((NAMERECORDSTRINGS *)(arg1))->usNameRecordIndex < ((NAMERECORDSTRINGS *)(arg2))->usNameRecordIndex) return -1; return 1; } /* ---------------------------------------------------------------------- */ /* sort largest first */ PRIVATE void SortNameRecordsByStringLength(NAMERECORDSTRINGS *pNameRecordStrings,uint16 NameRecordCount) { if (pNameRecordStrings == NULL || NameRecordCount == 0) return; qsort (pNameRecordStrings, NameRecordCount, sizeof(*pNameRecordStrings),DescendingStringLengthCompare); } /* ---------------------------------------------------------------------- */ /* sorts by index */ PRIVATE void SortNameRecordsByNameRecordIndex(NAMERECORDSTRINGS *pNameRecordStrings,uint16 NameRecordCount) { if (pNameRecordStrings == NULL || NameRecordCount == 0) return; qsort (pNameRecordStrings, NameRecordCount, sizeof(*pNameRecordStrings),AscendingRecordIndexCompare); } /* ---------------------------------------------------------------------- */ /* sorts by platformID, then encodingID, then languageID, then nameID */ PRIVATE int CRTCB AscendingNameRecordCompare( CONST void *arg1, CONST void *arg2 ) { if (((PNAMERECORD)(arg1))->platformID == ((PNAMERECORD)(arg2))->platformID) /* they're the same */ { if (((PNAMERECORD)(arg1))->encodingID == ((PNAMERECORD)(arg2))->encodingID) /* they're the same */ { if (((PNAMERECORD)(arg1))->languageID == ((PNAMERECORD)(arg2))->languageID) /* they're the same */ { if (((PNAMERECORD)(arg1))->nameID == ((PNAMERECORD)(arg2))->nameID) /* they're the same */ { return 0; } if (((PNAMERECORD)(arg1))->nameID < ((PNAMERECORD)(arg2))->nameID) /* they're the same */ return -1; return 1; } if (((PNAMERECORD)(arg1))->languageID < ((PNAMERECORD)(arg2))->languageID) /* they're the same */ return -1; return 1; } if (((PNAMERECORD)(arg1))->encodingID < ((PNAMERECORD)(arg2))->encodingID) /* they're the same */ return -1; return 1; } if (((PNAMERECORD)(arg1))->platformID < ((PNAMERECORD)(arg2))->platformID) /* they're the same */ return -1; return 1; } /* ---------------------------------------------------------------------- */ /* This module will take as input the pNameRecordArray that has been created by ReadAllocNameRecords and possible modified */ /* by the client, and write the records out the the OutputBuffer in and optimized fashion. That is if there is possible */ /* sharing of string data among NameRecords, it is written that way. */ /* note, this function is not the inverse of ReadAllocNameRecords because it writes the name table directly to the buffer at */ /* offset 0. It is up to the client to place that data in a TrueType file and update the directory that points to it */ /* To get a maximum size for the buffer to pass in, call CalcMaxNameTableLength. This will return the size of an unoptimized */ /* name table. */ /* ---------------------------------------------------------------------- */ int16 WriteNameRecords(TTFACC_FILEBUFFERINFO * pOutputBufferInfo, /* bufferInfo for a NAME table, not a TrueType file */ PNAMERECORD pNameRecordArray, uint16 NameRecordCount, BOOL bDeleteStrings, /* if true don't write out strings marked for deletion. if false, write out all strings */ BOOL bOptimize, /* lcp 4/8/97, if True optimize the string storage for smallest space */ uint32 *pulBytesWritten) { NAME_HEADER NameHeader; NAMERECORDSTRINGS *pNameRecordStrings; /* structure array to allow sorting by string length */ int16 errCode = NO_ERROR; uint32 ulNameOffset;/* an absolute offset from beginning of buffer */ uint16 usStringsOffset; /* a relative offset from beginning of the name table */ uint32 ulOffset; /* current absolute offset used for writing out Name_Records */ uint16 usBytesWritten; uint16 i,j,k; uint16 index; uint16 BaseIndex; uint16 ValidNameRecordCount = 0; char *pStr1, *pStr2; /* temps to point to either new or old string from PNAMERECORD Array */ *pulBytesWritten = 0; if (pNameRecordArray == NULL || NameRecordCount == 0) return ERR_GENERIC; /* before we start this, need to sort the actual NameRecords by platformID etc */ qsort (pNameRecordArray, NameRecordCount, sizeof(*pNameRecordArray),AscendingNameRecordCompare); ulNameOffset = 0L; NameHeader.formatSelector = 0; ulOffset = ulNameOffset + GetGenericSize(NAME_HEADER_CONTROL); /* first create the NameRecordStrings array to sort */ pNameRecordStrings = (NAMERECORDSTRINGS *)Mem_Alloc(NameRecordCount * sizeof(*pNameRecordStrings)); if (pNameRecordStrings == NULL) return ERR_MEM; for (i = ValidNameRecordCount = 0; i < NameRecordCount; ++i) { if (bDeleteStrings && pNameRecordArray[i].bDeleteString) continue; pNameRecordStrings[ValidNameRecordCount].usNameRecordIndex = i; pNameRecordStrings[ValidNameRecordCount].usNameRecordStringLength = pNameRecordArray[i].stringLength; pNameRecordStrings[ValidNameRecordCount].usNameRecordStringIndex = i; pNameRecordStrings[ValidNameRecordCount].usNameRecordStringCharIndex = 0; pNameRecordArray[i].stringOffset = 0; /* initialize for the Write activity below */ ++ValidNameRecordCount; } usStringsOffset = 0; NameHeader.offsetToStringStorage = GetGenericSize(NAME_HEADER_CONTROL) + (GetGenericSize(NAME_RECORD_CONTROL)*ValidNameRecordCount); if (bOptimize) { uint16 maxCharIndex; /* need to sort these babies by length */ SortNameRecordsByStringLength(pNameRecordStrings,ValidNameRecordCount); /* now look for identical lengths, and compare, if the same, mark them */ for (i = 1; i < ValidNameRecordCount; ++i) { if ((pStr1 = pNameRecordArray[pNameRecordStrings[i].usNameRecordIndex].pNewNameString) == NULL) /* if we're just using the old string */ pStr1 = pNameRecordArray[pNameRecordStrings[i].usNameRecordIndex].pNameString; if ((pStr2 = pNameRecordArray[pNameRecordStrings[i-1].usNameRecordIndex].pNewNameString) == NULL) pStr2 = pNameRecordArray[pNameRecordStrings[i-1].usNameRecordIndex].pNameString; if ( (pNameRecordStrings[i].usNameRecordStringLength == pNameRecordStrings[i-1].usNameRecordStringLength) && (memcmp(pStr1, pStr2,pNameRecordStrings[i].usNameRecordStringLength) == 0)) /* they are the same */ { pNameRecordStrings[i].usNameRecordStringIndex = pNameRecordStrings[i-1].usNameRecordStringIndex; /* set the index the same */ pNameRecordStrings[i].usNameRecordStringCharIndex = pNameRecordStrings[i-1].usNameRecordStringCharIndex; } else /* i string is shorter (or the same), because of sort */ /* now look for subsets (smaller within larger), if found, mark with array index and char index */ { for (j = 0; j < i - 1; ++j) /* check if contained in any the string before */ { if ((pStr2 = pNameRecordArray[pNameRecordStrings[j].usNameRecordStringIndex].pNewNameString) == NULL) pStr2 = pNameRecordArray[pNameRecordStrings[j].usNameRecordStringIndex].pNameString; /* Calculate the maximum index beyond which the string compare would go off the end of Str2 */ maxCharIndex = pNameRecordStrings[j].usNameRecordStringLength - pNameRecordStrings[i].usNameRecordStringLength; for (k = 0; k <= maxCharIndex; ++k) /* move along string to look for compare */ { if (memcmp(pStr1, pStr2 + k,pNameRecordStrings[i].usNameRecordStringLength) == 0) /* one is contained in the other */ { pNameRecordStrings[i].usNameRecordStringIndex = pNameRecordStrings[j].usNameRecordStringIndex; /* set the index the same */ pNameRecordStrings[i].usNameRecordStringCharIndex = k; /* set the char index */ break; } } if (k <= maxCharIndex) /* we found a match and we set the values */ break; } } } /* now put it back the way it was. NOTE, we are only sorting ValidNameRecordCount records */ SortNameRecordsByNameRecordIndex(pNameRecordStrings,ValidNameRecordCount); } /* now, we have an array of structures we can output */ for (i = 0; i < ValidNameRecordCount; ++i) { index = pNameRecordStrings[i].usNameRecordIndex; BaseIndex = pNameRecordStrings[i].usNameRecordStringIndex; if (!pNameRecordArray[index].bStringWritten) /* this baby has not been written */ { if (index != BaseIndex) /* if this points to another string, that has not been written */ { if (!pNameRecordArray[BaseIndex].bStringWritten) /* base string hasn't been written */ { pNameRecordArray[BaseIndex].stringOffset = usStringsOffset; /* set this one too */ pNameRecordArray[BaseIndex].bStringWritten = TRUE; if ((pStr1 = pNameRecordArray[BaseIndex].pNewNameString) == NULL) pStr1 = pNameRecordArray[BaseIndex].pNameString; if ((errCode = WriteBytes(pOutputBufferInfo, (uint8 *)pStr1, ulNameOffset + NameHeader.offsetToStringStorage + usStringsOffset,pNameRecordArray[BaseIndex].stringLength)) != NO_ERROR) break; usStringsOffset = (uint16)(usStringsOffset + pNameRecordArray[BaseIndex].stringLength); } pNameRecordArray[index].stringOffset = pNameRecordArray[BaseIndex].stringOffset + pNameRecordStrings[i].usNameRecordStringCharIndex; } else { pNameRecordArray[index].stringOffset = usStringsOffset + pNameRecordStrings[i].usNameRecordStringCharIndex; if ((pStr1 = pNameRecordArray[index].pNewNameString) == NULL) pStr1 = pNameRecordArray[index].pNameString; if ((errCode = WriteBytes(pOutputBufferInfo, (uint8 *)pStr1, ulNameOffset + NameHeader.offsetToStringStorage + usStringsOffset,pNameRecordArray[index].stringLength)) != NO_ERROR) break; usStringsOffset = (uint16)(usStringsOffset + pNameRecordArray[index].stringLength); } pNameRecordArray[index].bStringWritten = TRUE; } /* now write that NameRecord thing */ if ((errCode = WriteGeneric(pOutputBufferInfo,(uint8 *) &(pNameRecordArray[index]), SIZEOF_NAME_RECORD, NAME_RECORD_CONTROL, ulOffset, &usBytesWritten)) != NO_ERROR) break; ulOffset += usBytesWritten; } if (errCode == NO_ERROR) { NameHeader.numNameRecords = ValidNameRecordCount; *pulBytesWritten = NameHeader.offsetToStringStorage + usStringsOffset; errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) &NameHeader, SIZEOF_NAME_HEADER, NAME_HEADER_CONTROL, ulNameOffset, &usBytesWritten ); } Mem_Free(pNameRecordStrings); return errCode; } /* ---------------------------------------------------------------------- */ /* will free up both strings, as well as the array. NOTE: the NewNameString must */ /* have been allocated with the same function as was handed to the ReadAllocNameRecords function */ /* or something compatible with the lpfnFree function */ /* ---------------------------------------------------------------------- */ void FreeNameRecords(PNAMERECORD pNameRecordArray, uint16 NameRecordCount, CFP_FREEPROC lfpnFree) { uint16 i; if (pNameRecordArray == NULL) return; for (i = 0; i < NameRecordCount; ++i) { if (pNameRecordArray[i].pNameString != NULL) lfpnFree(pNameRecordArray[i].pNameString); if (pNameRecordArray[i].pNewNameString != NULL) lfpnFree(pNameRecordArray[i].pNewNameString); } lfpnFree(pNameRecordArray); } /* ---------------------------------------------------------------------- */ /* next three functions only used by Name Wizard and Embedding .dll, not by CreateFontPackage */ /* or MergeFontPackage */ /* ---------------------------------------------------------------------- */ int16 InsertTable(TTFACC_FILEBUFFERINFO * pOutputBufferInfo, __in_bcount(4) const char * szTag, uint8 * puchTableBuffer, uint32 ulTableBufferLength) { uint32 ulTableOffset; uint32 ulTableLength; uint32 ulOffset; int16 errCode = NO_ERROR; uint16 usnTables; uint16 i; uint16 usBytesRead; uint16 usBytesWritten; OFFSET_TABLE OffsetTable; DIRECTORY Directory; uint32 ulTag; int32 lCopySize; if (puchTableBuffer == NULL || ulTableBufferLength == 0) return ERR_GENERIC; ulTableOffset = TTTableOffset( pOutputBufferInfo, szTag); ulTableLength = TTTableLength( pOutputBufferInfo, szTag); ConvertStringTagToLong(szTag,&ulTag); if (ulTableOffset == DIRECTORY_ERROR) { DIRECTORY *aDirectory; uint16 usnNewTables, usLastTable; uint32 ulBytesRead, ulBytesWritten, ulNewSize, ulTableDirSize, ulNewTableDirSize; /* read offset table and determine number of existing tables */ ulOffset = pOutputBufferInfo->ulOffsetTableOffset; if ((errCode = ReadGeneric((TTFACC_FILEBUFFERINFO *) pOutputBufferInfo, (uint8 *) &OffsetTable, SIZEOF_OFFSET_TABLE, OFFSET_TABLE_CONTROL, ulOffset, &usBytesRead)) != NO_ERROR) return(errCode); usnTables = OffsetTable.numTables; usnNewTables = usnTables + 1; // Check for ushort overflow, number of tables becomes more than 0xFFFF if (usnNewTables <= usnTables) { return ERR_FORMAT; } usLastTable = usnTables; ulOffset += usBytesRead; aDirectory = (DIRECTORY *) Mem_Alloc(((int32)usnNewTables) * sizeof(DIRECTORY)); /* one extra for new table */ if (aDirectory == NULL) return(ERR_MEM); /* read directory entries */ if ((errCode = ReadGenericRepeat((TTFACC_FILEBUFFERINFO *) pOutputBufferInfo, (uint8 *)aDirectory, DIRECTORY_CONTROL, ulOffset, &ulBytesRead, usnTables, SIZEOF_DIRECTORY)) != NO_ERROR) { Mem_Free(aDirectory); return(errCode); } ulOffset += ulBytesRead; /* update existing offsets to account for new entry */ for(i = 0; i < usLastTable; i++) aDirectory[ i ].offset += SIZEOF_DIRECTORY; ulNewSize = SIZEOF_DIRECTORY + RoundToLongWord(pOutputBufferInfo->ulBufferSize); /* setup new entry point to end of file with zero size */ aDirectory[ usLastTable ].length = 0; aDirectory[ usLastTable ].offset = ulNewSize; aDirectory[ usLastTable ].tag = ulTag; aDirectory[ usLastTable ].checkSum = 0; SortByTag( aDirectory, usnNewTables ); OffsetTable.numTables = usnNewTables; OffsetTable.searchRange = (uint16)((0x0001 << ( log2( usnNewTables ))) << 4 ); OffsetTable.entrySelector = (uint16)(log2((uint16)(0x0001 << ( log2( usnNewTables ))))); OffsetTable.rangeShift = (uint16)((usnNewTables << 4) - ((0x0001 << ( log2( usnNewTables ))) * 16 )); /* allocate space for new font image */ pOutputBufferInfo->puchBuffer = (uint8 *)pOutputBufferInfo->lpfnReAllocate(pOutputBufferInfo->puchBuffer,ulNewSize); if (pOutputBufferInfo->puchBuffer == NULL) { Mem_Free(aDirectory); return ERR_MEM; } pOutputBufferInfo->ulBufferSize = ulNewSize; if ((errCode = ZeroLongWordAlign(pOutputBufferInfo,pOutputBufferInfo->ulBufferSize + SIZEOF_DIRECTORY, NULL)) != NO_ERROR) { Mem_Free(aDirectory); return errCode; } ulTableDirSize = SIZEOF_OFFSET_TABLE + (usnTables * SIZEOF_DIRECTORY); ulNewTableDirSize = SIZEOF_OFFSET_TABLE + (usnNewTables * SIZEOF_DIRECTORY); lCopySize = pOutputBufferInfo->ulBufferSize - ulNewTableDirSize; if (lCopySize>0 && (errCode = CopyBlock(pOutputBufferInfo,ulNewTableDirSize,ulTableDirSize,lCopySize)) != NO_ERROR) { Mem_Free(aDirectory); return errCode; } /* copy in directory header */ ulOffset = pOutputBufferInfo->ulOffsetTableOffset; if ((errCode = WriteGeneric((TTFACC_FILEBUFFERINFO *) pOutputBufferInfo, (uint8 *) &OffsetTable, SIZEOF_OFFSET_TABLE, OFFSET_TABLE_CONTROL, ulOffset, &usBytesWritten)) != NO_ERROR) { Mem_Free(aDirectory); return(errCode); } ulOffset += usBytesWritten; /* copy in directory entries */ if ((errCode = WriteGenericRepeat((TTFACC_FILEBUFFERINFO *) pOutputBufferInfo, (uint8 *)aDirectory, DIRECTORY_CONTROL, ulOffset, &ulBytesWritten, usnNewTables, SIZEOF_DIRECTORY)) != NO_ERROR) { Mem_Free(aDirectory); return(errCode); } ulOffset += ulBytesWritten; Mem_Free(aDirectory); ulTableOffset = TTTableOffset( pOutputBufferInfo, szTag); ulTableLength = TTTableLength( pOutputBufferInfo, szTag); if (ulTableOffset == DIRECTORY_ERROR) return ERR_GENERIC; } if(ulTableLength == 0) { uint32 ulNewOffset = RoundToLongWord(pOutputBufferInfo->ulBufferSize); pOutputBufferInfo->puchBuffer = (uint8 *)pOutputBufferInfo->lpfnReAllocate(pOutputBufferInfo->puchBuffer,ulNewOffset + RoundToLongWord(ulTableBufferLength)); if (pOutputBufferInfo->puchBuffer == NULL) { return ERR_MEM; } pOutputBufferInfo->ulBufferSize = ulNewOffset + RoundToLongWord(ulTableBufferLength); if ((errCode = ZeroLongWordAlign(pOutputBufferInfo,pOutputBufferInfo->ulBufferSize, NULL)) != NO_ERROR) return errCode; ulOffset = pOutputBufferInfo->ulOffsetTableOffset; if ((errCode = ReadGeneric( pOutputBufferInfo, (uint8 *) &OffsetTable, SIZEOF_OFFSET_TABLE, OFFSET_TABLE_CONTROL, ulOffset, &usBytesRead)) != NO_ERROR) return(errCode); usnTables = OffsetTable.numTables; ulOffset += usBytesRead; /* where to start reading the Directory entries */ for (i = 0; i < usnTables; ++i ) { if ((errCode = ReadGeneric( pOutputBufferInfo, (uint8 *) &Directory, SIZEOF_DIRECTORY, DIRECTORY_CONTROL, ulOffset, &usBytesRead )) != NO_ERROR) break; if (Directory.tag == ulTag) /* need to update the offset */ { Directory.offset = ulNewOffset; if ((errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) &Directory, SIZEOF_DIRECTORY, DIRECTORY_CONTROL, ulOffset, &usBytesWritten )) != NO_ERROR) break; } ulOffset += usBytesRead; /* increment for next time */ } if (errCode != NO_ERROR) return errCode; ulTableOffset = ulNewOffset; }else { int32 lShift; uint32 ulStartShiftOffset; lShift = RoundToLongWord(ulTableBufferLength) - RoundToLongWord(ulTableLength); /* number of bytes to shift the tables forward */ ulStartShiftOffset = ulTableOffset + RoundToLongWord(ulTableLength); /* the offset of the table after this one */ lCopySize = pOutputBufferInfo->ulBufferSize - ulStartShiftOffset; /* need to move everything forward, or back, then insert this one */ if (lShift > 0) /* need more room */ { pOutputBufferInfo->puchBuffer = (uint8 *)pOutputBufferInfo->lpfnReAllocate(pOutputBufferInfo->puchBuffer,pOutputBufferInfo->ulBufferSize + lShift); if (pOutputBufferInfo->puchBuffer == NULL) return ERR_MEM; pOutputBufferInfo->ulBufferSize += lShift; } if (lCopySize>0 && (errCode = CopyBlock(pOutputBufferInfo,ulStartShiftOffset + lShift, ulStartShiftOffset,lCopySize)) != NO_ERROR) return errCode; if (lShift < 0) /* it shrank */ pOutputBufferInfo->ulBufferSize += lShift; /* now we need to update all of the offsets in the directory */ ulOffset = pOutputBufferInfo->ulOffsetTableOffset; if ((errCode = ReadGeneric( pOutputBufferInfo, (uint8 *) &OffsetTable, SIZEOF_OFFSET_TABLE, OFFSET_TABLE_CONTROL, ulOffset, &usBytesRead)) != NO_ERROR) return(errCode); usnTables = OffsetTable.numTables; ulOffset += usBytesRead; /* where to start reading the Directory entries */ for (i = 0; i < usnTables; ++i ) { if ((errCode = ReadGeneric( pOutputBufferInfo, (uint8 *) &Directory, SIZEOF_DIRECTORY, DIRECTORY_CONTROL, ulOffset, &usBytesRead )) != NO_ERROR) break; if (Directory.offset >= ulStartShiftOffset) /* need to update the offset */ { Directory.offset += lShift; if ((errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) &Directory, SIZEOF_DIRECTORY, DIRECTORY_CONTROL, ulOffset, &usBytesWritten )) != NO_ERROR) break; } ulOffset += usBytesRead; /* increment for next time */ } if (errCode != NO_ERROR) return errCode; } if ((errCode = WriteBytes(pOutputBufferInfo, puchTableBuffer, ulTableOffset, ulTableBufferLength)) != NO_ERROR) return errCode; if ((errCode = UpdateDirEntry(pOutputBufferInfo, szTag, ulTableBufferLength)) != NO_ERROR) return errCode; SetFileChecksum(pOutputBufferInfo, pOutputBufferInfo->ulBufferSize); /* lcp add this 5/20/97 */ return errCode; } /* ---------------------------------------------------------------------- */ int16 WriteNameTable(TTFACC_FILEBUFFERINFO * pOutputBufferInfo, PNAMERECORD pNameRecordArray, /* internal representation of NameRecord - from ttftable.h */ uint16 NameRecordCount, BOOL bOptimize) /* lcp 4/8/97, optimize string storage for size */ { uint8 * puchBuffer; int16 errCode = NO_ERROR; uint32 ulBytesWritten = 0; uint32 ulMaxNewNameTableLength; TTFACC_FILEBUFFERINFO NameTableBufferInfo; /* needed by WriteNameRecords */ ulMaxNewNameTableLength = CalcMaxNameTableLength(pNameRecordArray, NameRecordCount); if ((errCode = Mem_Init()) != NO_ERROR) /* need to initialize for debug mode, but make sure we're not stomping already initiated stuff */ return errCode; puchBuffer = (uint8 *) Mem_Alloc(ulMaxNewNameTableLength); if (puchBuffer == NULL) return ERR_MEM; /* now fake up a bufferinfo so that WriteNameRecords will write to the actual file buffer */ InitFileBufferInfo(&NameTableBufferInfo, puchBuffer, ulMaxNewNameTableLength, NULL /* can't reallocate!!! */); if ((errCode = WriteNameRecords(&NameTableBufferInfo, pNameRecordArray, NameRecordCount, TRUE, bOptimize, &ulBytesWritten)) == NO_ERROR) /* insert the Name table here, shifting other tables forward if necessary */ errCode = InsertTable(pOutputBufferInfo, NAME_TAG, puchBuffer, ulBytesWritten); Mem_Free(puchBuffer); Mem_End(); /* need free up the track for debug mode */ return errCode; } /* ---------------------------------------------------------------------- */ int16 WriteSmartOS2Table(TTFACC_FILEBUFFERINFO * pOutputBufferInfo, MAINOS2 * pOS2) { uint8 * puchBuffer; int16 errCode = NO_ERROR; uint16 usBytesWritten = 0; uint16 usMaxOS2Len; DIRECTORY Directory; MAINOS2 OldOS2; TTFACC_FILEBUFFERINFO OS2TableBufferInfo; BOOL bWritten = FALSE; /* look at what is in the font already to make sure it is a version we understand */ if ( (GetTTDirectory( pOutputBufferInfo, OS2_TAG, &Directory ) != DIRECTORY_ERROR) && (GetSmarterOS2( pOutputBufferInfo, &OldOS2) != 0) ) { /* if the version is beyond what we understand */ if(OldOS2.usVersion > 2) { /* make sure there is enough room to write what we do understand */ if(Directory.length >= GetGenericSize(VERSION2OS2_CONTROL)) { pOS2->usVersion = OldOS2.usVersion; if((errCode = WriteGeneric(pOutputBufferInfo, (uint8 *)pOS2, SIZEOF_VERSION2OS2, VERSION2OS2_CONTROL, Directory.offset, &usBytesWritten)) != NO_ERROR) return errCode; bWritten = TRUE; }else { return ERR_FORMAT; } } } if(!bWritten) { /* if we have gotton here that means the font contains a OS2 table who's format we undestand */ if ((errCode = Mem_Init()) != NO_ERROR) /* need to initialize for debug mode, but make sure we're not stomping already initiated stuff */ return errCode; usMaxOS2Len = GetGenericSize(VERSION2OS2_CONTROL); puchBuffer = (uint8 *) Mem_Alloc(usMaxOS2Len); if (puchBuffer == NULL) return ERR_MEM; /* now fake up a bufferinfo so that we will write to the actual file buffer */ InitFileBufferInfo(&OS2TableBufferInfo, puchBuffer, usMaxOS2Len, NULL /* can't reallocate!!! */); if(pOS2->usVersion == 0) errCode = WriteGeneric(&OS2TableBufferInfo, (uint8 *)pOS2, SIZEOF_OS2, OS2_CONTROL, 0, &usBytesWritten); else if(pOS2->usVersion == 1) errCode = WriteGeneric(&OS2TableBufferInfo, (uint8 *)pOS2, SIZEOF_NEWOS2, NEWOS2_CONTROL, 0, &usBytesWritten); else if(pOS2->usVersion == 2) errCode = WriteGeneric(&OS2TableBufferInfo, (uint8 *)pOS2, SIZEOF_VERSION2OS2, VERSION2OS2_CONTROL, 0, &usBytesWritten); if(errCode == NO_ERROR) errCode = InsertTable(pOutputBufferInfo, OS2_TAG, puchBuffer, usBytesWritten); Mem_Free(puchBuffer); Mem_End(); /* need free up the track for debug mode */ } return errCode; } /* ---------------------------------------------------------------------- */ int16 CompressTables( TTFACC_FILEBUFFERINFO * pOutputBufferInfo, uint32 * pulBytesWritten ) { /* this routine compresses the tables present in a font file by removing space between them which is unused. It follows four basic steps: 1. Make a list of tables to keep. 2. Sort the list of tables by offset so that the gaps between them are easy to detect and fill in. 3. Move the tables to eliminate gaps. Clean up by recalculating checksums and putting in zero pad bytes for long word alignment at the same time. 4. Sort the list of tables by tag (as required for the table directory) and write out a new table directory. */ DIRECTORY *aDirectory; DIRECTORY CandDirectory; uint16 i; OFFSET_TABLE OffsetTable; uint16 usnTables; uint16 usnNewTables; uint32 ulOffset; uint16 usTableIdx; uint16 usBytesRead; uint16 usBytesWritten; uint32 ulSaveBytesWritten = 0; uint16 DoTwo; int16 errCode; /* read offset table and determine number of existing tables */ ulOffset = pOutputBufferInfo->ulOffsetTableOffset; if ((errCode = ReadGeneric( pOutputBufferInfo, (uint8 *) &OffsetTable, SIZEOF_OFFSET_TABLE, OFFSET_TABLE_CONTROL, ulOffset, &usBytesRead)) != NO_ERROR) return(ERR_MEM); usnTables = OffsetTable.numTables; ulOffset += usBytesRead; /* Create a list of valid tables */ aDirectory = (DIRECTORY *) Mem_Alloc((usnTables) * sizeof(DIRECTORY)); if (aDirectory == NULL) return(ERR_MEM); usnNewTables = 0; for (i = 0; i < usnTables; ++i ) { if ((errCode = ReadGeneric( pOutputBufferInfo, (uint8 *) &CandDirectory, SIZEOF_DIRECTORY, DIRECTORY_CONTROL, ulOffset, &usBytesRead )) != NO_ERROR) break; ulOffset += usBytesRead; if (CandDirectory.tag != DELETETABLETAG && CandDirectory.length != 0 && CandDirectory.offset != 0) { aDirectory[ usnNewTables ] = CandDirectory; usnNewTables++; } } if (errCode != NO_ERROR) { Mem_Free(aDirectory); return errCode; } /* sort directories by offset */ SortByOffset( aDirectory, usnNewTables ); /* compress table data and adjust directory entries to reflect the changes */ ulOffset = pOutputBufferInfo->ulOffsetTableOffset + GetGenericSize( OFFSET_TABLE_CONTROL ) + (usnNewTables) * GetGenericSize( DIRECTORY_CONTROL ); if ((errCode = ZeroLongWordAlign(pOutputBufferInfo, ulOffset, &ulOffset)) != NO_ERROR) { Mem_Free(aDirectory); return errCode; } DoTwo = FALSE; for ( usTableIdx = 0; usTableIdx < usnNewTables; usTableIdx++ ) { /* copy the table from where it currently is to the lowest available spot, thus filling in any existing gaps */ if (!DoTwo) /* if not the 2nd of two directories pointing to the same data */ { if ((errCode = CopyBlock( pOutputBufferInfo, ulOffset, aDirectory[ usTableIdx ].offset, aDirectory[ usTableIdx ].length )) != NO_ERROR) break; if (usTableIdx + 1 < usnNewTables) { /* special case for bloc and bdat tables */ if ( (aDirectory[ usTableIdx ].offset == aDirectory[ usTableIdx + 1 ].offset) && (aDirectory[ usTableIdx ].length != 0) ) { DoTwo = TRUE; /* need to proccess 2 directories pointing to same data */ aDirectory[ usTableIdx + 1 ].offset = ulOffset; aDirectory[ usTableIdx + 1 ].length = aDirectory[ usTableIdx ].length; } } aDirectory[ usTableIdx ].offset = ulOffset; /* calc offset for next table */ /* zero out any pad bytes and determine the checksum for the entry */ if ((errCode = ZeroLongWordGap( pOutputBufferInfo, aDirectory[ usTableIdx ].offset, aDirectory[ usTableIdx ].length, &ulOffset)) != NO_ERROR) break; } else { DoTwo = FALSE; /* so next time we'll perform the copy */ } if ((errCode = CalcChecksum( pOutputBufferInfo, aDirectory[ usTableIdx ].offset, aDirectory[ usTableIdx ].length, &aDirectory[ usTableIdx ].checkSum )) != NO_ERROR) break; } while (errCode == NO_ERROR) /* so we can break out on error */ { ulSaveBytesWritten = ulOffset; /* write out the new directory info */ SortByTag( aDirectory, usnNewTables ); OffsetTable.numTables = usnNewTables ; OffsetTable.searchRange = (uint16)((0x0001 << ( log2( usnNewTables ))) << 4 ); OffsetTable.entrySelector = (uint16)(log2((uint16)(0x0001 << ( log2( usnNewTables ))))); OffsetTable.rangeShift = (uint16)((usnNewTables << 4) - ((0x0001 << ( log2( usnNewTables ))) * 16 )); ulOffset = pOutputBufferInfo->ulOffsetTableOffset; if ((errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) &OffsetTable, SIZEOF_OFFSET_TABLE, OFFSET_TABLE_CONTROL, ulOffset, &usBytesWritten)) != NO_ERROR) break; ulOffset += usBytesWritten; for ( i = 0; i < usnNewTables; i++ ) { if ((errCode = WriteGeneric( pOutputBufferInfo, (uint8 *) &(aDirectory[ i ]), SIZEOF_DIRECTORY, DIRECTORY_CONTROL, ulOffset, &usBytesWritten)) != NO_ERROR) break; ulOffset += usBytesWritten; } if (errCode != NO_ERROR) break; *pulBytesWritten = ulSaveBytesWritten; break; } Mem_Free(aDirectory); return(errCode); } /* ---------------------------------------------------------------------- */
38,856
320
# An example showing how to use sensor data, here with the SenseHAT (or SenseHAT emulator) # Refer to RaspberryPi forums Teaching and learning resources : https://www.raspberrypi.org/forums/viewtopic.php?f=49&t=202386 for some talk using it. # compass added for show, but commented as it will not work if just enabled from guizero import * from sense_hat import SenseHat # from sense_emu import SenseHat #use this instead of sense_hat if you don't have a SenseHAT, but are using Raspbian/x86 Desktop sense=SenseHat() SENSOR_ENVIRONMENT_UPDATE_FREQUENCY = 1000 #time in milliseconds (ms) SENSOR_IMU_UPDATE_FREQUENCY = 100 def read_temp_sensor(): return round(sense.get_temperature(),1) def read_humidity_sensor(): return round(sense.get_humidity(),1) def read_pressure_sensor(): return round(sense.get_pressure()*0.1,1) def update_environment_sensors(): count_text.value=int(count_text.value)+1 #used to debug, i.e. check it is actually incrementing temperature_text.value = read_temp_sensor(),"ยฐC" humidity_text.value = read_humidity_sensor(),"%" pressure_text.value = read_pressure_sensor(),"kPa" def update_IMU_sensors(): orient_yaw,orient_pitch,orient_roll = sense.get_orientation().values() mag_x,mag_y,mag_z = sense.get_compass_raw().values() acc_x,acc_y,acc_z = sense.get_accelerometer_raw().values() gyro_x,gyro_y,gyro_z = sense.get_gyroscope_raw().values() IMU_orient_yaw_text.value = round(orient_yaw,1) IMU_orient_pitch_text.value = round(orient_pitch,1) IMU_orient_roll_text.value = round(orient_roll,1) IMU_mag_x_text.value = round(mag_x,1) IMU_mag_y_text.value = round(mag_y,1) IMU_mag_z_text.value = round(mag_z,1) IMU_acc_x_text.value = round(acc_x,1) IMU_acc_y_text.value = round(acc_y,1) IMU_acc_z_text.value = round(acc_z,1) IMU_gyro_x_text.value = round(gyro_x,1) IMU_gyro_y_text.value = round(gyro_y,1) IMU_gyro_z_text.value = round(gyro_z,1) if __name__ == '__main__': app = App(title="Sensor Display!", height=230, width=420, layout='grid') title_count = Text(app, "count 'debug':", grid=[0, 0]) count_text = Text(app, "1", grid=[1, 0]) title = Text(app, "Temperature Sensor value:", grid=[0, 1]) temperature_text = Text(app, "xx", grid=[1, 1]) title2 = Text(app, "Humidity Sensor value:", grid=[0, 2]) humidity_text = Text(app, "xx", grid=[1, 2]) title3 = Text(app, "Pressure Sensor value:", grid=[0, 3]) pressure_text = Text(app, "xx", grid=[1, 3]) #IMU box IMU_title_orient_yaw = Text(app, "Yaw", grid=[1, 5]) IMU_title_orient_pitch = Text(app, "Pitch", grid=[2, 5]) IMU_title_orient_roll = Text(app, "Roll", grid=[3, 5]) IMU_title_orient = Text(app, "Orientation:", grid=[0, 6]) IMU_orient_yaw_text = Text(app, "xx", grid=[1, 6]) IMU_orient_pitch_text = Text(app, "xx", grid=[2, 6]) IMU_orient_roll_text = Text(app, "xx", grid=[3, 6]) IMU_title_x = Text(app, "X", grid=[1, 8]) IMU_title_y = Text(app, "Y", grid=[2, 8]) IMU_title_z = Text(app, "Z", grid=[3, 8]) IMU_title_mag = Text(app, "Magnetometer ยตT", grid=[0, 9]) IMU_title_acc = Text(app, "Accelerometer Gs", grid=[0, 10]) IMU_title_gyro = Text(app, "Gyroscope rad/s", grid=[0, 11]) IMU_mag_x_text = Text(app, "xx", grid=[1, 9]) IMU_mag_y_text = Text(app, "xx", grid=[2, 9]) IMU_mag_z_text = Text(app, "xx", grid=[3, 9]) IMU_acc_x_text = Text(app, "xx", grid=[1, 10]) IMU_acc_y_text = Text(app, "xx", grid=[2, 10]) IMU_acc_z_text = Text(app, "xx", grid=[3, 10]) IMU_gyro_x_text = Text(app, "xx", grid=[1, 11]) IMU_gyro_y_text = Text(app, "xx", grid=[2, 11]) IMU_gyro_z_text = Text(app, "xx", grid=[3, 11]) IMU_title_compass = Text(app, "Compass North Bearing", grid=[0, 13]) IMU_compass_text = Text(app, "xx", grid=[1, 13]) app.repeat(SENSOR_ENVIRONMENT_UPDATE_FREQUENCY, update_environment_sensors) app.repeat(SENSOR_IMU_UPDATE_FREQUENCY, update_IMU_sensors) app.display()
1,771
431
/** * Copyright ยฉ 2006-2016 Web Cohesion (<EMAIL>) * * 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.webcohesion.enunciate.modules.jackson.model; import com.webcohesion.enunciate.facets.Facet; import com.webcohesion.enunciate.facets.HasFacets; import com.webcohesion.enunciate.javac.decorations.element.DecoratedElement; import com.webcohesion.enunciate.metadata.ClientName; import com.webcohesion.enunciate.modules.jackson.EnunciateJacksonContext; import java.util.Set; import java.util.TreeSet; /** * Used to wrap @JsonAnyGetter. * * @author <NAME> */ public class WildcardMember extends DecoratedElement<javax.lang.model.element.Element> implements HasFacets { private final Set<Facet> facets = new TreeSet<Facet>(); public WildcardMember(javax.lang.model.element.Element delegate, TypeDefinition typeDef, EnunciateJacksonContext context) { super(delegate, context.getContext().getProcessingEnvironment()); this.facets.addAll(Facet.gatherFacets(delegate, context.getContext())); this.facets.addAll(typeDef.getFacets()); } public String getName() { return getSimpleName().toString(); } /** * The simple name for client-side code generation. * * @return The simple name for client-side code generation. */ public String getClientSimpleName() { String clientSimpleName = getSimpleName().toString(); ClientName clientName = getAnnotation(ClientName.class); if (clientName != null) { clientSimpleName = clientName.value(); } return clientSimpleName; } /** * The facets here applicable. * * @return The facets here applicable. */ public Set<Facet> getFacets() { return facets; } }
688
1,991
<reponame>qq758689805/Pocsuite-dev<gh_stars>1000+ #!/usr/bin/env python # coding: utf-8 from setuptools import setup, find_packages from pocsuite import ( __version__ as version, __author__ as author, __author_email__ as author_email, __license__ as license) setup( name='pocsuite', version=version, description="Pocsuite is an open-sourced remote vulnerability testing framework developed by the Knownsec Security Team.", long_description="""\ Pocsuite is an open-sourced remote vulnerability testing and proof-of-concept development framework developed by the Knownsec Security Team. It comes with a powerful proof-of-concept engine, many niche features for the ultimate penetration testers and security researchers.""", classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='PoC,Exp,Pocsuite', author=author, author_email=author_email, url='http://pocsuite.org', license=license, packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'lxml', ], entry_points={ 'console_scripts': [ 'pocsuite = pocsuite.pocsuite_cli:main', 'pcs-console = pocsuite.pocsuite_console:main', 'pcs-verify = pocsuite.pocsuite_verify:main', 'pcs-attack = pocsuite.pocsuite_attack:main', ], }, )
533
402
<reponame>padrecedano/android-speech<filename>speech/src/main/java/net/gotev/speech/engine/BaseSpeechRecognitionEngine.java package net.gotev.speech.engine; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.widget.LinearLayout; import net.gotev.speech.DelayedOperation; import net.gotev.speech.SpeechDelegate; import net.gotev.speech.GoogleVoiceTypingDisabledException; import net.gotev.speech.SpeechRecognitionException; import net.gotev.speech.SpeechRecognitionNotAvailable; import net.gotev.speech.Logger; import net.gotev.speech.ui.SpeechProgressView; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; public class BaseSpeechRecognitionEngine implements SpeechRecognitionEngine { private static final String LOG_TAG = BaseSpeechRecognitionEngine.class.getSimpleName(); private Context mContext; private SpeechRecognizer mSpeechRecognizer; private SpeechDelegate mDelegate; private SpeechProgressView mProgressView; private String mCallingPackage; private String mUnstableData; private DelayedOperation mDelayedStopListening; private final List<String> mPartialData = new ArrayList<>(); private List<String> mLastPartialResults = null; private Locale mLocale = Locale.getDefault(); private boolean mPreferOffline = false; private boolean mGetPartialResults = true; private boolean mIsListening = false; private long mLastActionTimestamp; private long mStopListeningDelayInMs = 4000; private long mTransitionMinimumDelay = 1200; @Override public void init(Context context) { initDelayedStopListening(context); } @Override public void clear() { mPartialData.clear(); mUnstableData = null; } @Override public void onReadyForSpeech(final Bundle bundle) { mPartialData.clear(); mUnstableData = null; } @Override public void onBeginningOfSpeech() { if (mProgressView != null) mProgressView.onBeginningOfSpeech(); mDelayedStopListening.start(new DelayedOperation.Operation() { @Override public void onDelayedOperation() { returnPartialResultsAndRecreateSpeechRecognizer(); } @Override public boolean shouldExecuteDelayedOperation() { return true; } }); } @Override public void onRmsChanged(final float v) { try { if (mDelegate != null) mDelegate.onSpeechRmsChanged(v); } catch (final Throwable exc) { Logger.error(getClass().getSimpleName(), "Unhandled exception in delegate onSpeechRmsChanged", exc); } if (mProgressView != null) mProgressView.onRmsChanged(v); } @Override public void onPartialResults(final Bundle bundle) { mDelayedStopListening.resetTimer(); final List<String> partialResults = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); final List<String> unstableData = bundle.getStringArrayList("android.speech.extra.UNSTABLE_TEXT"); if (partialResults != null && !partialResults.isEmpty()) { mPartialData.clear(); mPartialData.addAll(partialResults); mUnstableData = unstableData != null && !unstableData.isEmpty() ? unstableData.get(0) : null; try { if (mLastPartialResults == null || !mLastPartialResults.equals(partialResults)) { if (mDelegate != null) mDelegate.onSpeechPartialResults(partialResults); mLastPartialResults = partialResults; } } catch (final Throwable exc) { Logger.error(getClass().getSimpleName(), "Unhandled exception in delegate onSpeechPartialResults", exc); } } } @Override public void onResults(final Bundle bundle) { mDelayedStopListening.cancel(); final List<String> results = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); final String result; if (results != null && !results.isEmpty() && results.get(0) != null && !results.get(0).isEmpty()) { result = results.get(0); } else { Logger.info(getClass().getSimpleName(), "No speech results, getting partial"); result = getPartialResultsAsString(); } mIsListening = false; try { if (mDelegate != null) mDelegate.onSpeechResult(result.trim()); } catch (final Throwable exc) { Logger.error(getClass().getSimpleName(), "Unhandled exception in delegate onSpeechResult", exc); } if (mProgressView != null) mProgressView.onResultOrOnError(); initSpeechRecognizer(mContext); } @Override public void onError(final int code) { Logger.error(LOG_TAG, "Speech recognition error", new SpeechRecognitionException(code)); returnPartialResultsAndRecreateSpeechRecognizer(); } @Override public void onBufferReceived(final byte[] bytes) { } @Override public void onEndOfSpeech() { if (mProgressView != null) mProgressView.onEndOfSpeech(); } @Override public void onEvent(final int i, final Bundle bundle) { } @Override public String getPartialResultsAsString() { final StringBuilder out = new StringBuilder(""); for (final String partial : mPartialData) { out.append(partial).append(" "); } if (mUnstableData != null && !mUnstableData.isEmpty()) out.append(mUnstableData); return out.toString().trim(); } @Override public void startListening(SpeechProgressView progressView, SpeechDelegate delegate) throws SpeechRecognitionNotAvailable, GoogleVoiceTypingDisabledException { if (mIsListening) return; if (mSpeechRecognizer == null) throw new SpeechRecognitionNotAvailable(); if (delegate == null) throw new IllegalArgumentException("delegate must be defined!"); if (throttleAction()) { Logger.debug(getClass().getSimpleName(), "Hey man calm down! Throttling start to prevent disaster!"); return; } mProgressView = progressView; mDelegate = delegate; if (progressView != null && !(progressView.getParent() instanceof LinearLayout)) throw new IllegalArgumentException("progressView must be put inside a LinearLayout!"); final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) .putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1) .putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, mGetPartialResults) .putExtra(RecognizerIntent.EXTRA_LANGUAGE, mLocale.getLanguage()) .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); if (mCallingPackage != null && !mCallingPackage.isEmpty()) { intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, mCallingPackage); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, mPreferOffline); } try { mSpeechRecognizer.startListening(intent); } catch (final SecurityException exc) { throw new GoogleVoiceTypingDisabledException(); } mIsListening = true; updateLastActionTimestamp(); try { if (mDelegate != null) mDelegate.onStartOfSpeech(); } catch (final Throwable exc) { Logger.error(getClass().getSimpleName(), "Unhandled exception in delegate onStartOfSpeech", exc); } } @Override public boolean isListening() { return mIsListening; } @Override public Locale getLocale() { return mLocale; } @Override public void setLocale(Locale locale) { mLocale = locale; } @Override public void stopListening() { if (!mIsListening) return; if (throttleAction()) { Logger.debug(getClass().getSimpleName(), "Hey man calm down! Throttling stop to prevent disaster!"); return; } mIsListening = false; updateLastActionTimestamp(); returnPartialResultsAndRecreateSpeechRecognizer(); } public void initSpeechRecognizer(final Context context) { if (context == null) throw new IllegalArgumentException("context must be defined!"); mContext = context; if (SpeechRecognizer.isRecognitionAvailable(context)) { if (mSpeechRecognizer != null) { try { mSpeechRecognizer.destroy(); } catch (final Throwable exc) { Logger.debug(getClass().getSimpleName(), "Non-Fatal error while destroying speech. " + exc.getMessage()); } finally { mSpeechRecognizer = null; } } mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(context); mSpeechRecognizer.setRecognitionListener(this); init(context); } else { mSpeechRecognizer = null; } clear(); } @Override public void returnPartialResultsAndRecreateSpeechRecognizer() { mIsListening = false; try { if (mDelegate != null) mDelegate.onSpeechResult(getPartialResultsAsString()); } catch (final Throwable exc) { Logger.error(getClass().getSimpleName(), "Unhandled exception in delegate onSpeechResult", exc); } if (mProgressView != null) mProgressView.onResultOrOnError(); initSpeechRecognizer(mContext); } @Override public void setPartialResults(boolean getPartialResults) { this.mGetPartialResults = getPartialResults; } @Override public void unregisterDelegate() { mProgressView = null; mDelegate = null; } @Override public void setPreferOffline(boolean preferOffline) { mPreferOffline = preferOffline; } private void initDelayedStopListening(final Context context) { if (mDelayedStopListening != null) { mDelayedStopListening.cancel(); mDelayedStopListening = null; stopDueToDelay(); } mDelayedStopListening = new DelayedOperation(context, "delayStopListening", mStopListeningDelayInMs); } protected void stopDueToDelay() { } private void updateLastActionTimestamp() { mLastActionTimestamp = new Date().getTime(); } private boolean throttleAction() { return (new Date().getTime() <= (mLastActionTimestamp + mTransitionMinimumDelay)); } @Override public void setCallingPackage(String callingPackage) { this.mCallingPackage = callingPackage; } @Override public void setTransitionMinimumDelay(long milliseconds) { this.mTransitionMinimumDelay = milliseconds; } @Override public void setStopListeningAfterInactivity(long milliseconds) { this.mStopListeningDelayInMs = milliseconds; } @Override public void shutdown() { if (mSpeechRecognizer != null) { try { mSpeechRecognizer.stopListening(); mSpeechRecognizer.destroy(); } catch (final Exception exc) { Logger.error(getClass().getSimpleName(), "Warning while de-initing speech recognizer", exc); } } unregisterDelegate(); } }
5,129
311
//package com.sec.exploits.CommonsCollections; // //import org.apache.commons.collections.Transformer; //import org.apache.commons.collections.functors.ChainedTransformer; //import org.apache.commons.collections.functors.ConstantTransformer; //import org.apache.commons.collections.functors.InvokerTransformer; // //import java.lang.reflect.Method; // ///** // * @program: Gadgets // * @description: // * @author: 0range // * @create: 2021-05-12 14:20 // **/ // // //public class Demo { // public static void main(String[] args) throws Exception { //// InvokerTransformer it = new InvokerTransformer( //// "exec", //// new Class[]{String.class}, //// new String[]{"open /Applications/Calculator.app"} //// ); ////// //ๅพ—ๅˆฐRuntime.getRuntime()ๅฎžไพ‹input ////// Object input = Class.forName("java.lang.Runtime").getMethod("getRuntime").invoke(Class.forName("java.lang.Runtime")); ////// ////// //ไธบไบ†่ƒฝ่งฆๅ‘exec.invoke(input,"cmd"),้œ€่ฆๆ‰ง่กŒtransformๆ–นๆณ• ////// it.transform(input); //// //// Transformer[] transformers = new Transformer[] { //// //ไปฅไธ‹ไธคไธช่ฏญๅฅ็ญ‰ๅŒ,ไธ€ไธชๆ˜ฏ้€š่ฟ‡ๅๅฐ„ๆœบๅˆถๅพ—ๅˆฐ๏ผŒไธ€ไธชๆ˜ฏ็›ดๆŽฅ่ฐƒ็”จๅพ—ๅˆฐRuntimeๅฎžไพ‹ //// // new ConstantTransformer(Class.forName("java.lang.Runtime").getMethod("getRuntime").invoke(Class.forName("java.lang.Runtime"))), //// new ConstantTransformer(Runtime.getRuntime()), //// new InvokerTransformer("exec", new Class[] {String.class}, new Object[] {"open /Applications/Calculator.app"}) //// }; //// Transformer transformerChain = new ChainedTransformer(transformers); //// transformerChain.transform(null); // // Method gm = Class.forName("java.lang.Class").getMethod("getMethod", new Class[]{String.class, Class[].class}); // System.out.println(gm.getName());//getMethod // Method gr = (Method)gm.invoke(Class.forName("java.lang.Runtime"), "getRuntime", new Class[]{});//ๅŽไธคไธชๅ‚ๆ•ฐๅฏนๅบ”getMethodๆ–นๆณ•็š„ๅ‚ๆ•ฐ // System.out.println(gr.getName());//getRuntime // Method i = (Method)gm.invoke(Class.forName("java.lang.reflect.Method"), "invoke", new Class[] {Object.class, Object[].class}); // System.out.println(i.getName());//invoke // Method exec = (Method)gm.invoke(Class.forName("java.lang.Runtime"), "exec", new Class[] {String.class}); // System.out.println(exec.getName());//exec // // // //1.ๅฎขๆˆท็ซฏๆž„ๅปบๆ”ปๅ‡ปไปฃ็  // //ๆญคๅค„ๆž„ๅปบไบ†ไธ€ไธชtransformers็š„ๆ•ฐ็ป„๏ผŒๅœจๅ…ถไธญๆž„ๅปบไบ†ไปปๆ„ๅ‡ฝๆ•ฐๆ‰ง่กŒ็š„ๆ ธๅฟƒไปฃ็  // Transformer[] transformers = new Transformer[] { // new ConstantTransformer(Runtime.class), // new InvokerTransformer("getMethod", new Class[] {String.class, Class[].class}, new Object[] {"getRuntime", new Class[]{}}), // new InvokerTransformer("invoke", new Class[] {Object.class, Object[].class}, new Object[] {null, new Object[]{}}), // new InvokerTransformer("exec", new Class[] {String.class}, new Object[] {"open /Applications/Calculator.app"}) // }; // //ๅฐ†transformersๆ•ฐ็ป„ๅญ˜ๅ…ฅChaniedTransformer่ฟ™ไธช็ปงๆ‰ฟ็ฑป // Transformer transformerChain = new ChainedTransformer(transformers); // // // transformerChain.transform(null); // // // // // } //}
1,404
337
package test; public class A { public void usage(RemData p) { System.out.println(p.component1()); } }
48
4,904
<reponame>jagrutifrankdemo/async-http-client<filename>client/src/main/java/org/asynchttpclient/handler/resumable/ResumableIOExceptionFilter.java /* * Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.asynchttpclient.handler.resumable; import org.asynchttpclient.Request; import org.asynchttpclient.filter.FilterContext; import org.asynchttpclient.filter.IOExceptionFilter; /** * Simple {@link org.asynchttpclient.filter.IOExceptionFilter} that replay the current {@link org.asynchttpclient.Request} using a {@link ResumableAsyncHandler} */ public class ResumableIOExceptionFilter implements IOExceptionFilter { public <T> FilterContext<T> filter(FilterContext<T> ctx) { if (ctx.getIOException() != null && ctx.getAsyncHandler() instanceof ResumableAsyncHandler) { Request request = ResumableAsyncHandler.class.cast(ctx.getAsyncHandler()).adjustRequestRange(ctx.getRequest()); return new FilterContext.FilterContextBuilder<>(ctx).request(request).replayRequest(true).build(); } return ctx; } }
493
575
// 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 COMPONENTS_PAGE_LOAD_METRICS_RENDERER_FAKE_PAGE_TIMING_SENDER_H_ #define COMPONENTS_PAGE_LOAD_METRICS_RENDERER_FAKE_PAGE_TIMING_SENDER_H_ #include <set> #include <vector> #include "components/page_load_metrics/common/page_load_metrics.mojom.h" #include "components/page_load_metrics/common/page_load_timing.h" #include "components/page_load_metrics/renderer/page_timing_sender.h" #include "third_party/blink/public/mojom/mobile_metrics/mobile_friendliness.mojom.h" namespace page_load_metrics { // PageTimingSender implementation for use in tests. Allows for setting and // verifying basic expectations when sending PageLoadTiming. By default, // FakePageTimingSender will verify that expected and actual // PageLoadTimings match on each invocation to ExpectPageLoadTiming() and // SendTiming(), as well as in the destructor. Tests can force additional // validations by calling VerifyExpectedTimings. // // Expected PageLoadTimings are specified via ExpectPageLoadTiming, and actual // PageLoadTimings are dispatched through SendTiming(). When SendTiming() is // called, we verify that the actual PageLoadTimings dipatched through // SendTiming() match the expected PageLoadTimings provided via // ExpectPageLoadTiming. // // Normally, gmock would be used in place of this class, but gmock is not // compatible with structures that use aligned memory, and PageLoadTiming uses // base::Optional which uses aligned memory, so we're forced to roll // our own implementation here. See // https://groups.google.com/forum/#!topic/googletestframework/W-Hud3j_c6I for // more details. class FakePageTimingSender : public PageTimingSender { public: class PageTimingValidator { public: PageTimingValidator(); ~PageTimingValidator(); // PageLoadTimings that are expected to be sent through SendTiming() should // be passed to ExpectPageLoadTiming. void ExpectPageLoadTiming(const mojom::PageLoadTiming& timing); // CpuTimings that are expected to be sent through SendTiming() should be // passed to ExpectCpuTiming. void ExpectCpuTiming(const base::TimeDelta& timing); // Forces verification that actual timings sent through SendTiming() match // expected timings provided via ExpectPageLoadTiming. void VerifyExpectedTimings() const; // Forces verification that actual timings sent through SendTiming() match // expected timings provided via ExpectCpuTiming. void VerifyExpectedCpuTimings() const; void VerifyExpectedInputTiming() const; void VerifyExpectedMobileFriendliness() const; // PageLoad features that are expected to be sent through SendTiming() // should be passed via UpdateExpectedPageLoadFeatures. void UpdateExpectPageLoadFeatures(const blink::mojom::WebFeature feature); // PageLoad CSS properties that are expected to be sent through SendTiming() // should be passed via UpdateExpectedPageLoadCSSProperties. void UpdateExpectPageLoadCssProperties( blink::mojom::CSSSampleId css_property_id); void UpdateExpectFrameRenderDataUpdate( const mojom::FrameRenderDataUpdate& render_data) { expected_render_data_ = render_data.Clone(); } void UpdateExpectedInputTiming(const base::TimeDelta input_delay); void UpdateExpectedMobileFriendliness( const blink::MobileFriendliness& mobile_friendliness); void UpdateExpectFrameIntersectionUpdate( const mojom::FrameIntersectionUpdate& frame_intersection_update) { expected_frame_intersection_update_ = frame_intersection_update.Clone(); } // Forces verification that actual features sent through SendTiming match // expected features provided via ExpectPageLoadFeatures. void VerifyExpectedFeatures() const; // Forces verification that actual CSS properties sent through SendTiming // match expected CSS properties provided via ExpectPageLoadCSSProperties. void VerifyExpectedCssProperties() const; void VerifyExpectedRenderData() const; void VerifyExpectedFrameIntersectionUpdate() const; const std::vector<mojom::PageLoadTimingPtr>& expected_timings() const { return expected_timings_; } const std::vector<mojom::PageLoadTimingPtr>& actual_timings() const { return actual_timings_; } void UpdateTiming( const mojom::PageLoadTimingPtr& timing, const mojom::FrameMetadataPtr& metadata, const mojom::PageLoadFeaturesPtr& new_features, const std::vector<mojom::ResourceDataUpdatePtr>& resources, const mojom::FrameRenderDataUpdate& render_data, const mojom::CpuTimingPtr& cpu_timing, const mojom::DeferredResourceCountsPtr& new_deferred_resource_data, const mojom::InputTimingPtr& input_timing, const blink::MobileFriendliness& mobile_friendliness); private: std::vector<mojom::PageLoadTimingPtr> expected_timings_; std::vector<mojom::PageLoadTimingPtr> actual_timings_; std::vector<mojom::CpuTimingPtr> expected_cpu_timings_; std::vector<mojom::CpuTimingPtr> actual_cpu_timings_; std::set<blink::mojom::WebFeature> expected_features_; std::set<blink::mojom::WebFeature> actual_features_; std::set<blink::mojom::CSSSampleId> expected_css_properties_; std::set<blink::mojom::CSSSampleId> actual_css_properties_; mojom::FrameRenderDataUpdatePtr expected_render_data_; mojom::FrameRenderDataUpdate actual_render_data_; mojom::FrameIntersectionUpdatePtr expected_frame_intersection_update_; mojom::FrameIntersectionUpdatePtr actual_frame_intersection_update_; mojom::InputTimingPtr expected_input_timing; mojom::InputTimingPtr actual_input_timing; blink::MobileFriendliness expected_mobile_friendliness; blink::MobileFriendliness actual_mobile_friendliness; DISALLOW_COPY_AND_ASSIGN(PageTimingValidator); }; explicit FakePageTimingSender(PageTimingValidator* validator); ~FakePageTimingSender() override; void SendTiming( const mojom::PageLoadTimingPtr& timing, const mojom::FrameMetadataPtr& metadata, mojom::PageLoadFeaturesPtr new_features, std::vector<mojom::ResourceDataUpdatePtr> resources, const mojom::FrameRenderDataUpdate& render_data, const mojom::CpuTimingPtr& cpu_timing, mojom::DeferredResourceCountsPtr new_deferred_resource_data, mojom::InputTimingPtr new_input_timing, const blink::MobileFriendliness& mobile_friendliness) override; void SetUpSmoothnessReporting( base::ReadOnlySharedMemoryRegion shared_memory) override; private: PageTimingValidator* const validator_; DISALLOW_COPY_AND_ASSIGN(FakePageTimingSender); }; } // namespace page_load_metrics #endif // COMPONENTS_PAGE_LOAD_METRICS_RENDERER_FAKE_PAGE_TIMING_SENDER_H_
2,293
3,834
package org.enso.table.parsing; import java.time.LocalTime; import java.util.Locale; public class TimeParser extends BaseTimeParser { public TimeParser(String[] formats, Locale locale) { super(formats, locale, LocalTime::parse); } }
79
945
<filename>Modules/Core/Common/src/itkPlatformMultiThreader.cxx<gh_stars>100-1000 /*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) <NAME>, <NAME>, <NAME> * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkPlatformMultiThreader.h" #include "itkNumericTraits.h" #include <algorithm> #include <iostream> #include <string> #include <algorithm> #if defined(ITK_USE_PTHREADS) # include "itkPlatformMultiThreaderPosix.cxx" #elif defined(ITK_USE_WIN32_THREADS) # include "itkPlatformMultiThreaderWindows.cxx" #else # include "itkPlatformMultiThreaderSingle.cxx" #endif namespace itk { PlatformMultiThreader::PlatformMultiThreader() { for (ThreadIdType i = 0; i < ITK_MAX_THREADS; ++i) { m_ThreadInfoArray[i].WorkUnitID = i; m_ThreadInfoArray[i].ActiveFlag = nullptr; m_ThreadInfoArray[i].ActiveFlagLock = nullptr; #if !defined(ITK_LEGACY_REMOVE) m_MultipleMethod[i] = nullptr; m_MultipleData[i] = nullptr; #endif m_SpawnedThreadActiveFlag[i] = 0; m_SpawnedThreadActiveFlagLock[i] = nullptr; m_SpawnedThreadInfoArray[i].WorkUnitID = i; } } PlatformMultiThreader::~PlatformMultiThreader() = default; void PlatformMultiThreader::SetMaximumNumberOfThreads(ThreadIdType numberOfThreads) { Superclass::SetMaximumNumberOfThreads(numberOfThreads); Superclass::SetNumberOfWorkUnits(this->GetMaximumNumberOfThreads()); } void PlatformMultiThreader::SetNumberOfWorkUnits(ThreadIdType numberOfWorkUnits) { this->SetMaximumNumberOfThreads(numberOfWorkUnits); } void PlatformMultiThreader::SetSingleMethod(ThreadFunctionType f, void * data) { m_SingleMethod = f; m_SingleData = data; } #if !defined(ITK_LEGACY_REMOVE) // Set one of the user defined methods that will be run on NumberOfWorkUnits // threads when MultipleMethodExecute is called. This method should be // called with index = 0, 1, .., NumberOfWorkUnits-1 to set up all the // required user defined methods void PlatformMultiThreader::SetMultipleMethod(ThreadIdType index, ThreadFunctionType f, void * data) { // You can only set the method for 0 through NumberOfWorkUnits-1 if (index >= m_NumberOfWorkUnits) { itkExceptionMacro(<< "Can't set method " << index << " with a thread count of " << m_NumberOfWorkUnits); } else { m_MultipleMethod[index] = f; m_MultipleData[index] = data; } } #endif void PlatformMultiThreader::SingleMethodExecute() { ThreadIdType thread_loop = 0; ThreadProcessIdType process_id[ITK_MAX_THREADS]; if (!m_SingleMethod) { itkExceptionMacro(<< "No single method set!"); } // obey the global maximum number of threads limit m_NumberOfWorkUnits = std::min(MultiThreaderBase::GetGlobalMaximumNumberOfThreads(), m_NumberOfWorkUnits); // Init process_id table because a valid process_id (i.e., non-zero), is // checked in the WaitForSingleMethodThread loops for (thread_loop = 1; thread_loop < m_NumberOfWorkUnits; ++thread_loop) { process_id[thread_loop] = ITK_DEFAULT_THREAD_ID; } // Spawn a set of threads through the SingleMethodProxy. Exceptions // thrown from a thread will be caught by the SingleMethodProxy. A // naive mechanism is in place for determining whether a thread // threw an exception. // // Thanks to <NAME> for suggestions on how to catch // exceptions thrown by threads. bool exceptionOccurred = false; std::string exceptionDetails; try { for (thread_loop = 1; thread_loop < m_NumberOfWorkUnits; ++thread_loop) { m_ThreadInfoArray[thread_loop].UserData = m_SingleData; m_ThreadInfoArray[thread_loop].NumberOfWorkUnits = m_NumberOfWorkUnits; m_ThreadInfoArray[thread_loop].ThreadFunction = m_SingleMethod; process_id[thread_loop] = this->SpawnDispatchSingleMethodThread(&m_ThreadInfoArray[thread_loop]); } } catch (std::exception & e) { // get the details of the exception to rethrow them exceptionDetails = e.what(); // If creation of any thread failed, we must make sure that all // threads are correctly cleaned exceptionOccurred = true; } catch (...) { // If creation of any thread failed, we must make sure that all // threads are correctly cleaned exceptionOccurred = true; } // Now, the parent thread calls this->SingleMethod() itself // // try { m_ThreadInfoArray[0].UserData = m_SingleData; m_ThreadInfoArray[0].NumberOfWorkUnits = m_NumberOfWorkUnits; m_SingleMethod((void *)(&m_ThreadInfoArray[0])); } catch (ProcessAborted &) { // Need cleanup and rethrow ProcessAborted // close down other threads for (thread_loop = 1; thread_loop < m_NumberOfWorkUnits; ++thread_loop) { try { this->SpawnWaitForSingleMethodThread(process_id[thread_loop]); } catch (...) {} } // rethrow throw; } catch (std::exception & e) { // get the details of the exception to rethrow them exceptionDetails = e.what(); // if this method fails, we must make sure all threads are // correctly cleaned exceptionOccurred = true; } catch (...) { // if this method fails, we must make sure all threads are // correctly cleaned exceptionOccurred = true; } // The parent thread has finished this->SingleMethod() - so now it // waits for each of the other processes to exit for (thread_loop = 1; thread_loop < m_NumberOfWorkUnits; ++thread_loop) { try { this->SpawnWaitForSingleMethodThread(process_id[thread_loop]); if (m_ThreadInfoArray[thread_loop].ThreadExitCode != WorkUnitInfo::ThreadExitCodeEnum::SUCCESS) { exceptionOccurred = true; } } catch (std::exception & e) { // get the details of the exception to rethrow them exceptionDetails = e.what(); exceptionOccurred = true; } catch (...) { exceptionOccurred = true; } } if (exceptionOccurred) { if (exceptionDetails.empty()) { itkExceptionMacro("Exception occurred during SingleMethodExecute"); } else { itkExceptionMacro(<< "Exception occurred during SingleMethodExecute" << std::endl << exceptionDetails); } } } // Print method for the multithreader void PlatformMultiThreader::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } } // namespace itk
2,460
892
{ "schema_version": "1.2.0", "id": "GHSA-m3p6-3gv6-4226", "modified": "2021-12-21T00:00:56Z", "published": "2021-12-17T00:00:39Z", "aliases": [ "CVE-2020-18984" ], "details": "A reflected cross-site scripting (XSS) vulnerability in the zimbraAdmin/public/secureRequest.jsp component of Zimbra Collaboration 8.8.12 allows unauthenticated attackers to execute arbitrary web scripts or HTML via a host header injection.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2020-18984" }, { "type": "WEB", "url": "https://github.com/buxu/bug/issues/2" } ], "database_specific": { "cwe_ids": [ "CWE-79" ], "severity": "MODERATE", "github_reviewed": false } }
362
672
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from collections import OrderedDict import fnmatch import os import regex import sys class attrdict(dict): __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ def parse_args(): parser = argparse.ArgumentParser(description="Update license headers") parser.add_argument("--header", default="license.header", help="header file") parser.add_argument( "--extra", default=80, help="extra characters past beginning of file to look for header", ) parser.add_argument( "--editdist", default=12, type=int, help="max edit distance between headers" ) parser.add_argument( "--remove", default=False, action="store_true", help="remove the header" ) parser.add_argument( "--cslash", default=False, action="store_true", help='use C slash "//" style comments', ) parser.add_argument( "-v", default=False, action="store_true", dest="verbose", help="verbose output" ) group = parser.add_mutually_exclusive_group() group.add_argument( "-k", default=False, action="store_true", dest="check", help="check headers" ) group.add_argument( "-i", default=False, action="store_true", dest="inplace", help="edit file inplace", ) parser.add_argument("files", metavar="FILES", nargs="+", help="files to process") return parser.parse_args() def file_read(filename): with open(filename) as file: return file.read() def file_lines(filename): return file_read(filename).rstrip().split("\n") def wrapper(prefix, leader, suffix, header): return prefix + "\n".join([leader + line for line in header]) + suffix def wrapper_chpp(header, args): if args.cslash: return wrapper("", "//", "\n", header) else: return wrapper("/*\n", " *", "\n */\n", header) def wrapper_hash(header, args): return wrapper("", "#", "\n", header) file_types = OrderedDict( { "CMakeLists.txt": attrdict({"wrapper": wrapper_hash, "hashbang": False}), "Makefile": attrdict({"wrapper": wrapper_hash, "hashbang": False}), "*.cpp": attrdict({"wrapper": wrapper_chpp, "hashbang": False}), "*.dockfile": attrdict({"wrapper": wrapper_hash, "hashbang": False}), "*.h": attrdict({"wrapper": wrapper_chpp, "hashbang": False}), "*.inc": attrdict({"wrapper": wrapper_chpp, "hashbang": False}), "*.java": attrdict({"wrapper": wrapper_chpp, "hashbang": False}), "*.prolog": attrdict({"wrapper": wrapper_chpp, "hashbang": False}), "*.py": attrdict({"wrapper": wrapper_hash, "hashbang": True}), "*.sh": attrdict({"wrapper": wrapper_hash, "hashbang": True}), "*.thrift": attrdict({"wrapper": wrapper_chpp, "hashbang": False}), "*.txt": attrdict({"wrapper": wrapper_hash, "hashbang": True}), "*.yml": attrdict({"wrapper": wrapper_hash, "hashbang": False}), } ) file_pattern = regex.compile( "|".join(["^" + fnmatch.translate(type) + "$" for type in file_types.keys()]) ) def get_filename(filename): return os.path.basename(filename) def get_fileextn(filename): split = os.path.splitext(filename) if len(split) <= 1: return "" return split[-1] def get_wrapper(filename): if filename in file_types: return file_types[filename] return file_types["*" + get_fileextn(filename)] def message(file, string): if file: print(string, file=file) def main(): fail = False log_to = None args = parse_args() if args.verbose: log_to = sys.stderr if args.check: log_to = None if args.verbose: log_to = sys.stdout header_text = file_lines(args.header) if len(args.files) == 1 and args.files[0] == "-": files = [file.strip() for file in sys.stdin.readlines()] else: files = args.files for filepath in files: filename = get_filename(filepath) matched = file_pattern.match(filename) if not matched: message(log_to, "Skip : " + filepath) continue content = file_read(filepath) wrap = get_wrapper(filename) header_comment = wrap.wrapper(header_text, args) start = 0 end = 0 # Look for an exact substr match # found = content.find(header_comment, 0, len(header_comment) + args.extra) if found >= 0: if not args.remove: message(log_to, "OK : " + filepath) continue start = found end = found + len(header_comment) else: # Look for a fuzzy match in the first 60 chars # found = regex.search( "(?be)(%s){e<=%d}" % (regex.escape(header_comment[0:60]), 6), content[0 : 80 + args.extra], ) if found: fuzzy = regex.compile( "(?be)(%s){e<=%d}" % (regex.escape(header_comment), args.editdist) ) # If the first 80 chars match - try harder for the rest of the header # found = fuzzy.search( content[0 : len(header_comment) + args.extra], found.start() ) if found: start = found.start() end = found.end() if args.remove: if start == 0 and end == 0: if not args.inplace: print(content, end="") message(log_to, "OK : " + filepath) continue # If removing the header text, zero it out there. header_comment = "" message(log_to, "Fix : " + filepath) if args.check: fail = True continue # Remove any partially matching header # content = content[0:start] + content[end:] if wrap.hashbang: search = regex.search("^#!.*\n", content) if search: content = ( content[search.start() : search.end()] + header_comment + content[search.end() :] ) else: content = header_comment + content else: content = header_comment + content if args.inplace: with open(filepath, "w") as file: print(content, file=file, end="") else: print(content, end="") if fail: return 1 return 0 if __name__ == "__main__": sys.exit(main())
3,231
556
""" Smoke Plume Hot smoke is emitted from a circular region at the bottom. The simulation computes the resulting air flow in a closed box. """ from phi.flow import * DOMAIN = dict(x=64, y=64, bounds=Box[0:100, 0:100]) velocity = StaggeredGrid((0, 0), extrapolation.ZERO, **DOMAIN) # or use CenteredGrid smoke = CenteredGrid(0, extrapolation.BOUNDARY, x=200, y=200, bounds=DOMAIN['bounds']) INFLOW = 0.2 * CenteredGrid(SoftGeometryMask(Sphere(center=(50, 10), radius=5)), extrapolation.ZERO, resolution=smoke.resolution, bounds=smoke.bounds) pressure = None for _ in view(smoke, velocity, 'pressure', play=False, namespace=globals()).range(warmup=1): smoke = advect.mac_cormack(smoke, velocity, 1) + INFLOW buoyancy_force = smoke * (0, 0.1) @ velocity # resamples smoke to velocity sample points velocity = advect.semi_lagrangian(velocity, velocity, 1) + buoyancy_force velocity, pressure = fluid.make_incompressible(velocity, (), Solve('auto', 1e-5, 0, x0=pressure))
345
348
{"nom":"Sainte-Euphรฉmie","circ":"2รจme circonscription","dpt":"Ain","inscrits":1100,"abs":654,"votants":446,"blancs":28,"nuls":15,"exp":403,"res":[{"nuance":"MDM","nom":"<NAME>","voix":252},{"nuance":"LR","nom":"<NAME>","voix":151}]}
94
435
<reponame>glasnt/data { "copyright_text": "CC-BY-NC-SA 4.0", "description": "Welcome back to PyConline AU 2021!\n\nProgram: http://2021.pycon.org.au/program\nRegister: http://2021.pycon.org.au/attend", "duration": 99, "language": "eng", "recorded": "2021-09-11", "related_urls": [ { "label": "Conference schedule", "url": "https://2021.pycon.org.au/program/" }, { "label": "http://2021.pycon.org.au/attend", "url": "http://2021.pycon.org.au/attend" }, { "label": "http://2021.pycon.org.au/program", "url": "http://2021.pycon.org.au/program" } ], "speakers": [ "<NAME>" ], "tags": [ "australia", "conference", "programming", "python" ], "thumbnail_url": "https://i.ytimg.com/vi_webp/x6CUKf5dhLw/maxresdefault.webp", "title": "Welcome to PyConline AU 2021", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=x6CUKf5dhLw" } ] }
467
3,259
import base64 import http.server as SimpleHTTPServer import select import socket import socketserver as SocketServer import threading from urllib.request import urlopen def pipe_sockets(sock1, sock2, timeout): """Pipe data from one socket to another and vice-versa.""" sockets = [sock1, sock2] try: while True: rlist, _, xlist = select.select(sockets, [], sockets, timeout) if xlist: break for sock in rlist: data = sock.recv(8096) if not data: # disconnected break other = next(s for s in sockets if s is not sock) other.sendall(data) except IOError: pass finally: for sock in sockets: sock.close() class Future: # concurrent.futures.Future docs say that they shouldn't be instantiated # directly, so this is a simple implementation which mimics the Future # which can safely be instantiated! def __init__(self): self._event = threading.Event() self._result = None self._exc = None def result(self, timeout=None): if not self._event.wait(timeout): raise AssertionError("Future timed out") if self._exc is not None: raise self._exc return self._result def set_result(self, result): self._result = result self._event.set() def set_exception(self, exception): self._exc = exception self._event.set() class ProxyServerThread(threading.Thread): spinup_timeout = 10 def __init__(self, timeout=None): self.proxy_host = 'localhost' self.proxy_port = None # randomly selected by OS self.timeout = timeout self.proxy_server = None self.socket_created_future = Future() self.requests = [] self.auth = None super().__init__() self.daemon = True def reset(self): self.requests.clear() self.auth = None def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop() self.join() def set_auth(self, username, password): self.auth = "%s:%s" % (username, password) def get_proxy_url(self, with_scheme=True): assert self.socket_created_future.result(self.spinup_timeout) if self.auth: auth = "%s@" % self.auth else: auth = "" if with_scheme: scheme = "http://" else: scheme = "" return "%s%s%s:%s" % (scheme, auth, self.proxy_host, self.proxy_port) def run(self): assert not self.proxy_server, ("This class is not reentrable. " "Please create a new instance.") requests = self.requests proxy_thread = self class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): timeout = self.timeout def check_auth(self): if proxy_thread.auth is not None: auth_header = self.headers.get('Proxy-Authorization') b64_auth = base64.standard_b64encode( proxy_thread.auth.encode() ).decode() expected_auth = "Basic %s" % b64_auth if auth_header != expected_auth: self.send_response(401) self.send_header('Connection', 'close') self.end_headers() self.wfile.write( ( "not authenticated. Expected %r, received %r" % (expected_auth, auth_header) ).encode() ) self.connection.close() return False return True def do_GET(self): if not self.check_auth(): return requests.append(self.path) req = urlopen(self.path, timeout=self.timeout) self.send_response(req.getcode()) content_type = req.info().get('content-type', None) if content_type: self.send_header('Content-Type', content_type) self.send_header('Connection', 'close') self.end_headers() self.copyfile(req, self.wfile) self.connection.close() req.close() def do_CONNECT(self): if not self.check_auth(): return requests.append(self.path) # Make a raw TCP connection to the target server host, port = self.path.split(':') try: addr = host, int(port) other_connection = \ socket.create_connection(addr, timeout=self.timeout) except socket.error: self.send_error(502, 'Bad gateway') return # Respond that a tunnel has been created self.send_response(200) self.send_header('Connection', 'close') self.end_headers() pipe_sockets(self.connection, # it closes sockets other_connection, self.timeout) # ThreadingTCPServer offloads connections to separate threads, so # the serve_forever loop doesn't block until connection is closed # (unlike TCPServer). This allows to shutdown the serve_forever loop # even if there's an open connection. try: self.proxy_server = SocketServer.ThreadingTCPServer( (self.proxy_host, 0), Proxy ) # don't hang if there're some open connections self.proxy_server.daemon_threads = True self.proxy_port = self.proxy_server.server_address[1] except Exception as e: self.socket_created_future.set_exception(e) raise else: self.socket_created_future.set_result(True) self.proxy_server.serve_forever() def stop(self): self.proxy_server.shutdown() # stop serve_forever() self.proxy_server.server_close() class HttpServerThread(threading.Thread): spinup_timeout = 10 def __init__(self, timeout=None): self.server_host = 'localhost' self.server_port = None # randomly selected by OS self.timeout = timeout self.http_server = None self.socket_created_future = Future() super(HttpServerThread, self).__init__() self.daemon = True def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop() self.join() def get_server_url(self): assert self.socket_created_future.result(self.spinup_timeout) return "http://%s:%s" % (self.server_host, self.server_port) def run(self): assert not self.http_server, ("This class is not reentrable. " "Please create a new instance.") class Server(SimpleHTTPServer.SimpleHTTPRequestHandler): timeout = self.timeout def do_GET(self): if self.path == "/": self.send_response(200) self.send_header('Connection', 'close') self.end_headers() self.wfile.write(b"Hello world") elif self.path == "/json": self.send_response(200) self.send_header('Content-type', 'application/json') self.send_header('Connection', 'close') self.end_headers() self.wfile.write(b'{"hello":"world"}') elif self.path == "/json/plain": self.send_response(200) self.send_header('Content-type', 'text/plain;charset=utf-8') self.send_header('Connection', 'close') self.end_headers() self.wfile.write(b'{"hello":"world"}') else: self.send_response(404) self.send_header('Connection', 'close') self.send_header('X-test-header', 'hello') self.end_headers() self.wfile.write(b"Not found") self.connection.close() # ThreadingTCPServer offloads connections to separate threads, so # the serve_forever loop doesn't block until connection is closed # (unlike TCPServer). This allows to shutdown the serve_forever loop # even if there's an open connection. try: self.http_server = SocketServer.ThreadingTCPServer( (self.server_host, 0), Server ) # don't hang if there're some open connections self.http_server.daemon_threads = True self.server_port = self.http_server.server_address[1] except Exception as e: self.socket_created_future.set_exception(e) raise else: self.socket_created_future.set_result(True) self.http_server.serve_forever() def stop(self): self.http_server.shutdown() # stop serve_forever() self.http_server.server_close()
4,772
1,205
<filename>qutip/control/__init__.py<gh_stars>1000+ from qutip.control.grape import *
34
1,013
/*! @authors <NAME> (<EMAIL>) @date 2014-2020 @copyright BSD-3-Clause */ #pragma once #include <pyclustering/interface/pyclustering_package.hpp> #include <pyclustering/definitions.hpp> /** * * @brief Clustering algorithm CURE returns allocated clusters. * @details Caller should destroy returned clustering data using 'cure_data_destroy' when * it is not required anymore. * * @param[in] sample: input data for clustering. * @param[in] number_clusters: number of clusters that should be allocated. * @param[in] number_repr_points: number of representation points for each cluster. * @param[in] compression: coefficient defines level of shrinking of representation * points toward the mean of the new created cluster after merging on each step. * * @return Returns pointer to cure data - clustering result that can be used for obtaining * allocated clusters, representative points and means of each cluster. * */ extern "C" DECLARATION void * cure_algorithm(const pyclustering_package * const sample, const size_t number_clusters, const size_t number_repr_points, const double compression); /** * * @brief Destroys CURE clustering data (clustering results). * * @param[in] pointer_cure_data: pointer to CURE clustering data. * */ extern "C" DECLARATION void cure_data_destroy(void * pointer_cure_data); /** * * @brief Returns allocated clusters by CURE algorithm. * @details Caller should destroy returned result in 'pyclustering_package'. * * @param[in] pointer_cure_data: pointer to CURE clustering data. * * @return Package where results of clustering are stored. * */ extern "C" DECLARATION pyclustering_package * cure_get_clusters(void * pointer_cure_data); /** * * @brief Returns CURE representors of each cluster. * @details Caller should destroy returned result in 'pyclustering_package'. * * @param[in] pointer_cure_data: pointer to CURE clustering data. * * @return Package where representative points for each cluster are stored. * */ extern "C" DECLARATION pyclustering_package * cure_get_representors(void * pointer_cure_data); /** * * @brief Returns CURE mean points of each cluster. * @details Caller should destroy returned result in 'pyclustering_package'. * * @param[in] pointer_cure_data: pointer to CURE clustering data. * * @return Package where mean point of each cluster is stored. * */ extern "C" DECLARATION pyclustering_package * cure_get_means(void * pointer_cure_data);
774
15,092
{ "title": "Third party libraries", "slug": "third-party", "description": "There are several 3rd party libraries that you can use to add additional functionality and features to your BootstrapVue project." }
56
912
# -*- coding: utf-8 -*- ''' # Copyright (c) 2015 Microsoft Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # This file was generated and any changes will be overwritten. ''' from __future__ import unicode_literals from .permission_request import PermissionRequest from ..request_builder_base import RequestBuilderBase class PermissionRequestBuilder(RequestBuilderBase): def __init__(self, request_url, client): """Initialize the PermissionRequestBuilder Args: request_url (str): The url to perform the PermissionRequest on client (:class:`OneDriveClient<onedrivesdk.request.one_drive_client.OneDriveClient>`): The client which will be used for the request """ super(PermissionRequestBuilder, self).__init__(request_url, client) def request(self, expand=None, select=None, options=None): """Builds the PermissionRequest Args: expand (str): Default None, comma-seperated list of relationships to expand in the response. select (str): Default None, comma-seperated list of properties to include in the response. options (list of :class:`Option<onedrivesdk.options.Option>`): A list of options to pass into the request. Defaults to None. Returns: :class:`PermissionRequest<onedrivesdk.request.permission_request.PermissionRequest>`: The PermissionRequest """ req = PermissionRequest(self._request_url, self._client, options) req._set_query_options(expand=expand, select=select) return req def delete(self): """Deletes the specified Permission.""" self.request().delete() def get(self): """Gets the specified Permission. Returns: :class:`Permission<onedrivesdk.model.permission.Permission>`: The Permission. """ return self.request().get() def update(self, permission): """Updates the specified Permission. Args: permission (:class:`Permission<onedrivesdk.model.permission.Permission>`): The Permission to update. Returns: :class:`Permission<onedrivesdk.model.permission.Permission>`: The updated Permission """ return self.request().update(permission)
1,265
323
<gh_stars>100-1000 #ifndef _ROS_baxter_core_msgs_EndEffectorState_h #define _ROS_baxter_core_msgs_EndEffectorState_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "ros/time.h" namespace baxter_core_msgs { class EndEffectorState : public ros::Msg { public: typedef ros::Time _timestamp_type; _timestamp_type timestamp; typedef uint32_t _id_type; _id_type id; typedef uint8_t _enabled_type; _enabled_type enabled; typedef uint8_t _calibrated_type; _calibrated_type calibrated; typedef uint8_t _ready_type; _ready_type ready; typedef uint8_t _moving_type; _moving_type moving; typedef uint8_t _gripping_type; _gripping_type gripping; typedef uint8_t _missed_type; _missed_type missed; typedef uint8_t _error_type; _error_type error; typedef uint8_t _reverse_type; _reverse_type reverse; typedef float _position_type; _position_type position; typedef float _force_type; _force_type force; typedef const char* _state_type; _state_type state; typedef const char* _command_type; _command_type command; typedef const char* _command_sender_type; _command_sender_type command_sender; typedef uint32_t _command_sequence_type; _command_sequence_type command_sequence; enum { STATE_FALSE = 0 }; enum { STATE_TRUE = 1 }; enum { STATE_UNKNOWN = 2 }; enum { POSITION_CLOSED = 0.0 }; enum { POSITION_OPEN = 100.0 }; enum { FORCE_MIN = 0.0 }; enum { FORCE_MAX = 100.0 }; EndEffectorState(): timestamp(), id(0), enabled(0), calibrated(0), ready(0), moving(0), gripping(0), missed(0), error(0), reverse(0), position(0), force(0), state(""), command(""), command_sender(""), command_sequence(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; *(outbuffer + offset + 0) = (this->timestamp.sec >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->timestamp.sec >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->timestamp.sec >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->timestamp.sec >> (8 * 3)) & 0xFF; offset += sizeof(this->timestamp.sec); *(outbuffer + offset + 0) = (this->timestamp.nsec >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->timestamp.nsec >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->timestamp.nsec >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->timestamp.nsec >> (8 * 3)) & 0xFF; offset += sizeof(this->timestamp.nsec); *(outbuffer + offset + 0) = (this->id >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->id >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->id >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->id >> (8 * 3)) & 0xFF; offset += sizeof(this->id); *(outbuffer + offset + 0) = (this->enabled >> (8 * 0)) & 0xFF; offset += sizeof(this->enabled); *(outbuffer + offset + 0) = (this->calibrated >> (8 * 0)) & 0xFF; offset += sizeof(this->calibrated); *(outbuffer + offset + 0) = (this->ready >> (8 * 0)) & 0xFF; offset += sizeof(this->ready); *(outbuffer + offset + 0) = (this->moving >> (8 * 0)) & 0xFF; offset += sizeof(this->moving); *(outbuffer + offset + 0) = (this->gripping >> (8 * 0)) & 0xFF; offset += sizeof(this->gripping); *(outbuffer + offset + 0) = (this->missed >> (8 * 0)) & 0xFF; offset += sizeof(this->missed); *(outbuffer + offset + 0) = (this->error >> (8 * 0)) & 0xFF; offset += sizeof(this->error); *(outbuffer + offset + 0) = (this->reverse >> (8 * 0)) & 0xFF; offset += sizeof(this->reverse); union { float real; uint32_t base; } u_position; u_position.real = this->position; *(outbuffer + offset + 0) = (u_position.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_position.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_position.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_position.base >> (8 * 3)) & 0xFF; offset += sizeof(this->position); union { float real; uint32_t base; } u_force; u_force.real = this->force; *(outbuffer + offset + 0) = (u_force.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_force.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_force.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_force.base >> (8 * 3)) & 0xFF; offset += sizeof(this->force); uint32_t length_state = strlen(this->state); varToArr(outbuffer + offset, length_state); offset += 4; memcpy(outbuffer + offset, this->state, length_state); offset += length_state; uint32_t length_command = strlen(this->command); varToArr(outbuffer + offset, length_command); offset += 4; memcpy(outbuffer + offset, this->command, length_command); offset += length_command; uint32_t length_command_sender = strlen(this->command_sender); varToArr(outbuffer + offset, length_command_sender); offset += 4; memcpy(outbuffer + offset, this->command_sender, length_command_sender); offset += length_command_sender; *(outbuffer + offset + 0) = (this->command_sequence >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->command_sequence >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->command_sequence >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->command_sequence >> (8 * 3)) & 0xFF; offset += sizeof(this->command_sequence); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; this->timestamp.sec = ((uint32_t) (*(inbuffer + offset))); this->timestamp.sec |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); this->timestamp.sec |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); this->timestamp.sec |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->timestamp.sec); this->timestamp.nsec = ((uint32_t) (*(inbuffer + offset))); this->timestamp.nsec |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); this->timestamp.nsec |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); this->timestamp.nsec |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->timestamp.nsec); this->id = ((uint32_t) (*(inbuffer + offset))); this->id |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); this->id |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); this->id |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->id); this->enabled = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->enabled); this->calibrated = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->calibrated); this->ready = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->ready); this->moving = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->moving); this->gripping = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->gripping); this->missed = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->missed); this->error = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->error); this->reverse = ((uint8_t) (*(inbuffer + offset))); offset += sizeof(this->reverse); union { float real; uint32_t base; } u_position; u_position.base = 0; u_position.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_position.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_position.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_position.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->position = u_position.real; offset += sizeof(this->position); union { float real; uint32_t base; } u_force; u_force.base = 0; u_force.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_force.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_force.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_force.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->force = u_force.real; offset += sizeof(this->force); uint32_t length_state; arrToVar(length_state, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_state; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_state-1]=0; this->state = (char *)(inbuffer + offset-1); offset += length_state; uint32_t length_command; arrToVar(length_command, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_command; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_command-1]=0; this->command = (char *)(inbuffer + offset-1); offset += length_command; uint32_t length_command_sender; arrToVar(length_command_sender, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_command_sender; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_command_sender-1]=0; this->command_sender = (char *)(inbuffer + offset-1); offset += length_command_sender; this->command_sequence = ((uint32_t) (*(inbuffer + offset))); this->command_sequence |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); this->command_sequence |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); this->command_sequence |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->command_sequence); return offset; } const char * getType(){ return "baxter_core_msgs/EndEffectorState"; }; const char * getMD5(){ return "ade777f069d738595bc19e246b8ec7a0"; }; }; } #endif
4,556
4,050
/* * Copyright 2020 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package azkaban.webapp.metrics; import azkaban.metrics.AzkabanAPIMetrics; import azkaban.utils.Props; /** * Defines all the metrics the Web server can emit. */ public interface WebMetrics { void setUp(final DataProvider dataProvider); void startReporting(final Props props); AzkabanAPIMetrics setUpAzkabanAPIMetrics(final String endpointUri); void markWebGetCall(); void markWebPostCall(); /** * DropWizard Gauges are instantaneous measurement of a value. * This interface defines the methods {@link WebMetrics} implementations will call to obtain * said measurements. */ interface DataProvider { int getNumberOfIdleServerThreads(); int getNumberOfServerThreads(); int getServerJobsQueueSize(); long getNumberOfQueuedFlows(); int getNumberOfRunningFlows(); long getNumberOfCurrentSessions(); long getNumberOfAgedQueuedFlows(); } }
433
775
""" Model templates registry. """ # Copyright (C) 2021 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions # and limitations under the License. import copy import glob import os import yaml from ote_sdk.entities.model_template import parse_model_template class Registry: """ Class that implements a model templates registry. """ def __init__(self, templates_dir=None, templates=None, experimental=False): if templates is None: if templates_dir is None: templates_dir = os.getenv("TEMPLATES_DIR") if templates_dir is None: raise RuntimeError("The templates_dir is not set.") template_filenames = glob.glob( os.path.join(templates_dir, "**", "template.yaml"), recursive=True ) if experimental: template_filenames.extend( glob.glob( os.path.join(templates_dir, "**", "template_experimental.yaml"), recursive=True, ) ) template_filenames = [os.path.abspath(p) for p in template_filenames] self.templates = [] for template_file in template_filenames: self.templates.append(parse_model_template(template_file)) else: self.templates = copy.deepcopy(templates) self.task_types = self.__collect_task_types(self.templates) @staticmethod def __collect_task_types(templates): return {template.task_type for template in templates} def filter(self, framework=None, task_type=None): """ Filters registry by framework and/or task type and returns filtered registry. """ templates = copy.deepcopy(self.templates) if framework is not None: templates = [ template for template in templates if template.framework.lower() == framework.lower() ] if task_type is not None: templates = [ template for template in templates if str(template.task_type).lower() == task_type.lower() ] return Registry(templates=templates) def get(self, template_id): """ Returns a model template with specified template_id. """ templates = [ template for template in self.templates if template.model_template_id == template_id ] if not templates: raise ValueError( f"Could not find a template with {template_id} in registry." ) return templates[0] def __str__(self): templates_infos = [ { "name": t.name, "id": t.model_template_id, "path": t.model_template_path, "task_type": str(t.task_type), } for t in self.templates ] return yaml.dump(templates_infos) def find_and_parse_model_template(path_or_id): """ In first function attempts to read a model template from disk under assumption that a path is passed. If the attempt is failed, it tries to find template in registry under assumption that an ID is passed. """ if os.path.exists(path_or_id): return parse_model_template(path_or_id) return Registry(".").get(path_or_id)
1,693
419
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include "tsl_format_export.h" typedef struct { char *src; char *dst; int is_slim; } env_t; void usage() { printf("Usage: app [option]\n"); printf("\t-i(src_path)\n"); printf("\t-o[dst_path]\n"); printf("\t-s slim thing mode\n"); } void print_env(env_t *env) { if (!env) { return; } printf("\nEnv\n"); printf("=========================================\n"); printf("SRC:%s\n", env->src ? env->src : "NULL"); printf("DST:%s\n", env->dst ? env->dst : "NULL"); printf("%s slim TSL mode\n", env->is_slim == 0 ? "not" : ""); printf("=========================================\n"); } void set_default(env_t *env) { if (!env) { return; } if (!env->dst) { env->dst = "conv.txt"; } } int main(int argc, char **argv) { int ret = -1; env_t env; int opt = 0; memset(&env, 0, sizeof(env_t)); while ((opt = getopt(argc, argv, "i:o::s")) != -1) { switch (opt) { case 'i': env.src = optarg; break; case 'o': env.dst = optarg; break; case 's': env.is_slim = 1; break; default: usage(); return 0; } } if (!env.src) { usage(); return 0; } set_default(&env); print_env(&env); if (tsl_format_convert(env.src, env.dst, env.is_slim) != 0) { TFormat_printf("[err] convert fail"); goto do_exit; } tsl_format_dump(env.dst); ret = 0; do_exit: return ret; }
928
1,019
<gh_stars>1000+ package com.roncoo.education.course.service.dao; import com.roncoo.education.course.service.dao.impl.mapper.entity.DicList; import com.roncoo.education.course.service.dao.impl.mapper.entity.DicListExample; import com.roncoo.education.util.base.Page; public interface DicListDao { int save(DicList record); int deleteById(Long id); int updateById(DicList record); DicList getById(Long id); Page<DicList> listForPage(int pageCurrent, int pageSize, DicListExample example); }
187
675
#include "Exception.h" #include "engine/core/log/Log.h" namespace Echo { Exception::Exception() : m_lineNum(0) { } Exception::Exception(const String& msg) : m_msg(msg) , m_lineNum(0) { } Exception::Exception(const String &msg, const String &filename, ui32 lineNum) : m_msg(msg) , m_filename(filename) , m_lineNum(0) { } Exception::~Exception() { } const String& Exception::getMessage() const { return m_msg; } void Exception::setMessage(const String& msg) { m_msg = msg; } const String& Exception::getFilename() const { return m_filename; } ui32 Exception::getLineNum() const { return m_lineNum; } void __EchoThrowException(const String& msg, const char* filename, ui32 lineNum) { EchoLogError("EchoThrowException[%s] file[%s] line[%d]", msg.c_str(), filename, lineNum); throw Exception(msg, filename, lineNum); }; }
349
12,536
// Copyright 2019 The gVisor 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 "test/syscalls/linux/socket_ipv4_datagram_based_socket_unbound.h" #include "gtest/gtest.h" #include "test/syscalls/linux/ip_socket_test_util.h" #include "test/util/capability_util.h" namespace gvisor { namespace testing { void IPv4DatagramBasedUnboundSocketTest::SetUp() { if (GetParam().type & SOCK_RAW) { SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability())); } } // Check that dropping a group membership that does not exist fails. TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastInvalidDrop) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); // Unregister from a membership that we didn't have. ip_mreq group = {}; group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress); group.imr_interface.s_addr = htonl(INADDR_LOOPBACK); EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &group, sizeof(group)), SyscallFailsWithErrno(EADDRNOTAVAIL)); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfZero) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreqn iface = {}; EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface, sizeof(iface)), SyscallSucceeds()); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfInvalidNic) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreqn iface = {}; iface.imr_ifindex = -1; EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface, sizeof(iface)), SyscallFailsWithErrno(EADDRNOTAVAIL)); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfInvalidAddr) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreq iface = {}; iface.imr_interface.s_addr = inet_addr("255.255.255"); EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface, sizeof(iface)), SyscallFailsWithErrno(EADDRNOTAVAIL)); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfSetShort) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); // Create a valid full-sized request. ip_mreqn iface = {}; iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()); // Send an optlen of 1 to check that optlen is enforced. EXPECT_THAT( setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface, 1), SyscallFailsWithErrno(EINVAL)); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfDefault) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); in_addr get = {}; socklen_t size = sizeof(get); ASSERT_THAT( getsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size), SyscallSucceeds()); EXPECT_EQ(size, sizeof(get)); EXPECT_EQ(get.s_addr, 0); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfDefaultReqn) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreqn get = {}; socklen_t size = sizeof(get); ASSERT_THAT( getsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size), SyscallSucceeds()); // getsockopt(IP_MULTICAST_IF) can only return an in_addr, so it treats the // first sizeof(struct in_addr) bytes of struct ip_mreqn as a struct in_addr. // Conveniently, this corresponds to the field ip_mreqn::imr_multiaddr. EXPECT_EQ(size, sizeof(in_addr)); // getsockopt(IP_MULTICAST_IF) will only return the interface address which // hasn't been set. EXPECT_EQ(get.imr_multiaddr.s_addr, 0); EXPECT_EQ(get.imr_address.s_addr, 0); EXPECT_EQ(get.imr_ifindex, 0); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfSetAddrGetReqn) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); in_addr set = {}; set.s_addr = htonl(INADDR_LOOPBACK); ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &set, sizeof(set)), SyscallSucceeds()); ip_mreqn get = {}; socklen_t size = sizeof(get); ASSERT_THAT( getsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size), SyscallSucceeds()); // getsockopt(IP_MULTICAST_IF) can only return an in_addr, so it treats the // first sizeof(struct in_addr) bytes of struct ip_mreqn as a struct in_addr. // Conveniently, this corresponds to the field ip_mreqn::imr_multiaddr. EXPECT_EQ(size, sizeof(in_addr)); EXPECT_EQ(get.imr_multiaddr.s_addr, set.s_addr); EXPECT_EQ(get.imr_address.s_addr, 0); EXPECT_EQ(get.imr_ifindex, 0); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfSetReqAddrGetReqn) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreq set = {}; set.imr_interface.s_addr = htonl(INADDR_LOOPBACK); ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &set, sizeof(set)), SyscallSucceeds()); ip_mreqn get = {}; socklen_t size = sizeof(get); ASSERT_THAT( getsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size), SyscallSucceeds()); // getsockopt(IP_MULTICAST_IF) can only return an in_addr, so it treats the // first sizeof(struct in_addr) bytes of struct ip_mreqn as a struct in_addr. // Conveniently, this corresponds to the field ip_mreqn::imr_multiaddr. EXPECT_EQ(size, sizeof(in_addr)); EXPECT_EQ(get.imr_multiaddr.s_addr, set.imr_interface.s_addr); EXPECT_EQ(get.imr_address.s_addr, 0); EXPECT_EQ(get.imr_ifindex, 0); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfSetNicGetReqn) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreqn set = {}; set.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()); ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &set, sizeof(set)), SyscallSucceeds()); ip_mreqn get = {}; socklen_t size = sizeof(get); ASSERT_THAT( getsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size), SyscallSucceeds()); EXPECT_EQ(size, sizeof(in_addr)); EXPECT_EQ(get.imr_multiaddr.s_addr, 0); EXPECT_EQ(get.imr_address.s_addr, 0); EXPECT_EQ(get.imr_ifindex, 0); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfSetAddr) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); in_addr set = {}; set.s_addr = htonl(INADDR_LOOPBACK); ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &set, sizeof(set)), SyscallSucceeds()); in_addr get = {}; socklen_t size = sizeof(get); ASSERT_THAT( getsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size), SyscallSucceeds()); EXPECT_EQ(size, sizeof(get)); EXPECT_EQ(get.s_addr, set.s_addr); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfSetReqAddr) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreq set = {}; set.imr_interface.s_addr = htonl(INADDR_LOOPBACK); ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &set, sizeof(set)), SyscallSucceeds()); in_addr get = {}; socklen_t size = sizeof(get); ASSERT_THAT( getsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size), SyscallSucceeds()); EXPECT_EQ(size, sizeof(get)); EXPECT_EQ(get.s_addr, set.imr_interface.s_addr); } TEST_P(IPv4DatagramBasedUnboundSocketTest, IpMulticastIfSetNic) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreqn set = {}; set.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()); ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &set, sizeof(set)), SyscallSucceeds()); in_addr get = {}; socklen_t size = sizeof(get); ASSERT_THAT( getsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &get, &size), SyscallSucceeds()); EXPECT_EQ(size, sizeof(get)); EXPECT_EQ(get.s_addr, 0); } TEST_P(IPv4DatagramBasedUnboundSocketTest, TestJoinGroupNoIf) { // TODO(b/185517803): Fix for native test. SKIP_IF(!IsRunningOnGvisor()); auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreqn group = {}; group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress); EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group)), SyscallFailsWithErrno(ENODEV)); } TEST_P(IPv4DatagramBasedUnboundSocketTest, TestJoinGroupInvalidIf) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); ip_mreqn group = {}; group.imr_address.s_addr = inet_addr("255.255.255"); group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress); EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group)), SyscallFailsWithErrno(ENODEV)); } // Check that multiple memberships are not allowed on the same socket. TEST_P(IPv4DatagramBasedUnboundSocketTest, TestMultipleJoinsOnSingleSocket) { auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket()); auto fd = socket1->get(); ip_mreqn group = {}; group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress); group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()); EXPECT_THAT( setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group)), SyscallSucceeds()); EXPECT_THAT( setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group)), SyscallFailsWithErrno(EADDRINUSE)); } } // namespace testing } // namespace gvisor
4,813
14,425
<reponame>bzhaoopenstack/hadoop /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.federation.router; import java.io.IOException; import java.util.EnumSet; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.fs.CacheFlag; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedEntries; import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry; import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo; import org.apache.hadoop.hdfs.protocol.CachePoolEntry; import org.apache.hadoop.hdfs.protocol.CachePoolInfo; import org.apache.hadoop.hdfs.server.federation.resolver.ActiveNamenodeResolver; import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamespaceInfo; import org.apache.hadoop.hdfs.server.federation.resolver.RemoteLocation; import org.apache.hadoop.hdfs.server.namenode.NameNode; /** * Module that implements all the RPC calls in * {@link org.apache.hadoop.hdfs.protocol.ClientProtocol} related to Cache Admin * in the {@link RouterRpcServer}. */ public class RouterCacheAdmin { /** RPC server to receive client calls. */ private final RouterRpcServer rpcServer; /** RPC clients to connect to the Namenodes. */ private final RouterRpcClient rpcClient; /** Interface to identify the active NN for a nameservice or blockpool ID. */ private final ActiveNamenodeResolver namenodeResolver; public RouterCacheAdmin(RouterRpcServer server) { this.rpcServer = server; this.rpcClient = this.rpcServer.getRPCClient(); this.namenodeResolver = this.rpcClient.getNamenodeResolver(); } public long addCacheDirective(CacheDirectiveInfo path, EnumSet<CacheFlag> flags) throws IOException { rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true); final List<RemoteLocation> locations = rpcServer.getLocationsForPath(path.getPath().toString(), true, false); RemoteMethod method = new RemoteMethod("addCacheDirective", new Class<?>[] {CacheDirectiveInfo.class, EnumSet.class}, new RemoteParam(getRemoteMap(path, locations)), flags); Map<RemoteLocation, Long> response = rpcClient.invokeConcurrent(locations, method, false, false, long.class); return response.values().iterator().next(); } public void modifyCacheDirective(CacheDirectiveInfo directive, EnumSet<CacheFlag> flags) throws IOException { rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true); Path p = directive.getPath(); if (p != null) { final List<RemoteLocation> locations = rpcServer .getLocationsForPath(directive.getPath().toString(), true, false); RemoteMethod method = new RemoteMethod("modifyCacheDirective", new Class<?>[] {CacheDirectiveInfo.class, EnumSet.class}, new RemoteParam(getRemoteMap(directive, locations)), flags); rpcClient.invokeConcurrent(locations, method); return; } RemoteMethod method = new RemoteMethod("modifyCacheDirective", new Class<?>[] {CacheDirectiveInfo.class, EnumSet.class}, directive, flags); Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces(); rpcClient.invokeConcurrent(nss, method, false, false); } public void removeCacheDirective(long id) throws IOException { rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true); RemoteMethod method = new RemoteMethod("removeCacheDirective", new Class<?>[] {long.class}, id); Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces(); rpcClient.invokeConcurrent(nss, method, false, false); } public BatchedEntries<CacheDirectiveEntry> listCacheDirectives(long prevId, CacheDirectiveInfo filter) throws IOException { rpcServer.checkOperation(NameNode.OperationCategory.READ, true); if (filter.getPath() != null) { final List<RemoteLocation> locations = rpcServer .getLocationsForPath(filter.getPath().toString(), true, false); RemoteMethod method = new RemoteMethod("listCacheDirectives", new Class<?>[] {long.class, CacheDirectiveInfo.class}, prevId, new RemoteParam(getRemoteMap(filter, locations))); Map<RemoteLocation, BatchedEntries> response = rpcClient.invokeConcurrent( locations, method, false, false, BatchedEntries.class); return response.values().iterator().next(); } RemoteMethod method = new RemoteMethod("listCacheDirectives", new Class<?>[] {long.class, CacheDirectiveInfo.class}, prevId, filter); Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces(); Map<FederationNamespaceInfo, BatchedEntries> results = rpcClient .invokeConcurrent(nss, method, true, false, BatchedEntries.class); return results.values().iterator().next(); } public void addCachePool(CachePoolInfo info) throws IOException { rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true); RemoteMethod method = new RemoteMethod("addCachePool", new Class<?>[] {CachePoolInfo.class}, info); Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces(); rpcClient.invokeConcurrent(nss, method, true, false); } public void modifyCachePool(CachePoolInfo info) throws IOException { rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true); RemoteMethod method = new RemoteMethod("modifyCachePool", new Class<?>[] {CachePoolInfo.class}, info); Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces(); rpcClient.invokeConcurrent(nss, method, true, false); } public void removeCachePool(String cachePoolName) throws IOException { rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true); RemoteMethod method = new RemoteMethod("removeCachePool", new Class<?>[] {String.class}, cachePoolName); Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces(); rpcClient.invokeConcurrent(nss, method, true, false); } public BatchedEntries<CachePoolEntry> listCachePools(String prevKey) throws IOException { rpcServer.checkOperation(NameNode.OperationCategory.READ, true); RemoteMethod method = new RemoteMethod("listCachePools", new Class<?>[] {String.class}, prevKey); Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces(); Map<FederationNamespaceInfo, BatchedEntries> results = rpcClient .invokeConcurrent(nss, method, true, false, BatchedEntries.class); return results.values().iterator().next(); } /** * Returns a map with the CacheDirectiveInfo mapped to each location. * @param path CacheDirectiveInfo to be mapped to the locations. * @param locations the locations to map. * @return map with CacheDirectiveInfo mapped to the locations. */ private Map<RemoteLocation, CacheDirectiveInfo> getRemoteMap( CacheDirectiveInfo path, final List<RemoteLocation> locations) { final Map<RemoteLocation, CacheDirectiveInfo> dstMap = new HashMap<>(); Iterator<RemoteLocation> iterator = locations.iterator(); while (iterator.hasNext()) { dstMap.put(iterator.next(), path); } return dstMap; } }
2,611
1,353
/* * Copyright (c) 2017, <NAME> * 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 copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. */ package com.twelvemonkeys.imageio.plugins.tga; import com.twelvemonkeys.imageio.ImageWriterBase; import com.twelvemonkeys.imageio.util.IIOUtil; import com.twelvemonkeys.imageio.util.ImageTypeSpecifiers; import com.twelvemonkeys.io.LittleEndianDataOutputStream; import com.twelvemonkeys.io.enc.EncoderStream; import com.twelvemonkeys.lang.Validate; import javax.imageio.*; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageWriterSpi; import javax.imageio.stream.ImageOutputStream; import java.awt.*; import java.awt.color.ColorSpace; import java.awt.image.*; import java.io.DataOutput; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static com.twelvemonkeys.imageio.plugins.tga.TGAImageWriteParam.isRLE; import static com.twelvemonkeys.lang.Validate.notNull; /** * TGAImageWriter */ final class TGAImageWriter extends ImageWriterBase { TGAImageWriter(ImageWriterSpi provider) { super(provider); } @Override public IIOMetadata getDefaultImageMetadata(final ImageTypeSpecifier imageType, final ImageWriteParam param) { Validate.notNull(imageType, "imageType"); TGAHeader header = TGAHeader.from(imageType.createBufferedImage(1, 1), isRLE(param, null)); return new TGAMetadata(header, null); } @Override public IIOMetadata convertImageMetadata(final IIOMetadata inData, final ImageTypeSpecifier imageType, final ImageWriteParam param) { Validate.notNull(inData, "inData"); Validate.notNull(imageType, "imageType"); if (inData instanceof TGAMetadata) { return inData; } // TODO: Make metadata mutable, and do actual merge return getDefaultImageMetadata(imageType, param); } @Override public void setOutput(Object output) { super.setOutput(output); if (imageOutput != null) { imageOutput.setByteOrder(ByteOrder.LITTLE_ENDIAN); } } @Override public ImageWriteParam getDefaultWriteParam() { return new TGAImageWriteParam(getLocale()); } @Override public void write(final IIOMetadata streamMetadata, final IIOImage image, final ImageWriteParam param) throws IOException { assertOutput(); Validate.notNull(image, "image"); if (image.hasRaster()) { throw new UnsupportedOperationException("Raster not supported"); } final boolean compressed = isRLE(param, image.getMetadata()); RenderedImage renderedImage = image.getRenderedImage(); TGAHeader header = TGAHeader.from(renderedImage, compressed); header.write(imageOutput); processImageStarted(0); WritableRaster rowRaster = header.getPixelDepth() == 32 ? ImageTypeSpecifiers.createInterleaved(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {2, 1, 0, 3}, DataBuffer.TYPE_BYTE, true, false).createBufferedImage(renderedImage.getWidth(), 1).getRaster() : renderedImage.getSampleModel().getTransferType() == DataBuffer.TYPE_INT ? ImageTypeSpecifiers.createInterleaved(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {2, 1, 0}, DataBuffer.TYPE_BYTE, false, false).createBufferedImage(renderedImage.getWidth(), 1).getRaster() : ImageTypeSpecifier.createFromRenderedImage(renderedImage).createBufferedImage(renderedImage.getWidth(), 1).getRaster(); final DataBuffer buffer = rowRaster.getDataBuffer(); for (int tileY = 0; tileY < renderedImage.getNumYTiles(); tileY++) { for (int tileX = 0; tileX < renderedImage.getNumXTiles(); tileX++) { if (abortRequested()) { break; } // Wraps TYPE_INT rasters to TYPE_BYTE Raster raster = asByteRaster(renderedImage.getTile(tileX, tileY), renderedImage.getColorModel()); for (int y = 0; y < raster.getHeight(); y++) { if (abortRequested()) { break; } DataOutput imageOutput = compressed ? createRLEStream(header, this.imageOutput) : this.imageOutput; switch (buffer.getDataType()) { case DataBuffer.TYPE_BYTE: rowRaster.setDataElements(0, 0, raster.createChild(0, y, raster.getWidth(), 1, 0, 0, null)); imageOutput.write(((DataBufferByte) buffer).getData()); break; case DataBuffer.TYPE_USHORT: rowRaster.setDataElements(0, 0, raster.createChild(0, y, raster.getWidth(), 1, 0, 0, null)); short[] shorts = ((DataBufferUShort) buffer).getData(); // TODO: Get rid of this, due to stupid design in EncoderStream... ByteBuffer bb = ByteBuffer.allocate(shorts.length * 2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.asShortBuffer().put(shorts); imageOutput.write(bb.array()); // TODO: The below should work just as good // for (short value : shorts) { // imageOutput.writeShort(value); // } break; default: throw new IIOException("Unsupported data type"); } if (compressed) { ((LittleEndianDataOutputStream) imageOutput).close(); } } processImageProgress(tileY * 100f / renderedImage.getNumYTiles()); } } // TODO: If we have thumbnails, we need to write extension too. processImageComplete(); } private static LittleEndianDataOutputStream createRLEStream(final TGAHeader header, final ImageOutputStream stream) { return new LittleEndianDataOutputStream(new EncoderStream(IIOUtil.createStreamAdapter(stream), new RLEEncoder(header.getPixelDepth()))); } // TODO: Refactor to common util // TODO: Implement WritableRaster too, for use in reading private Raster asByteRaster(final Raster raster, ColorModel colorModel) { switch (raster.getTransferType()) { case DataBuffer.TYPE_BYTE: return raster; case DataBuffer.TYPE_USHORT: return raster; // TODO: We handle USHORT especially for now.. case DataBuffer.TYPE_INT: final int bands = colorModel.getNumComponents(); final DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer(); int w = raster.getWidth(); int h = raster.getHeight(); int size = buffer.getSize(); return new Raster( new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, w, h, bands, w * bands, createBandOffsets(colorModel)), new DataBuffer(DataBuffer.TYPE_BYTE, size * bands) { @Override public int getElem(int bank, int i) { int index = i / bands; int shift = (i % bands) * 8; return (buffer.getElem(index) >>> shift) & 0xFF; } @Override public void setElem(int bank, int i, int val) { throw new UnsupportedOperationException("Wrapped buffer is read-only"); } }, new Point()) {}; default: throw new IllegalArgumentException(String.format("Raster type %d not supported", raster.getTransferType())); } } private int[] createBandOffsets(final ColorModel colorModel) { notNull(colorModel, "colorModel"); if (colorModel instanceof DirectColorModel) { DirectColorModel dcm = (DirectColorModel) colorModel; int[] masks = dcm.getMasks(); int[] offs = new int[masks.length]; for (int i = 0; i < masks.length; i++) { int mask = masks[i]; int off = 0; // TODO: FixMe! This only works for standard 8 bit masks (0xFF) if (mask != 0) { while ((mask & 0xFF) == 0) { mask >>>= 8; off++; } } offs[i] = off; } return offs; } throw new IllegalArgumentException(String.format("%s not supported", colorModel.getClass().getSimpleName())); } public static void main(String[] args) throws IOException { BufferedImage image = ImageIO.read(new File(args[0])); ImageIO.write(image, "TGA", new File("foo.tga")); } }
4,674
777
<reponame>google-ar/chromium // 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 CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_SINK_WITH_CAST_MODES_H_ #define CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_SINK_WITH_CAST_MODES_H_ #include <set> #include "chrome/browser/media/router/media_sink.h" #include "chrome/browser/ui/webui/media_router/media_cast_mode.h" namespace media_router { // Contains information on a MediaSink and the set of cast modes it is // compatible with. This should be interpreted under the context of a // QueryResultManager which contains a mapping from MediaCastMode to // MediaSource. struct MediaSinkWithCastModes { explicit MediaSinkWithCastModes(const MediaSink& sink); MediaSinkWithCastModes(const MediaSinkWithCastModes& other); ~MediaSinkWithCastModes(); MediaSink sink; CastModeSet cast_modes; bool Equals(const MediaSinkWithCastModes& other) const; }; } // namespace media_router #endif // CHROME_BROWSER_UI_WEBUI_MEDIA_ROUTER_MEDIA_SINK_WITH_CAST_MODES_H_
398
575
// Copyright 2019 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. package org.chromium.chrome.browser.autofill_assistant; import static androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.chromium.chrome.browser.autofill_assistant.AutofillAssistantUiTestUtil.getElementValue; import static org.chromium.chrome.browser.autofill_assistant.AutofillAssistantUiTestUtil.waitUntilViewMatchesCondition; import androidx.test.filters.MediumTest; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.browser.autofill_assistant.proto.ActionProto; import org.chromium.chrome.browser.autofill_assistant.proto.ChipProto; import org.chromium.chrome.browser.autofill_assistant.proto.GeneratePasswordForFormFieldProto; import org.chromium.chrome.browser.autofill_assistant.proto.PresaveGeneratedPasswordProto; import org.chromium.chrome.browser.autofill_assistant.proto.PromptProto; import org.chromium.chrome.browser.autofill_assistant.proto.SaveGeneratedPasswordProto; import org.chromium.chrome.browser.autofill_assistant.proto.SelectorProto; import org.chromium.chrome.browser.autofill_assistant.proto.SetFormFieldValueProto; import org.chromium.chrome.browser.autofill_assistant.proto.SupportedScriptProto; import org.chromium.chrome.browser.autofill_assistant.proto.SupportedScriptProto.PresentationProto; import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.password_manager.PasswordChangeLauncher; import org.chromium.chrome.browser.password_manager.PasswordManagerClientBridgeForTesting; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.browser.test.util.TestThreadUtils; import java.util.ArrayList; import java.util.Collections; /** * Integration tests for password change flows. */ @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) @RunWith(ChromeJUnit4ClassRunner.class) public class AutofillAssistantPasswordManagerIntegrationTest { @Rule public CustomTabActivityTestRule mTestRule = new CustomTabActivityTestRule(); private static final String TEST_PAGE = "/components/test/data/autofill_assistant/html/" + "form_target_website.html"; private WebContents getWebContents() { return mTestRule.getWebContents(); } @Before public void setUp() throws Exception { AutofillAssistantPreferencesUtil.setInitialPreferences(true); mTestRule.startCustomTabActivityWithIntent( AutofillAssistantUiTestUtil.createMinimalCustomTabIntentForAutobot( mTestRule.getTestServer().getURL(TEST_PAGE), /* startImmediately = */ true)); TestThreadUtils.runOnUiThreadBlocking( () -> PasswordManagerClientBridgeForTesting.setLeakDialogWasShownForTesting( getWebContents(), true)); } @After public void tearDown() { TestThreadUtils.runOnUiThreadBlocking( () -> PasswordManagerClientBridgeForTesting.setLeakDialogWasShownForTesting( getWebContents(), false)); } /** * Helper function to start a password change flow. */ private void startPasswordChangeFlow(AutofillAssistantTestScript script, String username) { AutofillAssistantTestService testService = new AutofillAssistantTestService(Collections.singletonList(script)); testService.scheduleForInjection(); TestThreadUtils.runOnUiThreadBlocking( () -> PasswordChangeLauncher.start(getWebContents().getTopLevelNativeWindow(), getWebContents().getLastCommittedUrl(), username)); } /** * Run a password change flow (fill a form with username, old password, new * password). */ @Test @MediumTest public void testPasswordChangeFlow() throws Exception { ArrayList<ActionProto> list = new ArrayList<>(); // Sets username list.add((ActionProto) ActionProto.newBuilder() .setSetFormValue( SetFormFieldValueProto.newBuilder() .addValue(SetFormFieldValueProto.KeyPress.newBuilder() .setUseUsername(true)) .setElement(SelectorProto.newBuilder().addFilters( SelectorProto.Filter.newBuilder().setCssSelector( "#username")))) .build()); // Generates new password list.add((ActionProto) ActionProto.newBuilder() .setGeneratePasswordForFormField( GeneratePasswordForFormFieldProto.newBuilder() .setMemoryKey("memory-key") .setElement(SelectorProto.newBuilder().addFilters( SelectorProto.Filter.newBuilder().setCssSelector( "#new-password")))) .build()); // Presaves generated password list.add((ActionProto) ActionProto.newBuilder() .setPresaveGeneratedPassword( PresaveGeneratedPasswordProto.newBuilder().setMemoryKey( "memory-key")) .build()); // Sets new password list.add((ActionProto) ActionProto.newBuilder() .setSetFormValue( SetFormFieldValueProto.newBuilder() .addValue(SetFormFieldValueProto.KeyPress.newBuilder() .setClientMemoryKey("memory-key")) .setElement(SelectorProto.newBuilder().addFilters( SelectorProto.Filter.newBuilder().setCssSelector( "#new-password")))) .build()); // Sets password confirmation list.add((ActionProto) ActionProto.newBuilder() .setSetFormValue( SetFormFieldValueProto.newBuilder() .addValue(SetFormFieldValueProto.KeyPress.newBuilder() .setClientMemoryKey("memory-key")) .setElement(SelectorProto.newBuilder().addFilters( SelectorProto.Filter.newBuilder().setCssSelector( "#password-conf")))) .build()); // Saves generated password list.add((ActionProto) ActionProto.newBuilder() .setSaveGeneratedPassword( SaveGeneratedPasswordProto.newBuilder().setMemoryKey("memory-key")) .build()); // Fills login password field with saved password list.add((ActionProto) ActionProto.newBuilder() .setSetFormValue( SetFormFieldValueProto.newBuilder() .addValue(SetFormFieldValueProto.KeyPress.newBuilder() .setUsePassword(true)) .setElement(SelectorProto.newBuilder().addFilters( SelectorProto.Filter.newBuilder().setCssSelector( "#login-password")))) .build()); // Shows prompt list.add((ActionProto) ActionProto.newBuilder() .setPrompt(PromptProto.newBuilder().setMessage("Prompt").addChoices( PromptProto.Choice.newBuilder())) .build()); AutofillAssistantTestScript script = new AutofillAssistantTestScript( (SupportedScriptProto) SupportedScriptProto.newBuilder() .setPath("form_target_website.html") .setPresentation(PresentationProto.newBuilder().setAutostart(true).setChip( ChipProto.newBuilder().setText("Password generation"))) .build(), list); String username = "test_username"; startPasswordChangeFlow(script, username); waitUntilViewMatchesCondition(withText("Prompt"), isCompletelyDisplayed()); assertThat(getElementValue(getWebContents(), "username"), is(username)); String password = getElementValue(getWebContents(), "new-password"); String confirmation_password = getElementValue(getWebContents(), "password-conf"); String saved_password = getElementValue(getWebContents(), "login-password"); assertThat(password.length(), greaterThan(0)); assertThat(password, is(confirmation_password)); assertThat(saved_password.length(), greaterThan(0)); assertThat(saved_password, is(password)); } }
4,836
1,444
package mage.cards.h; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.PutIntoGraveFromAnywhereSourceTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.PreventionEffectData; import mage.abilities.effects.PreventionEffectImpl; import mage.abilities.effects.common.CreateTokenEffect; import mage.abilities.effects.common.ShuffleIntoLibrarySourceEffect; import mage.abilities.keyword.HasteAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Zone; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.token.ElementalShamanToken; import mage.game.stack.Spell; /** * * @author LevelX2 */ public final class Hostility extends CardImpl { public Hostility(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{R}{R}{R}"); this.subtype.add(SubType.ELEMENTAL); this.subtype.add(SubType.INCARNATION); this.power = new MageInt(6); this.toughness = new MageInt(6); // Haste this.addAbility(HasteAbility.getInstance()); // If a spell you control would deal damage to an opponent, prevent that damage. // Create a 3/1 red Elemental Shaman creature token with haste for each 1 damage prevented this way. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new HostilityEffect())); // When Hostility is put into a graveyard from anywhere, shuffle it into its owner's library. this.addAbility(new PutIntoGraveFromAnywhereSourceTriggeredAbility(new ShuffleIntoLibrarySourceEffect())); } private Hostility(final Hostility card) { super(card); } @Override public Hostility copy() { return new Hostility(this); } } class HostilityEffect extends PreventionEffectImpl { public HostilityEffect() { super(Duration.WhileOnBattlefield, Integer.MAX_VALUE, false, false); staticText = "If a spell you control would deal damage to an opponent, prevent that damage. Create a 3/1 red Elemental Shaman creature token with haste for each 1 damage prevented this way."; } public HostilityEffect(final HostilityEffect effect) { super(effect); } @Override public HostilityEffect copy() { return new HostilityEffect(this); } @Override public boolean checksEventType(GameEvent event, Game game) { switch (event.getType()) { case DAMAGE_PLAYER: return true; } return false; } @Override public boolean applies(GameEvent event, Ability source, Game game) { if (super.applies(event, source, game)) { if (game.getOpponents(source.getControllerId()).contains(event.getTargetId())) { Spell spell = game.getStack().getSpell(event.getSourceId()); if (spell != null && spell.isControlledBy(source.getControllerId())) { return true; } } } return false; } @Override public boolean replaceEvent(GameEvent event, Ability source, Game game) { PreventionEffectData preventionEffectData = preventDamageAction(event, source, game); if (preventionEffectData.getPreventedDamage() > 0) { new CreateTokenEffect(new ElementalShamanToken(true), preventionEffectData.getPreventedDamage()).apply(game, source); } return true; } }
1,316
5,169
<gh_stars>1000+ { "name": "SSCustomTabMenu", "version": "0.1.7", "summary": "Custom tab menu controller for iOS.", "description": "This CustomTabMenu will add custom menu at bottom!", "homepage": "https://github.com/simformsolutions/SSCustomTabMenu", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "simformsolutions": "<EMAIL>" }, "source": { "git": "https://github.com/simformsolutions/SSCustomTabMenu.git", "tag": "0.1.7" }, "platforms": { "ios": "9.0" }, "subspecs": [ { "name": "CustomTabMenu", "subspecs": [ { "name": "Helper", "source_files": "SSCustomTabMenu/CustomTabMenu/Helper/*.swift" }, { "name": "SSTabStoryBoard", "resource_bundles": { "SSCustomTabMenu": [ "SSCustomTabMenu/CustomTabMenu/SSTabStoryBoard/*.storyboard" ] } }, { "name": "image", "source_files": "SSCustomTabMenu/CustomTabMenu/image/*.png" } ] } ] }
526
369
// Copyright (c) 2017-2021, Mudita <NAME>.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "NotifyGUIBedtimeReminderAction.hpp" #include <service-appmgr/include/service-appmgr/Constants.hpp> #include <appmgr/messages/AlarmMessage.hpp> namespace alarms { NotifyGUIBedtimeReminderAction::NotifyGUIBedtimeReminderAction(sys::Service &service) : service{service} {} bool NotifyGUIBedtimeReminderAction::execute() { return service.bus.sendUnicast(std::make_shared<BedtimeNotification>(), service::name::appmgr); } bool NotifyGUIBedtimeReminderAction::turnOff() { return true; } } // namespace alarms
266
1,240
// SEEDocumentListGroupTableRowView.h // SubEthaEdit // // Created by <NAME> on 24.02.14. #import <Cocoa/Cocoa.h> @interface SEEDocumentListGroupTableRowView : NSTableRowView @end
73
2,151
<reponame>MauroArgentino/RSXGL /* * Mesa 3-D graphics library * Version: 7.7 * * Copyright (C) 2009 <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef REMAP_H #define REMAP_H #include "main/compiler.h" #include "main/mfeatures.h" struct gl_function_pool_remap { int pool_index; int remap_index; }; struct gl_function_remap { int func_index; int dispatch_offset; /* for sanity check */ }; #if FEATURE_remap_table extern int driDispatchRemapTable[]; extern const char * _mesa_get_function_spec(int func_index); extern int _mesa_map_function_spec(const char *spec); extern void _mesa_map_function_array(const struct gl_function_remap *func_array); extern void _mesa_map_static_functions(void); extern void _mesa_init_remap_table(void); #else /* FEATURE_remap_table */ static inline const char * _mesa_get_function_spec(int func_index) { return NULL; } static inline int _mesa_map_function_spec(const char *spec) { return -1; } static inline void _mesa_map_function_array(const struct gl_function_remap *func_array) { } static inline void _mesa_map_static_functions(void) { } static inline void _mesa_init_remap_table(void) { } #endif /* FEATURE_remap_table */ #endif /* REMAP_H */
744
1,351
<reponame>heroku-miraheze/trafficserver /** @file Base class for log files @section license License 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. */ #pragma once #include <cstdarg> #include <cstdio> #include <sys/time.h> #include <cstdint> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "ink_memory.h" #include "ink_string.h" #include "ink_file.h" #include "ink_cap.h" #include "ink_time.h" #include "SimpleTokenizer.h" #define LOGFILE_ROLLED_EXTENSION ".old" #define LOGFILE_SEPARATOR_STRING "_" #define LOGFILE_DEFAULT_PERMS (0644) #define LOGFILE_ROLL_MAXPATHLEN 4096 #define BASELOGFILE_DEBUG_MODE \ 0 // change this to 1 to enable debug messages // TODO find a way to enable this from autotools typedef enum { LL_Debug = 0, // process does not die LL_Note, // process does not die LL_Warning, // process does not die LL_Error, // process does not die LL_Fatal, // causes process termination } LogLogPriorityLevel; #define log_log_trace(...) \ do { \ if (BASELOGFILE_DEBUG_MODE) \ BaseLogFile::log_log(LL_Debug, __VA_ARGS__); \ } while (0) #define log_log_error(...) \ do { \ if (BASELOGFILE_DEBUG_MODE) \ BaseLogFile::log_log(LL_Error, __VA_ARGS__); \ } while (0) /* * * BaseMetaInfo class * * Used to store persistent information between ATS instances * */ class BaseMetaInfo { public: enum { DATA_FROM_METAFILE = 1, // metadata was read (or attempted to) // from metafile VALID_CREATION_TIME = 2, // creation time is valid VALID_SIGNATURE = 4, // signature is valid // (i.e., creation time only) FILE_OPEN_SUCCESSFUL = 8 // metafile was opened successfully }; enum { BUF_SIZE = 640 // size of read/write buffer }; private: char *_filename; // the name of the meta file time_t _creation_time; // file creation time uint64_t _log_object_signature; // log object signature int _flags; // metainfo status flags char _buffer[BUF_SIZE]; // read/write buffer void _read_from_file(); void _write_to_file(); void _build_name(const char *filename); public: BaseMetaInfo(const char *filename) : _flags(0) { _build_name(filename); _read_from_file(); } BaseMetaInfo(char *filename, time_t creation) : _creation_time(creation), _log_object_signature(0), _flags(VALID_CREATION_TIME) { _build_name(filename); _write_to_file(); } BaseMetaInfo(char *filename, time_t creation, uint64_t signature) : _creation_time(creation), _log_object_signature(signature), _flags(VALID_CREATION_TIME | VALID_SIGNATURE) { _build_name(filename); _write_to_file(); } ~BaseMetaInfo() { ats_free(_filename); } bool get_creation_time(time_t *time) { if (_flags & VALID_CREATION_TIME) { *time = _creation_time; return true; } else { return false; } } bool get_log_object_signature(uint64_t *signature) { if (_flags & VALID_SIGNATURE) { *signature = _log_object_signature; return true; } else { return false; } } bool data_from_metafile() const { return (_flags & DATA_FROM_METAFILE ? true : false); } bool file_open_successful() { return (_flags & FILE_OPEN_SUCCESSFUL ? true : false); } }; /* * * BaseLogFile Class * */ class BaseLogFile { public: // member functions BaseLogFile() = delete; BaseLogFile &operator=(const BaseLogFile &) = delete; BaseLogFile(const char *name); BaseLogFile(const char *name, uint64_t sig); BaseLogFile(const BaseLogFile &); ~BaseLogFile(); int roll(); int roll(long interval_start, long interval_end); static bool rolled_logfile(char *path); static bool exists(const char *pathname); int open_file(int perm = -1); int close_file(); void change_name(const char *new_name); void display(FILE *fd = stdout); const char * get_name() const { return m_name; } bool is_open() { return (m_fp != nullptr); } off_t get_size_bytes() const { return m_bytes_written; } bool is_init() { return m_is_init; } const char * get_hostname() const { return m_hostname; } void set_hostname(const char *hn) { m_hostname = ats_strdup(hn); } static void log_log(LogLogPriorityLevel priority, const char *format, ...); // member variables enum { LOG_FILE_NO_ERROR = 0, LOG_FILE_COULD_NOT_OPEN_FILE, }; FILE *m_fp = nullptr; long m_start_time = time(nullptr); long m_end_time = 0L; uint64_t m_bytes_written = 0; private: // member functions int timestamp_to_str(long timestamp, char *buf, int size); // member variables ats_scoped_str m_name; ats_scoped_str m_hostname; bool m_is_regfile = false; bool m_is_init = false; BaseMetaInfo *m_meta_info = nullptr; uint64_t m_signature = 0; bool m_has_signature = false; };
2,359
2,728
<reponame>rsdoherty/azure-sdk-for-python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import asyncio from ._test_base import _ReceiveTest class LegacyReceiveMessageBatchTest(_ReceiveTest): def run_sync(self): count = 0 while count < self.args.num_messages: batch = self.receiver.fetch_next(max_batch_size=self.args.num_messages - count) if self.args.peeklock: for msg in batch: msg.complete() count += len(batch) async def run_async(self): count = 0 while count < self.args.num_messages: batch = await self.async_receiver.fetch_next(max_batch_size=self.args.num_messages - count) if self.args.peeklock: await asyncio.gather(*[m.complete() for m in batch]) count += len(batch)
422
1,511
<gh_stars>1000+ /***************************************************************************** * * * Copyright (c) <NAME> 1993 * * * * Permission to use, copy, modify, and distribute this software and its * * documentation for any purpose and without fee is hereby granted, provided * * that the above copyright notice appears in all copies and that both the * * copyright notice and this permission notice appear in supporting * * documentation, and that the name University of Delaware not be used in * * advertising or publicity pertaining to distribution of the software *
331
1,767
<gh_stars>1000+ package com.annimon.stream.test.hamcrest; import com.annimon.stream.Collectors; import com.annimon.stream.DoubleStream; import com.annimon.stream.Stream; import com.annimon.stream.function.Function; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.junit.Test; import static com.annimon.stream.test.hamcrest.CommonMatcher.description; import static com.annimon.stream.test.hamcrest.CommonMatcher.hasOnlyPrivateConstructors; import static com.annimon.stream.test.hamcrest.DoubleStreamMatcher.elements; import static com.annimon.stream.test.hamcrest.DoubleStreamMatcher.hasElements; import static com.annimon.stream.test.hamcrest.DoubleStreamMatcher.isEmpty; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class DoubleStreamMatcherTest { @Test public void testPrivateConstructor() { assertThat(DoubleStreamMatcher.class, hasOnlyPrivateConstructors()); } @Test public void testIsEmpty() { assertThat(DoubleStream.empty(), isEmpty()); StringDescription description = new StringDescription(); isEmpty().describeTo(description); assertThat(description.toString(), is("an empty stream")); } @Test public void testHasElements() { assertThat(DoubleStream.of(1, 2), hasElements()); assertThat(DoubleStream.empty(), not(hasElements())); StringDescription description = new StringDescription(); hasElements().describeTo(description); assertThat(description.toString(), is("a non-empty stream")); } @Test(expected = AssertionError.class) public void testIsEmptyOnNullValue() { assertThat(null, isEmpty()); } @Test(expected = AssertionError.class) public void testHasElementsOnNullValue() { assertThat(null, hasElements()); } @SuppressWarnings("unchecked") @Test public void testElements() { final DoubleStream stream = DoubleStream.of(-0.987, 1.234, Math.PI, 1.618); final Double[] expected = new Double[] {-0.987, 1.234, Math.PI, 1.618}; final Matcher<DoubleStream> matcher = elements(arrayContaining(expected)); assertThat(stream, matcher); assertTrue(matcher.matches(stream)); assertFalse(elements(arrayContaining(expected)).matches(DoubleStream.empty())); assertThat(matcher, description(allOf( containsString("DoubleStream elements"), containsString(Stream.of(expected) .map(new Function<Double, String>() { @Override public String apply(Double t) { return String.format("<%s>", t.toString()); } }) .collect(Collectors.joining(", "))) ))); } @Test public void testAssertIsEmptyOperator() { DoubleStream.empty() .custom(DoubleStreamMatcher.assertIsEmpty()); } @Test(expected = AssertionError.class) public void testAssertIsEmptyOperatorOnEmptyStream() { DoubleStream.of(1, 2) .custom(DoubleStreamMatcher.assertIsEmpty()); } @Test public void testAssertHasElementsOperator() { DoubleStream.of(1, 2) .custom(DoubleStreamMatcher.assertHasElements()); } @Test(expected = AssertionError.class) public void testAssertHasElementsOperatorOnEmptyStream() { DoubleStream.empty() .custom(DoubleStreamMatcher.assertHasElements()); } @Test public void testAssertElementsOperator() { DoubleStream.of(-0.987, 1.234, Math.PI, 1.618) .custom(DoubleStreamMatcher.assertElements( arrayContaining(-0.987, 1.234, Math.PI, 1.618))); } }
1,680
310
package org.seasar.doma.jdbc.criteria.declaration; import org.seasar.doma.jdbc.criteria.context.Join; public class JoinDeclaration extends ComparisonDeclaration { public JoinDeclaration(Join join) { super(() -> join.on, on -> join.on = on); } }
90
771
#ifndef SEGMATCH_SIMPLE_NORMAL_ESTIMATOR_HPP_ #define SEGMATCH_SIMPLE_NORMAL_ESTIMATOR_HPP_ #define PCL_NO_PRECOMPILE #include <pcl/features/normal_3d.h> #include "segmatch/normal_estimators/normal_estimator.hpp" namespace segmatch { /// \brief Least squares normal estimation as using the PCL implementation. class SimpleNormalEstimator : public NormalEstimator { public: /// \brief Initializes a new instance of the SimpleNorminalEstimator class. /// \param search_radius The search radius used for estimating the normals. SimpleNormalEstimator(const float search_radius); /// \brief Notifies the estimator that points have been transformed. /// \param transformation Linear transformation applied to the points. void notifyPointsTransformed( const kindr::minimal::QuatTransformationTemplate<float>& transformation) override { } /// \brief Clear all the normals and the associated information. Equivalent to removing all the /// points from the cloud. void clear() override { } /// \brief Updates the normals of the points of a cloud. /// \param points The point cloud for which normals have to be computed. /// \param points_mapping Mapping from the indices of the points in the old point cloud to the /// indices of the points in the new point cloud since the last update. /// \param new_points_indices Indices of the points added to the point cloud since the /// last update. /// \param points_neighbors_provider Object for nearest neighbors searches. /// \returns Vector of booleans indicating which normals or curvatures changed after the update. std::vector<bool> updateNormals( const MapCloud& points, const std::vector<int>& points_mapping, const std::vector<int>& new_points_indices, PointsNeighborsProvider<MapPoint>& points_neighbors_provider) override; /// \brief Gets the current normal vectors of the point cloud. /// \returns Cloud containing the normal vectors. const PointNormals& getNormals() const { return normals_; } private: PointNormals normals_; pcl::NormalEstimation<MapPoint, PclNormal> normal_estimator_; }; // class SimpleNormalEstimator } // namespace segmatch #endif // SEGMATCH_SIMPLE_NORMAL_ESTIMATOR_HPP_
655
416
<reponame>ljz663/tencentcloud-sdk-java<gh_stars>100-1000 /* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.ccc.v20200210.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class CallInMetrics extends AbstractModel{ /** * IVR้ฉป็•™ๆ•ฐ้‡ */ @SerializedName("IvrCount") @Expose private Long IvrCount; /** * ๆŽ’้˜Ÿไธญๆ•ฐ้‡ */ @SerializedName("QueueCount") @Expose private Long QueueCount; /** * ๆŒฏ้“ƒไธญๆ•ฐ้‡ */ @SerializedName("RingCount") @Expose private Long RingCount; /** * ๆŽฅ้€šไธญๆ•ฐ้‡ */ @SerializedName("AcceptCount") @Expose private Long AcceptCount; /** * ๅฎขๆœ่ฝฌๆŽฅๅค–็บฟไธญๆ•ฐ้‡ */ @SerializedName("TransferOuterCount") @Expose private Long TransferOuterCount; /** * ๆœ€ๅคงๆŽ’้˜Ÿๆ—ถ้•ฟ */ @SerializedName("MaxQueueDuration") @Expose private Long MaxQueueDuration; /** * ๅนณๅ‡ๆŽ’้˜Ÿๆ—ถ้•ฟ */ @SerializedName("AvgQueueDuration") @Expose private Long AvgQueueDuration; /** * ๆœ€ๅคงๆŒฏ้“ƒๆ—ถ้•ฟ */ @SerializedName("MaxRingDuration") @Expose private Long MaxRingDuration; /** * ๅนณๅ‡ๆŒฏ้“ƒๆ—ถ้•ฟ */ @SerializedName("AvgRingDuration") @Expose private Long AvgRingDuration; /** * ๆœ€ๅคงๆŽฅ้€šๆ—ถ้•ฟ */ @SerializedName("MaxAcceptDuration") @Expose private Long MaxAcceptDuration; /** * ๅนณๅ‡ๆŽฅ้€šๆ—ถ้•ฟ */ @SerializedName("AvgAcceptDuration") @Expose private Long AvgAcceptDuration; /** * Get IVR้ฉป็•™ๆ•ฐ้‡ * @return IvrCount IVR้ฉป็•™ๆ•ฐ้‡ */ public Long getIvrCount() { return this.IvrCount; } /** * Set IVR้ฉป็•™ๆ•ฐ้‡ * @param IvrCount IVR้ฉป็•™ๆ•ฐ้‡ */ public void setIvrCount(Long IvrCount) { this.IvrCount = IvrCount; } /** * Get ๆŽ’้˜Ÿไธญๆ•ฐ้‡ * @return QueueCount ๆŽ’้˜Ÿไธญๆ•ฐ้‡ */ public Long getQueueCount() { return this.QueueCount; } /** * Set ๆŽ’้˜Ÿไธญๆ•ฐ้‡ * @param QueueCount ๆŽ’้˜Ÿไธญๆ•ฐ้‡ */ public void setQueueCount(Long QueueCount) { this.QueueCount = QueueCount; } /** * Get ๆŒฏ้“ƒไธญๆ•ฐ้‡ * @return RingCount ๆŒฏ้“ƒไธญๆ•ฐ้‡ */ public Long getRingCount() { return this.RingCount; } /** * Set ๆŒฏ้“ƒไธญๆ•ฐ้‡ * @param RingCount ๆŒฏ้“ƒไธญๆ•ฐ้‡ */ public void setRingCount(Long RingCount) { this.RingCount = RingCount; } /** * Get ๆŽฅ้€šไธญๆ•ฐ้‡ * @return AcceptCount ๆŽฅ้€šไธญๆ•ฐ้‡ */ public Long getAcceptCount() { return this.AcceptCount; } /** * Set ๆŽฅ้€šไธญๆ•ฐ้‡ * @param AcceptCount ๆŽฅ้€šไธญๆ•ฐ้‡ */ public void setAcceptCount(Long AcceptCount) { this.AcceptCount = AcceptCount; } /** * Get ๅฎขๆœ่ฝฌๆŽฅๅค–็บฟไธญๆ•ฐ้‡ * @return TransferOuterCount ๅฎขๆœ่ฝฌๆŽฅๅค–็บฟไธญๆ•ฐ้‡ */ public Long getTransferOuterCount() { return this.TransferOuterCount; } /** * Set ๅฎขๆœ่ฝฌๆŽฅๅค–็บฟไธญๆ•ฐ้‡ * @param TransferOuterCount ๅฎขๆœ่ฝฌๆŽฅๅค–็บฟไธญๆ•ฐ้‡ */ public void setTransferOuterCount(Long TransferOuterCount) { this.TransferOuterCount = TransferOuterCount; } /** * Get ๆœ€ๅคงๆŽ’้˜Ÿๆ—ถ้•ฟ * @return MaxQueueDuration ๆœ€ๅคงๆŽ’้˜Ÿๆ—ถ้•ฟ */ public Long getMaxQueueDuration() { return this.MaxQueueDuration; } /** * Set ๆœ€ๅคงๆŽ’้˜Ÿๆ—ถ้•ฟ * @param MaxQueueDuration ๆœ€ๅคงๆŽ’้˜Ÿๆ—ถ้•ฟ */ public void setMaxQueueDuration(Long MaxQueueDuration) { this.MaxQueueDuration = MaxQueueDuration; } /** * Get ๅนณๅ‡ๆŽ’้˜Ÿๆ—ถ้•ฟ * @return AvgQueueDuration ๅนณๅ‡ๆŽ’้˜Ÿๆ—ถ้•ฟ */ public Long getAvgQueueDuration() { return this.AvgQueueDuration; } /** * Set ๅนณๅ‡ๆŽ’้˜Ÿๆ—ถ้•ฟ * @param AvgQueueDuration ๅนณๅ‡ๆŽ’้˜Ÿๆ—ถ้•ฟ */ public void setAvgQueueDuration(Long AvgQueueDuration) { this.AvgQueueDuration = AvgQueueDuration; } /** * Get ๆœ€ๅคงๆŒฏ้“ƒๆ—ถ้•ฟ * @return MaxRingDuration ๆœ€ๅคงๆŒฏ้“ƒๆ—ถ้•ฟ */ public Long getMaxRingDuration() { return this.MaxRingDuration; } /** * Set ๆœ€ๅคงๆŒฏ้“ƒๆ—ถ้•ฟ * @param MaxRingDuration ๆœ€ๅคงๆŒฏ้“ƒๆ—ถ้•ฟ */ public void setMaxRingDuration(Long MaxRingDuration) { this.MaxRingDuration = MaxRingDuration; } /** * Get ๅนณๅ‡ๆŒฏ้“ƒๆ—ถ้•ฟ * @return AvgRingDuration ๅนณๅ‡ๆŒฏ้“ƒๆ—ถ้•ฟ */ public Long getAvgRingDuration() { return this.AvgRingDuration; } /** * Set ๅนณๅ‡ๆŒฏ้“ƒๆ—ถ้•ฟ * @param AvgRingDuration ๅนณๅ‡ๆŒฏ้“ƒๆ—ถ้•ฟ */ public void setAvgRingDuration(Long AvgRingDuration) { this.AvgRingDuration = AvgRingDuration; } /** * Get ๆœ€ๅคงๆŽฅ้€šๆ—ถ้•ฟ * @return MaxAcceptDuration ๆœ€ๅคงๆŽฅ้€šๆ—ถ้•ฟ */ public Long getMaxAcceptDuration() { return this.MaxAcceptDuration; } /** * Set ๆœ€ๅคงๆŽฅ้€šๆ—ถ้•ฟ * @param MaxAcceptDuration ๆœ€ๅคงๆŽฅ้€šๆ—ถ้•ฟ */ public void setMaxAcceptDuration(Long MaxAcceptDuration) { this.MaxAcceptDuration = MaxAcceptDuration; } /** * Get ๅนณๅ‡ๆŽฅ้€šๆ—ถ้•ฟ * @return AvgAcceptDuration ๅนณๅ‡ๆŽฅ้€šๆ—ถ้•ฟ */ public Long getAvgAcceptDuration() { return this.AvgAcceptDuration; } /** * Set ๅนณๅ‡ๆŽฅ้€šๆ—ถ้•ฟ * @param AvgAcceptDuration ๅนณๅ‡ๆŽฅ้€šๆ—ถ้•ฟ */ public void setAvgAcceptDuration(Long AvgAcceptDuration) { this.AvgAcceptDuration = AvgAcceptDuration; } public CallInMetrics() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public CallInMetrics(CallInMetrics source) { if (source.IvrCount != null) { this.IvrCount = new Long(source.IvrCount); } if (source.QueueCount != null) { this.QueueCount = new Long(source.QueueCount); } if (source.RingCount != null) { this.RingCount = new Long(source.RingCount); } if (source.AcceptCount != null) { this.AcceptCount = new Long(source.AcceptCount); } if (source.TransferOuterCount != null) { this.TransferOuterCount = new Long(source.TransferOuterCount); } if (source.MaxQueueDuration != null) { this.MaxQueueDuration = new Long(source.MaxQueueDuration); } if (source.AvgQueueDuration != null) { this.AvgQueueDuration = new Long(source.AvgQueueDuration); } if (source.MaxRingDuration != null) { this.MaxRingDuration = new Long(source.MaxRingDuration); } if (source.AvgRingDuration != null) { this.AvgRingDuration = new Long(source.AvgRingDuration); } if (source.MaxAcceptDuration != null) { this.MaxAcceptDuration = new Long(source.MaxAcceptDuration); } if (source.AvgAcceptDuration != null) { this.AvgAcceptDuration = new Long(source.AvgAcceptDuration); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "IvrCount", this.IvrCount); this.setParamSimple(map, prefix + "QueueCount", this.QueueCount); this.setParamSimple(map, prefix + "RingCount", this.RingCount); this.setParamSimple(map, prefix + "AcceptCount", this.AcceptCount); this.setParamSimple(map, prefix + "TransferOuterCount", this.TransferOuterCount); this.setParamSimple(map, prefix + "MaxQueueDuration", this.MaxQueueDuration); this.setParamSimple(map, prefix + "AvgQueueDuration", this.AvgQueueDuration); this.setParamSimple(map, prefix + "MaxRingDuration", this.MaxRingDuration); this.setParamSimple(map, prefix + "AvgRingDuration", this.AvgRingDuration); this.setParamSimple(map, prefix + "MaxAcceptDuration", this.MaxAcceptDuration); this.setParamSimple(map, prefix + "AvgAcceptDuration", this.AvgAcceptDuration); } }
4,063
2,151
<filename>third_party/blink/renderer/core/css/properties/longhands/baseline_shift_custom.cc // 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 "third_party/blink/renderer/core/css/properties/longhands/baseline_shift.h" #include "third_party/blink/renderer/core/css/css_value_list.h" #include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h" #include "third_party/blink/renderer/core/css/properties/computed_style_utils.h" #include "third_party/blink/renderer/core/style/computed_style.h" namespace blink { namespace CSSLonghand { const CSSValue* BaselineShift::ParseSingleValue( CSSParserTokenRange& range, const CSSParserContext& context, const CSSParserLocalContext&) const { CSSValueID id = range.Peek().Id(); if (id == CSSValueBaseline || id == CSSValueSub || id == CSSValueSuper) return CSSPropertyParserHelpers::ConsumeIdent(range); return CSSPropertyParserHelpers::ConsumeLengthOrPercent( range, kSVGAttributeMode, kValueRangeAll); } const CSSValue* BaselineShift::CSSValueFromComputedStyleInternal( const ComputedStyle& style, const SVGComputedStyle& svg_style, const LayoutObject*, Node* styled_node, bool allow_visited_style) const { switch (svg_style.BaselineShift()) { case BS_SUPER: return CSSIdentifierValue::Create(CSSValueSuper); case BS_SUB: return CSSIdentifierValue::Create(CSSValueSub); case BS_LENGTH: return ComputedStyleUtils::ZoomAdjustedPixelValueForLength( svg_style.BaselineShiftValue(), style); } NOTREACHED(); return nullptr; } } // namespace CSSLonghand } // namespace blink
608
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/GMM.framework/GMM */ #import <GMM/XXUnknownSuperclass.h> @class LBSPoint, NSMutableArray, LBSAddress, NSString; @interface LBSUserLocation : XXUnknownSuperclass { LBSPoint *_latLng; // 4 = 0x4 NSString *_source; // 8 = 0x8 BOOL _hasAccuracy; // 12 = 0xc int _accuracy; // 16 = 0x10 BOOL _hasConfidence; // 20 = 0x14 int _confidence; // 24 = 0x18 LBSAddress *_address; // 28 = 0x1c NSString *_misc; // 32 = 0x20 BOOL _hasObsolete; // 36 = 0x24 BOOL _obsolete; // 37 = 0x25 NSMutableArray *_features; // 40 = 0x28 NSString *_locationString; // 44 = 0x2c long long _timestamp; // 48 = 0x30 BOOL _hasLocType; // 56 = 0x38 int _locType; // 60 = 0x3c } @property(assign, nonatomic) int locType; // G=0x31d69; S=0x31091; @synthesize=_locType @property(assign, nonatomic) BOOL hasLocType; // G=0x31d49; S=0x31d59; @synthesize=_hasLocType @property(assign, nonatomic) long long timestamp; // G=0x31d1d; S=0x31d35; @synthesize=_timestamp @property(retain, nonatomic) NSString *locationString; // G=0x31ce9; S=0x31cf9; @synthesize=_locationString @property(readonly, assign, nonatomic) BOOL hasLocationString; // G=0x31079; @property(retain, nonatomic) NSMutableArray *features; // G=0x31cb5; S=0x31cc5; @synthesize=_features @property(assign, nonatomic) BOOL obsolete; // G=0x31ca5; S=0x30fb1; @synthesize=_obsolete @property(assign, nonatomic) BOOL hasObsolete; // G=0x31c85; S=0x31c95; @synthesize=_hasObsolete @property(retain, nonatomic) NSString *misc; // G=0x31c51; S=0x31c61; @synthesize=_misc @property(readonly, assign, nonatomic) BOOL hasMisc; // G=0x30f99; @property(retain, nonatomic) LBSAddress *address; // G=0x31c1d; S=0x31c2d; @synthesize=_address @property(readonly, assign, nonatomic) BOOL hasAddress; // G=0x30f81; @property(assign, nonatomic) int confidence; // G=0x31c0d; S=0x30f5d; @synthesize=_confidence @property(assign, nonatomic) BOOL hasConfidence; // G=0x31bed; S=0x31bfd; @synthesize=_hasConfidence @property(assign, nonatomic) int accuracy; // G=0x31bdd; S=0x30f39; @synthesize=_accuracy @property(assign, nonatomic) BOOL hasAccuracy; // G=0x31bbd; S=0x31bcd; @synthesize=_hasAccuracy @property(retain, nonatomic) NSString *source; // G=0x31b89; S=0x31b99; @synthesize=_source @property(readonly, assign, nonatomic) BOOL hasSource; // G=0x30f21; @property(retain, nonatomic) LBSPoint *latLng; // G=0x31b55; S=0x31b65; @synthesize=_latLng @property(readonly, assign, nonatomic) BOOL hasLatLng; // G=0x30f09; // declared property getter: - (int)locType; // 0x31d69 // declared property setter: - (void)setHasLocType:(BOOL)type; // 0x31d59 // declared property getter: - (BOOL)hasLocType; // 0x31d49 // declared property setter: - (void)setTimestamp:(long long)timestamp; // 0x31d35 // declared property getter: - (long long)timestamp; // 0x31d1d // declared property setter: - (void)setLocationString:(id)string; // 0x31cf9 // declared property getter: - (id)locationString; // 0x31ce9 // declared property setter: - (void)setFeatures:(id)features; // 0x31cc5 // declared property getter: - (id)features; // 0x31cb5 // declared property getter: - (BOOL)obsolete; // 0x31ca5 // declared property setter: - (void)setHasObsolete:(BOOL)obsolete; // 0x31c95 // declared property getter: - (BOOL)hasObsolete; // 0x31c85 // declared property setter: - (void)setMisc:(id)misc; // 0x31c61 // declared property getter: - (id)misc; // 0x31c51 // declared property setter: - (void)setAddress:(id)address; // 0x31c2d // declared property getter: - (id)address; // 0x31c1d // declared property getter: - (int)confidence; // 0x31c0d // declared property setter: - (void)setHasConfidence:(BOOL)confidence; // 0x31bfd // declared property getter: - (BOOL)hasConfidence; // 0x31bed // declared property getter: - (int)accuracy; // 0x31bdd // declared property setter: - (void)setHasAccuracy:(BOOL)accuracy; // 0x31bcd // declared property getter: - (BOOL)hasAccuracy; // 0x31bbd // declared property setter: - (void)setSource:(id)source; // 0x31b99 // declared property getter: - (id)source; // 0x31b89 // declared property setter: - (void)setLatLng:(id)lng; // 0x31b65 // declared property getter: - (id)latLng; // 0x31b55 - (void)writeTo:(id)to; // 0x317c9 - (BOOL)readFrom:(id)from; // 0x313f9 - (id)dictionaryRepresentation; // 0x31125 - (id)description; // 0x310b5 // declared property setter: - (void)setLocType:(int)type; // 0x31091 // declared property getter: - (BOOL)hasLocationString; // 0x31079 - (id)featureAtIndex:(unsigned)index; // 0x31059 - (unsigned)featuresCount; // 0x31039 - (void)addFeature:(id)feature; // 0x30fd5 // declared property setter: - (void)setObsolete:(BOOL)obsolete; // 0x30fb1 // declared property getter: - (BOOL)hasMisc; // 0x30f99 // declared property getter: - (BOOL)hasAddress; // 0x30f81 // declared property setter: - (void)setConfidence:(int)confidence; // 0x30f5d // declared property setter: - (void)setAccuracy:(int)accuracy; // 0x30f39 // declared property getter: - (BOOL)hasSource; // 0x30f21 // declared property getter: - (BOOL)hasLatLng; // 0x30f09 - (void)dealloc; // 0x30e61 @end
2,090
992
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "bnodecache.h" #include "fdb_internal.h" #include "filemgr.h" std::atomic<BnodeCacheMgr*> BnodeCacheMgr::instance(nullptr); std::mutex BnodeCacheMgr::instanceMutex; static uint64_t defaultCacheSize = 134217728; // 128MB static uint64_t defaultFlushLimit = 1048576; // 1MB /** * Hash function to determine the shard within a file * using the offset. */ static std::hash<std::string> str_hash; FileBnodeCache::FileBnodeCache(std::string fname, FileMgr* file, size_t num_shards) : filename(fname), curFile(file), refCount(0), numVictims(0), numItems(0), numItemsWritten(0), accessTimestamp(0), evictionInProgress(false) { for (size_t i = 0; i < num_shards; ++i) { shards.emplace_back(new BnodeCacheShard(i)); } } const std::string& FileBnodeCache::getFileName(void) const { return filename; } FileMgr* FileBnodeCache::getFileManager(void) const { return curFile; } uint32_t FileBnodeCache::getRefCount(void) const { return refCount.load(); } uint64_t FileBnodeCache::getNumVictims(void) const { return numVictims.load(); } uint64_t FileBnodeCache::getNumItems(void) const { return numItems.load(); } uint64_t FileBnodeCache::getNumItemsWritten(void) const { return numItemsWritten.load(); } uint64_t FileBnodeCache::getAccessTimestamp(void) const { return accessTimestamp.load(std::memory_order_relaxed); } size_t FileBnodeCache::getNumShards(void) const { return shards.size(); } void FileBnodeCache::setAccessTimestamp(uint64_t timestamp) { accessTimestamp.store(timestamp, std::memory_order_relaxed); } bool FileBnodeCache::empty() { bool empty = true; acquireAllShardLocks(); for (size_t i = 0; i < shards.size(); ++i) { if (!shards[i]->empty()) { empty = false; break; } } releaseAllShardLocks(); return empty; } void FileBnodeCache::acquireAllShardLocks() { for (size_t i = 0; i < shards.size(); ++i) { spin_lock(&shards[i]->lock); } } void FileBnodeCache::releaseAllShardLocks() { for (size_t i = 0; i < shards.size(); ++i) { spin_unlock(&shards[i]->lock); } } bool FileBnodeCache::setEvictionInProgress(bool to) { bool inverse = !to; return evictionInProgress.compare_exchange_strong(inverse, to); } BnodeCacheMgr* BnodeCacheMgr::init(uint64_t cache_size, uint64_t flush_limit) { BnodeCacheMgr* tmp = instance.load(); if (tmp == nullptr) { // Ensure two threads don't both create an instance LockHolder lh(instanceMutex); tmp = instance.load(); if (tmp == nullptr) { tmp = new BnodeCacheMgr(cache_size, flush_limit); instance.store(tmp); } else { tmp->updateParams(cache_size, flush_limit); } } else { LockHolder lh(instanceMutex); tmp->updateParams(cache_size, flush_limit); } return tmp; } BnodeCacheMgr* BnodeCacheMgr::get() { BnodeCacheMgr* cacheMgr = instance.load(); if (cacheMgr == nullptr) { // Create the buffer cache manager with default config return init(defaultCacheSize, defaultFlushLimit); } return cacheMgr; } void BnodeCacheMgr::destroyInstance() { LockHolder lh(instanceMutex); BnodeCacheMgr* tmp = instance.load(); if (tmp != nullptr) { delete tmp; instance = nullptr; } } void BnodeCacheMgr::eraseFileHistory(FileMgr* file) { if (!file) { return; } LockHolder lh(instanceMutex); BnodeCacheMgr* tmp = instance.load(); if (tmp) { tmp->removeDirtyBnodes(file); tmp->removeCleanBnodes(file); tmp->removeFile(file); } } BnodeCacheMgr::BnodeCacheMgr(uint64_t cache_size, uint64_t flush_limit) : bnodeCacheLimit(cache_size), bnodeCacheCurrentUsage(0), flushLimit(flush_limit) { spin_init(&bnodeCacheLock); int rv = init_rw_lock(&fileListLock); if (rv != 0) { fdb_log(nullptr, FDB_RESULT_ALLOC_FAIL, "BnodeCacheMgr::BnodeCacheMgr: RW Lock init failed; " "error code: %d", rv); assert(false); } } BnodeCacheMgr::~BnodeCacheMgr() { spin_lock(&bnodeCacheLock); for (auto entry : fileMap) { delete entry.second; } spin_unlock(&bnodeCacheLock); spin_destroy(&bnodeCacheLock); int rv = destroy_rw_lock(&fileListLock); if (rv != 0) { fdb_log(nullptr, FDB_RESULT_ALLOC_FAIL, "BnodeCacheMgr::~BnodeCacheMgr: RW lock destroy failed; " "error code: %d", rv); assert(false); } } void BnodeCacheMgr::updateParams(uint64_t cache_size, uint64_t flush_limit) { bnodeCacheLimit.store(cache_size); flushLimit.store(flush_limit); } int BnodeCacheMgr::read(FileMgr* file, Bnode** node, cs_off_t offset) { if (!file) { return FDB_RESULT_INVALID_ARGS; } // Note that we don't need to grab the bnodeCacheLock here as the bnode // cache is already created and binded when the file is created or opened // for the first time. FileBnodeCache* fcache = file->getBnodeCache(); if (fcache == nullptr) { spin_lock(&bnodeCacheLock); // Check again within bnodeCacheLock fcache = file->getBnodeCache(); if (fcache == nullptr) { // A file bnode cache doesn not exist, creating it fcache = createFileBnodeCache_UNLOCKED(file); } spin_unlock(&bnodeCacheLock); } if (fcache) { // file exists, update the access timestamp (in ms) fcache->setAccessTimestamp(gethrtime() / 1000000); size_t shard_num = str_hash(std::to_string(offset)) % fcache->getNumShards(); spin_lock(&fcache->shards[shard_num]->lock); auto entry = fcache->shards[shard_num]->allNodes.find(offset); if (entry != fcache->shards[shard_num]->allNodes.end()) { // cache hit *node = entry->second; entry->second->incRefCount(); // Move the item to the back of the clean node list if the item is // not dirty (to ensure that it is the last entry in this file's // clean node list that is evicted which is done based on LRU) if (fcache->shards[shard_num]->dirtyIndexNodes.find( entry->second->getCurOffset()) == fcache->shards[shard_num]->dirtyIndexNodes.end()) { list_remove(&fcache->shards[shard_num]->cleanNodes, &entry->second->list_elem); list_push_back(&fcache->shards[shard_num]->cleanNodes, &entry->second->list_elem); } spin_unlock(&fcache->shards[shard_num]->lock); return (*node)->getNodeSize(); } else { // cache miss fdb_status status = fetchFromFile(file, node, offset); if (status != FDB_RESULT_SUCCESS) { // does not exist spin_unlock(&fcache->shards[shard_num]->lock); return status; } else { // Add back to allBNodes hash table fcache->shards[shard_num]->allNodes.insert( std::make_pair((*node)->getCurOffset(), *node)); // Add to back of clean node list list_push_back(&fcache->shards[shard_num]->cleanNodes, &((*node)->list_elem)); bnodeCacheCurrentUsage.fetch_add((*node)->getMemConsumption()); fcache->numItems++; (*node)->incRefCount(); spin_unlock(&fcache->shards[shard_num]->lock); // Do Eviction if necessary // TODO: Implement an eviction daemon perhaps rather than having // the reader do it .. performEviction(*node); return (*node)->getNodeSize(); } } } // does not exist .. cache miss return 0; } int BnodeCacheMgr::write(FileMgr* file, Bnode* node, cs_off_t offset) { if (!file) { return FDB_RESULT_INVALID_ARGS; } FileBnodeCache* fcache = file->getBnodeCache(); if (fcache == nullptr) { spin_lock(&bnodeCacheLock); // Check again within bnodeCacheLock fcache = file->getBnodeCache(); if (fcache == nullptr) { // A file bnode cache doesn not exist, creating it fcache = createFileBnodeCache_UNLOCKED(file); } spin_unlock(&bnodeCacheLock); } // Update the access timestamp (in ms) fcache->setAccessTimestamp(gethrtime() / 1000000); size_t shard_num = str_hash(std::to_string(offset)) % fcache->getNumShards(); spin_lock(&fcache->shards[shard_num]->lock); // search shard hash table auto entry = fcache->shards[shard_num]->allNodes.find(offset); if (entry == fcache->shards[shard_num]->allNodes.end()) { // insert into hash table auto result = fcache->shards[shard_num]->allNodes.insert( std::make_pair(node->getCurOffset(), node)); if (!result.second) { // Offset already exists fdb_log(nullptr, FDB_RESULT_EEXIST, "Fatal Error: Offset (%s) already in use (race)!", std::to_string(offset).c_str()); spin_unlock(&fcache->shards[shard_num]->lock); return FDB_RESULT_EEXIST; } bnodeCacheCurrentUsage.fetch_add(node->getMemConsumption()); fcache->numItems++; fcache->numItemsWritten++; } else { fdb_log(nullptr, FDB_RESULT_EEXIST, "Fatal Error: Offset (%s) already in use!", std::to_string(offset).c_str()); spin_unlock(&fcache->shards[shard_num]->lock); return FDB_RESULT_EEXIST; } fcache->shards[shard_num]->dirtyIndexNodes[offset] = node; spin_unlock(&fcache->shards[shard_num]->lock); performEviction(node); return node->getNodeSize(); } int BnodeCacheMgr::writeMulti(FileMgr* file, std::vector<bnode_offset_t> &nodes) { if (!file) { return FDB_RESULT_INVALID_ARGS; } int total_bytes_written = 0; std::vector<Bnode*> wrote; for (auto node : nodes) { int bytes_written = write(file, node.first, node.second); if (bytes_written == static_cast<int>(node.first->getNodeSize())) { total_bytes_written += bytes_written; wrote.push_back(node.first); } else { // Return the failed response code, after un-doing // writes written as part of this change. total_bytes_written = bytes_written; removeSelectBnodes(file, wrote); break; } } return total_bytes_written; } fdb_status BnodeCacheMgr::flush(FileMgr* file) { FileBnodeCache* fcache = file->getBnodeCache(); if (fcache) { // Note that this function is invoked as part of a commit operation // while the filemgr's lock is already grabbed by a committer. // Therefore, we don't need to grab all the shard locks at once. return flushDirtyIndexNodes(fcache, true, true); } return FDB_RESULT_FILE_NOT_OPEN; } fdb_status BnodeCacheMgr::addLastBlockMeta(FileMgr* file, bid_t bid) { if (!file) { return FDB_RESULT_INVALID_ARGS; } FileBnodeCache* fcache = file->getBnodeCache(); if (!fcache) { return FDB_RESULT_FILE_NOT_OPEN; } fdb_status status = FDB_RESULT_SUCCESS; size_t blocksize = fcache->getFileManager()->getBlockSize(); size_t offset_of_blk = blocksize - sizeof(IndexBlkMeta); IndexBlkMeta blk_meta; blk_meta.set(BLK_NOT_FOUND, fcache->getFileManager()->getSbBmpRevnum()); ssize_t ret = fcache->getFileManager()->writeBuf( &blk_meta, sizeof(IndexBlkMeta), bid * blocksize + offset_of_blk); if (ret != static_cast<ssize_t>(sizeof(IndexBlkMeta))) { status = ret < 0 ? (fdb_status)ret : FDB_RESULT_WRITE_FAIL; } return status; } fdb_status BnodeCacheMgr::invalidateBnode(FileMgr* file, Bnode* node) { if (!file || !node) { return FDB_RESULT_INVALID_ARGS; } FileBnodeCache* fcache = file->getBnodeCache(); if (!fcache) { return FDB_RESULT_FILE_NOT_OPEN; } size_t shard_num = str_hash(std::to_string(node->getCurOffset())) % fcache->getNumShards(); if (node->getRefCount() <= 1) { spin_lock(&fcache->shards[shard_num]->lock); // Search shard hash table auto entry = fcache->shards[shard_num]->allNodes.find(node->getCurOffset()); if (entry != fcache->shards[shard_num]->allNodes.end()) { // Remove from all nodes list fcache->shards[shard_num]->allNodes.erase(node->getCurOffset()); // Remove from dirty index nodes (if present) fcache->shards[shard_num]->dirtyIndexNodes.erase(node->getCurOffset()); // Remove from clean nodes (if present) list_remove(&fcache->shards[shard_num]->cleanNodes, &node->list_elem); fcache->numItems--; fcache->numItemsWritten--; // Decrement memory usage bnodeCacheCurrentUsage.fetch_sub(node->getMemConsumption()); spin_unlock(&fcache->shards[shard_num]->lock); } else { spin_unlock(&fcache->shards[shard_num]->lock); fdb_log(nullptr, FDB_RESULT_KEY_NOT_FOUND, "Warning: Failed to remove bnode (at offset: %s) " "in file '%s', because it wasn't found in the cache!", std::to_string(node->getCurOffset()).c_str(), fcache->getFileName().c_str()); return FDB_RESULT_KEY_NOT_FOUND; } } else { // failure of invalidation is used as one of conditions // in BnodeMgr layer during node cloning, so we don't // need to report warning here. return FDB_RESULT_FILE_IS_BUSY; } return FDB_RESULT_SUCCESS; } // Remove all dirty index nodes for the File // (they are only discarded and not written back) void BnodeCacheMgr::removeDirtyBnodes(FileMgr* file) { if (!file) { return; } FileBnodeCache* fcache = file->getBnodeCache(); if (fcache) { // Note that this function is only invoked as part of database // file close or removal when there are no database handles // for a given file. Therefore we don't need to grab all the // shard locks at once. // Remove all dirty bnodes flushDirtyIndexNodes(fcache, false, true); } } // Remove all clean bnodes of the File void BnodeCacheMgr::removeCleanBnodes(FileMgr* file) { if (!file) { return; } FileBnodeCache* fcache = file->getBnodeCache(); if (fcache) { struct list_elem *elem; Bnode* item; // Note that this function is only invoked as part of database // file close or removal when there are no database handles // for a given file. Therefore we don't need to grab all the // shard locks at once. // Remove all clean blocksfrom each shard in the file for (size_t i = 0; i < fcache->getNumShards(); ++i) { spin_lock(&fcache->shards[i]->lock); elem = list_begin(&fcache->shards[i]->cleanNodes); while (elem) { item = reinterpret_cast<Bnode*>(elem); // Remove from the clean nodes list elem = list_remove(&fcache->shards[i]->cleanNodes, elem); // Remove from the all node list fcache->shards[i]->allNodes.erase(item->getCurOffset()); fcache->numItems--; // Decrement memory usage bnodeCacheCurrentUsage.fetch_sub(item->getMemConsumption()); // Free the item delete item; } spin_unlock(&fcache->shards[i]->lock); } } } // Remove a file bnode cache from the file bnode cache list. // MUST ensure that there is no dirty index node that belongs to this File // (or memory leak occurs). bool BnodeCacheMgr::removeFile(FileMgr* file) { bool rv = false; if (!file) { return rv; } FileBnodeCache* fcache = file->getBnodeCache(); if (fcache) { // Acquire lock spin_lock(&bnodeCacheLock); // File Bnode cache must be empty if (!fcache->empty()) { spin_unlock(&bnodeCacheLock); fdb_log(nullptr, FDB_RESULT_FILE_REMOVE_FAIL, "Warning: Failed to remove file cache instance for " "a file '%s' because the file cache instance is not " "empty!", file->getFileName()); return rv; } // Remove from the file bnode cache map fileMap.erase(std::string(file->getFileName())); spin_unlock(&bnodeCacheLock); // We don't need to grab the file bnode cache's partition locks // at once because this function is only invoked when there are // no database handles that access the file. if (prepareDeallocationForFileBnodeCache(fcache)) { freeFileBnodeCache(fcache); // No other callers accessing the file rv = true; } // Otherwise, a file bnode cache is in use by eviction, Deletion delayed } return rv; } FileBnodeCache* BnodeCacheMgr::createFileBnodeCache(FileMgr* file) { spin_lock(&bnodeCacheLock); FileBnodeCache* fcache = createFileBnodeCache_UNLOCKED(file); spin_unlock(&bnodeCacheLock); return fcache; } // bnodeCacheLock to be acquired before invoking this function FileBnodeCache* BnodeCacheMgr::createFileBnodeCache_UNLOCKED(FileMgr* file) { if (!file) { return nullptr; } // Before a new file bnode cache is created, garbage collect zombies cleanUpInvalidFileBnodeCaches(); size_t num_shards; if (file->getConfig()->getNumBcacheShards()) { num_shards = file->getConfig()->getNumBcacheShards(); } else { num_shards = DEFAULT_NUM_BCACHE_PARTITIONS; } std::string file_name(file->getFileName()); FileBnodeCache* fcache = new FileBnodeCache(file_name, file, num_shards); // For random eviction among shards randomize(); // Insert into file map fileMap[file_name] = fcache; file->setBnodeCache(fcache); if (writer_lock(&fileListLock) == 0) { fileList.push_back(fcache); writer_unlock(&fileListLock); } else { fdb_log(nullptr, FDB_RESULT_LOCK_FAIL, "BnodeCacheMgr::createFileBnodeCache(): " "Failed to acquire writer lock on the file list lock!"); } return fcache; } bool BnodeCacheMgr::freeFileBnodeCache(FileBnodeCache* fcache, bool force) { if (!fcache) { return false; } if (!fcache->empty() && !force) { fdb_log(nullptr, FDB_RESULT_FILE_IS_BUSY, "Warning: Failed to free file bnode cache instance for file " "'%s', because the file block cache instance isn't empty!", fcache->getFileName().c_str()); return false; } if (fcache->getRefCount() != 0 && !force) { fdb_log(nullptr, FDB_RESULT_FILE_IS_BUSY, "Warning: Failed to free file bnode cache instance for file " "'%s', because its ref counter is not zero!", fcache->getFileName().c_str()); return false; } fileMap.erase(fcache->getFileName()); // Free file bnode cache delete fcache; return true; } static const size_t BNODE_BUFFER_HEADROOM = 256; fdb_status BnodeCacheMgr::fetchFromFile(FileMgr* file, Bnode** node, cs_off_t offset) { if (!file) { return FDB_RESULT_INVALID_ARGS; } fdb_status status = FDB_RESULT_SUCCESS; ssize_t ret = 0; // 1> Read the first 4 bytes uint32_t length; ret = file->readBuf(&length, sizeof(length), offset); if (ret != sizeof(length)) { status = ret < 0 ? (fdb_status)ret : FDB_RESULT_READ_FAIL; return status; } length = Bnode::readNodeSize(&length); // 2> Alloc Buffer // Note: we allocate a little bit more memory to avoid to call // realloc() if a few new entries are inserted. void *buf = malloc(length + BNODE_BUFFER_HEADROOM); // 3> Read: If the node is written over multiple blocks, read // them accoding to the block meta. size_t blocksize = file->getBlockSize(); size_t blocksize_avail = blocksize - sizeof(IndexBlkMeta); size_t offset_of_block = offset % blocksize; size_t offset_of_buffer = 0; size_t remaining_size = length; bid_t cur_bid = offset / blocksize; IndexBlkMeta blk_meta; Bnode* bnode_out = new Bnode(); if (offset_of_block + length <= blocksize_avail) { // Entire node is stored in a single block ret = file->readBuf(buf, length, offset); if (ret != static_cast<ssize_t>(length)) { status = ret < 0 ? (fdb_status)ret : FDB_RESULT_READ_FAIL; free(buf); delete bnode_out; return status; } // add BID info into the bnode bnode_out->addBidList(cur_bid); } else { size_t cur_slice_size; while (remaining_size) { cur_slice_size = blocksize_avail - offset_of_block; if (cur_slice_size > remaining_size) { cur_slice_size = remaining_size; } // read data from the block ret = file->readBuf((uint8_t*)buf + offset_of_buffer, cur_slice_size, cur_bid * blocksize + offset_of_block); if (ret != static_cast<ssize_t>(cur_slice_size)) { status = ret < 0 ? (fdb_status)ret : FDB_RESULT_READ_FAIL; free(buf); delete bnode_out; return status; } // add BID info into the bnode bnode_out->addBidList(cur_bid); remaining_size -= cur_slice_size; offset_of_buffer += cur_slice_size; if (remaining_size) { // Read next block's info from the meta segment ret = file->readBuf(&blk_meta, sizeof(IndexBlkMeta), cur_bid * blocksize + blocksize_avail); if (ret != static_cast<ssize_t>(sizeof(IndexBlkMeta))) { status = ret < 0 ? (fdb_status)ret : FDB_RESULT_READ_FAIL; free(buf); delete bnode_out; return status; } blk_meta.decode(); cur_bid = blk_meta.nextBid; offset_of_block = 0; } } } bnode_out->importRaw(buf, length + BNODE_BUFFER_HEADROOM); bnode_out->setCurOffset(offset); // 'buf' to be freed by client *node = bnode_out; return status; } bool dirtyNodesCustomSort(std::pair<size_t, Bnode*> entry1, std::pair<size_t, Bnode*> entry2) { return (entry1.second->getCurOffset() < entry2.second->getCurOffset()); } fdb_status BnodeCacheMgr::writeCachedData(WriteCachedDataArgs& args) { ssize_t ret = 0; fdb_status status = FDB_RESULT_SUCCESS; if (args.flush_all) { // 'Flush all' option // => use temp_buf to write as large as data sequentially. if (args.temp_buf_pos + args.size_to_append > defaultFlushLimit || args.batch_write_offset + args.temp_buf_pos != args.cur_offset) { // 1) The remaining space in the temp buf is not enough, OR // 2) Last written data in the buffer and incoming data are not // consecutive, // => flush current buffer and reset. ret = args.fcache->getFileManager()->writeBuf(args.temp_buf.get(), args.temp_buf_pos, args.batch_write_offset); if (ret != static_cast<ssize_t>(args.temp_buf_pos)) { status = ret < 0 ? (fdb_status)ret : FDB_RESULT_WRITE_FAIL; return status; } args.temp_buf_pos = 0; args.batch_write_offset = args.cur_offset; } memcpy(args.temp_buf.get() + args.temp_buf_pos, args.data_to_append, args.size_to_append); args.temp_buf_pos += args.size_to_append; } else { // Otherwise => directly invoke writeBuf(). ret = args.fcache->getFileManager()->writeBuf(args.data_to_append, args.size_to_append, args.cur_offset); if (ret != static_cast<ssize_t>(args.size_to_append)) { status = ret < 0 ? (fdb_status)ret : FDB_RESULT_WRITE_FAIL; return status; } } return FDB_RESULT_SUCCESS; } fdb_status BnodeCacheMgr::flushDirtyIndexNodes(FileBnodeCache* fcache, bool sync, bool flush_all) { if (!fcache) { return FDB_RESULT_INVALID_ARGS; } ssize_t ret = 0; fdb_status status = FDB_RESULT_SUCCESS; std::vector<std::pair<size_t, Bnode*>> dirty_nodes; std::map<cs_off_t, Bnode*>* shard_dirty_tree; uint64_t flushed = 0; size_t count = 0; // Allocate the temporary buffer (1MB) to write multiple dirty index nodes at once WriteCachedDataArgs temp_buf_args(fcache, defaultFlushLimit, flush_all); while (true) { if (count == 0) { for (size_t i = 0; i < fcache->getNumShards(); ++i) { spin_lock(&fcache->shards[i]->lock); if (flush_all) { // In case of flush_all, push all the dirty items to // the temporary vector to sort those items with their offsets. for (auto &entry : fcache->shards[i]->dirtyIndexNodes) { dirty_nodes.push_back(std::make_pair(i, entry.second)); } } else { auto entry = fcache->shards[i]->dirtyIndexNodes.begin(); if (entry != fcache->shards[i]->dirtyIndexNodes.end()) { dirty_nodes.push_back(std::make_pair(i, entry->second)); } } spin_unlock(&fcache->shards[i]->lock); } if (dirty_nodes.empty()) { break; } else if (dirty_nodes.size() > 1) { // Ensure that the dirty nodes are written in increasing // offset order std::sort(dirty_nodes.begin(), dirty_nodes.end(), dirtyNodesCustomSort); } } auto dirty_entry = dirty_nodes[count++]; size_t shard_num = dirty_entry.first; Bnode* dirty_bnode = dirty_entry.second; spin_lock(&fcache->shards[shard_num]->lock); shard_dirty_tree = &fcache->shards[shard_num]->dirtyIndexNodes; bool item_exist = false; if (!shard_dirty_tree->empty()) { if (shard_dirty_tree->find(dirty_bnode->getCurOffset()) != shard_dirty_tree->end()) { item_exist = true; } } if (!item_exist) { // The original item in the shard dirty index node map was removed. // Moving on to the next one in the cross-shard dirty node list spin_unlock(&fcache->shards[shard_num]->lock); if (count == dirty_nodes.size()) { count = 0; dirty_nodes.clear(); } continue; } // Remove from the shard dirty index node list shard_dirty_tree->erase(dirty_bnode->getCurOffset()); if (sync) { size_t nodesize = dirty_bnode->getNodeSize(); size_t blocksize = fcache->getFileManager()->getBlockSize(); size_t blocksize_avail = blocksize - sizeof(IndexBlkMeta); size_t offset_of_block = dirty_bnode->getCurOffset() % blocksize; size_t offset_of_buf = 0; size_t remaining_size = nodesize; void *buf = nullptr; if ( !(buf = dirty_bnode->exportRaw()) ) { // TODO: Handle this gracefully perhaps .. assert(false); } uint64_t dirty_bnode_offset = dirty_bnode->getCurOffset(); if (flush_all && count == 1) { temp_buf_args.batch_write_offset = dirty_bnode_offset; } if (flush_all && temp_buf_args.batch_write_offset + temp_buf_args.temp_buf_pos < dirty_bnode_offset) { // To avoid 'node size' field (4 bytes) being written over multiple // blocks, a few bytes can be skipped and we need to calibrate it. // before calibration, we should append block meta if necessary. bid_t prev_bid = (temp_buf_args.batch_write_offset + temp_buf_args.temp_buf_pos) / blocksize; bid_t cur_bid = dirty_bnode_offset / blocksize; size_t prev_blk_offset = (temp_buf_args.batch_write_offset + temp_buf_args.temp_buf_pos) % blocksize; // skipped length should be smaller than 4 bytes. if (prev_bid + 1 == cur_bid && prev_blk_offset + sizeof(uint32_t) > blocksize_avail) { // adjust temp_buf_pos to point to the IndexBlkMeta location // (i.e., the last 16 bytes in the block). temp_buf_args.temp_buf_pos += (blocksize_avail - prev_blk_offset); IndexBlkMeta blk_meta; blk_meta.set(cur_bid, fcache->getFileManager()->getSbBmpRevnum()); temp_buf_args.data_to_append = &blk_meta; temp_buf_args.size_to_append = sizeof(IndexBlkMeta); temp_buf_args.cur_offset = prev_bid * blocksize + blocksize_avail; status = writeCachedData(temp_buf_args); if (status != FDB_RESULT_SUCCESS) { spin_unlock(&fcache->shards[shard_num]->lock); return status; } } } if (remaining_size <= blocksize_avail - offset_of_block) { // entire node can be written in a block .. just write it. temp_buf_args.data_to_append = buf; temp_buf_args.size_to_append = remaining_size; temp_buf_args.cur_offset = dirty_bnode->getCurOffset(); status = writeCachedData(temp_buf_args); if (status != FDB_RESULT_SUCCESS) { spin_unlock(&fcache->shards[shard_num]->lock); return status; } } else { IndexBlkMeta blk_meta; size_t cur_slice_size; size_t num_blocks = dirty_bnode->getBidListSize(); bid_t cur_bid; for (size_t i = 0; i < num_blocks; ++i) { cur_bid = dirty_bnode->getBidFromList(i); cur_slice_size = blocksize_avail - offset_of_block; if (cur_slice_size > remaining_size) { cur_slice_size = remaining_size; } // write data for the block temp_buf_args.data_to_append = static_cast<uint8_t*>(buf) + offset_of_buf; temp_buf_args.size_to_append = cur_slice_size; temp_buf_args.cur_offset = cur_bid * blocksize + offset_of_block; status = writeCachedData(temp_buf_args); if (status != FDB_RESULT_SUCCESS) { spin_unlock(&fcache->shards[shard_num]->lock); return status; } remaining_size -= cur_slice_size; offset_of_buf += cur_slice_size; if (remaining_size) { // Intermediate block, write metadata to indicate it blk_meta.set(dirty_bnode->getBidFromList(i+1), fcache->getFileManager()->getSbBmpRevnum()); temp_buf_args.data_to_append = &blk_meta; temp_buf_args.size_to_append = sizeof(IndexBlkMeta); temp_buf_args.cur_offset = cur_bid * blocksize + blocksize_avail; status = writeCachedData(temp_buf_args); if (status != FDB_RESULT_SUCCESS) { spin_unlock(&fcache->shards[shard_num]->lock); return status; } // new block .. reset block offset offset_of_block = 0; } } } // Move to the shard clean node list list_push_back(&fcache->shards[shard_num]->cleanNodes, &dirty_bnode->list_elem); flushed += dirty_bnode->getNodeSize(); } else { // Not synced, just discarded fcache->numItems--; fcache->numItemsWritten--; // Remove from the all node list fcache->shards[shard_num]->allNodes.erase(dirty_bnode->getCurOffset()); // Decrement memory usage bnodeCacheCurrentUsage.fetch_sub(dirty_bnode->getMemConsumption()); flushed += dirty_bnode->getNodeSize(); // Free the dirty node as it can be simply discarded delete dirty_bnode; } spin_unlock(&fcache->shards[shard_num]->lock); if (count == dirty_nodes.size()) { count = 0; dirty_nodes.clear(); } if (sync) { if (flush_all || flushed < flushLimit) { continue; } else { break; } } } if (flush_all && temp_buf_args.temp_buf_pos) { ret = fcache->getFileManager()->writeBuf(temp_buf_args.temp_buf.get(), temp_buf_args.temp_buf_pos, temp_buf_args.batch_write_offset); if (ret != static_cast<ssize_t>(temp_buf_args.temp_buf_pos)) { status = ret < 0 ? (fdb_status)ret : FDB_RESULT_WRITE_FAIL; return status; } } return status; } bool BnodeCacheMgr::prepareDeallocationForFileBnodeCache(FileBnodeCache* fcache) { bool ret = true; if (writer_lock(&fileListLock) == 0) { // Remove from the global file list bool found = false; for (auto entry = fileList.begin(); entry != fileList.end(); ++entry) { if (*entry == fcache) { fileList.erase(entry); found = true; break; } } if (!found) { // File has already been removed form fileList writer_unlock(&fileListLock); return false; } if (fcache->getRefCount() != 0) { // The file bnode cache is currently being accessed by another // thread for eviction fileZombies.push_front(fcache); ret = false; // Delay the deletion } writer_unlock(&fileListLock); } else { ret = false; fdb_log(nullptr, FDB_RESULT_LOCK_FAIL, "BnodeCacheMgr::prepareDeallocationForFileBnodeCache(): " "Failed to acquire writer lock on the file list lock!"); } return ret; } void BnodeCacheMgr::cleanUpInvalidFileBnodeCaches() { if (writer_lock(&fileListLock) == 0) { for (auto itr = fileZombies.begin(); itr != fileZombies.end();) { if (freeFileBnodeCache(*itr)) { itr = fileZombies.erase(itr); } else { ++itr; } } writer_unlock(&fileListLock); } else { fdb_log(nullptr, FDB_RESULT_LOCK_FAIL, "BnodeCacheMgr::cleanUpInvalidFileBnodeCaches(): " "Failed to acquire writer lock on the file list lock!"); } } void BnodeCacheMgr::performEviction(Bnode *node_to_protect) { // The global bnode cache lock need not be acquired here because the // file's bnode cache instance (FileBnodeCache) can be freed only if // there are no database handles opened for the file. struct list_elem* elem; Bnode* item = nullptr; FileBnodeCache* victim = nullptr; // Select the victim and then the clean blocks from the victim file, eject // items until memory usage falls 4K (max btree node size) less than // the allowed bnodeCacheLimit. // TODO: Maybe implement a daemon task that does this eviction, // rather than the reader/writer doing it. while (bnodeCacheCurrentUsage.load() >= bnodeCacheLimit) { // Firstly, select the victim file victim = chooseEvictionVictim(); if (victim && victim->setEvictionInProgress(true)) { // Check whether the file has at least one block to be evicted, // if not try picking a random victim again if (victim->numItems.load() == 0) { victim->refCount--; victim->setEvictionInProgress(false); victim = nullptr; } } else if (victim) { victim->refCount--; victim = nullptr; } if (victim == nullptr) { continue; } size_t num_shards = victim->getNumShards(); size_t i = random(num_shards); BnodeCacheShard* bshard = nullptr; size_t toVisit = num_shards; while (bnodeCacheCurrentUsage.load() > (bnodeCacheLimit - 4096) && toVisit-- != 0) { i = (i + 1) % num_shards; // Round-robin over empty shards bshard = victim->shards[i].get(); spin_lock(&bshard->lock); if (bshard->empty()) { spin_unlock(&bshard->lock); continue; } if (list_empty(&bshard->cleanNodes)) { spin_unlock(&bshard->lock); // When the victim shard has no clean index node, evict // some dirty blocks from shards. fdb_status status = flushDirtyIndexNodes(victim, true, false); if (status != FDB_RESULT_SUCCESS) { fdb_log(nullptr, status, "BnodeCacheMgr::performEviction(): Flushing dirty " "index nodes failed for shard %s in file '%s'", std::to_string(i).c_str(), victim->getFileName().c_str()); return; } spin_lock(&bshard->lock); } elem = list_pop_front(&bshard->cleanNodes); if (elem) { item = reinterpret_cast<Bnode*>(elem); if (item != node_to_protect && item->getRefCount() == 0) { victim->numVictims++; victim->numItems--; // Remove from the shard nodes list bshard->allNodes.erase(item->getCurOffset()); // Decrement mem usage stat bnodeCacheCurrentUsage.fetch_sub(item->getMemConsumption()); // Free bnode instance delete item; } else { list_push_back(&bshard->cleanNodes, &item->list_elem); } } spin_unlock(&bshard->lock); } victim->refCount--; victim->setEvictionInProgress(false); victim = nullptr; } } static const size_t MAX_VICTIM_SELECTIONS = 5; static const size_t MIN_TIMESTAMP_GAP = 15000; // 15 seconds FileBnodeCache* BnodeCacheMgr::chooseEvictionVictim() { FileBnodeCache* ret = nullptr; uint64_t max_items = 0; uint64_t min_timestamp = static_cast<uint64_t>(-1); uint64_t max_timestamp = 0; uint64_t victim_timestamp, victim_num_items; int victim_idx, victim_by_time = -1, victim_by_items = -1; size_t num_attempts; if (reader_lock(&fileListLock) == 0) { // Pick the victim that has the oldest access timestamp // among the files randomly selected, if the gap between // the oldest and the newest timestamps is greater than // the threshold. Otherwise, pick the victim that has the // largest number of cached items among the files. num_attempts = fileList.size() / 10 + 1; if (num_attempts > MAX_VICTIM_SELECTIONS) { num_attempts = MAX_VICTIM_SELECTIONS; } else { if (num_attempts == 1 && fileList.size() > 1) { ++num_attempts; } } for (size_t i = 0; i < num_attempts && !fileList.empty(); ++i) { victim_idx = rand() % fileList.size(); victim_timestamp = fileList[victim_idx]->getAccessTimestamp(); victim_num_items = fileList[victim_idx]->numItems; if (victim_num_items) { if (victim_timestamp < min_timestamp) { min_timestamp = victim_timestamp; victim_by_time = victim_idx; } if (victim_timestamp > max_timestamp) { max_timestamp = victim_timestamp; } if (victim_num_items > max_items) { max_items = victim_num_items; victim_by_items = victim_idx; } } } if (max_timestamp - min_timestamp > MIN_TIMESTAMP_GAP) { if (victim_by_time != -1) { ret = fileList.at(victim_by_time); } } else { if (victim_by_items != -1) { ret = fileList.at(victim_by_items); } } if (ret) { ret->refCount++; } reader_unlock(&fileListLock); } else { fdb_log(nullptr, FDB_RESULT_LOCK_FAIL, "BnodeCacheMgr::chooseEvictionVictim(): " "Failed to acquire reader lock on the file list lock!"); } return ret; } void BnodeCacheMgr::removeSelectBnodes(FileMgr* file, std::vector<Bnode*>& nodes) { if (!file) { return; } FileBnodeCache* fcache = file->getBnodeCache(); if (!fcache) { return; } for (auto node : nodes) { size_t shard_num = str_hash(std::to_string(node->getCurOffset())) % fcache->getNumShards(); spin_lock(&fcache->shards[shard_num]->lock); // Search shard hash table auto entry = fcache->shards[shard_num]->allNodes.find(node->getCurOffset()); if (entry != fcache->shards[shard_num]->allNodes.end()) { // Remove from all nodes list fcache->shards[shard_num]->allNodes.erase(node->getCurOffset()); // Remove from dirty index nodes (if present) fcache->shards[shard_num]->dirtyIndexNodes.erase(node->getCurOffset()); // Remove from clean nodes (if present) list_remove(&fcache->shards[shard_num]->cleanNodes, &node->list_elem); fcache->numItems--; fcache->numItemsWritten--; // Decrement memory usage bnodeCacheCurrentUsage.fetch_sub(node->getMemConsumption()); } spin_unlock(&fcache->shards[shard_num]->lock); } }
22,539
416
/* NSExtensionRequestHandling.h Copyright (c) 2013-2019, Apple Inc. All rights reserved. */ #import <Foundation/Foundation.h> #if __OBJC2__ NS_ASSUME_NONNULL_BEGIN @class NSExtensionContext; // The basic NSExtensionRequestHandling protocol defines a lifecycle hook into the extension. Non view-controller-based services might keep track of the current request using this method. Implemented by the principal object of the extension. @protocol NSExtensionRequestHandling <NSObject> @required // Tells the extension to prepare its interface for the requesting context, and request related data items. At this point [(NS|UI)ViewController extensionContext] returns a non-nil value. This message is delivered after initialization, but before the conforming object will be asked to "do something" with the context (i.e. before -[(NS|UI)ViewController loadView]). Subclasses of classes conforming to this protocol are expected to call [super beginRequestWithExtensionContext:] if this method is overridden. - (void)beginRequestWithExtensionContext:(NSExtensionContext *)context; @end NS_ASSUME_NONNULL_END #endif
296
763
package org.batfish.question.multipath; import static com.google.common.base.MoreObjects.firstNonNull; import static org.batfish.common.util.TracePruner.DEFAULT_MAX_TRACES; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.batfish.datamodel.PacketHeaderConstraints; import org.batfish.datamodel.questions.Question; import org.batfish.question.specifiers.PathConstraintsInput; import org.batfish.specifier.Location; /** * A zero-input question to check for multipath inconsistencies. It computes all-pairs reachability * from any {@link Location source} to any destination, and returns traces for all detected * multipath inconsistencies. * * <p>In the future, we can consider adding a flag that would stop the reachability analysis after * the first multipath inconsistency is found. */ public class MultipathConsistencyQuestion extends Question { private static final String PROP_HEADERS = "headers"; private static final String PROP_MAX_TRACES = "maxTraces"; private static final String PROP_PATH_CONSTRAINTS = "pathConstraints"; @Nonnull private final PacketHeaderConstraints _headerConstraints; private final int _maxTraces; @Nonnull private final PathConstraintsInput _pathConstraints; @JsonCreator public MultipathConsistencyQuestion( @Nullable @JsonProperty(PROP_HEADERS) PacketHeaderConstraints headerConstraints, @Nullable @JsonProperty(PROP_MAX_TRACES) Integer maxTraces, @Nullable @JsonProperty(PROP_PATH_CONSTRAINTS) PathConstraintsInput pathConstraints) { setDifferential(false); _headerConstraints = firstNonNull(headerConstraints, PacketHeaderConstraints.unconstrained()); _maxTraces = firstNonNull(maxTraces, DEFAULT_MAX_TRACES); _pathConstraints = firstNonNull(pathConstraints, PathConstraintsInput.unconstrained()); } public MultipathConsistencyQuestion() { this(null, null, null); } @Override public boolean getDataPlane() { return true; } @JsonProperty(PROP_HEADERS) @Nonnull PacketHeaderConstraints getHeaderConstraints() { return _headerConstraints; } @JsonProperty(PROP_MAX_TRACES) public int getMaxTraces() { return _maxTraces; } @Override public String getName() { return "multipath"; } @JsonProperty(PROP_PATH_CONSTRAINTS) @Nonnull PathConstraintsInput getPathConstraints() { return _pathConstraints; } }
823
571
/*************************************************************************** Copyright 2015 Ufora Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ #ifndef BSA_CORE_AtomicOps_hppml_ #define BSA_CORE_AtomicOps_hppml_ #include "Platform.hpp" #include <stdint.h> //include guard wrapper for atomic ops. should reimplement necessary functions on windows #if defined(BSA_PLATFORM_LINUX) || defined(BSA_PLATFORM_APPLE) #if __x86_64__ || _WIN64 typedef volatile int64_t AO_t; #else typedef volatile int32_t AO_t; #endif inline AO_t AO_fetch_and_add_full(AO_t* refcount, AO_t ct) { return __sync_fetch_and_add(refcount, ct); } inline AO_t AO_load(AO_t* value) { __sync_synchronize(); return *value; } inline void AO_store(AO_t* value, AO_t toStore) { __sync_synchronize(); *value = toStore; __sync_synchronize(); } inline bool AO_compare_and_swap_full(AO_t* val, AO_t toCheckAgainst, AO_t toSwapInIfSuccessful) { return __sync_bool_compare_and_swap(val, toCheckAgainst, toSwapInIfSuccessful); } inline void fullMemoryBarrier() { __sync_synchronize(); } #else #if __x86_64__ || _WIN64 typedef volatile uint64_t AO_t; #else typedef volatile __int32 AO_t; #endif AO_t AO_fetch_and_add_full(AO_t* refcount, AO_t ct); AO_t AO_load(AO_t* value); void AO_store(AO_t* value, AO_t toStore); bool AO_compare_and_swap_full(AO_t* val, AO_t toCheckAgainst, AO_t toSwapInIfSuccessful); #endif #endif
783
14,361
<reponame>eivindbohler/GPUImage #import "GPUImage3x3TextureSamplingFilter.h" @interface GPUImageDirectionalSobelEdgeDetectionFilter : GPUImage3x3TextureSamplingFilter @end
61
1,362
package org.mitre.synthea.helpers; import java.util.Map; import org.yaml.snakeyaml.Yaml; /** * Helper class to parse a YAML file into a (hopefully) useable map format. * This is useful for arbitrary YAML which doesn't try to adhere to any schema. * (If it does adhere to a schema, * there are other methods to parse YAML to objects which should be preferred) * Java doesn't have dynamic typing so this class exposes a "get" method which takes a path string, * and walks the map to find the desired item. */ public class SimpleYML { /** * The internal representation of the YAML file. */ private Map<String,?> internalMap; /** * Create a new SimpleYML from the String contents from a file. * * @param rawContent YML file as a String */ public SimpleYML(String rawContent) { Yaml yaml = new Yaml(); internalMap = (Map<String,?>) yaml.load(rawContent); } /** * Get the object at the given path from the YML. * For example, given the following YML:<pre> * foo: * bar: 2 * baz: 4 * qux: * corge: 9 * grault: -1 * plugh: 7 * </pre> * calling get("foo.qux.grault") will return Integer(-1) * * @param path Path to desired object * @return the object at path */ public Object get(String path) { String[] pathSegments = path.split("\\."); Map<String,?> current = internalMap; // note: length-2 because we don't want to get the last piece as a map for (int i = 0; i <= pathSegments.length - 2; i++) { current = (Map<String,?>) current.get(pathSegments[i]); } return current.get(pathSegments[pathSegments.length - 1]); } }
595
568
<reponame>jgtaylor123/novoda_spikes<gh_stars>100-1000 package com.novoda.magicmirror; import android.Manifest; import android.app.Dialog; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.WindowManager; import android.widget.Toast; import com.novoda.magicmirror.facerecognition.FaceStatusView; import com.novoda.magicmirror.facerecognition.LookingEyes; import com.novoda.magicmirror.sfx.FacialExpressionEffects; import com.novoda.magicmirror.sfx.SfxMappings; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.novoda.notils.caster.Views; import com.novoda.notils.logger.simple.Log; import com.novoda.magicmirror.facerecognition.CameraSourcePreview; import com.novoda.magicmirror.facerecognition.FaceCameraSource; import com.novoda.magicmirror.facerecognition.FaceDetectionUnavailableException; import com.novoda.magicmirror.facerecognition.FaceExpression; import com.novoda.magicmirror.facerecognition.FaceReactionSource; import com.novoda.magicmirror.facerecognition.FaceTracker; import com.novoda.magicmirror.facerecognition.KeyToFaceMappings; import com.novoda.magicmirror.facerecognition.KeyboardFaceSource; import com.novoda.magicmirror.sfx.GlowView; import com.novoda.magicmirror.sfx.ParticlesLayout; public class FaceRecognitionActivity extends AppCompatActivity { private static final int CAMERA_PERMISSION_REQUEST = 0; private final DeviceInformation deviceInformation = new DeviceInformation(); private FaceReactionSource faceSource; private CameraSourcePreview preview; private SystemUIHider systemUIHider; private FaceStatusView faceStatus; private LookingEyes lookingEyes; private GlowView glowView; private ParticlesLayout particlesView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_face_recognition); lookingEyes = (LookingEyes) findViewById(R.id.looking_eyes); faceStatus = (FaceStatusView) findViewById(R.id.status); preview = (CameraSourcePreview) findViewById(R.id.preview); glowView = Views.findById(this, R.id.glow_background); particlesView = Views.findById(this, R.id.particles); particlesView.initialise(); systemUIHider = new SystemUIHider(findViewById(android.R.id.content)); keepScreenOn(); boolean hasCamera = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT); if (!hasCamera) { Toast.makeText(this, R.string.no_camera_available_error, Toast.LENGTH_SHORT).show(); finish(); return; } if (isUsingCamera()) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST ); } else { tryToCreateCameraSource(); } displayErrorIfPlayServicesMissing(); } else { createKeyboardSource(); } } private boolean isUsingCamera() { return !deviceInformation.isEmulator(); } private void keepScreenOn() { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private void createKeyboardSource() { KeyToFaceMappings mappings = KeyToFaceMappings.newInstance(); faceSource = new KeyboardFaceSource(faceListener, mappings); } private void tryToCreateCameraSource() { try { faceSource = FaceCameraSource.createFrom(this, faceListener, preview); } catch (FaceDetectionUnavailableException e) { Toast.makeText(this, R.string.face_detection_not_available_error, Toast.LENGTH_LONG).show(); } } private void displayErrorIfPlayServicesMissing() { int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this); if (code != ConnectionResult.SUCCESS) { Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(this, code, 101); dlg.show(); } } @Override protected void onResume() { super.onResume(); systemUIHider.hideSystemUi(); if (faceSourceHasBeenDefined()) { faceSource.start(); } } private boolean faceSourceHasBeenDefined() { return faceSource != null; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == CAMERA_PERMISSION_REQUEST) { if (isPermissionGranted(grantResults)) { tryToCreateCameraSource(); } else { Log.e("User denied CAMERA permission"); finish(); } } } private boolean isPermissionGranted(@NonNull int[] grantResults) { return grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED; } @Override protected void onPause() { super.onPause(); preview.stop(); lookingEyes.hide(); systemUIHider.showSystemUi(); } @Override protected void onDestroy() { super.onDestroy(); if (faceSourceHasBeenDefined()) { faceSource.release(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (faceSource.onKeyDown(keyCode)) { return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (faceSource.onKeyUp(keyCode)) { return true; } return super.onKeyUp(keyCode, event); } private final FaceTracker.FaceListener faceListener = new FaceTracker.FaceListener() { private final SfxMappings mappings = SfxMappings.newInstance(); @Override public void onNewFace(final FaceExpression expression) { runOnUiThread(new Runnable() { @Override public void run() { FacialExpressionEffects effects = mappings.forExpression(expression); glowView.transitionToColor(effects.glowColorRes()); if (effects.hasParticle()) { particlesView.startParticles(effects.getParticle()); } else { particlesView.stopParticles(); } if (expression.isMissing()) { lookingEyes.show(); faceStatus.hide(); } else { lookingEyes.hide(); faceStatus.setExpression(expression); faceStatus.show(); } } }); } }; }
3,054
460
package org.sxdata.jingwei.service.Impl; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.sxdata.jingwei.bean.PageforBean; import org.sxdata.jingwei.dao.CarteInfoDao; import org.sxdata.jingwei.dao.SlaveDao; import org.sxdata.jingwei.dao.UserGroupDao; import org.sxdata.jingwei.entity.CarteInfoEntity; import org.sxdata.jingwei.entity.SlaveEntity; import org.sxdata.jingwei.entity.SlaveUserRelationEntity; import org.sxdata.jingwei.entity.UserGroupAttributeEntity; import org.sxdata.jingwei.service.SlaveService; import org.sxdata.jingwei.util.CommonUtil.StringDateUtil; import org.sxdata.jingwei.util.TaskUtil.CarteClient; import org.sxdata.jingwei.util.TaskUtil.CarteStatusVo; import org.sxdata.jingwei.util.TaskUtil.KettleEncr; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by cRAZY on 2017/2/28. */ @Service public class SlaveServiceImpl implements SlaveService { @Autowired protected SlaveDao slaveDao; @Autowired protected CarteInfoDao carteInfoDao; @Autowired protected UserGroupDao userGroupDao; @Override public Integer getAllSlaveSize() { return slaveDao.getAllSlave("").size(); } public String[] getXvalue(List<CarteInfoEntity> items) throws Exception{ String[] xValue=new String[items.size()]; for(int i=0;i<items.size();i++){ CarteInfoEntity item=items.get(i); String xHour=item.getxHour(); xValue[i]=xHour+"็‚น"; } return xValue; } public String[] getXvalue(List<CarteInfoEntity> items,String flag) throws Exception{ String[] xValue=new String[items.size()]; for(int i=0;i<items.size();i++){ CarteInfoEntity item=items.get(i); String nDate=StringDateUtil.dateToString(item.getnDate(),"yyyy-MM-dd HH:mm:ss"); nDate=nDate.substring(11,16); xValue[i]=nDate; } return xValue; } @Override //่Žทๅ–ๆ‰€ๆœ‰่Š‚็‚น็š„ๆ‰€ๆœ‰ๆŒ‡ๆ ‡ไฟกๆฏ(ๆŸไธชๆ—ถ้—ดๆฎต,้ป˜่ฎค3ไธชๅฐๆ—ถๅ†…็š„) public String allSlaveQuato(String userGroupName) throws Exception { List<SlaveEntity> slaves=slaveDao.getAllSlave(userGroupName); JSONObject result=new JSONObject(); //่ดŸ่ฝฝ JSONObject loadAvg=new JSONObject(); //CPU JSONObject cpuUsage=new JSONObject(); //็บฟ็จ‹ๆ•ฐ JSONObject threadNum=new JSONObject(); //ๅ†…ๅญ˜ JSONObject freeMem=new JSONObject(); //่ฎพ็ฝฎ่ตทๅง‹ๅ’Œ็ป“ๆŸ็š„ๆ—ถ้—ดๆฎต Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 3); String minDate= StringDateUtil.dateToString(calendar.getTime(), "yyyy-MM-dd HH:mm:ss"); String maxDate=StringDateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"); //X่ฝดๆ—ถ้—ดๅๆ ‡ ๅ››ไธชๆŠ˜็บฟๅ›พ้€š็”จ JSONObject xValue=new JSONObject(); xValue.put("type","category"); xValue.put("boundaryGap",false); //ๆŠ˜็บฟๅ›พ้กถ้ƒจ็š„่Š‚็‚นhostNameๅ ๅ››ไธชๆŠ˜็บฟๅ›พ้€š็”จ String[] legend=new String[slaves.size()]; //ๆธฒๆŸ“่ดŸ่ฝฝๆŠ˜็บฟๅ›พ JSONArray loadAvgDataArray=new JSONArray(); JSONObject loadAvgYValue=new JSONObject(); loadAvgYValue.put("type","value"); loadAvgYValue.put("min",0); float maxLoadAvg=0; //ๆธฒๆŸ“็บฟ็จ‹ๆ•ฐๆŠ˜็บฟๅ›พ JSONArray threadNumDataArray=new JSONArray(); JSONObject threadNumYValue=new JSONObject(); threadNumYValue.put("type", "value"); threadNumYValue.put("min",0); Integer maxThreadNum=0; //ๆธฒๆŸ“CPUไฝฟ็”จ็އๆŠ˜็บฟๅ›พ JSONArray cpuUsageDataArray=new JSONArray(); JSONObject cpuUsageYValue=new JSONObject(); cpuUsageYValue.put("type", "value"); cpuUsageYValue.put("min",0); double maxCpuUsage=0.0; //ๆธฒๆŸ“็ฉบ้—ฒๅ†…ๅญ˜ๆŠ˜็บฟๅ›พ JSONArray freeMemDataArray=new JSONArray(); JSONObject freeMemYValue=new JSONObject(); freeMemYValue.put("type", "value"); freeMemYValue.put("min",0); Integer maxFreeMem=0; for(int i1=0;i1<slaves.size();i1++){ SlaveEntity slave=slaves.get(i1); List<CarteInfoEntity> items=carteInfoDao.getSlaveQuatoBySlaveId(minDate, maxDate, slave.getSlaveId()); //ๆŠ˜็บฟๅ›พX่ฝดๅ†…ๅฎนๅŠๅ‚ๆ•ฐ if(i1==0){ xValue.put("data",this.getXvalue(items,"")); } //ๆŠ˜็บฟๅ›พ็š„้กถ้ƒจ ๆ–‡ๅญ—ๆ่ฟฐ legend[i1]=slave.getHostName(); //่Žทๅ–ๆŠ˜็บฟๆฏไธช็‚น็š„ๅ–ๅ€ผ float[] loadAvgs=new float[items.size()]; int[] threadNums=new int[items.size()]; double [] cpuUsages=new double[items.size()]; int[] freeMems=new int[items.size()]; for(int j1=0;j1<items.size();j1++){ CarteInfoEntity item=items.get(j1); loadAvgs[j1]=item.getLoadAvg(); threadNums[j1]=item.getThreadNum(); Double cpuUsageValue=Double.valueOf(item.getHostCpuUsage().trim().substring(0,item.getHostCpuUsage().trim().length()-1)); cpuUsages[j1]=cpuUsageValue; int hostFreeMem=Integer.valueOf(item.getHostFreeMem().trim().substring(0,item.getHostFreeMem().trim().length()-2)); freeMems[j1]=hostFreeMem/1024; } //่Žทๅ–ๆฏไธชๆŠ˜็บฟๅ›พY่ฝดๆ‰€้œ€่ฆ็š„ๆœ€ๅคงๅ€ผ float thisSlaveMaxLoadAvg=StringDateUtil.getMaxValueByFloatArray(loadAvgs); Integer thisSlaveMaxThreadNum=StringDateUtil.getMaxValueByIntArray(threadNums); double thisSlaveMaxCpuUsage=StringDateUtil.getMaxValueBydoubleArray(cpuUsages); Integer thisSlaveMaxFreeMem=StringDateUtil.getMaxValueByIntArray(freeMems); if(maxCpuUsage<thisSlaveMaxCpuUsage) maxCpuUsage=thisSlaveMaxCpuUsage; if(maxFreeMem<thisSlaveMaxFreeMem) maxFreeMem=thisSlaveMaxFreeMem; if (maxLoadAvg<thisSlaveMaxLoadAvg) maxLoadAvg=thisSlaveMaxLoadAvg; if (maxThreadNum<thisSlaveMaxThreadNum) maxThreadNum=thisSlaveMaxThreadNum; //่ดŸ่ฝฝๆŠ˜็บฟๅ›พๆ•ฐๆฎ JSONObject loadAvgData=new JSONObject(); loadAvgData.put("name",slave.getHostName()); loadAvgData.put("type","line"); loadAvgData.put("data",loadAvgs); loadAvgDataArray.add(loadAvgData); //็บฟ็จ‹ๆ•ฐๆŠ˜็บฟๅ›พๆ•ฐๆฎ JSONObject threadNumData=new JSONObject(); threadNumData.put("name",slave.getHostName()); threadNumData.put("type","line"); threadNumData.put("data", threadNums); threadNumDataArray.add(threadNumData); //CPUไฝฟ็”จ็އๆŠ˜็บฟๅ›พๆ•ฐๆฎ JSONObject cpuUsageData=new JSONObject(); cpuUsageData.put("name",slave.getHostName()); cpuUsageData.put("type","line"); cpuUsageData.put("data", cpuUsages); cpuUsageDataArray.add(cpuUsageData); //็ฉบ้—ฒๅ†…ๅญ˜ๆŠ˜็บฟๅ›พๆ•ฐๆฎๅ’ŒY่ฝด JSONObject freeMemData=new JSONObject(); freeMemData.put("name",slave.getHostName()); freeMemData.put("type","line"); freeMemData.put("data", freeMems); freeMemDataArray.add(freeMemData); } //่ดŸ่ฝฝY่ฝดๆœ€ๅคงๅ€ผ if(maxLoadAvg<=5){ loadAvgYValue.put("max",5); }else if(maxLoadAvg<=10){ loadAvgYValue.put("max",10); }else if(maxLoadAvg<=20){ loadAvgYValue.put("max",20); }else{ loadAvgYValue.put("max",40); } //็บฟ็จ‹ๆ•ฐY่ฝดๆœ€ๅคงๅ€ผ if(maxThreadNum<=100){ threadNumYValue.put("max",100); }else if(maxThreadNum<=200){ threadNumYValue.put("max",200); }else if(maxThreadNum<=500){ threadNumYValue.put("max",500); }else{ threadNumYValue.put("max",1000); } //cpuไฝฟ็”จ็އY่ฝดๆœ€ๅคงๅ€ผ if(maxCpuUsage<=1.0){ cpuUsageYValue.put("max",1.0); }else if(maxCpuUsage<=2.0){ cpuUsageYValue.put("max",2.0); }else if(maxCpuUsage<=5.0){ cpuUsageYValue.put("max",5.0); }else if(maxCpuUsage<=10.0){ cpuUsageYValue.put("max",10.0); }else if(maxCpuUsage<=20.0){ cpuUsageYValue.put("max",20.0); }else{ cpuUsageYValue.put("max",50.0); } JSONObject cpuAxisLable=new JSONObject(); cpuAxisLable.put("formatter","{value} %"); cpuUsageYValue.put("axisLabel",cpuAxisLable); //็ฉบ้—ฒๅ†…ๅญ˜Y่ฝดๆœ€ๅคงๅ€ผ if(maxFreeMem<=1000){ freeMemYValue.put("max",1000); }else if(maxFreeMem<2000){ freeMemYValue.put("max",2000); }else if(maxFreeMem<5000){ freeMemYValue.put("max",5000); }else{ freeMemYValue.put("max",10000); } JSONObject freeMemAxisLable=new JSONObject(); freeMemAxisLable.put("formatter","{value} MB"); freeMemYValue.put("axisLabel",freeMemAxisLable); //่ดŸ่ฝฝ loadAvg.put("Y",loadAvgYValue); loadAvg.put("X",xValue); loadAvg.put("series",loadAvgDataArray); loadAvg.put("legend",legend); //็บฟ็จ‹ๆ•ฐ threadNum.put("legend",legend); threadNum.put("X",xValue); threadNum.put("series",threadNumDataArray); threadNum.put("Y",threadNumYValue); //cpuไฝฟ็”จ็އ cpuUsage.put("legend",legend); cpuUsage.put("X",xValue); cpuUsage.put("series",cpuUsageDataArray); cpuUsage.put("Y",cpuUsageYValue); //็ฉบ้—ฒๅ†…ๅญ˜ freeMem.put("legend",legend); freeMem.put("X",xValue); freeMem.put("series",freeMemDataArray); freeMem.put("Y",freeMemYValue); //ๅ››ไธชๆŠ˜็บฟๅ›พ็ป„่ฃ…็š„json result.put("loadAvg",loadAvg); result.put("threadNum",threadNum); result.put("cpuUsage",cpuUsage); result.put("freeMem",freeMem); return result.toString(); } @Override //ๆ‰€ๆœ‰่Š‚็‚นๆŸไธชๆŒ‡ๆ ‡ไฟกๆฏ็š„ๆŠ˜็บฟๅ›พ public String slaveQuatoLineChart(String quatoType,String maxOrAvg,String chooseDate,String userGroupName) throws Exception { List<SlaveEntity> slaves=slaveDao.getAllSlave(userGroupName); if(null==slaves || slaves.size()<1) return null; /* try{ slaves=setLoadAvgAndStatus(slaves); }catch (Exception e){ e.printStackTrace(); }*/ JSONObject result=new JSONObject(); //่ฎพ็ฝฎ้œ€่ฆ่Žทๅ–ๆŒ‡ๆ ‡ไฟกๆฏ็š„่ตทๆญขๆ—ถ้—ดๆฎต if(null==chooseDate || chooseDate==""){ chooseDate=StringDateUtil.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"); chooseDate=chooseDate.substring(0,10); }else{ chooseDate=chooseDate.substring(0,10); } String minDate= chooseDate+" 00:00:00"; String maxDate= chooseDate+" 23:59:59"; //X่ฝด ๆ—ถ้—ดๅๆ ‡ ไปปไฝ•ๆŒ‡ๆ ‡้กน้€š็”จ JSONObject xValue=new JSONObject(); xValue.put("type","category"); xValue.put("boundaryGap",false); //ๆŠ˜็บฟๅ›พ้กถ้ƒจ็š„่Š‚็‚นhostNameๅ ไปปไฝ•ๆŒ‡ๆ ‡้€š็”จ String[] legend=new String[slaves.size()]; for(int i=0;i<slaves.size();i++){ SlaveEntity slave=slaves.get(i); List<CarteInfoEntity> items=new ArrayList<CarteInfoEntity>(); if(maxOrAvg.equals("ๆœ€ๅคงๅ€ผ")){ items=carteInfoDao.slaveQuatoByMax(minDate,maxDate,slave.getSlaveId()); }else{ items=carteInfoDao.slaveQuatoByAvg(minDate, maxDate, slave.getSlaveId()); } if(i==0){ xValue.put("data",this.getXvalue(items)); } //ๆŠ˜็บฟๅ›พ็š„้กถ้ƒจ ๆ–‡ๅญ—ๆ่ฟฐ legend[i]=slave.getHostName(); } //ๆŠ˜็บฟๅ›พY่ฝดไปฅๅŠๆ‰€ๆœ‰ๆŠ˜็บฟๅ†…ๅฎน็š„้›†ๅˆ JSONObject yValue=new JSONObject(); yValue.put("type", "value"); yValue.put("min", 0); JSONArray series=new JSONArray(); if(quatoType.equals("่ดŸ่ฝฝๆŒ‡ๆ•ฐ")){ float maxLoadAvg=0; for(int i1=0;i1<slaves.size();i1++){ SlaveEntity slave=slaves.get(i1); List<CarteInfoEntity> items=new ArrayList<CarteInfoEntity>(); if(maxOrAvg.equals("ๆœ€ๅคงๅ€ผ")){ items=carteInfoDao.slaveQuatoByMax(minDate,maxDate,slave.getSlaveId()); }else{ items=carteInfoDao.slaveQuatoByAvg(minDate, maxDate, slave.getSlaveId()); } float[] loadAvgs=new float[items.size()]; for(int j1=0;j1<items.size();j1++){ CarteInfoEntity item=items.get(j1); loadAvgs[j1]=item.getLoadAvg(); } float thisSlaveMax=StringDateUtil.getMaxValueByFloatArray(loadAvgs); if(thisSlaveMax>maxLoadAvg) maxLoadAvg=thisSlaveMax; //่ดŸ่ฝฝๆŠ˜็บฟๅ›พY่ฝดๅ’Œๆ•ฐๆฎ JSONObject loadAvgData=new JSONObject(); loadAvgData.put("name",slave.getHostName()); loadAvgData.put("type","line"); loadAvgData.put("data",loadAvgs); series.add(loadAvgData); } if(maxLoadAvg<=5){ yValue.put("max",5); }else if(maxLoadAvg<=10){ yValue.put("max",10); }else if(maxLoadAvg<=20){ yValue.put("max",20); }else{ yValue.put("max",40); } }else if(quatoType.equals("CPUๅˆฉ็”จ็އ")){ Double maxCpuUsage=0.0; for(int i1=0;i1<slaves.size();i1++){ SlaveEntity slave=slaves.get(i1); List<CarteInfoEntity> items=new ArrayList<CarteInfoEntity>(); if(maxOrAvg.equals("ๆœ€ๅคงๅ€ผ")){ items=carteInfoDao.slaveQuatoByMax(minDate,maxDate,slave.getSlaveId()); }else{ items=carteInfoDao.slaveQuatoByAvg(minDate, maxDate, slave.getSlaveId()); } double [] cpuUsages=new double[items.size()]; for(int j1=0;j1<items.size();j1++){ CarteInfoEntity item=items.get(j1); Double cpuUsageValue=Double.valueOf(item.getHostCpuUsage().trim().substring(0, item.getHostCpuUsage().trim().length() - 1)); cpuUsages[j1]=cpuUsageValue; } Double thisSlaveMax=StringDateUtil.getMaxValueBydoubleArray(cpuUsages); if(maxCpuUsage<thisSlaveMax){ maxCpuUsage=thisSlaveMax; } JSONObject cpuUsageData=new JSONObject(); cpuUsageData.put("name",slave.getHostName()); cpuUsageData.put("type", "line"); cpuUsageData.put("data", cpuUsages); series.add(cpuUsageData); } if(maxCpuUsage<=1.0){ yValue.put("max",1.0); }else if(maxCpuUsage<=2.0){ yValue.put("max",2.0); }else if(maxCpuUsage<=5.0){ yValue.put("max",5.0); }else if(maxCpuUsage<=10.0){ yValue.put("max",10.0); }else if(maxCpuUsage<=20.0){ yValue.put("max",20.0); }else{ yValue.put("max",50.0); } JSONObject cpuAxisLable=new JSONObject(); cpuAxisLable.put("formatter","{value} %"); yValue.put("axisLabel",cpuAxisLable); }else if(quatoType.equals("็ฉบ้—ฒๅ†…ๅญ˜")){ Integer maxFreeMem=0; for(int i1=0;i1<slaves.size();i1++){ SlaveEntity slave=slaves.get(i1); List<CarteInfoEntity> items=new ArrayList<CarteInfoEntity>(); if(maxOrAvg.equals("ๆœ€ๅคงๅ€ผ")){ items=carteInfoDao.slaveQuatoByMax(minDate,maxDate,slave.getSlaveId()); }else{ items=carteInfoDao.slaveQuatoByAvg(minDate, maxDate, slave.getSlaveId()); } int[] freeMems=new int[items.size()]; for(int j1=0;j1<items.size();j1++){ CarteInfoEntity item=items.get(j1); int hostFreeMem=Integer.valueOf(item.getHostFreeMem()); freeMems[j1]=hostFreeMem/1024; } Integer thisSlaveMax=StringDateUtil.getMaxValueByIntArray(freeMems); if(thisSlaveMax>maxFreeMem){ maxFreeMem=thisSlaveMax; } JSONObject freeMemData=new JSONObject(); freeMemData.put("name",slave.getHostName()); freeMemData.put("type", "line"); freeMemData.put("data", freeMems); series.add(freeMemData); } if(maxFreeMem<=1000){ yValue.put("max",1000); }else if(maxFreeMem<2000){ yValue.put("max",2000); }else if(maxFreeMem<5000){ yValue.put("max",5000); }else{ yValue.put("max",10000); } JSONObject freeMemAxisLable=new JSONObject(); freeMemAxisLable.put("formatter","{value} MB"); yValue.put("axisLabel",freeMemAxisLable); }else if(quatoType.equals("็บฟ็จ‹ๆ•ฐ")){ Integer maxThreadNum=0; for(int i1=0;i1<slaves.size();i1++){ SlaveEntity slave=slaves.get(i1); List<CarteInfoEntity> items=new ArrayList<CarteInfoEntity>(); if(maxOrAvg.equals("ๆœ€ๅคงๅ€ผ")){ items=carteInfoDao.slaveQuatoByMax(minDate,maxDate,slave.getSlaveId()); }else{ items=carteInfoDao.slaveQuatoByAvg(minDate, maxDate, slave.getSlaveId()); } int[] threadNums=new int[items.size()]; for(int j1=0;j1<items.size();j1++){ CarteInfoEntity item=items.get(j1); threadNums[j1]=item.getThreadNum(); } Integer thisSlaveMax=StringDateUtil.getMaxValueByIntArray(threadNums); if(thisSlaveMax>maxThreadNum){ maxThreadNum=thisSlaveMax; } JSONObject threadNumData=new JSONObject(); threadNumData.put("name",slave.getHostName()); threadNumData.put("type", "line"); threadNumData.put("data", threadNums); series.add(threadNumData); } if(maxThreadNum<=100){ yValue.put("max",100); }else if(maxThreadNum<=200){ yValue.put("max",200); }else if(maxThreadNum<=500){ yValue.put("max",500); }else{ yValue.put("max",1000); } }else if(quatoType.equals("็ฉบ้—ฒ็กฌ็›˜")){ Integer maxFreeDisk=0; for(int i1=0;i1<slaves.size();i1++){ SlaveEntity slave=slaves.get(i1); List<CarteInfoEntity> items=new ArrayList<CarteInfoEntity>(); if(maxOrAvg.equals("ๆœ€ๅคงๅ€ผ")){ items=carteInfoDao.slaveQuatoByMax(minDate,maxDate,slave.getSlaveId()); }else{ items=carteInfoDao.slaveQuatoByAvg(minDate, maxDate, slave.getSlaveId()); } int[] hostFreeDisks=new int[items.size()]; for(int j1=0;j1<items.size();j1++){ CarteInfoEntity item=items.get(j1); hostFreeDisks[j1]=Integer.valueOf(item.getHostFreeDisk()); } Integer thisSlaveMax=StringDateUtil.getMaxValueByIntArray(hostFreeDisks); if(thisSlaveMax>maxFreeDisk){ maxFreeDisk=thisSlaveMax; } JSONObject freeDiskData=new JSONObject(); freeDiskData.put("name",slave.getHostName()); freeDiskData.put("type", "line"); freeDiskData.put("data", hostFreeDisks); series.add(freeDiskData); } if(maxFreeDisk<=50){ yValue.put("max",50); }else if(maxFreeDisk<=100){ yValue.put("max",100); }else if(maxFreeDisk<=200){ yValue.put("max",200); }else if(maxFreeDisk<=500){ yValue.put("max",500); }else if(maxFreeDisk<=1000){ yValue.put("max",1000); }else{ yValue.put("max",2000); } JSONObject diskAxisLable=new JSONObject(); diskAxisLable.put("formatter","{value} GB"); yValue.put("axisLabel",diskAxisLable); }else if(quatoType.equals("ไฝœไธšๆ•ฐ")){ Integer maxJobNum=0; for(int i1=0;i1<slaves.size();i1++){ SlaveEntity slave=slaves.get(i1); List<CarteInfoEntity> items=new ArrayList<CarteInfoEntity>(); if(maxOrAvg.equals("ๆœ€ๅคงๅ€ผ")){ items=carteInfoDao.slaveQuatoByMax(minDate,maxDate,slave.getSlaveId()); }else{ items=carteInfoDao.slaveQuatoByAvg(minDate, maxDate, slave.getSlaveId()); } int[] jobNums=new int[items.size()]; for(int j1=0;j1<items.size();j1++){ CarteInfoEntity item=items.get(j1); jobNums[j1]=item.getJobNum(); } Integer thisSlaveMax=StringDateUtil.getMaxValueByIntArray(jobNums); if(thisSlaveMax>maxJobNum) maxJobNum=thisSlaveMax; JSONObject jobNumData=new JSONObject(); jobNumData.put("name",slave.getHostName()); jobNumData.put("type","line"); jobNumData.put("data", jobNums); series.add(jobNumData); } if(maxJobNum<10){ yValue.put("max",10); }else if(maxJobNum<20){ yValue.put("max",20); }else if(maxJobNum<50){ yValue.put("max",50); }else if(maxJobNum<100){ yValue.put("max",100); }else if(maxJobNum<500){ yValue.put("max",500); } }else if(quatoType.equals("่ฝฌๆขๆ•ฐ")){ Integer maxTransNum=0; for(int i1=0;i1<slaves.size();i1++){ SlaveEntity slave=slaves.get(i1); List<CarteInfoEntity> items=new ArrayList<CarteInfoEntity>(); if(maxOrAvg.equals("ๆœ€ๅคงๅ€ผ")){ items=carteInfoDao.slaveQuatoByMax(minDate,maxDate,slave.getSlaveId()); }else{ items=carteInfoDao.slaveQuatoByAvg(minDate, maxDate, slave.getSlaveId()); } int[] transNums=new int[items.size()]; for(int j1=0;j1<items.size();j1++){ CarteInfoEntity item=items.get(j1); transNums[j1]=item.getTransNum(); } Integer thisSlaveMax=StringDateUtil.getMaxValueByIntArray(transNums); if(thisSlaveMax>maxTransNum) maxTransNum=thisSlaveMax; JSONObject transNumData=new JSONObject(); transNumData.put("name",slave.getHostName()); transNumData.put("type","line"); transNumData.put("data", transNums); series.add(transNumData); } if(maxTransNum<10){ yValue.put("max",10); }else if(maxTransNum<20){ yValue.put("max",20); }else if(maxTransNum<50){ yValue.put("max",50); }else if(maxTransNum<100){ yValue.put("max",100); }else if(maxTransNum<500){ yValue.put("max",500); } } result.put("X",xValue); result.put("legend",legend); result.put("Y",yValue); result.put("series",series); return result.toString(); } @Override //ๆ‰€ๆœ‰่Š‚็‚นๆŸไธชๆŒ‡ๆ ‡ไฟกๆฏ็š„ๆŸฑๅฝขๅ›พ public String slaveQuatoColumnDiagram(String quatoType,String maxOrAvg,String chooseDate,String userGroupName) throws Exception { return null; } @Override //ๆ‰€ๆœ‰่Š‚็‚นๆŸไธชๆŒ‡ๆ ‡ไฟกๆฏ็š„ๆ–‡ๆœฌ public String slaveQuatoHTMLText(String quatoType,String maxOrAvg,String chooseDate,String userGroupName) throws Exception { return null; } @Override //่Žทๅ–ๆ‰€ๆœ‰่Š‚็‚น็š„ๆŸไธชๆŒ‡ๆ ‡้กนไฟกๆฏ //param1:่Š‚็‚น็š„ๅ“ชไธชๆŒ‡ๆ ‡ params2:่ง†ๅ›พ็ฑปๅž‹ param3:ๆ˜พ็คบๅนณๅ‡ๅ€ผ่ฟ˜ๆ˜ฏๆœ€ๅคงๅ€ผ public String slaveQuatoByCondition(String quatoType,String viewType,String maxOrAvg,String chooseDate,String userGroupName) throws Exception { String result=null; if(viewType.equals("ๆŠ˜็บฟๅ›พ")){ result=this.slaveQuatoLineChart(quatoType,maxOrAvg,chooseDate,userGroupName); }else if(viewType.equals("ๆŸฑๅฝขๅ›พ")){ result=this.slaveQuatoColumnDiagram(quatoType,maxOrAvg,chooseDate,userGroupName); }else{ result=this.slaveQuatoHTMLText(quatoType,maxOrAvg,chooseDate,userGroupName); } return result; } //่ฎพ็ฝฎ่Š‚็‚น็š„่ดŸ่ฝฝๅ’Œ็Šถๆ€ public List<SlaveEntity> setLoadAvgAndStatus(List<SlaveEntity> slaves) throws Exception{ List<SlaveEntity> result=new ArrayList<SlaveEntity>(); for(SlaveEntity slave:slaves){ //ๅฏนๅ–ๅ‡บ็š„่Š‚็‚นๅฏ†็ ่ฟ›่กŒ่งฃ็ ้‡ๆ–ฐ่ต‹ๅ€ผ slave.setPassword(<PASSWORD>(slave.getPassword())); //่Žทๅ–่Š‚็‚น็Šถๆ€็š„็›ธๅ…ณไฟกๆฏ CarteClient carteClient=new CarteClient(slave); String status=null; status=carteClient.getStatusOrNull(); boolean dbActive=!carteClient.isDBActive(); CarteStatusVo carteStatusVo = null; if (status != null) { if (dbActive) { carteStatusVo = CarteStatusVo.parseXml(status); //่ฎพ็ฝฎ่ดŸ่ฝฝไปฅๅŠ่Š‚็‚นๆ˜ฏๅฆๆญฃๅธธ slave.setLoadAvg(carteStatusVo.getLoadAvg()); slave.setStatus("<font color='green'>่Š‚็‚นๆญฃๅธธ</font>"); } else { slave.setLoadAvg(0); slave.setStatus("<font color='red'>่ฏฅ่Š‚็‚น่ฟžๆŽฅ่ต„ๆบๆ•ฐๆฎๅบ“ๅผ‚ๅธธ</font>"); } } else { slave.setLoadAvg(0); slave.setStatus("<font color='red'>่Š‚็‚นๅผ‚ๅธธ</font>"); } result.add(slave); } return result; } @Override //่Žทๅ–ๆ‰€ๆœ‰่Š‚็‚นไฟกๆฏ public List<SlaveEntity> getAllSlave(String userGroupName) throws Exception { List<SlaveEntity> slaves=slaveDao.getAllSlave(userGroupName); return this.setLoadAvgAndStatus(slaves); } @Override //้€‰ๆ‹ฉไธ€ไธช่ดŸ่ฝฝๆŒ‡ๆ•ฐๆœ€ไฝŽ็š„่Š‚็‚น public SlaveEntity getSlaveByLoadAvg(List<SlaveEntity> slaves) throws Exception { SlaveEntity minSlave=null; List<SlaveEntity> errorSlaves=new ArrayList<SlaveEntity>(); if(slaves!=null && slaves.size()>0){ //่Žทๅ–ไธๆญฃๅธธ่Š‚็‚น for(int i=0;i<slaves.size();i++){ if (slaves.get(i).getLoadAvg()==0){ errorSlaves.add(slaves.get(i)); } } //็งป้™คไธๆญฃๅธธ่Š‚็‚น for(SlaveEntity errorSlave:errorSlaves){ slaves.remove(errorSlave); } //ไปŽๆญฃๅธธ่Š‚็‚นไธญ่Žทๅ–่ดŸ่ฝฝๆŒ‡ๆ•ฐๆœ€ไฝŽ็š„่Š‚็‚น if(slaves.size()==1){ minSlave=slaves.get(0); }else if(slaves.size()>1){ minSlave=slaves.get(0); for(int i=0;i<slaves.size();i++){ if (slaves.get(i).getLoadAvg()<minSlave.getLoadAvg()){ minSlave=slaves.get(i); } } } } return minSlave; } @Override public PageforBean findSlaveByPageInfo(Integer start, Integer limit,String userGroupName) throws Exception { List<SlaveEntity> slaves=slaveDao.findSlaveByPageInfo(start,limit,userGroupName); //่ฟ›ไธ€ๆญฅ่Žทๅ–่Š‚็‚น็š„่ฏฆ็ป†ไฟกๆฏ ่ฟ่กŒ็š„ไฝœไธš/่ฝฌๆขๆ•ฐ ๅœจ็บฟๆ—ถ้•ฟ็ญ‰ for(SlaveEntity slave:slaves){ slave.setPassword(<PASSWORD>(slave.getPassword())); CarteClient cc=new CarteClient(slave); String status=null; CarteStatusVo vo=null; status=cc.getStatusOrNull(); boolean dbActive=!cc.isDBActive(); if(status!=null){ //่ฎพ็ฝฎ่Š‚็‚น ่ฟ่กŒไธญ็š„ไฝœไธš/่ฝฌๆขๆ•ฐ ่ฟ่กŒๆ—ถ้—ด vo=CarteStatusVo.parseXml(status); slave.setRunningJobNum(vo.getRunningJobNum()); slave.setRunningTransNum(vo.getRunningTransNum()); slave.setUpTime(vo.getUpTime()); //่ฎพ็ฝฎ่Š‚็‚น็š„็Šถๆ€ไปฅๅŠ่ดŸ่ฝฝ if (dbActive) { //่ฎพ็ฝฎ่ดŸ่ฝฝไปฅๅŠ่Š‚็‚นๆ˜ฏๅฆๆญฃๅธธ slave.setLoadAvg(vo.getLoadAvg()); slave.setStatus("<font color='green'>่Š‚็‚นๆญฃๅธธ</font>"); } else { slave.setLoadAvg(0); slave.setStatus("<font color='red'>่ฏฅ่Š‚็‚น่ฟžๆŽฅ่ต„ๆบๆ•ฐๆฎๅบ“ๅผ‚ๅธธ</font>"); } //TODO ๅทฒๅฎŒๆˆ็š„ไฝœไธš/่ฝฌๆข้œ€่ฆไปŽๆ—ฅๅฟ—่กจ่Žทๅ– // slave.setFinishJobNum(XXXX); //slave.setFinishTransNum(XXX); }else{ slave.setLoadAvg(0); slave.setStatus("<font color='red'>่Š‚็‚นๅผ‚ๅธธ</font>"); } } //่Žทๅ–ๆ€ป่ฎฐๅฝ•ๆ•ฐ Integer count=slaveDao.getSlaveTotalCount(); PageforBean result=new PageforBean(); result.setRoot(slaves); result.setTotalProperty(count); return result; } @Override public void deleteSlave(Integer slaveId) throws Exception { /* ObjectId objectId=new LongObjectId(slaveId); App.getInstance().getRepository().deleteSlave(objectId);*/ slaveDao.deleteTransSlave(slaveId); slaveDao.deleteSlaveUserGroup(slaveId); slaveDao.deleteSlaveServer(slaveId); } @Override public String slaveTest(String hostName) throws Exception{ JSONObject json=new JSONObject(); SlaveEntity slave=slaveDao.getSlaveByHostName(hostName); slave.setPassword(KettleEncr.decryptPasswd(slave.getPassword())); CarteClient cc=new CarteClient(slave); boolean isActive=cc.isActive(); int timeOut=3000; boolean slaveNetStatus= InetAddress.getByName(hostName).isReachable(timeOut); if(isActive){ json.put("carteStatus","Y"); }else{ json.put("carteStatus","N"); } /* if(isdbActive){ json.put("slaveRepo","Y"); }else{ json.put("slaveRepo","N"); }*/ if(slaveNetStatus){ json.put("slaveNetwork","Y"); }else{ json.put("slaveNetwork","N"); } String jarArray=""; try { boolean isdbActive=!cc.isDBActive(); String hostInfo=cc.getSlaveHostInfo(); if(!StringDateUtil.isEmpty(hostInfo)){ jarArray=hostInfo.split("\\$")[3]; } }catch (Exception e){ } json.put("slaveJarSupport",jarArray); return json.toString(); } @Override public String addSlave(HttpServletRequest request) throws Exception{ String result="Y"; JSONObject json=JSONObject.fromObject(request.getParameter("slaveServer")); SlaveEntity slave=(SlaveEntity)JSONObject.toBean(json,SlaveEntity.class); slave.setPassword(<PASSWORD>(slave.getPassword())); Integer id=slaveDao.selectMaxId(); if(null==id) id=1; else id+=1; slave.setSlaveId(id); //ๅˆคๆ–ญๆ˜ฏๅฆๅญ˜ๅœจ็›ธๅŒ็š„่Š‚็‚น List<SlaveEntity> items=slaveDao.getAllSlave(""); for(SlaveEntity item:items){ if(item.getHostName().equals(slave.getHostName()) && item.getPort().equals(slave.getPort())){ result="N"; return result; } } slaveDao.addSlave(slave); //ๅˆคๆ–ญๆทปๅŠ ่Š‚็‚น็š„ๆ˜ฏadmin่ฟ˜ๆ˜ฏๆ™ฎ้€š็ฎก็†ๅ‘˜ Integer typeId=Integer.valueOf(request.getParameter("userType")); if(typeId==1){ UserGroupAttributeEntity attr=(UserGroupAttributeEntity)request.getSession().getAttribute("userInfo"); String userGroupName=attr.getUserGroupName(); SlaveUserRelationEntity sr=new SlaveUserRelationEntity(); sr.setSlaveId(id); sr.setUserGroupName(userGroupName); userGroupDao.addUserSlaveRelation(sr); }else{ String[] userGroupNameArray=request.getParameterValues("userGroupArray"); if(null!=userGroupNameArray && userGroupNameArray.length>0){ for(String userGroupName:userGroupNameArray){ if(!StringDateUtil.isEmpty(userGroupName)){ SlaveUserRelationEntity sr=new SlaveUserRelationEntity(); sr.setSlaveId(id); sr.setUserGroupName(userGroupName); userGroupDao.addUserSlaveRelation(sr); } } } } return result; } @Override public String updateSlave(HttpServletRequest request) throws Exception { String result="Y"; JSONObject json=JSONObject.fromObject(request.getParameter("slaveServer")); SlaveEntity targetSlave=(SlaveEntity)JSONObject.toBean(json,SlaveEntity.class); targetSlave.setPassword(<PASSWORD>.<PASSWORD>(targetSlave.getPassword())); //ๅˆคๆ–ญๆ˜ฏๅฆๅญ˜ๅœจ็›ธๅŒ่Š‚็‚น List<SlaveEntity> items=slaveDao.getAllSlave(""); for(SlaveEntity item:items){ if(item.getSlaveId().toString().equals(targetSlave.getSlaveId().toString())){ continue; } if(item.getHostName().equals(targetSlave.getHostName()) && item.getPort().equals(targetSlave.getPort())){ result="N"; return result; } if(item.getName().equals(targetSlave.getName())){ result="N"; return result; } } slaveDao.updateSlaveServer(targetSlave); return result; } @Override public SlaveEntity getSlaveByHostName(Integer id) throws Exception { return slaveDao.getSlaveById(id); } }
19,055
8,890
<reponame>PyVCEchecker/LightGBM<filename>tests/cpp_tests/test.py # coding: utf-8 from pathlib import Path import numpy as np preds = [np.loadtxt(str(name)) for name in Path(__file__).absolute().parent.glob('*.pred')] np.testing.assert_allclose(preds[0], preds[1])
103
471
package com.dtflys.spring.test.client0; import com.dtflys.forest.annotation.Request; /** * @author gongjun[<EMAIL>] * @since 2017-04-20 19:02 */ public interface BeastshopClient { @Request( url = "https://www.thebeastshop.com/", timeout = 80000, keyStore = "keystore1" ) String index(); @Request( url = "https://www.baidu.com/", timeout = 80000, keyStore = "keystore1" ) String index2(); }
236
1,008
<filename>turms-plugins/turms-plugin-antispam/src/main/java/im/turms/plugin/antispam/character/data/U80.java /* * Copyright (C) 2019 The Turms Project * https://github.com/turms-im/turms * * 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. */ // Generated Code - Do NOT edit manually package im.turms.plugin.antispam.character.data; public final class U80 { public static final char[][] DATA = { Common.$79616F, // '่€€'(8000) -> "yao" Common.$6C616F, // '่€'(8001) -> "lao" Common.$6C616F, // '่€‚'(8002) -> "lao" Common.$6B616F, // '่€ƒ'(8003) -> "kao" Common.$6D616F, // '่€„'(8004) -> "mao" Common.$7A6865, // '่€…'(8005) -> "zhe" Common.$7169, // '่€†'(8006) -> "qi" Common.$676F75, // '่€‡'(8007) -> "gou" Common.$676F75, // '่€ˆ'(8008) -> "gou" Common.$676F75, // '่€‰'(8009) -> "gou" Common.$646965, // '่€Š'(800A) -> "die" Common.$646965, // '่€‹'(800B) -> "die" Common.$6572, // '่€Œ'(800C) -> "er" Common.$73687561, // '่€'(800D) -> "shua" Common.$7275616E, // '่€Ž'(800E) -> "ruan" Common.$6E6169, // '่€'(800F) -> "nai" Common.$6E6169, // '่€'(8010) -> "nai" Common.$6475616E, // '่€‘'(8011) -> "duan" Common.$6C6569, // '่€’'(8012) -> "lei" Common.$74696E67, // '่€“'(8013) -> "ting" Common.$7A69, // '่€”'(8014) -> "zi" Common.$67656E67, // '่€•'(8015) -> "geng" Common.$6368616F, // '่€–'(8016) -> "chao" Common.$68616F, // '่€—'(8017) -> "hao" Common.$79756E, // '่€˜'(8018) -> "yun" Common.$6261, // '่€™'(8019) -> "ba" Common.$7069, // '่€š'(801A) -> "pi" Common.$7969, // '่€›'(801B) -> "yi" Common.$7369, // '่€œ'(801C) -> "si" Common.$7175, // '่€'(801D) -> "qu" Common.$6A6961, // '่€ž'(801E) -> "jia" Common.$6A75, // '่€Ÿ'(801F) -> "ju" Common.$68756F, // '่€ '(8020) -> "huo" Common.$636875, // '่€ก'(8021) -> "chu" Common.$6C616F, // '่€ข'(8022) -> "lao" Common.$6C756E, // '่€ฃ'(8023) -> "lun" Common.$6A69, // '่€ค'(8024) -> "ji" Common.$74616E67, // '่€ฅ'(8025) -> "tang" Common.$6F75, // '่€ฆ'(8026) -> "ou" Common.$6C6F75, // '่€ง'(8027) -> "lou" Common.$6E6F75, // '่€จ'(8028) -> "nou" Common.$6A69616E67, // '่€ฉ'(8029) -> "jiang" Common.$70616E67, // '่€ช'(802A) -> "pang" Common.$7A6861, // '่€ซ'(802B) -> "zha" Common.$6C6F75, // '่€ฌ'(802C) -> "lou" Common.$6A69, // '่€ญ'(802D) -> "ji" Common.$6C616F, // '่€ฎ'(802E) -> "lao" Common.$68756F, // '่€ฏ'(802F) -> "huo" Common.$796F75, // '่€ฐ'(8030) -> "you" Common.$6D6F, // '่€ฑ'(8031) -> "mo" Common.$68756169, // '่€ฒ'(8032) -> "huai" Common.$6572, // '่€ณ'(8033) -> "er" Common.$7969, // '่€ด'(8034) -> "yi" Common.$64696E67, // '่€ต'(8035) -> "ding" Common.$7965, // '่€ถ'(8036) -> "ye" Common.$6461, // '่€ท'(8037) -> "da" Common.$736F6E67, // '่€ธ'(8038) -> "song" Common.$71696E, // '่€น'(8039) -> "qin" Common.$79756E, // '่€บ'(803A) -> "yun" Common.$636869, // '่€ป'(803B) -> "chi" Common.$64616E, // '่€ผ'(803C) -> "dan" Common.$64616E, // '่€ฝ'(803D) -> "dan" Common.$686F6E67, // '่€พ'(803E) -> "hong" Common.$67656E67, // '่€ฟ'(803F) -> "geng" Common.$7A6869, // '่€'(8040) -> "zhi" Common.$70616E, // '่'(8041) -> "pan" Common.$6E6965, // '่‚'(8042) -> "nie" Common.$64616E, // '่ƒ'(8043) -> "dan" Common.$7A68656E, // '่„'(8044) -> "zhen" Common.$636865, // '่…'(8045) -> "che" Common.$6C696E67, // '่†'(8046) -> "ling" Common.$7A68656E67, // '่‡'(8047) -> "zheng" Common.$796F75, // '่ˆ'(8048) -> "you" Common.$7761, // '่‰'(8049) -> "wa" Common.$6C69616F, // '่Š'(804A) -> "liao" Common.$6C6F6E67, // '่‹'(804B) -> "long" Common.$7A6869, // '่Œ'(804C) -> "zhi" Common.$6E696E67, // '่'(804D) -> "ning" Common.$7469616F, // '่Ž'(804E) -> "tiao" Common.$6572, // '่'(804F) -> "er" Common.$7961, // '่'(8050) -> "ya" Common.$746965, // '่‘'(8051) -> "tie" Common.$677561, // '่’'(8052) -> "gua" Common.$7875, // '่“'(8053) -> "xu" Common.$6C69616E, // '่”'(8054) -> "lian" Common.$68616F, // '่•'(8055) -> "hao" Common.$7368656E67, // '่–'(8056) -> "sheng" Common.$6C6965, // '่—'(8057) -> "lie" Common.$70696E, // '่˜'(8058) -> "pin" Common.$6A696E67, // '่™'(8059) -> "jing" Common.$6A75, // '่š'(805A) -> "ju" Common.$6269, // '่›'(805B) -> "bi" Common.$6469, // '่œ'(805C) -> "di" Common.$67756F, // '่'(805D) -> "guo" Common.$77656E, // '่ž'(805E) -> "wen" Common.$7875, // '่Ÿ'(805F) -> "xu" Common.$70696E67, // '่ '(8060) -> "ping" Common.$636F6E67, // '่ก'(8061) -> "cong" Common.$64696E67, // '่ข'(8062) -> "ding" Common.$6E69, // '่ฃ'(8063) -> "ni" Common.$74696E67, // '่ค'(8064) -> "ting" Common.$6A75, // '่ฅ'(8065) -> "ju" Common.$636F6E67, // '่ฆ'(8066) -> "cong" Common.$6B7569, // '่ง'(8067) -> "kui" Common.$6C69616E, // '่จ'(8068) -> "lian" Common.$6B7569, // '่ฉ'(8069) -> "kui" Common.$636F6E67, // '่ช'(806A) -> "cong" Common.$6C69616E, // '่ซ'(806B) -> "lian" Common.$77656E67, // '่ฌ'(806C) -> "weng" Common.$6B7569, // '่ญ'(806D) -> "kui" Common.$6C69616E, // '่ฎ'(806E) -> "lian" Common.$6C69616E, // '่ฏ'(806F) -> "lian" Common.$636F6E67, // '่ฐ'(8070) -> "cong" Common.$616F, // '่ฑ'(8071) -> "ao" Common.$7368656E67, // '่ฒ'(8072) -> "sheng" Common.$736F6E67, // '่ณ'(8073) -> "song" Common.$74696E67, // '่ด'(8074) -> "ting" Common.$6B7569, // '่ต'(8075) -> "kui" Common.$6E6965, // '่ถ'(8076) -> "nie" Common.$7A6869, // '่ท'(8077) -> "zhi" Common.$64616E, // '่ธ'(8078) -> "dan" Common.$6E696E67, // '่น'(8079) -> "ning" Common.$716965, // '่บ'(807A) -> "qie" Common.$6E69, // '่ป'(807B) -> "ni" Common.$74696E67, // '่ผ'(807C) -> "ting" Common.$74696E67, // '่ฝ'(807D) -> "ting" Common.$6C6F6E67, // '่พ'(807E) -> "long" Common.$7975, // '่ฟ'(807F) -> "yu" Common.$7975, // '่‚€'(8080) -> "yu" Common.$7A68616F, // '่‚'(8081) -> "zhao" Common.$7369, // '่‚‚'(8082) -> "si" Common.$7375, // '่‚ƒ'(8083) -> "su" Common.$7969, // '่‚„'(8084) -> "yi" Common.$7375, // '่‚…'(8085) -> "su" Common.$34, // '่‚†'(8086) -> "4" Common.$7A68616F, // '่‚‡'(8087) -> "zhao" Common.$7A68616F, // '่‚ˆ'(8088) -> "zhao" Common.$726F75, // '่‚‰'(8089) -> "rou" Common.$7969, // '่‚Š'(808A) -> "yi" Common.$6C65, // '่‚‹'(808B) -> "le" Common.$6A69, // '่‚Œ'(808C) -> "ji" Common.$716975, // '่‚'(808D) -> "qiu" Common.$6B656E, // '่‚Ž'(808E) -> "ken" Common.$63616F, // '่‚'(808F) -> "cao" Common.$6765, // '่‚'(8090) -> "ge" Common.$626F, // '่‚‘'(8091) -> "bo" Common.$6875616E, // '่‚’'(8092) -> "huan" Common.$6875616E67, // '่‚“'(8093) -> "huang" Common.$636869, // '่‚”'(8094) -> "chi" Common.$72656E, // '่‚•'(8095) -> "ren" Common.$7869616F, // '่‚–'(8096) -> "xiao" Common.$7275, // '่‚—'(8097) -> "ru" Common.$7A686F75, // '่‚˜'(8098) -> "zhou" Common.$7975616E, // '่‚™'(8099) -> "yuan" Common.$6475, // '่‚š'(809A) -> "du" Common.$67616E67, // '่‚›'(809B) -> "gang" Common.$726F6E67, // '่‚œ'(809C) -> "rong" Common.$67616E, // '่‚'(809D) -> "gan" Common.$636861, // '่‚ž'(809E) -> "cha" Common.$776F, // '่‚Ÿ'(809F) -> "wo" Common.$6368616E67, // '่‚ '(80A0) -> "chang" Common.$6775, // '่‚ก'(80A1) -> "gu" Common.$7A6869, // '่‚ข'(80A2) -> "zhi" Common.$68616E, // '่‚ฃ'(80A3) -> "han" Common.$6675, // '่‚ค'(80A4) -> "fu" Common.$666569, // '่‚ฅ'(80A5) -> "fei" Common.$66656E, // '่‚ฆ'(80A6) -> "fen" Common.$706569, // '่‚ง'(80A7) -> "pei" Common.$70616E67, // '่‚จ'(80A8) -> "pang" Common.$6A69616E, // '่‚ฉ'(80A9) -> "jian" Common.$66616E67, // '่‚ช'(80AA) -> "fang" Common.$7A68756E, // '่‚ซ'(80AB) -> "zhun" Common.$796F75, // '่‚ฌ'(80AC) -> "you" Common.$6E61, // '่‚ญ'(80AD) -> "na" Common.$616E67, // '่‚ฎ'(80AE) -> "ang" Common.$6B656E, // '่‚ฏ'(80AF) -> "ken" Common.$72616E, // '่‚ฐ'(80B0) -> "ran" Common.$676F6E67, // '่‚ฑ'(80B1) -> "gong" Common.$7975, // '่‚ฒ'(80B2) -> "yu" Common.$77656E, // '่‚ณ'(80B3) -> "wen" Common.$79616F, // '่‚ด'(80B4) -> "yao" Common.$7169, // '่‚ต'(80B5) -> "qi" Common.$7069, // '่‚ถ'(80B6) -> "pi" Common.$7169616E, // '่‚ท'(80B7) -> "qian" Common.$7869, // '่‚ธ'(80B8) -> "xi" Common.$7869, // '่‚น'(80B9) -> "xi" Common.$666569, // '่‚บ'(80BA) -> "fei" Common.$6B656E, // '่‚ป'(80BB) -> "ken" Common.$6A696E67, // '่‚ผ'(80BC) -> "jing" Common.$746169, // '่‚ฝ'(80BD) -> "tai" Common.$7368656E, // '่‚พ'(80BE) -> "shen" Common.$7A686F6E67, // '่‚ฟ'(80BF) -> "zhong" Common.$7A68616E67, // '่ƒ€'(80C0) -> "zhang" Common.$786965, // '่ƒ'(80C1) -> "xie" Common.$7368656E, // '่ƒ‚'(80C2) -> "shen" Common.$776569, // '่ƒƒ'(80C3) -> "wei" Common.$7A686F75, // '่ƒ„'(80C4) -> "zhou" Common.$646965, // '่ƒ…'(80C5) -> "die" Common.$64616E, // '่ƒ†'(80C6) -> "dan" Common.$666569, // '่ƒ‡'(80C7) -> "fei" Common.$6261, // '่ƒˆ'(80C8) -> "ba" Common.$626F, // '่ƒ‰'(80C9) -> "bo" Common.$7175, // '่ƒŠ'(80CA) -> "qu" Common.$7469616E, // '่ƒ‹'(80CB) -> "tian" Common.$626569, // '่ƒŒ'(80CC) -> "bei" Common.$677561, // '่ƒ'(80CD) -> "gua" Common.$746169, // '่ƒŽ'(80CE) -> "tai" Common.$7A69, // '่ƒ'(80CF) -> "zi" Common.$666569, // '่ƒ'(80D0) -> "fei" Common.$7A6869, // '่ƒ‘'(80D1) -> "zhi" Common.$6E69, // '่ƒ’'(80D2) -> "ni" Common.$70696E67, // '่ƒ“'(80D3) -> "ping" Common.$7A69, // '่ƒ”'(80D4) -> "zi" Common.$6675, // '่ƒ•'(80D5) -> "fu" Common.$70616E67, // '่ƒ–'(80D6) -> "pang" Common.$7A68656E, // '่ƒ—'(80D7) -> "zhen" Common.$7869616E, // '่ƒ˜'(80D8) -> "xian" Common.$7A756F, // '่ƒ™'(80D9) -> "zuo" Common.$706569, // '่ƒš'(80DA) -> "pei" Common.$6A6961, // '่ƒ›'(80DB) -> "jia" Common.$7368656E67, // '่ƒœ'(80DC) -> "sheng" Common.$7A6869, // '่ƒ'(80DD) -> "zhi" Common.$62616F, // '่ƒž'(80DE) -> "bao" Common.$6D75, // '่ƒŸ'(80DF) -> "mu" Common.$7175, // '่ƒ '(80E0) -> "qu" Common.$6875, // '่ƒก'(80E1) -> "hu" Common.$6B65, // '่ƒข'(80E2) -> "ke" Common.$636869, // '่ƒฃ'(80E3) -> "chi" Common.$79696E, // '่ƒค'(80E4) -> "yin" Common.$7875, // '่ƒฅ'(80E5) -> "xu" Common.$79616E67, // '่ƒฆ'(80E6) -> "yang" Common.$6C6F6E67, // '่ƒง'(80E7) -> "long" Common.$646F6E67, // '่ƒจ'(80E8) -> "dong" Common.$6B61, // '่ƒฉ'(80E9) -> "ka" Common.$6C75, // '่ƒช'(80EA) -> "lu" Common.$6A696E67, // '่ƒซ'(80EB) -> "jing" Common.$6E75, // '่ƒฌ'(80EC) -> "nu" Common.$79616E, // '่ƒญ'(80ED) -> "yan" Common.$70616E67, // '่ƒฎ'(80EE) -> "pang" Common.$6B7561, // '่ƒฏ'(80EF) -> "kua" Common.$7969, // '่ƒฐ'(80F0) -> "yi" Common.$6775616E67, // '่ƒฑ'(80F1) -> "guang" Common.$686169, // '่ƒฒ'(80F2) -> "hai" Common.$6765, // '่ƒณ'(80F3) -> "ge" Common.$646F6E67, // '่ƒด'(80F4) -> "dong" Common.$636869, // '่ƒต'(80F5) -> "chi" Common.$6A69616F, // '่ƒถ'(80F6) -> "jiao" Common.$78696F6E67, // '่ƒท'(80F7) -> "xiong" Common.$78696F6E67, // '่ƒธ'(80F8) -> "xiong" Common.$6572, // '่ƒน'(80F9) -> "er" Common.$616E, // '่ƒบ'(80FA) -> "an" Common.$68656E67, // '่ƒป'(80FB) -> "heng" Common.$7069616E, // '่ƒผ'(80FC) -> "pian" Common.$6E656E67, // '่ƒฝ'(80FD) -> "neng" Common.$7A69, // '่ƒพ'(80FE) -> "zi" Common.$677569, // '่ƒฟ'(80FF) -> "gui" }; private U80() {} }
8,660
476
/**\file cloud_matcher.cpp * \brief Description... * * @version 1.0 * @author <NAME> */ // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #include <dynamic_robot_localization/common/common.h> #include <dynamic_robot_localization/cloud_matchers/impl/cloud_matcher.hpp> // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #ifndef DRL_NO_PRECOMPILE #include <pcl/impl/instantiate.hpp> #include <pcl/point_types.h> #define PCL_INSTANTIATE_DRLCloudMatcher(T) template class PCL_EXPORTS dynamic_robot_localization::CloudMatcher<T>; PCL_INSTANTIATE(DRLCloudMatcher, DRL_POINT_TYPES) #endif // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
426
5,774
/* * Nuklear - 1.32.0 - public domain * no warrenty implied; use at your own risk. * authored from 2015-2016 by <NAME> */ /* * ============================================================== * * API * * =============================================================== */ #ifndef NK_XLIB_GL2_H_ #define NK_XLIB_GL2_H_ #include <X11/Xlib.h> NK_API struct nk_context* nk_x11_init(Display *dpy, Window win); NK_API void nk_x11_font_stash_begin(struct nk_font_atlas **atlas); NK_API void nk_x11_font_stash_end(void); NK_API int nk_x11_handle_event(XEvent *evt); NK_API void nk_x11_render(enum nk_anti_aliasing, int max_vertex_buffer, int max_element_buffer); NK_API void nk_x11_shutdown(void); #endif /* * ============================================================== * * IMPLEMENTATION * * =============================================================== */ #ifdef NK_XLIB_GL2_IMPLEMENTATION #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <time.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xresource.h> #include <X11/Xlocale.h> #include <GL/gl.h> #ifndef NK_X11_DOUBLE_CLICK_LO #define NK_X11_DOUBLE_CLICK_LO 20 #endif #ifndef NK_X11_DOUBLE_CLICK_HI #define NK_X11_DOUBLE_CLICK_HI 200 #endif struct nk_x11_vertex { float position[2]; float uv[2]; nk_byte col[4]; }; struct nk_x11_device { struct nk_buffer cmds; struct nk_draw_null_texture null; GLuint font_tex; }; static struct nk_x11 { struct nk_x11_device ogl; struct nk_context ctx; struct nk_font_atlas atlas; Cursor cursor; Display *dpy; Window win; long last_button_click; } x11; NK_INTERN long nk_timestamp(void) { struct timeval tv; if (gettimeofday(&tv, NULL) < 0) return 0; return (long)((long)tv.tv_sec * 1000 + (long)tv.tv_usec/1000); } NK_INTERN void nk_x11_device_upload_atlas(const void *image, int width, int height) { struct nk_x11_device *dev = &x11.ogl; glGenTextures(1, &dev->font_tex); glBindTexture(GL_TEXTURE_2D, dev->font_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)width, (GLsizei)height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); } NK_API void nk_x11_render(enum nk_anti_aliasing AA, int max_vertex_buffer, int max_element_buffer) { /* setup global state */ struct nk_x11_device *dev = &x11.ogl; int width, height; XWindowAttributes attr; XGetWindowAttributes(x11.dpy, x11.win, &attr); width = attr.width; height = attr.height; glPushAttrib(GL_ENABLE_BIT|GL_COLOR_BUFFER_BIT|GL_TRANSFORM_BIT); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /* setup viewport/project */ glViewport(0,0,(GLsizei)width,(GLsizei)height); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0f, width, height, 0.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); { GLsizei vs = sizeof(struct nk_x11_vertex); size_t vp = offsetof(struct nk_x11_vertex, position); size_t vt = offsetof(struct nk_x11_vertex, uv); size_t vc = offsetof(struct nk_x11_vertex, col); /* convert from command queue into draw list and draw to screen */ const struct nk_draw_command *cmd; const nk_draw_index *offset = NULL; struct nk_buffer vbuf, ebuf; /* fill convert configuration */ struct nk_convert_config config; static const struct nk_draw_vertex_layout_element vertex_layout[] = { {NK_VERTEX_POSITION, NK_FORMAT_FLOAT, NK_OFFSETOF(struct nk_x11_vertex, position)}, {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, NK_OFFSETOF(struct nk_x11_vertex, uv)}, {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, NK_OFFSETOF(struct nk_x11_vertex, col)}, {NK_VERTEX_LAYOUT_END} }; memset(&config, 0, sizeof(config)); config.vertex_layout = vertex_layout; config.vertex_size = sizeof(struct nk_x11_vertex); config.vertex_alignment = NK_ALIGNOF(struct nk_x11_vertex); config.null = dev->null; config.circle_segment_count = 22; config.curve_segment_count = 22; config.arc_segment_count = 22; config.global_alpha = 1.0f; config.shape_AA = AA; config.line_AA = AA; /* convert shapes into vertexes */ nk_buffer_init_default(&vbuf); nk_buffer_init_default(&ebuf); nk_convert(&x11.ctx, &dev->cmds, &vbuf, &ebuf, &config); /* setup vertex buffer pointer */ {const void *vertices = nk_buffer_memory_const(&vbuf); glVertexPointer(2, GL_FLOAT, vs, (const void*)((const nk_byte*)vertices + vp)); glTexCoordPointer(2, GL_FLOAT, vs, (const void*)((const nk_byte*)vertices + vt)); glColorPointer(4, GL_UNSIGNED_BYTE, vs, (const void*)((const nk_byte*)vertices + vc));} /* iterate over and execute each draw command */ offset = (const nk_draw_index*)nk_buffer_memory_const(&ebuf); nk_draw_foreach(cmd, &x11.ctx, &dev->cmds) { if (!cmd->elem_count) continue; glBindTexture(GL_TEXTURE_2D, (GLuint)cmd->texture.id); glScissor( (GLint)(cmd->clip_rect.x), (GLint)((height - (GLint)(cmd->clip_rect.y + cmd->clip_rect.h))), (GLint)(cmd->clip_rect.w), (GLint)(cmd->clip_rect.h)); glDrawElements(GL_TRIANGLES, (GLsizei)cmd->elem_count, GL_UNSIGNED_SHORT, offset); offset += cmd->elem_count; } nk_clear(&x11.ctx); nk_buffer_clear(&dev->cmds); nk_buffer_free(&vbuf); nk_buffer_free(&ebuf); } /* default OpenGL state */ glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); } NK_API void nk_x11_font_stash_begin(struct nk_font_atlas **atlas) { nk_font_atlas_init_default(&x11.atlas); nk_font_atlas_begin(&x11.atlas); *atlas = &x11.atlas; } NK_API void nk_x11_font_stash_end(void) { const void *image; int w, h; image = nk_font_atlas_bake(&x11.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); nk_x11_device_upload_atlas(image, w, h); nk_font_atlas_end(&x11.atlas, nk_handle_id((int)x11.ogl.font_tex), &x11.ogl.null); if (x11.atlas.default_font) nk_style_set_font(&x11.ctx, &x11.atlas.default_font->handle); } NK_API int nk_x11_handle_event(XEvent *evt) { struct nk_context *ctx = &x11.ctx; /* optional grabbing behavior */ if (ctx->input.mouse.grab) { XDefineCursor(x11.dpy, x11.win, x11.cursor); ctx->input.mouse.grab = 0; } else if (ctx->input.mouse.ungrab) { XWarpPointer(x11.dpy, None, x11.win, 0, 0, 0, 0, (int)ctx->input.mouse.pos.x, (int)ctx->input.mouse.pos.y); XUndefineCursor(x11.dpy, x11.win); ctx->input.mouse.ungrab = 0; } if (evt->type == KeyPress || evt->type == KeyRelease) { /* Key handler */ int ret, down = (evt->type == KeyPress); KeySym *code = XGetKeyboardMapping(x11.dpy, (KeyCode)evt->xkey.keycode, 1, &ret); if (*code == XK_Shift_L || *code == XK_Shift_R) nk_input_key(ctx, NK_KEY_SHIFT, down); else if (*code == XK_Control_L || *code == XK_Control_R) nk_input_key(ctx, NK_KEY_CTRL, down); else if (*code == XK_Delete) nk_input_key(ctx, NK_KEY_DEL, down); else if (*code == XK_Return) nk_input_key(ctx, NK_KEY_ENTER, down); else if (*code == XK_Tab) nk_input_key(ctx, NK_KEY_TAB, down); else if (*code == XK_Left) nk_input_key(ctx, NK_KEY_LEFT, down); else if (*code == XK_Right) nk_input_key(ctx, NK_KEY_RIGHT, down); else if (*code == XK_Up) nk_input_key(ctx, NK_KEY_UP, down); else if (*code == XK_Down) nk_input_key(ctx, NK_KEY_DOWN, down); else if (*code == XK_BackSpace) nk_input_key(ctx, NK_KEY_BACKSPACE, down); else if (*code == XK_space && !down) nk_input_char(ctx, ' '); else if (*code == XK_Page_Up) nk_input_key(ctx, NK_KEY_SCROLL_UP, down); else if (*code == XK_Page_Down) nk_input_key(ctx, NK_KEY_SCROLL_DOWN, down); else if (*code == XK_Home) { nk_input_key(ctx, NK_KEY_TEXT_START, down); nk_input_key(ctx, NK_KEY_SCROLL_START, down); } else if (*code == XK_End) { nk_input_key(ctx, NK_KEY_TEXT_END, down); nk_input_key(ctx, NK_KEY_SCROLL_END, down); } else { if (*code == 'c' && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_COPY, down); else if (*code == 'v' && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_PASTE, down); else if (*code == 'x' && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_CUT, down); else if (*code == 'z' && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_TEXT_UNDO, down); else if (*code == 'r' && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_TEXT_REDO, down); else if (*code == XK_Left && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, down); else if (*code == XK_Right && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, down); else if (*code == 'b' && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_TEXT_LINE_START, down); else if (*code == 'e' && (evt->xkey.state & ControlMask)) nk_input_key(ctx, NK_KEY_TEXT_LINE_END, down); else { if (*code == 'i') nk_input_key(ctx, NK_KEY_TEXT_INSERT_MODE, down); else if (*code == 'r') nk_input_key(ctx, NK_KEY_TEXT_REPLACE_MODE, down); if (down) { char buf[32]; KeySym keysym = 0; if (XLookupString((XKeyEvent*)evt, buf, 32, &keysym, NULL) != NoSymbol) nk_input_glyph(ctx, buf); } } } XFree(code); return 1; } else if (evt->type == ButtonPress || evt->type == ButtonRelease) { /* Button handler */ int down = (evt->type == ButtonPress); const int x = evt->xbutton.x, y = evt->xbutton.y; if (evt->xbutton.button == Button1) { if (down) { /* Double-Click Button handler */ long dt = nk_timestamp() - x11.last_button_click; if (dt > NK_X11_DOUBLE_CLICK_LO && dt < NK_X11_DOUBLE_CLICK_HI) nk_input_button(ctx, NK_BUTTON_DOUBLE, x, y, nk_true); x11.last_button_click = nk_timestamp(); } else nk_input_button(ctx, NK_BUTTON_DOUBLE, x, y, nk_false); nk_input_button(ctx, NK_BUTTON_LEFT, x, y, down); } else if (evt->xbutton.button == Button2) nk_input_button(ctx, NK_BUTTON_MIDDLE, x, y, down); else if (evt->xbutton.button == Button3) nk_input_button(ctx, NK_BUTTON_RIGHT, x, y, down); else if (evt->xbutton.button == Button4) nk_input_scroll(ctx, nk_vec2(0,1.0f)); else if (evt->xbutton.button == Button5) nk_input_scroll(ctx, nk_vec2(0,-1.0f)); else return 0; return 1; } else if (evt->type == MotionNotify) { /* Mouse motion handler */ const int x = evt->xmotion.x, y = evt->xmotion.y; nk_input_motion(ctx, x, y); if (ctx->input.mouse.grabbed) { ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; XWarpPointer(x11.dpy, None, x11.win, 0, 0, 0, 0, (int)ctx->input.mouse.pos.x, (int)ctx->input.mouse.pos.y); } return 1; } else if (evt->type == KeymapNotify) { XRefreshKeyboardMapping(&evt->xmapping); return 1; } return 0; } NK_API struct nk_context* nk_x11_init(Display *dpy, Window win) { x11.dpy = dpy; x11.win = win; if (!setlocale(LC_ALL,"")) return 0; if (!XSupportsLocale()) return 0; if (!XSetLocaleModifiers("@im=none")) return 0; /* create invisible cursor */ {static XColor dummy; char data[1] = {0}; Pixmap blank = XCreateBitmapFromData(dpy, win, data, 1, 1); if (blank == None) return 0; x11.cursor = XCreatePixmapCursor(dpy, blank, blank, &dummy, &dummy, 0, 0); XFreePixmap(dpy, blank);} nk_buffer_init_default(&x11.ogl.cmds); nk_init_default(&x11.ctx, 0); return &x11.ctx; } NK_API void nk_x11_shutdown(void) { struct nk_x11_device *dev = &x11.ogl; nk_font_atlas_clear(&x11.atlas); nk_free(&x11.ctx); glDeleteTextures(1, &dev->font_tex); nk_buffer_free(&dev->cmds); XFreeCursor(x11.dpy, x11.cursor); memset(&x11, 0, sizeof(x11)); } #endif
6,907
634
#define WIN32_LEAN_AND_MEAN #define CINTERFACE #include <algorithm> #include <map> #include <vector> #include <dwmapi.h> #include <DDrawCompat/DDrawLog.h> #include <DDrawCompat/v0.3.1/D3dDdi/KernelModeThunks.h> #include <DDrawCompat/v0.3.1/D3dDdi/ScopedCriticalSection.h> #include <DDrawCompat/v0.3.1/DDraw/RealPrimarySurface.h> #include <DDrawCompat/v0.3.1/Gdi/PresentationWindow.h> #include <DDrawCompat/v0.3.1/Gdi/VirtualScreen.h> #include <DDrawCompat/v0.3.1/Gdi/Window.h> namespace { struct UpdateWindowContext { Gdi::Region obscuredRegion; Gdi::Region invalidatedRegion; Gdi::Region virtualScreenRegion; DWORD processId; }; struct Window { HWND hwnd; HWND presentationWindow; RECT windowRect; RECT clientRect; Gdi::Region windowRegion; Gdi::Region visibleRegion; Gdi::Region invalidatedRegion; COLORREF colorKey; BYTE alpha; bool isLayered; bool isVisibleRegionChanged; Window(HWND hwnd) : hwnd(hwnd) , presentationWindow(nullptr) , windowRect{} , clientRect{} , windowRegion(nullptr) , colorKey(CLR_INVALID) , alpha(255) , isLayered(true) , isVisibleRegionChanged(false) { } }; const RECT REGION_OVERRIDE_MARKER_RECT = { 32000, 32000, 32001, 32001 }; std::map<HWND, Window> g_windows; std::vector<Window*> g_windowZOrder; std::map<HWND, Window>::iterator addWindow(HWND hwnd) { DWMNCRENDERINGPOLICY ncRenderingPolicy = DWMNCRP_DISABLED; DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &ncRenderingPolicy, sizeof(ncRenderingPolicy)); BOOL disableTransitions = TRUE; DwmSetWindowAttribute(hwnd, DWMWA_TRANSITIONS_FORCEDISABLED, &disableTransitions, sizeof(disableTransitions)); const auto style = GetClassLong(hwnd, GCL_STYLE); if (style & CS_DROPSHADOW) { CALL_ORIG_FUNC(SetClassLongA)(hwnd, GCL_STYLE, style & ~CS_DROPSHADOW); } return g_windows.emplace(hwnd, Window(hwnd)).first; } bool bltWindow(const RECT& dst, const RECT& src, const Gdi::Region& clipRegion) { if (dst.left == src.left && dst.top == src.top || clipRegion.isEmpty()) { return false; } HDC screenDc = GetDC(nullptr); SelectClipRgn(screenDc, clipRegion); BitBlt(screenDc, dst.left, dst.top, src.right - src.left, src.bottom - src.top, screenDc, src.left, src.top, SRCCOPY); SelectClipRgn(screenDc, nullptr); ReleaseDC(nullptr, screenDc); return true; } Gdi::Region getWindowRegion(HWND hwnd) { Gdi::Region rgn; if (ERROR == CALL_ORIG_FUNC(GetWindowRgn)(hwnd, rgn)) { return nullptr; } return rgn; } void updatePosition(Window& window, const RECT& oldWindowRect, const RECT& oldClientRect, const Gdi::Region& oldVisibleRegion, Gdi::Region& invalidatedRegion) { const bool isClientOriginChanged = window.clientRect.left - window.windowRect.left != oldClientRect.left - oldWindowRect.left || window.clientRect.top - window.windowRect.top != oldClientRect.top - oldWindowRect.top; const bool isClientWidthChanged = window.clientRect.right - window.clientRect.left != oldClientRect.right - oldClientRect.left; const bool isClientHeightChanged = window.clientRect.bottom - window.clientRect.top != oldClientRect.bottom - oldClientRect.top; const bool isClientInvalidated = isClientWidthChanged && (GetClassLong(window.hwnd, GCL_STYLE) & CS_HREDRAW) || isClientHeightChanged && (GetClassLong(window.hwnd, GCL_STYLE) & CS_VREDRAW); const bool isFrameInvalidated = isClientOriginChanged || isClientWidthChanged || isClientHeightChanged || window.windowRect.right - window.windowRect.left != oldWindowRect.right - oldWindowRect.left || window.windowRect.bottom - window.windowRect.top != oldWindowRect.bottom - oldWindowRect.top; Gdi::Region preservedRegion; if (!isClientInvalidated || !isFrameInvalidated) { preservedRegion = oldVisibleRegion - invalidatedRegion; preservedRegion.offset(window.windowRect.left - oldWindowRect.left, window.windowRect.top - oldWindowRect.top); preservedRegion &= window.visibleRegion; if (isClientInvalidated) { preservedRegion -= window.clientRect; } else { if (isFrameInvalidated) { preservedRegion &= window.clientRect; } if (isClientWidthChanged) { RECT r = window.clientRect; r.left += oldClientRect.right - oldClientRect.left; if (r.left < r.right) { preservedRegion -= r; } } if (isClientHeightChanged) { RECT r = window.clientRect; r.top += oldClientRect.bottom - oldClientRect.top; if (r.top < r.bottom) { preservedRegion -= r; } } Gdi::Region updateRegion; GetUpdateRgn(window.hwnd, updateRegion, FALSE); updateRegion.offset(window.clientRect.left, window.clientRect.top); preservedRegion -= updateRegion; } bool isCopied = false; if (!isFrameInvalidated) { isCopied = bltWindow(window.windowRect, oldWindowRect, preservedRegion); } else { isCopied = bltWindow(window.clientRect, oldClientRect, preservedRegion); } if (isCopied) { invalidatedRegion |= preservedRegion; } } window.invalidatedRegion = window.visibleRegion - preservedRegion; if (!window.invalidatedRegion.isEmpty()) { window.invalidatedRegion.offset(-window.clientRect.left, -window.clientRect.top); } } BOOL CALLBACK updateWindow(HWND hwnd, LPARAM lParam) { auto& context = *reinterpret_cast<UpdateWindowContext*>(lParam); DWORD processId = 0; GetWindowThreadProcessId(hwnd, &processId); if (processId != context.processId || Gdi::PresentationWindow::isPresentationWindow(hwnd)) { return TRUE; } auto it = g_windows.find(hwnd); if (it == g_windows.end()) { it = addWindow(hwnd); } g_windowZOrder.push_back(&it->second); const LONG exStyle = CALL_ORIG_FUNC(GetWindowLongA)(hwnd, GWL_EXSTYLE); const bool isLayered = exStyle & WS_EX_LAYERED; const bool isVisible = IsWindowVisible(hwnd) && !IsIconic(hwnd); bool setPresentationWindowRgn = false; if (isLayered != it->second.isLayered) { it->second.isLayered = isLayered; it->second.isVisibleRegionChanged = isVisible; if (!isLayered) { it->second.presentationWindow = Gdi::PresentationWindow::create(hwnd); setPresentationWindowRgn = true; } else if (it->second.presentationWindow) { Gdi::PresentationWindow::destroy(it->second.presentationWindow); it->second.presentationWindow = nullptr; } } Gdi::Region windowRegion(getWindowRegion(hwnd)); if (windowRegion && !PtInRegion(windowRegion, REGION_OVERRIDE_MARKER_RECT.left, REGION_OVERRIDE_MARKER_RECT.top) || !windowRegion && it->second.windowRegion) { swap(it->second.windowRegion, windowRegion); setPresentationWindowRgn = true; } WINDOWINFO wi = {}; Gdi::Region visibleRegion; if (isVisible) { wi.cbSize = sizeof(wi); GetWindowInfo(hwnd, &wi); if (!IsRectEmpty(&wi.rcWindow)) { if (it->second.windowRegion) { visibleRegion = it->second.windowRegion; visibleRegion.offset(wi.rcWindow.left, wi.rcWindow.top); } else { visibleRegion = wi.rcWindow; } visibleRegion &= context.virtualScreenRegion; visibleRegion -= context.obscuredRegion; if (!isLayered && !(exStyle & WS_EX_TRANSPARENT)) { context.obscuredRegion |= visibleRegion; } } } std::swap(it->second.windowRect, wi.rcWindow); std::swap(it->second.clientRect, wi.rcClient); swap(it->second.visibleRegion, visibleRegion); if (!isLayered) { if (!it->second.visibleRegion.isEmpty()) { updatePosition(it->second, wi.rcWindow, wi.rcClient, visibleRegion, context.invalidatedRegion); } if (exStyle & WS_EX_TRANSPARENT) { context.invalidatedRegion |= visibleRegion - it->second.visibleRegion; } if (isVisible && !it->second.isVisibleRegionChanged) { visibleRegion.offset(it->second.windowRect.left - wi.rcWindow.left, it->second.windowRect.top - wi.rcWindow.top); if (it->second.visibleRegion != visibleRegion) { it->second.isVisibleRegionChanged = true; } } if (it->second.presentationWindow) { if (setPresentationWindowRgn) { Gdi::PresentationWindow::setWindowRgn(it->second.presentationWindow, it->second.windowRegion); } WINDOWPOS wp = {}; wp.flags = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOREDRAW | SWP_NOSENDCHANGING; if (isVisible) { wp.hwndInsertAfter = GetWindow(hwnd, GW_HWNDPREV); if (!wp.hwndInsertAfter) { wp.hwndInsertAfter = (GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) ? HWND_TOPMOST : HWND_TOP; } else if (wp.hwndInsertAfter == it->second.presentationWindow) { wp.flags |= SWP_NOZORDER; } wp.x = it->second.windowRect.left; wp.y = it->second.windowRect.top; wp.cx = it->second.windowRect.right - it->second.windowRect.left; wp.cy = it->second.windowRect.bottom - it->second.windowRect.top; wp.flags |= SWP_SHOWWINDOW; } else { wp.flags |= SWP_HIDEWINDOW | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER; } Gdi::PresentationWindow::setWindowPos(it->second.presentationWindow, wp); } } return TRUE; } } namespace Gdi { namespace Window { void onStyleChanged(HWND hwnd, WPARAM wParam) { if (GWL_EXSTYLE == wParam) { D3dDdi::ScopedCriticalSection lock; auto it = g_windows.find(hwnd); if (it != g_windows.end()) { const bool isLayered = GetWindowLong(hwnd, GWL_EXSTYLE) & WS_EX_LAYERED; if (isLayered != it->second.isLayered) { updateAll(); } } } } void onSyncPaint(HWND hwnd) { LOG_FUNC("Window::onSyncPaint", hwnd); bool isInvalidated = false; { D3dDdi::ScopedCriticalSection lock; auto it = g_windows.find(hwnd); if (it == g_windows.end()) { return; } if (it->second.isVisibleRegionChanged) { it->second.isVisibleRegionChanged = false; const LONG origWndProc = CALL_ORIG_FUNC(GetWindowLongA)(hwnd, GWL_WNDPROC); CALL_ORIG_FUNC(SetWindowLongA)(hwnd, GWL_WNDPROC, reinterpret_cast<LONG>(CALL_ORIG_FUNC(DefWindowProcA))); if (it->second.isLayered) { SetWindowRgn(hwnd, Gdi::Region(it->second.windowRegion).release(), FALSE); } else { Gdi::Region rgn(it->second.visibleRegion); rgn.offset(-it->second.windowRect.left, -it->second.windowRect.top); rgn |= REGION_OVERRIDE_MARKER_RECT; SetWindowRgn(hwnd, rgn, FALSE); } CALL_ORIG_FUNC(SetWindowLongA)(hwnd, GWL_WNDPROC, origWndProc); } isInvalidated = !it->second.invalidatedRegion.isEmpty(); if (isInvalidated) { RedrawWindow(hwnd, nullptr, it->second.invalidatedRegion, RDW_INVALIDATE | RDW_ERASE | RDW_FRAME | RDW_ALLCHILDREN); it->second.invalidatedRegion = nullptr; } } if (isInvalidated) { RECT emptyRect = {}; RedrawWindow(hwnd, &emptyRect, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_FRAME | RDW_ERASENOW); } } void present(CompatRef<IDirectDrawSurface7> dst, CompatRef<IDirectDrawSurface7> src, CompatRef<IDirectDrawClipper> clipper) { D3dDdi::ScopedCriticalSection lock; for (auto window : g_windowZOrder) { if (window->presentationWindow && !window->visibleRegion.isEmpty()) { clipper->SetHWnd(&clipper, 0, window->presentationWindow); dst->Blt(&dst, nullptr, &src, nullptr, DDBLT_WAIT, nullptr); } } } void present(Gdi::Region excludeRegion) { D3dDdi::ScopedCriticalSection lock; std::unique_ptr<HDC__, void(*)(HDC)> virtualScreenDc(nullptr, &Gdi::VirtualScreen::deleteDc); RECT virtualScreenBounds = Gdi::VirtualScreen::getBounds(); for (auto window : g_windowZOrder) { if (!window->presentationWindow) { continue; } Gdi::Region visibleRegion(window->visibleRegion); if (excludeRegion) { visibleRegion -= excludeRegion; } if (visibleRegion.isEmpty()) { continue; } if (!virtualScreenDc) { const bool useDefaultPalette = false; virtualScreenDc.reset(Gdi::VirtualScreen::createDc(useDefaultPalette)); if (!virtualScreenDc) { return; } } HDC dc = GetWindowDC(window->presentationWindow); RECT rect = window->windowRect; visibleRegion.offset(-rect.left, -rect.top); SelectClipRgn(dc, visibleRegion); CALL_ORIG_FUNC(BitBlt)(dc, 0, 0, rect.right - rect.left, rect.bottom - rect.top, virtualScreenDc.get(), rect.left - virtualScreenBounds.left, rect.top - virtualScreenBounds.top, SRCCOPY); CALL_ORIG_FUNC(ReleaseDC)(window->presentationWindow, dc); } } void presentLayered(CompatRef<IDirectDrawSurface7> dst, POINT offset) { D3dDdi::ScopedCriticalSection lock; HDC dstDc = nullptr; for (auto it = g_windowZOrder.rbegin(); it != g_windowZOrder.rend(); ++it) { auto& window = **it; if (!window.isLayered) { continue; } if (!dstDc) { const UINT D3DDDIFMT_UNKNOWN = 0; const UINT D3DDDIFMT_X8R8G8B8 = 22; D3dDdi::KernelModeThunks::setDcFormatOverride(D3DDDIFMT_X8R8G8B8); dst->GetDC(&dst, &dstDc); D3dDdi::KernelModeThunks::setDcFormatOverride(D3DDDIFMT_UNKNOWN); if (!dstDc) { return; } } HDC windowDc = GetWindowDC(window.hwnd); Gdi::Region rgn(window.visibleRegion); RECT wr = window.windowRect; if (0 != offset.x || 0 != offset.y) { OffsetRect(&wr, offset.x, offset.y); rgn.offset(offset.x, offset.y); } SelectClipRgn(dstDc, rgn); auto colorKey = window.colorKey; if (CLR_INVALID != colorKey) { CALL_ORIG_FUNC(TransparentBlt)(dstDc, wr.left, wr.top, wr.right - wr.left, wr.bottom - wr.top, windowDc, 0, 0, wr.right - wr.left, wr.bottom - wr.top, colorKey); } else { BLENDFUNCTION blend = {}; blend.SourceConstantAlpha = window.alpha; CALL_ORIG_FUNC(AlphaBlend)(dstDc, wr.left, wr.top, wr.right - wr.left, wr.bottom - wr.top, windowDc, 0, 0, wr.right - wr.left, wr.bottom - wr.top, blend); } CALL_ORIG_FUNC(ReleaseDC)(window.hwnd, windowDc); } if (dstDc) { SelectClipRgn(dstDc, nullptr); dst->ReleaseDC(&dst, dstDc); } } void updateAll() { LOG_FUNC("Window::updateAll"); if (!Gdi::PresentationWindow::isThreadReady()) { return; } UpdateWindowContext context; context.processId = GetCurrentProcessId(); context.virtualScreenRegion = VirtualScreen::getRegion(); std::vector<HWND> invalidatedWindows; { D3dDdi::ScopedCriticalSection lock; g_windowZOrder.clear(); EnumWindows(updateWindow, reinterpret_cast<LPARAM>(&context)); for (auto it = g_windows.begin(); it != g_windows.end();) { if (g_windowZOrder.end() == std::find(g_windowZOrder.begin(), g_windowZOrder.end(), &it->second)) { if (it->second.presentationWindow) { Gdi::PresentationWindow::destroy(it->second.presentationWindow); } it = g_windows.erase(it); } else { ++it; } } for (auto it = g_windowZOrder.rbegin(); it != g_windowZOrder.rend(); ++it) { auto& window = **it; if (window.isVisibleRegionChanged || !window.invalidatedRegion.isEmpty()) { invalidatedWindows.push_back(window.hwnd); } } } for (auto hwnd : invalidatedWindows) { SendNotifyMessage(hwnd, WM_SYNCPAINT, 0, 0); } } void updateLayeredWindowInfo(HWND hwnd, COLORREF colorKey, BYTE alpha) { D3dDdi::ScopedCriticalSection lock; auto it = g_windows.find(hwnd); if (it != g_windows.end()) { it->second.colorKey = colorKey; it->second.alpha = alpha; if (!it->second.visibleRegion.isEmpty()) { DDraw::RealPrimarySurface::scheduleUpdate(); } } } } }
6,981
533
<filename>tests/test_cms_user.py<gh_stars>100-1000 # _*_ coding: utf-8 _*_ """ Created by Allen7D on 2020/4/12. """ from app import create_app from tests.utils import get_authorization __author__ = 'Allen7D' app = create_app() def test_get_user_list(): with app.test_client() as client: rv = client.get('/cms/user/list?page=1&size=10', headers={ 'Authorization': get_authorization() }) json_data = rv.get_json() print(json_data) def test_get_user(): with app.test_client() as client: rv = client.get('/cms/user/2', headers={ 'Authorization': get_authorization() }) json_data = rv.get_json() print(json_data) test_get_user_list() test_get_user()
336
12,278
<gh_stars>1000+ // Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2012-2019 <NAME>, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP #include <boost/geometry/util/math.hpp> #include <boost/geometry/strategies/buffer.hpp> #include <boost/geometry/algorithms/detail/buffer/parallel_continue.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace buffer { // TODO: once change this to proper strategy // It is different from current segment intersection because these are not segments but lines // If we have the Line concept, we can create a strategy // Assumes a convex corner struct line_line_intersection { template <typename Point> static inline strategy::buffer::join_selector apply(Point const& pi, Point const& pj, Point const& qi, Point const& qj, Point& ip) { typedef typename coordinate_type<Point>::type ct; // Construct lines in general form (ax + by + c = 0), // (will be replaced by a general_form structure in a next PR) ct const pa = get<1>(pi) - get<1>(pj); ct const pb = get<0>(pj) - get<0>(pi); ct const pc = -pa * get<0>(pi) - pb * get<1>(pi); ct const qa = get<1>(qi) - get<1>(qj); ct const qb = get<0>(qj) - get<0>(qi); ct const qc = -qa * get<0>(qi) - qb * get<1>(qi); ct const denominator = pb * qa - pa * qb; // Even if the corner was checked before (so it is convex now), that // was done on the original geometry. This function runs on the buffered // geometries, where sides are generated and might be slightly off. In // Floating Point, that slightly might just exceed the limit and we have // to check it again. // For round joins, it will not be used at all. // For miter joins, there is a miter limit // If segments are parallel/collinear we must be distinguish two cases: // they continue each other, or they form a spike ct const zero = ct(); if (math::equals(denominator, zero)) { return parallel_continue(qb, -qa, pb, -pa) ? strategy::buffer::join_continue : strategy::buffer::join_spike ; } set<0>(ip, (pc * qb - pb * qc) / denominator); set<1>(ip, (pa * qc - pc * qa) / denominator); return strategy::buffer::join_convex; } }; }} // namespace detail::buffer #endif // DOXYGEN_NO_DETAIL }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_LINE_LINE_INTERSECTION_HPP
1,159
596
<filename>src/test/java/com/ryantenney/metrics/spring/SharedRegistryTest.java /** * Copyright (C) 2012 <NAME> (<EMAIL>) * * 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.ryantenney.metrics.spring; import org.junit.Assert; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; public class SharedRegistryTest { @Test public void testDefaultRegistries() { ClassPathXmlApplicationContext ctx = null; try { MetricRegistry instance = new MetricRegistry(); SharedMetricRegistries.add("SomeSharedRegistry", instance); ctx = new ClassPathXmlApplicationContext("classpath:shared-registry.xml"); Assert.assertSame("Should be the same MetricRegistry", instance, ctx.getBean(MetricRegistry.class)); } finally { if (ctx != null) { ctx.close(); } } } }
463