code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
// // ipaddress.h // // Circle - A C++ bare metal environment for Raspberry Pi // Copyright (C) 2015 R. Stange <rsta2@o2online.de> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #ifndef _circle_net_ipaddress_h #define _circle_net_ipaddress_h #include <circle/string.h> #include <circle/types.h> #define IP_ADDRESS_SIZE 4 class CIPAddress { public: CIPAddress (void); CIPAddress (u32 nAddress); CIPAddress (const u8 *pAddress); CIPAddress (const CIPAddress &rAddress); ~CIPAddress (void); boolean operator== (const CIPAddress &rAddress2) const; boolean operator!= (const CIPAddress &rAddress2) const; boolean operator== (const u8 *pAddress2) const; boolean operator!= (const u8 *pAddress2) const; void Set (u32 nAddress); void Set (const u8 *pAddress); void Set (const CIPAddress &rAddress); const u8 *Get (void) const; void CopyTo (u8 *pBuffer) const; unsigned GetSize (void) const; void Format (CString *pString) const; boolean OnSameNetwork (const CIPAddress &rAddress2, const u8 *pNetMask) const; public: static const CIPAddress AnyAddress; private: boolean m_bValid; u8 m_Address[IP_ADDRESS_SIZE]; }; #endif
darth-vader-lg/glcncrpi
include/circle/net/ipaddress.h
C
gpl-3.0
1,753
<?php theme_include('header'); ?> <div class="navigation"> <nav> <span class="logoCont"> <img class="mobile-logo" src="img/logo.png"> </span> <ul class="nav-flex"> <li><a href="index.php"><img class="nav-logo" src="img/logo.png"></a></li> <li ><a class="nav-button-small" href="index.php">NEWS</a></li> <li ><a class="nav-button-small" href="hof1.html">H<span class="desktop">AND </span>O<span class="desktop">F </span>F<span class="desktop">ATE </span>1</a></li> <li ><a class="nav-button-small" href="hof2.html">H<span class="desktop">AND </span>O<span class="desktop">F </span>F<span class="desktop">ATE </span>2</a></li> <li ><a class="nav-button-small" href="about.html">ABOUT</a></li> <li ><a class="nav-button-small" href="presskit/">PRESSKIT</a></li> </ul> </nav> </div> <div class="landing"> <div class="leftQuote"> <div class="quoteHolder"> "Hand of Fate might just be one of the most instantly-atmospheric games this reviewer has ever encountered" <a href="http://gameplanet.com.au/pc/reviews/g54f525d828582/Hand-of-Fate-review">- Chris Brown, Game Planet</a> </div> </div> <div class="landingImage"> <img src="img/landing.png" alt="landing image" /> </div> <div class="rightQuote"> <div class="quoteHolder"> "Defiant Deals a Winning Hand" <a href="http://gameinformer.com/games/hand_of_fate/b/pc/archive/2015/02/16/defiant-deals-a-winning-hand.aspx">- Daniel Tack, Game Informer</a> </div> </div> </div> <div class='home-background'> <div class="container"> <div class="twitter-title">Latest Tweets <div class="twitter-container"> <a class="twitter-timeline" data-width="400" data-height="700" data-theme="dark" data-link-color="#a02626" href="https://twitter.com/DefiantDev">Tweets by DefiantDev</a> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> </div> </div> <div class="blog"> <div class="blog-box-heading">Latest News</div> <div class="blog-entry-container"> <?php if(has_posts()): ?> <?php $i = 0; while(posts()): ?> <article> <div class="blog-title"> <?php echo article_title(); ?> </div> <div class="blog-date">Posted <time datetime="<?php echo date(DATE_W3C, article_time()); ?>"> <?php echo relative_time(article_time()); ?></time>. </div> <div class="blog-content"> <?php echo article_html(); ?> </div> <img class="bottom-blog-border" src="img/border.png"> </article> <?php endwhile; ?> <ul class="items"> <?php posts(); ?> <?php else: ?> <div class="wrap"> <h1>No posts yet!</h1> <p>Looks like you have some writing to do!</p> </div> <?php endif; ?> </div> </div> <div class="twitter-title mobile-twitter">Latest Tweets <div class="twitter-container"> <a class="twitter-timeline" data-width="400" data-height="700" data-theme="dark" data-link-color="#a02626" href="https://twitter.com/DefiantDev">Tweets by DefiantDev</a> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> </div> </div> <div class='clear-float'></div> <?php theme_include('footer'); ?> </div> </div> </body>
1002915/defiantdev
themes/default/posts.php
PHP
gpl-3.0
3,467
/* * Copyright (C) 2013-2016 The OmniROM Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.omnirom.omniswitch; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Point; import android.graphics.drawable.ColorDrawable; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.View; import android.view.WindowManager; import org.omnirom.omniswitch.launcher.Launcher; public class SwitchConfiguration { private final static String TAG = "OmniSwitch:SwitchConfiguration"; private static boolean DEBUG = false; public float mBackgroundOpacity = 0.7f; public boolean mDimBehind = true; public int mLocation = 0; // 0 = right 1 = left public boolean mAnimate = true; public int mIconSize = 60; // in dip public int mIconSizePx = 60; public int mQSActionSizePx = 60; // in px public int mActionSizePx = 48; // in px public int mOverlayIconSizeDp = 30; public int mOverlayIconSizePx = 30; public int mOverlayIconBorderDp = 2; public int mOverlayIconBorderPx = 2; public int mIconBorderDp = 4; // in dp public int mIconBorderPx = 4; public float mDensity; public int mDensityDpi; public int mMaxWidth; public boolean mShowRambar = true; public int mStartYRelative; public int mDragHandleHeight; public int mDragHandleWidth; public int mDefaultDragHandleWidth; public boolean mShowLabels = true; public int mDragHandleColor; public int mIconDpi; public boolean mAutoHide; public static final int AUTO_HIDE_DEFAULT = 3000; // 3s public boolean mDragHandleShow = true; public boolean mRestrictedMode; public int mLevelHeight; // in px public int mItemChangeWidthX; // in px - maximum value - can be lower if more items public int mThumbnailWidth; // in px public int mThumbnailHeight; // in px public Map<Integer, Boolean> mButtons; public boolean mLevelBackgroundColor = true; public boolean mLimitLevelChangeX = true; public Map<Integer, Boolean> mSpeedSwitchButtons; public int mLimitItemsX = 10; public float mLabelFontSize; public int mButtonPos = 1; // 0 = top 1 = bottom public List<String> mFavoriteList = new ArrayList<String>(); public boolean mSpeedSwitcher = true; public boolean mFilterActive = true; public boolean mFilterRunning; public long mFilterTime; public boolean mSideHeader = true; private static SwitchConfiguration mInstance; private WindowManager mWindowManager; private int mDefaultHandleHeight; private int mLabelFontSizePx; public int mMaxHeight; public int mMemDisplaySize; public int mLayoutStyle; public float mThumbRatio = 1.0f; public IconSize mIconSizeDesc = IconSize.NORMAL; public int mIconBorderHorizontalDp = 8; // in dp public int mIconBorderHorizontalPx = 8; // in px public BgStyle mBgStyle = BgStyle.SOLID_LIGHT; public boolean mLaunchStatsEnabled; public boolean mRevertRecents; public int mIconSizeQuickPx = 100; public boolean mDimActionButton; public List<String> mLockedAppList = new ArrayList<String>(); public boolean mTopSortLockedApps; private Context mContext; private ContextThemeWrapper mThemeContext; public boolean mDynamicDragHandleColor; public boolean mBlockSplitscreenBreakers = true; public boolean mUsePowerHint; public Set<String> mHiddenAppsList = new HashSet<String>(); public Launcher mLauncher; public boolean mColorfulHeader; public boolean mBottomFavorites; public boolean mButtonHide; public int mShortcutIconSizeDp = 32; public boolean mSystemFont; // old pref slots private static final String PREF_DRAG_HANDLE_COLOR = "drag_handle_color"; private static final String PREF_DRAG_HANDLE_OPACITY = "drag_handle_opacity"; private static final String PREF_FLAT_STYLE = "flat_style"; private List<OnSharedPreferenceChangeListener> mPrefsListeners = new ArrayList<OnSharedPreferenceChangeListener>(); public enum IconSize { SMALL, NORMAL, LARGE } public enum BgStyle { TRANSPARENT, SOLID_LIGHT, SOLID_DARK, SOLID_SYSTEM } public static SwitchConfiguration getInstance(Context context) { if (mInstance == null) { mInstance = new SwitchConfiguration(context); } return mInstance; } private SwitchConfiguration(Context context) { mContext = context; mThemeContext = new ContextThemeWrapper(context, R.style.AppThemeSystem); mWindowManager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); setDensityConfiguration(context); updatePrefs(PreferenceManager.getDefaultSharedPreferences(context), ""); } public boolean onConfigurationChanged(Context context) { final float newDensity = context.getResources().getDisplayMetrics().density; if(DEBUG){ Log.d(TAG, "onConfigurationChanged " + mDensity + " " + newDensity); } if (newDensity != mDensity) { setDensityConfiguration(context); return true; } return false; } private void setDensityConfiguration(Context context) { mDensity = context.getResources().getDisplayMetrics().density; mDensityDpi = context.getResources().getDisplayMetrics().densityDpi; if(DEBUG){ Log.d(TAG, "setDensityConfiguration " + mDensity); } mDefaultHandleHeight = Math.round(100 * mDensity); mRestrictedMode = !hasSystemPermission(context); mLevelHeight = Math.round(80 * mDensity); mItemChangeWidthX = Math.round(40 * mDensity); mActionSizePx = Math.round(48 * mDensity); mQSActionSizePx = Math.round(60 * mDensity); mOverlayIconSizePx = Math.round(mOverlayIconSizeDp * mDensity); mOverlayIconBorderPx = Math.round(mOverlayIconBorderDp * mDensity); mIconBorderHorizontalPx = Math.round(mIconBorderHorizontalDp * mDensity); mIconSizeQuickPx = Math.round(100 * mDensity); mIconBorderPx = Math.round(mIconBorderDp * mDensity); // Render the default thumbnail background mThumbnailWidth = (int) context.getResources().getDimensionPixelSize( R.dimen.thumbnail_width); mThumbnailHeight = (int) context.getResources() .getDimensionPixelSize(R.dimen.thumbnail_height); mMemDisplaySize = (int) context.getResources().getDimensionPixelSize( R.dimen.ram_display_size); } public void initDefaults(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (!prefs.contains(SettingsActivity.PREF_BG_STYLE) && prefs.contains(PREF_FLAT_STYLE)) { boolean flatStyle = prefs.getBoolean(PREF_FLAT_STYLE, true); prefs.edit().putString(SettingsActivity.PREF_BG_STYLE, flatStyle ? "0" : "1").commit(); } if (!prefs.contains(SettingsActivity.PREF_DRAG_HANDLE_COLOR_NEW) && prefs.contains(PREF_DRAG_HANDLE_COLOR)) { int dragHandleColor = prefs.getInt(PREF_DRAG_HANDLE_COLOR, getDefaultDragHandleColor()); int opacity = prefs.getInt(PREF_DRAG_HANDLE_OPACITY, 100); dragHandleColor = (dragHandleColor & 0x00FFFFFF) + (opacity << 24); prefs.edit().putInt(SettingsActivity.PREF_DRAG_HANDLE_COLOR_NEW, dragHandleColor).commit(); } } public void updatePrefs(SharedPreferences prefs, String key) { if(DEBUG){ Log.d(TAG, "updatePrefs"); } mLocation = prefs.getInt(SettingsActivity.PREF_DRAG_HANDLE_LOCATION, 0); int opacity = prefs.getInt(SettingsActivity.PREF_OPACITY, 70); mBackgroundOpacity = (float) opacity / 100.0f; mAnimate = prefs.getBoolean(SettingsActivity.PREF_ANIMATE, true); String iconSize = prefs .getString(SettingsActivity.PREF_ICON_SIZE, String.valueOf(mIconSize)); mIconSize = Integer.valueOf(iconSize); if (mIconSize == 60) { mIconSizeDesc = IconSize.NORMAL; mIconSize = 52; } else if (mIconSize == 80) { mIconSizeDesc = IconSize.LARGE; mIconSize = 70; } else { mIconSizeDesc = IconSize.SMALL; } mShowRambar = prefs.getBoolean(SettingsActivity.PREF_SHOW_RAMBAR, true); mShowLabels = prefs.getBoolean(SettingsActivity.PREF_SHOW_LABELS, true); int relHeightStart = (int) (getDefaultOffsetStart() / (getCurrentDisplayHeight() / 100)); mStartYRelative = prefs .getInt(SettingsActivity.PREF_HANDLE_POS_START_RELATIVE, relHeightStart); mDragHandleHeight = prefs.getInt(SettingsActivity.PREF_HANDLE_HEIGHT, mDefaultHandleHeight); mIconSizePx = Math.round(mIconSize * mDensity); mMaxWidth = Math.round((mIconSize + mIconBorderDp) * mDensity); mMaxHeight = Math.round((mIconSize + mIconBorderDp) * mDensity); mLabelFontSize = 14f; // add a small gap mLabelFontSizePx = Math.round((mLabelFontSize + mIconBorderDp) * mDensity); mDragHandleColor = prefs.getInt( SettingsActivity.PREF_DRAG_HANDLE_COLOR_NEW, getDefaultDragHandleColor()); mAutoHide = prefs.getBoolean(SettingsActivity.PREF_AUTO_HIDE_HANDLE, false); mDragHandleShow = prefs.getBoolean( SettingsActivity.PREF_DRAG_HANDLE_ENABLE, true); mDimBehind = prefs.getBoolean(SettingsActivity.PREF_DIM_BEHIND, false); mDefaultDragHandleWidth = Math.round(20 * mDensity); mDragHandleWidth = prefs.getInt( SettingsActivity.PREF_HANDLE_WIDTH, mDefaultDragHandleWidth); mButtons = Utils.buttonStringToMap(prefs.getString(SettingsActivity.PREF_BUTTONS_NEW, SettingsActivity.PREF_BUTTON_DEFAULT_NEW), SettingsActivity.PREF_BUTTON_DEFAULT_NEW); mLevelBackgroundColor = prefs.getBoolean(SettingsActivity.PREF_SPEED_SWITCHER_COLOR, true); mLimitLevelChangeX = prefs.getBoolean(SettingsActivity.PREF_SPEED_SWITCHER_LIMIT, true); mSpeedSwitchButtons = Utils.buttonStringToMap(prefs.getString(SettingsActivity.PREF_SPEED_SWITCHER_BUTTON_NEW, SettingsActivity.PREF_SPEED_SWITCHER_BUTTON_DEFAULT_NEW), SettingsActivity.PREF_SPEED_SWITCHER_BUTTON_DEFAULT_NEW); mLimitItemsX = prefs.getInt(SettingsActivity.PREF_SPEED_SWITCHER_ITEMS, 10); String buttonPos = prefs.getString(SettingsActivity.PREF_BUTTON_POS, "1"); mButtonPos = Integer.valueOf(buttonPos); String bgStyle = prefs.getString(SettingsActivity.PREF_BG_STYLE, "0"); int bgStyleInt = Integer.valueOf(bgStyle); if (bgStyleInt == 0) { mBgStyle = BgStyle.SOLID_LIGHT; } else if(bgStyleInt == 1) { mBgStyle = BgStyle.TRANSPARENT; } else if(bgStyleInt == 3) { mBgStyle = BgStyle.SOLID_SYSTEM; } else { mBgStyle = BgStyle.SOLID_DARK; } mFavoriteList.clear(); String favoriteListString = prefs.getString(SettingsActivity.PREF_FAVORITE_APPS, ""); Utils.parseCollection(favoriteListString, mFavoriteList); mSpeedSwitcher = prefs.getBoolean(SettingsActivity.PREF_SPEED_SWITCHER, true); String filterTimeString = prefs.getString(SettingsActivity.PREF_APP_FILTER_TIME, "0"); mFilterTime = Integer.valueOf(filterTimeString); if (mFilterTime != 0) { // value is in hours but we need millisecs mFilterTime = mFilterTime * 3600 * 1000; } String layoutStyle = prefs.getString(SettingsActivity.PREF_LAYOUT_STYLE, "1"); mLayoutStyle = Integer.valueOf(layoutStyle); String thumbSize = prefs.getString(SettingsActivity.PREF_THUMB_SIZE, "1.0"); mThumbRatio = Float.valueOf(thumbSize); mFilterRunning = prefs.getBoolean(SettingsActivity.PREF_APP_FILTER_RUNNING, false); mLaunchStatsEnabled = prefs.getBoolean(SettingsActivity.PREF_LAUNCH_STATS, false); mRevertRecents = prefs.getBoolean(SettingsActivity.PREF_REVERT_RECENTS, false); mBottomFavorites = prefs.getBoolean(SettingsActivity.PREF_BOTTOM_FAVORITES, false); mDimActionButton = prefs.getBoolean(SettingsActivity.PREF_DIM_ACTION_BUTTON, false); mLockedAppList.clear(); String lockedAppsListString = prefs.getString(SettingsActivity.PREF_LOCKED_APPS_LIST, ""); Utils.parseLockedApps(lockedAppsListString, mLockedAppList); mTopSortLockedApps = prefs.getBoolean(SettingsActivity.PREF_LOCKED_APPS_SORT, false); mDynamicDragHandleColor = prefs.getBoolean(SettingsActivity.PREF_DRAG_HANDLE_DYNAMIC_COLOR, false); mBlockSplitscreenBreakers = prefs.getBoolean(SettingsActivity.PREF_BLOCK_APPS_ON_SPLITSCREEN, true); mUsePowerHint = prefs.getBoolean(SettingsActivity.PREF_USE_POWER_HINT, false); mColorfulHeader = prefs.getBoolean(SettingsActivity.PREF_COLOR_TASK_HEADER, false); mButtonHide = prefs.getBoolean(SettingsActivity.PREF_BUTTON_HIDE, false); mSystemFont = prefs.getBoolean(SettingsActivity.PREF_SYSTEM_FONT, false); mHiddenAppsList.clear(); String hiddenListString = prefs.getString(SettingsActivity.PREF_HIDDEN_APPS, ""); Utils.parseCollection(hiddenListString, mHiddenAppsList); for(OnSharedPreferenceChangeListener listener : mPrefsListeners) { if(DEBUG){ Log.d(TAG, "onSharedPreferenceChanged " + listener.getClass().getName()); } listener.onSharedPreferenceChanged(prefs, key); } } public void resetDefaults(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().clear().commit(); } // includes rotation public int getCurrentDisplayHeight() { Point size = new Point(); mWindowManager.getDefaultDisplay().getSize(size); int height = size.y; return height; } public int getCurrentDisplayWidth() { Point size = new Point(); mWindowManager.getDefaultDisplay().getSize(size); int width = size.x; return width; } public boolean isLandscape() { return getCurrentDisplayWidth() > getCurrentDisplayHeight(); } public int getCurrentOverlayWidth() { if (isLandscape()) { // landscape return Math.max(mMaxWidth * 6, (int) (getCurrentDisplayWidth() * 0.66f)); } return getCurrentDisplayWidth(); } public int getCurrentOffsetStart() { return (getCurrentDisplayHeight() / 100) * mStartYRelative; } public int getCurrentOffsetStart(int height) { return (height / 100) * mStartYRelative; } public int getCustomOffsetStart(int startYRelative) { return (getCurrentDisplayHeight() / 100) * startYRelative; } public int getDefaultOffsetStart() { return ((getCurrentDisplayHeight() / 2) - mDefaultHandleHeight / 2); } public int getDefaultHeightRelative() { return mDefaultHandleHeight / (getCurrentDisplayHeight() / 100); } public int getCurrentOffsetEnd() { return getCurrentOffsetStart() + mDragHandleHeight; } public int getCustomOffsetEnd(int startYRelative, int handleHeight) { return getCustomOffsetStart(startYRelative) + handleHeight; } public int getDefaultOffsetEnd() { return getDefaultOffsetStart() + mDefaultHandleHeight; } private boolean hasSystemPermission(Context context) { int result = context .checkCallingOrSelfPermission(android.Manifest.permission.REMOVE_TASKS); return result == android.content.pm.PackageManager.PERMISSION_GRANTED; } public int calcHorizontalDivider(boolean fullscreen) { int horizontalDividerWidth = 0; int width = fullscreen ? getCurrentDisplayWidth() : getCurrentOverlayWidth(); int columnWidth = mMaxWidth + mIconBorderHorizontalPx; int numColumns = width / columnWidth; if (numColumns > 1) { int equalWidth = width / numColumns; if (equalWidth > columnWidth) { horizontalDividerWidth = equalWidth - columnWidth; } } return horizontalDividerWidth; } public int calcVerticalDivider(int height) { int verticalDividerHeight = 0; int numRows = height / getItemMaxHeight(); if (numRows > 1) { int equalHeight = height / numRows; if (equalHeight > getItemMaxHeight()) { verticalDividerHeight = equalHeight - getItemMaxHeight(); } } return verticalDividerHeight; } public int getItemMaxHeight() { return mShowLabels ? mMaxHeight + mLabelFontSizePx : mMaxHeight; } public int getOverlayHeaderWidth() { return mOverlayIconSizePx + 2 * mOverlayIconBorderPx; } public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener prefsListener) { mPrefsListeners.add(prefsListener); } public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener prefsListener) { mPrefsListeners.remove(prefsListener); } public int getLauncherViewWidth() { if (isLandscape()) { return (int) (getCurrentDisplayWidth() * 0.75f); } return getCurrentDisplayWidth(); } public int getDragHandleColor() { if (mDynamicDragHandleColor) { return getSystemAccentColor(); } return mDragHandleColor; } public int getDefaultDragHandleColor() { return mContext.getResources().getColor(R.color.default_drag_handle_color); } public int getSystemPrimaryColor() { return mContext.getResources().getColor(R.color.system_default_primary); } public int getSystemPrimaryDarkColor() { return mContext.getResources().getColor(R.color.system_default_primary_dark); } public int getSystemAccentColor() { return getAttrColor(mThemeContext, android.R.attr.colorAccent); } public int getTaskHeaderColor() { return getButtonBackgroundColor(); } public int getCurrentButtonTint(int color) { if (Utils.isBrightColor(color)) { return mContext.getResources().getColor(R.color.text_color_light); } else { return mContext.getResources().getColor(R.color.text_color_dark); } } public int getCurrentTextTint(int color) { return getCurrentButtonTint(color); } public int getButtonBackgroundColor() { if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_LIGHT) { return mContext.getResources().getColor(R.color.button_bg_flat_color); } else if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_DARK) { return mContext.getResources().getColor(R.color.button_bg_flat_color_dark); } else if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_SYSTEM) { return getSystemPrimaryDarkColor(); } return mContext.getResources().getColor(R.color.bg_transparent); } public int getBackgroundRipple() { if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_LIGHT) { return R.drawable.ripple_dark; } else if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_DARK) { return R.drawable.ripple_light; } else if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_SYSTEM) { return R.drawable.ripple_system; } return R.drawable.ripple_light; } public int getViewBackgroundColor() { if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_LIGHT) { return mContext.getResources().getColor(R.color.bg_flat_color); } else if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_DARK) { return mContext.getResources().getColor(R.color.bg_flat_color_dark); } else if (mBgStyle == SwitchConfiguration.BgStyle.SOLID_SYSTEM) { return getSystemPrimaryColor(); } return mContext.getResources().getColor(R.color.bg_transparent); } public int getShadowColorValue() { if (mBgStyle == BgStyle.TRANSPARENT) { return 5; } return 0; } public int getPopupMenuStyle() { if (mBgStyle == BgStyle.SOLID_LIGHT) { return R.style.PopupMenuLight; } else if (mBgStyle == BgStyle.SOLID_DARK || mBgStyle == BgStyle.TRANSPARENT) { return R.style.PopupMenuDark; } else if (mBgStyle == BgStyle.SOLID_SYSTEM) { return R.style.PopupMenuSystem; } return R.style.PopupMenuLight; } public int getAttrColor(Context context, int attr) { TypedArray ta = context.obtainStyledAttributes(new int[]{attr}); int color = ta.getColor(0, 0); ta.recycle(); return color; } private static SharedPreferences getPrefs(Context context) { return PreferenceManager.getDefaultSharedPreferences(context); } public static String getWeatherIconPack(Context context) { return getPrefs(context).getString(SettingsActivity.WEATHER_ICON_PACK_PREFERENCE_KEY, null); } public static boolean isShowAllDayEvents(Context context) { return getPrefs(context).getBoolean(SettingsActivity.SHOW_ALL_DAY_EVENTS_PREFERENCE_KEY, false); } public static boolean isShowToday(Context context) { return getPrefs(context).getBoolean(SettingsActivity.SHOW_TODAY_PREFERENCE_KEY, true); } public static int getEventDisplayPeriod(Context context) { return Integer.valueOf(getPrefs(context).getString(SettingsActivity.SHOW_EVENTS_PERIOD_PREFERENCE_KEY, context.getResources().getString(R.string.preferences_widget_days_default))); } public static boolean isShowEvents(Context context) { return getPrefs(context).getBoolean(SettingsActivity.SHOW_EVENTS_PREFERENCE_KEY, true); } public static boolean isShowWeather(Context context) { return getPrefs(context).getBoolean(SettingsActivity.SHOW_WEATHER_PREFERENCE_KEY, true); } public static boolean isTopSpaceReserved(Context context) { return isShowToday(context) || isShowWeather(context) || isShowEvents(context); } public static void backwardCompatibility(Context context) { final String SHOW_TOP_WIDGET_PREFERENCE_KEY = "pref_topWidget"; SharedPreferences prefs = getPrefs(context); if (prefs.contains(SHOW_TOP_WIDGET_PREFERENCE_KEY)) { boolean value = prefs.getBoolean(SHOW_TOP_WIDGET_PREFERENCE_KEY, true); if (!value) { prefs.edit().putBoolean(SettingsActivity.SHOW_EVENTS_PREFERENCE_KEY, false).commit(); prefs.edit().putBoolean(SettingsActivity.SHOW_WEATHER_PREFERENCE_KEY, false).commit(); prefs.edit().putBoolean(SettingsActivity.SHOW_TODAY_PREFERENCE_KEY, false).commit(); } prefs.edit().remove(SHOW_TOP_WIDGET_PREFERENCE_KEY).commit(); } } }
omnirom/android_packages_apps_OmniSwitch
src/org/omnirom/omniswitch/SwitchConfiguration.java
Java
gpl-3.0
24,468
package de.devland.masterpassword.base; import com.orm.SugarApp; import com.squareup.otto.Bus; import com.squareup.otto.ThreadEnforcer; import de.devland.masterpassword.base.ui.BaseActivity; /** * Created by David Kunzler on 21.11.2014. */ public class BaseApp extends SugarApp { private static BaseApp instance; private Bus bus; private BaseActivity currentForegroundActivity; public static BaseApp getInstance() { return BaseApp.instance; } public void onCreate() { super.onCreate(); instance = this; bus = new Bus(ThreadEnforcer.ANY); } public static BaseApp get() { return instance; } public Bus getBus() { return this.bus; } public BaseActivity getCurrentForegroundActivity() { return this.currentForegroundActivity; } public void setCurrentForegroundActivity(BaseActivity currentForegroundActivity) { this.currentForegroundActivity = currentForegroundActivity; } }
dkunzler/masterpassword
app/src/main/java/de/devland/masterpassword/base/BaseApp.java
Java
gpl-3.0
1,008
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.nest.dat.layersrc; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.grender.Rendering; import com.bc.ceres.grender.Viewport; import org.esa.beam.framework.datamodel.Band; import org.esa.beam.framework.datamodel.MetadataElement; import org.esa.beam.framework.datamodel.Product; import org.esa.beam.framework.datamodel.RasterDataNode; import org.esa.nest.dat.graphics.GraphicShape; import org.esa.nest.dat.layers.ScreenPixelConverter; import org.esa.snap.datamodel.AbstractMetadata; import java.awt.*; import java.util.ArrayList; import java.util.List; /** * Shows the movement of GCP in a coregistered image */ public class GCPVectorLayer extends Layer { private final Product product; private final Band band; private static final float lineThickness = 4.0f; private final List<GCPData> gcpList = new ArrayList<>(200); public GCPVectorLayer(PropertySet configuration) { super(LayerTypeRegistry.getLayerType(GCPVectorLayerType.class.getName()), configuration); setName("GCP Movement"); product = (Product) configuration.getValue("product"); band = (Band) configuration.getValue("band"); getData(); } private void getData() { final MetadataElement absRoot = AbstractMetadata.getAbstractedMetadata(product); if (absRoot != null) { final MetadataElement bandElem = AbstractMetadata.getBandAbsMetadata(absRoot, band.getName(), false); if (bandElem != null) { final MetadataElement warpDataElem = bandElem.getElement("WarpData"); if (warpDataElem != null) { final MetadataElement[] gcpElems = warpDataElem.getElements(); gcpList.clear(); for (MetadataElement gcpElem : gcpElems) { final double mstX = gcpElem.getAttributeDouble("mst_x", 0); final double mstY = gcpElem.getAttributeDouble("mst_y", 0); final double slvX = gcpElem.getAttributeDouble("slv_x", 0); final double slvY = gcpElem.getAttributeDouble("slv_y", 0); gcpList.add(new GCPData(mstX, mstY, slvX, slvY)); } } } } } @Override protected void renderLayer(Rendering rendering) { if (gcpList.isEmpty()) return; final Viewport vp = rendering.getViewport(); final RasterDataNode raster = band; final ScreenPixelConverter screenPixel = new ScreenPixelConverter(vp, raster); if (!screenPixel.withInBounds()) { return; } final Graphics2D graphics = rendering.getGraphics(); graphics.setStroke(new BasicStroke(lineThickness)); graphics.setColor(Color.RED); for (GCPData gcp : gcpList) { GraphicShape.drawArrow(graphics, screenPixel, (int) gcp.slvX, (int) gcp.slvY, (int) gcp.mstX, (int) gcp.mstY); } } private static class GCPData { public final double mstX, mstY; public final double slvX, slvY; public GCPData(double mX, double mY, double sX, double sY) { this.mstX = mX; this.mstY = mY; this.slvX = sX; this.slvY = sY; } } }
kristotammeoja/ks
s1tbx-op-coregistration/src/main/java/org/esa/nest/dat/layersrc/GCPVectorLayer.java
Java
gpl-3.0
4,168
/** * @author Mathew "WSpecificermadev" WSpecificer * created on 09.05.2017 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.claim') .controller('ClaimCtrl', ClaimCtrl); /** @ngInject */ function ClaimCtrl($scope, $stateParams, claim, explorer, utility) { $scope.explorer = explorer; $scope.util = utility; var id = $stateParams.id; claim.getSpecificDefer(id).then(function () { var temp = claim.getSpecificData(); $scope.selectedClaimData = temp; }); } })();
cryptodevorg/Cortes-Explorer
src/app/pages/claim/ClaimCtrl.js
JavaScript
gpl-3.0
574
#ifndef __DIV64_H__ #define __DIV64_H__ #include <xboot.h> #include <types.h> u64_t div64(u64_t num, u64_t den); u64_t mod64(u64_t num, u64_t den); u64_t div64_64(u64_t * num, u64_t den); #endif /* __DIV64_H__ */
wayling/xboot-clone
src/include/div64.h
C
gpl-3.0
216
/// <summary> /// MethodsResourceDeployer.cs /// Andrea Tino - 2017 /// </summary> namespace Rosetta.AST.Renderings.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Rosetta.Renderings; using TestData = Rosetta.AST.Renderings.Data; using RenderingUtils = Rosetta.Renderings.Utilities; /// <summary> /// /// </summary> internal class MethodsResourceDeployer : IResourceProvider { /// <summary> /// Provides the necessary resources for processing comparison test. /// </summary> /// <returns></returns> public IEnumerable<TestResource> Provide() => RenderingUtils.RetrieveAllTestMethodsInClassContainer(this.Container) .Select(method => method.Name) .Select(name => new TestResource(this.Container, name, this.Assembly)); private Assembly Assembly => typeof(MethodsResourceDeployer).Assembly; private Type Container => typeof(TestData.Methods); } }
andry-tino/Rosetta
test/renderers/ASTWalker.Renderings.Tests/providers/MethodsResourceDeployer.cs
C#
gpl-3.0
1,064
package com.github.sgelb.booket.models; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.support.v4.content.ContextCompat; import android.util.Log; import android.widget.ImageView; import com.github.sgelb.booket.R; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; public class BitmapLoader { private static final String LOG_TAG = "BitmapLoader"; private final Context context; private final BitmapCache cache; private final Bitmap placeholder; public BitmapLoader(Context context) { this.context = context; this.cache = BitmapCache.getInstance(); this.placeholder = drawableToBitmap(ContextCompat.getDrawable(context, R.drawable.ic_blank_page)); } public void load(Book book, ImageView imageView) { String bid = book.getGoogleId(); // from cache Bitmap bitmap = cache.getBitmap(bid); if (bitmap != null) { Log.d(LOG_TAG, "Load bitmap from cache " + book.getTitle()); imageView.setImageBitmap(bitmap); return; } final WeakReference<ImageView> imageViewReference = new WeakReference<>(imageView); // TODO: test for file and move actual loading to AsyncTask // from disk bitmap = loadFromDisk(bid); if (bitmap != null) { Log.d(LOG_TAG, "Load bitmap from disk " + book.getTitle()); setCachedResizedBitmap(bitmap, bid, imageViewReference); return; } Log.d(LOG_TAG, "Load bitmap from web " + book.getTitle()); download(book, imageView); } private Bitmap loadFromDisk(String key) { String filename = key + ".jpg"; FileInputStream fis; Bitmap bitmap = null; try { fis = context.openFileInput(filename); bitmap = BitmapFactory.decodeStream(fis); fis.close(); } catch (FileNotFoundException e) { return null; } catch (IOException e) { // could not close fis e.printStackTrace(); } return bitmap; } private void setCachedResizedBitmap(Bitmap bitmap, String key, WeakReference<ImageView> imageViewWeakReference) { bitmap = resizeBitmapToWidth(bitmap); // always cache bitmaps loaded from disk or net cache.addBitmap(key, bitmap); if (imageViewWeakReference != null) { // only shown if referencing imageView still exists imageViewWeakReference.get().setImageBitmap(bitmap); } } private Bitmap resizeBitmapToWidth(Bitmap bitmap) { int width = (int) context.getResources().getDimension(R.dimen.thumbnail_width); int height = width * bitmap.getHeight() / bitmap.getWidth(); return Bitmap.createScaledBitmap(bitmap, width, height, true); } private void download(Book book, ImageView imageView) { if (cancelPotentialDownload(book.getGoogleId(), imageView)) { Log.d(LOG_TAG, "Downloading cover for " + book.getTitle()); BitmapDownloaderTask task = new BitmapDownloaderTask(imageView); DownloadedDrawable downloadedDrawable = new DownloadedDrawable(context.getResources(), placeholder, task); imageView.setImageDrawable(downloadedDrawable); task.execute(book.getGoogleId()); } } private static boolean cancelPotentialDownload(String bid, ImageView imageView) { BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); if (bitmapDownloaderTask != null) { String bitmapId = bitmapDownloaderTask.bid; if ((bitmapId == null) || (!bitmapId.equals(bid))) { bitmapDownloaderTask.cancel(true); } else { // URL is already being downloaded return false; } } // there was no download on this imageView or current download has been canceled return true; } private static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) { if (imageView != null) { Drawable drawable = imageView.getDrawable(); if (drawable instanceof DownloadedDrawable) { DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable; return downloadedDrawable.getBitmapDownloaderTask(); } } return null; } private class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> { private String bid; private final WeakReference<ImageView> imageViewReference; BitmapDownloaderTask(ImageView imageView) { imageViewReference = new WeakReference<>(imageView); } @Override protected Bitmap doInBackground(String... params) { bid = params[0]; return downloadBitmap(bid); } @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } bitmap = resizeBitmapToWidth(bitmap); cache.addBitmap(bid, bitmap); ImageView imageView = imageViewReference.get(); BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); // Change bitmap only if this process is still associated with it if (this == bitmapDownloaderTask) { imageView.setImageBitmap(bitmap); } } } private Bitmap downloadBitmap(String googleId) { Bitmap bitmap = null; HttpURLConnection con = null; //String isbn = BookHelper.isbn13to10(params[0]); URL url; // TODO: separate download sources String[] thumbnailUrls = { //"https://images-na.ssl-images-amazon.com/images/P/" + isbn + ".01", "https://books.google.de/books?id=" + googleId + "&printsec=frontcover&img=1&zoom=1" }; for (String thumbnailUrl : thumbnailUrls) { try { url = new URL(thumbnailUrl); con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(10000); con.setDoInput(true); con.connect(); if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream input = con.getInputStream(); bitmap = BitmapFactory.decodeStream(input); } } catch (MalformedURLException e) { Log.d("BOOKET", "MalformedURLException: " + e.getMessage()); } catch (SocketTimeoutException e) { Log.d("BOOKET", "SocketTimeoutException: " + e.getMessage()); } catch (IOException e) { Log.d("BOOKET", "IOException: " + e.getMessage()); } finally { if (con != null) { con.disconnect(); } } if (bitmap != null && bitmap.getWidth() > 1) { return bitmap; } } return bitmap; } /** * A fake Drawable that will be attached to the imageView while the download is in progress. * * <p>Contains a reference to the actual download task, so that a download task can be stopped * if a new binding is required, and makes sure that only the last started download process can * bind its result, independently of the download finish order.</p> */ private static class DownloadedDrawable extends BitmapDrawable { private final WeakReference<BitmapDownloaderTask> taskReference; DownloadedDrawable(Resources res, Bitmap bitmap, BitmapDownloaderTask task) { super(res, bitmap); taskReference = new WeakReference<>(task); } BitmapDownloaderTask getBitmapDownloaderTask() { return taskReference.get(); } } private Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return resizeBitmapToWidth(bitmap); } }
sgelb/booket
booket/app/src/main/java/com/github/sgelb/booket/models/BitmapLoader.java
Java
gpl-3.0
8,861
# SimpleNetwork
lyusupov/SoftRF
software/firmware/source/libraries/SimpleNetwork/README.md
Markdown
gpl-3.0
16
package xingu.utils.classloader.impl; import xingu.lang.NotImplementedYet; import xingu.utils.classloader.ClassLoaderManager; import xingu.utils.classloader.NamedClassLoader; public class ContextClassLoaderManager { private static ClassLoaderManager INSTANCE; static { final NamedClassLoader wrapper = new ClassLoaderAdapter("context-classloader", Thread.currentThread().getContextClassLoader()); INSTANCE = new ClassLoaderManager() { @Override public NamedClassLoader byId(String classLoaderName) { return wrapper; } @Override public void register(NamedClassLoader cl) { throw new NotImplementedYet(); } }; } public static ClassLoaderManager getClassLoaderManager() { return INSTANCE; } }
leandrocruz/xingu
utils/src/main/java/xingu/utils/classloader/impl/ContextClassLoaderManager.java
Java
gpl-3.0
756
/* * This file is part of Dependency-Track. * * Dependency-Track is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Dependency-Track is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * Dependency-Track. If not, see http://www.gnu.org/licenses/. */ package org.owasp.dependencytrack.model; import javax.persistence.*; import java.math.BigDecimal; @Entity @Table(name = "vulnerability") public class Vulnerability { public enum Severity { HIGH, MEDIUM, LOW, INFO } /** * The unique identifier of the persisted object. */ @Id @Column(name = "id") @GeneratedValue private Integer id; @Column(name = "name") private String name; @Column(name = "description", columnDefinition = "LONGTEXT") private String description; @Column(name = "CWE ") private String cwe; @Column(name = "cvssscore") private BigDecimal cvssScore; @Column(name = "matchedcpe") private String matchedCPE; @Column(name = "matchedallpreviouscpe") private String matchedAllPreviousCPE; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCwe() { return cwe; } public String getCweId() { if (cwe != null) { return cwe.substring(4, 7); } return null; } public Severity getSeverity() { final double dv = cvssScore.doubleValue(); if (dv >= 7) { return Severity.HIGH; } else if (dv >= 4) { return Severity.MEDIUM; } else if (dv > 0) { return Severity.LOW; } else { return Severity.INFO; } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setCwe(String cwe) { this.cwe = cwe; } public BigDecimal getCvssScore() { return cvssScore; } public void setCvssScore(BigDecimal cvssScore) { this.cvssScore = cvssScore; } public String getMatchedCPE() { return matchedCPE; } public void setMatchedCPE(String matchedCPE) { this.matchedCPE = matchedCPE; } public String getMatchedAllPreviousCPE() { return matchedAllPreviousCPE; } public void setMatchedAllPreviousCPE(String matchedAllPreviousCPE) { this.matchedAllPreviousCPE = matchedAllPreviousCPE; } }
wjase/dependency-track
src/main/java/org/owasp/dependencytrack/model/Vulnerability.java
Java
gpl-3.0
3,125
<?php /** * Created by PhpStorm. * User: Ermin Islamagić - https://ermin.islamagic.com * Date: 19.8.2016 * Time: 10:10 */ // Plugin config array $config = array(); // Name $config['PLUGIN_NAME'] = 'Locale'; // Model $config['PLUGIN_MODEL'] = 'LocaleModel'; // Directory $config['PLUGIN_DIR'] = 'app/plugins/' . $config['PLUGIN_NAME'] . '/'; // Controller path $config['PLUGIN_CONTROLLERS_PATH'] = $config['PLUGIN_DIR'] . 'controllers/'; // Model path $config['PLUGIN_MODELS_PATH'] = $config['PLUGIN_DIR'] . 'models/'; // Views path $config['PLUGIN_VIEWS_PATH'] = $config['PLUGIN_DIR'] . 'views/'; // Components path $config['PLUGIN_COMPONENTS_PATH'] = $config['PLUGIN_CONTROLLERS_PATH'] . 'components/'; // Web path $config['PLUGIN_WEB_PATH'] = $config['PLUGIN_DIR'] . 'web/'; // Image path $config['PLUGIN_IMG_PATH'] = $config['PLUGIN_WEB_PATH'] . 'img/'; // Css path $config['PLUGIN_CSS_PATH'] = $config['PLUGIN_WEB_PATH'] . 'css/'; // Js path $config['PLUGIN_JS_PATH'] = $config['PLUGIN_WEB_PATH'] . 'js/'; // Libraries path $config['PLUGIN_LIBS_PATH'] = $config['PLUGIN_WEB_PATH'] . 'libs/'; // ID $config['PLUGIN_ID'] = "3"; // Version $config['PLUGIN_VERSION'] = "1.0"; // Build $config['PLUGIN_BUILD'] = "1.0.0"; // Initiate Registry $registry = Registry::getInstance(); // Register the plugin config $registry->set($config['PLUGIN_NAME'], $config); // Get all plugins $plugins = $registry->get('plugins'); // Check if "$plugins" variable type is equal null if (is_null($plugins)) { // Set "$plugins" variable type to empty array $plugins = array(); } // Update plugin name type to array with plugin name $plugins[$config['PLUGIN_NAME']] = array('Locale'); // Register the plugin $registry->set('plugins', $plugins); // Unset plugin config array unset($config); // Unset plugins array unset($plugins);
clientmarketing/food-factory
source/app/plugins/Locale/config/config.inc.php
PHP
gpl-3.0
1,840
; no symbol conflict x equ 1 y data x, y end
endlos99/xdt99
test/asm/aslinks2a.asm
Assembly
gpl-3.0
51
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef OLDSTYLE_CASTS_H #define OLDSTYLE_CASTS_H #include <QtCore/qobject.h> class OldStyleCast: public QObject { Q_OBJECT public: signals: public slots: inline void foo() {} inline int bar(int, int*, const int *, volatile int *, const int * volatile *) { return 0; } inline void slot(int, QObject * const) {} }; #endif // OLDSTYLE_CASTS_H
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtbase/tests/auto/tools/moc/oldstyle-casts.h
C
gpl-3.0
1,634
package net.modyssey.starmall.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.util.ResourceLocation; import net.modyssey.starmall.client.gui.components.ScrollingList; import net.modyssey.starmall.markets.stock.StockCategory; import org.lwjgl.opengl.GL11; import java.awt.geom.Rectangle2D; public class GuiItemStockList extends ScrollingList { private StockCategory stockCategory; private GuiTeleporterController parent; private RenderItem itemRenderer = new RenderItem(); private FontRenderer fontRenderer; private int selectedItem = -1; public GuiItemStockList(GuiTeleporterController parent, FontRenderer fontRenderer) { super(new Rectangle2D.Double(57,28,55,110), 20); this.parent = parent; this.fontRenderer = fontRenderer; itemRenderer.zLevel += 5; } public void setStockCategory(StockCategory stockCategory) { this.stockCategory = stockCategory; } public int getSelectedItem() { return selectedItem; } public void clearSelectedItem() { selectedItem = -1; } @Override protected void itemMouseClick(int item) { selectedItem = item; parent.updateItem(); } @Override protected Rectangle2D getScrollGripBounds() { return new Rectangle2D.Double(207, 12, 6, 11); } @Override protected ResourceLocation getScrollGripTexture() { return new ResourceLocation("starmall:textures/gui/station.png"); } @Override protected int getScrollGripTopCap() { return 2; } @Override protected int getScrollGripBottomCap() { return 1; } @Override protected Rectangle2D getScrollTrackBounds() { return new Rectangle2D.Double(112, 28, 6, 111); } @Override protected int getEntryCount() { return (stockCategory == null)?0:stockCategory.getItemCount(); } @Override protected void drawEntry(int i, int y) { int rectX = getX() + 1; int rectY = getY() + y + 1; GL11.glEnable(GL11.GL_DEPTH_TEST); if (i == selectedItem) { drawHorizontalLine(getX(), getX() + getWidth() - 2, rectY-1, 0xFFFFFFFF); drawHorizontalLine(getX(), getX() + getWidth() - 2, rectY+getEntryHeight()-2, 0xFFFFFFFF); drawVerticalLine(getX(), rectY-1, rectY+getEntryHeight()-2, 0xFFFFFFFF); drawVerticalLine(getX() + getWidth() - 2, rectY-1, rectY+getEntryHeight()-2, 0xFFFFFFFF); } GL11.glEnable(GL11.GL_LIGHTING); GL11.glPushMatrix(); GL11.glTranslatef(0, 0, -5); itemRenderer.renderItemIntoGUI(fontRenderer, Minecraft.getMinecraft().getTextureManager(), stockCategory.get(i).getItem(), rectX, rectY, true); GL11.glPopMatrix(); GL11.glDisable(GL11.GL_LIGHTING); String displayText = stockCategory.get(i).getItem().getDisplayName(); int displayTextLen = fontRenderer.getStringWidth(displayText); if (displayTextLen >= 37) { String ellipsis = "..."; int ellipsisLen = fontRenderer.getStringWidth(ellipsis); while (displayText.length() > 0 && displayTextLen + ellipsisLen >= 37) { displayText = displayText.substring(0, displayText.length()-2); displayTextLen = fontRenderer.getStringWidth(displayText); } displayText = displayText.concat(ellipsis); } fontRenderer.drawString(displayText, rectX + 18, rectY + 6, 0xFFFFFF, false); GL11.glDisable(GL11.GL_DEPTH_TEST); } }
CannibalVox/ModJamTeleporters
src/main/java/net/modyssey/starmall/client/gui/GuiItemStockList.java
Java
gpl-3.0
3,679
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package myclasses.salisterra.ro; public class ClasaMea { public static void main (String[] args) { // create an instance of MyClass MyClass obiectSauInstanta = new MyClass("cucubaw este doar un sir"); MyClass altobiect = new MyClass("alt sir Nata ;)"); MyClass altreileaobiect = new MyClass("deja e stresant nu?"); System.out.println(obiectSauInstanta.myString); System.out.println(obiectSauInstanta.getCounter()); MyClass.cucu = 10.0; System.out.println(MyClass.cucu); Creion c = new Creion(); c.producator = "Herliz"; System.out.println(c.producator); } }
gapacurar/eBooksStore
Test/src/myclasses/salisterra/ro/ClasaMea.java
Java
gpl-3.0
979
/* * ScatterGDX.h - scatter effect * * Copyright (c) 2017-2020 gi0e5b06 (on github.com) * * This file is part of LSMM - * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #ifndef SCATTERGDX_H #define SCATTERGDX_H #include "Effect.h" #include "ScatterGDXControls.h" #include "ValueBuffer.h" #include "lmms_math.h" class ScatterGDXEffect : public Effect { public: ScatterGDXEffect(Model* parent, const Descriptor::SubPluginFeatures::Key* key); virtual ~ScatterGDXEffect(); virtual bool processAudioBuffer(sampleFrame* buf, const fpp_t frames); virtual EffectControls* controls() { return &m_gdxControls; } protected: private: ScatterGDXControls m_gdxControls; sampleFrame* m_buffer; uint32_t m_len, m_prev; int32_t m_pos, m_time; int32_t m_start, m_end; friend class ScatterGDXControls; }; #endif
gi0e5b06/lmms
plugins/ScatterGDX/ScatterGDX.h
C
gpl-3.0
1,569
{% comment %} Explanation of what we're doing to render the text content in psuedo ruby: body = "1 <ref> A </ref> 2 <ref> B </ref> <ref> A </ref>" body_split = body.split('<ref>') # i.e. [ '1', 'A </ref> 2', 'B </ref>', 'A </ref>' ] if text contains '</ref>' ref_and_text = text.split('</ref>') ref = ref_and_text.first.normalize_whitespace.strip.slugify increment ref_number render link from ref if ref_and_text.length > 1 render ref_and_text.last # e.g. [ 'A', '2'] else render text # e.g. the first group -------- References - read the code or something {% endcomment %} <span data-initialize-ref-count="{% increment ref_number %}"></span> {% assign citations = '' | split: '' %} {% assign body_split = content | split: '<ref>' %} {% assign char_count = '' %} {% comment %} ^ Instatiate variables, including ref_number since it starts at 0 {% endcomment %} <section class="text"> {% for text in body_split %} {% if text contains '</ref>' %} {% assign ref_and_text = text | split: '</ref>' %} {% assign ref = ref_and_text.first | strip | strip_newlines | downcase | replace: ' ', ' ' | replace: ' ', '-' | split: '|' %} {% assign citations = citations | concat: ref %} <sup id="cite_ref-{{ ref }}" class="reference"> <a href="#cite_note-{{ ref }}">[{% increment ref_number %}]</a> </sup> {% if ref_and_text.size == 2 %} {% assign char_count = char_count | append: ref_and_text.last %} {{ ref_and_text.last }} {% endif %} {% else %} {% assign char_count = char_count | append: text %} {{ text }} {% endif %} {% endfor %} </section> <section class="references"> <ol> {% assign uniq_references = citations | uniq %} {% assign ref_titles = page.references | map: 'title' %} {% assign ref_slugs = '' | split: '' %} {% assign alphabet = 'abcdefghijklmnopqrstuvwxyz' | split: '' %} {% for title in ref_titles %} {% assign slug = title | strip | strip_newlines | downcase | replace: ' ', ' ' | replace: ' ', '-' | split: '|' %} {% assign ref_slugs = ref_slugs | concat: slug %} {% endfor %} {% for ref_slug in uniq_references %} {% for s in ref_slugs %} {% if s == ref_slug %} {% assign index_of_ref = forloop.index0 %}{% break %} {% endif %} {% endfor %} {% assign reference = page.references[index_of_ref] %} {% assign citation_positions = '' | split: '' %} {% for s in citations %} {% if s == ref_slug %} {% assign citation_position = forloop.index | split: '|' %} {% assign citation_positions = citation_positions | concat: citation_position %} {% endif %} {% endfor %} <li id="cite_note-{{ ref_slug }}"> <span class="cite-backlink"> {% if citation_positions.size == 1 %} <b><a href="#cite_ref-{{ citation_positions.first }}">^</a></b> {% else %} ^ {% for n in citation_positions %} <a href="#cite_ref-{{ n }}"><sup><i> <b>{{ alphabet[forloop.index0] }}</b> </i></sup></a> {% endfor %} {% endif %} </span> <span class="reference-text"> <cite> {{ reference.author }} {% if reference.date_published %} ({{ reference.date_published }}) {% endif %} <a href="{{ reference.link }}">{{ reference.title }}</a>. {% if reference.publisher %} <i>{{ reference.publisher }}</i> {% endif %} </cite> </span> </li> {% endfor %} </ol> </section> <div class="link-to-pr"> <a href="{{ repository_url }}/edit/gh-pages/{{ uri_escaped_page_name }}">Improve this argument</a> </div> <div class="character-count"> <strong>Character count:</strong> <span>{{ char_count | strip_html | strip | strip_newlines | replace: ' ', ' ' | size }}</span> </div>
convinceme/webapp
app/views/arguments/liquid_template.html
HTML
gpl-3.0
4,025
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2004 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _TRAVERSE_H #define _TRAVERSE_H #pragma ident "@(#)traverse.h 1.4 05/06/08 SMI" /* * Routines used to traverse tdesc trees, invoking user-supplied callbacks * as the tree is traversed. */ #ifdef __cplusplus extern "C" { #endif #include "ctftools.h" typedef int (*tdtrav_cb_f)(tdesc_t *, tdesc_t **, void *); typedef struct tdtrav_data { int vgen; tdtrav_cb_f *firstops; tdtrav_cb_f *preops; tdtrav_cb_f *postops; void *private; } tdtrav_data_t; void tdtrav_init(tdtrav_data_t *, int *, tdtrav_cb_f *, tdtrav_cb_f *, tdtrav_cb_f *, void *); int tdtraverse(tdesc_t *, tdesc_t **, tdtrav_data_t *); int iitraverse(iidesc_t *, int *, tdtrav_cb_f *, tdtrav_cb_f *, tdtrav_cb_f *, void *); int iitraverse_hash(hash_t *, int *, tdtrav_cb_f *, tdtrav_cb_f *, tdtrav_cb_f *, void *); int iitraverse_td(iidesc_t *ii, tdtrav_data_t *); int tdtrav_assert(tdesc_t *, tdesc_t **, void *); #ifdef __cplusplus } #endif #endif /* _TRAVERSE_H */
mgood7123/UPM
Sources/dtrace-20160613/cmd/ctfconvert/traverse.h
C
gpl-3.0
1,918
class ElectricGuitar { private String brand; private int numOfPickups; private boolean rockStarUsesIt; public String getBrand() { return brand; } public void setBrand (String aBrand) { brand = aBrand; } public int getNumOfPickups () { return numOfPickups; } public void setNumOfPickups (int num) { numOfPickups = num; } public boolean getRockStarUsesIt() { return rockStarUsesIt; } public void setRockStarUsesIt (boolean yesOrNo) { rockStarUsesIt = yesOrNo; } }
ojwm/java_examples
headfirstjava/ElectricGuitar.java
Java
gpl-3.0
567
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Sun Sep 23 01:32:32 CEST 2012 --> <title>Click</title> <meta name="date" content="2012-09-23"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Click"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Click.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/abmash/core/browser/interaction/Clear.html" title="class in com.abmash.core.browser.interaction"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/abmash/core/browser/interaction/Click.ClickType.html" title="enum in com.abmash.core.browser.interaction"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/abmash/core/browser/interaction/Click.html" target="_top">Frames</a></li> <li><a href="Click.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_com.abmash.core.browser.interaction.ActionOnBrowser">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.abmash.core.browser.interaction</div> <h2 title="Class Click" class="title">Class Click</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../../com/abmash/core/browser/interaction/ActionOnBrowser.html" title="class in com.abmash.core.browser.interaction">com.abmash.core.browser.interaction.ActionOnBrowser</a></li> <li> <ul class="inheritance"> <li><a href="../../../../../com/abmash/core/browser/interaction/ActionOnHtmlElement.html" title="class in com.abmash.core.browser.interaction">com.abmash.core.browser.interaction.ActionOnHtmlElement</a></li> <li> <ul class="inheritance"> <li>com.abmash.core.browser.interaction.Click</li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">Click</span> extends <a href="../../../../../com/abmash/core/browser/interaction/ActionOnHtmlElement.html" title="class in com.abmash.core.browser.interaction">ActionOnHtmlElement</a></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/abmash/core/browser/interaction/Click.ClickType.html" title="enum in com.abmash.core.browser.interaction">Click.ClickType</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/abmash/core/browser/interaction/Click.html#Click(com.abmash.api.Browser, com.abmash.api.HtmlElement, com.abmash.core.browser.interaction.Click.ClickType)">Click</a></strong>(<a href="../../../../../com/abmash/api/Browser.html" title="class in com.abmash.api">Browser</a>&nbsp;browser, <a href="../../../../../com/abmash/api/HtmlElement.html" title="class in com.abmash.api">HtmlElement</a>&nbsp;element, <a href="../../../../../com/abmash/core/browser/interaction/Click.ClickType.html" title="enum in com.abmash.core.browser.interaction">Click.ClickType</a>&nbsp;clickType)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_com.abmash.core.browser.interaction.ActionOnBrowser"> <!-- --> </a> <h3>Methods inherited from class&nbsp;com.abmash.core.browser.interaction.<a href="../../../../../com/abmash/core/browser/interaction/ActionOnBrowser.html" title="class in com.abmash.core.browser.interaction">ActionOnBrowser</a></h3> <code><a href="../../../../../com/abmash/core/browser/interaction/ActionOnBrowser.html#execute()">execute</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Click(com.abmash.api.Browser, com.abmash.api.HtmlElement, com.abmash.core.browser.interaction.Click.ClickType)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Click</h4> <pre>public&nbsp;Click(<a href="../../../../../com/abmash/api/Browser.html" title="class in com.abmash.api">Browser</a>&nbsp;browser, <a href="../../../../../com/abmash/api/HtmlElement.html" title="class in com.abmash.api">HtmlElement</a>&nbsp;element, <a href="../../../../../com/abmash/core/browser/interaction/Click.ClickType.html" title="enum in com.abmash.core.browser.interaction">Click.ClickType</a>&nbsp;clickType)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Click.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/abmash/core/browser/interaction/Clear.html" title="class in com.abmash.core.browser.interaction"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/abmash/core/browser/interaction/Click.ClickType.html" title="enum in com.abmash.core.browser.interaction"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/abmash/core/browser/interaction/Click.html" target="_top">Frames</a></li> <li><a href="Click.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_com.abmash.core.browser.interaction.ActionOnBrowser">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
alp82/abmash
doc/com/abmash/core/browser/interaction/Click.html
HTML
gpl-3.0
10,535
package cm.aptoide.pt.abtesting; import cm.aptoide.pt.dataprovider.ws.v7.BaseBody; /** * Created by franciscocalado on 19/06/18. */ public class ABTestImpressionResponse extends BaseBody { private boolean cache; private String payload; private String assignment; private String context; private String status; public boolean isCache() { return cache; } public void setCache(boolean cache) { this.cache = cache; } public String getPayload() { return payload; } public void setPayload(String payload) { this.payload = payload; } public String getAssignment() { return assignment; } public void setAssignment(String assignment) { this.assignment = assignment; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
Aptoide/aptoide-client-v8
app/src/main/java/cm/aptoide/pt/abtesting/ABTestImpressionResponse.java
Java
gpl-3.0
989
package cm.aptoide.pt.search; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cursoradapter.widget.CursorAdapter; import cm.aptoide.pt.R; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class SuggestionCursorAdapter extends CursorAdapter { private static final int ITEM_LAYOUT = R.layout.simple_dropdown_item; private static final String[] COLUMN_NAMES = { "_id", android.app.SearchManager.SUGGEST_COLUMN_TEXT_1 }; private final List<String> suggestions; public SuggestionCursorAdapter(Context context, List<String> initialSuggestions) { super(context, null, false); this.suggestions = new LinkedList<>(); if (initialSuggestions != null && !initialSuggestions.isEmpty()) { setData(initialSuggestions); } } public SuggestionCursorAdapter(Context context) { this(context, Collections.emptyList()); } public void setData(@NonNull List<String> newSuggestions) { suggestions.clear(); suggestions.addAll(newSuggestions); changeCursor(getCursorFor(suggestions)); } @NonNull private MatrixCursor getCursorFor(@NonNull List<String> data) { final MatrixCursor cursor = new MatrixCursor(COLUMN_NAMES, data.size()); int index = 0; for (String item : data) { cursor.newRow() .add(Integer.toString(index++)) .add(item); } return cursor; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context) .inflate(ITEM_LAYOUT, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { TextView textView = (TextView) view.findViewById(R.id.dropdown_text); textView.setText(getSuggestionAtCurrentPosition(cursor)); } public List<String> getSuggestions() { return suggestions; } public CharSequence getSuggestionAt(int position) { final Cursor cursor = getCursor(); if (cursor.moveToPosition(position)) { return getSuggestionAtCurrentPosition(cursor); } throw new UnsupportedOperationException("Unable to find query at position " + position); } private String getSuggestionAtCurrentPosition(Cursor cursor) { return cursor.getString(cursor.getColumnIndex(android.app.SearchManager.SUGGEST_COLUMN_TEXT_1)); } }
Aptoide/aptoide-client-v8
app/src/main/java/cm/aptoide/pt/search/SuggestionCursorAdapter.java
Java
gpl-3.0
2,549
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>apps.home.views</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th bgcolor="#70b0f0" class="navbar-select" >&nbsp;&nbsp;&nbsp;Home&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> Package&nbsp;apps :: Package&nbsp;home :: Module&nbsp;views </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="apps.home.views-pysrc.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <h1 class="epydoc">Source Code for <a href="apps.home.views-module.html">Module apps.home.views</a></h1> <pre class="py-src"> <a name="L1"></a><tt class="py-lineno"> 1</tt> <tt class="py-line"><tt class="py-comment"># -*- coding: utf-8 -*-</tt> </tt> <a name="L2"></a><tt class="py-lineno"> 2</tt> <tt class="py-line"> </tt> <a name="L3"></a><tt class="py-lineno"> 3</tt> <tt class="py-line"><tt class="py-keyword">from</tt> <tt class="py-name">django</tt><tt class="py-op">.</tt><tt class="py-name">http</tt> <tt class="py-keyword">import</tt> <tt class="py-name">HttpResponse</tt> </tt> <a name="L4"></a><tt class="py-lineno"> 4</tt> <tt class="py-line"><tt class="py-keyword">from</tt> <tt class="py-name">django</tt><tt class="py-op">.</tt><tt class="py-name">template</tt> <tt class="py-keyword">import</tt> <tt class="py-name">RequestContext</tt><tt class="py-op">,</tt> <tt class="py-name">loader</tt> </tt> <a name="L5"></a><tt class="py-lineno"> 5</tt> <tt class="py-line"><tt class="py-keyword">from</tt> <tt class="py-name">models</tt> <tt class="py-keyword">import</tt> <tt class="py-name">Bussiness</tt><tt class="py-op">,</tt><tt class="py-name">Student</tt> </tt> <a name="L6"></a><tt class="py-lineno"> 6</tt> <tt class="py-line"> </tt> <a name="L7"></a><tt class="py-lineno"> 7</tt> <tt class="py-line"><tt class="py-comment"># Create your views here.</tt> </tt> <a name="index"></a><div id="index-def"><a name="L8"></a><tt class="py-lineno"> 8</tt> <a class="py-toggle" href="#" id="index-toggle" onclick="return toggle('index');">-</a><tt class="py-line"><tt class="py-keyword">def</tt> <a class="py-def-name" href="apps.home.views-module.html#index">index</a><tt class="py-op">(</tt><tt class="py-param">request</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt> </div><div id="index-collapsed" style="display:none;" pad="++" indent="++++"></div><div id="index-expanded"><a name="L9"></a><tt class="py-lineno"> 9</tt> <tt class="py-line"> <tt class="py-docstring">"""</tt> </tt> <a name="L10"></a><tt class="py-lineno">10</tt> <tt class="py-line"><tt class="py-docstring"> Vista correspondiente a la p&#225;gina principal de la aplicaci&#243;n empresas.</tt> </tt> <a name="L11"></a><tt class="py-lineno">11</tt> <tt class="py-line"><tt class="py-docstring"> En esta vista listamos las empresas almacenadas en la base de datos, as&#237; como </tt> </tt> <a name="L12"></a><tt class="py-lineno">12</tt> <tt class="py-line"><tt class="py-docstring"> los alumnos que est&#225;n trabajando en ella. A continuaci&#243;n, se muestra tambi&#233;n </tt> </tt> <a name="L13"></a><tt class="py-lineno">13</tt> <tt class="py-line"><tt class="py-docstring"> un ranking de las empresas seg&#250;n su nota media.</tt> </tt> <a name="L14"></a><tt class="py-lineno">14</tt> <tt class="py-line"><tt class="py-docstring"> """</tt> </tt> <a name="L15"></a><tt class="py-lineno">15</tt> <tt class="py-line"> <tt class="py-name">template</tt> <tt class="py-op">=</tt> <tt class="py-name">loader</tt><tt class="py-op">.</tt><tt class="py-name">get_template</tt><tt class="py-op">(</tt><tt class="py-string">'home/index.html'</tt><tt class="py-op">)</tt> </tt> <a name="L16"></a><tt class="py-lineno">16</tt> <tt class="py-line"> <tt class="py-name">asociados</tt><tt class="py-op">=</tt><tt class="py-name">dict</tt><tt class="py-op">(</tt><tt class="py-op">)</tt> </tt> <a name="L17"></a><tt class="py-lineno">17</tt> <tt class="py-line"> <tt class="py-name">notas</tt><tt class="py-op">=</tt><tt class="py-name">dict</tt><tt class="py-op">(</tt><tt class="py-op">)</tt> </tt> <a name="L18"></a><tt class="py-lineno">18</tt> <tt class="py-line"> <tt class="py-keyword">for</tt> <tt class="py-name">bussiness</tt> <tt class="py-keyword">in</tt> <tt class="py-name">Bussiness</tt><tt class="py-op">.</tt><tt class="py-name">objects</tt><tt class="py-op">.</tt><tt class="py-name">all</tt><tt class="py-op">(</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt> <a name="L19"></a><tt class="py-lineno">19</tt> <tt class="py-line"> <tt class="py-name">students</tt> <tt class="py-op">=</tt> <tt class="py-op">[</tt><tt class="py-op">]</tt> </tt> <a name="L20"></a><tt class="py-lineno">20</tt> <tt class="py-line"> <tt class="py-name">average</tt><tt class="py-op">=</tt><tt class="py-number">0</tt> </tt> <a name="L21"></a><tt class="py-lineno">21</tt> <tt class="py-line"> <tt class="py-name">cont</tt><tt class="py-op">=</tt><tt class="py-number">0</tt> </tt> <a name="L22"></a><tt class="py-lineno">22</tt> <tt class="py-line"> <tt class="py-keyword">for</tt> <tt class="py-name">student</tt> <tt class="py-keyword">in</tt> <tt class="py-name">Student</tt><tt class="py-op">.</tt><tt class="py-name">objects</tt><tt class="py-op">.</tt><tt class="py-name">all</tt><tt class="py-op">(</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt> <a name="L23"></a><tt class="py-lineno">23</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-name">student</tt><tt class="py-op">.</tt><tt class="py-name">bussiness</tt> <tt class="py-op">==</tt> <tt class="py-name">bussiness</tt><tt class="py-op">:</tt> </tt> <a name="L24"></a><tt class="py-lineno">24</tt> <tt class="py-line"> <tt class="py-name">students</tt><tt class="py-op">.</tt><tt class="py-name">append</tt><tt class="py-op">(</tt><tt class="py-name">student</tt><tt class="py-op">.</tt><tt class="py-name">alias</tt><tt class="py-op">)</tt> </tt> <a name="L25"></a><tt class="py-lineno">25</tt> <tt class="py-line"> <tt class="py-name">average</tt><tt class="py-op">=</tt><tt class="py-name">average</tt><tt class="py-op">+</tt><tt class="py-name">student</tt><tt class="py-op">.</tt><tt class="py-name">mark</tt> </tt> <a name="L26"></a><tt class="py-lineno">26</tt> <tt class="py-line"> <tt class="py-name">cont</tt><tt class="py-op">=</tt><tt class="py-name">cont</tt><tt class="py-op">+</tt><tt class="py-number">1</tt> </tt> <a name="L27"></a><tt class="py-lineno">27</tt> <tt class="py-line"> <tt class="py-name">asociados</tt><tt class="py-op">[</tt><tt class="py-name">bussiness</tt><tt class="py-op">]</tt><tt class="py-op">=</tt><tt class="py-name">students</tt> </tt> <a name="L28"></a><tt class="py-lineno">28</tt> <tt class="py-line"> <tt class="py-name">average</tt><tt class="py-op">=</tt><tt class="py-name">average</tt><tt class="py-op">/</tt><tt class="py-name">cont</tt> </tt> <a name="L29"></a><tt class="py-lineno">29</tt> <tt class="py-line"> <tt class="py-name">notas</tt><tt class="py-op">[</tt><tt class="py-name">bussiness</tt><tt class="py-op">]</tt><tt class="py-op">=</tt><tt class="py-name">average</tt> </tt> <a name="L30"></a><tt class="py-lineno">30</tt> <tt class="py-line"> <tt class="py-name">context</tt> <tt class="py-op">=</tt> <tt class="py-name">RequestContext</tt><tt class="py-op">(</tt><tt class="py-name">request</tt><tt class="py-op">,</tt><tt class="py-op">{</tt><tt class="py-string">'asociados'</tt><tt class="py-op">:</tt><tt class="py-name">asociados</tt><tt class="py-op">,</tt><tt class="py-string">'notas'</tt><tt class="py-op">:</tt><tt class="py-name">notas</tt><tt class="py-op">,</tt><tt class="py-op">}</tt><tt class="py-op">)</tt> </tt> <a name="L31"></a><tt class="py-lineno">31</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt class="py-name">HttpResponse</tt><tt class="py-op">(</tt><tt class="py-name">template</tt><tt class="py-op">.</tt><tt class="py-name">render</tt><tt class="py-op">(</tt><tt class="py-name">context</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt> </div><a name="L32"></a><tt class="py-lineno">32</tt> <tt class="py-line"> </tt><script type="text/javascript"> <!-- expandto(location.href); // --> </script> </pre> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th bgcolor="#70b0f0" class="navbar-select" >&nbsp;&nbsp;&nbsp;Home&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Fri Oct 30 12:26:41 2015 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
mpvillafranca/empresas
src/apps/home/html/apps.home.views-pysrc.html
HTML
gpl-3.0
11,479
package wayerr.reflect; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Класс предоставляющий {@link Type} или {@link Class} по имени типа. Также * позволяет получить некоторую информацию о типе. * * @author rad */ public class TypeFactory { private static final Map<Class, String> m_primToName = new HashMap<Class, String>(); private static final Map<String, Class> m_nameToPrim = new HashMap<String, Class>(); static { // Карта соответсвий имен примитивных типов m_primToName.put(byte.class, "B"); m_primToName.put(char.class, "C"); m_primToName.put(double.class, "D"); m_primToName.put(float.class, "F"); m_primToName.put(int.class, "I"); m_primToName.put(long.class, "J"); m_primToName.put(short.class, "S"); m_primToName.put(boolean.class, "Z"); m_nameToPrim.put("B", byte.class); m_nameToPrim.put("C", char.class); m_nameToPrim.put("D", double.class); m_nameToPrim.put("F", float.class); m_nameToPrim.put("I", int.class); m_nameToPrim.put("J", long.class); m_nameToPrim.put("S", short.class); m_nameToPrim.put("Z", boolean.class); } //private Type m_type; private enum TypeClass { PRIMITIVE, ARRAY, CLASS, PARAMETRIZED } /** * * @param name - имя типа (возвращаемое { * @see Type.toString()} ) */ public TypeFactory(String name) throws ClassNotFoundException { //m_type = parse(name); } public static Type parse(String name) throws ClassNotFoundException { TypeClass tc = getTypeClass(name); Type t = null; switch(tc) { case PRIMITIVE: t = createPrimitive(name); break; case CLASS: t = createClass(name); break; case ARRAY: t = createArray(name); break; case PARAMETRIZED: t = createParametrized(name); break; } return t; } /** * Определяет класс типа * * @param name * @return */ private static TypeClass getTypeClass(String name) { TypeClass tc = null; char start = name.charAt(0); char end = name.charAt(name.length() - 1); if(name.length() == 1) {//примитивный тип обозначенный одной буквой tc = TypeClass.PRIMITIVE; } else if(start == '[' || end == ']') { // массив tc = TypeClass.ARRAY; } else if(end == '>') { // параметризованный (напр List<String>) tc = TypeClass.PARAMETRIZED; } else { // либо класс, либо примитив обозначеннй словом (напр. int ) if(name.indexOf(".") > -1 || Character.isUpperCase(start)) { // тип имеет полное обозначение или тип имеет краткое обозначение //и начинается с большой буквы, значит не примитив или примитив //в боксе напр. java.lang.Integer) tc = TypeClass.CLASS; } else { tc = TypeClass.PRIMITIVE; } } return tc; } private static Class<?> createPrimitive(String name) throws ClassNotFoundException { if(name.length() > 1) { name = getShortPrimName(name); } Class<?> t = m_nameToPrim.get(name); if(t == null) { throw new ClassNotFoundException("Can not load primitive type for name: " + name); } return t; } private static Class<?> createArray(String name) throws ClassNotFoundException { if(name.charAt(0) != '[') { //array имеет имя вроде java.lang.String[] name = name.substring(0, name.length() - 2);//обрезание скобок [] String letter = (name.indexOf('.') > -1) ? "L" : getShortPrimName(name); name = "[" + letter + name + ";"; } return createClass(name); } private static Class<?> createClass(String name) throws ClassNotFoundException { return Class.forName(name, false, TypeFactory.class.getClassLoader()); } private static String getShortPrimName(String name) { return ("boolean".equals(name)) ? "Z" : name.substring(0, 1).toUpperCase(); //z - boolean } private static Type createParametrized(String name) throws ClassNotFoundException { int first = name.indexOf("<"); int last = name.lastIndexOf(">"); String raw = name.substring(0, first); ArrayList<Type> params = new ArrayList<Type>(); String paramsSring = name.substring(first + 1, last); //парсинг char[] chars = paramsSring.toCharArray(); int start = 0; for(int i = 0; i < chars.length; i++) { char ch = chars[i]; if(ch == '<') { // пропускаем до '>' int rec = 1;// означает вложенность "<>" while(rec > 0) { // пока не закроются все открытые '<' ch = chars[++i]; if(ch == '<') {// если открывается '<' ++rec; // то уровень вложенности увеличиваем } else if(ch == '>') { // а если закрывается --rec; //то уменьшаем } } } if(ch == ',' || i == (chars.length - 1)) { //если запятая или конец строки то один параметр закончился String paramName; paramName = paramsSring.substring(start, (i == (chars.length - 1)) ? chars.length : i);// если конец строки то до конца резать params.add(TypeFactory.parse(paramName)); if(ch == ' ' || ch == ',') { // пропускаем запятые и пробелы while(i < chars.length) { ch = chars[++i]; if(ch != ' ' && ch != ',') { break; } } } start = i; } } Type[] pa = new Type[params.size()]; return new ParameterizedTypeImpl(createClass(raw), params.toArray(pa), null); } /** * Скрывает внутри себя набор костыей позволяющих получит имя типа удобное * для сериализации FIXME найти более удобоваримые пути решения данной * проблемы * * @param type * @return */ public static String getName(Type type) { StringBuilder typeName = new StringBuilder(); if(type instanceof GenericArrayType) { //WARNING workaround для получения вменяемого имени типа // берется базовый тип и добавляется перфикс массива и ';' // без этого кода лоя массива строк будет возвращаться // "java.lang.String[]" когда нужно "[Ljava.lang.String;" Type srcType = ((GenericArrayType)type).getGenericComponentType(); //WARNING рекурсия из-за того что исходный тип может оказаться классом \ //или чем еще что также придется причесывать, возможно этого делать ненужно typeName.append("["); if(srcType instanceof Class) {//нужно добавить идентификатор типа Class c = (Class)srcType; if(!c.isPrimitive()) { typeName.append("L");//вида [L<имя класса>; typeName.append(c.getName()); typeName.append(";"); } else { typeName.append(m_primToName.get(c)); } } else { typeName.append(getName(srcType)); } } else if(type instanceof Class) { //WARNING workaround для получения вменяемого имени типа //позволяет избавится от префикса class перед именем типа return ((Class)type).getName(); }/* else if (type instanceof ParameterizedType){ ParameterizedType pt = (ParameterizedType) type; Type raw = pt.getRawType(); typeName.append(getTypeName(raw)); Type params[] = pt.getActualTypeArguments(); for(Type p : params){ typeName.append(' '); typeName.append(getTypeName(p)); } } */ else { typeName.append(type.toString()); } return typeName.toString(); } public static Class<?> getClass(String typeName) throws ClassNotFoundException { TypeClass tc = getTypeClass(typeName); Class<?> t = null; switch(tc) { case PRIMITIVE: t = createPrimitive(typeName); break; case CLASS: t = createClass(typeName); break; case ARRAY: t = createArray(typeName); break; case PARAMETRIZED: int first = typeName.indexOf("<"); String raw = typeName.substring(0, first); t = createClass(raw); break; } return t; } }
wayerr/ivasu
src/main/java/wayerr/reflect/TypeFactory.java
Java
gpl-3.0
10,373
/* * Copyright (C) 2009 Christopho, Solarus - http://www.solarus-engine.org * * Solarus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Solarus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SOLARUS_LANGUAGE_SCREEN_H #define SOLARUS_LANGUAGE_SCREEN_H #include "Common.h" #include "Screen.h" /** * @brief Shows a screen to let the user choose his language. * * This screen is displayed only the first time the program is launched, * that is, when the configuration file does not exist or does not contains * the language setting yet. */ class LanguageScreen: public Screen { private: Transition *transition; Surface *intermediate_surface; std::string *language_codes; TextSurface **language_texts; int cursor_position; int first_visible_language; int nb_visible_languages; static const int max_visible_languages; int nb_languages; bool finished; void set_cursor_position(int cursor_position); public: // creation and destruction LanguageScreen(Solarus &solarus); ~LanguageScreen(); // update and display void notify_event(InputEvent &event); void update(); void display(Surface *destination_surface); }; #endif
ziz/solarus
include/menus/LanguageScreen.h
C
gpl-3.0
1,741
<?php namespace Acd\Controller; use \Acd\View\HeaderMenu; use \Acd\Model\ContentLoader; use \Acd\Model\SessionNavigation; // Output class Relation { private $idContent; private $idStructure; private $view; private $content; private $sessionNavigation; private $requestUrl; const VIEW_LIST = 'list'; // List of all parents of a contents public function __construct() { $this->initializeSessionNavigation(); } /* Setters and getters attributes */ public function setIdContent($id) { $this->id = (string)$id; } public function getIdContent() { return $this->id; } public function setIdStructure($idStructure) { $this->idStructure = (string)$idStructure; } public function getIdStructure() { return $this->idStructure; } public function setView($view) { $this->view = (string)$view; } public function getView() { return $this->view; } private function setContent($content) { $this->content = $content; } private function getContent() { return $this->content; } private function setParents($parents) { $this->parents = $parents; } private function getParents() { return $this->parents; } public function load() { $contentLoader = new ContentLoader(); $contentLoader->setId($this->getIdStructure()); $this->setContent($contentLoader->loadContent('id', $this->getIdContent())); // Parents $this->setParents($contentLoader->loadContents('parents', $this->getIdContent())); } public function getTitle() { return 'Relations of '; } // back button private function initializeSessionNavigation() { $this->sessionNavigation = new SessionNavigation(); $this->sessionNavigation->load(); } public function setRequestUrl($url) { $this->requestUrl = $url; } public function getHeaderMenuOu() { $headerMenuOu = new HeaderMenu(); $headerMenuOu->setBack(!$this->sessionNavigation->isEmpty()); return $headerMenuOu; } public function render() { $ou = new \Acd\View\Relation(); $ou->setContentTitle($this->getContent()->getTitle()); $ou->setParentList($this->getParents()); $this->sessionNavigation->push([ 'hash' => 'relation - '.$this->getIdStructure().' - '.$this->getIdContent(), // Page hash, consecutive same hash no add navigation 'url' => $this->requestUrl, 'title' => $this->getTitle().$this->getContent()->getTitle() ]); $this->sessionNavigation->save(); return $ou->render(); } }
stripTM/acd
app/controller/Relation.php
PHP
gpl-3.0
2,386
<?php //-------------------------------------------------------------------------- // Debut classe conSQL // Gestion du lien avec mySQL //-------------------------------------------------------------------------- class conSQL { var $sqlid = 0; // id SQL utilisé partout //-------------------------------------------------------------------------- // function conSQL // établissement d'une connexion SQL. // - $psrv : nom du serveur sur lequel est exécuté le PHP // (par ex désigné par la variable d'environnement $SERVER_NAME) // - $pdb : nom de la base SQL. NB: chez free, une seule base par utilisateur // donc on modifie la base donnée par l'appelant. //-------------------------------------------------------------------------- function conSQL($psrv, $pdb, $debug) { if ($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) { // si le serveur est la machine locale if ( $debug == "1" ) print "base locale<br>\n"; $srv = "localhost"; $db = $pdb; $user = "root"; $pw = ""; } else { // base de données sur sql.free.fr (une seule base sur ce serveur, nom=login) $srv = "sql.free.fr"; if ( $debug == "1" ) print "base Free: $srv <br>\n"; $db = $pdb; $user = "remi.lapointe"; $pw = "rem000"; } // 128=CLIENT_LOCAL_FILES $this->sqlid = mysql_pconnect($srv , $user, $pw, 128); if ( ! $this->sqlid ) die( "Impossible d'établir une connexion avec MySQL ($srv, $user, ".$_SERVER['SERVER_ADDR'].")" ); mysql_select_db( $db, $this->sqlid ) or die ( "Impossible d'ouvrir la base de données: ".mysql_error() ); } //-------------------------------------------------------------------------- // function selectSQL // exécution d'une requete de sélection, retour du résultat et nombre // d'éléments obtenus. //-------------------------------------------------------------------------- function selectSQL($preq, &$resu) { $resu = mysql_query($preq, $this->sqlid ); if ( ! $resu ) die ( "Requete: \n\t$preq\nErreur fatale avec select: ".mysql_error()); return (mysql_num_rows($resu)); } //-------------------------------------------------------------------------- // function sqlquery // exécution d'une requete de sélection, retour du résultat et nombre // d'éléments obtenus. //-------------------------------------------------------------------------- function sqlquery($preq, &$resu) { $resu = mysql_query($preq, $this->sqlid ); if ( ! $resu ) { print "<p>La requete<br>: $preq<br>\n"; die ( "a provoque l'erreur: ".mysql_error()); } } //-------------------------------------------------------------------------- // function closeSQL // fermeture connexion si existe //-------------------------------------------------------------------------- function closeSQL() { if ($this->sqlid) mysql_close( $this->sqlid ); } } //-------------------------------------------------------------------------- // Fin classe conSQL //-------------------------------------------------------------------------- ?>
remilap/WebRemiFree
php/clas_consql.php
PHP
gpl-3.0
3,167
from math import * def f(e, x): return abs(eval(e.replace('^', '**').replace('x', '('+str(x)+')'))) def solve(e, a, b): N = 1999 t = f(e, a) + f(e, b) for i in range(1, 2*N): if i % 2 == 0: t += 2*f(e, a + (b-a)*i/2/N) else: t += 4*f(e, a + (b-a)*i/2/N) return (b-a)*t/6/N def main(): ## with open('input.txt', 'r') as f: data = f.read().splitlines() a, b = map(int, data[0].split()) e = data[1] ## # a, b = map(int, input().split()) # e = input() ans = solve(e, a, b) # print(ans) ## ans = str(ans) with open('output.txt', 'w') as f: f.write(ans) print('Done:') if len(ans) > 500: print(ans[:200] + '...') else: print(ans) ## main()
Lipen/LipenDev
Azeroth/Northrend/TP Olymp/TaskE.py
Python
gpl-3.0
687
package com.xolider.shipfighter.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector3; import com.xolider.shipfighter.utils.Constants; /** * Created by clement on 20/10/17. */ public class Button { private TextureRegion t; private float x, y, width, height, scale; private boolean alreadyTouch = false; public Button(TextureRegion t, float x, float y, float scale) { this.t = t; this.scale = scale; this.width = t.getRegionWidth()*this.scale; this.height = t.getRegionHeight()*this.scale; this.x = x; this.y = y; this.t.flip(false, true); this.t.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); } public boolean isTouched(int index) { if(Gdx.input.isTouched(index)) { double x = Gdx.input.getX(index)/((double)Gdx.graphics.getWidth()/Constants.WIDTH); double y = Gdx.input.getY(index)/((double)Gdx.graphics.getHeight()/Constants.HEIGHT); if(x > this.x && x < this.x + width && y > this.y && y < this.y + height) { return true; } } return false; } public boolean isClicked(int index) { if(isTouched(index)) { if(!alreadyTouch) { alreadyTouch = true; return true; } return false; } alreadyTouch = false; return false; } public TextureRegion getTexture() { return t; } public void draw(SpriteBatch batch) { batch.draw(this.t, x, y, width, height); } }
xolider/ShipFighter
core/src/com/xolider/shipfighter/ui/Button.java
Java
gpl-3.0
1,827
function MissingFilesPage() { } MissingFilesPage.prototype.createNodes = function() { var self = this; this.page = document.createElement("div"); this.page.innerHTML = "<h1>Missing Files</h1>"; this.content = document.createElement("div"); this.page.appendChild(this.content); this.loadList(function() { }); return this.page; } MissingFilesPage.prototype.removeNodes = function() { $(this.page).remove(); } MissingFilesPage.prototype.groupData = function(data) { // TODO group by directory return data.missingFiles.reduce(function(acc, file) { acc[file.showName] = acc[file.showName] || []; acc[file.showName].push(file); return acc; }, {}); } MissingFilesPage.prototype.loadList = function(callback) { var self = this; $.getJSON("/api/library/filter/missingFiles", function(data) { var grouped = self.groupData(data); $(self.content).empty(); for (var groupKey in grouped) { var groupEl = document.createElement("ol"); groupEl.textContent = groupKey; var groupArray = grouped[groupKey]; var nodes = groupArray.map(function(file) { var el = document.createElement("li"); el.textContent = file.path; return el; }); var deleteButton = self.createDeleteButton(groupArray); $(groupEl).append(deleteButton); $(groupEl).append(nodes); self.content.appendChild(groupEl); } callback(grouped); }); } MissingFilesPage.prototype.createDeleteButton = function(groupArray) { var button = document.createElement("button"); button.textContent = "remove"; $(button).click(function() { var paths = groupArray.map(function(file) { return file.path; }); $.ajax({ url: "/api/library/removeFiles/", type: "DELETE", data: JSON.stringify({paths: paths}) }).done(function() { });; }); return button; }
Nehmulos/media-u
src/public/js/MissingFilesPage.js
JavaScript
gpl-3.0
2,077
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207, * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com. ********************************************************************************/ /** * Helper class to create ComponentForWorkflowForm based objects */ class ComponentForWorkflowFormFactory { /** * Make and return the correct ComponentForWorkflowForm based object * @param $moduleClassName string * @param $modelClassName string * @param $type string * @param $componentType string * @return TimeTriggerForWorkflowForm|TriggerForWorkflowForm|ActionForWorkflowForm * @throws NotSupportedException */ public static function makeByComponentType($moduleClassName, $modelClassName, $type, $componentType) { assert('is_string($moduleClassName)'); assert('is_string($modelClassName)'); assert('is_string($type)'); assert('is_string($componentType)'); if($componentType == ComponentForWorkflowForm::TYPE_TIME_TRIGGER) { return new TimeTriggerForWorkflowForm($moduleClassName, $modelClassName, $type); } elseif($componentType == ComponentForWorkflowForm::TYPE_TRIGGERS) { return new TriggerForWorkflowForm($moduleClassName, $modelClassName, $type); } elseif($componentType == ComponentForWorkflowForm::TYPE_ACTIONS) { return new ActionForWorkflowForm($modelClassName, $type); } elseif($componentType == ComponentForWorkflowForm::TYPE_EMAIL_MESSAGES) { return new EmailMessageForWorkflowForm($modelClassName, $type); } else { throw new NotSupportedException(); } } } ?>
deep9/zurmo
app/protected/modules/workflows/forms/ComponentForWorkflowFormFactory.php
PHP
gpl-3.0
3,188
<html> <head> <title>Converting File</title> </head> <body> <a href="http://cloud.honestrepair.net"> <img src="http://localhost/HRProprietary/converter/HRBanner.png" alt="HonestRepair"> </a> <div style="" <br> <div align="center"><p><h2>Your file has been converted</h2></div> <br> <div align="center"> <?php if ( isset( $_POST['convertDownload'] ) ) { $extension = $_POST['selected']; $file = $_POST['hiddenFile']; $userTempDirectory = ('/var/www/html/cloud/temp'); $pathname = $userTempDirectory . '/' . $file; $filename = pathinfo($pathname, PATHINFO_FILENAME); $newFile = $filename . '.' . $extension; $newPathname = $userTempDirectory . '/' . $newFile; $oldExtension = pathinfo($pathname, PATHINFO_EXTENSION); $docarray = array('txt' ,'doc', 'xls', 'xlsx', 'docx', 'rtf', 'odf', 'odt'); $imgarray = array('jpg', 'jpeg', 'bmp', 'png', 'gif'); $stub = ('http://localhost/cloud/temp/'); $newFileURL = $stub . $newFile; print $file; echo ' has sucessfully been converted to '; print $newFile; echo '. You can download this file below.'; if (in_array($oldExtension,$docarray) ) { shell_exec ("unoconv -f $extension $pathname"); } if (in_array($oldExtension,$imgarray) ) { $height = $_POST['height']; $width = $_POST['width']; $rotate = ('-rotate ' . $_POST['rotate']); $wxh = $width . 'x' . $height; if ($wxh === '0x0') { shell_exec("convert $pathname $rotate $newPathname"); } elseif (($width or $height) != '0') { shell_exec("convert -resize $wxh $rotate $pathname $newPathname"); } } } elseif ( isset( $_POST['convertCloud'] ) ) { require_once('/var/www/html/wp-load.php'); $user_ID = get_current_user_id(); $file = $_POST['hiddenFile']; $extension = $_POST['selected']; $userTempDirectory = ('/var/www/html/cloud/temp/'); $userCloudDirectory = ('/var/www/html/cloud/' . get_current_user_id() . '/'); $pathname = $userTempDirectory . $file; $oldPathname = $userTempDirectory . $file; $filename = pathinfo($pathname, PATHINFO_FILENAME); $oldExtension = pathinfo($pathname, PATHINFO_EXTENSION); $newFile = $filename . '.' . $extension; $newPathname = $userCloudDirectory . $newFile; $docarray = array('txt' ,'doc', 'xls', 'xlsx', 'docx', 'rtf', 'odf', 'odt'); $imgarray = array('jpg', 'jpeg', 'bmp', 'png', 'gif'); $stub = ('http://localhost/cloud/'); $newFileURL = $stub . $user_ID . '/' . $newFile; if ($user_ID == 0) { print $file; echo ' has sucessfully been converted to '; print $newFile; echo ' HOWEVER since you ARE NOT LOGGED IN your file was placed in a temporary Cloud. Your files are still available for download below.'; } else { print $file; echo ' has sucessfully been converted to '; print $newFile; echo '. A copy of '; print $newFile; echo ' was placed in your Cloud Drive. You can download both files below.'; } if (in_array($oldExtension,$docarray) ) { shell_exec ("unoconv -o $newPathname -f $extension $pathname"); } if (in_array($oldExtension,$imgarray) ) { $height = $_POST['height']; $width = $_POST['width']; $rotate = ('-rotate ' . $_POST['rotate']); $wxh = $width . 'x' . $height; if ($wxh === '0x0') { shell_exec("convert $pathname $rotate $newPathname"); } elseif (($width or $height) != '0') { shell_exec("convert -resize $wxh $rotate $pathname $newPathname"); } } } else { print ('No file to convert.'); } ?> </div> <div align="center"> <br> <div align="left"> <ul><a href="<?php echo $newFileURL; ?>">Click Here to download your converted file</a></ul> <ul><a href="http://localhost/cloud/temp/<?php echo $file; ?>">Click Here to download your original file</a></ul> <ul><a href="http://localhost/HRProprietary/converter/converter.php">Click Here to convert another file</a></ul> </div> </div> <br> <div> <p>Thanks for using our software! To support HonestRepair and help power it's in-house servers and future software development please like and share on social media, check out our blog, sign-up for Cloud Storage, have a website made, or schedule an appointment for honest computer repair.</p> <br><p>This software is copyright by Justin G. 2015. By downloading your converted file you agree that HonestRepair is not responsible for formatting discrepencies or errors in either of your documents. </p> </div> </body> </html>
zelon88/HRToolkit
converter/Versions/Unstable/Version-1-1-5/converter.php
PHP
gpl-3.0
4,432
/* Collisions - a real-time simulation program of colliding particles. Copyright (C) 2011 - 2015 G. Endignoux This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.txt */ #include "graph.hpp" #include "document.hpp" // Constructeur. Graph::Graph(const Configuration& config) : mLayout(new QGridLayout(this)), mZone(new GraphZone(this)), mLabelZoom(new QLabel("zoom :")), mSliderZoom(new QSlider(Qt::Horizontal)), mConfig(config), mEditMode(false) { mSliderZoom->setRange(-500, 500); // Création de l'interface graphique. mLayout->setMargin(0); mLayout->addWidget(mZone, 0, 0, 1, 2); mLayout->addWidget(mLabelZoom, 1, 0); mLayout->addWidget(mSliderZoom, 1, 1); // Connexion des signaux et slots. QObject::connect(mSliderZoom, SIGNAL(valueChanged(int)), this, SLOT(setZoom(int))); QObject::connect(mZone, SIGNAL(draw()), this, SIGNAL(draw())); QObject::connect(mZone, SIGNAL(fullDraw()), this, SIGNAL(fullDraw())); QObject::connect(mZone, SIGNAL(point(Coord<double>)), this, SLOT(pointEvent(Coord<double>))); QObject::connect(mZone, SIGNAL(hover(Coord<double>)), this, SLOT(hoverEvent(Coord<double>))); QObject::connect(mZone, SIGNAL(noHover()), this, SIGNAL(noHover())); mSliderZoom->setValue(0); } // Passe au mode édition. void Graph::setEditMode() { mEditMode = true; emit fullDraw(); } // Passe au mode simulation. void Graph::setSimulMode() { mEditMode = false; emit fullDraw(); } // Changement de zoom. void Graph::setZoom(int value) { mZone->mZoom = std::pow(10, value / 250.0); emit fullDraw(); } // Définit la liste de polygones associée. void Graph::setPolygones(QList<DrawPolygone> polygones) { mPolygones = polygones; emit fullDraw(); } // Trouve le point du quadrillage le plus proche. Coord<double> Graph::normalize(Coord<double> pt) const { int logZoom = std::floor(1.8 - std::log10(mZone->mZoom)); double space = std::pow(10, logZoom); return Coord<double>(std::round(pt.x / space) * space, std::round(pt.y / space) * space); } // Evénements de souris sur un point du graphe. void Graph::pointEvent(Coord<double> pt) { emit point(pt, this->normalize(pt)); } void Graph::hoverEvent(Coord<double> pt) { emit hover(pt, this->normalize(pt)); } // Mise à l'échelle du QPainter. void Graph::myInitPainter(QPainter& painter) const { painter.translate(mZone->width() / 2, mZone->height() / 2); painter.scale(mZone->mZoom, mZone->mZoom); painter.translate(mZone->mTranslate.x, mZone->mTranslate.y); } // Redessine la QPixmap de fond. void Graph::reinitBackground(bool force) { if (mZone->size() == mOldSize && !force) return; mOldSize = mZone->size(); mBackground = QPixmap(mZone->size()); QPainter painter(&mBackground); this->myInitPainter(painter); painter.setRenderHint(QPainter::Antialiasing); // En mode édition. if (mEditMode) { mBackground.fill(Qt::white); // Trace les polygones. for (auto& polygone : mPolygones) polygone.draw(painter); } // En mode simulation. else { mBackground.fill(mConfig.contour().color()); // Trace le contour. painter.setBrush(Qt::white); painter.setPen(mConfig.contour().color()); painter.drawPolygon(mConfig.contour().sommets().toPolygon()); // Trace les obstacles. for (auto& obstacle : mConfig.obstacles()) { painter.setBrush(obstacle.color()); painter.setPen(obstacle.color()); painter.drawPolygon(obstacle.sommets().toPolygon()); } } // Trace le quadrillage. painter.setRenderHint(QPainter::Antialiasing, false); painter.setPen(QPen()); this->drawAxes(painter); } // Dessine le quadrillage. void Graph::drawAxes(QPainter& painter) const { QTransform inverted = painter.transform().inverted(); QPointF leftTop = inverted.map(QPointF(0, 0)); QPointF rightBottom = inverted.map(QPointF(this->size().width(), this->size().height())); int logZoom = std::floor(1.8 - std::log10(mZone->mZoom)); double remain = 2 - std::log10(mZone->mZoom) - logZoom; // Détermine les nuances de gris à utiliser suivant le zoom. int _grey = 0x20 + 0x80 * (1 - remain); int _black = 0x17F - _grey; if (_black > 0xFF) _black = 0xFF; QColor grey(0x00, 0x00, 0x00, _grey); QColor black(0x00, 0x00, 0x00, _black); // Détermine les lignes minimum et maximum. double space = std::pow(10, logZoom); Coord<int> min = Coord<int>(std::floor(leftTop.x() / space), std::floor(leftTop.y() / space)); Coord<int> max = Coord<int>(std::ceil(rightBottom.x() / space), std::ceil(rightBottom.y() / space)); // Dessine les lignes de différentes couleurs. Graph::drawPartialAxes(painter, grey, min, max, space, 1); Graph::drawPartialAxes(painter, black, min, max, space, 10.0); Graph::drawPartialAxes(painter, Qt::black, min, max, space, 100.0, false); } // Dessine un maillage de lignes de même couleur. void Graph::drawPartialAxes(QPainter& painter, const QColor& color, Coord<int> min, Coord<int> max, double space, double ratio, bool skipBig) { painter.setPen(color); for (int i = std::floor(min.x / ratio) ; i <= std::ceil(max.x / ratio) ; ++i) { if (skipBig && i % 10 == 0) continue; painter.drawLine(QLineF(ratio * i * space, min.y * space, ratio * i * space, max.y * space)); } for (int i = std::floor(min.y / ratio) ; i <= std::ceil(max.y / ratio) ; ++i) { if (skipBig && i % 10 == 0) continue; painter.drawLine(QLineF(min.x * space, ratio * i * space, max.x * space, ratio * i * space)); } }
gendx/collisions
src/graphic/graph.cpp
C++
gpl-3.0
6,462
//******************************************************************************************** //* //* This file is part of Egoboo. //* //* Egoboo is free software: you can redistribute it and/or modify it //* under the terms of the GNU General Public License as published by //* the Free Software Foundation, either version 3 of the License, or //* (at your option) any later version. //* //* Egoboo is distributed in the hope that it will be useful, but //* WITHOUT ANY WARRANTY; without even the implied warranty of //* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //* General Public License for more details. //* //* You should have received a copy of the GNU General Public License //* along with Egoboo. If not, see <http://www.gnu.org/licenses/>. //* //******************************************************************************************** /// @file egolib/Platform/file_win.c /// @brief Windows-specific filesystem functions. /// @details #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> #undef NOMINMAX #include <shlobj.h> #include <shellapi.h> #include <shlwapi.h> #include "egolib/file_common.h" #include "egolib/log.h" #include "egolib/strutil.h" #include "egolib/platform.h" // this include must be the absolute last include #include "egolib/mem.h" //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- #define HAS_ATTRIBS(ATTRIBS,VAR) ((INVALID_FILE_ATTRIBUTES != (VAR)) && ( (ATTRIBS) == ( (VAR) & (ATTRIBS) ) )) //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- struct s_win32_find_context; typedef struct s_win32_find_context win32_find_context_t; //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- extern int sys_fs_init(const char *argv0); //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- // Paths that the game will deal with static char _binaryPath[MAX_PATH] = EMPTY_CSTR; static char _dataPath[MAX_PATH] = EMPTY_CSTR; static char _userPath[MAX_PATH] = EMPTY_CSTR; static char _configPath[MAX_PATH] = EMPTY_CSTR; //-------------------------------------------------------------------------------------------- // File Routines //-------------------------------------------------------------------------------------------- /// @brief Get the user data path. /// @return @a true on success, @a false on failure static bool computeUserDataPath() { // The save path goes into the user's ApplicationData directory, // according to Microsoft's standards. Will people like this, or // should I stick saves someplace easier to find, like My Documents? SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, _userPath); strncat(_userPath, SLASH_STR "Egoboo", MAX_PATH); return true; } /// @brief Compute the binary path. /// @return @a true on success, @a false on failure static bool computeBinaryPath() { GetModuleFileName(NULL, _binaryPath, MAX_PATH); PathRemoveFileSpec(_binaryPath); return true; } /// @brief Compute the basicdata path. /// @return @a true on success, @a false on failure static bool computeBasicDataPath() { char temporary[MAX_PATH]; // (1) Check for data in the working directory char workingDirectory[MAX_PATH] = EMPTY_CSTR; GetCurrentDirectory(MAX_PATH, workingDirectory); snprintf(temporary, MAX_PATH, "%s" SLASH_STR "basicdat", workingDirectory); DWORD attrib = GetFileAttributes(temporary); if (HAS_ATTRIBS(FILE_ATTRIBUTE_DIRECTORY, attrib)) { strncpy(_dataPath, workingDirectory, MAX_PATH); return true; } // IF (1) failed // THEN check for data in the binary directory snprintf(temporary, MAX_PATH, "%s" SLASH_STR "basicdat", _binaryPath); attrib = GetFileAttributes(temporary); if (HAS_ATTRIBS(FILE_ATTRIBUTE_DIRECTORY, attrib)) { strncpy(_dataPath, _binaryPath, MAX_PATH); return true; } return false; } int sys_fs_init(const char *argv0) { printf("Initializing filesystem services ..."); if (!computeUserDataPath()) { // Fatal error here, we can't find the user data path. printf(" FAILURE: could not find user data path!\n"); return 1; } if (!computeBinaryPath()) { // Fatal error here, we can't find the binary path. printf(" FAILURE: could not find binary path!\n"); return 1; } if (!computeBasicDataPath()) { // Fatal error here, we can't find the basic data path. printf(" FAILURE: could not find data path!\n"); return 1; } printf(" SUCCESS\n"); // config path is the same as the data path in win32 strncpy(_configPath, _dataPath, SDL_arraysize(_configPath)); // the log file cannot be started until there is a user data path to dump the file into // so dump this debug info to stdout printf("Game directories are:\n\tBinaries: %s\n\tData: %s\n\tUser Data: %s\n\tConfig Files: %s\n", _binaryPath, _dataPath, _userPath, _configPath); return 0; } const char *fs_getBinaryDirectory() { return _binaryPath; } const char *fs_getDataDirectory() { return _dataPath; } const char *fs_getUserDirectory() { return _userPath; } const char *fs_getConfigDirectory() { return _configPath; } int fs_fileIsDirectory(const char *filename) { if (INVALID_CSTR(filename)) { return -1; } DWORD fileAttrs = GetFileAttributes(filename); return HAS_ATTRIBS(FILE_ATTRIBUTE_DIRECTORY, fileAttrs); } // Had to revert back to prog x code to prevent import/skin bug int fs_createDirectory(const char *dirname) { if (INVALID_CSTR(dirname)) { return 1; } return (0 != CreateDirectory(dirname, NULL)) ? 0 : 1; } int fs_removeDirectory(const char *dirname) { if (INVALID_CSTR(dirname)) { return 1; } return (0 != RemoveDirectory(dirname)) ? 0 : 1; } void fs_deleteFile( const char *filename ) { if (VALID_CSTR(filename )) { DeleteFile(filename); } } bool fs_copyFile(const char *source, const char *dest) { if (INVALID_CSTR(source) || INVALID_CSTR(dest)) { return false; } return (TRUE == CopyFile(source, dest, false)); } //-------------------------------------------------------------------------------------------- // Directory Functions //-------------------------------------------------------------------------------------------- struct s_win32_find_context { WIN32_FIND_DATA wfdData; HANDLE hFind; }; const char *fs_findFirstFile(const char *searchDir, const char *searchExtension, fs_find_context_t *fs_search) { char searchSpec[MAX_PATH] = EMPTY_CSTR; if (INVALID_CSTR(searchDir) || !fs_search) { return NULL; } win32_find_context_t *pcnt = EGOBOO_NEW(win32_find_context_t); if (!pcnt) { return NULL; } fs_search->type = win32_find; fs_search->ptr.w = pcnt; size_t len = strlen(searchDir) + 1; if (C_SLASH_CHR != searchDir[len] || C_BACKSLASH_CHR != searchDir[len]) { _snprintf(searchSpec, MAX_PATH, "%s" SLASH_STR, searchDir); } else { strncpy(searchSpec, searchDir, MAX_PATH); } if (NULL != searchExtension) { _snprintf(searchSpec, MAX_PATH, "%s*.%s", searchSpec, searchExtension); } else { strncat(searchSpec, "*", MAX_PATH); } pcnt->hFind = FindFirstFile( searchSpec, &pcnt->wfdData ); if ( pcnt->hFind == INVALID_HANDLE_VALUE ) { return NULL; } return pcnt->wfdData.cFileName; } const char *fs_findNextFile(fs_find_context_t *fs_search) { if (!fs_search || win32_find != fs_search->type) { return NULL; } win32_find_context_t *pcnt = fs_search->ptr.w; if (!pcnt) { return NULL; } if (NULL == pcnt->hFind || INVALID_HANDLE_VALUE == pcnt->hFind) { return NULL; } if (!FindNextFile( pcnt->hFind, &pcnt->wfdData)) { return NULL; } return pcnt->wfdData.cFileName; } void fs_findClose(fs_find_context_t *fs_search) { if (NULL == fs_search || win32_find != fs_search->type) { return; } win32_find_context_t *pcnt = fs_search->ptr.w; if (NULL == pcnt) { return; } if (NULL != pcnt->hFind) { FindClose(pcnt->hFind); pcnt->hFind = NULL; } EGOBOO_DELETE(pcnt); BLANK_STRUCT_PTR(fs_search) } int DirGetAttrib(const char *fromdir) { return(GetFileAttributes(fromdir)); }
penguinflyer5234/egoboo
egolib/src/egolib/Platform/file_win.c
C
gpl-3.0
9,026
#TARGET_NAME = test SRC = \ normal_test.cc \ loop_test.cc \ loop_monkey_test.cc \ loop_connection_test.cc \ protocol_test.cc \ main.cc HEADERS = LINK_LIBS = rmcc OPT_LINK_FLGS = OPT_LINK_LIBS = cppunit dl OPT_LIB_DIRS = OPT_CMPL_FLGS = OPT_INCLUDE_DIRS = CLEAN_TARGETS = include ../_make_/MakeSub.def
roma/roma-php-client
src/rmcc_test/Makefile
Makefile
gpl-3.0
324
<?php class com_wiris_quizzes_impl_HTMLGui { public function __construct($lang) { if(!php_Boot::$skip_constructor) { $this->lang = (($lang !== null) ? $lang : "en"); $this->t = com_wiris_quizzes_impl_Translator::getInstance($this->lang); }} public function filterEmbeddedAnswersHTML($html, $mode, $q, $qi) { $regexp = new EReg("<(input|img)[^>]*(wirisauthoringfield|wirisembeddedauthoringfield|wirisanswerfield)[^>]*(/>|>[^<]*</(input|img)>)", "gm"); $html = $regexp->replace($html, "<<wirisembeddedanswerfield>>"); $i = 0; $start = 0; $pos = null; $sb = new StringBuf(); while(($pos = _hx_index_of($html, "<<wirisembeddedanswerfield>>", $start)) !== -1) { $sb->add(_hx_substr($html, $start, $pos - $start)); if($mode === com_wiris_quizzes_api_ui_QuizzesUIConstants::$AUTHORING) { $value = $q->getCorrectAnswer($i); if(com_wiris_quizzes_impl_MathContent::getMathType($value) === com_wiris_quizzes_impl_MathContent::$TYPE_MATHML) { $src = com_wiris_quizzes_impl_QuizzesBuilderImpl::getInstance()->getConfiguration()->get(com_wiris_quizzes_api_ConfigurationKeys::$PROXY_URL) . "?service=render&mml=" . rawurlencode($value) . "&centerBaseline=false"; $sb->add("<img class=\"wirisembeddedauthoringfield\" src=\"" . $src . "\" data-answer-index=\"" . _hx_string_rec($i, "") . "\" />"); unset($src); } else { $sb->add("<input type=\"text\" class=\"wirisembeddedauthoringfield\" value=\"" . com_wiris_util_xml_WXmlUtils::htmlEscape($value) . "\" data-answer-index=\"" . _hx_string_rec($i, "") . "\" />"); } unset($value); } else { if($mode === com_wiris_quizzes_api_ui_QuizzesUIConstants::$DELIVERY) { $sb->add("<input type=\"hidden\" class=\"wirisanswerfield\" value=\"\" />"); } else { if($mode === com_wiris_quizzes_api_ui_QuizzesUIConstants::$REVIEW) { $value = $qi->getStudentAnswer($i); if($value === null) { $value = ""; } $sb->add("<input type=\"hidden\" class=\"wirisanswerfield wirisembeddedfeedback wirisassertionsfeedback wiriscorrectfeedback\" value=\"" . com_wiris_util_xml_WXmlUtils::htmlEscape($value) . "\" />"); unset($value); } } } $i++; $start = $pos + 28; } $sb->add(_hx_substr($html, $start, null)); return $sb->b; } public function printMathML($h, $mathml) { $safeMathML = com_wiris_quizzes_impl_HTMLTools::encodeUnicodeChars($mathml); $src = com_wiris_quizzes_impl_QuizzesBuilderImpl::getInstance()->getConfiguration()->get(com_wiris_quizzes_api_ConfigurationKeys::$PROXY_URL) . "?service=render&mml=" . rawurlencode($safeMathML); $h->openclose("img", new _hx_array(array(new _hx_array(array("src", $src)), new _hx_array(array("align", "middle")), new _hx_array(array("class", "wirismathml"))))); } public function printMath($h, $math) { if(com_wiris_quizzes_impl_MathContent::getMathType($math) === com_wiris_quizzes_impl_MathContent::$TYPE_MATHML) { $tools = new com_wiris_quizzes_impl_HTMLTools(); if($tools->isTokensMathML($math)) { $h->text($tools->mathMLToText($math)); } else { $this->printMathML($h, $math); } } else { $h->text($math); } } public function printLocalData($h, $q, $unique, $conf) { $h->openDivClass(null, "wirisfieldsetwrapper"); $h->openFieldset("wirislocaldatafieldset" . _hx_string_rec($unique, ""), $this->t->t("inputmethod"), "wirismainfieldset"); $anchor = (($conf->optAuxiliarCas && !$conf->optOpenAnswer) ? "#auxiliar-cas" : ""); $h->help("wirisinputmethodhelp" . _hx_string_rec($unique, ""), "http://www.wiris.com/quizzes/docs/moodle/manual/correct-answer" . $anchor, $this->t->t("manual")); $id = null; if($conf->optOpenAnswer) { $h->openDivClass("wirisinputfielddiv" . _hx_string_rec($unique, ""), "wirissecondaryfieldset"); $h->openUl("wirisinputfieldul", "wirisul"); $id = "wirislocaldata" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_LocalData::$KEY_OPENANSWER_INPUT_FIELD . "]"; if($conf->optAnswerFieldInlineEditor) { $h->openLi(); $h->input("radio", $id . "[0]", $id, com_wiris_quizzes_impl_LocalData::$VALUE_OPENANSWER_INPUT_FIELD_INLINE_EDITOR, null, null); $h->label($this->t->t("answerinputinlineeditor"), $id . "[0]", null); $h->close(); } if($conf->optAnswerFieldPopupEditor) { $h->openLi(); $h->input("radio", $id . "[1]", $id, com_wiris_quizzes_impl_LocalData::$VALUE_OPENANSWER_INPUT_FIELD_POPUP_EDITOR, null, null); $h->label($this->t->t("answerinputpopupeditor"), $id . "[1]", null); $h->close(); } if($conf->optAnswerFieldPlainText) { $h->openLi(); $h->input("radio", $id . "[2]", $id, com_wiris_quizzes_impl_LocalData::$VALUE_OPENANSWER_INPUT_FIELD_PLAIN_TEXT, null, null); $h->label($this->t->t("answerinputplaintext"), $id . "[2]", null); $h->close(); } $handEnabled = com_wiris_quizzes_impl_QuizzesBuilderImpl::getInstance()->getConfiguration()->get(com_wiris_quizzes_api_ConfigurationKeys::$HAND_ENABLED); if(strtolower($handEnabled) === "true") { if($conf->optAnswerFieldInlineHand) { $h->openLi(); $h->input("radio", $id . "[3]", $id, com_wiris_quizzes_impl_LocalData::$VALUE_OPENANSWER_INPUT_FIELD_INLINE_HAND, null, null); $h->label($this->t->t("answerinputinlinehand"), $id . "[3]", null); $h->close(); } } $h->close(); $h->close(); if($conf->optCompoundAnswer) { $h->openDivClass("wiriscompoundanswerdiv" . _hx_string_rec($unique, ""), "wirissecondaryfieldset"); $id = "wirislocaldata" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_LocalData::$KEY_OPENANSWER_COMPOUND_ANSWER . "]"; $h->input("checkbox", $id, "", com_wiris_quizzes_impl_LocalData::$VALUE_OPENANSWER_COMPOUND_ANSWER_TRUE, null, null); $h->label($this->t->t("compoundanswer"), $id, null); $h->openDivClass("wiriscompoundanswergradediv" . _hx_string_rec($unique, ""), "wiristerciaryfieldset"); $h->openDiv("wiriscompoundanswergradeand" . _hx_string_rec($unique, "")); $id = "wirislocaldata" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_LocalData::$KEY_OPENANSWER_COMPOUND_ANSWER_GRADE . "][and]"; $h->input("radio", $id, "wiriscompoundanswergrade", com_wiris_quizzes_impl_LocalData::$VALUE_OPENANSWER_COMPOUND_ANSWER_GRADE_AND, null, null); $h->label($this->t->t("allanswerscorrect"), $id, null); $h->close(); $h->openDiv("wiriscompoundanswergradedistribute" . _hx_string_rec($unique, "")); $id = "wirislocaldata" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_LocalData::$KEY_OPENANSWER_COMPOUND_ANSWER_GRADE . "][distribute]"; $h->input("radio", $id, "wiriscompoundanswergrade", com_wiris_quizzes_impl_LocalData::$VALUE_OPENANSWER_COMPOUND_ANSWER_GRADE_DISTRIBUTE, null, null); $h->label($this->t->t("distributegrade"), $id, null); $id = "wirislocaldata" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_LocalData::$KEY_OPENANSWER_COMPOUND_ANSWER_GRADE_DISTRIBUTION . "]"; $h->input("text", $id, "", "", $this->t->t("gradedistribution"), "wirisadditionalinput"); $h->close(); $h->close(); $h->close(); } } if($conf->optAuxiliarCas) { $h->openDivClass("wirisauxiliarcasdiv" . _hx_string_rec($unique, ""), "wirissecondaryfieldset"); $id = "wirislocaldata" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_LocalData::$KEY_SHOW_CAS . "]"; if(!$conf->optAuxiliarCasReplaceEditor) { $h->input("checkbox", $id, "", com_wiris_quizzes_impl_LocalData::$VALUE_SHOW_CAS_ADD, null, null); } $h->label($this->t->t("showauxiliarcas"), $id, null); if($conf->optAuxiliarCasReplaceEditor) { $h->text(" "); $h->select($id, null, new _hx_array(array(new _hx_array(array(com_wiris_quizzes_impl_LocalData::$VALUE_SHOW_CAS_FALSE, $this->t->t("no"))), new _hx_array(array(com_wiris_quizzes_impl_LocalData::$VALUE_SHOW_CAS_ADD, $this->t->t("add"))), new _hx_array(array(com_wiris_quizzes_impl_LocalData::$VALUE_SHOW_CAS_REPLACE_INPUT, $this->t->t("replaceeditor")))))); } $h->text(" "); $h->jsComponent("wirisinitialcontentbutton" . _hx_string_rec($unique, ""), "JsInitialCasInput", $q->getLocalData(com_wiris_quizzes_impl_LocalData::$KEY_CAS_INITIAL_SESSION)); $h->close(); } $h->close(); $h->close(); } public function getLangFromCasSession($session) { $start = _hx_index_of($session, "<session", null); if($start === -1) { return null; } $end = _hx_index_of($session, ">", $start + 1); $start = _hx_index_of($session, "lang", $start); if($start === -1 || $start > $end) { return null; } $start = _hx_index_of($session, "\"", $start) + 1; return _hx_substr($session, $start, 2); } public function printAssertionFeedback($h, $c, $q) { $gradeClass = $this->getGradeClass($c->value); $typeClass = _hx_substr($c->assertion, 0, _hx_index_of($c->assertion, "_", null)); $h->openSpan(null, $gradeClass . " " . $typeClass); $feedback = $this->t->t($c->assertion . "_correct_feedback"); $index = $q->getAssertionIndex($c->assertion, $c->getCorrectAnswer(), $c->getAnswer()); if($index !== -1) { $a = $q->assertions[$index]; if($a->parameters !== null) { $i = null; { $_g1 = 0; $_g = $a->parameters->length; while($_g1 < $_g) { $i1 = $_g1++; $name = _hx_array_get($a->parameters, $i1)->name; $value = _hx_array_get($a->parameters, $i1)->content; $feedback = str_replace("\${" . $name . "}", $value, $feedback); unset($value,$name,$i1); } } } } $h->text($feedback); $h->close(); } public function showAssertionFeedback($check) { if($check->getAssertionName() === com_wiris_quizzes_impl_Assertion::$EQUIVALENT_ALL) { return false; } if(com_wiris_quizzes_impl_Assertion::isSyntacticName($check->getAssertionName()) && $check->value === 1.0) { return false; } return true; } public function printAnswerAssertionsFeedback($h, $correctAnswer, $userAnswer, $q, $qi) { $h->openUl(null, "wiristestassertionslist"); $checks = $qi->getMatchingChecks($correctAnswer, $userAnswer); $j = null; { $_g1 = 0; $_g = $checks->length; while($_g1 < $_g) { $j1 = $_g1++; $check = $checks[$j1]; if($this->showAssertionFeedback($check)) { $h->openLi(); $this->printAssertionFeedback($h, $check, $q); $h->close(); } unset($j1,$check); } } $h->close(); } public function printCorrectAnswerFeedback($h, $correctAnswer, $userAnswer, $q, $qi) { $grade = $qi->getAnswerGrade($correctAnswer, $userAnswer, $q); $h->openSpan(null, "wiriscorrectanswerfeedback"); if(_hx_equal($grade, 1)) { $h->openSpan(null, "wiriscorrect"); $h->text($this->t->t("correct")); $h->close(); } else { if(_hx_equal($grade, 0)) { $h->openSpan(null, "wirisincorrect"); $h->text($this->t->t("incorrect")); $h->close(); } else { $h->openSpan(null, "wirispartiallycorrect"); $h->text(_hx_string_rec(Math::round($grade * 100), "") . "% " . $this->t->t("partiallycorrect")); $h->close(); } $h->text(" " . $this->t->t("thecorrectansweris") . " "); $this->printMath($h, $q->getCorrectAnswer($correctAnswer)); $h->text("."); } $h->close(); } public function getAnswerFeedbackHtml($correctAnswer, $userAnswer, $q, $qi, $conf) { $h = new com_wiris_quizzes_impl_HTML(); if($conf->showCorrectAnswerFeedback) { $this->printCorrectAnswerFeedback($h, $correctAnswer, $userAnswer, $q, $qi); } if($conf->showAssertionsFeedback) { $this->printAnswerAssertionsFeedback($h, $correctAnswer, $userAnswer, $q, $qi); } return $h->getString(); } public function getWirisTestDynamic($q, $qi, $correctAnswer, $userAnswer, $unique) { $h = new com_wiris_quizzes_impl_HTML(); $hasCorrectAnswer = $q->correctAnswers !== null && $correctAnswer < $q->correctAnswers->length; $h->openDivClass("wiristestresult" . _hx_string_rec($unique, ""), "wiristestresult"); $h->openDivClass(null, "wirisfieldsetwrapper"); $h->openFieldset("wiristestvalidationfieldset" . _hx_string_rec($unique, ""), $this->t->t("validation"), "wirismainfieldset"); if($q->assertions !== null && $q->assertions->length > 0 && $qi->hasEvaluation()) { $h->openDivClass("wiristestgrade" . _hx_string_rec($unique, ""), "wiristestgrade"); $grade = $qi->getAnswerGrade($correctAnswer, $userAnswer, $q); if($grade === 1.0) { $h->openSpan("wiristestgradetext" . _hx_string_rec($unique, ""), "wiristestgradetext wiriscorrect"); $h->text($this->t->t("correct")); $h->close(); } else { if($grade === 0.0) { $h->openSpan("wiristestgradetext" . _hx_string_rec($unique, ""), "wiristestgradetext wirisincorrect"); $h->text($this->t->t("incorrect")); $h->close(); } else { $h->openSpan("wiristestgradetext" . _hx_string_rec($unique, ""), "wiristestgradetext wirispartiallycorrect"); $h->text(_hx_string_rec(Math::round($grade * 100), "") . "% "); $h->text($this->t->t("partiallycorrect")); $h->close(); } } $h->close(); $h->openDivClass("wiristestassertions" . _hx_string_rec($unique, ""), "wiristestassertions"); $h->openDivClass("wiristestassertionslistwrapper" . _hx_string_rec($unique, ""), "wiristestassertionslistwrapper"); $this->printAnswerAssertionsFeedback($h, $correctAnswer, $userAnswer, $q, $qi); $h->close(); $h->close(); } else { $h->text($this->t->t("clicktesttoevaluate")); } $h->close(); $h->close(); $h->close(); $h->openDivClass("wiristestcorrectanswer" . _hx_string_rec($unique, "") . "[" . _hx_string_rec($correctAnswer, "") . "]", "wiristestcorrectanswer"); $h->openDivClass(null, "wirisfieldsetwrapper"); $h->openFieldset("wiristestcorrectanswerfieldset" . _hx_string_rec($unique, ""), $this->t->t("correctanswer"), "wirismainfieldset"); if($hasCorrectAnswer) { $content = _hx_array_get($q->correctAnswers, $correctAnswer)->content; if(com_wiris_quizzes_impl_MathContent::getMathType($content) === com_wiris_quizzes_impl_MathContent::$TYPE_MATHML) { if($qi->hasVariables()) { $content = $qi->expandVariablesMathML($content); } $h->open("span", new _hx_array(array(new _hx_array(array("class", "mathml"))))); $this->printMathML($h, $content); $h->close(); } else { if($qi->hasVariables()) { $content = $qi->expandVariablesText($content); } $h->text($content); } } $h->close(); $h->close(); $h->close(); return $h->getString(); } public function printTester($h, $q, $qi, $correctAnswer, $userAnswer, $unique) { if($q === null) { $q = new com_wiris_quizzes_impl_QuestionImpl(); } if($qi === null) { $qi = new com_wiris_quizzes_impl_QuestionInstanceImpl(); } $hasUserAnswer = $qi->userData !== null && $qi->userData->answers !== null && $qi->userData->answers->length > $userAnswer; $h->openDivClass("wiristestwrapper" . _hx_string_rec($unique, ""), "wiristestwrapper"); $h->openDivClass("wiristestanswerwrapper" . _hx_string_rec($unique, ""), "wiristestanswerwrapper"); $h->jsComponent("wirisanswer" . _hx_string_rec($unique, "") . "[" . _hx_string_rec($userAnswer, "") . "]", "JsInput", com_wiris_quizzes_impl_HTMLGui_0($this, $correctAnswer, $h, $hasUserAnswer, $q, $qi, $unique, $userAnswer)); $h->close(); $h->openDivClass("wiristestbuttons" . _hx_string_rec($unique, ""), "wiristestbuttons"); $h->input("button", "wiristestbutton" . _hx_string_rec($unique, ""), null, $this->t->t("test"), null, "wirisbutton"); $h->input("button", "wirisrestartbutton" . _hx_string_rec($unique, ""), null, $this->t->t("start"), null, "wirisbutton"); $h->close(); $h->openDivClass("wiristestdynamic" . _hx_string_rec($unique, ""), "wiristestdynamic"); $h->raw($this->getWirisTestDynamic($q, $qi, $correctAnswer, $userAnswer, $unique)); $h->close(); $h->close(); } public function printAssertionsControls($h, $q, $correctAnswer, $userAnswer, $unique, $conf) { $answers = "[" . _hx_string_rec($correctAnswer, "") . "][" . _hx_string_rec($userAnswer, "") . "]"; $h->openDiv("wirisassertioncontrols" . _hx_string_rec($unique, "")); $h->openDivClass(null, "wirisfieldsetwrapper"); $h->openFieldset("wiriscomparisonfieldset" . _hx_string_rec($unique, "") . $answers, $this->t->t("comparisonwithstudentanswer"), "wirismainfieldset wiriscomparisonfieldset"); $h->help("wiriscomparisonhelp" . _hx_string_rec($unique, ""), "http://www.wiris.com/quizzes/docs/moodle/manual/validation#comparison", $this->t->t("manual")); $h->openDivClass("wiristolerance" . _hx_string_rec($unique, ""), "wiristolerance"); $idtol = "wirisoption" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_TOLERANCE . "]"; $h->label($this->t->t("tolerancedigits") . ":", $idtol, "wirisleftlabel2"); $h->text(" "); $h->input("text", $idtol, "", null, null, null); $idRelTol = "wirisoption" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_RELATIVE_TOLERANCE . "]"; $h->input("checkbox", $idRelTol, "", null, null, null); $h->label($this->t->t("relative"), $idRelTol, null); $h->close(); $h->openUl("wiriscomparison" . _hx_string_rec($unique, "") . $answers, "wirisul"); $i = null; $idassertion = null; { $_g1 = 0; $_g = com_wiris_quizzes_impl_Assertion::$equivalent->length; while($_g1 < $_g) { $i1 = $_g1++; if(!$conf->optGradingFunction && com_wiris_quizzes_impl_Assertion::$equivalent[$i1] === com_wiris_quizzes_impl_Assertion::$EQUIVALENT_FUNCTION) { continue; } $h->openLiClass("wiris" . com_wiris_quizzes_impl_Assertion::$equivalent[$i1]); $idassertion = "wirisassertion" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$equivalent[$i1] . "]" . $answers; $h->input("radio", $idassertion, "wirisradiocomparison" . _hx_string_rec($unique, "") . $answers, null, null, null); $h->label($this->t->t(com_wiris_quizzes_impl_Assertion::$equivalent[$i1]), $idassertion, null); if(com_wiris_quizzes_impl_Assertion::$equivalent[$i1] === com_wiris_quizzes_impl_Assertion::$EQUIVALENT_FUNCTION) { $h->text(" "); $h->input("text", "wirisassertionparam" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$EQUIVALENT_FUNCTION . "][name]" . $answers, "", "", null, null); $idNotEvaluate = "wirisassertionparam" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$EQUIVALENT_FUNCTION . "][notevaluate]" . $answers; $h->input("checkbox", $idNotEvaluate, null, null, null, null); $h->label($this->t->t("notevaluate"), $idNotEvaluate, "wirissmalllabel"); unset($idNotEvaluate); } $h->close(); unset($i1); } } $h->openLiClass("wiriscomparesets"); $comparesetsid = "wirisassertionparam" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$EQUIVALENT_SYMBOLIC . "," . com_wiris_quizzes_impl_Assertion::$EQUIVALENT_LITERAL . "][comparesets]" . $answers; $h->input("checkbox", $comparesetsid, null, null, null, null); $h->text(" "); $h->label($this->t->t("comparesets"), $comparesetsid, null); $h->close(); $h->openLiClass("wirisusecase"); $usecaseid = "wirisassertionparam" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$EQUIVALENT_LITERAL . "][usecase]" . $answers; $h->input("checkbox", $usecaseid, null, null, null, null); $h->text(" "); $h->label($this->t->t("usecase"), $usecaseid, null); $h->close(); $h->openLiClass("wirisusespaces"); $usespacesid = "wirisassertionparam" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$EQUIVALENT_LITERAL . "][usespaces]" . $answers; $h->input("checkbox", $usespacesid, null, null, null, null); $h->text(" "); $h->label($this->t->t("usespaces"), $usespacesid, null); $h->close(); $h->close(); $h->close(); $h->close(); $h->openDivClass(null, "wirisfieldsetwrapper"); $h->openFieldset("wirisadditionalchecksfieldset" . _hx_string_rec($unique, "") . $answers, $this->t->t("additionalproperties"), "wirismainfieldset wirisadditionalchecksfieldset"); $h->help("wirisadditionalcheckshelp" . _hx_string_rec($unique, ""), "http://www.wiris.com/quizzes/docs/moodle/manual/validation#properties", $this->t->t("manual")); $h->openDivClass("wirisstructurediv" . _hx_string_rec($unique, "") . $answers, "wirissecondaryfieldset"); $h->openDivClass("wirisstructuredivlegend" . _hx_string_rec($unique, "") . $answers, "wirissecondaryfieldsetlegend"); $h->text($this->t->t("structure") . ":"); $h->close(); $options = new _hx_array(array()); $options[0] = new _hx_array(array()); $options[0][0] = ""; $options[0][1] = $this->t->t("none"); { $_g1 = 0; $_g = com_wiris_quizzes_impl_Assertion::$structure->length; while($_g1 < $_g) { $i1 = $_g1++; $options[$i1 + 1] = new _hx_array(array()); $options[$i1 + 1][0] = com_wiris_quizzes_impl_Assertion::$structure[$i1]; $options[$i1 + 1][1] = $this->t->t(com_wiris_quizzes_impl_Assertion::$structure[$i1]); unset($i1); } } $h->select("wirisstructureselect" . _hx_string_rec($unique, "") . $answers, "", $options); $h->close(); $h->openDivClass("wirismorediv" . _hx_string_rec($unique, "") . $answers, "wirissecondaryfieldset"); $h->text($this->t->t("more") . ":"); $h->openUl("wirismore" . _hx_string_rec($unique, "") . $answers, "wirisul"); { $_g1 = 0; $_g = com_wiris_quizzes_impl_Assertion::$checks->length; while($_g1 < $_g) { $i1 = $_g1++; $h->openLi(); $idassertion = "wirisassertion" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$checks[$i1] . "]" . $answers; $h->input("checkbox", $idassertion, null, null, null, null); $h->label($this->t->t(com_wiris_quizzes_impl_Assertion::$checks[$i1]), $idassertion, null); $parameters = com_wiris_quizzes_impl_Assertion::getParameterNames(com_wiris_quizzes_impl_Assertion::$checks[$i1]); if($parameters !== null) { $j = null; { $_g3 = 0; $_g2 = $parameters->length; while($_g3 < $_g2) { $j1 = $_g3++; $h->text(" "); $h->input("text", "wirisassertionparam" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$checks[$i1] . "][" . $parameters[$j1] . "]" . $answers, null, null, null, null); unset($j1); } unset($_g3,$_g2); } unset($j); } $h->close(); unset($parameters,$i1); } } $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); } public function printAssertionsSummary($h, $q, $index, $unique, $conf) { $syntax = null; $equivalent = null; $inputMethod = null; $properties = new _hx_array(array()); $showInputMethod = false; $showSyntax = false; $showComparison = false; $showProperties = false; $showAlgorithm = false; $showOptions = false; if(com_wiris_quizzes_impl_LocalData::$VALUE_OPENANSWER_INPUT_FIELD_INLINE_HAND === $q->getLocalData(com_wiris_quizzes_impl_LocalData::$KEY_OPENANSWER_INPUT_FIELD)) { $showInputMethod = true; $inputMethod = $this->t->t("answerinputinlinehand"); } if($q->assertions !== null) { $i = null; { $_g1 = 0; $_g = $q->assertions->length; while($_g1 < $_g) { $i1 = $_g1++; $a = $q->assertions[$i1]; if($a->isSyntactic()) { $text = $this->getAssertionString($a, 80); if(!($text === $this->t->t(com_wiris_quizzes_impl_Assertion::$SYNTAX_EXPRESSION))) { $syntax = $text; $showSyntax = true; } unset($text); } else { if($index === $a->getCorrectAnswer()) { $text = $this->getAssertionString($a, 80); if(StringTools::startsWith($a->name, "equivalent_")) { if(!($text === $this->t->t(com_wiris_quizzes_impl_Assertion::$EQUIVALENT_SYMBOLIC))) { $equivalent = $text; $showComparison = true; } } else { $properties->push($text); $showProperties = true; } unset($text); } } unset($i1,$a); } } } $options = ""; $tolerance = $q->getOption(com_wiris_quizzes_api_QuizzesConstants::$OPTION_TOLERANCE); if(!($tolerance === $q->defaultOption(com_wiris_quizzes_api_QuizzesConstants::$OPTION_TOLERANCE))) { $options = $this->t->t("tolerancedigits") . ": " . _hx_substr($tolerance, 5, strlen($tolerance) - 6); $showOptions = true; } $relative = $q->getOption(com_wiris_quizzes_api_QuizzesConstants::$OPTION_RELATIVE_TOLERANCE); if(!($relative === $q->defaultOption(com_wiris_quizzes_api_QuizzesConstants::$OPTION_RELATIVE_TOLERANCE))) { if(strlen($options) > 0) { $options .= ", "; } $options .= $this->t->t("absolutetolerance"); $showOptions = true; } $showAlgorithm = $q->wirisCasSession !== null && strlen($q->wirisCasSession) > 0; if($showSyntax || $showComparison || $showProperties || $showAlgorithm || $showOptions || $showInputMethod) { $h->openDivClass(null, "wirisfieldsetwrapper"); $h->openFieldset("validationandvariables" . _hx_string_rec($unique, ""), $this->t->t("validationandvariables"), "wirisfieldsetvalidationandvariables"); $h->help("wirisvalidationandvariableshelp" . _hx_string_rec($unique, ""), "http://www.wiris.com/quizzes/docs/moodle/manual/short-answer#vav", $this->t->t("manual")); $h->openDl("wirisassertionsummarydl" . _hx_string_rec($unique, ""), "wirisassertionsummarydl"); if($showInputMethod) { $h->dt($this->t->t("inputmethod")); $h->dd($inputMethod); } if($showSyntax) { $h->dt($this->t->t("allowedinput")); $h->dd($syntax); } if($showComparison || $showOptions) { $h->dt($this->t->t("comparison")); $cmp = ""; if($showComparison) { $cmp .= $equivalent; } if($showOptions) { if(strlen($cmp) > 0) { $cmp .= ", "; } $cmp .= $options; } $h->dd($cmp); } if($showProperties) { $h->dt($this->t->t("properties")); $prop = new StringBuf(); $i = null; { $_g1 = 0; $_g = $properties->length; while($_g1 < $_g) { $i1 = $_g1++; if($i1 > 0) { $prop->add(", "); } $prop->add($properties[$i1]); unset($i1); } } $h->dd($prop->b); } if($showAlgorithm) { $h->dt($this->t->t("variables")); $variables = $this->t->t("hasalgorithm"); if(!($q->getOption(com_wiris_quizzes_api_QuizzesConstants::$OPTION_PRECISION) === $q->defaultOption(com_wiris_quizzes_api_QuizzesConstants::$OPTION_PRECISION))) { $variables .= ", " . $this->t->t("precision") . ": " . $q->getOption(com_wiris_quizzes_api_QuizzesConstants::$OPTION_PRECISION); } $h->dd($variables); } $h->close(); $h->close(); $h->close(); } } public function shortenText($text, $chars) { if(strlen($text) > $chars) { $text = _hx_substr($text, 0, $chars - 3); $n = strlen($text) - 1; $c = _hx_char_code_at($text, $n); while($c === 32 || $c === 44 || $c === 46) { $text = _hx_substr($text, 0, $n); $n--; $c = _hx_char_code_at($text, $n); } $text .= "..."; } return $text; } public function getAssertionString($a, $chars) { $text = $this->t->t($a->name); if($a->parameters !== null && $a->parameters->length > 0) { $sb = new StringBuf(); $i = null; $count = 0; { $_g1 = 0; $_g = $a->parameters->length; while($_g1 < $_g) { $i1 = $_g1++; $ap = $a->parameters[$i1]; if($ap->name === com_wiris_quizzes_impl_Assertion::$PARAM_ORDER_MATTERS && !($ap->content === "true")) { if($count > 0) { $sb->add("; "); } $sb->add($this->t->t("comparesets")); $count++; } else { if($ap->name === com_wiris_quizzes_impl_Assertion::$PARAM_REPETITION_MATTERS) { } else { if($ap->content === "true") { if($count > 0) { $sb->add("; "); } $sb->add($this->t->t($ap->name)); $count++; } else { if($ap->content === "false") { } else { if($ap->content === com_wiris_quizzes_impl_Assertion::getParameterDefaultValue($a->name, $ap->name)) { } else { if($count > 0) { $sb->add("; "); } $sb->add($this->shortenText($ap->content, Math::floor(Math::round($chars / 3.0)))); $count++; } } } } } unset($i1,$ap); } } if($count > 0) { $parameters = $this->shortenText($sb->b, $chars - strlen($text) - 3); $text .= " (" . $parameters . ")"; } } return $text; } public function getWirisCasApplet($id, $lang) { $caslangs = $this->getWirisCasLanguages(); $caslang = "en"; $i = null; { $_g1 = 0; $_g = $caslangs->length; while($_g1 < $_g) { $i1 = $_g1++; if($caslangs[$i1][0] === $lang) { $caslang = $lang; } unset($i1); } } $h = new com_wiris_quizzes_impl_HTML(); $h->open("applet", new _hx_array(array(new _hx_array(array("id", $id)), new _hx_array(array("name", "wiriscas")), new _hx_array(array("codebase", com_wiris_quizzes_impl_QuizzesBuilderImpl::getInstance()->getConfiguration()->get(com_wiris_quizzes_api_ConfigurationKeys::$SERVICE_URL) . "/wiris-codebase")), new _hx_array(array("code", "WirisApplet_net_" . $caslang)), new _hx_array(array("archive", "wrs_net_" . $caslang . ".jar")), new _hx_array(array("height", "100%")), new _hx_array(array("width", "100%"))))); $h->openclose("param", new _hx_array(array(new _hx_array(array("name", "command")), new _hx_array(array("value", "false"))))); $h->openclose("param", new _hx_array(array(new _hx_array(array("name", "commands")), new _hx_array(array("value", "false"))))); $h->openclose("param", new _hx_array(array(new _hx_array(array("name", "interface")), new _hx_array(array("value", "false"))))); $h->close(); return $h->getString(); } public function printOutputControls($h, $unique) { $h->openDiv("wirisoutputcontrols" . _hx_string_rec($unique, "")); $h->openDivClass(null, "wirisfieldsetwrapper"); $h->openFieldset("wirisoutputcontrolsfieldset" . _hx_string_rec($unique, ""), $this->t->t("outputoptions"), "wirismainfieldset"); $h->help("wirisoutputcontrolshelp" . _hx_string_rec($unique, ""), "http://www.wiris.com/quizzes/docs/moodle/manual/variables", $this->t->t("manual")); $h->openTable("wirisoutputcontrolslist" . _hx_string_rec($unique, ""), "wirisoutputcontrolslist"); $id = null; $h->openTr(null); $h->openTd("wirisleftlabellist"); $id = "wirisoption" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_PRECISION . "]"; $h->label($this->t->t(com_wiris_quizzes_api_QuizzesConstants::$OPTION_PRECISION), $id, "wirisleftlabel"); $h->close(); $h->openTd(null); $h->input("text", $id, null, null, null, "wirissmalltextfield"); $h->openSpan("wirisfloatingexample" . _hx_string_rec($unique, ""), "wirisfloatingexample"); $h->text($this->t->t("example") . ":"); $h->openSpan("wirisfloatingexamplewrapper" . _hx_string_rec($unique, ""), null); $h->close(); $h->close(); $h->close(); $h->close(); $h->openTr(null); $h->openTd("wirisleftlabellist"); $id = "wirisoption" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_FLOAT_FORMAT . "]"; $h->label($this->t->t("notation"), $id, "wirisleftlabel"); $h->close(); $h->openTd(null); $h->select($id, null, new _hx_array(array(new _hx_array(array("mg", $this->t->t("auto"))), new _hx_array(array("mr", $this->t->t("floatingDecimal"))), new _hx_array(array("f", $this->t->t("fixedDecimal"))), new _hx_array(array("me", $this->t->t("scientific")))))); $id = "wirisoption" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_DECIMAL_SEPARATOR . "]"; $h->label($this->t->t("decimalSeparator"), null, "wirisleftlabel wirissecondlabel"); $h->select($id, null, new _hx_array(array(new _hx_array(array(".", $this->t->t("point"))), new _hx_array(array(",", $this->t->t("comma")))))); $id = "wirisoption" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_DIGIT_GROUP_SEPARATOR . "]"; $h->label($this->t->t("thousandsSeparator"), null, "wirisleftlabel wirissecondlabel"); $h->select($id, null, new _hx_array(array(new _hx_array(array(".", $this->t->t("point"))), new _hx_array(array(",", $this->t->t("comma"))), new _hx_array(array(" ", $this->t->t("space"))), new _hx_array(array("", $this->t->t("None")))))); $h->close(); $h->close(); $h->openTr("wirisrowthinspace"); $h->openTd("wirisleftlabellist"); $id = "wirisoptionpart" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_TIMES_OPERATOR . "]"; $h->label($this->t->t(com_wiris_quizzes_api_QuizzesConstants::$OPTION_TIMES_OPERATOR), null, "wirisleftlabel"); $h->close(); $h->openTd(null); $h->openSpan(null, "wirishorizontalparam"); $h->input("radio", $id . "[0]", $id, com_wiris_quizzes_impl_HTMLGui_1($this, $h, $id, $unique), com_wiris_quizzes_impl_HTMLGui_2($this, $h, $id, $unique), null); $h->label("a" . com_wiris_quizzes_impl_HTMLGui_3($this, $h, $id, $unique) . "b", $id . "[0]", null); $h->close(); $h->openSpan(null, "wirishorizontalparam"); $h->input("radio", $id . "[1]", $id, com_wiris_quizzes_impl_HTMLGui_4($this, $h, $id, $unique), com_wiris_quizzes_impl_HTMLGui_5($this, $h, $id, $unique), null); $h->label("a" . com_wiris_quizzes_impl_HTMLGui_6($this, $h, $id, $unique) . "b", $id . "[1]", null); $h->close(); $id = "wirisoption" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_IMPLICIT_TIMES_OPERATOR . "]"; $h->input("checkbox", $id, null, "true", $this->t->t(com_wiris_quizzes_api_QuizzesConstants::$OPTION_IMPLICIT_TIMES_OPERATOR), null); $h->label($this->t->t("invisible"), $id, null); $h->close(); $h->close(); $h->openTr(null); $h->openTd("wirisleftlabellist"); $id = "wirisoptionpart" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_api_QuizzesConstants::$OPTION_IMAGINARY_UNIT . "]"; $h->label($this->t->t(com_wiris_quizzes_api_QuizzesConstants::$OPTION_IMAGINARY_UNIT), null, "wirisleftlabel"); $h->close(); $h->openTd(null); $h->openSpan(null, "wirishorizontalparam"); $h->input("radio", $id . "[0]", $id, "i", "i", null); $h->label("i", $id . "[0]", null); $h->close(); $h->openSpan(null, "wirishorizontalparam"); $h->input("radio", $id . "[1]", $id, "j", "j", null); $h->label("j", $id . "[1]", null); $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); } public function getWirisCasLanguages() { $langs = new _hx_array(array(new _hx_array(array("ca", $this->t->t("Catalan"))), new _hx_array(array("en", $this->t->t("English"))), new _hx_array(array("es", $this->t->t("Spanish"))), new _hx_array(array("et", $this->t->t("Estonian"))), new _hx_array(array("eu", $this->t->t("Basque"))), new _hx_array(array("fr", $this->t->t("French"))), new _hx_array(array("de", $this->t->t("German"))), new _hx_array(array("it", $this->t->t("Italian"))), new _hx_array(array("nl", $this->t->t("Dutch"))), new _hx_array(array("pt", $this->t->t("Portuguese"))))); return $langs; } public function printInputControls($h, $q, $correctAnswer, $userAnswer, $unique) { $answers = "[" . _hx_string_rec($correctAnswer, "") . "][" . _hx_string_rec($userAnswer, "") . "]"; $id = null; $h->openDiv("wirisinputcontrols" . _hx_string_rec($unique, "")); $h->openDivClass(null, "wirisfieldsetwrapper"); $h->openFieldset("wirisinputcontrolsfieldset" . _hx_string_rec($unique, ""), $this->t->t("allowedinput"), "wirismainfieldset"); $h->help("wirisinputcontrolshelp" . _hx_string_rec($unique, ""), "http://www.wiris.com/quizzes/docs/moodle/manual/validation#allowed-input", $this->t->t("manual")); $h->openDivClass("wirissyntaxassertions" . _hx_string_rec($unique, ""), "wirissyntaxassertions"); $h->openUl("wirisinputcontrolslist" . _hx_string_rec($unique, ""), "wirisinputcontrolslist"); $i = null; { $_g1 = 0; $_g = com_wiris_quizzes_impl_Assertion::$syntactic->length; while($_g1 < $_g) { $i1 = $_g1++; $h->openLi(); $id = "wirisassertion" . _hx_string_rec($unique, "") . "[" . com_wiris_quizzes_impl_Assertion::$syntactic[$i1] . "]" . $answers; $h->input("radio", $id, "wirisradiosyntax" . _hx_string_rec($unique, ""), null, null, null); $h->openStrong(); $h->label($this->t->t(com_wiris_quizzes_impl_Assertion::$syntactic[$i1]), $id, null); $h->close(); $h->text(" "); $h->label($this->t->t(com_wiris_quizzes_impl_Assertion::$syntactic[$i1] . "_description"), $id, null); $h->close(); unset($i1); } } $h->close(); $h->openCollapsibleFieldset("wirissyntaxparams" . _hx_string_rec($unique, ""), $this->t->t("syntaxparams"), "wirissyntaxparams", true, true); $h->openDivClass("wirissyntaxconstants" . _hx_string_rec($unique, ""), "wirissyntaxparam wirisspaceafter"); $h->openSpan("wirissyntaxconstantslabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->text($this->t->t("constants") . ":"); $h->close(); $h->openSpan("wirissyntaxconstantsvalues" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $id = "wirisassertionparampart" . _hx_string_rec($unique, "") . "[syntax_expression, syntax_quantity][constants]" . $answers; $letterpi = com_wiris_quizzes_impl_HTMLGui_7($this, $answers, $correctAnswer, $h, $i, $id, $q, $unique, $userAnswer); $this->syntaxCheckbox($h, $id . "[0]", $letterpi, $letterpi, false); $this->syntaxCheckbox($h, $id . "[1]", "e", "e", false); $this->syntaxCheckbox($h, $id . "[2]", "i", "i", false); $this->syntaxCheckbox($h, $id . "[3]", "j", "j", false); $h->close(); $h->close(); $h->openDivClass("wirissyntaxfunctions" . _hx_string_rec($unique, ""), "wirissyntaxparam"); $h->openDivClass("wirissyntaxfunctionscheckboxes" . _hx_string_rec($unique, ""), "wirisspaceafter"); $h->openSpan("wirissyntaxfunctionlabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->text($this->t->t("functions") . ":"); $h->close(); $h->openSpan("wirissyntaxfunctionvalues" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $id = "wirisassertionparampart" . _hx_string_rec($unique, "") . "[syntax_expression][functions]" . $answers; $this->syntaxCheckbox($h, $id . "[0]", "exp, log, ln", $this->t->t("explog"), false); $this->syntaxCheckbox($h, $id . "[1]", "sin, cos, tan, asin, acos, atan, arcsin, arccos, arctan, cosec, csc, sec, cotan, cot, acosec, acsc, asec, acotan, acot, sen, asen, arcsen", $this->t->t("trigonometric"), false); $this->syntaxCheckbox($h, $id . "[2]", "sinh, cosh, tanh, asinh, acosh, atanh, arcsinh, arccosh, arctanh, cosech, csch, sech, cotanh, coth, acosech, acsch, asech, acotanh, acoth, senh, asenh, arcsenh", $this->t->t("hyperbolic"), false); $this->syntaxCheckbox($h, $id . "[3]", "min, max, sign", $this->t->t("arithmetic"), false); $h->close(); $h->close(); $h->openDivClass("wirissyntaxfunctionscustom" . _hx_string_rec($unique, ""), "wirisspaceafter"); $h->openSpan("wirissyntaxuserfunctionlabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->label($this->t->t("userfunctions") . ":", $id . "[4]", null); $h->close(); $h->openSpan("wirissyntaxfunctionscustomvalues" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $h->input("text", $id . "[4]", "", null, null, "wirisuserfunctions"); $h->close(); $h->close(); $h->close(); $h->openDivClass("wirissyntaxunits" . _hx_string_rec($unique, ""), "wirissyntaxparam wirisspaceafter"); $h->openSpan("wirissyntaxunitslabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->text($this->t->t("units") . ":"); $h->close(); $h->openSpan("wirissyntaxunitsvalues" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $id = "wirisassertionparampart" . _hx_string_rec($unique, "") . "[syntax_quantity][units]" . $answers; $this->syntaxCheckbox($h, $id . "[0]", "m", "m", false); $this->syntaxCheckbox($h, $id . "[1]", "s", "s", false); $this->syntaxCheckbox($h, $id . "[2]", "g", "g", false); $this->syntaxCheckbox($h, $id . "[3]", com_wiris_quizzes_impl_Assertion::$ANGLE_UNITS_LIST, com_wiris_quizzes_impl_HTMLGui_8($this, $answers, $correctAnswer, $h, $i, $id, $letterpi, $q, $unique, $userAnswer) . " ' \"", false); $this->syntaxCheckbox($h, $id . "[4]", com_wiris_quizzes_impl_Assertion::$CURRENCY_UNITS_LIST, "\$" . com_wiris_quizzes_impl_HTMLGui_9($this, $answers, $correctAnswer, $h, $i, $id, $letterpi, $q, $unique, $userAnswer) . com_wiris_quizzes_impl_HTMLGui_10($this, $answers, $correctAnswer, $h, $i, $id, $letterpi, $q, $unique, $userAnswer), false); $this->syntaxCheckbox($h, $id . "[5]", com_wiris_quizzes_impl_Assertion::$PERCENT_UNITS_LIST, "%", false); $this->syntaxCheckbox($h, $id . "[6]", com_wiris_quizzes_impl_Assertion::$ALL_UNITS_LIST, $this->t->t("all"), true); $h->close(); $h->close(); $h->openDivClass("wirissyntaxunitprefixes" . _hx_string_rec($unique, ""), "wirissyntaxparam wirisspaceafter"); $h->openSpan("wirissyntaxunitslabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->text($this->t->t("unitprefixes") . ":"); $h->close(); $h->openSpan("wirissyntaxunitsvalues" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $id = "wirisassertionparampart" . _hx_string_rec($unique, "") . "[syntax_quantity][unitprefixes]" . $answers; $this->syntaxCheckbox($h, $id . "[0]", "M", "M", false); $this->syntaxCheckbox($h, $id . "[1]", "k", "k", false); $this->syntaxCheckbox($h, $id . "[2]", "c", "c", false); $this->syntaxCheckbox($h, $id . "[3]", "m", "m", false); $this->syntaxCheckbox($h, $id . "[4]", "y, z, a, f, p, n, " . com_wiris_quizzes_impl_HTMLGui_11($this, $answers, $correctAnswer, $h, $i, $id, $letterpi, $q, $unique, $userAnswer) . ", m, c, d, da, h, k, M, G, T, P, E, Z, Y", $this->t->t("all"), true); $h->close(); $h->close(); $h->openDivClass("wirissyntaxmixedfractions" . _hx_string_rec($unique, ""), "wirissyntaxparam wirisspaceafter"); $id = "wirisassertionparam" . _hx_string_rec($unique, "") . "[syntax_quantity][mixedfractions]" . $answers; $h->openSpan("wirissyntaxmixedfractionslabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->label($this->t->t("mixedfractions") . ":", $id, null); $h->close(); $h->openSpan("wirissyntaxmixedfractionsvalues" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $h->input("checkbox", $id, "", "true", null, null); $h->close(); $h->close(); $h->openDivClass("wirissyntaxlist" . _hx_string_rec($unique, ""), "wirissyntaxparam"); $id = "wirisassertionparam" . _hx_string_rec($unique, "") . "[syntax_expression,syntax_quantity][list]" . $answers; $h->openSpan("wirissyntaxlistlabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->label($this->t->t("list") . ":", $id, null); $h->close(); $h->openSpan("wirissyntaxlistvalue" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $h->input("checkbox", $id, "", "true", null, null); $h->close(); $h->close(); $h->openDivClass("wirissyntaxforcebrackets" . _hx_string_rec($unique, ""), "wirissyntaxparam"); $h->openSpan("wirissyntaxforcebracketslabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->close(); $h->openSpan("wirissyntaxforcebracketsvalues" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $id = "wirisassertionparam" . _hx_string_rec($unique, "") . "[syntax_expression][forcebrackets]" . $answers; $this->syntaxCheckbox($h, $id, "true", $this->t->t("forcebrackets"), false); $h->close(); $h->close(); $h->openDivClass("wirissyntaxintervals" . _hx_string_rec($unique, ""), "wirissyntaxparam wirisspacebefore"); $id = "wirisassertionparam" . _hx_string_rec($unique, "") . "[syntax_expression][intervals]" . $answers; $h->openSpan("wirissyntaxintervalslabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->label($this->t->t("intervals") . ":", $id, null); $h->close(); $h->openSpan("wirissyntaxintervalsvalue" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $h->input("checkbox", $id, "", "true", null, null); $h->close(); $h->close(); $h->openDivClass("wirissyntaxchars" . _hx_string_rec($unique, ""), "wirissyntaxparam wirisspacebefore"); $h->openSpan("wirissyntaxcharslabel" . _hx_string_rec($unique, ""), "wirissyntaxlabel"); $h->text($this->t->t("separators") . ":"); $h->close(); $h->openSpan("wirissyntaxcharsvalue" . _hx_string_rec($unique, ""), "wirissyntaxvalues"); $idgeneric = "wirisassertionparampart" . _hx_string_rec($unique, "") . "[syntax_expression,syntax_quantity]"; $h->openSpan("wirissyntaxcharspoint" . _hx_string_rec($unique, ""), "wirissyntaxchar"); $id = $idgeneric . "[point]" . $answers; $h->labelTitle($this->t->t("point") . ":", $id, "wirissyntaxcharslabel", $this->t->t("pointrole")); $h->select($id, "", new _hx_array(array(new _hx_array(array("nothing", $this->t->t("nothing"))), new _hx_array(array("decimalseparators", $this->t->t("decimalmark"))), new _hx_array(array("digitgroupseparators", $this->t->t("digitsgroup")))))); $h->close(); $h->openSpan("wirissyntaxcharscomma" . _hx_string_rec($unique, ""), "wirissyntaxchar"); $id = $idgeneric . "[comma]" . $answers; $h->labelTitle($this->t->t("comma") . ":", $id, "wirissyntaxcharslabel", $this->t->t("commarole")); $h->select($id, "", new _hx_array(array(new _hx_array(array("decimalseparators", $this->t->t("decimalmark"))), new _hx_array(array("digitgroupseparators", $this->t->t("digitsgroup"))), new _hx_array(array("itemseparators", $this->t->t("listitems")))))); $h->close(); $h->openSpan("wirissyntaxcharsspace" . _hx_string_rec($unique, ""), "wirissyntaxchar"); $id = $idgeneric . "[space]" . $answers; $h->labelTitle($this->t->t("space") . ":", $id, "wirissyntaxcharslabel", $this->t->t("spacerole")); $h->select($id, "", new _hx_array(array(new _hx_array(array("nothing", $this->t->t("nothing"))), new _hx_array(array("digitgroupseparators", $this->t->t("digitsgroup"))), new _hx_array(array("itemseparators", $this->t->t("listitems")))))); $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); $h->close(); } public function syntaxInput($h, $id, $name, $value, $label, $all, $radio) { $className = (($all) ? "wirisassertionparamall" : null); $h->openSpan(null, "wirishorizontalparam"); $h->input((($radio) ? "radio" : "checkbox"), $id, $name, $value, $value, $className); $h->labelTitle($label, $id, null, $value); $h->close(); } public function syntaxRadio($h, $id, $name, $value, $label) { $this->syntaxInput($h, $id, $name, $value, $label, false, true); } public function syntaxCheckbox($h, $id, $value, $label, $all) { $this->syntaxInput($h, $id, null, $value, $label, $all, false); } public function getAssertionFeedback($q, $a) { $h = new com_wiris_quizzes_impl_HTML(); $h->openUl(null, "wirisfeedbacklist"); $i = null; { $_g1 = 0; $_g = $a->length; while($_g1 < $_g) { $i1 = $_g1++; $c = $a[$i1]; $h->openLi(); $className = $this->getGradeClass($c->value); $suffix = (($c->value === 1.0) ? "_correct_feedback" : "_incorrect_feedback"); $h->openSpan(null, $className); $text = $this->t->t($c->assertion . $suffix); if($q !== null && $q->assertions !== null) { $index = $q->getAssertionIndex($c->assertion, $c->getCorrectAnswer(), $c->getAnswer()); if($index !== -1) { $ass = $q->assertions[$index]; if($ass->parameters !== null) { $j = null; { $_g3 = 0; $_g2 = $ass->parameters->length; while($_g3 < $_g2) { $j1 = $_g3++; $p = $ass->parameters[$j1]; $text = str_replace("\${" . $p->name . "}", $p->content, $text); unset($p,$j1); } unset($_g3,$_g2); } unset($j); } unset($ass); } unset($index); } $h->text($text); $h->close(); $h->close(); unset($text,$suffix,$i1,$className,$c); } } $h->close(); return $h->getString(); } public function getGradeClass($grade) { $className = null; if($grade === 1.0) { $className = "wiriscorrect"; } else { if($grade === 0.0) { $className = "wirisincorrect"; } else { $className = "wirispartiallycorrect"; } } return $className; } public function getTabPreview($q, $qi, $correctAnswer, $userAnswer, $unique, $conf) { $h = new com_wiris_quizzes_impl_HTML(); $this->printTester($h, $q, $qi, $correctAnswer, $userAnswer, $unique); return $h->getString(); } public function getTabVariables($q, $correctAnswer, $unique, $conf) { $h = new com_wiris_quizzes_impl_HTML(); $h->jsComponent("wiriscas" . _hx_string_rec($unique, ""), "jsCasInput", $q->wirisCasSession); $h->openDivClass("wiriscasbottomwrapper" . _hx_string_rec($unique, ""), "wiriscasbottomwrapper"); $this->printOutputControls($h, $unique); $h->close(); return $h->getString(); } public function getTabValidation($q, $correctAnswer, $userAnswer, $unique, $conf) { $h = new com_wiris_quizzes_impl_HTML(); $this->printInputControls($h, $q, $correctAnswer, $userAnswer, $unique); $this->printAssertionsControls($h, $q, $correctAnswer, $userAnswer, $unique, $conf); return $h->getString(); } public function getTabCorrectAnswer($q, $correctAnswer, $unique, $conf) { $h = new com_wiris_quizzes_impl_HTML(); if($conf->optOpenAnswer) { $h->openDivClass("wiriseditorwrapper" . _hx_string_rec($unique, ""), "wiriscorrectanswerfieldwrapper"); $content = ""; if($q->correctAnswers !== null && $q->correctAnswers->length > $correctAnswer) { $content = _hx_array_get($q->correctAnswers, $correctAnswer)->content; } $h->jsComponent("wiriscorrectanswer" . _hx_string_rec($unique, "") . "[" . _hx_string_rec($correctAnswer, "") . "]", "jsEditorInput", $content); $h->close(); } $this->printLocalData($h, $q, $unique, $conf); return $h->getString(); } public $lang; public $t; public function __call($m, $a) { if(isset($this->$m) && is_callable($this->$m)) return call_user_func_array($this->$m, $a); else if(isset($this->»dynamics[$m]) && is_callable($this->»dynamics[$m])) return call_user_func_array($this->»dynamics[$m], $a); else if('toString' == $m) return $this->__toString(); else throw new HException('Unable to call «'.$m.'»'); } function __toString() { return 'com.wiris.quizzes.impl.HTMLGui'; } } function com_wiris_quizzes_impl_HTMLGui_0(&$»this, &$correctAnswer, &$h, &$hasUserAnswer, &$q, &$qi, &$unique, &$userAnswer) { if($hasUserAnswer) { return _hx_array_get($qi->userData->answers, $userAnswer)->content; } else { return ""; } } function com_wiris_quizzes_impl_HTMLGui_1(&$»this, &$h, &$id, &$unique) { { $s = new haxe_Utf8(null); $s->addChar(183); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_2(&$»this, &$h, &$id, &$unique) { { $s = new haxe_Utf8(null); $s->addChar(183); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_3(&$»this, &$h, &$id, &$unique) { { $s = new haxe_Utf8(null); $s->addChar(183); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_4(&$»this, &$h, &$id, &$unique) { { $s = new haxe_Utf8(null); $s->addChar(215); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_5(&$»this, &$h, &$id, &$unique) { { $s = new haxe_Utf8(null); $s->addChar(215); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_6(&$»this, &$h, &$id, &$unique) { { $s = new haxe_Utf8(null); $s->addChar(215); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_7(&$»this, &$answers, &$correctAnswer, &$h, &$i, &$id, &$q, &$unique, &$userAnswer) { { $s = new haxe_Utf8(null); $s->addChar(960); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_8(&$»this, &$answers, &$correctAnswer, &$h, &$i, &$id, &$letterpi, &$q, &$unique, &$userAnswer) { { $s = new haxe_Utf8(null); $s->addChar(176); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_9(&$»this, &$answers, &$correctAnswer, &$h, &$i, &$id, &$letterpi, &$q, &$unique, &$userAnswer) { { $s = new haxe_Utf8(null); $s->addChar(8364); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_10(&$»this, &$answers, &$correctAnswer, &$h, &$i, &$id, &$letterpi, &$q, &$unique, &$userAnswer) { { $s = new haxe_Utf8(null); $s->addChar(165); return $s->toString(); } } function com_wiris_quizzes_impl_HTMLGui_11(&$»this, &$answers, &$correctAnswer, &$h, &$i, &$id, &$letterpi, &$q, &$unique, &$userAnswer) { { $s = new haxe_Utf8(null); $s->addChar(181); return $s->toString(); } }
nitro2010/moodle
question/wq/quizzes/lib/com/wiris/quizzes/impl/HTMLGui.class.php
PHP
gpl-3.0
52,625
package com.jeans.iservlet.service.fts; import java.util.List; import java.util.Map; import com.jeans.iservlet.model.portal.User; import com.jeans.iservlet.view.portal.FtsResultView; public interface FtsService { /** * 初始化Hibernate Search索引 * * @throws InterruptedException * */ public void reIndex() throws InterruptedException; /** * 执行搜索,搜索结果要根据当前用户进行可访问范围判断 * * @param catalog * @param keyword * @param user * @return */ public Map<String, List<FtsResultView>> search(String catalog, String keyword, User user); }
majorli/iServlet3
src/main/java/com/jeans/iservlet/service/fts/FtsService.java
Java
gpl-3.0
613
--- layout: amp title: ¿Se puede congelar la ensalada de col? permalink: /amp/ensalada-de-col/ normallink: /ensalada-de-col/ home: FALSE ogimg: /img/coleslaw-300x199.jpg.png sitemap: priority: 1 changefreq: 'monthly' --- ## Pregunta Compré una gran cabeza de col en el mercado de un granjero local, y quiero hacer un enorme lote de col con él. Sin embargo, creo que voy a obtener 8 o más tazas de col de la col que tengo, y no hay manera que puedo comer todo eso ensalada de col en una vez! No estoy seguro de cuál sería la mejor manera de almacenar la ensalada de col sería para que pueda disfrutarlo durante todo el verano. ¿Importa qué tipo de apósito que utilizo cuando se almacena la ensalada de col? ¿Puede congelar la ensalada de col? <amp-img src="https://sepuedecongelar.com/img/coleslaw-300x199.jpg" alt="¿Se puede congelar la ensalada de col?" height="400" width="800"></amp-img> ## Respuesta La ensalada de col puede ser congelada, pero depende del tipo de aderezo que elija usar con él. No se recomienda congelar la ensalada de col con un aderezo a base de mayonesa. La mayonesa tiene una tendencia a separarse después de ser congelada. La ensalada de col con un aderezo a base de mayonesa tiende a quedar acuosa y pierde su "crujido". Si desea usar un apósito a base de mayonesa con su ensalada de col, puede preparar la ensalada de col y congelarla desnuda y luego añadir el apósito Mezcla se ha descongelado. Para congelar la mezcla de col de ensalada seca, coloque la mezcla en una bolsa de congelador, y eliminar el exceso de aire. Selle la bolsa, luego etiqueta y fecha. Para descongelar, retire la bolsa del congelador y descongelarla en el refrigerador. Esto ayuda a mantener los ingredientes de la ensalada de col crujiente y fresco para el apósito. Vestir la ensalada de col con el apósito de mayonesa, mezclar para cubrir, y servir frío. Refrigere las sobras inmediatamente. Coleslaws a base de aceite y vinagre que utilizan semillas de mostaza, semillas de apio o jugo de limón se congelan mucho más con éxito y se pueden congelar con el vendaje ya agregado. Para congelar este tipo de ensalada de col, preparar la ensalada de col según la receta y mezclar bien en el apósito. Congele la ensalada de col en un recipiente seguro para el congelador o en una bolsa de congelador. Retire el exceso de aire, presione la ensalada de col, y sellar la bolsa. Etiquetar y fechar la ensalada de col y congelar. . Puede almacenarse apilado en el congelador. La ensalada de col congelada debe utilizarse dentro de unos meses de congelación. Para descongelar, quitar la ensalada de col del congelador y descongelar en el refrigerador durante varias horas o durante la noche. Coleslaw que está vestida será un poco más acuoso después de descongelación de lo que era cuando fresco, así que escurrir el exceso de agua de la ensalada de col antes de servir. La ensalada de col congelada previamente debe ser usada dentro de 2-3 días de la descongelación. Nunca vuelva a congelar la ensalada de col congelada previamente y manténgala siempre refrigerada.
sepuedecongelar/sepuedecongelar.github.io
_amp/2017-09-03-ensalada-de-col.md
Markdown
gpl-3.0
3,110
"""Utility functions""" import os import difflib def get_diff(str1, str2): """Returns git-diff-like diff between two strings""" expected = str1.splitlines(1) actual = str2.splitlines(1) diff = difflib.unified_diff(expected, actual, lineterm=-0, n=0) return ''.join(diff) def ensure_directory(path): """Creates the given directory, if not existing""" os.makedirs(path, exist_ok=True) def ensure_directory_of_file(file_path): """Creates the parent directory of a given file path, if not existing""" ensure_directory(os.path.dirname(file_path)) def check_service_name(service_name): """Raises an exception if service_name is not valid""" service_name_errors = get_service_name_errors(service_name) if service_name_errors: raise Exception('errors: %s' % str(service_name_errors)) def get_service_name_errors(service_name): """Checks if service_name is valid and returns errors if it is not. Returns None if service_name is valid""" errors = [] legal_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\' for index in range(len(service_name)): if not service_name[index] in legal_characters: errors.append('Illegal character in service name: %s at position %s' % (service_name[index], index)) return errors
perfalle/smartbox
common/utils.py
Python
gpl-3.0
1,360
package com.funny.autocode.util; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileUtils { /** * 根据路径删除指定的目录或文件,无论存在与否 * * @param sPath 要删除的目录或文件 * @return 删除成功返回 true,否则返回 false。 */ public static boolean DeleteFolder(String sPath) { boolean flag = false; File file = new File(sPath); // 判断目录或文件是否存在 if (!file.exists()) { // 不存在返回 false return flag; } else { // 判断是否为文件 if (file.isFile()) { // 为文件时调用删除文件方法 return deleteFile(sPath); } else { // 为目录时调用删除目录方法 return deleteDirectory(sPath); } } } /** * 删除单个文件 * * @param sPath 被删除文件的文件名 * @return 单个文件删除成功返回true,否则返回false */ public static boolean deleteFile(String sPath) { boolean flag = false; File file = new File(sPath); // 路径为文件且不为空则进行删除 if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } /** * 删除目录(文件夹)以及目录下的文件 * * @param sPath 被删除目录的文件路径 * @return 目录删除成功返回true,否则返回false */ public static boolean deleteDirectory(String sPath) { // 如果sPath不以文件分隔符结尾,自动添加文件分隔符 if (!sPath.endsWith(File.separator)) { sPath = sPath + File.separator; } File dirFile = new File(sPath); // 如果dir对应的文件不存在,或者不是一个目录,则退出 if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } boolean flag = true; // 删除文件夹下的所有文件(包括子目录) File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { // 删除子文件 if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) break; } // 删除子目录 else { flag = deleteDirectory(files[i].getAbsolutePath()); if (!flag) break; } } if (!flag) return false; // 删除当前目录 if (dirFile.delete()) { return true; } else { return false; } } public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) { final String userAgent = request.getHeader("USER-AGENT"); try { String finalFileName = null; if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器 finalFileName = URLEncoder.encode(fileName, "UTF-8"); } else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器 finalFileName = new String(fileName.getBytes("GBK"), "ISO8859-1"); } else { finalFileName = URLEncoder.encode(fileName, "UTF-8");// 其他浏览器 } response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");// 这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开 } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
funny5258/autocode
autocode-web/src/main/java/com/funny/autocode/util/FileUtils.java
Java
gpl-3.0
3,978
package org.saga.metadata; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; import org.saga.Saga; public class UnnaturalTag implements MetadataValue { /** * Key for unnatural tag. */ public static String METADATA_KEY = "unnatural"; /** * Value for unnatural tag. */ public static UnnaturalTag METADATA_VALUE = new UnnaturalTag(); @Override public boolean asBoolean() { return true; } @Override public byte asByte() { return 0; } @Override public double asDouble() { return 0; } @Override public float asFloat() { return 0; } @Override public int asInt() { return 0; } @Override public long asLong() { return 0; } @Override public short asShort() { return 0; } @Override public String asString() { return "unnatural"; } @Override public Plugin getOwningPlugin() { return Saga.plugin(); } @Override public void invalidate() { } @Override public Object value() { return asString(); } }
Olyol95/Saga
src/org/saga/metadata/UnnaturalTag.java
Java
gpl-3.0
990
# Zinlok The things lock. This project is about IoT. We are going to build a digital lock to lock anything you can imagine. Exs: your car, your house door, your programs, your profiles... *This is a security project made by some students from the "Universidad de Sevilla".
LoloCDF/Zinlok
README.md
Markdown
gpl-3.0
276
#!/usr/bin/env jruby require 'propane' # Pie Chart # By Ira Greenberg # # Uses the arc() function to generate a pie chart from the data # stored in an array. class PieChart < Propane::App def setup sketch_title 'Pie Chart' background 100 no_stroke diameter = [width, height].min * 0.75 angles = [30, 10, 45, 35, 60, 38, 75, 67] rads = angles.map(&:radians) # map angles to radians angrads = angles.zip(rads) last_ang = 0.0 angrads.each do |ar| fill ar[0] * 3.0 arc width / 2, height / 2, diameter, diameter, last_ang, last_ang + ar[1] last_ang += ar[1] end end def settings size 640, 360 smooth(4) end end PieChart.new
ruby-processing/propane-examples
processing_app/basics/form/pie_chart.rb
Ruby
gpl-3.0
696
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserService.cs" company="Patrick Magee"> // Copyright © 2013 Patrick Magee // // This program is free software: you can redistribute it and/or modify it // under the +terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // <summary> // The user service. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Nircbot.Core.Services { #region using System; using System.Collections.Generic; using System.Linq; using Nircbot.Core.Entities; using Nircbot.Core.Module; #endregion /// <summary> /// The user service. /// </summary> public class UserService : IUserService { #region Fields /// <summary> /// The users /// </summary> private readonly List<User> users = new List<User>(); #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="UserService"/> class. /// </summary> public UserService() { this.users.Add(new User { AccessLevel = AccessLevel.Root, Email = "patrick.magee@live.co.uk", Host = "patrick.mag@127.0.0.1", Nick = "Peej" }); } #endregion #region Public Methods and Operators /// <summary> /// Gets the user by host. /// </summary> /// <param name="host"> /// The host. /// </param> /// <returns> /// The <see cref="User"/>. /// </returns> public User GetUserByHost(string host) { return this.users.FirstOrDefault(u => u.Host.Equals(host, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Lists the admins. /// </summary> /// <returns> /// The <see cref="IEnumerable{User}"/>. /// </returns> public IEnumerable<User> ListAdmins() { return this.users.Where(u => u.AccessLevel >= AccessLevel.Admin); } #endregion } }
pjmagee/Nircbot
Nircbot.Core/Services/UserService.cs
C#
gpl-3.0
2,777
[1]: http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month # [Find the last Sunday of each month][1] ```ruby var dt = require('DateTime') var (year=2016) = ARGV.map{.to_i}... for i in (1 .. 12) { var date = dt.last_day_of_month( year => year, month => i ) while (date.dow != 7) { date = date.subtract(days => 1) } say date.ymd } ``` #### Output: ``` $ sidef last_sunday.sf 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 ```
trizen/sidef-book
programming_tasks/F/Find_the_last_Sunday_of_each_month.md
Markdown
gpl-3.0
574
--------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- -- TABLE WITH AUTHORS' NAMES FOR THE SELECTED CLASSES, WITH MOBILITY LINKS -- riccaboni.t08_names_allclasses_us_mob_atleastone --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- SHOW INDEX FROM riccaboni.t09; ALTER TABLE riccaboni.t09 ADD INDEX(localID); SHOW INDEX FROM riccaboni.t01_allclasses_appid_patstat_us_family; DROP TABLE IF EXISTS riccaboni.t08_names_allclasses_us_mob_atleastone; CREATE TABLE riccaboni.t08_names_allclasses_us_mob_atleastone AS SELECT a.*, b.mobileID, d.APPLN_ID, d.DOCDB_FAMILY_ID FROM riccaboni.t08_names_allclasses_us_atleastone a LEFT JOIN riccaboni.t09 b ON a.ID=b.localID INNER JOIN riccaboni.t01_allclasses_appid_patstat_us_atleastone c ON a.pat=c.pat INNER JOIN riccaboni.t01_allclasses_appid_patstat_us_family d ON c.APPLN_ID = d.APPLN_ID; /* Query OK, 3122408 rows affected (2 min 6,72 sec) Records: 3122408 Duplicates: 0 Warnings: 0 */ SHOW INDEX FROM riccaboni.t08_names_allclasses_us_mob_atleastone; ALTER TABLE riccaboni.t08_names_allclasses_us_mob_atleastone ADD INDEX(DOCDB_FAMILY_ID); ALTER TABLE riccaboni.t08_names_allclasses_us_mob_atleastone ADD INDEX(APPLN_ID); ALTER TABLE riccaboni.t08_names_allclasses_us_mob_atleastone ADD INDEX(ID); ALTER TABLE riccaboni.t08_names_allclasses_us_mob_atleastone ADD INDEX(pat); SELECT COUNT(DISTINCT a.ID) FROM riccaboni.t08_names_allclasses_us_mob_atleastone a WHERE a.mobileID IS NOT NULL; /* +----------------------+ | COUNT(DISTINCT a.ID) | +----------------------+ | 179547 | +----------------------+ 1 row in set (3,00 sec) */ SELECT COUNT(DISTINCT a.mobileID) FROM riccaboni.t08_names_allclasses_us_mob_atleastone a; /* +----------------------------+ | COUNT(DISTINCT a.mobileID) | +----------------------------+ | 105256 | +----------------------------+ 1 row in set (3,57 sec) So, there are 74.291 less IDS, when using the mobile inventor links SELECT COUNT(DISTINCT b.mobileID), CHAR_LENGTH(b.mobileID) AS Nchar FROM riccaboni.t08_names_allclasses_us_mob_atleastone b GROUP BY CHAR_LENGTH(b.mobileID); +----------------------------+-------+ | COUNT(DISTINCT b.mobileID) | Nchar | +----------------------------+-------+ | 0 | NULL | | 8 | 3 | | 67 | 4 | | 585 | 5 | | 4835 | 6 | | 32829 | 7 | | 66932 | 8 | +----------------------------+-------+ 7 rows in set (3,71 sec) */ --------------------------------------------------------------------------------------------------- -- File --------------------------------------------------------------------------------------------------- SELECT DISTINCT a.ID, a.name, a.mobileID FROM riccaboni.t08_names_allclasses_us_mob_atleastone a INTO OUTFILE '/var/lib/mysql-files/Names_ID_Mobile_Classes.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'; /* */
cchacua/m2-migrations
scripts/procedures/nationality_classifier/no/no.sql
SQL
gpl-3.0
3,530
alberto-elias-website ===================== My personal website
AlbertoElias/alberto-elias-website
README.md
Markdown
gpl-3.0
65
namespace Grove.Effects { using System.Collections.Generic; using System.Linq; using Decisions; public class CounterTargetSpellUnlessControllerPays1ForEachRevealedCard : Effect, IProcessDecisionResults<ChosenCards>, IChooseDecisionResults<List<Card>, ChosenCards>, IProcessDecisionResults<BooleanResult> { public ChosenCards ChooseResult(List<Card> candidates) { var cardsToReveal = Controller.Opponent.GetAvailableManaCount(usage: ManaUsage.Spells) + 1; return candidates.OrderBy(x => x.Score).Take(cardsToReveal).ToList(); } public void ProcessResults(BooleanResult results) { if (results.IsTrue) return; Stack.Counter(Target.Effect()); } public void ProcessResults(ChosenCards results) { foreach (var chosenCard in results) { chosenCard.Reveal(); } var targetSpellController = Target.Effect().Controller; Enqueue(new PayOr(targetSpellController, p => { p.ManaAmount = results.Count.Colorless(); p.Text = string.Format("Pay {0}?", results.Count); p.ProcessDecisionResults = this; })); } protected override void ResolveEffect() { Enqueue(new SelectCards(Controller, p => { p.SetValidator(c => c.HasColor(CardColor.Blue)); p.Zone = Zone.Hand; p.MinCount = 0; p.Text = "Choose any number of cards in your hand."; p.OwningCard = Source.OwningCard; p.ProcessDecisionResults = this; p.ChooseDecisionResults = this; })); } } }
pinky39/grove
source/Grove/Core/Effects/CounterTargetSpellUnlessControllerPays1ForEachRevealedCard.cs
C#
gpl-3.0
1,662
# wificredentialsviewer www.wificredentials.com Based on an article of Michael Haephrati at Code Project. https://www.codeproject.com/Articles/1164749/The-Secrets-of-Wi-Fi-Credentials All graphics are copyrighted to Secured Globe, Inc. New York www.securedglobe.com
haephrati/wificredentialsviewer
README.md
Markdown
gpl-3.0
266
package logiclda.infer; import java.util.Random; import java.util.Map; import java.util.ArrayList; import java.util.List; import logiclda.EvalLDA; import logiclda.infer.MirrorDescent; import logiclda.rules.GroundableRule; import logiclda.rules.LogicRule; import logiclda.infer.GroundRules; import logiclda.Corpus; import logiclda.LDAParameters; import logiclda.MiscUtil; /** * * Collapsed Gibbs Sampling inference for Latent Dirichlet Allocation * (Griffiths & Steyvers PNAS 2004) * * @author david * */ public class CollapsedGibbs { /** * Do a single Collapsed Gibbs sample, but with topic-words Phi fixed * * @param c Contains words, documents * @param p Contains hyperparameters * @param s Sample object to be updated in place * @param onlineInit If true, don't pre-subtract counts */ public static void fixedPhiSample(Corpus c, LDAParameters p, DiscreteSample s, boolean onlineInit, double[][] phi) { int N = c.N; int T = p.T; double[] tmp = new double[T]; for(int i = 0; i < N; i++) { // Reset sampling normalization sum to 0 double normsum = 0; // Remove current assignment from counts // (unless we're doing 'online-style' init) if(!onlineInit) { s.updateCounts(c.w[i], s.z[i], c.d[i], -1); } // Get un-normalized probabilities for each topic for(int j = 0; j < T; j++) { double phiterm = phi[j][c.w[i]]; double num2 = s.nd[c.d[i]][j] + p.alpha[j]; tmp[j] = phiterm * num2; normsum += tmp[j]; } // Sample the assignment s.z[i] = MiscUtil.multSample(p.rng, tmp, normsum); // Update the count matrices s.updateCounts(c.w[i], s.z[i], c.d[i], 1); } return; } public static DiscreteSample runGroundGibbs(Corpus c, LDAParameters p, DiscreteSample s, List<LogicRule> rules, int numsamp) { // Cast LogicRule to GroundableRule List<GroundableRule> grules = GroundRules.groundCast(rules); // Apply evidence for(GroundableRule gr : grules) gr.applyEvidence(c, p.T); // Ground the Logic Rules GroundRules gr = new GroundRules(grules, s.z, p.rng, p.T); // Best overall z-assignment found thus far // int[] bestz = new int[s.z.length]; System.arraycopy(s.z, 0, bestz, 0, s.z.length); MirrorDescent logicrules = new MirrorDescent(rules, p.rng); double bestobj = EvalLDA.ldaLoglike(s, p) + logicrules.satWeight(s.z); // Do the samples for(int si = 0; si < numsamp; si++) { System.out.println(String.format("Sample %d of %d", si, numsamp)); CollapsedGibbs.groundGibbsSample(gr, c, p, s, false); // Do we have a new best sample? if((si+1) % 500 == 0) { double newobj = EvalLDA.ldaLoglike(s, p) + logicrules.satWeight(s.z); if(newobj > bestobj) { System.arraycopy(s.z, 0, bestz, 0, s.z.length); bestobj = newobj; } } } // Use the best sample s.repopZ(c, bestz); return s; } /** * Externally called method for Ground LogicLDA sampling * @param gr * @param c * @param p * @param numsamp * @return */ public static DiscreteSample doGroundGibbs(List<GroundableRule> grules, Corpus c, LDAParameters p, int numsamp) { // Get relevant dimensions int N = c.N; int T = p.T; int W = p.W; int D = c.D; // Online initialization DiscreteSample s = new DiscreteSample(N, T, W, D); CollapsedGibbs.gibbsSample(c, p, s, true); // Ground the Logic Rules GroundRules gr = new GroundRules(grules, s.z, p.rng, p.T); // Do the samples for(int si = 0; si < numsamp; si++) { System.out.println(String.format("Sample %d of %d", si, numsamp)); CollapsedGibbs.groundGibbsSample(gr, c, p, s, false); } return s; } /** * Do a single Ground LogicLDA sample * * @param logicweights * @param c * @param p * @param s * @param onlineInit */ public static void groundGibbsSample(GroundRules gr, Corpus c, LDAParameters p, DiscreteSample s, boolean onlineInit) { int N = c.N; int T = p.T; double[] tmp = new double[T]; for(int i = 0; i < N; i++) { // Reset sampling normalization sum to 0 double normsum = 0; // Remove current assignment from counts // (unless we're doing 'online-style' init) if(!onlineInit) { s.updateCounts(c.w[i], s.z[i], c.d[i], -1); } // Get un-normalized probabilities for each topic for(int j = 0; j < T; j++) { double num1 = s.nw[c.w[i]][j] + p.beta[j][c.w[i]]; double den1 = s.nwcolsums[j] + p.betasums[j]; double num2 = s.nd[c.d[i]][j] + p.alpha[j]; tmp[j] = (num1 / den1) * num2; // If applicable, multiply the standard Collapsed Gibbs term // by the exp of the logic contribution if(gr.inLogic(i)) { s.z[i] = j; tmp[j] *= Math.exp(gr.evalAssign(s.z, i)); } normsum += tmp[j]; } // Sample the assignment s.z[i] = MiscUtil.multSample(p.rng, tmp, normsum); // Update the count matrices s.updateCounts(c.w[i], s.z[i], c.d[i], 1); } return; } /** * External method for doing online-init, then numsamp Logic Gibbs samples * * @param logicweights N x T matrix of (independent) rule contributions * @param c Contains words, documents * @param p Contains hyperparameters * @param numsamp How many samples to do * @param randseed Seed for random number generator * @return The final sample from the Markov Chain */ public static DiscreteSample doLogicGibbs(double[][] logicweights, Corpus c, LDAParameters p, int numsamp) { // Get relevant dimensions int N = c.N; int T = p.T; int W = p.W; int D = c.D; // Online initialization DiscreteSample s = new DiscreteSample(N, T, W, D); CollapsedGibbs.logicGibbsSample(logicweights, c, p, s, true); // Do the samples for(int si = 0; si < numsamp; si++) { System.out.println(String.format("Sample %d of %d", si, numsamp)); CollapsedGibbs.logicGibbsSample(logicweights, c, p, s, false); } return s; } /** * Do a single Logic Collapsed Gibbs sample * * @param logicweights N x T matrix of (independent) rule contributions * @param c Contains words, documents * @param p Contains hyperparameters * @param s Sample object to be updated in place * @param rng Random number generator for sampling * @param onlineInit If true, don't pre-subtract counts */ public static void logicGibbsSample(double[][] logicweights, Corpus c, LDAParameters p, DiscreteSample s, boolean onlineInit) { int N = c.N; int T = p.T; double[] tmp = new double[T]; for(int i = 0; i < N; i++) { // Reset sampling normalization sum to 0 double normsum = 0; // Remove current assignment from counts // (unless we're doing 'online-style' init) if(!onlineInit) { s.updateCounts(c.w[i], s.z[i], c.d[i], -1); } // Get un-normalized probabilities for each topic for(int j = 0; j < T; j++) { double num1 = s.nw[c.w[i]][j] + p.beta[j][c.w[i]]; double den1 = s.nwcolsums[j] + p.betasums[j]; double num2 = s.nd[c.d[i]][j] + p.alpha[j]; if(logicweights[i] != null) tmp[j] = (num1 / den1) * num2 * Math.exp(logicweights[i][j]); else tmp[j] = (num1 / den1) * num2; normsum += tmp[j]; } // Sample the assignment s.z[i] = MiscUtil.multSample(p.rng, tmp, normsum); // Update the count matrices s.updateCounts(c.w[i], s.z[i], c.d[i], 1); } return; } /** * External method for doing online-init, then numsamp Gibbs samples * @param c Contains words, documents * @param p Contains hyperparameters * @param numsamp How many samples to do * @param randseed Seed for random number generator * @return The final sample from the Markov Chain */ public static DiscreteSample doGibbs(Corpus c, LDAParameters p, int numsamp) { // Get relevant dimensions int N = c.N; int T = p.T; int W = p.W; int D = c.D; // Online initialization DiscreteSample s = new DiscreteSample(N, T, W, D); CollapsedGibbs.gibbsSample(c, p, s, true); // Do the samples for(int si = 0; si < numsamp; si++) { System.out.println(String.format("Sample %d of %d", si, numsamp)); CollapsedGibbs.gibbsSample(c, p, s, false); } return s; } /** * Do a single Collapsed Gibbs sample * * @param c Contains words, documents * @param p Contains hyperparameters * @param s Sample object to be updated in place * @param rng Random number generator for sampling * @param onlineInit If true, don't pre-subtract counts */ public static void gibbsSample(Corpus c, LDAParameters p, DiscreteSample s, boolean onlineInit) { int N = c.N; int T = p.T; double[] tmp = new double[T]; for(int i = 0; i < N; i++) { // Reset sampling normalization sum to 0 double normsum = 0; // Remove current assignment from counts // (unless we're doing 'online-style' init) if(!onlineInit) { s.updateCounts(c.w[i], s.z[i], c.d[i], -1); } // Get un-normalized probabilities for each topic for(int j = 0; j < T; j++) { double num1 = s.nw[c.w[i]][j] + p.beta[j][c.w[i]]; double den1 = s.nwcolsums[j] + p.betasums[j]; double num2 = s.nd[c.d[i]][j] + p.alpha[j]; tmp[j] = (num1 / den1) * num2; normsum += tmp[j]; } // Sample the assignment s.z[i] = MiscUtil.multSample(p.rng, tmp, normsum); // Update the count matrices s.updateCounts(c.w[i], s.z[i], c.d[i], 1); } return; } }
davidandrzej/LogicLDA
src/main/java/logiclda/infer/CollapsedGibbs.java
Java
gpl-3.0
9,595
using AppMigrate.Properties; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace AppMigrate { public partial class SettingsForm : Form { public SettingsForm() { InitializeComponent(); this.cbCheckDatabaseUpdateOnStartup.Checked = Settings.Default.CheckDatabaseUPdateOnStartup; } private void applyBtn_Click(object sender, EventArgs e) { Settings.Default.CheckDatabaseUPdateOnStartup = this.cbCheckDatabaseUpdateOnStartup.Checked; Settings.Default.Password = this.txtPassword.Text; Settings.Default.Save(); this.Close(); } private void cancelBtn_Click(object sender, EventArgs e) { this.Close(); } private void cbPassword_CheckedChanged(object sender, EventArgs e) { this.txtPassword.Enabled = this.cbPassword.Checked; if(!this.cbPassword.Checked) { this.txtPassword.Text = string.Empty; } } } }
C-Nedelcu/appmigrate
AppMigrate/SettingsForm.cs
C#
gpl-3.0
1,182
Drink-O-Water ============= Terms and condition If any of our plugin cause harm to your server, it is not our blame. We do not make any of our plugin for money, however some plugin are private and will not be an open download. In the future some of our plugins will be open-source. Please note that all of our plugin are made on Java 6 and are develop on MacBooks. These plugin would not work on any under running Java 5 or lower. Downloading Please download this only on bukkit! http://dev.bukkit.org/bukkit-plugins/drink-o-water/ Thanks you, Owner and coder: Bhavnnet Pannu
aksjeffrey/Drink-O-Water
README.md
Markdown
gpl-3.0
611
require 'ffi' module Archive module C def self.attach_function_maybe *args attach_function(*args) rescue FFI::NotFoundError end extend FFI::Library ffi_lib ["archive", "libarchive.so.2"] attach_function :archive_version_number, [], :int attach_function :archive_version_string, [], :string attach_function :archive_error_string, [:pointer], :string attach_function :archive_errno, [:pointer], :int attach_function :archive_read_new, [], :pointer attach_function :archive_read_open_filename, [:pointer, :string, :size_t], :int attach_function :archive_read_open_memory, [:pointer, :pointer, :size_t], :int attach_function :archive_read_support_compression_program, [:pointer, :string], :int attach_function :archive_read_support_compression_all, [:pointer], :int attach_function :archive_read_support_format_all, [:pointer], :int # TODO: this function has been renamed to :archive_read_free in libarchive 3.0 attach_function :archive_read_finish, [:pointer], :int attach_function :archive_read_extract, [:pointer, :pointer, :int], :int attach_function :archive_read_header_position, [:pointer], :int attach_function :archive_read_next_header, [:pointer, :pointer], :int attach_function :archive_read_data, [:pointer, :pointer, :size_t], :size_t attach_function :archive_read_data_into_fd, [:pointer, :int], :int attach_function :archive_write_new, [], :pointer attach_function :archive_write_open_filename, [:pointer, :string], :int callback :archive_open_callback, [:pointer, :pointer], :int callback :archive_write_callback, [:pointer, :pointer, :pointer, :size_t], :int callback :archive_close_callback, [:pointer, :pointer], :int # TODO: the following function is the real definition but uses multiple callbacks. This implies that it will not work with Rubinius (currently), but luckily we only need the write-callback actually. #attach_function :archive_write_open, [:pointer, :pointer, :archive_open_callback, :archive_write_callback, :archive_close_callback], :int attach_function :archive_write_open, [:pointer, :pointer, :pointer, :archive_write_callback, :pointer], :int # TODO: catch errors if not defined attach_function :archive_write_set_compression_none, [:pointer], :int attach_function_maybe :archive_write_set_compression_gzip, [:pointer], :int attach_function_maybe :archive_write_set_compression_bzip2, [:pointer], :int attach_function_maybe :archive_write_set_compression_compress, [:pointer], :int attach_function_maybe :archive_write_set_compression_lzma, [:pointer], :int attach_function_maybe :archive_write_set_compression_xz, [:pointer], :int attach_function :archive_write_set_compression_program, [:pointer, :string], :int def self.archive_write_set_compression(archive, compression) case compression when String archive_write_set_compression_program archive, compression when COMPRESSION_BZIP2 archive_write_set_compression_bzip2 archive when COMPRESSION_GZIP archive_write_set_compression_gzip archive when COMPRESSION_LZMA archive_write_set_compression_lzma archive when COMPRESSION_XZ archive_write_set_compression_xz archive when COMPRESSION_COMPRESS archive_write_set_compression_compress archive when COMPRESSION_NONE archive_write_set_compression_none archive else raise "Unknown compression type: #{compression}" end end attach_function :archive_write_set_format, [:pointer, :int], :int attach_function :archive_write_data, [:pointer, :pointer, :size_t], :ssize_t attach_function :archive_write_header, [:pointer, :pointer], :int attach_function :archive_write_finish, [:pointer], :void attach_function :archive_write_get_bytes_in_last_block, [:pointer], :int attach_function :archive_write_set_bytes_in_last_block, [:pointer, :int], :int attach_function :archive_entry_new, [], :pointer attach_function :archive_entry_free, [:pointer], :void attach_function :archive_entry_atime, [:pointer], :time_t attach_function :archive_entry_atime_nsec, [:pointer, :time_t, :long], :void attach_function_maybe :archive_entry_atime_is_set, [:pointer], :int attach_function :archive_entry_set_atime, [:pointer, :time_t, :long], :int attach_function_maybe :archive_entry_unset_atime, [:pointer], :int attach_function_maybe :archive_entry_birthtime, [:pointer], :time_t attach_function_maybe :archive_entry_birthtime_nsec, [:pointer, :time_t, :long], :void attach_function_maybe :archive_entry_birthtime_is_set, [:pointer], :int attach_function_maybe :archive_entry_set_birthtime, [:pointer, :time_t, :long], :int attach_function_maybe :archive_entry_unset_birthtime, [:pointer], :int attach_function :archive_entry_ctime, [:pointer], :time_t attach_function :archive_entry_ctime_nsec, [:pointer, :time_t, :long], :void attach_function_maybe :archive_entry_ctime_is_set, [:pointer], :int attach_function :archive_entry_set_ctime, [:pointer, :time_t, :long], :int attach_function_maybe :archive_entry_unset_ctime, [:pointer], :int attach_function :archive_entry_mtime, [:pointer], :time_t attach_function :archive_entry_mtime_nsec, [:pointer, :time_t, :long], :void attach_function_maybe :archive_entry_mtime_is_set, [:pointer], :int attach_function :archive_entry_set_mtime, [:pointer, :time_t, :long], :int attach_function_maybe :archive_entry_unset_mtime, [:pointer], :int attach_function :archive_entry_dev, [:pointer], :dev_t attach_function :archive_entry_set_dev, [:pointer, :dev_t], :void attach_function :archive_entry_devmajor, [:pointer], :dev_t attach_function :archive_entry_set_devmajor, [:pointer, :dev_t], :void attach_function :archive_entry_devminor, [:pointer], :dev_t attach_function :archive_entry_set_devminor, [:pointer, :dev_t], :void attach_function :archive_entry_filetype, [:pointer], :mode_t attach_function :archive_entry_set_filetype, [:pointer, :mode_t], :void attach_function :archive_entry_fflags, [:pointer, :pointer, :pointer], :void attach_function :archive_entry_set_fflags, [:pointer, :ulong, :ulong], :void attach_function :archive_entry_fflags_text, [:pointer], :string attach_function :archive_entry_gid, [:pointer], :gid_t attach_function :archive_entry_set_gid, [:pointer, :gid_t], :void attach_function :archive_entry_gname, [:pointer], :string attach_function :archive_entry_set_gname, [:pointer, :string], :void attach_function :archive_entry_hardlink, [:pointer], :string attach_function :archive_entry_set_hardlink, [:pointer, :string], :void attach_function :archive_entry_set_link, [:pointer, :string], :void attach_function :archive_entry_ino, [:pointer], :ino_t attach_function :archive_entry_set_ino, [:pointer, :ino_t], :void attach_function :archive_entry_mode, [:pointer], :mode_t attach_function :archive_entry_set_mode, [:pointer, :mode_t], :void attach_function :archive_entry_set_perm, [:pointer, :mode_t], :void attach_function :archive_entry_nlink, [:pointer], :uint attach_function :archive_entry_set_nlink, [:pointer, :uint], :void attach_function :archive_entry_pathname, [:pointer], :string attach_function :archive_entry_set_pathname, [:pointer, :string], :void attach_function :archive_entry_rdev, [:pointer], :dev_t attach_function :archive_entry_set_rdev, [:pointer, :dev_t], :void attach_function :archive_entry_rdevmajor, [:pointer], :dev_t attach_function :archive_entry_set_rdevmajor, [:pointer, :dev_t], :void attach_function :archive_entry_rdevminor, [:pointer], :dev_t attach_function :archive_entry_set_rdevminor, [:pointer, :dev_t], :void attach_function :archive_entry_size, [:pointer], :int64_t attach_function :archive_entry_set_size, [:pointer, :int64_t], :void attach_function_maybe :archive_entry_unset_size, [:pointer], :void attach_function_maybe :archive_entry_size_is_set, [:pointer], :int attach_function :archive_entry_sourcepath, [:pointer], :string attach_function :archive_entry_strmode, [:pointer], :string attach_function :archive_entry_symlink, [:pointer], :string attach_function :archive_entry_set_symlink, [:pointer, :string], :void attach_function :archive_entry_uid, [:pointer], :uid_t attach_function :archive_entry_set_uid, [:pointer, :uid_t], :void attach_function :archive_entry_uname, [:pointer], :string attach_function :archive_entry_set_uname, [:pointer, :string], :void attach_function :archive_entry_copy_stat, [:pointer, :pointer], :void attach_function :archive_entry_copy_fflags_text, [:pointer, :string], :string attach_function :archive_entry_copy_gname, [:pointer, :string], :string attach_function :archive_entry_copy_uname, [:pointer, :string], :string attach_function :archive_entry_copy_hardlink, [:pointer, :string], :string attach_function :archive_entry_copy_link, [:pointer, :string], :string attach_function :archive_entry_copy_symlink, [:pointer, :string], :string attach_function :archive_entry_copy_sourcepath, [:pointer, :string], :string attach_function :archive_entry_copy_pathname, [:pointer, :string], :string attach_function :archive_entry_xattr_clear, [:pointer], :void attach_function :archive_entry_xattr_add_entry, [:pointer, :string, :pointer, :size_t], :void attach_function :archive_entry_xattr_count, [:pointer], :int attach_function :archive_entry_xattr_reset, [:pointer], :int attach_function :archive_entry_xattr_next, [:pointer, :pointer, :pointer, :pointer], :int EOF = 1 OK = 0 RETRY = (-10) WARN = (-20) FAILED = (-25) FATAL = (-30) DATA_BUFFER_SIZE = 2**16 end COMPRESSION_NONE = 0 COMPRESSION_GZIP = 1 COMPRESSION_BZIP2 = 2 COMPRESSION_COMPRESS = 3 COMPRESSION_PROGRAM = 4 COMPRESSION_LZMA = 5 COMPRESSION_XZ = 6 COMPRESSION_UU = 7 COMPRESSION_RPM = 8 FORMAT_BASE_MASK = 0xff0000 FORMAT_CPIO = 0x10000 FORMAT_CPIO_POSIX = (FORMAT_CPIO | 1) FORMAT_CPIO_BIN_LE = (FORMAT_CPIO | 2) FORMAT_CPIO_BIN_BE = (FORMAT_CPIO | 3) FORMAT_CPIO_SVR4_NOCRC = (FORMAT_CPIO | 4) FORMAT_CPIO_SVR4_CRC = (FORMAT_CPIO | 5) FORMAT_SHAR = 0x20000 FORMAT_SHAR_BASE = (FORMAT_SHAR | 1) FORMAT_SHAR_DUMP = (FORMAT_SHAR | 2) FORMAT_TAR = 0x30000 FORMAT_TAR_USTAR = (FORMAT_TAR | 1) FORMAT_TAR_PAX_INTERCHANGE = (FORMAT_TAR | 2) FORMAT_TAR_PAX_RESTRICTED = (FORMAT_TAR | 3) FORMAT_TAR_GNUTAR = (FORMAT_TAR | 4) FORMAT_ISO9660 = 0x40000 FORMAT_ISO9660_ROCKRIDGE = (FORMAT_ISO9660 | 1) FORMAT_ZIP = 0x50000 FORMAT_EMPTY = 0x60000 FORMAT_AR = 0x70000 FORMAT_AR_GNU = (FORMAT_AR | 1) FORMAT_AR_BSD = (FORMAT_AR | 2) FORMAT_MTREE = 0x80000 FORMAT_RAW = 0x90000 FORMAT_XAR = 0xA0000 EXTRACT_OWNER = (0x0001) EXTRACT_PERM = (0x0002) EXTRACT_TIME = (0x0004) EXTRACT_NO_OVERWRITE = (0x0008) EXTRACT_UNLINK = (0x0010) EXTRACT_ACL = (0x0020) EXTRACT_FFLAGS = (0x0040) EXTRACT_XATTR = (0x0080) EXTRACT_SECURE_SYMLINKS = (0x0100) EXTRACT_SECURE_NODOTDOT = (0x0200) EXTRACT_NO_AUTODIR = (0x0400) EXTRACT_NO_OVERWRITE_NEWER = (0x0800) EXTRACT_SPARSE = (0x1000) def self.read_open_filename file_name, command = nil, &block Reader.open_filename file_name, command, &block end def self.read_open_memory string, command = nil, &block Reader.open_memory string, command, &block end def self.write_open_filename file_name, compression, format, &block Writer.open_filename file_name, compression, format, &block end def self.write_open_memory string, compression, format, &block Writer.open_memory string, compression, format, &block end def self.version_number C::archive_version_number end def self.version_string C::archive_version_string end class Error < StandardError def initialize(archive) if archive.kind_of? String super archive else super "#{C::archive_error_string(archive)}" end end end class BaseArchive def initialize alloc, free @archive = nil @archive_free = nil @archive = alloc.call @archive_free = [nil] raise Error, @archive unless @archive @archive_free[0] = free ObjectSpace.define_finalizer( self, BaseArchive.finalizer(@archive, @archive_free) ) end def self.finalizer archive, archive_free Proc.new do |*args| archive_free[0].call(archive) if archive_free[0] end end def close # TODO: do we need synchronization here? if @archive # TODO: Error check? @archive_free[0].call(@archive) end ensure @archive = nil @archive_free[0] = nil @data = nil end def archive raise Error, "No archive open" unless @archive @archive end protected :archive def error_string C::archive_error_string(@archive) end def errno C::archive_errno(@archive) end end end
patcon/ffi-libarchive
lib/ffi-libarchive/archive.rb
Ruby
gpl-3.0
13,613
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>cfitsTK: src/img_reduce/img_reduce.h File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">cfitsTK </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('img__reduce_8h.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">img_reduce.h File Reference</div> </div> </div><!--header--> <div class="contents"> <p><a href="img__reduce_8h_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:af3d15b471345b3248a1f0e1366bdbea9"><td class="memItemLeft" align="right" valign="top">int_fast8_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="img__reduce_8h.html#af3d15b471345b3248a1f0e1366bdbea9">init_img_reduce</a> ()</td></tr> <tr class="separator:af3d15b471345b3248a1f0e1366bdbea9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a937c6898a9899ac3f4035b970ec2a0bc"><td class="memItemLeft" align="right" valign="top">long&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="img__reduce_8h.html#a937c6898a9899ac3f4035b970ec2a0bc">IMG_REDUCE_cleanbadpix_fast</a> (const char *IDname, const char *IDbadpix_name, const char *IDoutname)</td></tr> <tr class="separator:a937c6898a9899ac3f4035b970ec2a0bc"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a94b3c5e62355eb83af8352a0f97cbc92"><td class="memItemLeft" align="right" valign="top">long&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="img__reduce_8h.html#a94b3c5e62355eb83af8352a0f97cbc92">IMG_REDUCE_cubesimplestat</a> (const char *IDin_name)</td></tr> <tr class="separator:a94b3c5e62355eb83af8352a0f97cbc92"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aa81da45369eb27d714946b96d9d0e604"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="img__reduce_8h.html#aa81da45369eb27d714946b96d9d0e604">IMG_REDUCE_cubeprocess</a> (const char *IDin_name)</td></tr> <tr class="separator:aa81da45369eb27d714946b96d9d0e604"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function Documentation</h2> <a class="anchor" id="a937c6898a9899ac3f4035b970ec2a0bc"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">long IMG_REDUCE_cleanbadpix_fast </td> <td>(</td> <td class="paramtype">const char *&#160;</td> <td class="paramname"><em>IDname</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const char *&#160;</td> <td class="paramname"><em>IDbadpix_name</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const char *&#160;</td> <td class="paramname"><em>IDoutname</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="aa81da45369eb27d714946b96d9d0e604"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int IMG_REDUCE_cubeprocess </td> <td>(</td> <td class="paramtype">const char *&#160;</td> <td class="paramname"><em>IDin_name</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>this is the main routine to pre-process a cube stream of images (PSFs)</p> <p>Optional inputs: calib_darkim (single frame or cube) calib_badpix (single frame) calib_flat </p> <p>remove dark</p> <p>remove bad pixels</p> <p>compute photocenter </p> </div> </div> <a class="anchor" id="a94b3c5e62355eb83af8352a0f97cbc92"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">long IMG_REDUCE_cubesimplestat </td> <td>(</td> <td class="paramtype">const char *&#160;</td> <td class="paramname"><em>IDin_name</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>compute ave, RMS </p> </div> </div> <a class="anchor" id="af3d15b471345b3248a1f0e1366bdbea9"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int_fast8_t init_img_reduce </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_2023aa0f1a7d7dd6bbe7e3d622e6aa1b.html">img_reduce</a></li><li class="navelem"><a class="el" href="img__reduce_8h.html">img_reduce.h</a></li> <li class="footer">Generated on Mon Sep 4 2017 19:29:34 for cfitsTK by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.9.1 </li> </ul> </div> </body> </html>
oguyon/Cfits
html/img__reduce_8h.html
HTML
gpl-3.0
9,452
/* Copyright 1991, 1994, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. 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 OPEN GROUP 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. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <X11/Xosdefs.h> #include <stdlib.h> #include <X11/fonts/fontmisc.h> #include "stubs.h" #define XK_LATIN1 #include <X11/keysymdef.h> #ifdef __SUNPRO_C #pragma weak serverGeneration #pragma weak register_fpe_functions #endif extern void BuiltinRegisterFpeFunctions(void); /* make sure everything initializes themselves at least once */ extern unsigned long serverGeneration; unsigned long __GetServerGeneration (void); unsigned long __GetServerGeneration (void) { OVERRIDE_DATA(serverGeneration); return serverGeneration; } weak void register_fpe_functions (void) { OVERRIDE_SYMBOL(register_fpe_functions); BuiltinRegisterFpeFunctions(); FontFileRegisterFpeFunctions(); #ifdef XFONT_FC fs_register_fpe_functions(); #endif }
ArcticaProject/vcxsrv
libXfont/src/util/miscutil.c
C
gpl-3.0
1,960
using System; using System.Reflection; using Sigil; using WowPacketParser.Hotfix; using WowPacketParser.Misc; namespace WowPacketParserModule.V7_0_3_22248.Hotfix { [HotfixSerializer] public class HotfixSerializer<T> : IHotfixSerializer<T> where T : class, new() { public override void GenerateDeserializer() { try { var deserializationEmitter = Emit<Func<Packet, T>>.NewDynamicMethod(); var deserializationResultLocal = deserializationEmitter.DeclareLocal<T>(); deserializationEmitter.NewObject<T>(); deserializationEmitter.StoreLocal(deserializationResultLocal); foreach (var propInfo in typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (propInfo.GetGetMethod() == null || propInfo.GetSetMethod() == null || !ShouldRead(propInfo)) continue; var propType = propInfo.PropertyType; var isArray = propType.IsArray; deserializationEmitter.LoadLocal(deserializationResultLocal); if (!isArray) { deserializationEmitter.LoadArgument(0); deserializationEmitter.LoadConstant(propInfo.Name); deserializationEmitter.LoadConstant(0); deserializationEmitter.NewArray<object>(); deserializationEmitter.CallVirtual(_binaryReaders[Type.GetTypeCode(propType)]); deserializationEmitter.Call(propInfo.GetSetMethod()); } else { var hotfixAttr = propInfo.GetCustomAttribute<HotfixArrayAttribute>(); deserializationEmitter.LoadConstant(hotfixAttr.Size); deserializationEmitter.NewArray(propType.GetElementType()); deserializationEmitter.CallVirtual(propInfo.GetSetMethod()); var loopBodyLabel = deserializationEmitter.DefineLabel(); var loopConditionLabel = deserializationEmitter.DefineLabel(); using (var iterationLocal = deserializationEmitter.DeclareLocal<int>()) { deserializationEmitter.LoadConstant(0); deserializationEmitter.StoreLocal(iterationLocal); deserializationEmitter.Branch(loopConditionLabel); deserializationEmitter.MarkLabel(loopBodyLabel); deserializationEmitter.LoadLocal(deserializationResultLocal); deserializationEmitter.CallVirtual(propInfo.GetGetMethod()); deserializationEmitter.LoadLocal(iterationLocal); deserializationEmitter.LoadArgument(0); deserializationEmitter.LoadConstant(propInfo.Name); deserializationEmitter.LoadConstant(1); deserializationEmitter.NewArray<object>(); deserializationEmitter.Duplicate(); deserializationEmitter.LoadConstant(0); deserializationEmitter.LoadLocal(iterationLocal); deserializationEmitter.Box<int>(); deserializationEmitter.StoreElement<object>(); deserializationEmitter.CallVirtual(_binaryReaders[Type.GetTypeCode(propType.GetElementType())]); deserializationEmitter.StoreElement(propType.GetElementType()); deserializationEmitter.LoadLocal(iterationLocal); deserializationEmitter.LoadConstant(1); deserializationEmitter.Add(); deserializationEmitter.StoreLocal(iterationLocal); deserializationEmitter.MarkLabel(loopConditionLabel); deserializationEmitter.LoadLocal(iterationLocal); deserializationEmitter.LoadConstant(hotfixAttr.Size); deserializationEmitter.CompareLessThan(); deserializationEmitter.BranchIfTrue(loopBodyLabel); } } } deserializationEmitter.LoadLocal(deserializationResultLocal); deserializationEmitter.Return(); _deserializer = deserializationEmitter.CreateDelegate(); } catch (SigilVerificationException sve) { Console.WriteLine(sve); } } } }
Carbenium/WowPacketParser
WowPacketParserModule.V7_0_3_22248/Hotfix/HotfixSerializer.cs
C#
gpl-3.0
4,879
/* * This file is part of SpellChecker plugin for Code::Blocks Studio * Copyright (C) 2009 Daniel Anselmi * * SpellChecker plugin is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * SpellChecker plugin is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SpellChecker. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef __HUNSPELL_CHECK_INTERFACE__ #define __HUNSPELL_CHECK_INTERFACE__ // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/string.h" // spell checker/thingie #include "wx/process.h" #include "wx/txtstrm.h" #include "wx/file.h" #include "SpellCheckUserInterface.h" #include "PersonalDictionary.h" // Get rid of the warning about identifiers being truncated in the debugger. Using the STL collections // will produce this everywhere. Must disable at beginning of stdafx.h because it doesn't work if // placed elsewhere. #ifdef __VISUALC__ #pragma warning(disable:4786) #endif class Hunspell; class HunspellInterface : public wxSpellCheckEngineInterface { public: HunspellInterface(wxSpellCheckUserInterface* pDlg = NULL); ~HunspellInterface(); // Spell Checker functions virtual wxString GetSpellCheckEngineName() { return _T("Hunspell"); } virtual int InitializeSpellCheckEngine(); virtual int UninitializeSpellCheckEngine(); virtual int SetOption(SpellCheckEngineOption& Option); virtual void UpdatePossibleValues(SpellCheckEngineOption& OptionDependency, SpellCheckEngineOption& OptionToUpdate); virtual wxString CheckSpelling(wxString strText); wxArrayString GetSuggestions(const wxString& strMisspelledWord); virtual bool IsWordInDictionary(const wxString& strWord); virtual int AddWordToDictionary(const wxString& strWord); virtual int RemoveWordFromDictionary(const wxString& strWord); virtual wxArrayString GetWordListAsArray(); void OpenPersonalDictionary(const wxString& strPersonalDictionaryFile); PersonalDictionary* GetPersonalDictionary() { return &m_PersonalDictionary; } void AddCustomMySpellDictionary(const wxString& strDictionaryName, const wxString& strDictionaryFileRoot); void CleanCustomMySpellDictionaries() { m_CustomMySpellDictionaryMap.clear(); } virtual wxString GetCharacterEncoding(); private: void PopulateDictionaryMap(StringToStringMap* pLookupMap, const wxString& strDictionaryPath); void AddDictionaryElement(StringToStringMap* pLookupMap, const wxString& strDictionaryPath, const wxString& strDictionaryName, const wxString& strDictionaryFileRoot); wxString GetSelectedLanguage(); wxString GetAffixFileName(); wxString GetAffixFileName(const wxString& strDictionaryName); wxString GetDictionaryFileName(); wxString GetDictionaryFileName(const wxString& strDictionaryName); Hunspell* m_pHunspell; StringToStringMap m_DictionaryLookupMap; StringToStringMap m_CustomMySpellDictionaryMap; wxString m_strDictionaryPath; PersonalDictionary m_PersonalDictionary; }; #endif // __MYSPELL_CHECK_INTERFACE__
simple-codeblocks/Codeblocks
src/plugins/contrib/SpellChecker/HunspellInterface.h
C
gpl-3.0
3,623
/* This file is part of White - Storm: Lightning (alpha). Copyright 2012 Christopher Augustus Greeley White - Storm: Lightning (alpha) is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. White - Storm: Lightning (alpha) is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with White - Storm: Lightning (alpha). If not, see <http://www.gnu.org/licenses/>. */ #include "Singleton Sender.h" namespace WSL { static void (* Recurse )( WSL::Singleton* ); static void LuaRegister( WSL::Engine* engine ) { luabind::open( engine->luaContainer->State ); //-----Component-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Base::Component>( "Component" ) .def( luabind::constructor<>() ) .def( "GetElement", &WSL::Components::Base::Component::GetElement ) .def( "GetID", &WSL::Components::Base::Component::GetID ) .def( "GetObjectID", &WSL::Components::Base::Component::GetObjectID ) .def( "GetComponentID", &WSL::Components::Base::Component::GetComponentID ) .def( "GetUpdateData", &WSL::Components::Base::Component::GetUpdateData ) .def( "SetElement", &WSL::Components::Base::Component::SetElement ) .def( "SetUpdateData", &WSL::Components::Base::Component::SetUpdateData ) ]; //-----sf::Color-----// luabind::module( engine->luaContainer->State )[ luabind::class_<sf::Color>( "SFMLColor" ) .def( luabind::constructor<>() ) ]; //-----Wrapped Color-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Scripting::Lua::ColorWrap>( "ColorWrap" ) .def( luabind::constructor< unsigned short, unsigned short, unsigned short >() ) .def( luabind::constructor< sf::Color >() ) .def( luabind::constructor<>() ) .def( "SetColor", &WSL::Containers::Scripting::Lua::ColorWrap::SetColor ) .def( "GetColor", &WSL::Containers::Scripting::Lua::ColorWrap::GetColor ) ]; //-----Animation Data-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Algorithimic::Base::AnimationData>( "AnimationData" ) .def( luabind::constructor<>() ) ]; //-----All Animaition Data-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Algorithimic::SubBase::AllAnimationData, WSL::Components::Algorithimic::Base::AnimationData>( "AllAnimationData" ) .def( luabind::constructor<>() ) ]; //-----Animation-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Algorithimic::Animation, WSL::Components::Algorithimic::Base::AnimationData>( "Animation" ) .def( luabind::constructor<>() ) .def( "GetAnimate", &WSL::Components::Algorithimic::Animation::GetAnimate ) .def( "GetDelay", &WSL::Components::Algorithimic::Animation::GetDelay ) .def( "GetSize", &WSL::Components::Algorithimic::Animation::GetSize ) .def( "GetType", &WSL::Components::Algorithimic::Animation::GetType ) .def( "SetAnimate", &WSL::Components::Algorithimic::Animation::SetAnimate ) .def( "SetCurrentFrame", &WSL::Components::Algorithimic::Animation::SetCurrentFrame ) .def( "SetDelay", &WSL::Components::Algorithimic::Animation::SetDelay ) .def( "SetType", (void(WSL::Components::Algorithimic::Animation::*)(bool))&WSL::Components::Algorithimic::Animation::SetType ) .def( "AddImage", &WSL::Components::Algorithimic::Animation::AddImage ) .def( "AnimateImages", &WSL::Components::Algorithimic::Animation::AnimateImages ) .def( "AnimateSheet", &WSL::Components::Algorithimic::Animation::AnimateSheet ) .def( "DeleteImage", &WSL::Components::Algorithimic::Animation::DeleteImage ) .def( "GatherData", &WSL::Components::Algorithimic::Animation::GatherData ) .def( "ReplaceData", &WSL::Components::Algorithimic::Animation::ReplaceData ) .def( "Reset", &WSL::Components::Algorithimic::Animation::Reset ) .def( "Restore", &WSL::Components::Algorithimic::Animation::Restore ) .def( "SetUpSpriteSheet", (void(WSL::Components::Algorithimic::Animation::*)(int,int,int,int,int,int,bool,bool))&WSL::Components::Algorithimic::Animation::SetUpSpriteSheet ) .def( "SetUpSpriteSheet", (void(WSL::Components::Algorithimic::Animation::*)(int,int,int,int,int,int,int,int,bool,bool))&WSL::Components::Algorithimic::Animation::SetUpSpriteSheet ) ]; //-----Render Functional-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Rendering_System::Base::RenderFunctonal, WSL::Components::Base::Component>( "RenderFunctonal" ) .def( luabind::constructor<>() ) .def( "SetRenderLayer", &WSL::Components::Rendering_System::Base::RenderFunctonal::SetRenderLayerName ) .def( "GetRenderLayer", &WSL::Components::Rendering_System::Base::RenderFunctonal::GetRenderLayerName ) ]; //-----Lightning Sprite-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Rendering_System::Base::Render_Base<sf::Sprite>, WSL::Components::Rendering_System::Base::RenderFunctonal>( "RenderBase" ) .def( luabind::constructor<>() ) ]; luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Rendering_System::Base::SubBase::SFMLType<sf::Sprite>, WSL::Components::Rendering_System::Base::Render_Base<sf::Sprite>>( "SFMLType" ) .def( luabind::constructor<>() ) ]; luabind::module( engine->luaContainer->State )[ luabind::class_< WSL::Components::LightningSprite, WSL::Components::Rendering_System::Base::SubBase::SFMLType< sf::Sprite > >( "LightningSprite" ) .def( luabind::constructor<>() ) .def( "Rotate", &WSL::Components::LightningSprite::Rotate ) .def( "Resize", (void(WSL::Components::LightningSprite::*)(float,float))&WSL::Components::LightningSprite::Resize ) .def( "Resize", (void(WSL::Components::LightningSprite::*)(float))&WSL::Components::LightningSprite::Resize ) .def( "AddAnimation", &WSL::Components::LightningSprite::AddAnimation ) .def( "SetImage", &WSL::Components::LightningSprite::SetImage ) .def( "SetUpSprite", (void(WSL::Components::LightningSprite::*)(float,float,bool))&WSL::Components::LightningSprite::SetUpSprite ) .def( "SetUpSprite", (void(WSL::Components::LightningSprite::*)(float,float,unsigned int,bool,WSL::Global::ImageLibrary*))&WSL::Components::LightningSprite::SetUpSprite ) .def( "SetUpSprite", (void(WSL::Components::LightningSprite::*)(unsigned int,bool, WSL::Global::ImageLibrary*))&WSL::Components::LightningSprite::SetUpSprite ) .def( "Scale", (void(WSL::Components::LightningSprite::*)(float,float))&WSL::Components::LightningSprite::Scale ) .def( "Scale", (void(WSL::Components::LightningSprite::*)(float))&WSL::Components::LightningSprite::Scale) .def( "SetImage", &WSL::Components::LightningSprite::SetImage ) .def( "GetPosition", &WSL::Components::LightningSprite::GetPosition ) .def( "SetPosition", (void(WSL::Components::LightningSprite::*)(float,float))&WSL::Components::LightningSprite::SetPosition ) .def( "SetPosition", (void(WSL::Components::LightningSprite::*)(float,float,float))&WSL::Components::LightningSprite::SetPosition ) .def( "SetPosition", (void(WSL::Components::LightningSprite::*)(WSL::Containers::Base::XYZ))&WSL::Components::LightningSprite::SetPosition ) .def( "SetDraw", &WSL::Components::LightningSprite::SetDraw ) .def( "GetDraw", &WSL::Components::LightningSprite::GetDraw ) .def( "AddAnimationToSingleton", &WSL::Components::LightningSprite::AddAnimationToSingleton ) .def( "AddAnimation", &WSL::Components::LightningSprite::AddAnimation ) .def( "SetAnimate", &WSL::Components::LightningSprite::SetAnimate ) .def( "SetCurrentAnimation", &WSL::Components::LightningSprite::SetCurrentAnimation ) .def( "SetAnimateFistToLast", &WSL::Components::LightningSprite::SetAnimateFirstToLast ) .def( "SetRefrence", &WSL::Components::LightningSprite::SetRefrence ) .def( "GetAnimate", &WSL::Components::LightningSprite::GetAnimate ) .def( "GetCurrentAnimation", &WSL::Components::LightningSprite::GetCurrentAnimation ) .def( "GetAnimateFirstToLast", &WSL::Components::LightningSprite::GetAnimateFirstToLast ) .def( "DeleteRefrence", &WSL::Components::LightningSprite::DeleteRefrence ) .def( "SendAnimation", &WSL::Components::LightningSprite::SendAnimation ) ]; //-----Polygon-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Rendering_System::Base::Render_Base<sf::Shape>, WSL::Components::Rendering_System::Base::RenderFunctonal>( "RenderBase" ) .def( luabind::constructor<>() ) .def( "AddPoint", (void(WSL::Components::Polygon::*)(float,float,float))&WSL::Components::Polygon::AddPoint) .def( "AddPoint", (void(WSL::Components::Polygon::*)(float,float))&WSL::Components::Polygon::AddPoint) .def( "AddPoint", (void(WSL::Components::Polygon::*)(WSL::Containers::Base::XYZ))&WSL::Components::Polygon::AddPoint) .def( "Rotate", &WSL::Components::Polygon::Rotate ) .def( "SetDraw", &WSL::Components::Polygon::SetDraw ) .def( "GetDraw", &WSL::Components::Polygon::GetDraw ) .def( "SetColor", (void(WSL::Components::Polygon::*)(WSL::Containers::Scripting::Lua::ColorWrap))&WSL::Components::Polygon::SetColor ) .def( "SetColor", (void(WSL::Components::Polygon::*)(sf::Color))&WSL::Components::Polygon::SetColor ) .def( "GetColor", &WSL::Components::Polygon::GetColor ) ]; luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Rendering_System::Base::SubBase::SFMLType<sf::Shape>, WSL::Components::Rendering_System::Base::Render_Base<sf::Shape>>( "SFMLType" ) .def( luabind::constructor<>() ) ]; luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Polygon, WSL::Components::Rendering_System::Base::SubBase::SFMLType<sf::Shape> >( "LightningSprite" ) .def( luabind::constructor<>() ) .def( "Rotate", &WSL::Components::Polygon::Rotate ) .def( "Scale", (void(WSL::Components::Polygon::*)(float,float))&WSL::Components::Polygon::Scale ) .def( "Scale", (void(WSL::Components::Polygon::*)(float))&WSL::Components::Polygon::Scale ) .def( "GetPosition", &WSL::Components::Polygon::GetPosition ) .def( "SetPosition", (void(WSL::Components::Polygon::*)(float,float))&WSL::Components::Polygon::SetPosition ) .def( "SetPosition", (void(WSL::Components::Polygon::*)(float,float,float))&WSL::Components::Polygon::SetPosition ) .def( "SetPosition", (void(WSL::Components::Polygon::*)(WSL::Containers::Base::XYZ))&WSL::Components::Polygon::SetPosition ) .def( "SetDraw", &WSL::Components::Polygon::SetDraw ) .def( "GetDraw", &WSL::Components::Polygon::GetDraw ) ]; //-----Vector Graphics-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::VectorGraphicsComponent, WSL::Components::Rendering_System::Base::RenderFunctonal>( "VectorGraphicsComponent" ) .def( luabind::constructor<>() ) ]; luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::Rendering_System::Base::Render_Base<WSL::Components::VectorGraphicsComponent>, WSL::Components::Rendering_System::Base::RenderFunctonal>( "RenderBase" ) .def( luabind::constructor<>() ) ]; luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Components::VectorGraphics, WSL::Components::Rendering_System::Base::Render_Base<WSL::Components::VectorGraphicsComponent>>( "VectorGraphics" ) .def( luabind::constructor<>() ) .def( "Rotate", &WSL::Components::VectorGraphics::Rotate ) .def( "SetDraw", &WSL::Components::VectorGraphics::SetDraw ) .def( "GetDraw", &WSL::Components::VectorGraphics::GetDraw ) .def( "SetColor", (void(WSL::Components::VectorGraphics::*)( WSL::Containers::Scripting::Lua::ColorWrap ))&WSL::Components::VectorGraphics::SetColor ) .def( "SetColor", (void(WSL::Components::VectorGraphics::*)( sf::Color ))&WSL::Components::VectorGraphics::SetColor ) .def( "GetColor", &WSL::Components::VectorGraphics::GetColor ) ]; //-----XYZ Base-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Base::XYZB>( "XYZB" ) .def( luabind::constructor<>() ) .def( "GetX", &WSL::Containers::Base::XYZ::GetX ) .def( "GetY", &WSL::Containers::Base::XYZ::GetY ) .def( "GetZ", &WSL::Containers::Base::XYZ::GetZ ) .def( "SetX", &WSL::Containers::Base::XYZ::SetX ) .def( "SetY", &WSL::Containers::Base::XYZ::SetY ) .def( "SetZ", &WSL::Containers::Base::XYZ::SetZ ) ]; //-----XYZ-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Base::XYZ, WSL::Containers::Base::XYZB>( "XYZ" ) .def( luabind::constructor<>() ) .def( "GetX", &WSL::Containers::Base::XYZ::GetX ) .def( "GetY", &WSL::Containers::Base::XYZ::GetY ) .def( "GetZ", &WSL::Containers::Base::XYZ::GetZ ) .def( "SetX", &WSL::Containers::Base::XYZ::SetX ) .def( "SetY", &WSL::Containers::Base::XYZ::SetY ) .def( "SetZ", &WSL::Containers::Base::XYZ::SetZ ) ]; //-----Vector-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Math::Vector>( "Vector" ) .def( luabind::constructor<>() ) .def( "CalculateVector", &WSL::Containers::Math::Vector::CalculateVector ) .def( "GetDestination", &WSL::Containers::Math::Vector::GetDestination ) .def( "GetDestinationX", &WSL::Containers::Math::Vector::GetDestinationX ) .def( "GetDestinationY", &WSL::Containers::Math::Vector::GetDestinationY ) .def( "GetDestinationZ", &WSL::Containers::Math::Vector::GetDestinationZ ) .def( "GetPosition", &WSL::Containers::Math::Vector::GetPosition ) .def( "GetThreeDimentional", &WSL::Containers::Math::Vector::GetThreeDimentional ) .def( "GetVector", &WSL::Containers::Math::Vector::GetVector ) .def( "GetX", &WSL::Containers::Math::Vector::GetX ) .def( "GetY", &WSL::Containers::Math::Vector::GetY ) .def( "GetZ", &WSL::Containers::Math::Vector::GetZ ) .def( "GetSpeed", &WSL::Containers::Math::Vector::GetSpeed ) .def( "Move", &WSL::Containers::Math::Vector::Move ) .def( "SetDestination", (void(WSL::Containers::Math::Vector::*)(float))&WSL::Containers::Math::Vector::SetDestination ) .def( "SetDestination", (void(WSL::Containers::Math::Vector::*)(float,float))&WSL::Containers::Math::Vector::SetDestination ) .def( "SetDestination", (void(WSL::Containers::Math::Vector::*)(float,float,float))&WSL::Containers::Math::Vector::SetDestination ) .def( "SetDestination", (void(WSL::Containers::Math::Vector::*)(WSL::Containers::Base::XYZ))&WSL::Containers::Math::Vector::SetDestination ) .def( "SetPosition", &WSL::Containers::Math::Vector::SetPosition ) .def( "SetSpeed", &WSL::Containers::Math::Vector::SetSpeed ) .def( "SetThreeDimentional", &WSL::Containers::Math::Vector::SetThreeDimentional ) .def( "SetVector", &WSL::Containers::Math::Vector::SetVector ) ]; //-----Bool XYZ-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::BoolXYZ>( "BoolXYZ" ) .def( luabind::constructor<>() ) .def( "GetBooleanValue", &WSL::Containers::BoolXYZ::GetBooleanValue ) .def( "GetCoordinates", &WSL::Containers::BoolXYZ::GetCoordinates ) .def( "SetBooleanValue", &WSL::Containers::BoolXYZ::SetBooleanValue ) .def( "SetCoordinates", &WSL::Containers::BoolXYZ::SetCoordinates ) ]; //-----Rectangle-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Collision::ScanAreaCollision::Rectangle>( "Rectangle__" ) .def( luabind::constructor<>() ) .def_readwrite( "x", &WSL::Collision::ScanAreaCollision::Rectangle::x ) .def_readwrite( "y", &WSL::Collision::ScanAreaCollision::Rectangle::y ) .def_readwrite( "z", &WSL::Collision::ScanAreaCollision::Rectangle::z ) .def_readwrite( "w", &WSL::Collision::ScanAreaCollision::Rectangle::w ) .def_readwrite( "h", &WSL::Collision::ScanAreaCollision::Rectangle::h ) .def_readwrite( "l", &WSL::Collision::ScanAreaCollision::Rectangle::l ) ]; //-----IDXYZ-----// luabind::module( engine->luaContainer->State )[ luabind::class_< WSL::Containers::IDXYZ >( "IDXYZ" ) .def( luabind::constructor<>() ) .def( "GetID", &WSL::Containers::IDXYZ::GetID ) .def( "GetObjectID", &WSL::Containers::IDXYZ::GetObjectID ) .def( "GetComponentID", &WSL::Containers::IDXYZ::GetComponentID ) .def( "GetPoint", &WSL::Containers::IDXYZ::GetPoint ) .def( "SetID", &WSL::Containers::IDXYZ::SetID ) .def( "SetObjectID", &WSL::Containers::IDXYZ::SetObjectID ) .def( "SetComponentID", &WSL::Containers::IDXYZ::SetComponentID ) .def( "SetPoint", &WSL::Containers::IDXYZ::SetPoint ) ]; //-----Scan Area-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Collision::ScanAreaCollision::ScanArea, WSL::Components::Base::Component>( "ScanArea" ) .def( luabind::constructor<>() ) .def( "GetCollide", &WSL::Collision::ScanAreaCollision::ScanArea::GetCollide ) .def( "SetCollide", &WSL::Collision::ScanAreaCollision::ScanArea::SetCollide ) .def( "GetCollision", &WSL::Collision::ScanAreaCollision::ScanArea::GetCollision ) .def( "SetCollision", &WSL::Collision::ScanAreaCollision::ScanArea::SetCollision ) .def( "SetX", &WSL::Collision::ScanAreaCollision::ScanArea::SetX ) .def( "SetY", &WSL::Collision::ScanAreaCollision::ScanArea::SetY ) .def( "SetZ", &WSL::Collision::ScanAreaCollision::ScanArea::SetZ ) .def( "GetX", &WSL::Collision::ScanAreaCollision::ScanArea::GetX ) .def( "GetY", &WSL::Collision::ScanAreaCollision::ScanArea::GetY ) .def( "GetZ", &WSL::Collision::ScanAreaCollision::ScanArea::GetZ ) .def( "GetVector", &WSL::Collision::ScanAreaCollision::ScanArea::GetVector ) .def( "SetVector", &WSL::Collision::ScanAreaCollision::ScanArea::SetVector ) .def( "SetLargeX", &WSL::Collision::ScanAreaCollision::ScanArea::SetLargeX ) .def( "SetSmallX", &WSL::Collision::ScanAreaCollision::ScanArea::SetSmallX ) .def( "SetLargeY", &WSL::Collision::ScanAreaCollision::ScanArea::SetLargeY ) .def( "SetSmallY", &WSL::Collision::ScanAreaCollision::ScanArea::SetSmallY ) .def( "SetLargeZ", &WSL::Collision::ScanAreaCollision::ScanArea::SetLargeZ ) .def( "SetSmallZ", &WSL::Collision::ScanAreaCollision::ScanArea::SetSmallZ ) .def( "GetLargeX", &WSL::Collision::ScanAreaCollision::ScanArea::GetLargeX ) .def( "GetSmallX", &WSL::Collision::ScanAreaCollision::ScanArea::GetSmallX ) .def( "GetLargeY", &WSL::Collision::ScanAreaCollision::ScanArea::GetLargeY ) .def( "GetSmallY", &WSL::Collision::ScanAreaCollision::ScanArea::GetSmallY ) .def( "GetLargeZ", &WSL::Collision::ScanAreaCollision::ScanArea::GetLargeZ ) .def( "GetSmallZ", &WSL::Collision::ScanAreaCollision::ScanArea::GetSmallZ ) .def( "GetBoundingBox", &WSL::Collision::ScanAreaCollision::ScanArea::GetBoundingBox ) .def( "SetBoundingBox", &WSL::Collision::ScanAreaCollision::ScanArea::SetBoundingBox ) .def( "GetR", &WSL::Collision::ScanAreaCollision::ScanArea::GetR ) .def( "SetR", &WSL::Collision::ScanAreaCollision::ScanArea::SetR ) .def( "GetACollisionData", &WSL::Collision::ScanAreaCollision::ScanArea::GetACollisionData ) .def( "GetCollisionDataSize", &WSL::Collision::ScanAreaCollision::ScanArea::GetCollisionDataSize ) .def( "ClearCollisionData", &WSL::Collision::ScanAreaCollision::ScanArea::ClearCollisionData ) .def( "AddCollisionData", &WSL::Collision::ScanAreaCollision::ScanArea::AddCollisionData ) ]; //-----Non class type-----// //-----int-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Scripting::Lua::LuaBindedType<int>>( "CppInt" ) .def( luabind::constructor<>() ) .def( "Get", &WSL::Containers::Scripting::Lua::LuaBindedType<int>::Get ) .def( "Set", &WSL::Containers::Scripting::Lua::LuaBindedType<int>::Set ) ]; //-----long long signed int-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Scripting::Lua::LuaBindedType<long long signed int>>( "CppLongInt" ) .def( luabind::constructor<>() ) .def( "Get", &WSL::Containers::Scripting::Lua::LuaBindedType<long long signed int>::Get ) .def( "Set", &WSL::Containers::Scripting::Lua::LuaBindedType<long long signed int>::Set ) ]; //-----double-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Scripting::Lua::LuaBindedType<double>>( "CppFloat" ) .def( luabind::constructor<>() ) .def( "Get", &WSL::Containers::Scripting::Lua::LuaBindedType<double>::Get ) .def( "Set", &WSL::Containers::Scripting::Lua::LuaBindedType<double>::Set ) ]; //-----boolean-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Scripting::Lua::LuaBindedType<bool>>( "CppBool" ) .def( luabind::constructor<>() ) .def( "Get", &WSL::Containers::Scripting::Lua::LuaBindedType<bool>::Get ) .def( "Set", &WSL::Containers::Scripting::Lua::LuaBindedType<bool>::Set ) ]; //-----Lua Manager-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::Scripting::LuaContainer>( "Stack" ) .def( luabind::constructor<>() ) .def( "AddInt", &WSL::Containers::Scripting::LuaContainer::AddInt ) .def( "AddLongInt", &WSL::Containers::Scripting::LuaContainer::AddLongInt ) .def( "AddFloat", &WSL::Containers::Scripting::LuaContainer::AddFloat ) .def( "GetInt", &WSL::Containers::Scripting::LuaContainer::GetIntegervalue ) .def( "GetLongInt", &WSL::Containers::Scripting::LuaContainer::GetLongInt ) .def( "GetFloat", &WSL::Containers::Scripting::LuaContainer::GetFloat ) .def( "SetInt", (void(WSL::Containers::Scripting::LuaContainer::*)(std::string,int))&WSL::Containers::Scripting::LuaContainer::SetVarible ) .def( "SetLongInt", (void(WSL::Containers::Scripting::LuaContainer::*)(std::string,long long signed int))&WSL::Containers::Scripting::LuaContainer::SetVarible ) .def( "SetFloat", (void(WSL::Containers::Scripting::LuaContainer::*)(std::string,double))&WSL::Containers::Scripting::LuaContainer::SetVarible ) .def( "SetInfo", &WSL::Containers::Scripting::LuaContainer::SetInfo ) ]; //-----Engine Struct-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Engine>( "Engine" ) .def( luabind::constructor<>() ) ]; //-----Input Class-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Global::Input>( "Input" ) .def( luabind::constructor<>() ) .def( "IsKeyDown", &WSL::Global::Input::IsKeyDown ) .def( "GetMouseClick", &WSL::Global::Input::GetMouseClick ) .def( "GetMouseEvent", &WSL::Global::Input::GetMouseEvent ) .def( "GetMousePosition", &WSL::Global::Input::GetMousePosition ) ]; //-----Base Entity-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Framework::Standard::Base::BaseEntity>( "BaseEntity" ) .def( luabind::constructor<>() ) ]; //-----Entity-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Framework::Standard::Base::Entity, WSL::Framework::Standard::Base::BaseEntity>( "Entity" ) .def( luabind::constructor<>() ) .def( "GetChild", &WSL::Framework::Standard::Base::Entity::GetChild ) .def( "GetComponentID", &WSL::Framework::Standard::Base::Entity::GetComponentID ) .def( "GetDestroy", &WSL::Framework::Standard::Base::Entity::GetDestroy ) .def( "GetDestroyScript", &WSL::Framework::Standard::Base::Entity::GetDestroyScript ) .def( "GetID", &WSL::Framework::Standard::Base::Entity::GetID ) .def( "GetInitializeScript", &WSL::Framework::Standard::Base::Entity::GetInitializeScript ) .def( "GetObjID", &WSL::Framework::Standard::Base::Entity::GetObjID ) .def( "GetOtherScript", &WSL::Framework::Standard::Base::Entity::GetOtherScript ) .def( "GetRefreshScript", &WSL::Framework::Standard::Base::Entity::GetRefreshScript ) .def( "RunScript", &WSL::Framework::Standard::Base::Entity::RunScript ) .def( "SendToLua", &WSL::Framework::Standard::Base::Entity::SendToLua ) .def( "SetChild", &WSL::Framework::Standard::Base::Entity::SetChild ) .def( "SetDestroy", &WSL::Framework::Standard::Base::Entity::SetDestroy ) .def( "SetDestroyScript", &WSL::Framework::Standard::Base::Entity::SetDestroyScript ) .def( "SetID", &WSL::Framework::Standard::Base::Entity::SetID ) .def( "SetInitializeScript", &WSL::Framework::Standard::Base::Entity::SetInitializeScript ) .def( "SetObjID", &WSL::Framework::Standard::Base::Entity::SetObjID ) .def( "SetOtherScript", &WSL::Framework::Standard::Base::Entity::SetOtherScript ) .def( "SetRefreshScript", &WSL::Framework::Standard::Base::Entity::SetResfreshScript ) ]; //-----Positional-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Framework::Standard::Positional, WSL::Framework::Standard::Base::Entity>( "Positional" ) .def( luabind::constructor<>() ) .def( "AddPolygon", &WSL::Framework::Standard::Positional::AddPolygon ) .def( "AddScanArea", &WSL::Framework::Standard::Positional::AddScanArea ) .def( "AddSprite", &WSL::Framework::Standard::Positional::AddSprite ) .def( "AddVectorGraphic", &WSL::Framework::Standard::Positional::AddVectorGraphic ) .def( "DeleteComponents", &WSL::Framework::Standard::Positional::DeleteComponents ) .def( "GetPosition", &WSL::Framework::Standard::Positional::GetPosition ) .def( "GetRotation", &WSL::Framework::Standard::Positional::GetRotation ) .def( "GetChild", &WSL::Framework::Standard::Positional::GetChild ) .def( "GetComponentID", &WSL::Framework::Standard::Positional::GetComponentID ) .def( "GetDestroy", &WSL::Framework::Standard::Positional::GetDestroy ) .def( "GetDestroyScript", &WSL::Framework::Standard::Positional::GetDestroyScript ) .def( "GetID", &WSL::Framework::Standard::Positional::GetID ) .def( "GetInitializeScript", &WSL::Framework::Standard::Positional::GetInitializeScript ) .def( "GetObjID", &WSL::Framework::Standard::Positional::GetObjID ) .def( "GetOtherScript", &WSL::Framework::Standard::Positional::GetOtherScript ) .def( "GetRefreshScript", &WSL::Framework::Standard::Positional::GetRefreshScript ) .def( "GetPhysicalBehavior", &WSL::Framework::Standard::Positional::GetPhysicalBehavior ) .def( "RunScript", &WSL::Framework::Standard::Positional::RunScript ) .def( "SendToLua", &WSL::Framework::Standard::Positional::SendToLua ) .def( "SetChild", &WSL::Framework::Standard::Positional::SetChild ) .def( "SetDestroy", &WSL::Framework::Standard::Positional::SetDestroy ) .def( "SetDestroyScript", &WSL::Framework::Standard::Positional::SetDestroyScript ) .def( "SetID", &WSL::Framework::Standard::Positional::SetID ) .def( "SetInitializeScript", &WSL::Framework::Standard::Positional::SetInitializeScript ) .def( "SetObjID", &WSL::Framework::Standard::Positional::SetObjID ) .def( "SetOtherScript", &WSL::Framework::Standard::Positional::SetOtherScript ) .def( "SetRefreshScript", &WSL::Framework::Standard::Positional::SetResfreshScript ) .def( "SetPosition", (void(WSL::Framework::Standard::Positional::*)(float,float))&WSL::Framework::Standard::Positional::SetPosition ) .def( "SetPosition", (void(WSL::Framework::Standard::Positional::*)(float,float,float))&WSL::Framework::Standard::Positional::SetPosition ) .def( "SetPosition", (void(WSL::Framework::Standard::Positional::*)(WSL::Containers::Base::XYZ))&WSL::Framework::Standard::Positional::SetPosition ) .def( "SetRotation", (void(WSL::Framework::Standard::Positional::*)(float))&WSL::Framework::Standard::Positional::SetRotation ) .def( "SetPhysicalBehavior", &WSL::Framework::Standard::Positional::SetPhysicalBehavior ) ]; //-----Mobile-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Framework::Standard::Mobile, WSL::Framework::Standard::Positional>( "Mobile" ) .def( luabind::constructor<>() ) .def( "AddPolygon", &WSL::Framework::Standard::Mobile::AddPolygon ) .def( "AddScanArea", &WSL::Framework::Standard::Mobile::AddScanArea ) .def( "AddSprite", &WSL::Framework::Standard::Mobile::AddSprite ) .def( "AddVectorGraphic", &WSL::Framework::Standard::Mobile::AddVectorGraphic ) .def( "Calculate", &WSL::Framework::Standard::Mobile::Calculate ) .def( "DeleteComponents", &WSL::Framework::Standard::Mobile::DeleteComponents ) .def( "GetAutoCalculate", &WSL::Framework::Standard::Mobile::GetAutoCalculate ) .def( "GetAutoMove", &WSL::Framework::Standard::Mobile::GetAutoMove ) .def( "GetPosition", &WSL::Framework::Standard::Mobile::GetPosition ) .def( "GetRotation", &WSL::Framework::Standard::Mobile::GetRotation ) .def( "GetChild", &WSL::Framework::Standard::Mobile::GetChild ) .def( "GetComponentID", &WSL::Framework::Standard::Mobile::GetComponentID ) .def( "GetDestroy", &WSL::Framework::Standard::Mobile::GetDestroy ) .def( "GetDestroyScript", &WSL::Framework::Standard::Mobile::GetDestroyScript ) .def( "GetID", &WSL::Framework::Standard::Mobile::GetID ) .def( "GetInitializeScript", &WSL::Framework::Standard::Mobile::GetInitializeScript ) .def( "GetObjID", &WSL::Framework::Standard::Mobile::GetObjID ) .def( "GetOtherScript", &WSL::Framework::Standard::Mobile::GetOtherScript ) .def( "GetRefreshScript", &WSL::Framework::Standard::Mobile::GetRefreshScript ) .def( "GetVector", &WSL::Framework::Standard::Mobile::GetVector ) .def( "GetPhysicalBehavior", &WSL::Framework::Standard::Mobile::GetPhysicalBehavior ) .def( "Move", &WSL::Framework::Standard::Mobile::Move ) .def( "RunScript", &WSL::Framework::Standard::Mobile::RunScript ) .def( "SendToLua", &WSL::Framework::Standard::Mobile::SendToLua ) .def( "SetAutoCalculate", &WSL::Framework::Standard::Mobile::SetAutoCalculate ) .def( "SetChild", &WSL::Framework::Standard::Mobile::SetChild ) .def( "SetDestroy", &WSL::Framework::Standard::Mobile::SetDestroy ) .def( "SetDestroyScript", &WSL::Framework::Standard::Mobile::SetDestroyScript ) .def( "SetDestination", (void(WSL::Framework::Standard::Mobile::*)(float))&WSL::Framework::Standard::Mobile::SetDestination ) .def( "SetDestination", (void(WSL::Framework::Standard::Mobile::*)(float,float))&WSL::Framework::Standard::Mobile::SetDestination ) .def( "SetDestination", (void(WSL::Framework::Standard::Mobile::*)(float,float,float))&WSL::Framework::Standard::Mobile::SetDestination ) .def( "SetDestination", (void(WSL::Framework::Standard::Mobile::*)(WSL::Containers::Base::XYZ))&WSL::Framework::Standard::Mobile::SetDestination ) .def( "SetAutoMove", &WSL::Framework::Standard::Mobile::SetAutoMove ) .def( "SetID", &WSL::Framework::Standard::Mobile::SetID ) .def( "SetInitializeScript", &WSL::Framework::Standard::Mobile::SetInitializeScript ) .def( "SetObjID", &WSL::Framework::Standard::Mobile::SetObjID ) .def( "SetOtherScript", &WSL::Framework::Standard::Mobile::SetOtherScript ) .def( "SetRefreshScript", &WSL::Framework::Standard::Mobile::SetResfreshScript ) .def( "SetPosition", (void(WSL::Framework::Standard::Mobile::*)(float,float))&WSL::Framework::Standard::Mobile::SetPosition ) .def( "SetPosition", (void(WSL::Framework::Standard::Mobile::*)(float,float,float))&WSL::Framework::Standard::Mobile::SetPosition ) .def( "SetPosition", (void(WSL::Framework::Standard::Mobile::*)(WSL::Containers::Base::XYZ))&WSL::Framework::Standard::Mobile::SetPosition ) .def( "SetRotation", (void(WSL::Framework::Standard::Mobile::*)(float))&WSL::Framework::Standard::Mobile::SetRotation ) .def( "SetVector", &WSL::Framework::Standard::Mobile::SetVector ) .def( "SetPhysicalBehavior", &WSL::Framework::Standard::Mobile::SetPhysicalBehavior ) ]; //-----Bubble Sort-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Algorithmic::BubbleSort>( "BubbleSort" ) .def( luabind::constructor<>() ) .def( "BubbleSortAlgorithm", &WSL::Algorithmic::BubbleSort::BubbleSortAlgorithm ) ]; //-----Sub Singleton Foundation-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Algorithmic::Base::SubSingletonFoundation>( "SubSingleFoundation" ) .def( luabind::constructor<>() ) ]; //-----Sub Singleton Base-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Algorithmic::Base::SubSingleBase, WSL::Algorithmic::Base::SubSingletonFoundation>( "SubSingleBase" ) .def( luabind::constructor<>() ) ]; //-----Level-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Algorithmic::Level, WSL::Algorithmic::Base::SubSingleBase>( "Level" ) .def( luabind::constructor<>() ) .def( "AddObject", &WSL::Algorithmic::Level::AddObject ) .def( "GetObject", (void(WSL::Algorithmic::Level::*)(unsigned int,int,int))&WSL::Algorithmic::Level::GetObject ) .def( "SearchAlgorithim", &WSL::Algorithmic::Level::SearchAlgorithim ) .def( "SetObject", &WSL::Algorithmic::Level::SetObject ) .def( "SetActive", &WSL::Algorithmic::Level::SetActive ) .def( "SetRefresh", &WSL::Algorithmic::Level::SetRefresh ) .def( "SetDestroy", &WSL::Algorithmic::Level::SetDestroy ) .def( "ObjectIsInLevel", &WSL::Algorithmic::Level::ObjectIsInLevel ) .def_readwrite( "active", &WSL::Algorithmic::Level::active ) .def_readwrite( "refresh", &WSL::Algorithmic::Level::refresh ) .def_readwrite( "destroy", &WSL::Algorithmic::Level::destroy ) ]; //-----Render Layer-----// luabind::module( engine->luaContainer->State ) [ luabind::class_<WSL::Algorithmic::RenderLayer, WSL::Algorithmic::Base::SubSingletonFoundation, WSL::Algorithmic::BubbleSort>( "RenderLayer" ) .def( "GetActive", &WSL::Algorithmic::RenderLayer::GetActive ) .def( "SetActive", &WSL::Algorithmic::RenderLayer::SetActive ) .def( "GetName", &WSL::Algorithmic::RenderLayer::GetName ) .def( "SetName", &WSL::Algorithmic::RenderLayer::SetName ) ]; //-----Sound Manager-----// luabind::module( engine->luaContainer->State )[ luabind::class_< WSL::Global::SoundManager >( "SoundManager" ) .def( luabind::constructor<>() ) .def( "CleanUp", &WSL::Global::SoundManager::CleanUp ) .def( "LoadSound", &WSL::Global::SoundManager::LoadSound ) .def( "PauseSound", &WSL::Global::SoundManager::PauseSound ) .def( "PlaySound", (unsigned int(WSL::Global::SoundManager::*)(unsigned int, bool))&WSL::Global::SoundManager::PlaySound ) .def( "PlaySound", (unsigned int(WSL::Global::SoundManager::*)(std::string, bool))&WSL::Global::SoundManager::PlaySound ) .def( "PlaySoundFromFile", &WSL::Global::SoundManager::PlaySoundFromFile ) .def( "SoundIsPaused", &WSL::Global::SoundManager::SoundIsPaused ) .def( "SoundIsPlaying", &WSL::Global::SoundManager::SoundIsPlaying ) .def( "SoundIsStopped", &WSL::Global::SoundManager::SoundIsStopped ) .def( "StopSound", &WSL::Global::SoundManager::StopSound ) .def( "UnPauseSound", &WSL::Global::SoundManager::UnPauseSound ) .def( "Update", &WSL::Global::SoundManager::Update ) ]; //-----SFML View-----// luabind::module( engine->luaContainer->State )[ luabind::class_<sf::View>( "SFMLView" ) .def( luabind::constructor<>() ) ]; //-----Camera-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Global::Camera>( "Camera" ) .def( luabind::constructor< float, float, float, float, float, float, sf::View* >() ) .def( luabind::constructor<>() ) .def( "GetX", &WSL::Global::Camera::GetX ) .def( "GetY", &WSL::Global::Camera::GetY ) .def( "GetZ", &WSL::Global::Camera::GetZ ) .def( "GetWidth", &WSL::Global::Camera::GetWidth ) .def( "GetHeight", &WSL::Global::Camera::GetHeight ) .def( "GetDepth", &WSL::Global::Camera::GetDepth ) .def( "GetCamera", &WSL::Global::Camera::GetCamera ) .def( "Move", &WSL::Global::Camera::Move ) .def( "Zoom", &WSL::Global::Camera::Zoom ) .def( "SetZoom", &WSL::Global::Camera::SetZoom ) .def( "SetX", &WSL::Global::Camera::SetX ) .def( "SetY", &WSL::Global::Camera::SetY ) .def( "SetZ", &WSL::Global::Camera::SetZ ) .def( "SetWidth", &WSL::Global::Camera::SetWidth ) .def( "SetHeight", &WSL::Global::Camera::SetHeight ) .def( "SetDepth", &WSL::Global::Camera::SetDepth ) .def( "SetCamera", &WSL::Global::Camera::SetCamera ) ]; //-----Singleton Base-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Base::SingletonBase>( "SingletonBase" ) .def( luabind::constructor<>() ) ]; //-----Core Info Container-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Containers::CoreInfoContainer>( "CoreInfoContainer" ) .def( luabind::constructor<>() ) .def( "GetID", &WSL::Containers::CoreInfoContainer::GetID ) .def( "GetObjID", &WSL::Containers::CoreInfoContainer::GetObjID ) .def( "GetComponentID", &WSL::Containers::CoreInfoContainer::GetComponentID ) .def( "SetID", &WSL::Containers::CoreInfoContainer::SetID ) .def( "SetObjID", &WSL::Containers::CoreInfoContainer::SetObjID ) .def( "SetComponentID", &WSL::Containers::CoreInfoContainer::SetComponentID ) ]; //-----Singleton-----// luabind::module( engine->luaContainer->State )[ luabind::class_<WSL::Singleton, WSL::Base::SingletonBase>( "Singleton" ) .def( luabind::constructor<>() ) .def( "AddPolygon", (void(WSL::Singleton::*)(std::string))&WSL::Singleton::AddPolygon ) .def( "AddPolygon", (void(WSL::Singleton::*)(void))&WSL::Singleton::AddPolygon ) .def( "AddScanArea", (void(WSL::Singleton::*)(std::string))&WSL::Singleton::AddScanArea ) .def( "AddScanArea", (void(WSL::Singleton::*)(void))&WSL::Singleton::AddScanArea ) .def( "AddSprite", (void(WSL::Singleton::*)(float,float,bool))&WSL::Singleton::AddSprite ) .def( "AddSprite", (void(WSL::Singleton::*)(float,float,unsigned int,bool))&WSL::Singleton::AddSprite ) .def( "AddSprite", (void(WSL::Singleton::*)(unsigned int,bool))&WSL::Singleton::AddSprite ) .def( "AddVectorGraphic", (void(WSL::Singleton::*)(std::string))&WSL::Singleton::AddVectorGraphic ) .def( "AddVectorGraphic", (void(WSL::Singleton::*)())&WSL::Singleton::AddVectorGraphic ) .def( "BaseSend", &WSL::Singleton::BaseSend ) .def( "ThreadObject", &WSL::Singleton::ThreadObject ) .def( "SendObject", &WSL::Singleton::SendObject ) .def( "EndObjectThread", &WSL::Singleton::EndObjectThread ) .def( "GetObject", &WSL::Singleton::GetObject ) .def( "Instantiate", &WSL::Singleton::Instantiate ) .def( "InstantiateLevel", &WSL::Singleton::InstantiateLevel ) .def( "InstantiateRenderLayer", (int(WSL::Singleton::*)(std::string))&WSL::Singleton::InstantiateRenderLayer ) .def( "GetLevel", (void(WSL::Singleton::*)(unsigned int))&WSL::Singleton::GetLevel ) .def( "GetLevel", (void(WSL::Singleton::*)(std::string))&WSL::Singleton::GetLevel ) .def( "GetRenderLayer", &WSL::Singleton::GetRenderLayer ) .def( "GetRenderLayerByLevel", (void(WSL::Singleton::*)(unsigned int))&WSL::Singleton::GetRenderLayerByLevel ) .def( "GetRenderLayerByLevel", (void(WSL::Singleton::*)(std::string))&WSL::Singleton::GetRenderLayerByLevel ) .def( "GetDebug", &WSL::Singleton::GetDebug ) .def( "GetSoundManager", &WSL::Singleton::GetSoundManager ) .def( "GetCamera", &WSL::Singleton::GetCamera ) .def( "GetMousePosition", &WSL::Singleton::GetMousePosition ) .def( "GetThreeDCollision", &WSL::Singleton::GetThreeDCollision ) .def( "SetLevel", (void(WSL::Singleton::*)(WSL::Algorithmic::Level*,unsigned int))&WSL::Singleton::SetLevel ) .def( "SetLevel", (void(WSL::Singleton::*)(WSL::Algorithmic::Level*,std::string))&WSL::Singleton::SetLevel ) .def( "SetDebug", &WSL::Singleton::SetDebug ) .def( "SetThreeDCollision", &WSL::Singleton::SetThreeDCollision ) .def( "LoadImage", &WSL::Singleton::LoadImage ) .def_readwrite( "debug", &WSL::Singleton::debug ) .def_readwrite( "run", &WSL::Singleton::run ) .def_readwrite( "currentInfo", &WSL::Singleton::currentInfo ) ]; } //Go'n old school style here!// static void Log( bool compile ) { std::ofstream file; file.open( "bin/Documentation/Compiles And Executions.txt" ); file<<"\n-----Beginning of log: -----\n"; std::string msg = "Software: White - Storm: Lightning.\n Version/Release: Alpha.\n Author: Christopher Augustus Greeley.\n Executed "; if( compile == true ) { msg += "and compiled "; } msg += "on "; msg += __DATE__; msg += " at "; msg += __TIME__; msg += ".\n"; file<<msg; msg = "This version of White - Storm: Lightning this was compiled with"; if( __cplusplus > 199711L ) msg += " a industry standard version of C++.\n"; else msg += " a non industry standard version of C++.\n"; file<<msg; file<<"-----End of log.-----\n"; file.close(); } static void Run( WSL::Singleton* engineSingleton ) { while( true ) { if( engineSingleton->run == true ) { engineSingleton->BaseSend(); luaL_dofile( engineSingleton->engine->luaContainer->State, "src/Scripts/Engine/Game Scripts/Begin Refresh.lua" ); engineSingleton->Cycle(); engineSingleton->BaseSend(); luaL_dofile( engineSingleton->engine->luaContainer->State, "src/Scripts/Engine/Game Scripts/End Refresh.lua" ); } else { engineSingleton->BaseSend(); luaL_dofile( engineSingleton->engine->luaContainer->State, "src/Scripts/Engine/Game Scripts/Destroy.lua" ); engineSingleton->CleanUp(); break; } } } static void (* BaseSend )(); static void (* SendObject )(); static void (* ExternalRegister )( std::vector< WSL::DataTranslation::Base::BaseTranslator* >* ); static void (* ExternalLuaRegister )( WSL::Engine* engine ); static bool externalRegister; static std::vector< WSL::DataTranslation::Base::BaseTranslator* > InitializeTranslators( std::vector< WSL::DataTranslation::Base::BaseTranslator* > translators ) { WSL::DataTranslation::EntityTranslator* entityTrans = new WSL::DataTranslation::EntityTranslator; entityTrans->BaseSend = BaseSend; entityTrans->SendObject = SendObject; { /*The strangte &* had a reason instead of a normal assignmnet, as it is years later I am writing this comment what I rmemeber was it for some reason preserved the correct type when sending an object to Lua instead of sending a base type or something to that degree.*/ WSL::DataTranslation::Base::BaseTranslator* temp = &*entityTrans; translators.push_back( temp ); } WSL::DataTranslation::PositionalTranslator* posTrans = new WSL::DataTranslation::PositionalTranslator; posTrans->BaseSend = BaseSend; posTrans->SendObject = SendObject; { WSL::DataTranslation::Base::BaseTranslator* temp = &*posTrans; translators.push_back( temp ); } WSL::DataTranslation::MobileTranslator* mobileTrans = new WSL::DataTranslation::MobileTranslator; mobileTrans->BaseSend = BaseSend; mobileTrans->SendObject = SendObject; { WSL::DataTranslation::Base::BaseTranslator* temp = &*mobileTrans; translators.push_back( temp ); } if( externalRegister == true ) ExternalRegister( &translators ); return translators; } static WSL::Singleton* singlet; static void MiddleBaseSend() { singlet->BaseSend(); } static void MiddleLuaObjectSend() { singlet->SendObjectToLua(); } static WSL::Singleton* InitializeEngine() { Log( true ); WSL::Singleton* engineSingleton = new WSL::Singleton( true ); LuaRegister( engineSingleton->engine ); if( externalRegister == true ) ExternalLuaRegister( engineSingleton->engine ); BaseSend = &MiddleBaseSend; SendObject = &MiddleLuaObjectSend; singlet = engineSingleton; engineSingleton->SetUpTranslators = &InitializeTranslators; engineSingleton->InitializeTranslators(); { WSL::DataTransfer::Lua::SingletonSender* engineSingletonSender = new WSL::DataTransfer::Lua::SingletonSender; engineSingletonSender->singleton = engineSingleton; engineSingleton->sender = engineSingletonSender; engineSingleton->BaseSend(); luaL_dofile( engineSingleton->engine->luaContainer->State, "src/Scripts/Engine/Game Scripts/Initialize.lua" ); } return engineSingleton; } static WSL::Singleton* EngineInitialize() { WSL::Singleton* engineSingleton = InitializeEngine(); Recurse = &Run; return engineSingleton; } static void ExecuteWhiteStormLightning() { Recurse( EngineInitialize() ); } }
GCGGames/White-StormLightning
WSL/White Storm Lightning.h
C
gpl-3.0
45,310
<?php require('config.php'); # Set variables. $action = !empty($_GET['q']) ? $_GET['q'] : NULL; $from = !empty($_GET['from']) ? $_GET['from'] : $config['date_from']; $to = !empty($_GET['to']) ? $_GET['to'] : $config['date_to']; # Optional arguments. $customer = !empty($_GET['customer']) && $_GET['customer'] != 'all' ? $_GET['customer'] : NULL; $route = !empty($_GET['from_postcode']) && !empty($_GET['to_postcode']) ? array($_GET['from_postcode'], $_GET['to_postcode']) : NULL; $bidir = isset($_GET['bidir']) ? TRUE : NULL; $task_id = !empty($_GET['task']) ? intval($_GET['task']) : NULL; $task_ids = !empty($_GET['tasks']) ? $_GET['tasks'] : NULL; $ride_id = !empty($_GET['ride']) ? intval($_GET['ride']) : NULL; $limit = !empty($_GET['limit']) ? intval($_GET['limit']) : 1000; $min_dp = NULL; if ( isset($_GET['min_dp']) && is_numeric($_GET['min_dp']) ) { $t = intval($_GET['min_dp']); $operator = $_GET['min_dp_op'] == 'lt' ? "<" : ">"; $min_dp = sprintf("%s %d", $operator, $t); } $min_dr = NULL; if ( isset($_GET['min_dr']) && is_numeric($_GET['min_dr']) ) { $t = intval($_GET['min_dr']); $operator = $_GET['min_dr_op'] == 'lt' ? "<" : ">"; $min_dr = sprintf("%s %d", $operator, $t); } # Set the options in one convenient array. $options = array(); $options['customer'] = $customer; $options['route'] = $route; $options['bidir'] = $bidir; $options['min_dp'] = $min_dp; $options['min_dr'] = $min_dr; $options['task_id'] = $task_id; $options['ride_id'] = $ride_id; $options['limit'] = $limit; # Do nothing if no action is set. if ( !isset($action) ) { die("Action (q) not set."); } # Create the table generator. $table = new Table(); # Connect with the database. $table->database_connect(); # Generate table data. if ($action == "delays_negative") { # Show negative delays. $table->set_negative_delays($from, $to, $customer); $body = $table->build_tbody_tasks(); $table->build($body, "class='display' id='table_tasks'"); } elseif ($action == "delays_large") { # Get tasks with large delays. $table->set_large_delays($from, $to, $customer); $body = $table->build_tbody_tasks(); $table->build($body, "class='display' id='table_tasks'"); } elseif ($action == "tasks") { # Get all tasks. $table->set_tasks($from, $to, $options); $body = $table->build_tbody_tasks(); $table->build($body, "class='display' id='table_tasks'"); } elseif ($action == "rides") { # Get all tasks. $table->set_rides($from, $to, $options); $body = $table->build_tbody_rides(); $table->build($body, "class='display' id='table_rides'"); } elseif ($action == "route_frequencies") { # Get route frequencies. $table->set_route_frequencies($from, $to, $customer, $route); $body = $table->build_tbody_simple("gradeA"); $table->build($body, "class='display' id='table_route_frequencies'"); } elseif ($action == "route_task") { # Get route coordinates for a task. if ( !isset($task_id) ) { die("Task number (task) not set."); } $table->build_xml_task_route_coordinates($task_id); } elseif ($action == "route_ride") { # Get route coordinates for all tasks of a ride. if ( !isset($ride_id) ) { die("Ride number (ride) not set."); } $tasks = $table->get_tasks_from_ride($ride_id); $table->build_xml_task_route_coordinates_multi($tasks); } elseif ($action == "route_tasks") { # Get route coordinates for multiple tasks. if ( !isset($task_ids) ) { die("Task numbers (tasks) not set."); } $task_ids = explode(',', $task_ids); $table->build_xml_task_route_coordinates_multi($task_ids); } elseif ($action == "location") { # Get location information for a task. if ( !isset($task_id) && !isset($ride_id) ) { die("Task number (task) or ride number (ride) not set."); } if ( isset($task_id) ) { $ride_id = $table->get_ride_from_task($task_id); } $table->set_start_end_locations_for_ride($ride_id); $body = $table->build_tbody_ride_tasks(); $table->build($body, "class='display' id='table_location_info'", array('header')); } elseif ($action == "ride_view_planned") { # Get planned ride view. if ( !isset($task_id) && !isset($ride_id) ) { die("Task number (task) or ride number (ride) not set."); } if ( isset($task_id) ) { $ride_id = $table->get_ride_from_task($task_id); } $table->set_ride_tasks_planned_order($ride_id); $body = $table->build_tbody_ride_tasks(); $table->build($body, "class='display' id='table_ride_view_planned'", array('header')); } elseif ($action == "ride_view_realized") { # Get realized ride view. if ( !isset($task_id) && !isset($ride_id) ) { die("Task number (task) or ride number (ride) not set."); } if ( isset($task_id) ) { $ride_id = $table->get_ride_from_task($task_id); } $table->set_ride_tasks_realized_order($ride_id); $body = $table->build_tbody_ride_tasks(); $table->build($body, "class='display' id='table_ride_view_realized'", array('header')); } class Table { private $result; private $tableHeads = array(); private $output; /** * Connect with the PostgreSQL database. */ public function database_connect() { global $config; $this->dbconn = pg_connect("host={$config['host']} dbname={$config['dbname']} user={$config['username']} password={$config['password']}"); } /** * Set task data for tasks with a negative delay for a specific customer * and date range. */ public function set_negative_delays($from, $to, $customer=NULL) { $query = "SELECT r.ritregelnr AS task_id, r.ritlink, o.relatiecode, MIN(a.tijd) AS date, d.driving_time/60 AS driving_time, d.delay/60 AS delay, r.actiecode, v.vehicle_code, d.overnight FROM hist_bcacties a INNER JOIN driving_times d ON a.elipsref = d.task_id INNER JOIN tbl_ritregels r ON a.elipsref = r.ritregelnr INNER JOIN task_to_vehicle v ON a.elipsref = v.task_id INNER JOIN tbl_orders o ON r.orderlink = o.ordernr INNER JOIN tbl_ritregels r2 ON (r.ritlink = r2.ritlink AND r.volgorde = (r2.volgorde+1)) WHERE (r.locatieland = 'NL' AND r2.locatieland = 'NL') AND delay < 0 AND r.actiedatum BETWEEN '{$from}' AND '{$to}' --where GROUP BY r.ritregelnr, o.relatiecode, d.delay, d.driving_time, v.vehicle_code, d.overnight ORDER BY r.ritregelnr;"; if ( $customer ) { $query = str_replace("--where", "AND o.relatiecode = '{$customer}' --where", $query); } $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set task data for a date range. */ public function set_tasks($from, $to, $options=array()) { $query = "SELECT r.ritregelnr AS task_id, r.ritlink, o.relatiecode, MIN(a.tijd) AS date, (d.clean_driving_time/60) AS freeflow, (d.driving_time/60) AS driving_time, (d.planned_delay/60) AS planned_delay, (d.delay/60) AS delay, r.actiecode, v.vehicle_code, d.overnight AS o FROM hist_bcacties a INNER JOIN driving_times d ON a.elipsref = d.task_id INNER JOIN tbl_ritregels r ON a.elipsref = r.ritregelnr INNER JOIN task_to_vehicle v ON a.elipsref = v.task_id INNER JOIN tbl_orders o ON r.orderlink = o.ordernr INNER JOIN task_to_route tr ON tr.task_id = a.elipsref --from WHERE (r.actiedatum BETWEEN '{$from}' AND '{$to}') -- Filter on tasks within The Netherlands. AND (tr.from_country = 'NL' AND tr.to_country = 'NL') --where GROUP BY r.ritregelnr, o.relatiecode, d.clean_driving_time, d.driving_time, d.planned_delay, d.delay, v.vehicle_code, d.overnight ORDER BY r.ritregelnr --other;"; if ( isset($options['customer']) ) { $query = str_replace("--where", "AND o.relatiecode = '{$options['customer']}' --where", $query); } if ( isset($options['route']) ) { if ( isset($options['bidir']) ) { $query = str_replace("--where", "AND ((tr.from_postcode SIMILAR TO '{$options['route'][0]}' AND tr.to_postcode SIMILAR TO '{$options['route'][1]}') OR (tr.from_postcode SIMILAR TO '{$options['route'][1]}' AND tr.to_postcode SIMILAR TO '{$options['route'][0]}')) --where", $query); } else { $query = str_replace("--where", "AND (tr.from_postcode SIMILAR TO '{$options['route'][0]}' AND tr.to_postcode SIMILAR TO '{$options['route'][1]}') --where", $query); } } if ( isset($options['min_dp']) ) { $query = str_replace("--where", "AND d.planned_delay/60 {$options['min_dp']} --where", $query); } if ( isset($options['min_dr']) ) { $query = str_replace("--where", "AND d.delay/60 {$options['min_dr']} --where", $query); } if ( isset($options['limit']) ) { $query = str_replace("--other", "LIMIT {$options['limit']} --other", $query); } #print "<pre>{$query}</pre>"; $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set task data for a date range. */ public function set_rides($from, $to, $options=array()) { $customer = isset($options['customer']) ? "'{$options['customer']}'" : "NULL"; if ( isset($options['route']) ) { $route_from = "'{$options['route'][0]}'"; $route_to = "'{$options['route'][1]}'"; } else { $route_from = "NULL"; $route_to = "NULL"; } $bidir = isset($options['bidir']) ? "'t'" : "'f'"; $min_dp = isset($options['min_dp']) ? "'{$options['min_dp']}'" : "NULL"; $min_dr = isset($options['min_dr']) ? "'{$options['min_dr']}'" : "NULL"; $query = "SELECT * FROM get_rides('{$from}', '{$to}', {$customer}, {$route_from}, {$route_to}, {$bidir}, {$min_dp}, {$min_dr});"; $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set task data for tasks with a large delay. */ public function set_large_delays($from, $to, $customer=NULL) { $customer = $customer ? "'{$customer}'" : "NULL"; $query = "SELECT * FROM get_large_delays('{$from}', '{$to}', {$customer});"; $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set latitude and longitude coordinates for a task. */ public function set_geodata($task_id) { $query = "SELECT * FROM get_geodata_from_task({$task_id});"; $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set the frequencies for routes. * * @param string $from Start date in the format yyyy-mm-dd. * @param string $to End date in the format yyyy-mm-dd. * @param string $customer Customer code to filter on. * @param array $route Array with two strings, start postcode and end postcode. * @uses boolean $this->route_combinations Filter on both route directions. * @return array Query result resource array. */ public function set_route_frequencies($from, $to, $customer=NULL, $route=NULL) { $query = "SELECT COUNT(DISTINCT tr.ride_id) AS freq, tr.from_postcode, MIN(tr.from_city) as from_city, MIN(tr.from_country) as from_country, tr.to_postcode, MIN(tr.to_city) as to_city, MIN(tr.to_country) as to_country FROM tbl_ritregels r INNER JOIN task_to_route tr ON tr.ride_id = r.ritlink --from WHERE r.actiedatum BETWEEN '{$from}' AND '{$to}' --where -- Only group by the postcodes because these are used to define -- a route. GROUP BY tr.from_postcode, tr.to_postcode;"; if ( $customer) { $query = str_replace("--from", "INNER JOIN tbl_orders o ON r.orderlink = o.ordernr --from", $query); $query = str_replace("--where", "AND o.relatiecode = '{$customer}' --where", $query); } if ( $route ) { if ( isset($_GET['bidir']) ) { $query = str_replace("--where", "AND ((tr.from_postcode SIMILAR TO '{$route[0]}' AND tr.to_postcode SIMILAR TO '{$route[1]}') OR (tr.from_postcode SIMILAR TO '{$route[1]}' AND tr.to_postcode SIMILAR TO '{$route[0]}'))", $query); } else { $query = str_replace("--where", "AND (tr.from_postcode SIMILAR TO '{$route[0]}' AND tr.to_postcode SIMILAR TO '{$route[1]}')", $query); } } #print "<pre>{$query}</pre>"; # Execute the query and return the results. $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set departure and arrival location information of a task. Sets the * ZIP code and city of both locations. This is used for Google Maps to * mark the address locations for a task. * * @param string $task_id Task number (ritregelnr) of current task. * @uses $this->result Query result resource. */ public function set_start_end_locations_for_task($task_id) { $query = "SELECT tr.from_postcode, tr.from_city, tr.to_postcode, tr.to_city FROM tbl_ritregels r INNER JOIN task_to_route tr ON tr.task_id = r.ritregelnr WHERE r.ritregelnr = {$task_id};"; $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set departure and arrival locations information for all tasks of a ride. * Sets the ZIP code and city of both locations. * * @param string $ride_id Ride number. * @uses $this->result Query result resource. */ public function set_start_end_locations_for_ride($ride_id) { $query = "SELECT r.ritregelnr AS task_id, tr.from_postcode, tr.from_city, tr.to_postcode, r.locatiestraat as to_street, tr.to_city FROM tbl_ritregels r -- Doing an inner join should exclude the tasks that were not executed. INNER JOIN driving_times d ON d.task_id = r.ritregelnr LEFT OUTER JOIN task_to_route tr ON tr.task_id = r.ritregelnr WHERE r.ritlink = {$ride_id} ORDER BY d.task_start;"; $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set all tasks for a ride in the planned order. * * @param string $task_id Task number (ritregelnr). * @uses $this->result Query result resource. */ public function set_ride_tasks_planned_order($ride_id) { $query = "SELECT ritregelnr AS task_id, volgorde, actiecode, actiedatum AS action_date, -- planned date actietijd AS action_time_start, -- planned start time actietijdeind AS action_time_end -- planned finish time FROM tbl_ritregels WHERE ritlink = {$ride_id} ORDER BY volgorde"; $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set all tasks for a ride in the realized order. * * @param string $task_id Task number (ritregelnr). * @uses $this->result Query result resource. */ public function set_ride_tasks_realized_order($ride_id) { $query = "SELECT r.ritregelnr AS task_id, r.volgorde, r.actiecode, -- Get realized start time for task. We could use starttijd_taak -- instead, but that's unreliable because drivers don't always -- properly assign this. --r.starttijd_activiteit AS action_time_start, -- Use the start time as defined by PyRITS. d.task_start AS action_time_start, -- Get realized end time for task. We could also use -- eindtijd_taak for this. --r.eindtijd_activiteit AS action_time_end, -- Use the end time as defined by PyRITS. d.task_end AS action_time_end, d.clean_driving_time/60 AS freeflow, d.driving_time/60 AS driving_time, d.planned_delay/60 AS planned_delay, d.delay/60 AS delay, d.overnight AS o, d.static AS s FROM tbl_ritregels r -- Doing an inner join should exclude the tasks that were not executed. INNER JOIN driving_times d ON d.task_id = r.ritregelnr WHERE r.ritlink = {$ride_id} ORDER BY d.task_start;"; $this->result = pg_query($query) or die('Query failed: ' . pg_last_error()); $this->set_table_heads(); } /** * Set table heads from the query output. * * @uses array $this->tableHeads Column names for the query output. * @uses array $this->result Query output. */ private function set_table_heads() { $this->tableHeads = array(); $column_names = array( 'actiecode' => "Taak", 'action_date' => "Datum", 'action_time_start' => "Start", 'action_time_end' => "Eind", 'appointment' => "Klant afspraak", 'comment' => "Opmerking", 'date' => "Datum", 'delay' => "DR", 'driving_time' => "DT", 'freq' => "Frequentie", 'freeflow' => "FF", 'from_city' => "Van stad", 'from_country' => "Van land", 'from_postcode' => "Van postcode", 'locatiestraat' => "Straat", 'locatieplaats' => "Plaats", 'locations' => "Locaties", 'o' => "O", 'overnight' => "O", 'p' => "P", 'planned_delay' => "DP", 'ritregelnr' => "Taaknr.", 'ritlink' => "Ritnr.", 'relatiecode' => "Klant", 's' => "S", 'static' => "S", 'task_id' => "Taaknr.", 'time' => "Tijd", 'to_city' => "Naar stad", 'to_country' => "Naar land", 'to_postcode' => "Naar postcode", 'to_street' => "Naar straat", 'volgorde' => "#", 'vehicle_code' => "Voertuignr.", '' => "", ); for ($i = 0; $i < pg_num_fields($this->result); $i++) { $field = pg_field_name($this->result, $i); if ( array_key_exists($field, $column_names) ) { $field = $column_names[$field]; } $this->tableHeads[] = $field; } } /** * Return the ride number from a task number. * * @param integer $task_id Task number (ritregelnr). * @return integer $ride_id Ride number. */ function get_ride_from_task($task_id) { $query = "SELECT ritlink FROM tbl_ritregels WHERE ritregelnr = {$task_id};"; $result = pg_query($this->dbconn, $query) or die('Query failed: ' . pg_last_error()); $row = pg_fetch_row($result); $ride_id = $row ? $row[0] : NULL; return $ride_id; } /** * Return the task numbers of a ride number. * * @param integer $ride_id Ride number. * @return array $tasks Task numbers (ritregelnr). */ function get_tasks_from_ride($ride_id) { $query = "SELECT DISTINCT ritregelnr FROM tbl_ritregels WHERE ritlink = {$ride_id};"; $result = pg_query($this->dbconn, $query) or die('Query failed: ' . pg_last_error()); $tasks = array(); while ($row = pg_fetch_array($result)) { $tasks[] = $row[0]; } return $tasks; } /** * Print HTML table. * * @param string $body The HTML <tbody> element for the table. * @param string $properties Optional additional properties for the <table> tag. * @param array $components Specifies the elements for the table. Possible * items for the array are the strings 'header' and 'footer'. By * default, both the header and the table are printed. */ public function build($body, $properties="", $components = array('header','footer')) { print "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" {$properties}>"; if ( in_array('header', $components) ) { print $this->build_thead(); } print $body; if ( in_array('footer', $components) ) { print $this->build_tfoot(); } print "</table>"; } /** * Prints XML data for a Google map containing route coordinates for a * single task. * * @param string $task_id Task number (ritregelnr). * @uses $this->result Query result resource. * */ public function build_xml_task_route_coordinates($task_id) { # Get lat/lon data for the route. $this->set_geodata($task_id); # Print content. header("Content-type: text/xml"); print "<root>"; print "<route>"; while ( $line = pg_fetch_array($this->result, null, PGSQL_ASSOC) ) { print "<marker{$i} lat='{$line['latitude']}' lng='{$line['longitude']}'/>"; } print "</route>"; # Here follow additional markers for the start and end address. In the # Google map, these are displayed as two icons. $this->set_start_end_locations_for_task($task_id); $result = pg_fetch_array($this->result); # Initialize a cURL session. $curl_handle = curl_init(); # Set the maximum timeout for cURL transfers to 5 seconds. curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 5); # Return the result on successful cURL transfers. curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); # Google maps API URL. $google_maps_url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false"; # Get lat/lon data for post code + city of start location $location_start = sprintf("%s %s", $result['from_postcode'], $result['from_city']); $url = sprintf($google_maps_url, urlencode($location_start)); curl_setopt($curl_handle, CURLOPT_URL, $url); $result_start = curl_exec($curl_handle); $result_start = json_decode($result_start, true); # If no result, get lat/lon data for just the city of start location if ( count($result_start['results']) < 1 ) { $location_start = $result['from_city']; $url = sprintf($google_maps_url, urlencode($location_start)); curl_setopt($curl_handle, CURLOPT_URL, $url); $result_start = curl_exec($curl_handle); $result_start = json_decode($result_start, true); } # Get lat/lon data for post code + city of end location $location_end = sprintf("%s %s", $result['to_postcode'], $result['to_city']); $url = sprintf($google_maps_url, urlencode($location_end)); curl_setopt($curl_handle, CURLOPT_URL, $url); $result_end = curl_exec($curl_handle); $result_end = json_decode($result_end, true); # If no result, get lat/lon data for just the city of end location if ( count($result_end['results']) < 1 ) { $location_end = $result['to_city']; $url = sprintf($google_maps_url, urlencode($location_end)); curl_setopt($curl_handle, CURLOPT_URL, $url); $result_end = curl_exec($curl_handle); $result_end = json_decode($result_end, true); } # Close cURL session. curl_close($curl_handle); print "<start_end_location>"; printf("<start_end lat='%s' lng='%s' location='%s'/>", $result_start['results'][0]['geometry']['location']['lat'], $result_start['results'][0]['geometry']['location']['lng'], $location_start); printf("<start_end lat='%s' lng='%s' location='%s'/>", $result_end['results'][0]['geometry']['location']['lat'], $result_end['results'][0]['geometry']['location']['lng'], $location_end); print "</start_end_location>"; print "</root>"; } /** * Prints XML data for a Google map containing route coordinates for * multiple tasks. * * @param array $tasks Array containing task (ritregelnr) numbers. * @uses $this->result Query result resource. * */ public function build_xml_task_route_coordinates_multi($tasks) { header("Content-type: text/xml"); print "<root>"; print "<routes>"; for ($i = 0; $i < count($tasks); $i++) { print "<task id='{$tasks[$i]}'>"; $this->set_geodata($tasks[$i]); while ( $line = pg_fetch_array($this->result, null, PGSQL_ASSOC) ) { print "<marker{$i} lat='{$line['latitude']}' lng='{$line['longitude']}'/>"; } print "</task>"; } print "</routes>"; # Here follow additional markers for the start and end address. In the # Google map, these are displayed as two icons. Only set the address # markers for the first task. $this->set_start_end_locations_for_task($tasks[0]); $result = pg_fetch_array($this->result); # Initialize a cURL session. $curl_handle = curl_init(); # Set the maximum timeout for cURL transfers to 5 seconds. curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 5); # Return the result on successful cURL transfers. curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); # Google maps API URL. $google_maps_url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false"; # Get lat/lon data for post code + city of start location $location_start = sprintf("%s %s", $result['from_postcode'], $result['from_city']); $url = sprintf($google_maps_url, urlencode($location_start)); curl_setopt($curl_handle, CURLOPT_URL, $url); $result_start = curl_exec($curl_handle); $result_start = json_decode($result_start, true); # If no result, get lat/lon data for just the city of start location if ( count($result_start['results']) < 1 ) { $location_start = $result['from_city']; $url = sprintf($google_maps_url, urlencode($location_start)); curl_setopt($curl_handle, CURLOPT_URL, $url); $result_start = curl_exec($curl_handle); $result_start = json_decode($result_start, true); } # Get lat/lon data for post code + city of end location $location_end = sprintf("%s %s", $result['to_postcode'], $result['to_city']); $url = sprintf($google_maps_url, urlencode($location_end)); curl_setopt($curl_handle, CURLOPT_URL, $url); $result_end = curl_exec($curl_handle); $result_end = json_decode($result_end, true); # If no result, get lat/lon data for just the city of end location if ( count($result_end['results']) < 1 ) { $location_end = $result['to_city']; $url = sprintf($google_maps_url, urlencode($location_end)); curl_setopt($curl_handle, CURLOPT_URL, $url); $result_end = curl_exec($curl_handle); $result_end = json_decode($result_end, true); } # Close cURL session. curl_close($curl_handle); if ( isset($result_start['results'][0]) ) { print "<start_end_location>"; printf("<start_end lat='%s' lng='%s' location='%s'/>", $result_start['results'][0]['geometry']['location']['lat'], $result_start['results'][0]['geometry']['location']['lng'], $location_start); printf("<start_end lat='%s' lng='%s' location='%s'/>", $result_end['results'][0]['geometry']['location']['lat'], $result_end['results'][0]['geometry']['location']['lng'], $location_end); print "</start_end_location>"; } print "</root>"; } /** * Prints the HTML <thead> element for a table. * * The <thead> element contains the column names set in $this->tableHeads. * * @uses $this->tableHeads */ private function build_thead() { print "<thead>\n<tr>\n"; foreach ($this->tableHeads as $head) { print "<th>{$head}</th>\n"; } print "</tr>\n</thead>\n"; } /** * Prints the HTML <tfoot> element for a table. * * The <tfoot> element contains the column names set in $this->tableHeads. * * @uses $this->tableHeads */ private function build_tfoot() { print "<tfoot>\n<tr>\n"; foreach ($this->tableHeads as $head) { print "<th>{$head}</th>\n"; } print "</tr>\n</tfoot>\n"; } /** * Returns a HTML <tbody> element containing a list of tasks. * * The query result must yield rows with a field named 'task_id' containing * the task number. * * @uses $this->result * @return string A HTML <tbody> element. */ public function build_tbody_tasks() { $tbody = "<tbody>"; while ($line = pg_fetch_array($this->result, null, PGSQL_ASSOC)) { $class = "gradeA"; if ($line['driving_time'] == 0) { $class = "gradeX"; } $tbody .= "<tr class='{$class}' onclick='show_task(\"route\", {$line['task_id']} );'>\n"; foreach ($line as $key => $col_value) { if ( in_array($key, array("o","overnight")) ) { $col_value = $col_value == 't' ? "x" : ""; } $tbody .= "<td>{$col_value}</td>\n"; } $tbody .= "</tr>\n"; } $tbody .= "</tbody>"; return $tbody; } /** * Return HTML table body showing a list of rides. * * The query result must yield rows with a field named 'ritlink' containing * the ride number. * * @uses $this->result * @return string A HTML <tbody> element. */ public function build_tbody_rides() { $tbody = "<tbody>"; while ($line = pg_fetch_array($this->result, null, PGSQL_ASSOC)) { $tasks = ""; $class = "gradeA"; $tbody .= "<tr class='{$class}' onclick='show_ride(\"route\", {$line['ritlink']} );'>\n"; foreach ($line as $key => $col_value) { if ( $key == "o" ) { $col_value = $col_value == 't' ? "x" : ""; } $tbody .= "<td>{$col_value}</td>\n"; } $tbody .= "</tr>\n"; } $tbody .= "</tbody>"; return $tbody; } /** * Return HTML table body showing a list of tasks. It displays * all the tasks for a ride in the planned/realized order. * * The query result must yield rows with a field named 'task_id' containing * the task number. The current task is automatically highlighted if * $_GET['task'] is set. * * @uses $_GET['task'] * @uses $this->result * @return string A HTML <tbody> element. */ public function build_tbody_ride_tasks() { $task_id = !empty($_GET['task']) ? intval($_GET['task']) : NULL; $tbody = "<tbody>"; while ( $line = pg_fetch_array($this->result, null, PGSQL_ASSOC) ) { $class = "gradeA"; if ( $task_id && $line['task_id'] == $task_id ) { $class = "gradeX"; } $tbody .= "<tr class='{$class}' onclick='show_task(\"route\", {$line['task_id']} );'>\n"; foreach ($line as $key => $col_value) { if ( in_array($key, array("o","s")) ) { $col_value = $col_value == 't' ? "x" : ""; } $tbody .= "<td>{$col_value}</td>\n"; } $tbody .= "</tr>\n"; } $tbody .= "</tbody>"; return $tbody; } /** * Return a simple HTML table body. * * @uses $this->result * @return string A HTML <tbody> element. */ public function build_tbody_simple($class="") { $tbody = "<tbody>"; while ($line = pg_fetch_array($this->result, null, PGSQL_ASSOC)) { $tbody .= "<tr class='{$class}'>\n"; foreach ($line as $col_value) { $tbody .= "<td align='center'>{$col_value}</td>\n"; } $tbody .= "</tr>\n"; } $tbody .= "</tbody>"; return $tbody; } /** * Return a simple HTML table body containing a message. * * @param string $title Title for the message. * @param string $message Message body. * @param string $params Optional parameters for the table. * @return string A HTML table. */ public function message($title, $message, $params="") { $table = "<table {$params}> <thead> <tr> <th>{$title}</th> </tr> </thead> <tbody> <tr> <th>{$message}</th> </tr> </tbody> </table>"; return $table; } } ?>
figure002/pyrits
map/table.php
PHP
gpl-3.0
34,743
#pragma once #include "guid.h" #include "rpc_requester.h" #include "ring_change_notifier.h" #include "ring_oracle.h" #include <mordor/fibersynchronization.h> #include <mordor/iomanager.h> #include <mordor/socket.h> #include <boost/noncopyable.hpp> #include <map> #include <set> #include <vector> namespace lightning { class PingTracker; //! This manages the ring configuration on master. class RingManager : boost::noncopyable { public: typedef boost::shared_ptr<RingManager> ptr; RingManager(GroupConfiguration::ptr groupConfiguration, const Guid& hostGroupGuid, Mordor::IOManager* ioManager, boost::shared_ptr<Mordor::FiberEvent> hostDownEvent, RpcRequester::ptr requester, PingTracker::ptr acceptorPingTracker, RingOracle::ptr ringOracle, RingChangeNotifier::ptr ringChangeNotifier, uint64_t setRingTimeoutUs, uint64_t lookupRingRetryUs, uint64_t ringBroadcastIntervalUs); void run(); void broadcastRing(); private: void lookupRing(); bool trySetRing(); void waitForRingToBreak(); uint32_t generateRingId(const std::vector<uint32_t>& ring) const; //! Should redo this with ragel if it ever gets more states. enum State { LOOKING = 0, WAIT_ACK, OK }; GroupConfiguration::ptr groupConfiguration_; const Guid hostGroupGuid_; const uint64_t setRingTimeoutUs_; const uint64_t lookupRingRetryUs_; const uint64_t ringBroadcastIntervalUs_; Mordor::IOManager* ioManager_; boost::shared_ptr<Mordor::FiberEvent> hostDownEvent_; RpcRequester::ptr requester_; PingTracker::ptr acceptorPingTracker_; RingOracle::ptr ringOracle_; RingChangeNotifier::ptr ringChangeNotifier_; RingConfiguration::ptr currentRing_; RingConfiguration::ptr nextRing_; State currentState_; Mordor::FiberMutex mutex_; static const uint32_t kHashSeed = 239; }; } // namespace lightning
skywalker239/lightning-prototype
lib/ring_manager.h
C
gpl-3.0
2,059
/* A Bison parser, made by GNU Bison 2.7. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2012 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ #ifndef YY_YY_Y_TAB_H_INCLUDED # define YY_YY_Y_TAB_H_INCLUDED /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 1 #endif #if YYDEBUG extern int mu_sieve_yydebug; #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum mu_sieve_yytokentype { IDENT = 258, TAG = 259, NUMBER = 260, STRING = 261, MULTILINE = 262, REQUIRE = 263, IF = 264, ELSIF = 265, ELSE = 266, ANYOF = 267, ALLOF = 268, NOT = 269 }; #endif /* Tokens. */ #define IDENT 258 #define TAG 259 #define NUMBER 260 #define STRING 261 #define MULTILINE 262 #define REQUIRE 263 #define IF 264 #define ELSIF 265 #define ELSE 266 #define ANYOF 267 #define ALLOF 268 #define NOT 269 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { /* Line 2058 of yacc.c */ #line 33 "sieve.y" char *string; size_t number; sieve_instr_t instr; mu_sieve_value_t *value; mu_list_t list; size_t pc; struct { size_t start; size_t end; } pclist; struct { char *ident; mu_list_t args; } command; struct { size_t begin; size_t cond; size_t branch; } branch; /* Line 2058 of yacc.c */ #line 108 "sieve-gram.h" } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define mu_sieve_yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE mu_sieve_yylval; #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int mu_sieve_yyparse (void *YYPARSE_PARAM); #else int mu_sieve_yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int mu_sieve_yyparse (void); #else int mu_sieve_yyparse (); #endif #endif /* ! YYPARSE_PARAM */ #endif /* !YY_YY_Y_TAB_H_INCLUDED */
Distrotech/mailutils
libmu_sieve/sieve-gram.h
C
gpl-3.0
3,387
package core; import java.io.*; import java.util.*; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.functors.StringValueTransformer; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import au.com.bytecode.opencsv.CSVWriter; import core.SyntheticPopulation.Household; import core.SyntheticPopulation.Individual; import core.SyntheticPopulation.Population; public class TextFileHandler { private static final Logger logger = Logger.getLogger(TextFileHandler.class); /** * * @param fileName * @return */ public static ArrayList<ArrayList<String>> readCSV (String fileName) { ArrayList<ArrayList<String>> sheetData = new ArrayList<ArrayList<String>>(); BufferedReader br = null; try { // create BufferedReader to read csv file containing data br = new BufferedReader(new FileReader(fileName)); String strLine = ""; StringTokenizer st = null; // read comma separated file line by line while ((strLine = br.readLine()) != null) { // break comma separated line using "," st = new StringTokenizer(strLine, ","); ArrayList<String> data = new ArrayList<String>(); while (st.hasMoreTokens()) { // display csv file String editedValue = String.valueOf(st.nextToken()) .replace("\"", "").trim(); data.add(editedValue); } sheetData.add(data); } br.close(); } catch (Exception e) { //logger.error("Exception while reading csv file: ", e); } return sheetData; } /** * * @param filename * @param header * @param dataout */ public static void writeToCSV(String filename, String[] header, List<String[]> dataout) { CSVWriter csvWriter = null; try { Writer fw = new BufferedWriter(new FileWriter(filename)); csvWriter = new CSVWriter(fw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); csvWriter.writeNext(header); csvWriter.writeAll(dataout); csvWriter.flush(); } catch (IOException e) { System.out.println("Failed to write content to file:" + filename); } finally { if (csvWriter != null) { try { csvWriter.close(); } catch (IOException e) { System.out.println("Failed to close file after writing: "); } } } } /** * * @param filename * @param header * @param dataout */ public static void writeToCSV(String filename, String[] header, List<String[]> dataout, boolean append) { CSVWriter csvWriter = null; try { Writer fw = new BufferedWriter(new FileWriter(filename, append)); csvWriter = new CSVWriter(fw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); csvWriter.writeNext(header); csvWriter.writeAll(dataout); csvWriter.flush(); } catch (IOException e) { System.out.println("Failed to write content to file:" + filename); } finally { if (csvWriter != null) { try { csvWriter.close(); } catch (IOException e) { System.out.println("Failed to close file after writing: "); } } } } public static void writeToCSV(String filename, String[] header, double[][] dataout) { ArrayList<String[]> strOut = new ArrayList<String[]>(); for (int i=0; i<=dataout.length-1; i++) { String[] dataRow = new String[dataout[i].length]; for (int j=0; j<=dataRow.length-1; j++) { dataRow[j] = Double.toString(dataout[i][j]); } strOut.add(dataRow); } writeToCSV(filename, header, strOut); } /** * * @param filename * @param header * @param dataout */ public static void writeToCSV(String filename, String[] header, HashMap<Integer,Integer> dataout) { ArrayList<String[]> strOut = new ArrayList<String[]>(); for (Integer key : dataout.keySet()) { String[] str = new String[] {String.valueOf(key), String.valueOf(dataout.get(key))}; strOut.add(str); } writeToCSV(filename, header, strOut); } /** * * @param filename * @param header * @param dataout */ public static void writeToCSVIntegerDouble(String filename, String[] header, HashMap<Integer,Double> dataout, boolean append) { ArrayList<String[]> strOut = new ArrayList<String[]>(); for (Integer key : dataout.keySet()) { String[] str = new String[] {String.valueOf(key), String.valueOf(dataout.get(key))}; strOut.add(str); } writeToCSV(filename, header, strOut, append); } /** * */ public static void writeToText(String filename, String text, boolean append) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(filename, append)); writer.append(text); writer.newLine(); writer.flush(); } catch (IOException e) { logger.error("Failed to write file: " + filename, e); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { logger.error("Failed to close file after writing: " + filename, e); } } } } /** * write Travel Diary into CSV file. * * @param fileName * * @author vlcao */ public static void writeTravelDiaryToCSV(String fileName) { final String[] header = {"Travel_ID", "Agent ID", "Hhold ID", "Age", "Gender", "Income", "Travel_Origin", "Travel_Destination", "Start_Time", "End_Time", "Duration", "Mode_of_Transport", "Purpose", "Vehicle_ID", "Trip_ID"}; CSVWriter csvWriter = null; try { csvWriter = new CSVWriter(new BufferedWriter(new FileWriter(fileName)), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); csvWriter.writeNext(header); // Iterates the data and write it out to the .csv file for (Household hhold : Population.getHhPool().values()) { for (Integer indivID : hhold.getResidentsID()) { Individual individual = Population.getIndivPool().get(indivID); int[][] diaries = individual.getTravelDiariesWeekdays(); if (diaries == null) { continue; } for (int[] diary : diaries) { /* //NOT write to csv file for travel diary does NOT travel (stay at home) if ((diary[6] == -1 //origin && diary[7] == -1 //destination && diary[8] == -1 //start_time && diary[9] == -1 //end_time && diary[10] == -1 //duration && diary[11] == -1) //travel_mode || (diary[6] == 0 //origin && diary[7] == 0 //destination && diary[8] == 0 //start_time && diary[9] == 0 //end_time && diary[10] == 0) //duration ) { continue; } */ Integer[] diaryAsObj = ArrayUtils.toObject(diary); Collection<String> stringValues = CollectionUtils.collect(Arrays.asList(diaryAsObj), StringValueTransformer.getInstance()); csvWriter.writeNext(stringValues.toArray(new String[stringValues.size()])); } } } } catch (IOException e) { logger.error("Failed to create Travel Diaries file" + fileName, e); } finally { try { if (csvWriter != null) { csvWriter.close(); } } catch (IOException e) { logger.error("Failed to close file: " + fileName, e); } } } /** * * @param spTD * @param fileName */ public static void writeSpTD2CSV(List<List<int[][]>> spTD, String fileName) { final String[] header = {"hholdID", "indivID", "tripID", "departure_time", "trip_time", "mode", "purpose", "origin", "destination"}; CSVWriter writer = null; try { writer = new CSVWriter(new BufferedWriter(new FileWriter(fileName)), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); writer.writeNext(header); for (List<int[][]> spTDwOD : spTD) { for (int[][] tdHhold : spTDwOD) { for (int[] aTdHhold : tdHhold) { //NOT write to csv file for travel diary does NOT travel (stay at home) /* if ((aTdHhold[3] == 0 //departure_time && aTdHhold[4] == 0 //trip_time && aTdHhold[7] == 0 //origin && aTdHhold[8] == 0)//destination || (aTdHhold[3] == -1 //departure_time && aTdHhold[4] == -1 //trip_time && aTdHhold[7] == -1 //origin && aTdHhold[8] == -1)//destination ) { continue; } */ Collection<String> stringValues = CollectionUtils.collect(Arrays.asList(ArrayUtils.toObject(aTdHhold)), StringValueTransformer.getInstance()); writer.writeNext(stringValues.toArray(new String[stringValues.size()])); writer.flush(); } } } } catch (IOException e) { logger.error("Failed to write to file: " + e, e); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { logger.error("Failed to close file: " + fileName, e); } } } }
smart-facility/SPGen
sources/src/main/java/core/TextFileHandler.java
Java
gpl-3.0
10,259
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?> <? $this->createFrame()->begin("Загрузка"); ?> <table class="catalog-menu-table scroll-fixed<? if($_SERVER["REQUEST_URI"]=='/catalog/'):?> on-top<? endif ?>"><tr><td style="width: <? if($arResult["INTERESTS"] && IS_MOBILE):?>55%;<? else:?>100%<? endif ?>"> <!-- Menu {{{--> <tr><td> <div class="ag-shop-menu<? if($arResult["IN_CATALOG"]):?> catalog-menu<? endif ?>"> <div class="ag-shop-menu__container"> <div class="ag-shop-menu__header"> <div class="grid grid--bleed grid--justify-space-between grid--align-content-center"> <div class="grid__col grid__col-shrink" style="width: 80% !important"> <h2 class="ag-shop-menu__current"><? $sCAtalogName = 'Все категории'; foreach($arResult["SECTIONS"] as $arSection){ if(strpos($_SERVER["REQUEST_URI"], $arSection["SECTION_PAGE_URL"])!==false) $sCAtalogName = $arSection["NAME"]; } $arPath = explode("/",$_SERVER["REQUEST_URI"]); if($arPath[1]=='profile' && $arPath[2]=='wishes'){ echo "Мои желания"; } elseif($arPath[1]=='profile' && $arPath[2]=='order'){ echo "Мои заказы"; } elseif($arPath[1]=='rules' && $arPath[2]=='hiw'){ echo "Правила"; } elseif($arPath[1]=='rules' && $arPath[2]=='stores'){ echo "Адреса"; } elseif($arPath[1]=='rules' && $arPath[2]=='faq'){ echo "FAQ"; } else{ echo $sCAtalogName; } ?></h2> </div> <div class="grid__col grid__col-shrink"> <button class="ag-shop-menu__button ag-shop-menu__button--lines js-menu__button" type="button"><span></span></button> </div> </div> </div> <? /*if(preg_match("#^/catalog/.*#",$_SERVER["REQUEST_URI"])):*/?> <div class="ag-shop-menu__items js-menu__list" style=""> <? if($_SERVER["REQUEST_URI"]!='/catalog/' && IS_MOBILE):?> <div class="ag-shop-menu__item"> <a class="ag-shop-menu__link" href="/catalog/" > <? echo "Все категории" ?> </a> </div> <? endif ?> <?/* <?php foreach($arResult["SECTIONS"] as $section):?> <? if(!$section["products"])continue;?> <div class="ag-shop-menu__item"> <a class="ag-shop-menu__link<? if(preg_match("#^".$section["SECTION_PAGE_URL"]."#", $_SERVER["REQUEST_URI"])):?> ag-shop-menu__link--active<? endif?>" href="<?= $section["SECTION_PAGE_URL"];?>" > <?= $section["NAME"];?> </a> </div> <?endforeach?> */?> <?php foreach($arResult["SECTIONS"] as $section):?> <div class="ag-shop-menu__item"> <a class="ag-shop-menu__link<? if($section["CURRENT"]): ?> ag-shop-menu__link--active<? endif?>" href="/catalog/<?= $section["CODE"];?>/" > <?= $section["NAME"];?> </a> </div> <?endforeach?> <div class="ag-shop-menu__item ag-menu-breaker"></div> <div class="ag-shop-menu__item item-articles"> <a class="ag-shop-menu__link<? if(preg_match("#^/profile/order/.*#",$_SERVER["REQUEST_URI"])):?> ag-shop-menu__link--active<? endif?>" href="/profile/order/" > Мои заказы </a> </div> <div class="ag-shop-menu__item item-articles"> <a class="ag-shop-menu__link<? if($_SERVER["REQUEST_URI"]=="/profile/wishes/"):?> ag-shop-menu__link--active<? endif?>" href="/profile/wishes/" > Мои желания </a> </div> <div class="ag-shop-menu__item item-articles"> <a class="ag-shop-menu__link<? if($_SERVER["REQUEST_URI"]=="/rules/hiw/"):?> ag-shop-menu__link--active<? endif?>" href="/rules/hiw/" > Правила </a> </div> <div class="ag-shop-menu__item item-articles"> <a class="ag-shop-menu__link<? if($_SERVER["REQUEST_URI"]=="/rules/stores/"):?> ag-shop-menu__link--active<? endif?>" href="/rules/stores/" > Адреса </a> </div> <div class="ag-shop-menu__item item-articles"> <a class="ag-shop-menu__link<? if($_SERVER["REQUEST_URI"]=="/rules/faq/"):?> ag-shop-menu__link--active<? endif?>" href="/rules/faq/" > FAQ </a> </div> </div> <?/* endif */?> </div> </div> <!-- }}} Menu--> </td><td> <!-- Menu {{{--> <? if($arResult["INTERESTS"]):?> <div class="ag-shop-menu<? if($arResult["IN_CATALOG"]):?> tags-menu<? endif ?>"> <div class="ag-shop-menu__container"> <div class="ag-shop-menu__header"> <div class="grid grid--bleed grid--justify-space-between grid--align-content-center"> <div class="grid__col grid__col-shrink"> <h2 class="ag-shop-menu__current">Фильтры<span class="filter-counts"></span></h2> </div> <div class="grid__col grid__col-shrink"> <button class="ag-shop-menu__button ag-shop-menu__button--lines js-menu__button" type="button"><span></span></button> </div> </div> </div> <? /*if(preg_match("#^/catalog/.*#",$_SERVER["REQUEST_URI"])):*/?> <div class="ag-shop-menu__items js-menu__list" style="margin-left:-132%;width:225%;"> <? if($arResult["INTERESTS"]):?> <div class="ag-shop-filter__variants mobile-filter" id="interests-filter" style="display: block; text-align: center;"> <? foreach($arResult["INTERESTS"] as $INTEREST_ID=>$INTEREST):?> <label> <input type="checkbox" class="ag-interest" value="<?= $INTEREST_ID ?>" title="<?= $INTEREST["NAME"]?>"> <div class="ag-shop-filter__variants-item"> <?= $INTEREST["NAME"]?> <? if($INTEREST["COUNT"]):?> (<?= $INTEREST["COUNT"] ?>) <? endif ?> </div> </label> <? endforeach ?> </div> <? endif ?> </div> <?/* endif */?> </div> </div> <? endif ?> <!-- }}} Menu--> </td></tr></table>
active-citizen/shop.1c
www/local/components/ag/menu.catalog/templates/.default/template.php
PHP
gpl-3.0
6,782
/* * * Copyright (C) 2012 Stuart Bridgens * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 3) as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "squarefit.h" /*** RELIEF ***/ typedef enum { eUp, eDown, eLeft, eRight } eDirection; typedef struct defRelief{ unsigned int start, dist; } sRelief; typedef struct defListRelief{ sRelief *arr; unsigned int num; eDirection dir; unsigned int min, max; } sListRelief; /*!\brief Returns false if it would introduce a gap. */ bool addRelief(sListRelief *addTo, sSquare *add){ unsigned int numAdds=0; if(addTo == NULL) return FALSE; unsigned int s, d; switch(addTo->dir){ case eUp: s = add->x; d = add->y; break; case eDown: s = add->x; d = add->y + add->h; break; case eLeft: s = add->y; d = add->x; break; case eRight: s = add->y; d = add->x + add->w; break; default: return FALSE; } unsigned int start; if(addTo->num == 0 || s < addTo->arr[0].start) start = 0; else for(start=0; start < addTo->num && s < addTo->arr[start].start; ++start); if(start == addTo->num){ /** append */ ++addTo->num; addTo->arr = realloc_chk(addTo->arr, addTo->num * sizeof(sRelief)); sRelief *ref = &addTo->arr[ addTo->num-1 ]; ref->start = s; ref->dist = d; numAdds = 1; }else{ /** insert */ int remain; int stop = start; /** where in the original list do we stop with the new relief */ sRelief *newRelief = NULL; /** All the new relief created by the square */ unsigned int end; unsigned int prev = addTo->arr[stop].dist; switch(addTo->dir){ case eUp: case eDown: remain = (int)add->w; end = add->x + add->w; break; case eLeft: case eRight: remain = (int)add->h; end = add->y + add->h; break; default: return FALSE; } if(start==0){ newRelief = malloc_chk(sizeof(sRelief)); newRelief[0].start = s; newRelief[0].dist = d; remain -= (int)addTo->arr[0].start -s; prev = d; ++numAdds; } unsigned int nextD; while(remain > 0){ nextD = addTo->arr[stop].dist; if(prev > d || nextD > d){ /** Don't bother if it's all below the new relief or the same */ if(nextD > d) prev = nextD; else prev = d; ++numAdds; newRelief = realloc_chk(newRelief, numAdds * sizeof(sRelief)); newRelief[numAdds-1].start = addTo->arr[stop].start; newRelief[numAdds-1].dist = prev; } ++stop; if(stop < addTo->num){ remain -= addTo->arr[stop].start; if(remain < 0){ /** if our new relief cuts into the end */ ++numAdds; newRelief = realloc_chk(newRelief, numAdds * sizeof(sRelief)); newRelief[numAdds-1].start = end; newRelief[numAdds-1].dist = addTo->arr[stop -1].dist; } }else{ remain = 0; } } if(numAdds > 0){ /** stitch back together and cleanup */ sRelief *newTotal = calloc_chk(numAdds +addTo->num -stop +start, sizeof(sRelief)); if(start > 0) memcpy(newTotal, addTo->arr, start * sizeof(sRelief)); memcpy(&newTotal[start], newRelief, numAdds * sizeof(sRelief)); if(stop < addTo->num) memcpy(&newTotal[start +numAdds], &addTo->arr[stop], (addTo->num -stop) * sizeof(sRelief)); SAFE_DELETE(addTo->arr); addTo->arr = newTotal; addTo->num = numAdds +addTo->num -stop +start; } SAFE_DELETE(newRelief); } { /** manage min/max */ unsigned int i; addTo->min = (unsigned int) -1; addTo->max = 0; for(i = 0; i < addTo->num; ++i){ if(addTo->arr[i].dist > addTo->max) addTo->max = addTo->arr[i].dist; if(addTo->arr[i].dist < addTo->min) addTo->min = addTo->arr[i].dist; } } return TRUE; } void cleanupListRelief(sListRelief *clean){ SAFE_DELETE(clean->arr); clean->num = 0; } void printRelief(const sListRelief *printMe){ if(printMe == NULL) return; printf("Relief (%i, %i) ", printMe->min, printMe->max); switch(printMe->dir){ case eUp: printf(" up"); break; case eDown: printf(" down"); break; case eLeft: printf(" left"); break; case eRight: printf(" right"); break; } unsigned int i; for(i = 0; i < printMe->num; ++i){ printf(" (%i, %i)", printMe->arr[i].start, printMe->arr[i].dist); } printf("\n"); } /*** SQUARES ***/ /** Works only on empty squares. */ errCode consolidate(sListSquares *squares){ XTRA_LOG("-consolidate"); if(squares == NULL){ printf("<error> consolidate: squares are null\n"); return ERROR; } sListUint unfilled; memset(&unfilled, 0, sizeof(unfilled)); unsigned int i; for(i = 0; i < squares->num; ++i){ if(squares->dynarrFills[i] == FALSE) pushListUint(&unfilled, i); } # ifdef XTRA_LOGGING printSquares(squares); # endif /** gather clusters */ while(unfilled.num > 1){ sListUint cluster; memset(&cluster, 0, sizeof(sListUint)); sListUint branches; memset(&branches, 0, sizeof(sListUint)); sListSquares addThese; memset(&addThese, 0, sizeof(sListSquares)); sListUint remThese; memset(&remThese, 0, sizeof(remThese)); sListRelief reliefU; memset(&reliefU, 0, sizeof(sListRelief)); sListRelief reliefD; memset(&reliefD, 0, sizeof(sListRelief)); sListRelief reliefL; memset(&reliefL, 0, sizeof(sListRelief)); sListRelief reliefR; memset(&reliefR, 0, sizeof(sListRelief)); unsigned int c; sSquare *refO, *refMe, *refYou; reliefU.dir = eUp; reliefD.dir = eDown; reliefL.dir = eLeft; reliefR.dir = eRight; /** Start from the top/left most square. */ i = 0; refO = NULL; for(c = 0; c < unfilled.num; ++c){ refMe = &squares->dynarrSquares[ unfilled.arr[c] ]; if(refO == NULL || refMe->x + refMe->y < refO->x + refO->y){ refO = &squares->dynarrSquares[ unfilled.arr[c] ]; i = c; } } pushListUint(&branches, unfilled.arr[i]); pushListUint(&cluster, unfilled.arr[i]); snipListUint(&unfilled, i); refMe = &squares->dynarrSquares[branches.arr[0]]; addRelief(&reliefU, refMe); addRelief(&reliefD, refMe); addRelief(&reliefL, refMe); addRelief(&reliefR, refMe); while(branches.num > 0){ refMe = &squares->dynarrSquares[branches.arr[0]]; for(c = 0; c < unfilled.num; ++c){ refYou = &squares->dynarrSquares[ unfilled.arr[c] ]; if( ( (refYou->x == refMe->x + refMe->w) &&( (refYou->y >= refMe->y && refYou->y <= refMe->y + refMe->h) || (refYou->y + refYou->y >= refMe->y && refYou->y + refYou->y <= refYou->y + refYou->h) || (refYou->y < refMe->y && refYou->y + refYou->h > refMe->y + refMe->h) ) )||( (refYou->y == refMe->y + refMe->h) &&( (refYou->x >= refMe->x && refYou->x <= refMe->x + refMe->w) || (refYou->x + refYou->x >= refMe->x && refYou->x + refYou->x <= refYou->x + refYou->w) || (refYou->x < refMe->x && refYou->x + refYou->w > refMe->x + refMe->w) ) ) ){ pushListUint(&branches, unfilled.arr[c]); pushListUint(&cluster, unfilled.arr[c]); snipListUint(&unfilled, c); addRelief(&reliefU, refYou); addRelief(&reliefD, refYou); addRelief(&reliefL, refYou); addRelief(&reliefR, refYou); } } snipListUint(&branches, 0); } cleanupListUint(&branches); if(cluster.num < 2) goto consolidate_endLoop; /** Add and remove squares. */ { sSquare bign; bign.x = reliefL.max; bign.y = reliefU.min; bign.w = reliefR.min - bign.x; bign.h = reliefD.min - bign.y; /** detect if there are any unfilled squares creating donuts under the consolidated square. */ /** carry on */ addThese.boundryW = squares->boundryW; addThese.boundryH = squares->boundryH; EOE( addSquarePtr(&addThese, FALSE, &bign) ); sSquare isec; for(c = 0; c < cluster.num; ++c){ refYou = &squares->dynarrSquares[ cluster.arr[c] ]; EOE( overlap(&bign, refYou, &isec) ); if(isec.x == 0 || isec.y == 0 || isec.w == 0 || isec.h == 0) continue; EOE( addSquarePtr(&addThese, FALSE, &isec) ); pushListUint(&remThese, cluster.arr[c]); if(refYou->w != isec.w && refYou->h != isec.h){ if(refYou->x == isec.x){ if(refYou->y == isec.y){ addSquare(&addThese, FALSE, refYou->x, isec.y + isec.h, refYou->w, refYou->h - isec.h); addSquare(&addThese, FALSE, refYou->x + isec.w, refYou->y, refYou->w - isec.w, refYou->h); }else{ addSquare(&addThese, FALSE, refYou->x, refYou->y, refYou->w, refYou->h - isec.h); addSquare(&addThese, FALSE, refYou->x + isec.w, isec.y, refYou->w - isec.w, refYou->h - isec.h); } }else{ if(refYou->y == isec.y){ addSquare(&addThese, FALSE, refYou->x, refYou->y, refYou->w - isec.w, isec.h); addSquare(&addThese, FALSE, refYou->x, refYou->y + isec.h, refYou->w, refYou->h - isec.h); }else{ addSquare(&addThese, FALSE, refYou->x, refYou->y, refYou->w - isec.w, isec.h); addSquare(&addThese, FALSE, refYou->x, refYou->y, refYou->w - isec.w, isec.h); } } }else if(refYou->w == isec.w){ if(refYou->y == isec.y){ addSquare(&addThese, FALSE, refYou->x, refYou->y + isec.h, refYou->w, refYou->h - isec.h); }else{ addSquare(&addThese, FALSE, refYou->x, refYou->y, refYou->w, refYou->h - isec.h); } }else if(refYou->h == isec.h){ if(refYou->x == isec.x){ addSquare(&addThese, FALSE, refYou->x + isec.w, refYou->y, refYou->w - isec.w, isec.h); }else{ addSquare(&addThese, FALSE, refYou->x, refYou->y, refYou->w - isec.w, isec.h); } } } /** add it all in a big pot */ if(addThese.num > 0){ const unsigned int total = squares->num - remThese.num + addThese.num; sSquare *newSqu = calloc_chk(total, sizeof(sSquare)); bool *newFill = calloc_chk(total, sizeof(bool)); unsigned int numTmp = 0; unsigned int r; bool rem; for(c = 0; c < squares->num; ++c){ rem = FALSE; for(r=0; r < remThese.num && rem == FALSE; ++r) if(c != remThese.arr[r]) rem = TRUE; if(rem == FALSE){ newSqu[ numTmp ] = squares->dynarrSquares[c]; newFill[ numTmp ] = squares->dynarrFills[c]; ++numTmp; } } for(c = 0; c < addThese.num; ++c){ newSqu[ numTmp ] = addThese.dynarrSquares[c]; ++numTmp; } free(squares->dynarrSquares); free(squares->dynarrFills); squares->dynarrSquares = newSqu; squares->dynarrFills = newFill; squares->num = numTmp; } } consolidate_endLoop: cleanupListSquares(&addThese); cleanupListUint(&remThese); cleanupListRelief(&reliefU); cleanupListRelief(&reliefD); cleanupListRelief(&reliefL); cleanupListRelief(&reliefR); cleanupListUint(&cluster); } cleanupListUint(&unfilled); return NOPROB; } errCode addSquare(sListSquares *squares, bool filled, unsigned int x, unsigned int y, unsigned int w, unsigned int h){ if(squares == NULL){ printf("<error> addSquare: addTo is NULL.\n"); return ERROR; } # ifdef DEBUG if(w == 0 || h == 0){ WARN("addSquare: height or width is zero."); return PROBLEM; }else if(x + w > squares->boundryW || y + h > squares->boundryH){ WARN("addSquare: Square outside boundries (%i, %i, %i, %i) vs (%i, %i)", x, y, w, h, squares->boundryW, squares->boundryH ); return PROBLEM; }else if(anyOverlaps(squares, x, y, w, h)){ WARN("addSquare: Not adding square because it would overlap."); return PROBLEM; }else{ XTRA_LOG("Square added (%i, %i, %i, %i) [%i, %i]", x, y, w, h, squares->boundryW, squares->boundryH); } # endif ++squares->num; squares->dynarrSquares = realloc_chk(squares->dynarrSquares, squares->num * sizeof(sSquare)); squares->dynarrFills = realloc_chk(squares->dynarrFills, squares->num * sizeof(bool)); sSquare *tmp = &squares->dynarrSquares[squares->num-1]; tmp->x = x; tmp->y = y; tmp->w = w; tmp->h = h; squares->dynarrFills[squares->num-1] = filled; return NOPROB; } errCode addSquarePtr(sListSquares *squares, bool filled, sSquare *addMe){ if(addMe==NULL){ printf("<error> addSquarePtr: addMe is null.\n"); return ERROR; } return addSquare(squares, filled, addMe->x, addMe->y, addMe->w, addMe->h); } errCode overlap(const sSquare *a, const sSquare *b, sSquare *isec){ if(a == NULL || b == NULL || isec == NULL) return PROBLEM; memset(isec, 0, sizeof(sSquare)); /** test for the square falling wholing inside another */ if(a->x >= b->x && a->x <= b->x +b->w){ isec->x = a->x; if(a->x +a->w > b->x +b->w) isec->w = b->w -a->x +b->x; else isec->w = a->w; }else if(b->x >= a->x && b->x <= a->x +a->w){ isec->x = b->x; if(b->x +b->w > a->x +a->w) isec->w = a->w -b->x +a->x; else isec->w = b->w; }else if(a->x <= b->x && a->x +a->w >= b->y +b->w){ isec->x = b->x; isec->w = b->w; }else if(b->x <= a->x && b->x +b->w <= a->x +a->w){ isec->x = a->x; isec->w = a->w; } if(isec->w == 0){ if(a->x < b->x && a->x +a->w > b->x +b->w){ isec->w = a->w; isec->x = a->x; }else if(b->x < a->x && b->x +b->w > a->x +a->w){ isec->w = b->w; isec->x = b->x; } } if(a->x >= b->x && a->x <= b->x +b->w){ isec->x = a->x; if(a->x +a->w > b->x +b->w) isec->w = b->w -a->x +b->x; else isec->w = a->w; }else if(b->x >= a->x && b->x <= a->x +a->w){ isec->x = b->x; if(b->x +b->w > a->x +a->w) isec->w = a->w -b->x +a->x; else isec->w = b->w; }else if(a->y <= b->y && a->y +a->h >= b->y +b->h){ isec->y = b->y; isec->h = b->h; }else if(b->y <= a->y && b->y +b->h <= a->y +a->h){ isec->y = a->y; isec->h = a->h; } if(isec->h == 0){ if(a->y < b->y && a->y +a->h > b->y +b->h){ isec->h = b->h; isec->y = b->y; }else if(b->y < a->y && b->y +b->h > a->y +a->h){ isec->h = a->h; isec->y = a->y; } } if(isec->w == 0 || isec->h == 0) memset(isec, 0, sizeof(sSquare)); return NOPROB; } bool anyOverlaps(sListSquares *squares, unsigned int x, unsigned int y, unsigned int w, unsigned int h){ size_t i; sSquare *tmp; for(i=0; i < squares->num; ++i){ tmp = &squares->dynarrSquares[i]; if( ( (x >= tmp->x && x < tmp->x +tmp->w) || (x +w > tmp->x && x +w < tmp->x + tmp->w) ) && ( (y >= tmp->y && y < tmp->y +tmp->h) || (y +h > tmp->y && y +h < tmp->y +tmp->h) ) ){ return TRUE; } } return FALSE; } bool anyOverlapsPtr(sListSquares *squares, sSquare *checkme){ if(checkme==NULL){ printf("<error> anyOverlapsPtr: checkme is null.\n"); return ERROR; } return anyOverlaps(squares, checkme->x, checkme->y, checkme->w, checkme->h); } errCode incBoundries(sListSquares *squares, unsigned int w, unsigned int h){ unsigned int origW = squares->boundryW, origH = squares->boundryH; squares->boundryW += w; squares->boundryH += h; if(squares == NULL){ ERROR_LOG("squares is null."); return ERROR; } if(squares->num==0){ if(w == 0 || h == 0){ WARN("width and height need to be greater than 0"); return PROBLEM; } addSquare(squares, FALSE, 0, 0, w, h); }else if(squares->num==1){ if(squares->dynarrFills[0] == TRUE){ sSquare tmp; memcpy(&tmp, &squares->dynarrSquares[0], sizeof(sSquare)); if(h > 0 && w > 0) EOE( addSquare(squares, FALSE, tmp.w, tmp.h, w, h) ); if(w > 0) EOE( addSquare(squares, FALSE, tmp.w, 0, w, tmp.h) ); if(h > 0) EOE( addSquare(squares, FALSE, 0, tmp.h, tmp.w, h) ); }else{ sSquare *tmp = &squares->dynarrSquares[0]; tmp->w += w; tmp->h += h; } }else{ #if 1 sSquare addme; unsigned int startX = origW, startY = origH; if(w > 0 && h > 0){ int corner = getCornerSquare(squares, eRightSide, eBottomSide); if(squares->dynarrFills[corner] == TRUE){ addme.x = origW; addme.y = origH; addme.w = w; addme.h = h; if(anyOverlapsPtr(squares, &addme) == TRUE) return PROBLEM; EOE( addSquarePtr(squares, FALSE, &addme) ); }else{ sSquare *tmp = &squares->dynarrSquares[0]; tmp = &squares->dynarrSquares[corner]; startX = origW; startY = origH; origW -= tmp->w; origH -= tmp->h; tmp->w += w; tmp->h += h; } } if(w > 0){ addme.x = startX; addme.y = 0; addme.w = w; addme.h = origH; if(anyOverlapsPtr(squares, &addme) == TRUE) return PROBLEM; EOE( addSquarePtr(squares, FALSE, &addme) ); } if(h > 0){ addme.x = 0; addme.y = startY; addme.w = origW; addme.h = h; if(anyOverlapsPtr(squares, &addme) == TRUE) return PROBLEM; EOE( addSquarePtr(squares, FALSE, &addme) ); } #else sSquare *side; unsigned int i; short doHeight; sListSquares newSquares memset(&newSquares, 0, sizeof(newSquares)); int corner = getCornerSquare(squares, eRightSide, eBottomSide); sSquare addme; newSquares.boundryW = squares->boundryW; newSquares.boundryH = squares->boundryH; if(corner < 0 || corner >= squares->num) return PROBLEM; for(doHeight = 0; doHeight < 2; ++doHeight){ if( (doHeight==0 && w > 0) || (doHeight==1 && h > 0) ){ sListUint sides; memset(&sides, 0, sizeof(sListUint)); getSideSquares(squares, &sides, (doHeight==0) ? eRightSide : eBottomSide); for(i=0; i < sides.num; ++i){ if(sides.arr[i] == corner) continue; side = &squares->dynarrSquares[ sides.arr[i] ]; //- Sides should be safe enough to not have to check. if(squares->dynarrFills[ sides.arr[i] ] == TRUE){ if(doHeight==0){ addme.x = origW; addme.y = side->y; addme.w = w; addme.h = side->h; }else{ addme.x = side->x; addme.y = origH; addme.w = side->w; addme.h = h; } if(anyOverlapsPtr(squares, &addme) == TRUE){ WARN("Overlap detected.\n"); continue; } EOE( addSquarePtr( &newSquares, FALSE, &addme) ); }else{ if(doHeight==0) side->w += w; else side->h += h; } } cleanupListUint(&sides); } } tmp = &squares->dynarrSquares[corner]; if(squares->dynarrFills[corner]==TRUE){ if(w > 0){ addme.x = origW; addme.y = tmp->y; addme.w = w; addme.h = tmp->h + h; if(anyOverlapsPtr(squares, &addme) == TRUE){ WARN("Overlap detected.\n"); }else{ EOE( addSquarePtr(&newSquares, FALSE, &addme) ); } } if(h > 0){ addme.x = tmp->x; addme.y = origH; addme.w = tmp->w; addme.h = h; if(anyOverlapsPtr(squares, &addme) == TRUE){ WARN("Overlap detected.\n"); }else{ EOE( addSquarePtr(&newSquares, FALSE, &addme) ); } } }else{ tmp->w += w; tmp->h += h; } if(newSquares.num > 0) joinSquareLists(squares, &newSquares); cleanupListSquares(&newSquares); #endif } XTRA_LOG("New boundries %i, %i", squares->boundryW, squares->boundryH); return NOPROB; } int canFitSquare(sListSquares *squares, unsigned int w, unsigned int h){ if(squares == NULL){ printf("<error> canFitSquare: squares are null.\n"); return -1; } if(squares->num == 0){ printf("canFitSquare: No holes.\n"); return -1; } sSquare *tmp; size_t i; for(i=0; i < squares->num; ++i){ if(squares->dynarrFills[i] == FALSE){ tmp = &squares->dynarrSquares[i]; if(w <= tmp->w && h <= tmp->h){ return i; } } } return -1; } errCode getSideSquares(sListSquares *all, sListUint *outSides, eSquareSide side){ unsigned int idxSide, i; bool most; sSquare *sqrA, *sqrB; cleanupListUint(outSides); for(idxSide=0; idxSide < all->num; ++idxSide){ sqrA = &all->dynarrSquares[idxSide]; most = TRUE; for(i=0; i < all->num && most == TRUE; ++i){ if(i==idxSide) continue; sqrB = &all->dynarrSquares[i]; switch(side){ case eLeftSide: case eRightSide: if( (sqrA->y >= sqrB->y && sqrA->y < sqrB->y + sqrB->h) || (sqrA->y + sqrA->h > sqrB->y && sqrA->y + sqrA->h <= sqrB->y + sqrB->h) ){ if( (side == eLeftSide && sqrB->x < sqrA->x) || (side == eRightSide && sqrB->x > sqrA->x) ) most = FALSE; } break; case eTopSide: case eBottomSide: if( (sqrA->x >= sqrB->x && sqrA->x < sqrB->x + sqrB->w) || (sqrA->x + sqrA->w > sqrB->x && sqrA->x + sqrA->w <= sqrB->x + sqrB->w) ){ if( (side == eTopSide && sqrB->y < sqrA->y) || (side == eBottomSide && sqrB->y > sqrA->y) ) most = FALSE; } break; default: break; } } if(most == TRUE) pushListUint(outSides, idxSide); } return NOPROB; } int getCornerSquare(sListSquares *all, eSquareSide a, eSquareSide b){ bool top2bottom; bool left2right; if(a == eTopSide || b == eTopSide){ top2bottom=FALSE; }else if(a == eBottomSide || b == eBottomSide){ top2bottom=TRUE; }else{ printf("<warning> getCornerSquare: Didn't choose top or bottom sides.\n"); return -1; } if(a == eLeftSide || b == eLeftSide){ left2right=FALSE; }else if(a == eRightSide || b == eRightSide){ left2right=TRUE; }else{ printf("<warning> getCornerSquare: Didn't choose left or right side.\n"); return -1; } sListUint leftOrRightSides; memset(&leftOrRightSides, 0, sizeof(sListUint)); getSideSquares(all, &leftOrRightSides, (left2right==TRUE) ? eRightSide : eLeftSide); sListUint topOrBottomSides; memset(&topOrBottomSides, 0, sizeof(sListUint)); getSideSquares(all, &topOrBottomSides, (top2bottom==TRUE) ? eBottomSide : eTopSide); int found = -1; size_t i, j; for(i=0; i < leftOrRightSides.num; ++i){ for(j=0; j < topOrBottomSides.num; ++j){ if(leftOrRightSides.arr[i] == topOrBottomSides.arr[j]){ found = leftOrRightSides.arr[i]; goto getCornerSquare_endloop; } } } getCornerSquare_endloop: cleanupListUint(&leftOrRightSides); cleanupListUint(&topOrBottomSides); return found; } errCode joinSquareLists(sListSquares *to, sListSquares *from){ if(to == NULL || from == NULL){ printf("<error> joinSquareLists: 'to' or 'from' are null.\n"); return ERROR; } if(from->num == 0){ printf("<warning> joinSquareLists: 'from' has nothing.\n"); return PROBLEM; } to->dynarrSquares = realloc_chk(to->dynarrSquares, (to->num + from->num) * sizeof(sSquare)); memcpy( &to->dynarrSquares[to->num], from->dynarrSquares, from->num * sizeof(sSquare) ); to->dynarrFills = realloc_chk(to->dynarrFills, (to->num + from->num) * sizeof(bool)); memcpy( &to->dynarrFills[to->num], from->dynarrFills, from->num * sizeof(bool) ); to->num += from->num; return NOPROB; } void printSquares(const sListSquares *squares){ sSquare *ref; size_t i; printf("Squares %u * %u\n", squares->boundryW, squares->boundryH); for(i=0; i < squares->num; ++i){ ref = &squares->dynarrSquares[i]; printf("%u: (%u, %u) %u * %u. %s \n", (unsigned int)i, ref->x, ref->y, ref->w, ref->h, (squares->dynarrFills[i]==TRUE) ? "filled" : "empty" ); } } unsigned int getSquareIdxWithId(unsigned int ID){ return 0; } void cleanupListSquares(sListSquares *cleanMe){ SAFE_DELETE(cleanMe->dynarrSquares); SAFE_DELETE(cleanMe->dynarrFills); cleanMe->num = 0; } errCode fillSquare(sListSquares *squares, unsigned int idxFillMe, unsigned int w, unsigned int h){ if(idxFillMe >= squares->num){ printf("<error> fillSquare: bad index.\n"); return ERROR; } if(squares->dynarrFills[idxFillMe] == TRUE){ printf("<warning> fillSquare: square is already filled\n"); return PROBLEM; } sSquare *fill = &squares->dynarrSquares[idxFillMe]; if(w > fill->w || h > fill->h){ printf("<warning> fillSquare: square is too small\n"); return PROBLEM; } squares->dynarrFills[idxFillMe] = TRUE; if(w < fill->w){ unsigned int dif = fill->w -w; fill->w = w; addSquare(squares, FALSE, fill->x +w, fill->y, dif, fill->h); fill = &squares->dynarrSquares[idxFillMe]; //- refresh } if(h < fill->h){ unsigned int dif = fill->h -h; fill->h = h; addSquare(squares, FALSE, fill->x, fill->y +h, fill->w, dif); fill = &squares->dynarrSquares[idxFillMe]; //- refresh } return NOPROB; } errCode copySquares(sListSquares *to, const sListSquares *from){ if(to == NULL || from == NULL) return ERROR; if(from->num ==0) return NOPROB; to->dynarrSquares = calloc_chk(from->num, sizeof(sSquare)); to->dynarrFills = calloc_chk(from->num, sizeof(bool)); to->boundryW = from->boundryW; to->boundryH = from->boundryH; to->num = from->num; memcpy(to->dynarrSquares, from->dynarrSquares, to->num *sizeof(sSquare)); memcpy(to->dynarrFills, from->dynarrFills, to->num *sizeof(bool)); return NOPROB; } int fitNFillSquare( sListSquares *squares, unsigned int holeW, unsigned int holeH, unsigned int maxBoundryW, unsigned int maxBoundryH ){ if(squares == NULL){ WARN("squares is null"); return -1; } if(squares->num == 0){ if(holeW > maxBoundryW || holeH > maxBoundryH){ WARN("Image too large for max size."); return -1; } squares->dynarrSquares = calloc_chk(1, sizeof(sSquare)); squares->dynarrSquares[0].x=0; squares->dynarrSquares[0].y=0; squares->dynarrSquares[0].w =squares->boundryW =holeW; squares->dynarrSquares[0].h =squares->boundryH =holeH; squares->dynarrFills = calloc_chk(1, sizeof(bool)); squares->dynarrFills[0] = TRUE; ++squares->num; return 0; } int idx = canFitSquare(squares, holeW, holeH); if(idx < 0){ /** We need to expand the boundries */ #if 1 if(squares->boundryH >= holeH && squares->boundryW + holeW <= maxBoundryW) incBoundries(squares, holeW, 0); else if(squares->boundryW >= holeW && squares->boundryH + holeH <= maxBoundryH) incBoundries(squares, 0, holeH); else if(squares->boundryW + holeW <= maxBoundryW && squares->boundryH + holeH <= maxBoundryH) incBoundries(squares, holeW, holeH); else return -1; idx = canFitSquare(squares, holeW, holeH); #else size_t b; sListUint rightSides, bottomSides; sListUint *refSides; sSquare *ref, *best=NULL; eSquareSide curSide = eRightSide; while(curSide != NUM_SIDES){ /** Attempt to find a hole on the side with at least 1 dimension large enough. */ if(curSide == eRightSide) refSides = &rightSides; else refSides = &bottomSides; memset(refSides, 0, sizeof(sListUint)); getSideSquares(squares, refSides, curSide); for(b=0; b < refSides->num; ++b){ if(squares->dynarrFills[ refSides->arr[b] ] == FALSE){ ref = &squares->dynarrSquares[ refSides->arr[b] ]; if( (curSide == eRightSide && ref->h >= holeH) || (curSide == eBottomSide && ref->w >= holeW) ){ if(best == NULL){ best = ref; idx = b; }else if( (ref->w + ref->h) < (best->w + best->h) ){ /** The least increase wins */ best = ref; } } } } if(curSide==eRightSide) curSide=eBottomSide; else curSide=NUM_SIDES; } if(best != NULL){ int incW = holeW - best->w; int incH = holeH - best->h; if(incW < 0) incW = 0; if(incH < 0) incH = 0; EOE( incBoundries(squares, (unsigned int)incW, (unsigned int)incH) ); }else{ /** No hole found with at least 1 dimension large enough. */ int corner = getCornerSquare(squares, eRightSide, eBottomSide); if(corner >= 0 && squares->dynarrFills[corner]==FALSE){ int w = holeW - squares->dynarrSquares[corner].w; int h = holeH - squares->dynarrSquares[corner].h; if(w < 0) w =0; if(h < 0) h =0; EOE( incBoundries(squares, (unsigned int)w, (unsigned int)h) ); }else if(holeH <= squares->boundryH && squares->boundryW + holeW <= maxBoundryW){ EOE( incBoundries(squares, holeW, 0) ); }else if(holeW <= squares->boundryW && squares->boundryH + holeH <= maxBoundryH){ EOE( incBoundries(squares, 0, holeH) ); }else if( squares->boundryW + holeW <= maxBoundryW && squares->boundryH + holeH <= maxBoundryH ){ EOE( incBoundries(squares, holeW, holeH) ); } } idx = canFitSquare(squares, holeW, holeH); cleanupListUint(&rightSides); cleanupListUint(&bottomSides); #endif } if(idx >= 0){ EOE( fillSquare(squares, idx, holeW, holeH) ); } return idx; } errCode shrinkwrapSquares(sListSquares *wrapme){ return NOPROB; }
discostubee/texturecram
source/squarefit.c
C
gpl-3.0
28,534
#! /usr/bin/env bash # -*- coding: utf-8 -*- echo " *** Aumentar Tamaño /tmp *** " echo " SELECCIONA UNA OPCION:" echo " 1.-Forma Temporal (Remount)" echo " 2.-Forma Definitiva (fstab)" echo " 0.-Salir" echo "" read -p "OPCIÓN: " OPCION case $OPCION in 0) exit;; 1|2) echo "" echo " *** Tamaño que le quieres dar: *** " echo " Tiene que Quedar de Esta Forma : XY" echo " Ejemplo: 10G " echo " X.-El espacio que quieres que ocupe" echo " Y.-El Multiplicador que quieres usar G=Gigas M=Megas" echo " 0.-Salir" echo "" read -p "Tamaño: " TAMANO case $TAMANO in 0) exit;; *) echo "" echo "Tamaño Anterior:" df | grep /tmp if [[ $OPCION == 2 ]]; then echo "tmpfs /tmp tmpfs nodev,nosuid,size=$TAMANO 0 0" >> /etc/fstab fi echo "Tamaño Actual" sudo mount -o remount,size=$TAMANO /tmp df | grep /tmp ;; esac ;; *) echo "Error: Opcion no valida. Saliendo"; exit 1 ;; :) echo "Error: Está faltando un argumento en alguna parte. Saliendo"; exit 1 ;; ?) echo "Error: Indicador no válido en alguna parte. Saliendo"; exit 1 ;; esac exit 0
JackNapier151/Scripts
Scripts/EditTmp.sh
Shell
gpl-3.0
1,107
#include "Globals.h" #include "Application.h" #include "ModuleInput.h" #include "ModuleRender.h" #include "ModuleCollision.h" using namespace std; ModuleCollision::ModuleCollision() { matrix[COLLIDER_WALL][COLLIDER_WALL] = false; matrix[COLLIDER_WALL][COLLIDER_PLAYER_BODY] = false; matrix[COLLIDER_WALL][COLLIDER_ENEMY_BODY] = false; matrix[COLLIDER_WALL][COLLIDER_ENEMY_WEAPON] = false; matrix[COLLIDER_WALL][COLLIDER_PLAYER_FEET] = true; matrix[COLLIDER_WALL][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_WALL][COLLIDER_PLAYER_JUMP] = false; matrix[COLLIDER_WALL][COLLIDER_ENEMY_SHOT] = true; matrix[COLLIDER_WALL][COLLIDER_BORDER] = false; matrix[COLLIDER_WALL][COLLIDER_ENEMY_FEET] = true; matrix[COLLIDER_BORDER][COLLIDER_BORDER] = false; matrix[COLLIDER_BORDER][COLLIDER_PLAYER_BODY] = false; matrix[COLLIDER_BORDER][COLLIDER_ENEMY_BODY] = false; matrix[COLLIDER_BORDER][COLLIDER_ENEMY_WEAPON] = false; matrix[COLLIDER_BORDER][COLLIDER_PLAYER_FEET] = true; matrix[COLLIDER_BORDER][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_BORDER][COLLIDER_PLAYER_JUMP] = true; matrix[COLLIDER_BORDER][COLLIDER_ENEMY_SHOT] = true; matrix[COLLIDER_BORDER][COLLIDER_WALL] = false; matrix[COLLIDER_BORDER][COLLIDER_ENEMY_FEET] = false; matrix[COLLIDER_PLAYER_BODY][COLLIDER_WALL] = false; matrix[COLLIDER_PLAYER_BODY][COLLIDER_PLAYER_BODY] = false; matrix[COLLIDER_PLAYER_BODY][COLLIDER_ENEMY_BODY] = true; matrix[COLLIDER_PLAYER_BODY][COLLIDER_ENEMY_WEAPON] = true; matrix[COLLIDER_PLAYER_BODY][COLLIDER_PLAYER_FEET] = false; matrix[COLLIDER_PLAYER_BODY][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_PLAYER_BODY][COLLIDER_PLAYER_JUMP] = false; matrix[COLLIDER_PLAYER_BODY][COLLIDER_ENEMY_SHOT] = true; matrix[COLLIDER_PLAYER_BODY][COLLIDER_BORDER] = true; matrix[COLLIDER_PLAYER_BODY][COLLIDER_ENEMY_FEET] = false; matrix[COLLIDER_ENEMY_BODY][COLLIDER_WALL] = false; matrix[COLLIDER_ENEMY_BODY][COLLIDER_PLAYER_BODY] = true; matrix[COLLIDER_ENEMY_BODY][COLLIDER_ENEMY_BODY] = false; matrix[COLLIDER_ENEMY_BODY][COLLIDER_ENEMY_WEAPON] = false; matrix[COLLIDER_ENEMY_BODY][COLLIDER_PLAYER_FEET] = true; matrix[COLLIDER_ENEMY_BODY][COLLIDER_PLAYER_WEAPON] = true; matrix[COLLIDER_ENEMY_BODY][COLLIDER_PLAYER_JUMP] = true; matrix[COLLIDER_ENEMY_BODY][COLLIDER_ENEMY_SHOT] = false; matrix[COLLIDER_ENEMY_BODY][COLLIDER_BORDER] = false; matrix[COLLIDER_ENEMY_BODY][COLLIDER_ENEMY_FEET] = false; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_WALL] = true; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_PLAYER_BODY] = true; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_ENEMY_BODY] = false; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_ENEMY_WEAPON] = false; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_PLAYER_FEET] = false; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_PLAYER_JUMP] = true; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_ENEMY_SHOT] = false; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_BORDER] = true; matrix[COLLIDER_ENEMY_SHOT][COLLIDER_ENEMY_FEET] = false; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_WALL] = false; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_PLAYER_BODY] = true; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_ENEMY_BODY] = false; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_ENEMY_WEAPON] = false; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_PLAYER_FEET] = true; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_PLAYER_JUMP] = true; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_ENEMY_SHOT] = false; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_BORDER] = false; matrix[COLLIDER_ENEMY_WEAPON][COLLIDER_ENEMY_FEET] = false; matrix[COLLIDER_PLAYER_FEET][COLLIDER_WALL] = true; matrix[COLLIDER_PLAYER_FEET][COLLIDER_PLAYER_BODY] = false; matrix[COLLIDER_PLAYER_FEET][COLLIDER_ENEMY_BODY] = true; matrix[COLLIDER_PLAYER_FEET][COLLIDER_ENEMY_WEAPON] = true; matrix[COLLIDER_PLAYER_FEET][COLLIDER_PLAYER_FEET] = true; matrix[COLLIDER_PLAYER_FEET][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_PLAYER_FEET][COLLIDER_PLAYER_JUMP] = false; matrix[COLLIDER_PLAYER_FEET][COLLIDER_ENEMY_SHOT] = false; matrix[COLLIDER_PLAYER_FEET][COLLIDER_BORDER] = false; matrix[COLLIDER_PLAYER_FEET][COLLIDER_ENEMY_FEET] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_WALL] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_PLAYER_BODY] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_ENEMY_BODY] = true; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_ENEMY_WEAPON] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_PLAYER_FEET] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_PLAYER_JUMP] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_ENEMY_SHOT] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_BORDER] = false; matrix[COLLIDER_PLAYER_WEAPON][COLLIDER_ENEMY_FEET] = false; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_WALL] = false; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_PLAYER_BODY] = false; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_ENEMY_BODY] = true; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_ENEMY_WEAPON] = true; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_PLAYER_FEET] = false; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_PLAYER_JUMP] = false; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_ENEMY_SHOT] = true; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_BORDER] = true; matrix[COLLIDER_PLAYER_JUMP][COLLIDER_ENEMY_FEET] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_WALL] = true; matrix[COLLIDER_ENEMY_FEET][COLLIDER_PLAYER_BODY] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_ENEMY_BODY] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_ENEMY_WEAPON] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_PLAYER_FEET] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_PLAYER_WEAPON] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_PLAYER_JUMP] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_ENEMY_SHOT] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_BORDER] = false; matrix[COLLIDER_ENEMY_FEET][COLLIDER_ENEMY_FEET] = false; } // Destructor ModuleCollision::~ModuleCollision() {} update_status ModuleCollision::PreUpdate() { // Remove all colliders scheduled for deletion for (list<Collider*>::iterator it = colliders.begin(); it != colliders.end();) { if ((*it)->to_delete == true) { RELEASE(*it); it = colliders.erase(it); } else ++it; } return UPDATE_CONTINUE; } update_status ModuleCollision::Update() { list<Collider*>::iterator iter; for (list<Collider*>::iterator it = colliders.begin(); it != colliders.end(); ++it) { Collider* previous = *it; iter = it; for (++iter; iter != colliders.end(); ++iter) { Collider* current = *iter; if (previous->CheckCollision(current->rect) == true) { if (matrix[previous->type][current->type] && previous->callback) previous->callback->OnCollision(previous, current); if (matrix[current->type][previous->type] && current->callback) current->callback->OnCollision(current, previous); } } } if(App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) debug = !debug; if(debug == true) DebugDraw(); return UPDATE_CONTINUE; } void ModuleCollision::DebugDraw() { for (list<Collider*>::iterator it = colliders.begin(); it != colliders.end(); ++it) { if ((*it)->type == COLLIDER_PLAYER_FEET || (*it)->type == COLLIDER_ENEMY_FEET) { App->renderer->DrawQuad((*it)->rect, 0, 0, 0, 80); } else if ((*it)->type == COLLIDER_PLAYER_WEAPON || (*it)->type == COLLIDER_ENEMY_WEAPON) { App->renderer->DrawQuad((*it)->rect, 0, 0, 255, 80); } else if ((*it)->type == COLLIDER_PLAYER_JUMP) { App->renderer->DrawQuad((*it)->rect, 255, 255, 0, 80); } else if ((*it)->type == COLLIDER_ENEMY_SHOT) { App->renderer->DrawQuad((*it)->rect, 87, 35, 100, 80); } else App->renderer->DrawQuad((*it)->rect, 255, 0, 0, 80); } } // Called before quitting bool ModuleCollision::CleanUp() { LOG("Freeing all colliders"); for (list<Collider*>::iterator it = colliders.begin(); it != colliders.end(); ++it) RELEASE(*it); colliders.clear(); return true; } Collider* ModuleCollision::AddCollider(const SDL_Rect& rect, COLLIDER_TYPE type, Module* callback) { Collider* ret = new Collider(rect, type, callback); colliders.push_back(ret); return ret; } Collider* ModuleCollision::DeleteCollider(Collider * collider) { if (collider != nullptr) { colliders.remove(collider); RELEASE(collider); } return nullptr; } // ----------------------------------------------------- bool Collider::CheckCollision(const SDL_Rect& r) const { return (rect.x < r.x + r.w && rect.x + rect.w > r.x && rect.y < r.y + r.h && rect.h + rect.y > r.y); }
codeck1/TMNT-Arcade
TMNT arcade/ModuleCollision.cpp
C++
gpl-3.0
8,735
#!/bin/bash VBoxManage modifyvm $1 --macaddress$2 auto
jianyingdeshitou/config
virtualbox/home/bin/modifyvm-mac-auto.sh
Shell
gpl-3.0
56
# AntiLeave Minecraft Plugin ## Description How it works: When a player is in PVP and they log off, a NPC is placed where they logged out. If you kill the NPC, you get what was in the player's inventory. # Version 1.4 [BETA] # Config ```yml Settings: TicksDamager: 3 #Seconds for check PVP TicksEntity: 5 #Life Time Entity Seconds NameEntity: '&4&l%player% Leave...' #Name Entity Health: 700 #Health Entity Messages: KICK: '&4&lYou Leave u bad :(' ``` # Demo Pic ![Pic](https://proxy.spigotmc.org/ee559d38060355b47c3a399970c08e2a868f5cae?url=http%3A%2F%2Fimages.vfl.ru%2Fii%2F1481989257%2Fa61eb608%2F15365842.png)
BigTows/AntiLeave
README.md
Markdown
gpl-3.0
625
using System; using System.Collections.Generic; using System.Linq; using FICS.App.ConfigSubsystem; using FICS.App.GameSubsystem.Modes.Game.Style12; using Helpers.Loggers.CSV; using Proxima.Core.Commons; using Proxima.Core.Commons.Colors; using Proxima.Core.Commons.Positions; using Proxima.Core.Session; namespace FICS.App.GameSubsystem.Modes.Game { /// <summary> /// Represents the FICS game mode. All AI calculations and interactions with enemies will be done here. /// </summary> public class GameMode : FICSModeBase { private const string AILogsDirectory = "AILogs"; private const string CreatingPrefix = "Creating:"; private const string Style12Prefix = "<12>"; private const string HelperThreadsCountConfigKeyName = "HelperThreadsCount"; private GameSession _gameSession; private CsvLogger _csvLogger; private Dictionary<string, GameResult> _gameResultTokens; private Color _engineColor; /// <summary> /// Initializes a new instance of the <see cref="GameMode"/> class. /// </summary> /// <param name="configManager">The configuration manager.</param> public GameMode(ConfigManager configManager) : base(configManager) { var helperThreadsCount = configManager.GetValue<int>(HelperThreadsCountConfigKeyName); _gameSession = new GameSession(helperThreadsCount); _csvLogger = new CsvLogger(AILogsDirectory); _gameResultTokens = new Dictionary<string, GameResult> { { "1-0", GameResult.WhiteWon }, { "0-1", GameResult.BlackWon }, { "1/2-1/2", GameResult.Draw }, { "aborted on move 1", GameResult.Aborted } }; _gameSession.OnGameEnded += GameSession_OnGameEnded; } /// <summary> /// Processes message (does incoming moves, runs AI calculating and changes mode when game has ended.). /// </summary> /// <param name="message">The message to process.</param> public override void ProcessMessage(string message) { if (message.StartsWith(CreatingPrefix, StringComparison.Ordinal)) { InitGameSession(message); } else if (message.StartsWith(Style12Prefix, StringComparison.Ordinal)) { var response = ProcessMoveCommand(message); if (response != string.Empty) { SendData(response); } } else if (_gameResultTokens.Any(p => message.Contains(p.Key))) { SaveGameResult(message); ChangeMode(FICSModeType.Seek); } } /// <summary> /// Inits game session (sets engine color). /// </summary> /// <param name="message">The message to process.</param> private void InitGameSession(string message) { var username = ConfigManager.GetValue<string>("Username"); _engineColor = message.StartsWith($"{CreatingPrefix} {username}", StringComparison.Ordinal) ? Color.White : Color.Black; } /// <summary> /// Processes move command and runs AI calculating if necessary. /// </summary> /// <param name="message">The move message.</param> /// <returns>The response for the message (<see cref="string.Empty"/> if none).</returns> private string ProcessMoveCommand(string message) { var style12Parser = new Style12Parser(); var style12Container = style12Parser.Parse(message); if (style12Container?.Relation == Style12RelationType.EngineMove) { if (_gameSession.WhiteRemainingTime >= style12Container.RemainingTime[(int)Color.White] && _gameSession.BlackRemainingTime >= style12Container.RemainingTime[(int)Color.Black]) { _gameSession.UpdateRemainingTime(Color.White, style12Container.RemainingTime[(int)Color.White]); _gameSession.UpdateRemainingTime(Color.Black, style12Container.RemainingTime[(int)Color.Black]); CalculateEnemyMove(style12Container); return CalculateAIMove(); } } return string.Empty; } /// <summary> /// Applies enemy move to the bitboard. /// </summary> /// <param name="style12Container">The data from FICS.</param> private void CalculateEnemyMove(Style12Container style12Container) { if (style12Container.PreviousMove != null) { var color = style12Container.ColorToMove; var from = style12Container.PreviousMove.From; var to = style12Container.PreviousMove.To; if (style12Container.PreviousMove.PromotionPieceType.HasValue) { var promotionPieceType = style12Container.PreviousMove.PromotionPieceType.Value; _gameSession.Move(color, from, to, promotionPieceType); } else { _gameSession.Move(color, from, to); } } } /// <summary> /// Runs AI calculation and applies best move to the bitboard. /// </summary> /// <returns>The response (best move) to FICS.</returns> private string CalculateAIMove() { var aiResult = _gameSession.MoveAI(_engineColor); if (aiResult == null) { return null; } var fromConverted = PositionConverter.ToString(aiResult.PVNodes[0].From); var toConverted = PositionConverter.ToString(aiResult.PVNodes[0].To); _csvLogger.WriteLine(aiResult, _gameSession.Bitboard); return $"{fromConverted}-{toConverted}"; } /// <summary> /// Saves a game result to the log file. /// </summary> /// <param name="message">The data from FICS with the result message.</param> private void SaveGameResult(string message) { var gameResult = _gameResultTokens.First(p => message.Contains(p.Key)).Value; _csvLogger.WriteLine(gameResult, _engineColor); } private void GameSession_OnGameEnded(object sender, GameEndedEventArgs e) { if (e.GameResult == GameResult.Draw) { SendData("draw"); } } } }
Tearth/Proxima-b-2.0
Proximab/FICS.App/GameSubsystem/Modes/Game/GameMode.cs
C#
gpl-3.0
6,680
/** * Copyright (C) 2002-2013 by * Jeffrey Fulmer - <jeff@joedog.org>, et al. * This file is distributed as part of Siege * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *-- */ #ifndef BOOLEAN_H #define BOOLEAN_H typedef enum {boolean_false=0,boolean_true=1} BOOLEAN; #ifndef FALSE # define FALSE boolean_false #endif /*FALSE*/ #ifndef TRUE # define TRUE boolean_true #endif /*TRUE*/ #endif/*BOOLEAN_H*/
JoeDog/siege
include/joedog/boolean.h
C
gpl-3.0
1,098
/** ****************************************************************************** * @file FLASH/FLASH_WriteProtection/Inc/main.h * @author MCD Application Team * @brief Header for main.c module ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MAIN_H #define __MAIN_H /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_hal.h" #include "stm32072b_eval.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Base address of the Flash pages */ #define ADDR_FLASH_PAGE_0 ((uint32_t)0x08000000) /* Base @ of Page 0, 2 Kbytes */ #define ADDR_FLASH_PAGE_1 ((uint32_t)0x08000800) /* Base @ of Page 1, 2 Kbytes */ #define ADDR_FLASH_PAGE_2 ((uint32_t)0x08001000) /* Base @ of Page 2, 2 Kbytes */ #define ADDR_FLASH_PAGE_3 ((uint32_t)0x08001800) /* Base @ of Page 3, 2 Kbytes */ #define ADDR_FLASH_PAGE_4 ((uint32_t)0x08002000) /* Base @ of Page 4, 2 Kbytes */ #define ADDR_FLASH_PAGE_5 ((uint32_t)0x08002800) /* Base @ of Page 5, 2 Kbytes */ #define ADDR_FLASH_PAGE_6 ((uint32_t)0x08003000) /* Base @ of Page 6, 2 Kbytes */ #define ADDR_FLASH_PAGE_7 ((uint32_t)0x08003800) /* Base @ of Page 7, 2 Kbytes */ #define ADDR_FLASH_PAGE_8 ((uint32_t)0x08004000) /* Base @ of Page 8, 2 Kbytes */ #define ADDR_FLASH_PAGE_9 ((uint32_t)0x08004800) /* Base @ of Page 9, 2 Kbytes */ #define ADDR_FLASH_PAGE_10 ((uint32_t)0x08005000) /* Base @ of Page 10, 2 Kbytes */ #define ADDR_FLASH_PAGE_11 ((uint32_t)0x08005800) /* Base @ of Page 11, 2 Kbytes */ #define ADDR_FLASH_PAGE_12 ((uint32_t)0x08006000) /* Base @ of Page 12, 2 Kbytes */ #define ADDR_FLASH_PAGE_13 ((uint32_t)0x08006800) /* Base @ of Page 13, 2 Kbytes */ #define ADDR_FLASH_PAGE_14 ((uint32_t)0x08007000) /* Base @ of Page 14, 2 Kbytes */ #define ADDR_FLASH_PAGE_15 ((uint32_t)0x08007800) /* Base @ of Page 15, 2 Kbytes */ #define ADDR_FLASH_PAGE_16 ((uint32_t)0x08008000) /* Base @ of Page 16, 2 Kbytes */ #define ADDR_FLASH_PAGE_17 ((uint32_t)0x08008800) /* Base @ of Page 17, 2 Kbytes */ #define ADDR_FLASH_PAGE_18 ((uint32_t)0x08009000) /* Base @ of Page 18, 2 Kbytes */ #define ADDR_FLASH_PAGE_19 ((uint32_t)0x08009800) /* Base @ of Page 19, 2 Kbytes */ #define ADDR_FLASH_PAGE_20 ((uint32_t)0x0800A000) /* Base @ of Page 20, 2 Kbytes */ #define ADDR_FLASH_PAGE_21 ((uint32_t)0x0800A800) /* Base @ of Page 21, 2 Kbytes */ #define ADDR_FLASH_PAGE_22 ((uint32_t)0x0800B000) /* Base @ of Page 22, 2 Kbytes */ #define ADDR_FLASH_PAGE_23 ((uint32_t)0x0800B800) /* Base @ of Page 23, 2 Kbytes */ #define ADDR_FLASH_PAGE_24 ((uint32_t)0x0800C000) /* Base @ of Page 24, 2 Kbytes */ #define ADDR_FLASH_PAGE_25 ((uint32_t)0x0800C800) /* Base @ of Page 25, 2 Kbytes */ #define ADDR_FLASH_PAGE_26 ((uint32_t)0x0800D000) /* Base @ of Page 26, 2 Kbytes */ #define ADDR_FLASH_PAGE_27 ((uint32_t)0x0800D800) /* Base @ of Page 27, 2 Kbytes */ #define ADDR_FLASH_PAGE_28 ((uint32_t)0x0800E000) /* Base @ of Page 28, 2 Kbytes */ #define ADDR_FLASH_PAGE_29 ((uint32_t)0x0800E800) /* Base @ of Page 29, 2 Kbytes */ #define ADDR_FLASH_PAGE_30 ((uint32_t)0x0800F000) /* Base @ of Page 30, 2 Kbytes */ #define ADDR_FLASH_PAGE_31 ((uint32_t)0x0800F800) /* Base @ of Page 31, 2 Kbytes */ #define ADDR_FLASH_PAGE_32 ((uint32_t)0x08010000) /* Base @ of Page 32, 2 Kbytes */ #define ADDR_FLASH_PAGE_33 ((uint32_t)0x08010800) /* Base @ of Page 33, 2 Kbytes */ #define ADDR_FLASH_PAGE_34 ((uint32_t)0x08011000) /* Base @ of Page 34, 2 Kbytes */ #define ADDR_FLASH_PAGE_35 ((uint32_t)0x08011800) /* Base @ of Page 35, 2 Kbytes */ #define ADDR_FLASH_PAGE_36 ((uint32_t)0x08012000) /* Base @ of Page 36, 2 Kbytes */ #define ADDR_FLASH_PAGE_37 ((uint32_t)0x08012800) /* Base @ of Page 37, 2 Kbytes */ #define ADDR_FLASH_PAGE_38 ((uint32_t)0x08013000) /* Base @ of Page 38, 2 Kbytes */ #define ADDR_FLASH_PAGE_39 ((uint32_t)0x08013800) /* Base @ of Page 39, 2 Kbytes */ #define ADDR_FLASH_PAGE_40 ((uint32_t)0x08014000) /* Base @ of Page 40, 2 Kbytes */ #define ADDR_FLASH_PAGE_41 ((uint32_t)0x08014800) /* Base @ of Page 41, 2 Kbytes */ #define ADDR_FLASH_PAGE_42 ((uint32_t)0x08015000) /* Base @ of Page 42, 2 Kbytes */ #define ADDR_FLASH_PAGE_43 ((uint32_t)0x08015800) /* Base @ of Page 43, 2 Kbytes */ #define ADDR_FLASH_PAGE_44 ((uint32_t)0x08016000) /* Base @ of Page 44, 2 Kbytes */ #define ADDR_FLASH_PAGE_45 ((uint32_t)0x08016800) /* Base @ of Page 45, 2 Kbytes */ #define ADDR_FLASH_PAGE_46 ((uint32_t)0x08017000) /* Base @ of Page 46, 2 Kbytes */ #define ADDR_FLASH_PAGE_47 ((uint32_t)0x08017800) /* Base @ of Page 47, 2 Kbytes */ #define ADDR_FLASH_PAGE_48 ((uint32_t)0x08018000) /* Base @ of Page 48, 2 Kbytes */ #define ADDR_FLASH_PAGE_49 ((uint32_t)0x08018800) /* Base @ of Page 49, 2 Kbytes */ #define ADDR_FLASH_PAGE_50 ((uint32_t)0x08019000) /* Base @ of Page 50, 2 Kbytes */ #define ADDR_FLASH_PAGE_51 ((uint32_t)0x08019800) /* Base @ of Page 51, 2 Kbytes */ #define ADDR_FLASH_PAGE_52 ((uint32_t)0x0801A000) /* Base @ of Page 52, 2 Kbytes */ #define ADDR_FLASH_PAGE_53 ((uint32_t)0x0801A800) /* Base @ of Page 53, 2 Kbytes */ #define ADDR_FLASH_PAGE_54 ((uint32_t)0x0801B000) /* Base @ of Page 54, 2 Kbytes */ #define ADDR_FLASH_PAGE_55 ((uint32_t)0x0801B800) /* Base @ of Page 55, 2 Kbytes */ #define ADDR_FLASH_PAGE_56 ((uint32_t)0x0801C000) /* Base @ of Page 56, 2 Kbytes */ #define ADDR_FLASH_PAGE_57 ((uint32_t)0x0801C800) /* Base @ of Page 57, 2 Kbytes */ #define ADDR_FLASH_PAGE_58 ((uint32_t)0x0801D000) /* Base @ of Page 58, 2 Kbytes */ #define ADDR_FLASH_PAGE_59 ((uint32_t)0x0801D800) /* Base @ of Page 59, 2 Kbytes */ #define ADDR_FLASH_PAGE_60 ((uint32_t)0x0801E000) /* Base @ of Page 60, 2 Kbytes */ #define ADDR_FLASH_PAGE_61 ((uint32_t)0x0801E800) /* Base @ of Page 61, 2 Kbytes */ #define ADDR_FLASH_PAGE_62 ((uint32_t)0x0801F000) /* Base @ of Page 62, 2 Kbytes */ #define ADDR_FLASH_PAGE_63 ((uint32_t)0x0801F800) /* Base @ of Page 63, 2 Kbytes */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ #endif /* __MAIN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Fdepraetre/Handmouse
Software/Handmouse_STM/Lib_DL/STM32Cube_FW_F0_V1.8.0/Projects/STM32072B_EVAL/Examples/FLASH/FLASH_WriteProtection/Inc/main.h
C
gpl-3.0
8,297
package com.github.torkjel.rt.api.resources; import java.util.concurrent.atomic.AtomicInteger; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.github.torkjel.rt.api.Services; import com.github.torkjel.rt.api.dispatcher.Dispatcher; import com.github.torkjel.rt.api.model.Event; import lombok.extern.log4j.Log4j; import javax.ws.rs.container.AsyncResponse; @Path("/analytics") @Log4j public class Analytics { private static AtomicInteger submitCount = new AtomicInteger(0); @POST public Response submit( @QueryParam("timestamp") Long ts, @QueryParam("user") String user, @QueryParam("click") String click, @QueryParam("impression") String impression) { log.info("POST /analytics #" + submitCount.incrementAndGet()); if (click == null && impression == null) throw new WebApplicationException(400); Event event = Event.builder() .action(click != null ? "click" : "impression") .timestamp(ts) .user(user) .build(); dispatcher().submit(event); log.info("POST /analytics DONE"); return Response.accepted().build(); } @GET public void retrieve( @Suspended AsyncResponse response, @QueryParam("timestamp") Long timestamp) { log.info("GET /analytics"); dispatcher().retrieve( timestamp, (ts, stats) -> response.resume(Response.ok(stats.toString(), MediaType.TEXT_PLAIN).build())); log.info("GET /analytics DONE"); } @GET @Path("/perworker") public void retrievePerWorker( @Suspended AsyncResponse response, @QueryParam("timestamp") Long timestamp) { log.info("GET /analytics/perworker"); dispatcher().retrieveDetailed( timestamp, stats -> response.resume(Response.ok(stats, MediaType.TEXT_PLAIN).build())); log.info("GET /analytics/perworker DONE"); } @GET @Path("/allslices") public void retrieveAllSlicer(@Suspended AsyncResponse response, @QueryParam("timestamp") Long timestamp) { log.info("GET /analytics/allslices"); if (timestamp == null) timestamp = System.currentTimeMillis() / 1000; dispatcher().retrieveAllSlices( timestamp, stats -> response.resume(Response.ok(stats.toString(), MediaType.TEXT_PLAIN).build())); log.info("GET /analytics/allslices DONE"); } private Dispatcher dispatcher() { return Services.instance().getDispatcher(); } }
torkjel/rt
api/src/main/java/com/github/torkjel/rt/api/resources/Analytics.java
Java
gpl-3.0
2,888
#region using System; using System.Collections.Generic; using System.Linq; using LeagueSharp; #endregion namespace Marksman.Evade { public static class SpellDatabase { public static List<SpellData> Spells = new List<SpellData>(); static SpellDatabase() { //Add spells to the database #region Aatrox Spells.Add( new SpellData { ChampionName = "Aatrox", SpellName = "AatroxQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 600, Range = 650, Radius = 250, MissileSpeed = 2000, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "", }); Spells.Add( new SpellData { ChampionName = "Aatrox", SpellName = "AatroxE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1075, Radius = 35, MissileSpeed = 1250, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "AatroxEConeMissile", }); #endregion Aatrox #region Ahri Spells.Add( new SpellData { ChampionName = "Ahri", SpellName = "AhriOrbofDeception", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 100, MissileSpeed = 2500, MissileAccel = -3200, MissileMaxSpeed = 2500, MissileMinSpeed = 400, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "AhriOrbMissile", CanBeRemoved = true, ForceRemove = true, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Ahri", SpellName = "AhriOrbReturn", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 100, MissileSpeed = 60, MissileAccel = 1900, MissileMinSpeed = 60, MissileMaxSpeed = 2600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileFollowsUnit = true, CanBeRemoved = true, ForceRemove = true, MissileSpellName = "AhriOrbReturn", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Ahri", SpellName = "AhriSeduce", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 60, MissileSpeed = 1550, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "AhriSeduceMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); #endregion Ahri #region Amumu Spells.Add( new SpellData { ChampionName = "Amumu", SpellName = "BandageToss", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 90, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "SadMummyBandageToss", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Amumu", SpellName = "CurseoftheSadMummy", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 550, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 5, IsDangerous = true, MissileSpellName = "", }); #endregion Amumu #region Anivia Spells.Add( new SpellData { ChampionName = "Anivia", SpellName = "FlashFrost", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 110, MissileSpeed = 850, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "FlashFrostSpell", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); #endregion Anivia #region Annie Spells.Add( new SpellData { ChampionName = "Annie", SpellName = "Incinerate", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCone, Delay = 250, Range = 825, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = false, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); Spells.Add( new SpellData { ChampionName = "Annie", SpellName = "InfernalGuardian", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 600, Radius = 251, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "", }); #endregion Annie #region Ashe Spells.Add( new SpellData { ChampionName = "Ashe", SpellName = "Volley", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 60, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VolleyAttack", MultipleNumber = 9, MultipleAngle = 4.62f * (float)Math.PI / 180, CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall, CollisionObjectTypes.Minion } }); Spells.Add( new SpellData { ChampionName = "Ashe", SpellName = "EnchantedCrystalArrow", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 20000, Radius = 130, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "EnchantedCrystalArrow", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall } }); #endregion Ashe #region Bard Spells.Add( new SpellData { ChampionName = "Bard", SpellName = "BardQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "BardQMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Bard", SpellName = "BardR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 3400, Radius = 350, MissileSpeed = 2100, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "BardR", }); #endregion #region Blatzcrink Spells.Add( new SpellData { ChampionName = "Blitzcrank", SpellName = "RocketGrab", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 70, MissileSpeed = 1800, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = true, MissileSpellName = "RocketGrabMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Blitzcrank", SpellName = "StaticField", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 600, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); #endregion Blatzcrink #region Brand Spells.Add( new SpellData { ChampionName = "Brand", SpellName = "BrandBlaze", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 60, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "BrandBlazeMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Brand", SpellName = "BrandFissure", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 850, Range = 900, Radius = 240, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); #endregion Brand #region Braum Spells.Add( new SpellData { ChampionName = "Braum", SpellName = "BraumQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 60, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "BraumQMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Braum", SpellName = "BraumRWrapper", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1200, Radius = 115, MissileSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = true, MissileSpellName = "braumrmissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); #endregion Braum #region Caitlyn Spells.Add( new SpellData { ChampionName = "Caitlyn", SpellName = "CaitlynPiltoverPeacemaker", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 625, Range = 1300, Radius = 90, MissileSpeed = 2200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "CaitlynPiltoverPeacemaker", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Caitlyn", SpellName = "CaitlynEntrapment", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1000, Radius = 80, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 1, IsDangerous = false, MissileSpellName = "CaitlynEntrapmentMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); #endregion Caitlyn #region Cassiopeia Spells.Add( new SpellData { ChampionName = "Cassiopeia", SpellName = "CassiopeiaNoxiousBlast", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 600, Range = 850, Radius = 150, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "CassiopeiaNoxiousBlast", }); Spells.Add( new SpellData { ChampionName = "Cassiopeia", SpellName = "CassiopeiaPetrifyingGaze", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCone, Delay = 600, Range = 825, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = false, DangerValue = 5, IsDangerous = true, MissileSpellName = "CassiopeiaPetrifyingGaze", }); #endregion Cassiopeia #region Chogath Spells.Add( new SpellData { ChampionName = "Chogath", SpellName = "Rupture", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 1200, Range = 950, Radius = 250, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "Rupture", }); #endregion Chogath #region Corki Spells.Add( new SpellData { ChampionName = "Corki", SpellName = "PhosphorusBomb", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 300, Range = 825, Radius = 250, MissileSpeed = 1000, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "PhosphorusBombMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Corki", SpellName = "MissileBarrage", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 200, Range = 1300, Radius = 40, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "MissileBarrageMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Corki", SpellName = "MissileBarrage2", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 200, Range = 1500, Radius = 40, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "MissileBarrageMissile2", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); #endregion Corki #region Darius Spells.Add( new SpellData { ChampionName = "Darius", SpellName = "DariusAxeGrabCone", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCone, Delay = 300, Range = 550, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 3, IsDangerous = true, MissileSpellName = "DariusAxeGrabCone", }); #endregion Darius #region Diana Spells.Add( new SpellData { ChampionName = "Diana", SpellName = "DianaArc", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 895, Radius = 195, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "DianaArc", FromObjects = new[] { "Diana_Q_Trail.troy" }, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); #endregion Diana #region DrMundo Spells.Add( new SpellData { ChampionName = "DrMundo", SpellName = "InfectedCleaverMissileCast", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 60, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "InfectedCleaverMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); #endregion DrMundo #region Draven Spells.Add( new SpellData { ChampionName = "Draven", SpellName = "DravenDoubleShot", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 130, MissileSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "DravenDoubleShotMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Draven", SpellName = "DravenRCast", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 400, Range = 20000, Radius = 160, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "DravenR", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); #endregion Draven #region Ekko Spells.Add( new SpellData { ChampionName = "Ekko", SpellName = "EkkoQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1650, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = true, MissileSpellName = "ekkoqmis", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Ekko", SpellName = "EkkoW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 3750, Range = 1600, Radius = 375, MissileSpeed = 1650, FixedRange = false, DisabledByDefault = true, AddHitbox = false, DangerValue = 3, IsDangerous = false, MissileSpellName = "EkkoW", CanBeRemoved = true }); Spells.Add( new SpellData { ChampionName = "Ekko", SpellName = "EkkoR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1600, Radius = 375, MissileSpeed = 1650, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "EkkoR", CanBeRemoved = true, FromObjects = new[] { "Ekko_Base_R_TrailEnd.troy" } }); #endregion Ekko #region Elise Spells.Add( new SpellData { ChampionName = "Elise", SpellName = "EliseHumanE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 55, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = true, MissileSpellName = "EliseHumanE", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall } }); #endregion Elise #region Evelynn Spells.Add( new SpellData { ChampionName = "Evelynn", SpellName = "EvelynnR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 650, Radius = 350, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "EvelynnR", }); #endregion Evelynn #region Ezreal Spells.Add( new SpellData { ChampionName = "Ezreal", SpellName = "EzrealMysticShot", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 60, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "EzrealMysticShotMissile", ExtraMissileNames = new[] { "EzrealMysticShotPulseMissile" }, CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, Id = 229, }); Spells.Add( new SpellData { ChampionName = "Ezreal", SpellName = "EzrealEssenceFlux", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 80, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "EzrealEssenceFluxMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Ezreal", SpellName = "EzrealTrueshotBarrage", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 1000, Range = 20000, Radius = 160, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "EzrealTrueshotBarrage", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, Id = 245, }); #endregion Ezreal #region Fizz Spells.Add( new SpellData { ChampionName = "Fizz", SpellName = "FizzMarinerDoom", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 120, MissileSpeed = 1350, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "FizzMarinerDoomMissile", CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, CanBeRemoved = true, }); #endregion Fizz #region Galio Spells.Add( new SpellData { ChampionName = "Galio", SpellName = "GalioResoluteSmite", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 900, Radius = 200, MissileSpeed = 1300, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GalioResoluteSmite", }); Spells.Add( new SpellData { ChampionName = "Galio", SpellName = "GalioRighteousGust", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 120, MissileSpeed = 1200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GalioRighteousGust", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Galio", SpellName = "GalioIdolOfDurand", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 550, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 5, IsDangerous = true, MissileSpellName = "", }); #endregion Galio #region Gnar Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1125, Radius = 60, MissileSpeed = 2500, MissileAccel = -3000, MissileMaxSpeed = 2500, MissileMinSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, CanBeRemoved = true, ForceRemove = true, MissileSpellName = "gnarqmissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarQReturn", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 2500, Radius = 75, MissileSpeed = 60, MissileAccel = 800, MissileMaxSpeed = 2600, MissileMinSpeed = 60, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, CanBeRemoved = true, ForceRemove = true, MissileSpellName = "GnarQMissileReturn", DisableFowDetection = false, DisabledByDefault = true, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarBigQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1150, Radius = 90, MissileSpeed = 2100, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GnarBigQMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarBigW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotLine, Delay = 600, Range = 600, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GnarBigW", }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 473, Radius = 150, MissileSpeed = 903, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GnarE", }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarBigE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 475, Radius = 200, MissileSpeed = 1000, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GnarBigE", }); Spells.Add( new SpellData { ChampionName = "Gnar", SpellName = "GnarR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 500, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = false, DangerValue = 5, IsDangerous = true, MissileSpellName = "", }); #endregion #region Gragas Spells.Add( new SpellData { ChampionName = "Gragas", SpellName = "GragasQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1100, Radius = 275, MissileSpeed = 1300, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GragasQMissile", ExtraDuration = 4500, ToggleParticleName = "Gragas_.+_Q_(Enemy|Ally)", DontCross = true, }); Spells.Add( new SpellData { ChampionName = "Gragas", SpellName = "GragasE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 950, Radius = 200, MissileSpeed = 1200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GragasE", CanBeRemoved = true, ExtraRange = 300, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion }, }); Spells.Add( new SpellData { ChampionName = "Gragas", SpellName = "GragasR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1050, Radius = 375, MissileSpeed = 1800, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "GragasRBoom", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Gragas #region Graves Spells.Add( new SpellData { ChampionName = "Graves", SpellName = "GravesClusterShot", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 50, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "GravesClusterShotAttack", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, MultipleNumber = 3, MultipleAngle = 15 * (float) Math.PI / 180, }); Spells.Add( new SpellData { ChampionName = "Graves", SpellName = "GravesChargeShot", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 100, MissileSpeed = 2100, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "GravesChargeShotShot", CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Graves #region Heimerdinger Spells.Add( new SpellData { ChampionName = "Heimerdinger", SpellName = "Heimerdingerwm", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1500, Radius = 70, MissileSpeed = 1800, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "HeimerdingerWAttack2", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Heimerdinger", SpellName = "HeimerdingerE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 925, Radius = 100, MissileSpeed = 1200, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "heimerdingerespell", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Heimerdinger #region Irelia Spells.Add( new SpellData { ChampionName = "Irelia", SpellName = "IreliaTranscendentBlades", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 1200, Radius = 65, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "IreliaTranscendentBlades", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Irelia #region Janna Spells.Add( new SpellData { ChampionName = "Janna", SpellName = "JannaQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1700, Radius = 120, MissileSpeed = 900, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "HowlingGaleSpell", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Janna #region JarvanIV Spells.Add( new SpellData { ChampionName = "JarvanIV", SpellName = "JarvanIVDragonStrike", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 600, Range = 770, Radius = 70, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, }); Spells.Add( new SpellData { ChampionName = "JarvanIV", SpellName = "JarvanIVEQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 880, Radius = 70, MissileSpeed = 1450, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, }); Spells.Add( new SpellData { ChampionName = "JarvanIV", SpellName = "JarvanIVDemacianStandard", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 860, Radius = 175, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "JarvanIVDemacianStandard", }); #endregion JarvanIV #region Jayce Spells.Add( new SpellData { ChampionName = "Jayce", SpellName = "jayceshockblast", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 70, MissileSpeed = 1450, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "JayceShockBlastMis", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Jayce", SpellName = "JayceQAccel", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 70, MissileSpeed = 2350, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "JayceShockBlastWallMis", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Jayce #region Jinx //TODO: Detect the animation from fow instead of the missile. Spells.Add( new SpellData { ChampionName = "Jinx", SpellName = "JinxW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 600, Range = 1500, Radius = 60, MissileSpeed = 3300, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "JinxWMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Jinx", SpellName = "JinxR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 600, Range = 20000, Radius = 140, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "JinxR", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); #endregion Jinx #region Kalista Spells.Add( new SpellData { ChampionName = "Kalista", SpellName = "KalistaMysticShot", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 40, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "kalistamysticshotmis", ExtraMissileNames = new[] { "kalistamysticshotmistrue" }, CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Kalista #region Karma Spells.Add( new SpellData { ChampionName = "Karma", SpellName = "KarmaQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 60, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KarmaQMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); //TODO: add the circle at the end. Spells.Add( new SpellData { ChampionName = "Karma", SpellName = "KarmaQMantra", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 80, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KarmaQMissileMantra", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Karma #region Karthus Spells.Add( new SpellData { ChampionName = "Karthus", SpellName = "KarthusLayWasteA2", ExtraSpellNames = new[] { "karthuslaywastea3", "karthuslaywastea1", "karthuslaywastedeada1", "karthuslaywastedeada2", "karthuslaywastedeada3" }, Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 625, Range = 875, Radius = 160, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); #endregion Karthus #region Kassadin Spells.Add( new SpellData { ChampionName = "Kassadin", SpellName = "RiftWalk", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 450, Radius = 270, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "RiftWalk", }); #endregion Kassadin #region Kennen Spells.Add( new SpellData { ChampionName = "Kennen", SpellName = "KennenShurikenHurlMissile1", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1050, Radius = 50, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KennenShurikenHurlMissile1", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Kennen #region Khazix Spells.Add( new SpellData { ChampionName = "Khazix", SpellName = "KhazixW", ExtraSpellNames = new[] { "khazixwlong" }, Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1025, Radius = 73, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KhazixWMissile", CanBeRemoved = true, MultipleNumber = 3, MultipleAngle = 22f * (float) Math.PI / 180, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Khazix", SpellName = "KhazixE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 600, Radius = 300, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KhazixE", }); #endregion Khazix #region Kogmaw Spells.Add( new SpellData { ChampionName = "Kogmaw", SpellName = "KogMawQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 70, MissileSpeed = 1650, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KogMawQMis", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Kogmaw", SpellName = "KogMawVoidOoze", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1360, Radius = 120, MissileSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KogMawVoidOozeMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Kogmaw", SpellName = "KogMawLivingArtillery", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 1200, Range = 1800, Radius = 150, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "KogMawLivingArtillery", }); #endregion Kogmaw #region Leblanc Spells.Add( new SpellData { ChampionName = "Leblanc", SpellName = "LeblancSlide", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 600, Radius = 220, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LeblancSlide", }); Spells.Add( new SpellData { ChampionName = "Leblanc", SpellName = "LeblancSlideM", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 600, Radius = 220, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LeblancSlideM", }); Spells.Add( new SpellData { ChampionName = "Leblanc", SpellName = "LeblancSoulShackle", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 70, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "LeblancSoulShackle", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Leblanc", SpellName = "LeblancSoulShackleM", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 70, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "LeblancSoulShackleM", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Leblanc #region LeeSin Spells.Add( new SpellData { ChampionName = "LeeSin", SpellName = "BlindMonkQOne", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 65, MissileSpeed = 1800, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "BlindMonkQOne", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion LeeSin #region Leona Spells.Add( new SpellData { ChampionName = "Leona", SpellName = "LeonaZenithBlade", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 905, Radius = 70, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "LeonaZenithBladeMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Leona", SpellName = "LeonaSolarFlare", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 1000, Range = 1200, Radius = 300, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "LeonaSolarFlare", }); #endregion Leona #region Lissandra Spells.Add( new SpellData { ChampionName = "Lissandra", SpellName = "LissandraQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 700, Radius = 75, MissileSpeed = 2200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LissandraQMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Lissandra", SpellName = "LissandraQShards", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 700, Radius = 90, MissileSpeed = 2200, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "lissandraqshards", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Lissandra", SpellName = "LissandraE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1025, Radius = 125, MissileSpeed = 850, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LissandraEMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Lulu #region Lucian Spells.Add( new SpellData { ChampionName = "Lucian", SpellName = "LucianQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 500, Range = 1300, Radius = 65, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LucianQ", }); Spells.Add( new SpellData { ChampionName = "Lucian", SpellName = "LucianW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 55, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "lucianwmissile", }); Spells.Add( new SpellData { ChampionName = "Lucian", SpellName = "LucianRMis", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1400, Radius = 110, MissileSpeed = 2800, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "lucianrmissileoffhand", ExtraMissileNames = new[] { "lucianrmissile" }, DontCheckForDuplicates = true, DisabledByDefault = true, }); #endregion Lucian #region Lulu Spells.Add( new SpellData { ChampionName = "Lulu", SpellName = "LuluQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1450, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LuluQMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Lulu", SpellName = "LuluQPix", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1450, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LuluQMissileTwo", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Lulu #region Lux Spells.Add( new SpellData { ChampionName = "Lux", SpellName = "LuxLightBinding", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 70, MissileSpeed = 1200, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "LuxLightBindingMis", //CanBeRemoved = true, //CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall, }, }); Spells.Add( new SpellData { ChampionName = "Lux", SpellName = "LuxLightStrikeKugel", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1100, Radius = 275, MissileSpeed = 1300, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "LuxLightStrikeKugel", ExtraDuration = 5500, ToggleParticleName = "Lux_.+_E_tar_aoe_", DontCross = true, CanBeRemoved = true, DisabledByDefault = true, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Lux", SpellName = "LuxMaliceCannon", Slot = SpellSlot.R, Type = SkillShotType.SkillshotLine, Delay = 1000, Range = 3500, Radius = 190, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "LuxMaliceCannon", }); #endregion Lux #region Malphite Spells.Add( new SpellData { ChampionName = "Malphite", SpellName = "UFSlash", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 1000, Radius = 270, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "UFSlash", }); #endregion Malphite #region Malzahar Spells.Add( new SpellData { ChampionName = "Malzahar", SpellName = "AlZaharCalloftheVoid", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 1000, Range = 900, Radius = 85, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, DontCross = true, MissileSpellName = "AlZaharCalloftheVoid", }); #endregion Malzahar #region Morgana Spells.Add( new SpellData { ChampionName = "Morgana", SpellName = "DarkBindingMissile", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1300, Radius = 80, MissileSpeed = 1200, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "DarkBindingMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Morgana #region Nami Spells.Add( new SpellData { ChampionName = "Nami", SpellName = "NamiQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 950, Range = 1625, Radius = 150, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "namiqmissile", }); Spells.Add( new SpellData { ChampionName = "Nami", SpellName = "NamiR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 2750, Radius = 260, MissileSpeed = 850, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "NamiRMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Nami #region Nautilus Spells.Add( new SpellData { ChampionName = "Nautilus", SpellName = "NautilusAnchorDrag", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 90, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "NautilusAnchorDragMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, //walls? }); #endregion Nautilus #region Nocturne Spells.Add( new SpellData { ChampionName = "Nocturne", SpellName = "NocturneDuskbringer", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1125, Radius = 60, MissileSpeed = 1400, DangerValue = 2, IsDangerous = false, MissileSpellName = "NocturneDuskbringer", CollisionObjects = new[] {CollisionObjectTypes.YasuoWall} }); #endregion Nocturne #region Nidalee Spells.Add( new SpellData { ChampionName = "Nidalee", SpellName = "JavelinToss", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1500, Radius = 40, MissileSpeed = 1300, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "JavelinToss", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Nidalee #region Olaf Spells.Add( new SpellData { ChampionName = "Olaf", SpellName = "OlafAxeThrowCast", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, ExtraRange = 150, Radius = 105, MissileSpeed = 1600, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "olafaxethrow", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); #endregion Olaf #region Orianna Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OriannasQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 1500, Radius = 80, MissileSpeed = 1200, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "orianaizuna", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OriannaQend", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 1500, Radius = 90, MissileSpeed = 1200, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OrianaDissonanceCommand", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 0, Radius = 255, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "OrianaDissonanceCommand", FromObject = "yomu_ring_", }); Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OriannasE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 1500, Radius = 85, MissileSpeed = 1850, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "orianaredact", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Orianna", SpellName = "OrianaDetonateCommand", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 700, Range = 0, Radius = 410, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "OrianaDetonateCommand", FromObject = "yomu_ring_", }); #endregion Orianna #region Quinn Spells.Add( new SpellData { ChampionName = "Quinn", SpellName = "QuinnQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1050, Radius = 80, MissileSpeed = 1550, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "QuinnQMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Quinn #region Rengar Spells.Add( new SpellData { ChampionName = "Rengar", SpellName = "RengarE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 70, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "RengarEFinal", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion Rengar #region RekSai Spells.Add( new SpellData { ChampionName = "RekSai", SpellName = "reksaiqburrowed", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1625, Radius = 60, MissileSpeed = 1950, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = false, MissileSpellName = "RekSaiQBurrowedMis", CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion RekSai #region Riven Spells.Add( new SpellData { ChampionName = "Riven", SpellName = "rivenizunablade", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 125, MissileSpeed = 1600, FixedRange = false, AddHitbox = false, DangerValue = 5, IsDangerous = true, MultipleNumber = 3, MultipleAngle = 15 * (float) Math.PI / 180, MissileSpellName = "RivenLightsaberMissile", ExtraMissileNames = new[] { "RivenLightsaberMissileSide" } }); #endregion Riven #region Rumble Spells.Add( new SpellData { ChampionName = "Rumble", SpellName = "RumbleGrenade", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "RumbleGrenade", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Rumble", SpellName = "RumbleCarpetBombM", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 400, MissileDelayed = true, Range = 1200, Radius = 200, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 4, IsDangerous = false, MissileSpellName = "RumbleCarpetBombMissile", CanBeRemoved = false, CollisionObjects = new CollisionObjectTypes[] { }, }); #endregion Rumble #region Ryze Spells.Add( new SpellData { ChampionName = "Ryze", SpellName = "RyzeQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 900, Radius = 50, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "RyzeQ", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Ryze", SpellName = "ryzerq", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 900, Radius = 50, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ryzerq", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); #endregion #region Sejuani Spells.Add( new SpellData { ChampionName = "Sejuani", SpellName = "SejuaniArcticAssault", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 900, Radius = 70, MissileSpeed = 1600, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "", ExtraRange = 200, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.Minion, CollisionObjectTypes.YasuoWall }, }); //TODO: fix? Spells.Add( new SpellData { ChampionName = "Sejuani", SpellName = "SejuaniGlacialPrisonStart", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 110, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "sejuaniglacialprison", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); #endregion Sejuani #region Sion Spells.Add( new SpellData { ChampionName = "Sion", SpellName = "SionE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 800, Radius = 80, MissileSpeed = 1800, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "SionEMissile", CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Sion", SpellName = "SionR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 800, Radius = 120, MissileSpeed = 1000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, CollisionObjects = new[] { CollisionObjectTypes.Champions }, }); #endregion Sion #region Soraka Spells.Add( new SpellData { ChampionName = "Soraka", SpellName = "SorakaQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 950, Radius = 300, MissileSpeed = 1750, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Soraka #region Shen Spells.Add( new SpellData { ChampionName = "Shen", SpellName = "ShenShadowDash", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 650, Radius = 50, MissileSpeed = 1600, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ShenShadowDash", ExtraRange = 200, CollisionObjects = new[] { CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); #endregion Shen #region Shyvana Spells.Add( new SpellData { ChampionName = "Shyvana", SpellName = "ShyvanaFireball", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 60, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ShyvanaFireballMissile", CollisionObjects = new[] { CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Shyvana", SpellName = "ShyvanaTransformCast", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 150, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ShyvanaTransformCast", ExtraRange = 200, }); #endregion Shyvana #region Sivir Spells.Add( new SpellData { ChampionName = "Sivir", SpellName = "SivirQReturn", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 1250, Radius = 100, MissileSpeed = 1350, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SivirQMissileReturn", DisableFowDetection = false, MissileFollowsUnit = true, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Sivir", SpellName = "SivirQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1250, Radius = 90, MissileSpeed = 1350, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SivirQMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Sivir #region Skarner Spells.Add( new SpellData { ChampionName = "Skarner", SpellName = "SkarnerFracture", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 70, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SkarnerFractureMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Skarner #region Sona Spells.Add( new SpellData { ChampionName = "Sona", SpellName = "SonaR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 140, MissileSpeed = 2400, FixedRange = true, AddHitbox = true, DangerValue = 5, IsDangerous = true, MissileSpellName = "SonaR", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Sona #region Swain Spells.Add( new SpellData { ChampionName = "Swain", SpellName = "SwainShadowGrasp", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 1100, Range = 900, Radius = 180, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "SwainShadowGrasp", }); #endregion Swain #region Syndra Spells.Add( new SpellData { ChampionName = "Syndra", SpellName = "SyndraQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 600, Range = 800, Radius = 150, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SyndraQ", }); Spells.Add( new SpellData { ChampionName = "Syndra", SpellName = "syndrawcast", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 950, Radius = 210, MissileSpeed = 1450, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "syndrawcast", }); Spells.Add( new SpellData { ChampionName = "Syndra", SpellName = "syndrae5", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 300, Range = 950, Radius = 90, MissileSpeed = 1601, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "syndrae5", DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Syndra", SpellName = "SyndraE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 300, Range = 950, Radius = 90, MissileSpeed = 1601, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, DisableFowDetection = true, MissileSpellName = "SyndraE", }); #endregion Syndra #region Talon Spells.Add( new SpellData { ChampionName = "Talon", SpellName = "TalonRake", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 800, Radius = 80, MissileSpeed = 2300, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MultipleNumber = 3, MultipleAngle = 20 * (float) Math.PI / 180, MissileSpellName = "talonrakemissileone", }); Spells.Add( new SpellData { ChampionName = "Talon", SpellName = "TalonRakeReturn", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 800, Radius = 80, MissileSpeed = 1850, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MultipleNumber = 3, MultipleAngle = 20 * (float) Math.PI / 180, MissileSpellName = "talonrakemissiletwo", }); #endregion Riven #region Tahm Kench Spells.Add( new SpellData { ChampionName = "TahmKench", SpellName = "TahmKenchQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 951, Radius = 90, MissileSpeed = 2800, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "tahmkenchqmissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); #endregion Tahm Kench #region Thresh Spells.Add( new SpellData { ChampionName = "Thresh", SpellName = "ThreshQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1100, Radius = 70, MissileSpeed = 1900, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ThreshQMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Thresh", SpellName = "ThreshEFlay", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1075, Radius = 110, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, Centered = true, MissileSpellName = "ThreshEMissile1", }); #endregion Thresh #region Tristana Spells.Add( new SpellData { ChampionName = "Tristana", SpellName = "RocketJump", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 900, Radius = 270, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "RocketJump", }); #endregion Tristana #region Tryndamere Spells.Add( new SpellData { ChampionName = "Tryndamere", SpellName = "slashCast", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 0, Range = 660, Radius = 93, MissileSpeed = 1300, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "slashCast", }); #endregion Tryndamere #region TwistedFate Spells.Add( new SpellData { ChampionName = "TwistedFate", SpellName = "WildCards", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1450, Radius = 40, MissileSpeed = 1000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "SealFateMissile", MultipleNumber = 3, MultipleAngle = 28 * (float) Math.PI / 180, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion TwistedFate #region Twitch Spells.Add( new SpellData { ChampionName = "Twitch", SpellName = "TwitchVenomCask", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 900, Radius = 275, MissileSpeed = 1400, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "TwitchVenomCaskMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Twitch #region Urgot Spells.Add( new SpellData { ChampionName = "Urgot", SpellName = "UrgotHeatseekingLineMissile", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 125, Range = 1000, Radius = 60, MissileSpeed = 1600, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "UrgotHeatseekingLineMissile", CanBeRemoved = true, }); Spells.Add( new SpellData { ChampionName = "Urgot", SpellName = "UrgotPlasmaGrenade", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1100, Radius = 210, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "UrgotPlasmaGrenadeBoom", }); #endregion Urgot #region Varus Spells.Add( new SpellData { ChampionName = "Varus", SpellName = "VarusQMissilee", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1800, Radius = 70, MissileSpeed = 1900, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VarusQMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Varus", SpellName = "VarusE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 1000, Range = 925, Radius = 235, MissileSpeed = 1500, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VarusE", }); Spells.Add( new SpellData { ChampionName = "Varus", SpellName = "VarusR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 120, MissileSpeed = 1950, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "VarusRMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); #endregion Varus #region Veigar Spells.Add( new SpellData { ChampionName = "Veigar", SpellName = "VeigarBalefulStrike", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 950, Radius = 70, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VeigarBalefulStrikeMis", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Veigar", SpellName = "VeigarDarkMatter", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 1350, Range = 900, Radius = 225, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "", }); Spells.Add( new SpellData { ChampionName = "Veigar", SpellName = "VeigarEventHorizon", Slot = SpellSlot.E, Type = SkillShotType.SkillshotRing, Delay = 500, Range = 700, Radius = 80, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = false, DangerValue = 3, IsDangerous = true, DontAddExtraDuration = true, RingRadius = 350, ExtraDuration = 3300, DontCross = true, MissileSpellName = "", }); #endregion Veigar #region Velkoz Spells.Add( new SpellData { ChampionName = "Velkoz", SpellName = "VelkozQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1100, Radius = 50, MissileSpeed = 1300, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VelkozQMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Velkoz", SpellName = "VelkozQSplit", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 900, Radius = 55, MissileSpeed = 2100, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VelkozQMissileSplit", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Velkoz", SpellName = "VelkozW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1200, Radius = 88, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "VelkozWMissile", }); Spells.Add( new SpellData { ChampionName = "Velkoz", SpellName = "VelkozE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 800, Radius = 225, MissileSpeed = 1500, FixedRange = false, AddHitbox = false, DangerValue = 2, IsDangerous = false, MissileSpellName = "VelkozEMissile", }); #endregion Velkoz #region Vi Spells.Add( new SpellData { ChampionName = "Vi", SpellName = "Vi-q", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1000, Radius = 90, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ViQMissile", }); #endregion Vi #region Viktor Spells.Add( new SpellData { ChampionName = "Viktor", SpellName = "Laser", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1500, Radius = 80, MissileSpeed = 780, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ViktorDeathRayMissile", ExtraMissileNames = new[] { "viktoreaugmissile" }, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Viktor #region Xerath Spells.Add( new SpellData { ChampionName = "Xerath", SpellName = "xeratharcanopulse2", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 600, Range = 1600, Radius = 100, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "xeratharcanopulse2", }); Spells.Add( new SpellData { ChampionName = "Xerath", SpellName = "XerathArcaneBarrage2", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 700, Range = 1000, Radius = 200, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "XerathArcaneBarrage2", }); Spells.Add( new SpellData { ChampionName = "Xerath", SpellName = "XerathMageSpear", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 200, Range = 1150, Radius = 60, MissileSpeed = 1400, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MissileSpellName = "XerathMageSpearMissile", CanBeRemoved = true, CollisionObjects = new[] { CollisionObjectTypes.Minion, CollisionObjectTypes.Champions, CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Xerath", SpellName = "xerathrmissilewrapper", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 700, Range = 5600, Radius = 120, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "xerathrmissilewrapper", }); #endregion Xerath #region Yasuo Spells.Add( new SpellData { ChampionName = "Yasuo", SpellName = "yasuoq2", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 400, Range = 550, Radius = 20, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MissileSpellName = "yasuoq2", Invert = true, }); Spells.Add( new SpellData { ChampionName = "Yasuo", SpellName = "yasuoq3w", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1150, Radius = 90, MissileSpeed = 1500, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "yasuoq3w", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); Spells.Add( new SpellData { ChampionName = "Yasuo", SpellName = "yasuoq", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 400, Range = 550, Radius = 20, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = true, MissileSpellName = "yasuoq", Invert = true, }); #endregion Yasuo #region Zac Spells.Add( new SpellData { ChampionName = "Zac", SpellName = "ZacQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotLine, Delay = 500, Range = 550, Radius = 120, MissileSpeed = int.MaxValue, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZacQ", }); #endregion Zac #region Zed Spells.Add( new SpellData { ChampionName = "Zed", SpellName = "ZedShuriken", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 925, Radius = 50, MissileSpeed = 1700, FixedRange = true, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "zedshurikenmisone", FromObjects = new[] { "Zed_Clone_idle.troy", "Zed_Clone_Idle.troy" }, ExtraMissileNames = new[] { "zedshurikenmistwo", "zedshurikenmisthree" }, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Zed #region Ziggs Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 850, Radius = 140, MissileSpeed = 1700, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsQSpell", CanBeRemoved = false, DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsQBounce1", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 850, Radius = 140, MissileSpeed = 1700, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsQSpell2", ExtraMissileNames = new[] { "ZiggsQSpell2" }, CanBeRemoved = false, DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsQBounce2", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 850, Radius = 160, MissileSpeed = 1700, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsQSpell3", ExtraMissileNames = new[] { "ZiggsQSpell3" }, CanBeRemoved = false, DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsW", Slot = SpellSlot.W, Type = SkillShotType.SkillshotCircle, Delay = 250, Range = 1000, Radius = 275, MissileSpeed = 1750, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsW", DisableFowDetection = true, CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsE", Slot = SpellSlot.E, Type = SkillShotType.SkillshotCircle, Delay = 500, Range = 900, Radius = 235, MissileSpeed = 1750, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsE", DisableFowDetection = true, }); Spells.Add( new SpellData { ChampionName = "Ziggs", SpellName = "ZiggsR", Slot = SpellSlot.R, Type = SkillShotType.SkillshotCircle, Delay = 0, Range = 5300, Radius = 500, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZiggsR", DisableFowDetection = true, }); #endregion Ziggs #region Zilean Spells.Add( new SpellData { ChampionName = "Zilean", SpellName = "ZileanQ", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 300, Range = 900, Radius = 210, MissileSpeed = 2000, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZileanQMissile", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall } }); #endregion Zilean #region Zyra Spells.Add( new SpellData { ChampionName = "Zyra", SpellName = "ZyraQFissure", Slot = SpellSlot.Q, Type = SkillShotType.SkillshotCircle, Delay = 600, Range = 800, Radius = 220, MissileSpeed = int.MaxValue, FixedRange = false, AddHitbox = true, DangerValue = 2, IsDangerous = false, MissileSpellName = "ZyraQFissure", }); Spells.Add( new SpellData { ChampionName = "Zyra", SpellName = "ZyraGraspingRoots", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 250, Range = 1150, Radius = 70, MissileSpeed = 1150, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "ZyraGraspingRoots", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); Spells.Add( new SpellData { ChampionName = "Zyra", SpellName = "zyrapassivedeathmanager", Slot = SpellSlot.E, Type = SkillShotType.SkillshotMissileLine, Delay = 500, Range = 1474, Radius = 70, MissileSpeed = 2000, FixedRange = true, AddHitbox = true, DangerValue = 3, IsDangerous = true, MissileSpellName = "zyrapassivedeathmanager", CollisionObjects = new[] { CollisionObjectTypes.YasuoWall }, }); #endregion Zyra //Game.PrintChat("Added " + Spells.Count + " spells."); } public static SpellData GetByName(string spellName) { spellName = spellName.ToLower(); foreach (var spellData in Spells) { if (spellData.SpellName.ToLower() == spellName || spellData.ExtraSpellNames.Contains(spellName)) { return spellData; } } return null; } public static SpellData GetByMissileName(string missileSpellName) { missileSpellName = missileSpellName.ToLower(); foreach (var spellData in Spells) { if (spellData.MissileSpellName != null && spellData.MissileSpellName.ToLower() == missileSpellName || spellData.ExtraMissileNames.Contains(missileSpellName)) { return spellData; } } return null; } public static SpellData GetBySpeed(string ChampionName, int speed, int id = -1) { foreach (var spellData in Spells) { if (spellData.ChampionName == ChampionName && spellData.MissileSpeed == speed && (spellData.Id == -1 || id == spellData.Id)) { return spellData; } } return null; } } }
cna1436/LeagueShark
Marksman/Evade/SpellDatabase.cs
C#
gpl-3.0
141,531
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>) # Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ from . import api class stock_packages(osv.osv): _inherit = "stock.packages" def cancel_postage(self, cr, uid, ids, context=None): for package in self.browse(cr, uid, ids, context=context): if package.shipping_company_name.lower() != "usps": continue usps_config = api.v1.get_config(cr, uid, sale=package.pick_id.sale_id, context=context) test = package.pick_id.logis_company.test_mode if hasattr(package, "tracking_no") and package.tracking_no: try: response = api.v1.cancel_shipping(usps_config, package, shipper=None, test=test) except Exception, e: self.pool.get('stock.packages').write(cr, uid, package.id, {'ship_message': str(e)}, context=context) return { 'type': 'ir.actions.client', 'tag': 'action_warn', 'name': _('Exception'), 'params': {'title': _('Exception'), 'text': str(e), 'sticky': True} } if hasattr(response, "error") or not response.refunds[0].refunded: err = response.error if hasattr(response, "error") else response.refunds[0].message self.pool.get('stock.packages').write(cr, uid, package.id, {'ship_message': err}, context=context) return { 'type': 'ir.actions.client', 'tag': 'action_warn', 'name': _('Failure'), 'params': { 'title': _('Package #%s Cancellation Failed') % package.packge_no, 'text': err, 'sticky': True } } else: self.pool.get('stock.packages').write(cr, uid, package.id, { 'ship_message' : 'Shipment Cancelled', 'tracking_no': '' }, context=context) return super(stock_packages, self).cancel_postage(cr, uid, ids, context=context) stock_packages() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
lercloud/shipping_api_usps
stock_packages.py
Python
gpl-3.0
3,338
#include "folderchooser.h" #include "ui_folderchooser.h" #include <QFileSystemModel> #include <QDir> #include <QPushButton> #include <QDebug> FolderChooser::FolderChooser(const QString & start_folder,QWidget *parent) : QDialog(parent), ui(new Ui::FolderChooser) { ui->setupUi(this); QFileSystemModel *model = new QFileSystemModel(ui->folderView); model->setFilter(QDir::Dirs|QDir::Drives|QDir::NoDotAndDotDot); ui->folderView->setModel(model); QModelIndex root_index = model->setRootPath(start_folder); if (root_index.isValid()) { QItemSelection selection(root_index,model->index(root_index.row(),model->columnCount()-1,root_index.parent())); ui->folderView->selectionModel()->select(selection,QItemSelectionModel::ClearAndSelect); ui->folderView->scrollTo(root_index); ui->folderView->expand(root_index); } connect(ui->folderView->selectionModel(),SIGNAL(selectionChanged(const QItemSelection&,const QItemSelection&)),this,SLOT(selectionChanged())); #if QT_VERSION >= 0x050000 ui->folderView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); #else ui->folderView->header()->setResizeMode(0, QHeaderView::ResizeToContents); #endif ui->folderView->header()->hideSection(1); ui->folderView->header()->hideSection(2); ui->folderView->header()->hideSection(3); selectionChanged(); } FolderChooser::~FolderChooser() { delete ui; } QString FolderChooser::folderPath() const { return ((QFileSystemModel *)ui->folderView->model())->filePath(ui->folderView->selectionModel()->selectedIndexes().at(0)); } void FolderChooser::selectionChanged() { QItemSelectionModel * selection_model = ui->folderView->selectionModel(); QModelIndexList indexes = selection_model->selectedRows(); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled((indexes.count() > 0) && ((QFileSystemModel *)ui->folderView->model())->isDir(indexes.at(0))); }
AlexLevkovich/SimpleArch
folderchooser.cpp
C++
gpl-3.0
1,957
package com.example.jinghuang.proxytest; import android.util.Log; /** * Created by hakimhuang on 2016/12/29. */ public class CodingMyself implements Coding { public final static String TAG = "CodingMyself"; @Override public Object[] doCoding(int time) { Log.d(TAG, "coding myself, coding time=" + time); return new Object[] {"android", "ios"}; } }
jingtalk/VerifySomething
proxytest/src/main/java/com/example/jinghuang/proxytest/CodingMyself.java
Java
gpl-3.0
386
          ([C++](Cpp.md)) ![Qt Creator](PicQtCreator.png)![Ubuntu](PicUbuntu.png) [\[MyUnit.o\] Error 1](CppLinkErrorError1.md) =======================================================================================================================   [Link error](CppLinkError.md).   - [View a screenshot of this error (Build Issue tab)(png)](CppLinkErrorError1_BuildIssues.png) - [View a screenshot of this error (Compiler Output tab)(png)](CppLinkErrorError1_CompileOutput.png)   This [link error](CppLinkError.md) is displayed at the 'Build Issue' tab. The detailed error description can be found at the 'Compile Output' tab.   Detailed error descriptions encountered this way:   - ![Wt](PicWt.png)![Qt Creator](PicQtCreator.png)![Ubuntu](PicUbuntu.png) [cc1plus: internal compiler error: Segmentation fault](CppCompileErrorCc1plusInternalCompilerErrorSegmentationFault.md)          
richelbilderbeek/cpp
content/CppLinkErrorError1.md
Markdown
gpl-3.0
949
package ThanCue.Cues; /** * Created by mike on 27/06/16. */ public class VoiceCue extends Cue { private transient Process voice; private static final long serialVersionUID = 102L; public VoiceCue(){ this.setCueType(CueType.VOICE); } @Override public void playCue() { try { voice = Runtime.getRuntime().exec(new String[]{"espeak", getCueName()}); //todo mac/windows support like with vlcmusicplayer }catch(Exception ex){ ex.printStackTrace(); } } @Override public void stopCue() { voice.destroy(); // voice destruction works like this (@Mike) } }
OhmGeek/ThanCue
src/ThanCue/Cues/VoiceCue.java
Java
gpl-3.0
666
/* * This file is part of the libsigrok project. * * Copyright (C) 2013 Uwe Hermann <uwe@hermann-uwe.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include <check.h> #include "../include/libsigrok/libsigrok.h" #include "lib.h" int main(void) { int ret; Suite *s; SRunner *srunner; s = suite_create("mastersuite"); srunner = srunner_create(s); /* Add all testsuites to the master suite. */ srunner_add_suite(srunner, suite_core()); srunner_add_suite(srunner, suite_driver_all()); srunner_add_suite(srunner, suite_input_all()); srunner_add_suite(srunner, suite_input_binary()); srunner_add_suite(srunner, suite_output_all()); srunner_add_suite(srunner, suite_strutil()); srunner_add_suite(srunner, suite_version()); srunner_run_all(srunner, CK_VERBOSE); ret = srunner_ntests_failed(srunner); srunner_free(srunner); return (ret == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
JenSte/libsigrok
tests/check_main.c
C
gpl-3.0
1,588
<?php TpUtils::requirePaths(array( array('exceptions', 'TpInvalidParameterException.php'), array('TpEetDph.php'), array('TpMerchantConfig.php'), array('TpEscaper.php') )); /** * Class representing one payment instance. */ class TpPayment { /** * Config containing merchant-specific configuration options. * Instance of TpMerchantConfig, passed to the TpPayment constructor. * @var TpMerchantConfig */ protected $config; /** * @var float value indicating the amount of money that should be paid. */ protected $value = NULL; /** * @var string Currency identifier. */ protected $currency = NULL; /** * @var string Payment description that should be visible to the customer. */ protected $description = NULL; /** * Any merchant-specific data, that will be returned to the site after * the payment has been completed. * @var string */ protected $merchantData = NULL; /** * URL where to redirect the user after the payment has been completed. * It defaults to value configured in administration interface, but * can be overwritten using this property. * @var string */ protected $returnUrl = NULL; /** * Target of the “Back to e-shop” button on the offline payment info page. * If not set, defaults to the account URL. Must be a valid HTTP or HTTPS * URL. * * @var string|null */ protected $backToEshopUrl = null; /** * ID of payment method to use for paying. Setting this argument should * be result of user's selection, not merchant's selection. * @var integer */ protected $methodId = NULL; /** * @deprecated * @var string */ protected $customerData = NULL; /** * @var string|null Customer’s e-mail address. Used to send payment info and payment link from the payment info page. */ protected $customerEmail = NULL; /** * @var boolean If card payment will be charged immediately or only blocked and charged later by paymentDeposit operation. */ protected $deposit = NULL; /** * @var boolean If card payment is recurring. */ protected $isRecurring = NULL; /** * @var string numerical specific symbol (used only if payment method supports it). */ protected $merchantSpecificSymbol = NULL; /** * @var TpEetDph VAT decomposition for EET */ protected $eetDph = NULL; /** * Constructor. Create the payment. * @param config Instance of TpMerchantConfig containing merchant's * access credentials to the ThePay system. */ public function __construct(TpMerchantConfig $config = null) { $this->config = $config; if (is_null($this->returnUrl) && isset($_SERVER["HTTP_HOST"]) && isset($_SERVER["REQUEST_URI"])) { $this->returnUrl = ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"])?"https":"http")."://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]; } } /** * Sets the value property. * @param float $value * @throws TpInvalidParameterException */ public function setValue($value) { // Only positive numbers allowed. if (!is_numeric($value) || (double)$value < 0) { throw new TpInvalidParameterException("value"); } else { $this->value = (double)$value; } } /** * * @param string $currency */ public function setCurrency($currency) { $this->currency = $currency; } /** * Sets the description property. * @param string $description */ public function setDescription($description) { $this->description = $description; } /** * Sets the merchantData property. * @param string $data */ public function setMerchantData($data) { $this->merchantData = $data; } /** * Sets the returnUrl property. * @param string $returnUrl */ public function setReturnUrl($returnUrl) { $this->returnUrl = $returnUrl; } /** * @param string|null $backToEshopUrl */ public function setBackToEshopUrl($backToEshopUrl = null) { $this->backToEshopUrl = $backToEshopUrl; } /** * Sets the methodId property. * @param integer $methodId */ public function setMethodId($methodId) { $this->methodId = $methodId; } /** * Return MerchantConfig associated with this payment. * @return TpMerchantConfig */ public function getMerchantConfig() { return $this->config; } /** * Returns the value property. If value was not specified using * setValue() method, NULL is returned. * @return float */ public function getValue() { return $this->value; } /** * Returns the currency property. If currency was not specified using * setCurrency() method, NULL is returned. * @return string */ public function getCurrency() { return $this->currency; } /** * Returns the description property. If description was not specified * using setDescription() method, NULL is returned. * @return string */ public function getDescription() { return $this->description; } /** * Returns the merchantData property. If merchantData was not specified * using setMerchantData() method, NULL is returned. * @return string */ public function getMerchantData() { return $this->merchantData; } /** * Returns the returnUrl property. If returnUrl was not specified using * setReturnUrl() method, NULL is returned. * @return string */ public function getReturnUrl() { return $this->returnUrl; } /** * @return string|null */ public function getBackToEshopUrl() { return $this->backToEshopUrl; } /** * Returns the methodId property. If methodId was not specified using * setMethodId() property, NULL is returned. * @return integer */ public function getMethodId() { return $this->methodId; } /** * @deprecated * Set customer data. * @param string $data */ public function setCustomerData($data = null) { $this->customerData = $data; } /** * @deprecated * @return string previously set customer data */ public function getCustomerData() { return $this->customerData; } /** * @param null|string $customerEmail */ public function setCustomerEmail($customerEmail) { $this->customerEmail = $customerEmail; } /** * @return null|string */ public function getCustomerEmail() { return $this->customerEmail; } /** * @return boolean If card payment will be charged immediately or only blocked and charged later by paymentDeposit operation. */ public function getDeposit() { return $this->deposit; } /** * Set if card payment will be charged immediately or only blocked and charged later by paymentDeposit operation. * @param boolean $deposit */ public function setDeposit($deposit) { $this->deposit = $deposit; } /** * If card payment is recurring. * @return boolean */ public function getIsRecurring() { return $this->isRecurring; } /** * Set if card payment is recurring. * @param boolean $isRecurring */ public function setIsRecurring($isRecurring) { $this->isRecurring = $isRecurring; } /** * Numerical specific symbol (used only if payment method supports it). * @return string */ function getMerchantSpecificSymbol() { return $this->merchantSpecificSymbol; } /** * Numerical specific symbol (used only if payment method supports it). * @return string */ function setMerchantSpecificSymbol($merchantSpecificSymbol) { $this->merchantSpecificSymbol = $merchantSpecificSymbol; } /** * @return TpEetDph VAT decomposition for EET */ function getEetDph() { return $this->eetDph; } /** * @param TpEetDph $eetDph VAT decomposition for EET */ function setEetDph(TpEetDph $eetDph = NULL) { $this->eetDph = $eetDph; } /** * List arguments to put into the URL. Returns associative array of * arguments that should be contained in the ThePay gate call. * @return array */ public function getArgs() { $input = array(); $input["merchantId"] = $this->config->merchantId; $input["accountId"] = $this->config->accountId; if (!is_null($this->value)) { $input["value"] = number_format($this->value, 2, '.', ''); } if (!is_null($this->currency)) { $input["currency"] = $this->currency; } if (!is_null($this->description)) { $input["description"] = $this->description; } if (!is_null($this->merchantData)) { $input["merchantData"] = $this->merchantData; } if (!is_null($this->customerData)){ $input["customerData"] = $this->customerData; } if (!is_null($this->customerEmail)) { $input["customerEmail"] = $this->customerEmail; } if (!is_null($this->returnUrl)) { $input["returnUrl"] = $this->returnUrl; } $backToEshopUrlIsNull = is_null($this->backToEshopUrl); if(!$backToEshopUrlIsNull) { $input['backToEshopUrl'] = $this->backToEshopUrl; } if (!is_null($this->methodId)) { $input["methodId"] = $this->methodId; } if (!is_null($this->deposit)) { $input["deposit"] = $this->deposit ? '1' : '0'; } if (!is_null($this->isRecurring)) { $input["isRecurring"] = $this->isRecurring; } if (!is_null($this->merchantSpecificSymbol)) { $input["merchantSpecificSymbol"] = $this->merchantSpecificSymbol; } if (!is_null($this->eetDph) && !$this->eetDph->isEmpty()){ $input = array_merge($input, $this->eetDph->toArray()); } return $input; } /** * Returns signature to authenticate the payment. The signature * consists of hash of all specified parameters and the merchant * password specified in the configuration. So no one can alter the * payment, because the password is not known. * @return string */ public function getSignature() { $input = $this->getArgs(); $str = ""; foreach ($input as $key => $val) { $str .= $key."=".$val."&"; } $str .= "password=".$this->config->password; return $this->hashFunction($str); } /** * Function that calculates hash. * @param string $str * @return string */ public static function hashFunction($str) { return md5($str); } public function __toString(){ return 'TpGatePayment[value: '.$this->value.'; currency: '.$this->currency.'; description: '.$this->description.'; merchantData: '.$this->merchantData.'; returnUrl: '.$this->returnUrl.'; methodId: '.$this->methodId.'; deposit: '.$this->deposit.'; isRecurring: '.$this->isRecurring.'; merchantSpecificSymbol: '.$this->merchantSpecificSymbol.']'; } }
WebChemistry/ThePay
lib/TpPayment.php
PHP
gpl-3.0
10,188
# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com> # # This file is part of nbxmpp. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; If not, see <http://www.gnu.org/licenses/>. from nbxmpp.namespaces import Namespace from nbxmpp.protocol import NodeProcessed from nbxmpp.structs import StanzaHandler from nbxmpp.task import iq_request_task from nbxmpp.errors import MalformedStanzaError from nbxmpp.modules.base import BaseModule from nbxmpp.modules.util import raise_if_error from nbxmpp.modules.bookmarks.util import parse_bookmarks from nbxmpp.modules.bookmarks.util import build_storage_node BOOKMARK_OPTIONS = { 'pubsub#persist_items': 'true', 'pubsub#access_model': 'whitelist', } class PEPBookmarks(BaseModule): _depends = { 'publish': 'PubSub', 'request_items': 'PubSub', } def __init__(self, client): BaseModule.__init__(self, client) self._client = client self.handlers = [ StanzaHandler(name='message', callback=self._process_pubsub_bookmarks, ns=Namespace.PUBSUB_EVENT, priority=16), ] def _process_pubsub_bookmarks(self, _client, stanza, properties): if not properties.is_pubsub_event: return if properties.pubsub_event.node != Namespace.BOOKMARKS: return item = properties.pubsub_event.item if item is None: # Retract, Deleted or Purged return try: bookmarks = parse_bookmarks(item, self._log) except MalformedStanzaError as error: self._log.warning(error) self._log.warning(stanza) raise NodeProcessed if not bookmarks: self._log.info('Bookmarks removed') return pubsub_event = properties.pubsub_event._replace(data=bookmarks) self._log.info('Received bookmarks from: %s', properties.jid) for bookmark in bookmarks: self._log.info(bookmark) properties.pubsub_event = pubsub_event @iq_request_task def request_bookmarks(self): _task = yield items = yield self.request_items(Namespace.BOOKMARKS, max_items=1) raise_if_error(items) if not items: yield [] bookmarks = parse_bookmarks(items[0], self._log) for bookmark in bookmarks: self._log.info(bookmark) yield bookmarks @iq_request_task def store_bookmarks(self, bookmarks): _task = yield self._log.info('Store Bookmarks') self.publish(Namespace.BOOKMARKS, build_storage_node(bookmarks), id_='current', options=BOOKMARK_OPTIONS, force_node_options=True)
gajim/python-nbxmpp
nbxmpp/modules/bookmarks/pep_bookmarks.py
Python
gpl-3.0
3,379
package com.snail.webgame.game.protocal.fight.checkFight; import org.epilot.ccf.core.processor.ProtocolProcessor; import org.epilot.ccf.core.processor.Request; import org.epilot.ccf.core.processor.Response; import org.epilot.ccf.core.protocol.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.snail.webgame.game.common.GameMessageHead; import com.snail.webgame.game.common.util.Command; import com.snail.webgame.game.protocal.fight.service.FightMgtService; public class CheckFightProcessor extends ProtocolProcessor { private static Logger logger = LoggerFactory.getLogger("logs"); private FightMgtService fightMgtService; public void setFightMgtService(FightMgtService fightMgtService) { this.fightMgtService = fightMgtService; } /** * PVE战斗输出验证 */ public void execute(Request request, Response response) { Message message = request.getMessage(); GameMessageHead header = (GameMessageHead) message.getHeader(); header.setMsgType(Command.CHECK_FIGHT_RESP); int roleId = header.getUserID0(); CheckFightReq req = (CheckFightReq) message.getBody(); fightMgtService.checkFight(roleId, req); if (logger.isInfoEnabled()) { //logger.info(Resource.getMessage("game", "GAME_FIGHT_INFO_5") + ",roleId=" + roleId); } } }
bozhbo12/demo-spring-server
spring-game/src/main/java/com/spring/game/game/protocal/fight/checkFight/CheckFightProcessor.java
Java
gpl-3.0
1,290
#procmailrc h1 { border-bottom:1px solid #DDD; } .tree ul { padding-left:0px; padding-right: 0px; margin-right: 0px; } .tree li { list-style-type:none; margin:0; padding:10px 0px 0px 0px; position:relative; padding-left: 10px; } .tree li::before, .tree li::after { content:''; left:0px; position:absolute; right:auto; } /* vertical */ .tree li::before { border-left:1px solid #DDD; height:100%; top:1px; width:1px; } .tree li:last-child::before { height:40px; } .tree > ul > li:first-child::before { height:50px; top:-10px; } /* horizontal */ .tree li::after { border-top:1px solid #DDD; height:20px; top:40px; width:100%; } .tree li span { display:inline-block; padding:3px 3px; text-decoration:none; }
nitmir/django-procmail
procmail/static/procmail/tree.css
CSS
gpl-3.0
818
#Region "Microsoft.VisualBasic::bea891a36a69e22c25dac9ba470761d7, ..\sciBASIC#\Microsoft.VisualBasic.Architecture.Framework\ComponentModel\IO\WriteStream.vb" ' Author: ' ' asuka (amethyst.asuka@gcmodeller.org) ' xieguigang (xie.guigang@live.com) ' xie (genetics@smrucc.org) ' ' Copyright (c) 2016 GPL3 Licensed ' ' ' GNU GENERAL PUBLIC LICENSE (GPL3) ' ' This program is free software: you can redistribute it and/or modify ' it under the terms of the GNU General Public License as published by ' the Free Software Foundation, either version 3 of the License, or ' (at your option) any later version. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License ' along with this program. If not, see <http://www.gnu.org/licenses/>. #End Region 'Namespace ComponentModel.IO ' Public Delegate Function ToString(Of T)(x As T) As String ' Public Class WriteStream(Of T) : Implements IDisposable ' ReadOnly _stream As System.IO.FileStream ' ReadOnly _toString As ToString(Of T) ' ReadOnly _encoding As System.Text.Encoding ' ReadOnly _endT As String ' Sub New(handle As String, ToString As ToString(Of T), Optional encoding As TextEncodings.Encodings = Encodings.UTF8, Optional endl As String = vbCrLf) ' _stream = New System.IO.FileStream(handle, System.IO.FileMode.OpenOrCreate) ' _toString = ToString ' _encoding = encoding.GetEncodings ' _endT = endl ' End Sub ' Public Sub Write(x As T) ' Dim line As String = _toString(x) & _endT ' Dim buf As Byte() = _encoding.GetBytes(line) ' Call _stream.Write(buf, Scan0, buf.Length) ' End Sub ' Public Sub WriteBlock(source As IEnumerable(Of T)) ' Dim lines = source.ToArray(Function(x) _toString(x)) ' Dim block As String = String.Join(_endT, lines) ' Dim buf As Byte() = _encoding.GetBytes(block) ' Call _stream.Write(buf, Scan0, buf.Length) ' End Sub '#Region "IDisposable Support" ' Private disposedValue As Boolean ' To detect redundant calls ' ' IDisposable ' Protected Overridable Sub Dispose(disposing As Boolean) ' If Not Me.disposedValue Then ' If disposing Then ' ' TODO: dispose managed state (managed objects). ' Call _stream.Flush() ' Call _stream.Close() ' End If ' ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below. ' ' TODO: set large fields to null. ' End If ' Me.disposedValue = True ' End Sub ' ' TODO: override Finalize() only if Dispose(disposing As Boolean) above has code to free unmanaged resources. ' 'Protected Overrides Sub Finalize() ' ' ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above. ' ' Dispose(False) ' ' MyBase.Finalize() ' 'End Sub ' ' This code added by Visual Basic to correctly implement the disposable pattern. ' Public Sub Dispose() Implements IDisposable.Dispose ' ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above. ' Dispose(True) ' ' TODO: uncomment the following line if Finalize() is overridden above. ' ' GC.SuppressFinalize(Me) ' End Sub '#End Region ' End Class 'End Namespace
amethyst-asuka/GCModeller
src/runtime/sciBASIC#/Microsoft.VisualBasic.Architecture.Framework/ComponentModel/IO/WriteStream.vb
Visual Basic
gpl-3.0
3,852
:: Shuts down the system echo Shutting down... shutdown /s /f /t 0
redpois0n/usbwatcher
scripts/shutdown_win.bat
Batchfile
gpl-3.0
68
<?php # -*- coding: utf-8 -*- /** * Plugin Name: Meta Taxonomy * Plugin URI: https://github.com/tfrommen/meta-taxonomy * Description: This plugin registers a taxonomy that provides a high-performance means to query posts in a somewhat meta-based way. * Author: Thorsten Frommen * Author URI: http://tfrommen.de * Version: 1.3.0 * Text Domain: meta-taxonomy * Domain Path: /languages * License: GPLv3 */ namespace tfrommen\MetaTaxonomy; if ( ! function_exists( 'add_action' ) ) { return; } add_action( 'plugins_loaded', __NAMESPACE__ . '\initialize' ); /** * Initializes the plugin. * * @wp-hook plugins_loaded * * @return void */ function initialize() { if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) { require_once __DIR__ . '/vendor/autoload.php'; } $plugin = new Plugin( __FILE__ ); $plugin->initialize(); } if ( file_exists( __DIR__ . '/functions.php' ) ) { include_once __DIR__ . '/functions.php'; }
tfrommen/meta-taxonomy
src/meta-taxonomy.php
PHP
gpl-3.0
959
<?php $i18n = array( 'ADD_FIELD' => "Nieuw veld toevoegen", 'ADD_PAGETYPE' => "Nieuw Speciaal Pagina type aanmaken", 'BROWSE_IMAGES' => "Bladeren", 'BROWSE_PAGES' => "Bladeren", 'CHECKBOX' => "Check box", 'CONFIGURE' => "I18N Speciale Pagina's configureren", 'CONFIG_CREATE_TITLE' => "Nieuw Speciaal Pagina Type aanmaken", 'CONFIG_EDIT_FIELDS_DESCR' => "Hier kunt u additionele invul velden aanmaken, die getoond worden wanneer een Speciale Pagina van dit type bewerkt wordt.", 'CONFIG_EDIT_GENERAL_DESCR' => "Hier kunt u een type Speciale Pagina aanmaken, bijv. voor news, een blog of product specificaties", 'CONFIG_EDIT_SEARCH_DESCR' => "Als u de pagina's van dit type anders wenst weer te geven in de zoekresultaten, voeg dan de relevante HTML/PHP code hier in.", 'CONFIG_EDIT_TITLE' => "Speciaal Pagina Type bewerken", 'CONFIG_EDIT_VIEW_DESCR' => "Als alternatief voor het gebruiken van verschillende templates voor verschillende speciale pagina types, kunt de HTML/PHP code benodigd om een pagina van dit type te tonen hier ingeven.", 'CONFIG_OVERVIEW_DESCR' => "Momenteel zijn de volgende speciale pagina types beschikbaar", 'CONFIG_OVERVIEW_TITLE' => "Speciaal Pagina Types", 'COPY_PAGETYPE' => "Speciaal pagina type kopieren: ", 'CREATE_FROM_TEMPLATE' => "Of selecteer een speciaal pagina type uit een van de templates:", 'CREATE_PAGE' => "Nieuwe Speciale Pagina", 'CREATE_PAGE_DESCR' => "Welk type speciale pagina wilt u aanmaken?", 'CREATE_PAGE_TITLE' => "Nieuwe Speciale Pagina maken", 'DATE_FORMAT' => "%A, %B %e, %Y - %l:%M %p", 'DEFAULT_SEARCH_COMPONENT' => "HTML/PHP code om het standaardgedrag te dupliceren", 'DELETE' => "Delete", 'DELETE_FAILURE' => "Het speciale pagina type kon niet verwijderd worden.", 'DELETE_FIELD' => "Veld deleten", 'DELETE_PAGETYPE' => "Speciaal pagina type deleten: ", 'DELETE_SUCCESS' => "Het speciale pagina type is succesvol verwijderd.", 'DROPDOWN_BOX' => "Dropdown box", 'ERR_EMPTY_FIELD_LABEL' => "De veld titels mogen niet leeg zijn.", 'ERR_EMPTY_FIELD_NAME' => "De veldnamen mogen niet leeg zijn.", 'ERR_EMPTY_TITLE' => "De titel mag niet leeg zijn", 'ERR_INVALID_FIELD_NAME' => "De veldnamen dienen alfanummeriek te zijn.", 'ERR_INVALID_NAME' => "De naam dient alfanummeriek te zijn", 'ERR_MISSING_PARENT' => "U dient een bovenliggende pagina in te geven, als u een menu volgorde aangeeft.", 'ERR_NAME_EXISTS' => "Een speciaal pagina type met deze naam bestaat reeds.", 'ERR_RESERVED_FIELD_NAMES' => "De volgende veldnamen zijn gereserveerd: ", 'FIELD_DEFAULT_VALUE' => "Standaard waarde", 'FIELD_INDEX' => "Index", 'FIELD_LABEL' => "Label", 'FIELD_NAME' => "Naam", 'FIELD_TYPE' => "Type", 'FILTER' => "Filter", 'FILTER_TITLE' => "Vul een deel van een titel in of : en een tag/sleutelwoord", 'HEADERCOMPONENT' => "HTML/PHP code voor de kop van de pagina", 'IMAGE' => "Foto", 'LINK' => "Link", 'LONG_TEXT_FIELD' => "Lang tekst veld", 'MENU' => "Menu", 'MENU_DESCR' => "Selecteer, of en zo ja hoe een pagina van dit type weergegeven zal worden in het menu. U dient ook de bovenliggende pagina in te geven.", 'MENU_FIRST_POS' => "Nieuwste pagina als eerste", 'MENU_LAST_POS' => "Nieuwste pagina als laatste", 'MENU_NO' => "Niet in het menu", 'MENU_REVSLUG_POS' => "Gesorteerd op slug/URL, oplopend", 'MENU_SLUG_POS' => "Gesorteerd op slug/URL, aflopend", 'NAME' => "Naam", 'NAME_DESCR' => "De naam van het speciale pagina type - moet alfanummeriek zijn en wordt bijv. gebruikt om alle pagina's te tonen van dit type", 'PAGES' => "Toon alle Speciale Pagina's", 'PAGES_DESCR' => "Selecteer SVP het type Speciale Pagina's dat u wenst weer te geven.", 'PAGES_FOR' => "Speciale Pagina's van het type ", 'PAGES_TITLE' => "Toon Speciale Pagina's", 'PARENT_PAGE_DESCR' => "Als u de bovenliggende pagina leeg laat, dient deze geselecteerd te worden op het moment dat een pagina aangemaakt wordt", 'SAVE' => "Speciaal Pagina Type opslaan", 'SAVE_FAILURE' => "Het speciale pagina type kon niet opgeslagen worden.", 'SAVE_SUCCESS' => "Het speciale pagina type is succesvol opgeslagen.", 'SEARCHCOMPONENT' => "HTML/PHP code voor de weergave van een zoekresultaat", 'SET_DEFAULT' => "Bewerken...", 'SET_DEFAULT_CONTENT' => "Stel de standaard pagina inhoud in...", 'SHOWCOMPONENT' => "HTML/PHP code voor de weergave van een pagina", 'SLUG_URL_DESCR' => "Hier kunt u een patroon ingeven voor de automatisch aangemaakte slug/URL: Het moet minimaal 1 placeholder bevatten voor de functie strftime, bijv.: %d (dag van de maand in cijfers), %m (maand in cijfers), %y (jaar, 2 cijfers), %Y (jaar, 4 cijfers), %H (uren, 0-23), %M (minuten), %S (seconden)", 'TAB_FIELDS' => "Velden", 'TAB_GENERAL' => "Algemeen", 'TAB_SEARCH' => "Zoek", 'TAB_VIEW' => "Toon", 'TAG_KEYWORDS_DESCR' => "Deze tags/sleutelwoorden, welke gescheiden dienen te zijn met komma's, worden automatisch ingevoegd zodra een pagina aangemaakt worden, u kunt ze later nog aanpassen.", 'TEMPLATE_DESCR' => "Hier kunt u bepalen welke template voor dit pagina type gebruikt dient te worden. Of u maakt gebruik van de standaard template.", 'TEXTAREA' => "Multi-lijns tekst veld", 'TEXT_FIELD' => "Tekst veld", 'TITLE' => "Titel", 'UNDO_FAILURE' => "De custom velden konden niet hersteld worden.", 'UNDO_SUCCESS' => "De custom velden zijn succesvol hersteld.", 'VIEW_CREDATE' => "op creatie datum", 'VIEW_HIERARCHICAL' => "hierarchisch", 'VIEW_PUBDATE' => "op datum", 'VIEW_TITLE' => "op titel", 'WYSIWYG_EDITOR' => "WYSIWYG editor" );
mogilka/smiletrade
plugins/i18n_specialpages/lang/nl.php
PHP
gpl-3.0
5,848
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; using System.Collections.Immutable; namespace Microsoft.Cci { /// <summary> /// Target CPU types. /// </summary> internal enum Machine : ushort { // TODO: Should consider unifying this enum with MetadataReader.PEFileFlags.Machine !!! /// <summary> /// The target CPU is unknown or not specified. /// </summary> Unknown = 0x0000, /// <summary> /// Intel 386. /// </summary> I386 = 0x014C, /// <summary> /// ARM Thumb-2 little-endian. /// </summary> ARMThumb2 = 0x01c4, /// <summary> /// Intel 64 /// </summary> IA64 = 0x0200, /// <summary> /// AMD64 (K8) /// </summary> AMD64 = 0x8664, } /// <summary> /// The kind of metadata stored in the module. For example whether the module is an executable or a manifest resource file. /// </summary> internal enum ModuleKind { /// <summary> /// The module is an executable with an entry point and has a console. /// </summary> ConsoleApplication, /// <summary> /// The module is an executable with an entry point and does not have a console. /// </summary> WindowsApplication, /// <summary> /// The module is a library of executable code that is dynamically linked into an application and called via the application. /// </summary> DynamicallyLinkedLibrary, /// <summary> /// The module is a .winmdobj file. /// </summary> WindowsRuntimeMetadata, /// <summary> /// The module contains no executable code. Its contents is a resource stream for the modules that reference it. /// </summary> ManifestResourceFile, /// <summary> /// The module is a library of executable code but contains no .NET metadata and is specific to a processor instruction set. /// </summary> UnmanagedDynamicallyLinkedLibrary } /// <summary> /// Represents a .NET assembly. /// </summary> internal interface IAssembly : IModule, IAssemblyReference { /// <summary> /// A list of the files that constitute the assembly. These are not the source language files that may have been /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well /// as any external resources. It corresonds to the File table of the .NET assembly file format. /// </summary> IEnumerable<IFileReference> GetFiles(EmitContext context); /// <summary> /// A set of bits and bit ranges representing properties of the assembly. The value of <see cref="Flags"/> can be set /// from source code via the AssemblyFlags assembly custom attribute. The interpretation of the property depends on the target platform. /// </summary> uint Flags { get; } /// <summary> /// The public part of the key used to encrypt the SHA1 hash over the persisted form of this assembly. Empty or null if not specified. /// This value is used by the loader to decrypt an encrypted hash value stored in the assembly, which it then compares with a freshly computed hash value /// in order to verify the integrity of the assembly. /// </summary> IEnumerable<byte> PublicKey { get; } /// <summary> /// The contents of the AssemblySignatureKeyAttribute /// </summary> string SignatureKey { get; } AssemblyHashAlgorithm HashAlgorithm { get; } } /// <summary> /// A reference to a .NET assembly. /// </summary> internal interface IAssemblyReference : IModuleReference { /// <summary> /// Identifies the culture associated with the assembly reference. Typically specified for sattelite assemblies with localized resources. /// Empty or null if not specified. /// </summary> string Culture { get; } /// <summary> /// True if the implementation of the referenced assembly used at runtime is not expected to match the version seen at compile time. /// </summary> bool IsRetargetable { get; } /// <summary> /// Type of code contained in an assembly. Determines assembly binding model. /// </summary> AssemblyContentType ContentType { get; } /// <summary> /// The hashed 8 bytes of the public key of the referenced assembly. This is empty or null if the referenced assembly does not have a public key. /// </summary> IEnumerable<byte> PublicKeyToken { get; } /// <summary> /// The version of the assembly reference. Null means Version(0, 0, 0, 0). /// </summary> Version Version { get; } } /// <summary> /// An object that represents a .NET module. /// </summary> internal interface IModule : IUnit, IModuleReference { /// <summary> /// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly. /// </summary> IEnumerable<ITypeExport> GetExportedTypes(EmitContext context); /// <summary> /// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata /// with this assembly. /// </summary> IEnumerable<ICustomAttribute> AssemblyAttributes { get; } /// <summary> /// A list of objects representing persisted instances of pairs of security actions and sets of security permissions. /// These apply by default to every method reachable from the module. /// </summary> IEnumerable<SecurityAttribute> AssemblySecurityAttributes { get; } /// <summary> /// A list of the assemblies that are referenced by this module. /// </summary> IEnumerable<IAssemblyReference> GetAssemblyReferences(EmitContext context); /// <summary> /// A list of named byte sequences persisted with the assembly and used during execution, typically via .NET Framework helper classes. /// </summary> IEnumerable<ManagedResource> GetResources(EmitContext context); /// <summary> /// CorLibrary assembly referenced by this module. /// </summary> IAssemblyReference GetCorLibrary(EmitContext context); /// <summary> /// The preferred memory address at which the module is to be loaded at runtime. /// </summary> ulong BaseAddress { get; // ^ ensures result > uint.MaxValue ==> this.Requires64bits; } /// <summary> /// The Assembly that contains this module. If this module is main module then this returns this. /// </summary> new IAssembly GetContainingAssembly(EmitContext context); /// <summary> /// Flags that control the behavior of the target operating system. CLI implementations are supposed to ignore this, but some operating system pay attention. /// </summary> ushort DllCharacteristics { get; } /// <summary> /// The method that will be called to start execution of this executable module. /// </summary> IMethodReference EntryPoint { get; // ^ requires this.Kind == ModuleKind.ConsoleApplication || this.Kind == ModuleKind.WindowsApplication; } /// <summary> /// The alignment of sections in the module's image file. /// </summary> uint FileAlignment { get; } /// <summary> /// Returns zero or more strings used in the module. If the module is produced by reading in a CLR PE file, then this will be the contents /// of the user string heap. If the module is produced some other way, the method may return an empty enumeration or an enumeration that is a /// subset of the strings actually used in the module. The main purpose of this method is to provide a way to control the order of strings in a /// prefix of the user string heap when writing out a module as a PE file. /// </summary> IEnumerable<string> GetStrings(); /// <summary> /// Returns all top-level (not nested) types defined in the current module. /// </summary> IEnumerable<INamespaceTypeDefinition> GetTopLevelTypes(EmitContext context); /// <summary> /// True if the module contains only IL and is processor independent. /// </summary> bool ILOnly { get; } /// <summary> /// The kind of metadata stored in this module. For example whether this module is an executable or a manifest resource file. /// </summary> ModuleKind Kind { get; } /// <summary> /// The first part of a two part version number indicating the version of the linker that produced this module. For example, the 8 in 8.0. /// </summary> byte LinkerMajorVersion { get; } /// <summary> /// The first part of a two part version number indicating the version of the linker that produced this module. For example, the 0 in 8.0. /// </summary> byte LinkerMinorVersion { get; } /// <summary> /// Specifies the target CPU. /// </summary> Machine Machine { get; } /// <summary> /// The first part of a two part version number indicating the version of the format used to persist this module. For example, the 1 in 1.0. /// </summary> byte MetadataFormatMajorVersion { get; } /// <summary> /// The second part of a two part version number indicating the version of the format used to persist this module. For example, the 0 in 1.0. /// </summary> byte MetadataFormatMinorVersion { get; } /// <summary> /// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata /// with this module. /// </summary> IEnumerable<ICustomAttribute> ModuleAttributes { get; } /// <summary> /// The name of the module. /// </summary> string ModuleName { get; } /// <summary> /// A list of the modules that are referenced by this module. /// </summary> IEnumerable<IModuleReference> ModuleReferences { get; } /// <summary> /// A globally unique persistent identifier for this module. /// </summary> Guid PersistentIdentifier { get; } bool StrongNameSigned { get; } /// <summary> /// If set, the module contains instructions or assumptions that are specific to the AMD 64 bit instruction set. Setting this flag to /// true also sets Requires64bits to true. /// </summary> bool RequiresAmdInstructionSet { get; } /// <summary> /// If set, the module must include a machine code stub that transfers control to the virtual execution system. /// </summary> bool RequiresStartupStub { get; } /// <summary> /// If set, the module contains instructions that assume a 32 bit instruction set. For example it may depend on an address being 32 bits. /// This may be true even if the module contains only IL instructions because of PlatformInvoke and COM interop. /// </summary> bool Requires32bits { get; } /// <summary> /// True if the module contains only IL and is processor independent. Should there be a choice between launching as a 64-bit or 32-bit /// process, this setting will cause the host to launch it as a 32-bit process. /// </summary> bool Prefers32bits { get; } /// <summary> /// If set, the module contains instructions that assume a 64 bit instruction set. For example it may depend on an address being 64 bits. /// This may be true even if the module contains only IL instructions because of PlatformInvoke and COM interop. /// </summary> bool Requires64bits { get; } /// <summary> /// The size of the virtual memory initially committed for the initial process heap. /// </summary> ulong SizeOfHeapCommit { get; // ^ ensures result > uint.MaxValue ==> this.Requires64bits; } /// <summary> /// The size of the virtual memory to reserve for the initial process heap. /// </summary> ulong SizeOfHeapReserve { get; // ^ ensures result > uint.MaxValue ==> this.Requires64bits; } /// <summary> /// The size of the virtual memory initially committed for the initial thread's stack. /// </summary> ulong SizeOfStackCommit { get; // ^ ensures result > uint.MaxValue ==> this.Requires64bits; } /// <summary> /// The size of the virtual memory to reserve for the initial thread's stack. /// </summary> ulong SizeOfStackReserve { get; // ^ ensures result > uint.MaxValue ==> this.Requires64bits; } /// <summary> /// Identifies the version of the CLR that is required to load this module or assembly. /// </summary> string TargetRuntimeVersion { get; } /// <summary> /// True if the instructions in this module must be compiled in such a way that the debugging experience is not compromised. /// To set the value of this property, add an instance of System.Diagnostics.DebuggableAttribute to the MetadataAttributes list. /// </summary> bool TrackDebugData { get; } /// <summary> /// A list of named byte sequences persisted with the module and used during execution, typically via the Win32 API. /// A module will define Win32 resources rather than "managed" resources mainly to present metadata to legacy tools /// and not typically use the data in its own code. /// </summary> IEnumerable<IWin32Resource> Win32Resources { get; } /// <summary> /// An alternate form the Win32 resources may take. These represent the rsrc$01 and rsrc$02 section data and relocs /// from a COFF object file. /// </summary> ResourceSection Win32ResourceSection { get; } IAssembly AsAssembly { get; } ITypeReference GetPlatformType(PlatformType t, EmitContext context); bool IsPlatformType(ITypeReference typeRef, PlatformType t); IEnumerable<IReference> ReferencesInIL(out int count); /// <summary> /// Builds symbol definition to location map used for emitting token -> location info /// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj) /// </summary> MultiDictionary<DebugSourceDocument, DefinitionWithLocation> GetSymbolToLocationMap(); ImmutableArray<ExternNamespace> ExternNamespaces { get; } ushort MajorSubsystemVersion { get; } ushort MinorSubsystemVersion { get; } // An approximate number of method definitions that can // provide a basis for approximating the capacities of // various databases used during Emit. int HintNumberOfMethodDefinitions { get; } } internal struct DefinitionWithLocation { public readonly IDefinition Definition; public readonly uint StartLine; public readonly uint StartColumn; public readonly uint EndLine; public readonly uint EndColumn; public DefinitionWithLocation(IDefinition definition, int startLine, int startColumn, int endLine, int endColumn) { Debug.Assert(startLine >= 0); Debug.Assert(startColumn >= 0); Debug.Assert(endLine >= 0); Debug.Assert(endColumn >= 0); this.Definition = definition; this.StartLine = (uint)startLine; this.StartColumn = (uint)startColumn; this.EndLine = (uint)endLine; this.EndColumn = (uint)endColumn; } public override string ToString() { return string.Format( "{0} => start:{1}/{2}, end:{3}/{4}", this.Definition.ToString(), this.StartLine.ToString(), this.StartColumn.ToString(), this.EndLine.ToString(), this.EndColumn.ToString()); } } /// <summary> /// A reference to a .NET module. /// </summary> internal interface IModuleReference : IUnitReference { /// <summary> /// The Assembly that contains this module. May be null if the module is not part of an assembly. /// </summary> IAssemblyReference GetContainingAssembly(EmitContext context); } /// <summary> /// A unit of metadata stored as a single artifact and potentially produced and revised independently from other units. /// Examples of units include .NET assemblies and modules, as well C++ object files and compiled headers. /// </summary> internal interface IUnit : IUnitReference, IDefinition { } /// <summary> /// A reference to a instance of <see cref="IUnit"/>. /// </summary> internal interface IUnitReference : IReference, INamedEntity { } }
FrankLIKE/il2bc
CoreSource/PEWriter/Units.cs
C#
gpl-3.0
18,056
/* * Platformer Game Engine by Wohlstand, a free platform for game making * Copyright (c) 2014-2019 Vitaly Novichkov <admin@wohlnet.ru> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #ifndef WLD_HISTORY_MANAGER_H #define WLD_HISTORY_MANAGER_H #include <QObject> #include "items/item_tile.h" #include "items/item_scene.h" #include "items/item_path.h" #include "items/item_level.h" #include "items/item_music.h" #include "items/item_point.h" class WldHistoryManager : public QObject { Q_OBJECT friend class WldScene; WldScene* m_scene; bool historyChanged; int historyIndex; QList<QSharedPointer<IHistoryElement> > operationList; public: explicit WldHistoryManager(WldScene* scene, QObject* parent = nullptr); void addRemoveHistory(WorldData removedItems); void addPlaceHistory(WorldData placedItems); void addOverwriteHistory(WorldData removedItems, WorldData placedItems); void addMoveHistory(WorldData sourceMovedItems, WorldData targetMovedItems); void addChangeWorldSettingsHistory(HistorySettings::WorldSettingSubType subtype, QVariant extraData); void addChangeSettingsHistory(WorldData modifiedItems, HistorySettings::WorldSettingSubType subType, QVariant extraData); void addRotateHistory(WorldData rotatedItems, WorldData unrotatedItems); void addFlipHistory(WorldData flippedItems, WorldData unflippedItems); void addTransformHistory(WorldData transformedItems, WorldData sourceItems); //history information int getHistroyIndex(); bool canUndo(); bool canRedo(); public slots: //history modifiers void historyBack(); void historyForward(); void updateHistoryBuffer(); signals: void refreshHistoryButtons(); void showStatusMessage(QString text, int delay=2000); }; #endif // WLD_HISTORY_MANAGER_H
Wohlhabend-Networks/PGE-Project
Editor/editing/_scenes/world/wld_history_manager.h
C
gpl-3.0
2,430
package org.monstercraft.irc.plugin.handles.thread; import org.monstercraft.irc.plugin.Configuration.Variables; import org.monstercraft.irc.plugin.handles.IRCHandler; public class OutputThread extends Thread implements Runnable { private final IRCHandler parent; public OutputThread(final IRCHandler parent) { this.parent = parent; } @Override public void run() { while (parent.isConnected()) { try { int i = 0; while (!parent.getQueue().isEmpty()) { try { final String message = parent.getQueue().remove(); parent.write(message + "\r\n"); i++; if (i >= Variables.limit) { break; } if (parent.getQueue().isEmpty()) { break; } } catch (final Exception e) { break; } } if (Variables.limit != 0) { Thread.sleep(1000 / Variables.limit); } } catch (final Exception e) { break; } } } }
Monstercraft/MonsterIRC
src/main/java/org/monstercraft/irc/plugin/handles/thread/OutputThread.java
Java
gpl-3.0
1,294
#include "../../openexr-2.5.7/OpenEXR/IlmImf/ImfFastHuf.h"
AlienCowEatCake/ImageViewer
src/ThirdParty/OpenEXR/include/OpenEXR/ImfFastHuf.h
C
gpl-3.0
59
package com.toblexson.generators; import java.util.Random; import com.toblexson.reference.Values; import com.toblexson.tiles.ElevationTile; public class ElevationGenerator { private ElevationTile[][] grid; private Random random = new Random(); //Basic chance private double chance = 0.15; public ElevationGenerator(ElevationTile[][] grid) { this.grid = grid; addElevation(); } private void addElevation() { int[] tileAbove = new int[2]; int[] tileBelow = new int[2]; int[] tileLeft = new int[2]; int[] tileRight = new int[2]; for(int x = 0; x < Values.maxX; x++) { for(int y = 0; y < Values.maxY; y++) { tileAbove[0] = x; tileAbove[1] = y - 1; tileBelow[0] = x; tileBelow[1] = y + 1; tileLeft[0] = x - 1; tileLeft[1] = y; tileRight[0] = x + 1; tileRight[1] = y; GenTerrain(tileAbove, tileBelow, tileLeft, tileRight, -10, x, y, 1); GenTerrain(tileAbove, tileBelow, tileLeft, tileRight, 10, x, y, 4); GenTerrain(tileAbove, tileBelow, tileLeft, tileRight, 20, x, y, 3); } } } private void GenTerrain(int[] tileAbove, int[] tileBelow, int[] tileLeft, int[] tileRight, int height, int x, int y, int iterations) { for(int a = 0; a < iterations; a++) { System.out.println(a); //check if tile is within array if(tileAbove[1] < Values.maxY && tileAbove[1] >= 0 && tileBelow[1] < Values.maxX && tileBelow[1] >= 0 && tileLeft[0] < Values.maxY && tileLeft[0] >= 0 && tileRight[0] < Values.maxY && tileRight[0] >= 0) { //if so check to see if next to tile of height 20+ lower if(grid[tileAbove[0]] [tileAbove[1]].getElevation() == height - 20 || grid[tileBelow[0]] [tileBelow[1]].getElevation() == height - 20 || grid[tileLeft[0]] [tileLeft[1]].getElevation() == height - 20 || grid[tileRight[0]] [tileRight[1]].getElevation() == height - 20) { //generate tile with low change if(random.nextInt(100) < (chance / 4) * 100) { grid[x][y].setElevation(height); } //else if tile is next to same height tile } else if(grid[tileAbove[0]] [tileAbove[1]].getElevation() == height || grid[tileBelow[0]] [tileBelow[1]].getElevation() == height || grid[tileLeft[0]] [tileLeft[1]].getElevation() == height || grid[tileRight[0]] [tileRight[1]].getElevation() == height) { //generate tile with high chance if(random.nextInt(100) < (chance / 0.8) * 100) { grid[x][y].setElevation(height); } //else generate tile with normal chance } else { if(random.nextInt(100) < chance * 100) { grid[x][y].setElevation(height); } } } } } }
ToblexsonMC/DrainageBasinGenerator
src/com/toblexson/generators/ElevationGenerator.java
Java
gpl-3.0
2,688
using System; using System.Collections.Generic; using System.Text; using System.Net; using Semantria.Com.Mapping.Output; namespace Semantria.Com { public class RequestEventArgs : EventArgs { public RequestEventArgs(string method, string url, string message) { _method = method; _url = url; _message = message; } private string _method; public string Method { get { return _method; } } private string _url; public string Url { get { return _url; } } private string _message; public string Message { get { return _message; } } } public class ResponseEventArgs : EventArgs { public ResponseEventArgs() { } public ResponseEventArgs(HttpStatusCode status, string message) { _status = status; _message = message; } private HttpStatusCode _status; public HttpStatusCode Status { get { return _status; } } private string _message; public string Message { get { return _message; } } } public class ResponseErrorEventArgs : ResponseEventArgs { public ResponseErrorEventArgs(Type type, HttpStatusCode status, string message) : base(status, message) { _type = type; } private Type _type; public Type Type { get { return _type; } } } public class DocsAutoResponseEventArgs : EventArgs { public DocsAutoResponseEventArgs(IList<DocAnalyticData> analyticdata) { _analyticdata = analyticdata; } private IList<DocAnalyticData> _analyticdata; public IList<DocAnalyticData> AnalyticData { get { return _analyticdata; } } } public class CollsAutoResponseEventArgs : EventArgs { public CollsAutoResponseEventArgs(IList<CollAnalyticData> analyticdata) { _analyticdata = analyticdata; } private IList<CollAnalyticData> _analyticdata; public IList<CollAnalyticData> AnalyticData { get { return _analyticdata; } } } }
hacksome/hacksome
Semantria/Common/EventArgs.cs
C#
gpl-3.0
2,681
// stdafx.cpp : source file that includes just the standard includes // SearchlightWin32Project.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
InstitutoDOr/BROCCOLI
code/Bash_Wrapper/SearchlightWin32Project/SearchlightWin32Project/stdafx.cpp
C++
gpl-3.0
302
#region References using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; using Server.Diagnostics; #endregion namespace Server.Network { public class MessagePump { private Listener[] m_Listeners; private Queue<NetState> m_Queue; private Queue<NetState> m_WorkingQueue; private readonly Queue<NetState> m_Throttled; public MessagePump() { IPEndPoint[] ipep = Listener.EndPoints; m_Listeners = new Listener[ipep.Length]; bool success = false; do { for (int i = 0; i < ipep.Length; i++) { var l = new Listener(ipep[i]); if (!success && l != null) { success = true; } m_Listeners[i] = l; } if (!success) { Utility.PushColor(ConsoleColor.Yellow); Console.WriteLine("Retrying..."); Utility.PopColor(); Thread.Sleep(10000); } } while (!success); m_Queue = new Queue<NetState>(); m_WorkingQueue = new Queue<NetState>(); m_Throttled = new Queue<NetState>(); } public Listener[] Listeners { get { return m_Listeners; } set { m_Listeners = value; } } public void AddListener(Listener l) { Listener[] old = m_Listeners; m_Listeners = new Listener[old.Length + 1]; for (int i = 0; i < old.Length; ++i) { m_Listeners[i] = old[i]; } m_Listeners[old.Length] = l; } private void CheckListener() { for (int j = 0; j < m_Listeners.Length; ++j) { Socket[] accepted = m_Listeners[j].Slice(); for (int i = 0; i < accepted.Length; ++i) { var ns = new NetState(accepted[i], this); ns.Start(); if (ns.Running) { Utility.PushColor(ConsoleColor.Green); Console.WriteLine("Client: {0}: Connected. [{1} Online]", ns, NetState.Instances.Count); Utility.PopColor(); } } } } public void OnReceive(NetState ns) { lock (this) m_Queue.Enqueue(ns); Core.Set(); } public void Slice() { CheckListener(); lock (this) { Queue<NetState> temp = m_WorkingQueue; m_WorkingQueue = m_Queue; m_Queue = temp; } while (m_WorkingQueue.Count > 0) { NetState ns = m_WorkingQueue.Dequeue(); if (ns.Running) { HandleReceive(ns); } } lock (this) { while (m_Throttled.Count > 0) { m_Queue.Enqueue(m_Throttled.Dequeue()); } } } private const int BufferSize = 4096; private readonly BufferPool m_Buffers = new BufferPool("Processor", 4, BufferSize); private bool HandleSeed(NetState ns, ByteQueue buffer) { #region EC Support if (buffer.GetPacketID() == 0xFF) { // Packet 255 = 0xFF = Client KR. ns.IsKRClient = true; Console.WriteLine("KR-Client detected", ns); } #endregion if (buffer.GetPacketID() == 0xEF) { // new packet in client 6.0.5.0 replaces the traditional seed method with a seed packet // 0xEF = 239 = multicast IP, so this should never appear in a normal seed. So this is backwards compatible with older clients. ns.Seeded = true; return true; } else if (buffer.Length >= 4) { var m_Peek = new byte[4]; buffer.Dequeue(m_Peek, 0, 4); int seed = (m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3]; if (seed == 0) { Utility.PushColor(ConsoleColor.Green); Console.WriteLine("Login: {0}: Invalid client detected, disconnecting", ns); Utility.PopColor(); ns.Dispose(); return false; } ns.m_Seed = seed; ns.Seeded = true; return true; } else { return false; } } private bool CheckEncrypted(NetState ns, int packetID) { /* if (!ns.SentFirstPacket && packetID != 0xF0 && packetID != 0xF1 && packetID != 0xCF && packetID != 0x80 && packetID != 0x91 && packetID != 0xA4 && packetID != 0xEF) */ #region EC Support if (!ns.SentFirstPacket && packetID != 0xF0 && packetID != 0xF1 && packetID != 0xCF && packetID != 0x80 && packetID != 0x91 && packetID != 0xA4 && packetID != 0xEF && packetID != 0xE4 && packetID != 0xFF) #endregion { Console.WriteLine("Client: {0}: Encrypted client detected, disconnecting", ns); ns.Dispose(); return true; } return false; } public void HandleReceive(NetState ns) { ByteQueue buffer = ns.Buffer; if (buffer == null || buffer.Length <= 0) { return; } lock (buffer) { if (!ns.Seeded) { if (!HandleSeed(ns, buffer)) { return; } } int length = buffer.Length; while (length > 0 && ns.Running) { int packetID = buffer.GetPacketID(); if (CheckEncrypted(ns, packetID)) { break; } PacketHandler handler = ns.GetHandler(packetID); if (handler == null) { var data = new byte[length]; length = buffer.Dequeue(data, 0, length); new PacketReader(data, length, false).Trace(ns); break; } int packetLength = handler.Length; if (packetLength <= 0) { if (length >= 3) { packetLength = buffer.GetPacketLength(); if (packetLength < 3) { ns.Dispose(); break; } } else { break; } } if (length >= packetLength) { if (handler.Ingame) { if (ns.Mobile == null) { Utility.PushColor(ConsoleColor.DarkRed); Console.WriteLine( "Client: {0}: Sent ingame packet (0x{1:X2}) before having been attached to a mobile", ns, packetID); Utility.PopColor(); ns.Dispose(); break; } else if (ns.Mobile.Deleted) { ns.Dispose(); break; } } ThrottlePacketCallback throttler = handler.ThrottleCallback; if (throttler != null && !throttler(ns)) { m_Throttled.Enqueue(ns); return; } PacketReceiveProfile prof = null; if (Core.Profiling) { prof = PacketReceiveProfile.Acquire(packetID); } if (prof != null) { prof.Start(); } byte[] packetBuffer; if (BufferSize >= packetLength) { packetBuffer = m_Buffers.AcquireBuffer(); } else { packetBuffer = new byte[packetLength]; } packetLength = buffer.Dequeue(packetBuffer, 0, packetLength); var r = new PacketReader(packetBuffer, packetLength, handler.Length != 0); handler.OnReceive(ns, r); length = buffer.Length; if (BufferSize >= packetLength) { m_Buffers.ReleaseBuffer(packetBuffer); } if (prof != null) { prof.Finish(packetLength); } } else { break; } } } #region EC Support // Would be nicer to detect the enhanced client in clientversion.cs // It seems that UOKR-EH sends a version number bigger 66.0.0.0, UOSA-EH bigger 67.0.0.0 try { if (ns.Version.Major > 8) ns.IsKRClient = true; } //Standard classic client does not display version this early, so we can rule SA enhanced client out catch { ns.IsKRClient = false; } return; #endregion } } }
GenerationOfWorlds/GOW
Server/Network/MessagePump.cs
C#
gpl-3.0
7,462
MODX Evolution 1.1 = 5237b665001bf5a2e8feecbe4739d6dc
gohdan/DFC
known_files/hashes/assets/modules/store/installer/action.install.php
PHP
gpl-3.0
54
/* * This program is free software; you can redistribute it and/or modify * it under the terms of version 3 or later of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * neuralnet.h * * by Gary Wong, 1998 * $Id: neuralnet.h,v 1.31 2014/05/11 15:32:35 plm Exp $ */ #ifndef NEURALNET_H #define NEURALNET_H #include <stdio.h> #include "common.h" typedef struct _neuralnet { unsigned int cInput; unsigned int cHidden; unsigned int cOutput; unsigned int fDirect; int nTrained; float rBetaHidden; float rBetaOutput; float *arHiddenWeight; float *arOutputWeight; float *arHiddenThreshold; float *arOutputThreshold; } neuralnet; typedef enum { NNEVAL_NONE, NNEVAL_SAVE, NNEVAL_FROMBASE } NNEvalType; typedef enum { NNSTATE_NONE = -1, NNSTATE_INCREMENTAL, NNSTATE_DONE } NNStateType; typedef struct _NNState { NNStateType state; float *savedBase; float *savedIBase; #if !defined(USE_SIMD_INSTRUCTIONS) int cSavedIBase; #endif } NNState; extern int NeuralNetCreate(neuralnet * pnn, unsigned int cInput, unsigned int cHidden, unsigned int cOutput, float rBetaHidden, float rBetaOutput); extern void NeuralNetDestroy(neuralnet * pnn); #if !USE_SIMD_INSTRUCTIONS extern int NeuralNetEvaluate(const neuralnet * pnn, float arInput[], float arOutput[], NNState * pnState); #else extern int NeuralNetEvaluateSSE(const neuralnet * pnn, float arInput[], float arOutput[], NNState * pnState); #endif extern int NeuralNetLoad(neuralnet * pnn, FILE * pf); extern int NeuralNetLoadBinary(neuralnet * pnn, FILE * pf); extern int NeuralNetSaveBinary(const neuralnet * pnn, FILE * pf); extern int SIMD_Supported(void); /* Try to determine whetehr we are 64-bit or 32-bit */ #if _WIN32 || _WIN64 #if _WIN64 #define ENVIRONMENT64 #else #define ENVIRONMENT32 #endif #endif #if __GNUC__ #if __x86_64__ #define ENVIRONMENT64 #else #define ENVIRONMENT32 #endif #endif #endif
alcacoop/libgnubg-android
libgnubg/lib/neuralnet.h
C
gpl-3.0
2,467
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <LibGUI/Label.h> #include <LibGUI/Painter.h> #include <LibGfx/Bitmap.h> #include <LibGfx/Font.h> #include <LibGfx/Palette.h> namespace GUI { Label::Label(const StringView& text) : m_text(text) { set_frame_thickness(0); set_frame_shadow(Gfx::FrameShadow::Plain); set_frame_shape(Gfx::FrameShape::NoFrame); } Label::~Label() { } void Label::set_icon(Gfx::Bitmap* icon) { if (m_icon == icon) return; m_icon = icon; update(); } void Label::set_text(const StringView& text) { if (text == m_text) return; m_text = text; update(); } void Label::paint_event(PaintEvent& event) { Frame::paint_event(event); Painter painter(*this); painter.add_clip_rect(event.rect()); if (m_icon) { if (m_should_stretch_icon) { painter.draw_scaled_bitmap(frame_inner_rect(), *m_icon, m_icon->rect()); } else { auto icon_location = frame_inner_rect().center().translated(-(m_icon->width() / 2), -(m_icon->height() / 2)); painter.blit(icon_location, *m_icon, m_icon->rect()); } } if (text().is_empty()) return; int indent = 0; if (frame_thickness() > 0) indent = font().glyph_width('x') / 2; auto text_rect = frame_inner_rect(); text_rect.move_by(indent, 0); text_rect.set_width(text_rect.width() - indent * 2); if (is_enabled()) { painter.draw_text(text_rect, text(), m_text_alignment, palette().window_text(), Gfx::TextElision::Right); } else { painter.draw_text(text_rect.translated(1, 1), text(), font(), text_alignment(), Color::White, Gfx::TextElision::Right); painter.draw_text(text_rect, text(), font(), text_alignment(), Color::from_rgb(0x808080), Gfx::TextElision::Right); } } void Label::size_to_fit() { set_size_policy(SizePolicy::Fixed, SizePolicy::Fill); set_preferred_size(font().width(m_text), 0); } }
ursine/DTPToys
src/LibGUI/Label.cpp
C++
gpl-3.0
3,332