branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; internal class Utils { [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)] public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetCursorPos(ref Win32Point pt); public static void DoMouseClick() //Клик !ЛКМ, не работает, нужен реворк ивента { int num = (int)GetMousePosition().X; int num2 = (int)GetMousePosition().Y; mouse_event(2, num, num2, 0, 0); } public static Point GetMousePosition() //Поинтер на позицию мыши { Win32Point win32Point = default(Win32Point); GetCursorPos(ref win32Point); return new Point((double)win32Point.X, (double)win32Point.Y); } public static void Move(int xDelta, int yDelta) //Перемещение мыши { mouse_event(1, xDelta, yDelta, 0, 0); } private const int MOUSEEVENTF_LEFTDOWN = 2; private const int MOUSEEVENTF_LEFTUP = 4; private const int MOUSEEVENTF_RIGHTDOWN = 8; private const int MOUSEEVENTF_RIGHTUP = 16; private const int MOUSEEVENTF_MOVE = 1; internal struct Win32Point { public int X; public int Y; } } internal static class WindowTransparentHelper { /// <summary> Справочник в котором хранятся старые состояния стиля окон </summary> private static readonly Dictionary<IntPtr, int> s_extendedStyleHwndDictionary = new Dictionary<IntPtr, int>(); private const int WS_EX_TRANSPARENT = 0x00000020; private const int GWL_EXSTYLE = (-20); [DllImport("user32.dll", EntryPoint = "GetWindowLong")] private static extern int GetWindowLong(IntPtr hwnd, int index); [DllImport("user32.dll", EntryPoint = "SetWindowLong")] private static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle); /// <summary> Делает окно прозрачным для ввода мышки </summary> /// <param name="hwnd">HWND окна</param> public static void SetWindowExTransparent(IntPtr hwnd) { int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT); if (s_extendedStyleHwndDictionary.Keys.Contains(hwnd) == false) { s_extendedStyleHwndDictionary.Add(hwnd, extendedStyle); } } /// <summary> Отключает прозрачность для ввода мышки у окна</summary> /// <param name="hwnd">HWND окна</param> public static void UndoWindowExTransparent(IntPtr hwnd) { if (s_extendedStyleHwndDictionary.Keys.Contains(hwnd)) { int extendedStyle = s_extendedStyleHwndDictionary[hwnd]; SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle); } } } public class PopupTransparentBehavior { /// <summary> Прикрепляемое свойство зависимости отвечающее за прозрачность формы для ввода </summary> public static readonly DependencyProperty IsPopupEventTransparentProperty = DependencyProperty.RegisterAttached("IsPopupEventTransparent", typeof(bool), typeof(PopupTransparentBehavior), new UIPropertyMetadata(false, OnIsPopupEventTransparentPropertyChanged)); public static bool GetIsPopupEventTransparent(DependencyObject obj) { return (bool)obj.GetValue(IsPopupEventTransparentProperty); } public static void SetIsPopupEventTransparent(DependencyObject obj, bool value) { obj.SetValue(IsPopupEventTransparentProperty, value); } private static void OnIsPopupEventTransparentPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) { var element = target as FrameworkElement; var topParent = GetTopParent(element); var popupHwndSource = PresentationSource.FromVisual(topParent) as HwndSource; if (popupHwndSource == null) return; var newValue = (bool)e.NewValue; if (newValue) WindowTransparentHelper.SetWindowExTransparent(popupHwndSource.Handle); else WindowTransparentHelper.UndoWindowExTransparent(popupHwndSource.Handle); } public static FrameworkElement GetTopParent(FrameworkElement element) { return LogicalTreeHelper.GetChildren(element).Cast<FrameworkElement>().First(); } } <file_sep>using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace EssentialMacros { public partial class BindControl : UserControl { public BindControl() { InitializeComponent(); } public string BindText { set { BindName.Text = value; } } private Key _Keyx; public Key Keyx { get { return _Keyx; } set { _Keyx = value; BindKeyLabel.Content = "• • •"; if (value != Key.None) { BindKeyLabel.Content = value.ToString(); UnbindContainer.Visibility = Visibility.Visible; } } } private void RebindButton_KeyDown(object sender, KeyEventArgs e) { if (Constants.weaponArray.Exists(item => item.bind == e.Key)) { if (_Keyx == Key.None) BindKeyLabel.Content = "• • •"; else BindKeyLabel.Content = _Keyx.ToString(); RebindContainer.Visibility = Visibility.Hidden; Constants.BP.Focus(); } else { _Keyx = e.Key; WeaponElement result = Constants.weaponArray.Find(item => item.element == this); result.bind = e.Key; Constants.localMachineKey.SetValue(result.name, e.Key); BindKeyLabel.Content = e.Key.ToString(); RebindContainer.Visibility = Visibility.Hidden; UnbindContainer.Visibility = Visibility.Visible; } Constants.isBind = false; } private void RebindButton_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { Constants.isBind = false; if (_Keyx == Key.None) BindKeyLabel.Content = "• • •"; else BindKeyLabel.Content = _Keyx.ToString(); RebindContainer.Visibility = Visibility.Hidden; } private void BindButton_Click(object sender, RoutedEventArgs e) { Constants.isBind = true; BindKeyLabel.Content = "-press-"; RebindContainer.Visibility = Visibility.Visible; RebindButton.Focus(); } private void RebindButton_Click(object sender, RoutedEventArgs e) { Constants.isBind = true; BindKeyLabel.Content = "-press-"; RebindButton.Focus(); } private void UnbindButton_Click(object sender, RoutedEventArgs e) { if (Constants.offsetWorker.MouseIsDown) return; UnbindContainer.Visibility = Visibility.Hidden; BindButton.Visibility = Visibility.Visible; BindKeyLabel.Content = "• • •"; _Keyx = Key.None; WeaponElement result = Constants.weaponArray.Find(item => item.element == this); result.bind = Key.None; Constants.localMachineKey.SetValue(result.name, Key.None); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace EssentialMacros.Pages { /// <summary> /// Логика взаимодействия для SettingsPage.xaml /// </summary> public partial class SettingsPage : Page { public SettingsPage() { InitializeComponent(); } private void Page_Loaded(object sender, RoutedEventArgs e) { Sens.Value = double.Parse(Constants.localMachineKey.GetValue("Sensetivity").ToString()); Constants.offsetWorker.default_offset = double.Parse(Constants.localMachineKey.GetValue("Sensetivity").ToString()); Fov.Value = double.Parse(Constants.localMachineKey.GetValue("Fov").ToString()); Constants.offsetWorker.fov_offset = double.Parse(Constants.localMachineKey.GetValue("Fov").ToString()); } private void Sens_ValueChanged(object sender, EventArgs e) { Constants.localMachineKey.SetValue("Sensetivity", ((SliderControl)sender).Value); Constants.offsetWorker.default_offset = ((SliderControl)sender).Value; } private void Fov_ValueChanged(object sender, EventArgs e) { Constants.localMachineKey.SetValue("Fov", ((SliderControl)sender).Value); Constants.offsetWorker.fov_offset = ((SliderControl)sender).Value; } private void InventoryInfo_MouseEnter(object sender, MouseEventArgs e) { swapOverlay("ФИКС ИНВЕНТАРЯ", "Отключает функционал макроса, когда вы нажимаете на кнопку, забинженую на инвентарь."); } private void InventoryInfo_MouseLeave(object sender, MouseEventArgs e) { swapOverlay("", ""); } private void OverlayInfo_MouseEnter(object sender, MouseEventArgs e) { swapOverlay("ОВЕРЛЕЙ", "Отображает поверх игры информацию о статусе макросов"); } private void OverlayInfo_MouseLeave(object sender, MouseEventArgs e) { swapOverlay("", ""); } private void swapOverlay(string title, string data) { if (InfoOverlay.Visibility == Visibility.Visible) InfoOverlay.Visibility = Visibility.Hidden; else { InfoOverlay.Visibility = Visibility.Visible; InfoOverlayText.Text = data; InfoOverlayTitle.Content = title; } } } } <file_sep>using EssentialMacros; using EssentialMacros.Pages; using Microsoft.Win32; using System.Collections.Generic; static class Constants { public static BindingPage BP; public static SettingsPage SP; public static List<SettingsElement> settingsSetup = new List<SettingsElement>(); public static List<WeaponElement> weaponArray = new List<WeaponElement>(); public static WeaponElement currentWeapon = null; public static bool isBind = false; public static RegistryKey localMachineKey; public static OffsetWorker offsetWorker = new OffsetWorker(); } <file_sep>using EssentialMacros.Pages; using Gma.System.MouseKeyHook; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; namespace EssentialMacros { public partial class MainWindow : Window { KeyConverter keyConvert = new KeyConverter(); private IKeyboardMouseEvents mouseHook; KeyboardHook keyboardHook = new KeyboardHook(true); public MainWindow() { InitializeComponent(); } private void Minimize_Click(object sender, RoutedEventArgs e) { this.WindowState = WindowState.Minimized; } private void Grid_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) this.DragMove(); } private void Exit_Click(object sender, RoutedEventArgs e) { Process.GetCurrentProcess().Kill(); } private void Window_Loaded(object sender, RoutedEventArgs e) { //Анимация тайтла формы #region animation string[] titleChars = {"E", "s", "s", "e", "n", "t", "i", "a", "l", " ", "M", "a", "c", "r", "o", "s"}; new Task(()=> { Thread.Sleep(1000); foreach (string x in titleChars) { Dispatcher.Invoke(() => TitleText.Text += x); Thread.Sleep(150); } }).Start(); #endregion Constants.localMachineKey = Registry.CurrentUser.OpenSubKey("Software\\EssentialM", true); if (Constants.localMachineKey == null) { //Создание и конфигурация записи в регистре при первом запуске или её отсутствии Constants.localMachineKey = Registry.CurrentUser.CreateSubKey("Software\\EssentialM"); Constants.localMachineKey.SetValue("AK47", Key.None); Constants.localMachineKey.SetValue("BERDANKA", Key.None); Constants.localMachineKey.SetValue("BERETTA", Key.None); Constants.localMachineKey.SetValue("LR300", Key.None); Constants.localMachineKey.SetValue("M249", Key.None); Constants.localMachineKey.SetValue("MP5A4", Key.None); Constants.localMachineKey.SetValue("PISTOL", Key.None); Constants.localMachineKey.SetValue("PYTHON", Key.None); Constants.localMachineKey.SetValue("REVOLVER", Key.None); Constants.localMachineKey.SetValue("SMG", Key.None); Constants.localMachineKey.SetValue("TOMPSON", Key.None); Constants.localMachineKey.SetValue("M39", Key.None); Constants.localMachineKey.SetValue("Sensetivity", 1); Constants.localMachineKey.SetValue("Fov", 0); Constants.localMachineKey.SetValue("CrossHair", true); Constants.localMachineKey.SetValue("CrossHair_Y", 490); Constants.localMachineKey.SetValue("CrossHair_Size", 0.2); Constants.localMachineKey.SetValue("CrossHair_Opacity", 1); Constants.localMachineKey.SetValue("InventoryFix", true); Constants.localMachineKey.SetValue("InventoryKey", Key.Tab); Constants.localMachineKey.SetValue("Overlay", true); } Constants.BP = new BindingPage(); Constants.SP = new SettingsPage(); Constants.weaponArray.Add(new WeaponElement { name = "AK47", element = Constants.BP.ak_47, offsets = Encoding.UTF8.GetString(Properties.Resources.AK47).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("AK47").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "BERDANKA", element = Constants.BP.berdanka, offsets = Encoding.UTF8.GetString(Properties.Resources.Berdanka).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("BERDANKA").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "BERETTA", element = Constants.BP.beretta, offsets = Encoding.UTF8.GetString(Properties.Resources.Beretta).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("BERETTA").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "LR300", element = Constants.BP.lr300, offsets = Encoding.UTF8.GetString(Properties.Resources.LR300).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("LR300").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "M249", element = Constants.BP.m249, offsets = Encoding.UTF8.GetString(Properties.Resources.M249).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("M249").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "MP5A4", element = Constants.BP.mp5a4, offsets = Encoding.UTF8.GetString(Properties.Resources.MP5A4).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("MP5A4").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "PISTOL", element = Constants.BP.pistol, offsets = Encoding.UTF8.GetString(Properties.Resources.Pistol).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("PISTOL").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "PYTHON", element = Constants.BP.python, offsets = Encoding.UTF8.GetString(Properties.Resources.Python).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("PYTHON").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "REVOLVER", element = Constants.BP.revolver, offsets = Encoding.UTF8.GetString(Properties.Resources.Revolver).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("REVOLVER").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "SMG", element = Constants.BP.smg, offsets = Encoding.UTF8.GetString(Properties.Resources.SMG).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("SMG").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "TOMPSON", element = Constants.BP.tompson, offsets = Encoding.UTF8.GetString(Properties.Resources.Tompson).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("TOMPSON").ToString()) }); Constants.weaponArray.Add(new WeaponElement { name = "M39", element = Constants.BP.m39, offsets = Encoding.UTF8.GetString(Properties.Resources.AK47).Split('\n'), bind = (Key)keyConvert.ConvertFromString(Constants.localMachineKey.GetValue("M39").ToString()) }); for (int i = 0; i < Constants.weaponArray.Count; i++) { Constants.weaponArray[i].element.Keyx = Constants.weaponArray[i].bind; } keyboardHook.KeyDown += KHKeyDown; mouseHook = Hook.GlobalEvents(); mouseHook.MouseDown += Constants.offsetWorker.MD; mouseHook.MouseUp += Constants.offsetWorker.MU; MainFrame.Navigate(Constants.BP); } private void KHKeyDown(Keys key, bool Shift, bool Ctrl, bool Alt) //Ивент на KeyBoard Input { WeaponElement result = Constants.weaponArray.Find(item => (Keys)KeyInterop.VirtualKeyFromKey(item.bind) == key); if (result != null && !Constants.isBind && !Constants.offsetWorker.MouseIsDown) { //Отключение бинда if (Constants.currentWeapon == result) { result.element.BindName.Foreground = new SolidColorBrush(Colors.White); Constants.currentWeapon = null; } else { if (Constants.currentWeapon != null) Constants.currentWeapon.element.BindName.Foreground = new SolidColorBrush(Colors.White); Constants.currentWeapon = result; result.element.BindName.Foreground = new SolidColorBrush(Colors.Red); } } } //!---------------------------------------------------UTILS public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject { if (depObj != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject child = VisualTreeHelper.GetChild(depObj, i); if (child != null && child is T) { yield return (T)child; } foreach (T childOfChild in FindVisualChildren<T>(child)) { yield return childOfChild; } } } } private void BindsButton_Click(object sender, RoutedEventArgs e) { MainFrame.Navigate(Constants.BP); } private void SettingsButton_Click(object sender, RoutedEventArgs e) { MainFrame.Navigate(Constants.SP); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace EssentialMacros { /// <summary> /// Логика взаимодействия для SliderControl.xaml /// </summary> public partial class SliderControl : UserControl { public SliderControl() { InitializeComponent(); } public event EventHandler ValueChanged; public double Value { get { return currentSlider.Value; } set { currentSlider.Value = value; } } public string SliderText { set { SliderName.Text = value; } } public double Min { set { currentSlider.Minimum = value; } } public double Max { set { currentSlider.Maximum = value; } } public double Step { set { currentSlider.TickFrequency = value; } } private void CurrentSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { infoBar.Content = currentSlider.Value.ToString(); } private void CurrentSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) { ValueChanged?.Invoke(this, EventArgs.Empty); } } } <file_sep>using System; using System.Threading; using System.Windows.Forms; namespace EssentialMacros { class OffsetWorker { Thread offsetter; public bool MouseIsDown = false; public static bool inventoryIsOpen = false; public double default_offset = 1; public double fov_offset = 1; public void MC() { if (!inventoryIsOpen) { for (int i = 0; i < Constants.currentWeapon.offsets.Length; i++) { if (!MouseIsDown) //Выход из цикла, когда ЛКМ отжата break; string[] CharsArr = Constants.currentWeapon.offsets[i].Split(' '); //Сплит строки на массив if (CharsArr[0] == "Delay") //Обработчик пауз Thread.Sleep(int.Parse(CharsArr[1])); if (CharsArr[0] == "MoveR") //Обработчик смещений { int x = Convert.ToInt32(double.Parse(CharsArr[1]) * (1 / default_offset) * fov_offset); int y = Convert.ToInt32(double.Parse(CharsArr[2]) * (1 / default_offset) * fov_offset); Utils.Move(x, y); } /* Можно поправить в хелп классе клик и добавить обработчик кликов для всяких берданок. Но нахуя? */ } } } public void MD(object sender, MouseEventArgs e) //Ивент на нажатие ЛКМ { if (e.Button == MouseButtons.Left) { MouseIsDown = true; if (Constants.currentWeapon != null) { offsetter = new Thread(() => MC()); //Новый поток смещающий мышь по офсету offsetter.Start(); } } } public void MU(object sender, MouseEventArgs e) //Ивент на отжатие ЛКМ { if (e.Button == MouseButtons.Left) { MouseIsDown = false; if (Constants.currentWeapon != null && offsetter != null) offsetter.Abort(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace EssentialMacros { public class SettingsElement { public string name { get; set; } public object value { get; set; } } public class WeaponElement { public string name { get; set; } public BindControl element { get; set; } public string[] offsets { get; set; } public Key bind { get; set; } } }
ab2795c84298afe479d616b09be8e167f99f8251
[ "C#" ]
8
C#
desperationbtw/EssentialMacros
6c3737744720b5fc8ad3809e56ccb6693ba027b7
1bebd9838eeb0a3915e813d9dca8c06074d4e314
refs/heads/master
<file_sep># soleXin web page under construction User tools and libs * Grunt * Bootstrap 4 alpha * Icomoon * Eclipse * Sketch ##Build & Deploy ####build >grunt ####deploy to server >grunt deploy <file_sep>/* * sxWebUC Gruntfile */ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-ftp-push'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-subgrunt'); grunt.initConfig({ clean : { css : [ 'WebContent/css/*', '!WebContent/css/sx*' ], js : [ 'WebContent/js/**/bootstrap*', 'WebContent/js/**/npm.js', 'WebContent/js/umd/**' ] }, subgrunt : { target0 : { projects : { // For each of these projects, the specified grunt task will // be // executed: 'node_modules/module1' : 'default', 'node_modules/module2' : 'bower:install' } }, test : { 'bootstrap-4.0.0-alpha' : 'test' }, dist : { 'bootstrap-4.0.0-alpha' : 'dist' } }, copy : { files : { cwd : 'bootstrap-4.0.0-alpha/dist', src : [ '**/*' ], dest : 'WebContent', expand : true } }, ftp_push : { solexin : { options : { authKey : "serverA", // reference to .ftpauth file host : "ftp.solexin.ch", dest : "/html/soleXinUC", port : 21 }, files : [ { expand : true, cwd : 'WebContent', src : [ "**" ] } ] } } }); grunt.registerTask('bs', [ 'subgrunt:dist' ]); grunt.registerTask('default', [ 'bs', 'clean', 'copy:files' ]); grunt.registerTask('deploy', [ 'ftp_push' ]); }
5e06ffc8813ac4638127e56442383ccb7be9b2d4
[ "Markdown", "JavaScript" ]
2
Markdown
ironsugus/sxWebUC
024859d0b5c02947fe1456edea1515b02646bdac
51765b9fb4a6f6ae361e1b85b0ec50d94edc87e0
refs/heads/master
<file_sep>def factorial(n: int) -> int: if n == 2: return 2 return n * factorial(n - 1) def permutation(n: int, choices: int) -> int: return factorial(n) / factorial(n - choices) def combintation(n: int, choices: int) -> int: return factorial(n) / (factorial(n - choices) * factorial(choices))
45ada349edcc13229bef2494f54500fbd589f946
[ "Python" ]
1
Python
ImHereForTheCookies/groblies
d297d51bcc62972f6b82bda72ee9ccab6a0fd3af
b3582b11aa2006106ad2dda5f297c0dc0f1cdd8a
refs/heads/master
<repo_name>Download/solids-www<file_sep>/src/routes/about/index.js import { h } from 'preact'; import { Provider } from '../../components/Theme'; import HomeLayout from '../../components/HomeLayout'; import style from '../../components/HomeLayout/style'; import 'preact-material-components/List/style.css'; export const About = () => ( <Provider value={{ classes: style }}> <HomeLayout title="About" mainClass={style.home}> <h1>About</h1> <p><b>css-only material design primitives</b></p> </HomeLayout> </Provider> ); export default About; <file_sep>/src/components/LeftNav/index.jsx import { h } from 'preact'; import { Link } from 'preact-router/match'; import { createHelper } from 'preact-solids/style-classes'; import { Consumer } from 'preact-solids/theme'; import defaultClasses from 'solids/list/classes'; // import { ListGroup, Nav, ListItem, ListDivider } from '../../components/List'; import List from 'preact-solids/list'; // import Icon from 'preact-material-components/Icon'; // import List from 'preact-material-components/List'; export const LeftNav = ({ children, ...attributes }) => ( <Consumer>{({ classes = {}, scope = 'local' }) => { classes = { ...defaultClasses, ...classes }; let classNames = createHelper(classes, scope); const link = { Component: Link, activeClassName: classNames(classes.selected) }; return ( <List.Group> <List> <List.LinkItem {...link} href="/"><List.ItemGraphic>home</List.ItemGraphic>Home</List.LinkItem> <List.LinkItem {...link} href="/about"><List.ItemGraphic>info</List.ItemGraphic>About</List.LinkItem> <List.LinkItem {...link} href="/components"><List.ItemGraphic>extension</List.ItemGraphic>Components</List.LinkItem> <List.LinkItem {...link} href="/profile"><List.ItemGraphic>star</List.ItemGraphic>Me</List.LinkItem> <List.LinkItem {...link} href="/profile/john"><List.ItemGraphic>send</List.ItemGraphic>John</List.LinkItem> <List.Divider /> <List.LinkItem><List.ItemGraphic>inbox</List.ItemGraphic>Inbox</List.LinkItem> <List.LinkItem><List.ItemGraphic>drafts</List.ItemGraphic>Drafts</List.LinkItem> </List> </List.Group> ); }}</Consumer> ); export default LeftNav; <file_sep>/src/components/HomeLayout/index.jsx import classNames from 'classnames'; import { h } from 'preact'; import AppBar, { AppBarAction } from 'preact-solids/appbar'; import Drawer from 'preact-solids/drawer'; import LeftNav from '../LeftNav'; import RightNav from '../RightNav'; import Card from 'preact-solids/card'; import style from './style.scss'; export const HomeLayout = ({ title, children, className, mainClass, ...attributes }) => { attributes.className = classNames(style.solids, { [attributes.class || attributes.className]: attributes.class || attributes.className }) return ( <div {...attributes}> <AppBar title={title} reserveStart reserveEnd fixed tactile prominent shrink> <AppBarAction class="material-icons">file_download</AppBarAction> </AppBar> <Drawer fixed title="Title here"> <LeftNav /> </Drawer> <Drawer fixed end> <RightNav /> </Drawer> <main class={mainClass}> <Card class={style.z1}> <div class={style.content}>{children}</div> </Card> </main> </div> ); } /* <Row fill> </Row> <div class={style.parallax}> <div class={style.parallax_group}> <div class={classNames(style.parallax_layer, style.parallax_layer_base)}> </div> <div class={style.parallax_background}> <div class={classNames(style.parallax_layer, style.parallax_layer_bg)} /> <div class={classNames(style.parallax_layer, style.parallax_layer_bg2)} /> <div class={classNames(style.parallax_layer, style.parallax_layer_bg3)} /> <div class={classNames(style.parallax_layer, style.parallax_layer_bg4)} /> <div class={classNames(style.parallax_layer, style.parallax_layer_bg5)} /> </div> </div> </div> */ export default HomeLayout; <file_sep>/preact.config.js import { render } from 'prettyjson'; import ulog from 'ulog'; import path from 'path'; const log = ulog('solids:config:preact'); export default (config, env, helpers) => { // config.resolve.alias['solids/AppBar'] = path.resolve(__dirname, 'node_modules', 'solids', 'AppBar'); let loader = helpers.getLoadersByName(config, 'css-loader') .filter(loader => loader.rule && loader.rule.exclude)[0]; // loader.rule.exclude.push(path.resolve(__dirname, 'node_modules', 'solids')); loader.rule.exclude.push(path.resolve(__dirname, 'AppBar')); loader.rule.exclude.push(path.resolve(__dirname, 'Drawer')); loader = helpers.getLoadersByName(config, 'css-loader') .filter(loader => loader.rule && loader.rule.include)[0]; // loader.rule.include.push(path.resolve(__dirname, 'node_modules', 'solids')); loader.rule.include.push(path.resolve(__dirname, 'AppBar')); loader.rule.include.push(path.resolve(__dirname, 'Drawer')); // log.info(render(loader)); // log.info('===================='); loader = loader.rule.loader.filter(loader => loader.loader === 'css-loader')[0]; loader.options.localIdentName = '[local]_[hash:base64:3]'; log.info(render(config)); }; <file_sep>/script.js function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; } function createCookieObject () { var cookie_string = {}; var cookie = document.cookie; var vars = cookie.split("; "); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); // If first entry with this name if (typeof cookie_string[pair[0]] === "undefined") { cookie_string[pair[0]] = pair[1]; // If second entry with this name } else if (typeof cookie_string[pair[0]] === "string") { var arr = [ cookie_string[pair[0]], pair[1] ]; cookie_string[pair[0]] = arr; // If third or later entry with this name } else { cookie_string[pair[0]].push(pair[1]); } } return cookie_string; } function createQueryObject () { var query_string = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); // If first entry with this name if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = pair[1]; // If second entry with this name } else if (typeof query_string[pair[0]] === "string") { var arr = [ query_string[pair[0]], pair[1] ]; query_string[pair[0]] = arr; // If third or later entry with this name } else { query_string[pair[0]].push(pair[1]); } } return query_string; } var existingChannels = ""; var existingSources = ""; var existingDates = ""; var landingPage = false; var currentChannel = ""; var currentSource = ""; var MC_cookies = document.cookie; var cookieCharLimit = 4096; if (MC_cookies.indexOf("MC_landing") ==-1 || document.URL.indexOf('utm_source')!=-1 || document.referrer.indexOf('google.com')!=-1 || document.referrer.indexOf('yandex.com')!=-1 || document.referrer.indexOf('arabia.starzplay.com') > 30 || document.referrer.indexOf('arabia.starzplay.com')==-1) { createCookie("MC_landing",1); landingPage = true; var CookieString = createCookieObject(); var QueryString = createQueryObject(); if (typeof QueryString.utm_source === "undefined") { if (document.referrer ==="") { currentChannel = "(direct)"; currentSource = "(direct)"; } else if (QueryString.gclid) { currentChannel = "Adwords"; currentSource = "Google-CPC"; } else if (QueryString.dclid) { currentChannel = "DoubleClick"; currentSource = "DoubleClick"; } else if (document.referrer.indexOf("google.")!=-1) { currentChannel = "Organic"; currentSource = "Google-Organic"; } else if (QueryString.yclid) { currentChannel = "Yandex CPC"; currentSource = "Yandex-CPC"; } else if (document.referrer.indexOf("yandex")!=-1) { currentChannel = "Organic"; currentSource = "Yandex-Organic"; } else { currentChannel = 'Other'; currentSource = document.referrer.match(/:\/\/(.[^/]+)/)[1]; } } else{ currentSource = QueryString.utm_source+"/"+QueryString.utm_medium+"/"+QueryString.utm_campaign; currentChannel = QueryString.utm_source; } var d = new Date; currentDate = "" + d.getFullYear() + (('00' + (d.getMonth() + 1)).slice(-2)) + d.getDate(); if(typeof CookieString.mcfChannels != "undefined"){ if(CookieString.mcfSourceDetails.length>4096){ CookieString.mcfSourceDetails = CookieString.mcfSourceDetails.substring(CookieString.mcfSourceDetails.indexOf(">")+1,CookieString.mcfSourceDetails.length); CookieString.mcfChannels = CookieString.mcfChannels.substring(CookieString.mcfChannels.indexOf(">")+1,CookieString.mcfChannels.length); CookieString.mcfDates = CookieString.mcfDates.substring(CookieString.mcfDates.indexOf(">")+1,CookieString.mcfDates.length); } existingChannels = CookieString.mcfChannels; existingSources = CookieString.mcfSourceDetails; existingDates = CookieString.mcfDates; } if(existingSources.substring(existingSources.lastIndexOf(">")+1,existingSources.length)!=currentSource){ if(existingSources.length>0){ existingChannels = existingChannels + ">"; existingSources = existingSources + ">"; existingDates = existingDates + ">"; } createCookie ('mcfChannels',existingChannels+currentChannel,7); createCookie ('mcfSourceDetails',existingSources+currentSource,7); createCookie ('mcfDates',existingDates+currentDate,7); createCookie ('mcfLastInteraction',currentChannel+" | "+currentSource,7); } if(existingChannels == "") { createCookie('mcfFirstInteraction',currentChannel+" | "+currentSource,7); } }
c0e863dd63c2cfa13057f753c890c57b3e64d043
[ "JavaScript" ]
5
JavaScript
Download/solids-www
45094ff3b1b9a8197b2a4970ce83c0c78afd4f83
dd1cb4aecf35f2fc033c11f58ace4c868b7784cd
refs/heads/master
<file_sep># # This is a Shiny web application. You can run the application by clicking # the 'Run App' button above. # # Find out more about building applications with Shiny here: # # http://shiny.rstudio.com/ # library(shiny) library(httr) library(jsonlite) library(plotly) library(htmltools) library(tidyverse) library(lubridate) ckanSQL <- function(url) { # Make the Request r <- RETRY("GET", URLencode(url)) # Extract Content c <- content(r, "text") # Basic gsub to make NA's consistent with R json <- gsub('NaN', 'NA', c, perl = TRUE) # Create Dataframe data.frame(jsonlite::fromJSON(json)$result$records) } # df <- read_csv("66cdcd57-6c92-4aaa-8800-0ed9d8f03e22.csv") %>% # mutate(Month = month(mdy(Date)), Day = day(mdy(Date)), Year = year(mdy(Date))) # # group_by(df, Year, Month, Day) %>% # count() # group_by(df, Year, Month) %>% # summarise(avg_age = mean(get('Current Age'))) # Define UI for application ui <- fluidPage( # Application title titlePanel("Counts of 311 Jail Census"), # Sidebar sidebarLayout( sidebarPanel( dateRangeInput("dates", "Select Dates", start = Sys.Date()-30, end = Sys.Date(),)), mainPanel( plotlyOutput("count") ))) # Define server logic required to draw a histogram server <- function(input, output) { loadjail <- reactive({ # Build API Query with proper encodes input$dates[1] <- as.Date(input$dates[1], origin = "1970-01-01") input$dates[2] <- as.Date(input$dates[2], origin = "1970-01-01") url <- paste0("SELECT%20*%20FROM%20%2266cdcd57-6c92-4aaa-8800-0ed9d8f03e22%22%20WHERE%20%20%27Date%27%20%3E%3D%20%27", input$dates[1], "%27%20AND%20%27Date%27%20%3C%3D%20%27", input$dates[2], "%27") # Load and clean data jail <- ckanSQL(url) %>% na.omit() %>% mutate(date = as.Date(Date)) return(jail) }) #plot # inmates counted in census output$count <- renderPlotly({ # data for chart table <- loadjail %>% # group_by(Date) %>% # summarise(count = n()) group_by_(Date) %>% count() ggplot(table, aes(x = date, y = count)) + geom_bar() }) } # Run the application shinyApp(ui = ui, server = server) <file_sep>library(shiny) library(shinydashboard) library(reshape2) library(dplyr) library(plotly) library(shinythemes) library(countrycode) library(readr) library(readxl) library(DT) library(httr) pdf(NULL) GET("https://query.data.world/s/owq2xiknasfbqxec6r6vixndfsinnn", write_disk(tf <- tempfile(fileext = ".xlsx"))) df <- read_excel(tf) query_results <- GET("https://api.data.world/v0/queries/3da01c6c-85b6-4668-9afb-26c8103c2cb7/results") # # r <- GET("https://api.data.world/v0/datasets/ostevens/shiny-project-happiness", authenticate("<KEY>")) # # r <- GET("https://api.data.world/v0/queries/3da01c6c-85b6-4668-9afb-26c8103c2cb7", authenticate("ostevens", "<KEY>")) # # r <- GET("https://api.data.world/v0/queries/3da01c6c-85b6-4668-9afb-26c8103c2cb7") # # # alternative GET command # # GET("https://query.data.world/s/b6eyyji2thr3m2hdkmnvhywwwr72lp", write_disk(tf <- tempfile(fileext = ".xlsx"))) names(df) <- str_replace(names(df), "\\(","") %>% str_replace( "\\)","") %>% str_replace_all( " ","_") %>% str_replace( ",","") %>% str_to_lower() # You need to save requests as a variable GET("https://query.data.world/s/owq2xiknasfbqxec6r6vixndfsinnn") origdata <- df # origdata <- read_csv("data_behind_table_2_1_whr_2017.csv") # The file has been removed from your repo... so now it doesn't work money.wide <- read_excel("Download-GDPPCconstant-USD-countries.xls", skip = 2) money.long <- melt(money.wide, id.vars = c("CountryID","Country")) origdata <- mutate(origdata, year = as.character(year)) origdata <- left_join(origdata, money.long, by = c("country" = "Country", "year" = "variable")) origdata <- mutate(origdata, gdp = value) # I recommend you just removing stuff like this in the future, you don't need it, and if you have to bring it back, that's why you commit things to GitHub # happiness.load <- origdata %>% # mutate(confidence_in_gov = confidence_in_national_government, # Gini_Income = gini_of_household_income_reported_in_gallup_by_wp5_year, # Gini_Average = gini_index_world_bank_estimate_average_2000_13, # continent = countrycode(sourcevar = country, origin = "country.name",destination = "continent"), # region = countrycode(sourcevar = country, origin = "country.name", destination = "region"), # continent = as.character(ifelse(country == "Kosovo", "Europe", as.character(continent))), # region = as.factor(ifelse(country == "Kosovo", "Southern Europe", as.character(region))), # year_date = as.Date(ISOdate(year, 1, 1))) %>% # select(country:perceptions_of_corruption, Gini_Income, Gini_Average, gini_index_world_bank_estimate, confidence_in_gov, continent, region, gdp, year_date) happiness.load <- origdata %>% mutate(confidence_in_gov = confidence_in_national_government, Gini_Income = "Gini_of_household_income_reported_in_gallup,_By_wp5_year", Gini_Average = "Gini_index_(World_Bank_estimate),_average_2000-13", continent = countrycode(sourcevar = country, origin = "country.name",destination = "continent"), region = countrycode(sourcevar = country, origin = "country.name", destination = "region"), continent = as.factor(ifelse(country == "Kosovo", "Europe", as.character(continent)))) %>% select(country:perceptions_of_corruption, Gini_Income, Gini_Average, confidence_in_gov, continent, region, gdp) happiness <- mutate(happiness.load, year = as.numeric(as.character(year))) # ggplot(twenty16, aes(x = reorder(country, -life_ladder), y = life_ladder, fill = continent)) + geom_bar(stat = "identity") # ggplot(twenty16, aes(x = reorder(continent, -life_ladder), life_ladder, fill = continent)) + stat_summary(fun.y = "mean", geom = "bar") # Building a header header <- dashboardHeader(title = "Global Happiness Dashboard", dropdownMenu(type = "notifications", notificationItem(text = "This text is larger than you can see when you click. But: Who's happy? Who's miserable?", icon = icon("users")) ), dropdownMenu(type = "tasks", badgeStatus = "success", taskItem(value = 10, color = "green", text = "Figure out: does money correlate with happiness?") ), dropdownMenu(type = "messages", messageItem( from = "Owen", message = HTML("Thankyou, esteemed user, for using this app. Reach out to <EMAIL> for more information"), icon = icon("exclamation-circle")) ) ) #Assign dashboard sidebar sidebar <- dashboardSidebar( sidebarMenu( id = "tabs", menuItem("Plot", icon = icon("bar-chart"), tabName = "plot"), menuItem("Table", icon = icon("table"), tabName = "table"), selectInput("continentSelect", "Continent:", choices = c(sort(unique(happiness.load$continent))), multiple = TRUE, selectize = TRUE, selected = c("Americas")), # Year sliderInput(inputId = "yearSelect", label = "Year (2005-2016):", min = min(happiness$year), max = max(happiness$year), value = max(happiness$year),step = 1,round = T, sep = ''), menuItem("Scatterplots", tabName = "scatter",badgeLabel = "new", badgeColor = "green") ) ) #Body! body <- dashboardBody(tabItems( tabItem("plot", fluidRow( infoBoxOutput("Happiness",width = 6), valueBoxOutput("GDP") ), fluidRow( tabBox(title = "Plot", width = 12, tabPanel("GDP", plotlyOutput("plot_gdp"),plotlyOutput("regionalgdp")), tabPanel("Happiness", plotlyOutput("plot_happiness"), plotlyOutput("regionalhap"))) ) ), tabItem("table", fluidPage( box(title = "Country Stats", DT::dataTableOutput("table"), width = 12)) ), tabItem("scatter", fluidPage( inputPanel( # Select Y selectInput("y", "Y Axis:", #choices = c(choices = str_to_title(str_replace_all(names, "_"," ")) = colnames(happiness)), choices = colnames(happiness.load)[c(-(1:2))], selected = "life_ladder"), selectInput("x", "X Axis:", choices = colnames(happiness.load)[c(-(1:2))], selected = "gdp") ), fluidRow( plotlyOutput("scatterplot") ))))) # Server section ui <- dashboardPage(header, sidebar, body) # Define server logic server <- function(input, output) { # Reactive input data hInput <- reactive({ # Loading your data should be down here, not up in the beginning, but since you never got it working it be difficult happiness <- happiness.load %>% # Year Filter filter(year == input$yearSelect) # Continent Filter if (length(input$continentSelect) > 0 ) { happiness <- subset(happiness, continent %in% input$continentSelect) } return(happiness) }) # Reactive melted data mhInput <- reactive({ mhInput() %>% melt(c("country", input$x, input$y, "continent")) }) output$scatterplot <- renderPlotly({ ggplot(hInput(), aes_string(x = input$x, y = input$y, color = "continent")) + geom_point() + theme(legend.position = "top") }) # plot showing happiness by country output$plot_happiness <- renderPlotly({ dat <- hInput() ggplot(data = dat, aes(x = reorder(country, -life_ladder), y = life_ladder, fill = continent), text = paste("country:", country)) + geom_bar(stat = "identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1))+ labs(y = "Happiness (out of 10)", x = "Country", title = "Avg. Happiness by Country") }) #plot showing gdp by country output$plot_gdp <- renderPlotly({ data <- hInput() ggplot(data = data, aes(x = reorder(country, gdp), y = gdp, fill = continent)) + geom_bar(stat = "identity") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs(y = "GDP per capita", x = "Country", title = "GDP by Country") }) # GDP broken down by regino output$regionalgdp <- renderPlotly({ data <- hInput() ggplot(data, aes(x = reorder(region, -gdp),y = gdp, fill = continent)) + stat_summary(fun.y = "mean", geom = "bar") + labs(y = "Average Happiness", x = "Region", title = "Avg. GDP by Region") + guides(fill = FALSE) }) # Happiness broken down by region output$regionalhap <- renderPlotly({ data <- hInput() ggplot(data, aes(x = reorder(region, -life_ladder), life_ladder, fill = continent)) + stat_summary(fun.y = "mean", geom = "bar") + labs(y = "Avg GDP per capita", x = "Region", title = "Avg. Happiness by Region") + guides(fill = FALSE) }) # Data table of countries output$table <- DT::renderDataTable({ tabledisp <- hInput() datatable(select(hInput(), country, year, happiness = life_ladder, gdp, social_support:perceptions_of_corruption, gini = gini_index_world_bank_estimate), options = list(scrollX = TRUE)) %>% formatCurrency(4, '$') %>% formatRound(c(3,5), 3) %>% formatRound('healthy_life_expectancy_at_birth', 1) %>% formatPercentage('freedom_to_make_life_choices', 2) }) #happiness info box output$Happiness <- renderInfoBox({ h <- hInput() happiest <- h[which.max(h$life_ladder), 'country'] infoBox("Happiest country",value = happiest, subtitle = paste('Out of', nrow(h), "selected countries"), icon = icon("smile-o"), color = "purple") }) #GDP info box output$GDP <- renderValueBox({ h <- hInput() num <- round(mean(h$gdp, na.rm = T), 2) valueBox(subtitle = "Avg GDP Per Capita", value = num, icon("sort-numeric-asc"), color = "green") }) } # Run the application shinyApp(ui = ui, server = server) # # Define UI for application that draws a histogram # ui <- fluidPage( # # # Application title # titlePanel("Old Faithful Geyser Data"), # # # Sidebar with a slider input for number of bins # sidebarLayout( # sidebarPanel( # sliderInput("bins", # "Number of bins:", # min = 1, # max = 50, # value = 30) # ), # # # Show a plot of the generated distribution # mainPanel( # plotOutput("distPlot") # ) # ) # ) # # # Define server logic required to draw a histogram # server <- function(input, output) { # # output$distPlot <- renderPlot({ # # generate bins based on input$bins from ui.R # x <- faithful[, 2] # bins <- seq(min(x), max(x), length.out = input$bins + 1) # # # draw the histogram with the specified number of bins # hist(x, breaks = bins, col = 'darkgray', border = 'white') # }) # } # # # Run the application # shinyApp(ui = ui, server = server) #
6b0b602831a00b01bad055d3a5ff6dc692286977
[ "R" ]
2
R
RforOperations2018/HW4_ostevens
d00f4ac350e7596bc8839370725193c12c422cb5
bba279e2327b89e2012b656d0bf859b76a3931ef
refs/heads/master
<file_sep>package ie.nodstuff.rtpitestapp; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by nodstuff on 26/03/15. */ public class TimetableAdapter extends ArrayAdapter<Module> { private ArrayList<Module> users; public TimetableAdapter(Context context, int textViewResourceId, ArrayList<Module> users) { super(context, textViewResourceId, users); this.users = users; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.layout_timetable, null); } Module user = users.get(position); if (user != null) { TextView time = (TextView) v.findViewById(R.id.text1); TextView module = (TextView) v.findViewById(R.id.text2); TextView location = (TextView) v.findViewById(R.id.text3); if (time != null) { time.setText("Time: \t"+user.getTime()); } if(module != null) { module.setText("\t"+user.getModule()); } if(location != null) { location.setText("Room: \t"+user.getRoom()); } } return v; } }<file_sep>package ie.nodstuff.rtpitestapp; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class MyFragmentPagerAdapter1 extends FragmentPagerAdapter { // Holds tab titles private String tabTitles[] = new String[] { "Monday", "Tuesday", "Wednesday","Thursday","Friday" }; private TimetableFragment context; public MyFragmentPagerAdapter1(FragmentManager fm, TimetableFragment context) { super(fm); this.context = context; } @Override public int getCount() { return tabTitles.length; } // Return the correct Fragment based on index @Override public Fragment getItem(int position) { DayView x; if(position == 0){ x = new DayView(); x.setDay(tabTitles[0]); return x; } else if(position == 1) { x = new DayView(); x.setDay(tabTitles[1]); return x; } else if(position == 2) { x = new DayView(); x.setDay(tabTitles[2]); return x; }else if (position ==3){ x = new DayView(); x.setDay(tabTitles[3]); return x; }else if (position == 4){ x = new DayView(); x.setDay(tabTitles[4]); return x; } return null; } @Override public CharSequence getPageTitle(int position) { return tabTitles[position]; } }<file_sep>package ie.nodstuff.rtpitestapp; import android.app.Fragment; import android.app.FragmentManager; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import java.util.ArrayList; import java.util.List; /** * Created by jackhanley on 26/03/2015. */ public class RoomSearchFragment extends Fragment { private View v; private Spinner s; private RoomTimeTable roomTimeTable; private List list; private FragmentManager fragmentManager; private List classTimeTable; private String rooms []={"A106", "A109", "A111", "A113", "A117", "A121x", "A123", "A123L", "A125", "A127", "A129", "A133", "A141", "A143", "A144", "A145", "A146", "A149", "A163L", "A167", "A169", "A171", "A173", "A177", "A183", "A183L", "A189", "A190", "A193", "A195", "A196", "A198", "A207", "A213B", "A214", "A215A-MCPM", "A215B-MCE", "A215L", "A217A", "A217B", "A221A", "A221B-MSE", "A222", "A222X", "A225", "A235", "A236", "A243L", "A255", "A257", "A269", "A270", "A271", "A272", "A273", "A275", "A284", "A285", "A286", "A287", "A288","B112", "B116", "B117", "B118", "B123L", "B128", "B131", "B132", "B140", "B143", "B145", "B147", "B148", "B149", "B151", "B154", "B161", "B162", "B163", "B165", "B167", "B170", "B172", "B174", "B176", "B180", "B183", "B185", "B187", "B188", "B188A", "B189", "B190", "B212", "B214", "B217", "B219", "B222", "B223", "B224", "B225", "B227", "B228", "B229", "B230", "B231", "B233", "B234", "B240", "B241L", "B242", "B243", "B245", "B247", "B248", "B249", "B250", "B251", "B254", "B260", "B262", "B263", "B267", "B268", "B269", "B270", "B274", "B276", "B282", "B283", "B288","C110A", "C110C", "C117", "C117C", "C120", "C125", "C127", "C128", "C129", "C134", "C134x", "C136", "C147", "C149", "C150", "C151", "C154", "C162", "C167", "C169", "C170", "C172", "C212", "C214", "C215", "C219", "C222", "C223", "C228", "C229", "C230", "C231", "C234", "C236", "C243", "C247", "C251", "C252", "C256", "C262", "C263", "C268","D160", "D230", "D237", "D238", "D239", "D241", "D242", "D245", "D259A LSC", "D259B LSC","E15", "E3", "E4", "E6", "E7","F1.2", "F1.3", "F1.4", "F1.5", "F1.6", "F2.10", "F2.11", "F2.13","G1.1", "G1.2", "G1.3", "G1.4", "G1.5", "G1.6", "G2.6", "G2.7", "GT1","IT1", "IT1.1", "IT1.2", "IT1.3", "IT2", "IT2.1", "IT2.2", "IT2.3", "IT3", "IT4", "IT5" }; private Boolean firstOpen; private RoomTimeTableFragment roomTimeTableFragment; private ArrayAdapter<CharSequence> a; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { v=inflater.inflate(R.layout.fragment_room_time_table,container,false); s = (Spinner) v.findViewById(R.id.room_spinner); list = new ArrayList(); // list.add("-"); firstOpen=true; fragmentManager = getFragmentManager(); for(int i=0; i<rooms.length;i++){ list.add(rooms[i]); } a = new ArrayAdapter <CharSequence> (getActivity(),android.R.layout.simple_spinner_item,list); a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); s.setAdapter(a); s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if(!firstOpen) { new RoomTimeTableTask().execute(); }else { firstOpen=false; } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); return v; } private class RoomTimeTableTask extends AsyncTask<String,String,String> { // Asynchronous background task to get the bus information // Because we can't run network jobs on the UI thread @Override protected String doInBackground(String... params) { roomTimeTable = new RoomTimeTable(s.getSelectedItem().toString()); return ""; } protected void onPostExecute(String result){ Controller.getInstance().setRoomTimeTable(roomTimeTable.getList()); roomTimeTableFragment = new RoomTimeTableFragment(); fragmentManager.beginTransaction().setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).replace(R.id.container, roomTimeTableFragment).commit(); } } } <file_sep># RTPITestApp This is just a simple readme. That is all. <file_sep>package ie.nodstuff.rtpitestapp; import android.app.Fragment; import android.os.Bundle; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Created by jackhanley on 02/03/2015. */ public class WebViewFragment extends Fragment { private String currentURL; private WebView wv; private View v; public void init(String url) { currentURL = url; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { v = inflater.inflate(R.layout.fragment_web, container, false); if (currentURL != null) { wv = (WebView) v.findViewById(R.id.webView); wv.getSettings().setJavaScriptEnabled(true); wv.setWebViewClient(new SwAWebClient()); wv.loadUrl(currentURL); } wv.setOnKeyListener(new View.OnKeyListener(){ @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) { wv.goBack(); return true; } return false; } }); return v; } public void updateUrl(String url) { currentURL = url; wv = (WebView) getView().findViewById(R.id.webView); wv.getSettings().setJavaScriptEnabled(true); wv.loadUrl(url); } private class SwAWebClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } } }<file_sep>package ie.nodstuff.rtpitestapp; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import stab.SlidingTabLayout; public class TimetableFragment extends Fragment { private FragmentActivity myContext; private View v; private FragmentManager fragmentManager; private ViewPager viewPager; private SlidingTabLayout slidingTabLayout; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { v=inflater.inflate(R.layout.activity_timetable,container,false); viewPager = (ViewPager)v.findViewById(R.id.viewpager); fragmentManager = myContext.getSupportFragmentManager(); viewPager.setAdapter(new MyFragmentPagerAdapter1(fragmentManager, this)); slidingTabLayout = (SlidingTabLayout)v.findViewById(R.id.sliding_tabs); slidingTabLayout.setViewPager(viewPager); return v; } @Override public void onAttach(Activity activity) { myContext=(FragmentActivity) activity; super.onAttach(activity); } } <file_sep>package ie.nodstuff.rtpitestapp; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RteNews { URL u; InputStream is = null; String s; boolean test = false; int count = 0; ArrayList<NewsSlot> list = new ArrayList<NewsSlot>(); String headline = null; String content = null; private static RteNews mInstance = null; private RteNews(){ getNews(); } public static RteNews getInstance(){ if(mInstance == null) { mInstance = new RteNews(); } return mInstance; } public ArrayList<NewsSlot> getList() { return list; } public void getNews() { try { u = new URL("http://www.rte.ie/news/rss/news-headlines.xml"); is = u.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(new DataInputStream(is), "UTF8")); while ((s = in.readLine()) != null) { if (s.contains("<title>")) { test = true; String data = Pattern.quote("<title>") + "(.*?)" + Pattern.quote("</title>"); Pattern patternT = Pattern.compile(data); Matcher matcherT = patternT.matcher(s); while (matcherT.find()) { headline = matcherT.group(1); } headline = headline.replaceAll("&#39;", "'").replaceAll("&quot;", "\""); } if (count < 3 && test == true) { count++; } if (count < 5 && s.contains("<description>")) { String data2 = Pattern.quote("<description>") + "(.*?)" + Pattern.quote("</description>"); Pattern pattern2 = Pattern.compile(data2); Matcher matcher2 = pattern2.matcher(s); while (matcher2.find()) { content = matcher2.group(1); } content = content.replaceAll("&#39;", "'").replaceAll("&quot;", "\""); NewsSlot m = new NewsSlot(headline, content); list.add(m); count = 0; } } Controller.getInstance().setRte(list); } catch (MalformedURLException mue) { System.out.println("MalformedURLException"); mue.printStackTrace(); System.exit(1); } catch (IOException ioe) { System.out.println("IOException"); ioe.printStackTrace(); System.exit(1); } finally { try { is.close(); } catch (IOException ioe) { } } }}<file_sep>package ie.nodstuff.rtpitestapp; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; class RoomTimeTable{ URL u; InputStream is = null; DataInputStream dis; String s; boolean test = false; int count = 0; String course = "CCC"; String duration = "DDD"; String module = "MMM"; String day = "day"; String time="TTT"; String times[] = { "9:00", "10:00", "11:00", "12:00", "13:00", "14:00","15:00", "16:00", "17:00" }; String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday","Friday" }; int i=0; ArrayList<ClassSlot> list = new ArrayList<ClassSlot>(); public ArrayList<ClassSlot> getList(){ return this.list; } public RoomTimeTable(String room){ runTimetable(room); } public void runTimetable(String room) { System.out.print("hello "); try { String holder = room.replaceAll("\\s", "+"); for (int x = 1; x <= days.length; x++) { u = new URL( "http://timetables.cit.ie:70/reporting/Individual;Location;name;" + room +"%0D%0A?weeks=&days=" + x +"&periods=1-40&height=100&width=100"); is = u.openStream(); dis = new DataInputStream(new BufferedInputStream(is)); while ((s = dis.readLine()) != null) { if(i==9){ i=0; } if (s.contains(times[i])) { test = true; } if(count==13){ count=0; test=false; day=days[x-1]; ClassSlot m=new ClassSlot(day,time,module,course,duration); list.add(m); i++; } if (count < 13 && test == true) { String regexStringTime = Pattern.quote("<td rowspan='1' bgcolor='#C0C0C0'><font color='#000000'>") + "(.*?)" + Pattern.quote("</font></td>"); String regexStringCourse = Pattern.quote("<td align='left'><font color='#000000'>") + "(.*?)" + Pattern.quote("</font></td>"); String regexStringModule = Pattern.quote("<td align='left'><font color='#0000FF'>") + "(.*?)" + Pattern.quote("</font></td>"); String regexStringDuration = Pattern.quote("td colspan='1' rowspan='") + "(.*?)" + Pattern.quote("' >"); Pattern patternT = Pattern.compile(regexStringTime); Pattern patternC = Pattern.compile(regexStringCourse); Pattern patternM = Pattern.compile(regexStringModule); Pattern patternD = Pattern.compile(regexStringDuration); Matcher matcherT = patternT.matcher(s); Matcher matcherC = patternC.matcher(s); Matcher matcherM = patternM.matcher(s); Matcher matcherD = patternD.matcher(s); while (matcherT.find()) { time = matcherT.group(1); } while (matcherC.find()) { course = matcherC.group(1); } while (matcherM.find()) { module = matcherM.group(1); } while (matcherD.find()) { duration = matcherD.group(1); } count++; if(count==2&&(s.contains("<td colspan='1' rowspan='")==false)){ test=false; count=0; i++; } } } } } catch (MalformedURLException mue) { System.out.println("MalformedURLException"); mue.printStackTrace(); System.exit(1); } catch (IOException ioe) { System.out.println("IOException"); ioe.printStackTrace(); System.exit(1); } finally { try { is.close(); } catch (IOException ioe) { } } } }<file_sep>package ie.nodstuff.rtpitestapp; public class NewsSlot { private String headline; private String content; public String getHeadline() { return headline; } public void setHeadline(String headline) { this.headline = headline; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public NewsSlot(String headline, String content) { super(); this.headline = headline; this.content = content; } @Override public String toString() { return "NewsSlot [headline=" + headline + ", content=" + content + "]"; } }<file_sep>package ie.nodstuff.rtpitestapp; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by nodstuff on 17/03/15. */ public class AnnounceClass { private String module; private String lecturer; private String note; private String [] news = new String[3]; private static AnnounceClass mInstance = null; private AnnounceClass(){ } public static AnnounceClass getInstance(){ if(mInstance == null) { mInstance = new AnnounceClass(); } return mInstance; } public String getAnnouncementResults() throws IOException, JSONException { //Create JSON Objects and feed the required URL to the readJSONResult method to pull the data String url = "http://mytestannounce.elasticbeanstalk.com/Announce"; JSONObject jsonobject = new JSONObject(readJSONResult(url)); module = jsonobject.getString("class"); note = jsonobject.getString("note"); lecturer = jsonobject.getString("lecturer"); JSONArray newsArray = (JSONArray)jsonobject.get("news"); // Add the data to an array to be added to the controller to be shown on the main page for(int i=0;i<newsArray.length();i++){ news[i]=newsArray.getString(i); } // Add the data to the global controller Controller.getInstance().setNews(news); return module +"\n"+note+"\n"+lecturer; } private String readJSONResult(String s) throws IOException { //Pull down the JSON data and use stringbuilder to build it into strings //The parameter String s is a URL that leads to our Announce servlet on our VPS StringBuilder stringbuilder; BufferedReader bufferedreader; stringbuilder = new StringBuilder(); HttpResponse httpresponse = (new DefaultHttpClient()).execute(new HttpGet(s)); bufferedreader = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent())); String s1 = bufferedreader.readLine(); if (s1 != null){ stringbuilder.append(s1); } return stringbuilder.toString(); } } <file_sep>package ie.nodstuff.rtpitestapp; /** * Created by nodstuff on 28/02/15. */ public class Module{ private String day; private int hourOfDay=-1; private String time; private String module; private String room; private String duration; public Module(String day, String time,String module,String room, String duration){ this.day=day; this.time=time; this.module=module; this.room=room; this.duration=duration; setHourOfDay(time); } public String getDay() { return day; } public void setDay(String day) { this.day = day; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getModule() { return module; } public void setModule(String module) { this.module = module; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } @Override public String toString() { return "Time: "+time+"\n"+module+"\nLocation: "+room; } public void setHourOfDay(String time){ if(time!=null){ String [] temp = time.split(":"); this.hourOfDay=Integer.parseInt(temp[0]); } } public int getHourOfDay(){ return hourOfDay; } } <file_sep>package ie.nodstuff.rtpitestapp; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Timetable{ private URL u; private InputStream is = null; private DataInputStream dis; private String s; private boolean test = false; private int count = 0; private String time = "TTT"; private String room = "RRR"; private String duration = "DDD"; private String module = "MMM"; private String day = "day"; private String times[] = { "9:00", "10:00", "11:00", "12:00", "13:00", "14:00","15:00", "16:00", "17:00" }; private String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday","Friday" }; private int i=0; private ArrayList<Module> timetable = new ArrayList<Module>(); public ArrayList<Module> getTimetable(){ return this.timetable; } public Timetable(String courseCode){ //"CO.DCOM1 - A" runTimetable(courseCode); } public void runTimetable(String classGroup) { try { String holder = classGroup.replaceAll("\\s", "+"); for (int x = 1; x <= days.length; x++) { u = new URL( "http://timetables.cit.ie:70/reporting/Individual;Student+Set;name;" + holder + "%0D%0A?weeks=24-31;34-38&days=" + x + "&periods=5-40&height=200&width=100"); is = u.openStream(); dis = new DataInputStream(new BufferedInputStream(is)); while ((s = dis.readLine()) != null) { if(i==9){ i=0; } if (s.contains(times[i])) { test = true; } if(count==13){ count=0; test=false; day=days[x-1]; Module slot = new Module(day, time, module,room, duration); timetable.add(slot); i++; } if (count < 13 && test == true) { String regexStringTime = Pattern.quote("<td rowspan='1' bgcolor='#C0C0C0'><font color='#000000'>") + "(.*?)" + Pattern.quote("</font></td>"); String regexStringModule = Pattern.quote("<td align='left'><font color='#000000'>") + "(.*?)" + Pattern.quote("</font></td>"); String regexStringRoom = Pattern.quote("<td align='right'><font color='#008000'>") + "(.*?)" + Pattern.quote("</font></td>"); String regexStringDuration = Pattern.quote("td colspan='1' rowspan='") + "(.*?)" + Pattern.quote("' >"); Pattern patternT = Pattern.compile(regexStringTime); Pattern patternR = Pattern.compile(regexStringRoom); Pattern patternM = Pattern.compile(regexStringModule); Pattern patternD = Pattern.compile(regexStringDuration); Matcher matcherT = patternT.matcher(s); Matcher matcherR = patternR.matcher(s); Matcher matcherM = patternM.matcher(s); Matcher matcherD = patternD.matcher(s); if (matcherT.find()) { time = matcherT.group(1); } if (matcherR.find()) { room = matcherR.group(1); } if (matcherM.find()) { module = matcherM.group(1); } if (matcherD.find()) { duration = matcherD.group(1); } count++; if(count==2&&(s.contains("<td colspan='1' rowspan='")==false)){ test=false; count=0; i++; } } } } } catch (MalformedURLException mue) { System.out.println("MalformedURLException"); mue.printStackTrace(); System.exit(1); } catch (IOException ioe) { System.out.println("a, b, c ,d"); Scanner reader = new Scanner(System.in); String a=reader.next(); a=a.toUpperCase(); classGroup=classGroup + " - " + a; System.out.println(classGroup); runTimetable(classGroup); // ioe.printStackTrace(); // System.exit(1); } finally { try { is.close(); } catch (NullPointerException n) { } catch (IOException e) { e.printStackTrace(); } } } }
4a86c90beb5ac438ddcc3f284a610cba5511d930
[ "Markdown", "Java" ]
12
Java
DCOM3/RTPITestApp
69a9def8085ef9fa003eacf555d10dc55565bf98
d21b82f8bdcd44faac1b7a8f540e18f57cbef0eb
refs/heads/master
<repo_name>marciobarbosa/vim-conf<file_sep>/install.sh rm -r ~/.vim rm ~/.vimrc mkdir ~/.vim cp -r * ~/.vim cp .vimrc ~/.vimrc <file_sep>/README.md # vim-conf 1. INSTALL git clone https://github.com/marciobarbosa/vim-conf.git cd vim-conf ./install.sh
500653b7466c314370643a86465c69e1c5025e6a
[ "Markdown", "Shell" ]
2
Shell
marciobarbosa/vim-conf
18cdb6f1dc10fe628adc37b97f8521037786140d
09adb2bd41cea7f528dedf8ba496c55422744494
refs/heads/master
<file_sep>import {createStore} from 'redux'; import reducer from '../reducer'; import {composeWithDevTools} from 'redux-devtools-extension' // redux4.0版本在调试的时候,redux插件不能用,必须切换到3.7.2版本才行 export default ()=>createStore(reducer,composeWithDevTools())<file_sep>import React, { Component } from "react"; import { Card, Form, Input, Button, Checkbox } from "antd"; import { min } from "moment"; const FormItem = Form.Item; class Login extends Component { componentDidMount() { // this.props.form.validateFields(); } handerSubmit = e => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { console.log("表单数据:", values); } }); }; render() { const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form; return ( <div> <Card title="登陆行内表单"> <Form layout="inline" onSubmit={this.handerSubmit}> <FormItem> <Input placeholder="请输入用户名" /> </FormItem> <FormItem> <Input placeholder="请输入密码" /> </FormItem> <FormItem> <Button type="primary">登陆</Button> </FormItem> </Form> </Card> <Card title="水平表单"> <Form onSubmit={this.handerSubmit} style={{ width: 300 }}> <FormItem> {getFieldDecorator("userName", { rules: [ { required: true, message: "请输入用户名!" }, { min: 5, max: 10, message: "长度不够10个" } ], initialValue: "" })(<Input placeholder="请输入用户名" />)} </FormItem> <FormItem> {getFieldDecorator("pwd", { rules: [{ required: true, message: "请输入密码!" }], initialValue: "" })(<Input.Password placeholder="请输入密码" />)} </FormItem> <FormItem> {getFieldDecorator("remember", { valuePropName: "checked", initialValue: true })(<Checkbox type="primary">记住密码</Checkbox>)} <a href="javascript:;" style={{float:"right"}}>忘记密码</a> </FormItem> <FormItem> <Button type="primary" htmlType="submit"> 登陆 </Button> </FormItem> </Form> </Card> </div> ); } } export default Form.create()(Login); <file_sep>import JsonP from "jsonp"; import axios from 'axios' import { Modal } from "antd"; import Utils from './../utils/utils' export default class Axios { static requestList(_this,url,params){ var data={ params:params } this.ajax({ url, data }).then((data)=>{ if (data&&data.result) { _this.setState({ list: data.result.item_list.map((item, index) => { item.key = index; return item; }), pagination: Utils.pagination(data, current => { _this.params.page = current; _this.requestList(); }) }); } }) } static jsonp(options) { return new Promise((resolve, reject) => { JsonP( options.url, { param: "callback" }, function(err, response) { if (response.status ==='success') { resolve(response); } else { reject(response.message); } } ); }); } static ajax(option){ let loading; if (option.data && option.data.isShowLoading!==false) { loading=document.getElementById('ajaxLoading'); loading.style.display='block'; } let bassApi='https://www.easy-mock.com/mock/5a7278e28d0c633b9c4adbd7/api' return new Promise((resolve,reject)=>{ axios({ url:option.url, method:'get', baseURL:bassApi, timeout:5000, params:(option.data&&option.data.params)||'' }).then((response)=>{ if (option.data && option.data.isShowLoading!==false) { loading=document.getElementById('ajaxLoading'); loading.style.display='none'; } if (response.status==200) { let res=response.data; if (res.code==0) { resolve(res) }else{ Modal.info({ title:'提示', content:res.msg }) } }else{ reject(response.data) } }) }); } } <file_sep>import React, { Component } from "react"; import { Spin, Card, Button, Icon, Alert } from "antd"; import "./ui.less"; class Loadings extends Component { render() { return ( <div> <Card title="spin用法" className="card-warp"> <Spin size="small" /> <Spin /> <Spin size="large" /> <Spin size="large" tip="加载中..."> <Alert message="react" description="学习中" type="warning" /> </Spin> </Card> </div> ); } } export default Loadings; <file_sep>import React, { Component } from "react"; import { Card, Button, Form, Input, Select, Modal, message, Tree, Transfer, Switch } from "antd"; import ETable from "../../components/ETable"; import Utils from "../../utils/utils"; import axios from "../../axios"; import menuConfig from "../../config/menuConfig"; const FormItem = Form.Item; const Option = Select.Option; const TreeNode = Tree.TreeNode; class Permission extends Component { state = { list: [], isRoleVisible: false, ispermission: false, detailInfo: {}, isUserVisible: false }; // 创建角色 handerAddRole = () => { this.setState({ isRoleVisible: true }); }; // 设置权限 handerSetRole = () => { let itme = this.state.selectedItem; // console.log(itme.menus) if (!itme) { Modal.info({ title: "提示", content: "请选择一个角色" }); return; } this.setState({ ispermission: true, detailInfo: itme, menuInfo: itme.menus }); }; // 用户授权 handerSetUserRole = () => { let item = this.state.selectedItem; if (!item) { Modal.info({ title: "提示", content: "请选择一个角色" }); return; } this.setState({ isUserVisible: true, detailInfo: item }); this.getRoleUserList(item.id); }; //获取角色下的用户 getRoleUserList = id => { axios .ajax({ url: "/role/user_list", data: { params: { id } } }) .then(res => { if (res) { this.getAuthUserList(res.result); } }); }; getAuthUserList = dataSource => { const mockData = []; const targetData = []; if (dataSource && dataSource.length > 0) { for (let i = 0; i < dataSource.length; i++) { const datas = { key: dataSource[i].user_id, title: dataSource[i].user_name, status: dataSource[i].status }; if (datas.status == 1) { targetData.push(datas.key); } mockData.push(datas); } this.setState({ mockData, targetData }); } }; componentDidMount() { axios.requestList(this, "/role/list", {}); } handerRoleSubmit = () => { let data = this.roleForm.props.form.getFieldsValue(); axios .ajax({ url: "role/create", data: { params: data } }) .then(res => { if (res.code == 0) { message.success("创建成功!"); this.setState({ isRoleVisible: false }); axios.requestList(this, "/role/list", {}); this.roleForm.props.form.resetFields(); } }); }; // 设置权限数据提交 handerPermission = () => { let items = this.permForm.props.form.getFieldsValue(); items.role_id = this.state.selectedItem.id; items.menus = this.state.menuInfo; axios .ajax({ url: "/permission/edit", data: { params: { ...items } } }) .then(res => { if (res) { this.setState({ ispermission: false }); axios.requestList(this, "/role/list", {}); this.permForm.props.form.resetFields(); } }); }; // 保存用户授权的数据 handerUserSubmit = () => { let data = {}; data.user_ids = this.state.targetData; data.role_id = this.state.selectedItem.id; axios .ajax({ url: "/role/user_role_edit", data: { params: { ...data } } }) .then(res => { if (res) { this.setState({ isUserVisible: false }); axios.requestList(this, "/role/list", {}); } }); }; render() { const colums = [ { title: "角色id", dataIndex: "id" }, { title: "角色名称", dataIndex: "role_name" }, { title: "创建时间", dataIndex: "create_time", render: Utils.formateDate }, { title: "使用状态", dataIndex: "status", render(status) { return status == 1 ? "启用" : "停用"; } }, { title: "授权时间", dataIndex: "authorize_time", render: Utils.formateDate }, { title: "授权人", dataIndex: "authorize_user_name" } ]; return ( <div> <Card> <Button type="primary" onClick={this.handerAddRole}> 创建角色 </Button> <Button type="primary" onClick={this.handerSetRole}> 设置权限 </Button> <Button type="primary" onClick={this.handerSetUserRole}> 用户授权 </Button> </Card> <div className="content-wrap"> <ETable columns={colums} dataSource={this.state.list} pagination={this.state.pagination} updataSelectItem={Utils.updataSelectItem.bind(this)} selectedRowKeys={this.state.selectedRowKeys} selectedItem={this.state.selectedItem} /> </div> <Modal title="创建角色" visible={this.state.isRoleVisible} onCancel={() => { this.roleForm.props.form.resetFields(); this.setState({ isRoleVisible: false }); }} onOk={this.handerRoleSubmit} > <RoleForm wrappedComponentRef={inst => { this.roleForm = inst; }} /> </Modal> <Modal title="设置权限" width={600} visible={this.state.ispermission} onOk={this.handerPermission} onCancel={() => { this.setState({ ispermission: false }); }} > <PermEditForm detailInfo={this.state.detailInfo} patchMenuInfo={checkedKeys => { this.setState({ menuInfo: checkedKeys }); }} menuInfo={this.state.menuInfo} wrappedComponentRef={inst => (this.permForm = inst)} /> </Modal> <Modal title="用户授权" width={800} visible={this.state.isUserVisible} onOk={this.handerUserSubmit} onCancel={() => { this.setState({ isUserVisible: false }); }} > <RoleAuthForm detailInfo={this.state.detailInfo} targetKeys={this.state.targetData} mockData={this.state.mockData} wrappedComponentRef={inst => (this.userAuthForm = inst)} patchUserInfo={targetKeys => { this.setState({ targetData: targetKeys }); }} /> </Modal> </div> ); } } export default Permission; class RoleForm extends React.Component { render() { const { getFieldDecorator } = this.props.form; const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 19 } }; return ( <Form layout="horizontal"> <FormItem label="角色名称" {...formItemLayout}> {getFieldDecorator("role_name")( <Input type="text" placeholder="请输入角色名" /> )} </FormItem> <FormItem label="状态" {...formItemLayout}> {getFieldDecorator("status")( <Select placeholder="请选择"> <Option value={1}>启用</Option> <Option value={2}>停用</Option> </Select> )} </FormItem> </Form> ); } } RoleForm = Form.create()(RoleForm); class PermEditForm extends React.Component { onCheck = checkedKeys => { console.log(checkedKeys); this.props.patchMenuInfo(checkedKeys); }; renderTreeNode = data => { return data.map(item => { if (item.children) { return ( <TreeNode title={item.title} key={item.key}> {this.renderTreeNode(item.children)} </TreeNode> ); } else { return <TreeNode title={item.title} key={item.key} />; } }); }; render() { const { getFieldDecorator } = this.props.form; const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 19 } }; const detail_info = this.props.detailInfo; const menuInfo = this.props.menuInfo; return ( <Form layout="horizontal"> <FormItem label="角色名称" {...formItemLayout}> <Input disabled placeholder={detail_info.role_name} /> </FormItem> <FormItem label="状态" {...formItemLayout}> {getFieldDecorator("status", { initialValue: detail_info.status })( <Select> <Option value={1}>启用</Option> <Option value={0}>停用</Option> </Select> )} </FormItem> <Tree checkable defaultExpandAll onCheck={checkedKeys => { this.onCheck(checkedKeys); }} checkedKeys={menuInfo} > <TreeNode title="平台权限" key="platform_all"> {this.renderTreeNode(menuConfig)} </TreeNode> </Tree> </Form> ); } } PermEditForm = Form.create()(PermEditForm); class RoleAuthForm extends React.Component { filterOption = (inputValue, option) => option.title.indexOf(inputValue) > -1; handleChange = nextTargetKeys => { this.props.patchUserInfo(nextTargetKeys); }; render() { const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 19 } }; const detail_info = this.props.detailInfo; return ( <Form layout="horizontal"> <FormItem label="角色名称" {...formItemLayout}> <Input disabled placeholder={detail_info.role_name} /> </FormItem> <FormItem label="选择用户" {...formItemLayout}> <Transfer dataSource={this.props.mockData} titles={["待选用户", "已选用户"]} showSearch searchPlaceholder="输入用户名" filterOption={this.filterOption} targetKeys={this.props.targetKeys} onChange={this.handleChange} onSearch={this.handleSearch} render={item => item.title} /> </FormItem> </Form> ); } } RoleAuthForm = Form.create()(RoleAuthForm); <file_sep>import React, { Component } from "react"; import "./ui.less"; import { Modal, Button, Card } from "antd"; const confirm = Modal.confirm; class Models extends Component { showbox() { confirm({ title: "Do you Want to delete these items?", content: "Some descriptions", onOk() { console.log("OK"); }, onCancel() { console.log("Cancel"); } }); } render() { return ( <div> <Card title="基础模态框" className='warp'> <Button type="primary" onClick={this.showbox.bind(this)}> 确认 </Button> <Button type="primary" onClick={this.showbox.bind(this)}> 自定义弹窗 </Button> <Button type="primary" onClick={this.showbox.bind(this)}> 顶部20px </Button> <Button type="primary" onClick={this.showbox.bind(this)}> 水平垂直居中 </Button> </Card> <Card title="信息确认框" className='warp'> <Button type="primary">confirm</Button> <Button type="info">info</Button> <Button type="success">success</Button> <Button type="primary">warm</Button> </Card> </div> ); } } export default Models; <file_sep>import React, { Component } from "react"; import echartTheme from "./../themeLight"; // 按需加载 import echarts from "echarts/lib/echarts"; import "echarts/lib/chart/line"; import "echarts/lib/component/tooltip"; import "echarts/lib/component/legend"; import "echarts/lib/component/title"; import "echarts/lib/component/markPoint"; import ReactEchart from "echarts-for-react"; import { Card } from "antd"; class Line extends Component { componentWillMount() { echarts.registerTheme("Imooc", echartTheme); } getOption = () => { let option = { title: { text: "用户骑行订单", subtext: "纯属虚构", x: "center" }, tooltip: { trigger: "axis" }, xAxis: { data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] }, yAxis: { type: "value" }, legend: { type: "scroll", orient: "vertical", right: 10, top: 20, bottom: 20, data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] }, series: [ { name: "订单量", type: "line", radius: "55%", center: ["50%", "50%"], data: [1200, 1500, 1700, 1900, 1000, 4200, 2200], itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: "rgba(0, 0, 0, 0.5)" } } } ] }; return option; }; getOption2 = () => { let option = { title: { text: "折线图堆叠" }, tooltip: { trigger: "axis" }, legend: { data: ["邮件营销", "联盟广告", "视频广告", "直接访问", "搜索引擎"] }, grid: { left: "3%", right: "4%", bottom: "3%", containLabel: true }, xAxis: { type: "category", boundaryGap: false, data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] }, yAxis: { type: "value" }, series: [ { name: "邮件营销", type: "line", stack: "总量", data: [120, 132, 101, 134, 90, 230, 210] }, { name: "联盟广告", type: "line", stack: "总量", data: [220, 182, 191, 234, 290, 330, 310] }, { name: "视频广告", type: "line", stack: "总量", data: [150, 232, 201, 154, 190, 330, 410] }, { name: "直接访问", type: "line", stack: "总量", data: [320, 332, 301, 334, 390, 330, 320] }, { name: "搜索引擎", type: "line", stack: "总量", data: [820, 932, 901, 934, 1290, 1330, 1320] } ] }; return option; }; getOption3 = () => { let option = { title: { text: "堆叠区域图" }, tooltip: { trigger: "axis", axisPointer: { type: "cross", label: { backgroundColor: "#6a7985" } } }, legend: { data: ["邮件营销", "联盟广告", "视频广告", "直接访问", "搜索引擎"] }, grid: { left: "3%", right: "4%", bottom: "3%", containLabel: true }, xAxis: [ { type: "category", boundaryGap: false, data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] } ], yAxis: [ { type: "value" } ], series: [ { name: "邮件营销", type: "line", stack: "总量", areaStyle: {}, data: [120, 132, 101, 134, 90, 230, 210] }, { name: "联盟广告", type: "line", stack: "总量", areaStyle: {}, data: [220, 182, 191, 234, 290, 330, 310] }, { name: "视频广告", type: "line", stack: "总量", areaStyle: {}, data: [150, 232, 201, 154, 190, 330, 410] }, { name: "直接访问", type: "line", stack: "总量", areaStyle: { normal: {} }, data: [320, 332, 301, 334, 390, 330, 320] }, { name: "搜索引擎", type: "line", stack: "总量", label: { normal: { show: true, position: "top" } }, areaStyle: { normal: {} }, data: [820, 932, 901, 934, 1290, 1330, 1320] } ] }; return option; }; render() { return ( <div> <Card title="折线图"> <ReactEchart option={this.getOption()} theme="Imooc" style={{ height: 500 }} /> </Card> <Card title="折线图2"> <ReactEchart option={this.getOption2()} theme="Imooc" style={{ height: 500 }} /> </Card> <Card title="折线图3"> <ReactEchart option={this.getOption3()} theme="Imooc" style={{ height: 500 }} /> </Card> </div> ); } } export default Line; <file_sep>import React, { Component } from "react"; import echartTheme from "./../themeLight"; // 按需加载 import echarts from "echarts/lib/echarts"; import "echarts/lib/chart/pie"; import "echarts/lib/component/tooltip"; import "echarts/lib/component/legend"; import "echarts/lib/component/title"; import "echarts/lib/component/markPoint"; import ReactEchart from "echarts-for-react"; import { Card } from "antd"; class Pie extends Component { componentWillMount() { echarts.registerTheme("Imooc", echartTheme); } getOption = () => { let option = { title: { text: "用户骑行订单", subtext: "纯属虚构", x: "center" }, tooltip: { trigger: "item", formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { type: "scroll", orient: "vertical", right: 10, top: 20, bottom: 20, data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] }, series: [ { name: "订单量", type: "pie", radius: "55%", center: ["50%", "50%"], data: [ { value: 1200, name: "周一" }, { value: 1500, name: "周二" }, { value: 1700, name: "周三" }, { value: 1900, name: "周四" }, { value: 1000, name: "周五" }, { value: 4200, name: "周六" }, { value: 2200, name: "周日" } ], itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: "rgba(0, 0, 0, 0.5)" } } } ] }; return option; }; getOption2 = () => { let option = { title: { text: "用户骑行订单", subtext: "纯属虚构", x: "center" }, tooltip: { trigger: "item", formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { type: "scroll", orient: "vertical", right: 10, top: 20, bottom: 20, data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] }, series: [ { name: "订单量", type: "pie", radius: ["55%", "70%"], center: ["50%", "50%"], data: [ { value: 1200, name: "周一" }, { value: 1500, name: "周二" }, { value: 1700, name: "周三" }, { value: 1900, name: "周四" }, { value: 1000, name: "周五" }, { value: 4200, name: "周六" }, { value: 2200, name: "周日" } ], itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: "rgba(0, 0, 0, 0.5)" } } } ] }; return option; }; getOption3 = () => { let option = { title: { text: "用户骑行订单", subtext: "纯属虚构", x: "center" }, tooltip: { trigger: "item", formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { type: "scroll", orient: "vertical", right: 10, top: 20, bottom: 20, data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] }, series: [ { name: "订单量", type: "pie", radius: ["55%", "70%"], center: ["50%", "50%"], data: [ { value: 1200, name: "周一" }, { value: 1500, name: "周二" }, { value: 1700, name: "周三" }, { value: 1900, name: "周四" }, { value: 1000, name: "周五" }, { value: 4200, name: "周六" }, { value: 2200, name: "周日" } ].sort((a, b) => { return a.value - b.value; }), roseType: "radius", itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: "rgba(0, 0, 0, 0.5)" } } } ] }; return option; }; render() { return ( <div> <Card title="柱状图表1"> <ReactEchart option={this.getOption()} theme="Imooc" style={{ height: 500 }} /> </Card> <Card title="环形图"> <ReactEchart option={this.getOption2()} theme="Imooc" style={{ height: 500 }} /> </Card> <Card title="环形图3"> <ReactEchart option={this.getOption3()} theme="Imooc" style={{ height: 500 }} /> </Card> </div> ); } } export default Pie; <file_sep>import React, { Component } from "react"; import { Card, Button, Form, Modal, message } from "antd"; import axios from "./../../axios"; import Utils from "./../../utils/utils"; import BaseForm from "../../components/BaseForm"; import ETable from "../../components/ETable"; const FormItem = Form.Item; export default class Order extends Component { state = { list: [], orderInfo: {}, orderVisible: false }; params = { page: 1 }; formList = [ { type: "SELECT", label: "城市", placeholder: "全部", initialValue: "0", field: "city_id", width: 100, list: [ { id: "0", name: "全部" }, { id: "1", name: "北京" }, { id: "2", name: "武汉" }, { id: "3", name: "四川" } ] }, { type: "时间查询" }, { type: "SELECT", label: "订单状态", placeholder: "全部", field: "order_status", initialValue: "0", width: 100, list: [ { id: "0", name: "全部" }, { id: "1", name: "进行中" }, { id: "2", name: "结束行程" } ] } ]; // 请求表格数据 requestList = () => { let _this = this; axios.requestList(_this, "/order/list", this.params); }; componentDidMount() { this.requestList(); } handerFilter = params => { this.params = params; this.requestList(); }; handerFinsh = () => { if (!this.state.selectedItem) { Modal.info({ title: "信息", content: "请选择一条订单进行结束" }); return; } axios .ajax({ url: "/order/ebike_info", data: { params: 1 } }) .then(res => { if (res.code === "0") { this.setState({ orderVisible: true, orderInfo: res.result }); } }); }; // 确定结束订单 handerOK = () => { axios .ajax({ url: "/order/finish_order", data: { params: 1 } }) .then(res => { if (res.code === "0") { message.success("订单结束成功!"); this.setState({ orderVisible: false, selectedItem: null, selectedRowKeys: [] }); this.requestList(); } }); }; // 跳转订单详情页面 openDetail = () => { if (!this.state.selectedItem) { Modal.info({ title: "信息", content: "请选择一条订单" }); return; } // console.log(this.state.selectedItem[0]) window.open( `/#/common/order/detail/${this.state.selectedItem[0].id}`, "_blank" ); }; render() { const columns = [ { title: "订单编号", dataIndex: "order_sn" }, { title: "车辆编号", dataIndex: "bike_sn" }, { title: "用户名", dataIndex: "user_name" }, { title: "手机号码", dataIndex: "mobile" }, { title: "里程", dataIndex: "distance", render(distance) { return distance / 1000 + "KM"; } }, { title: "行驶时长", dataIndex: "total_time", render(total_time) { return total_time; } }, { title: "状态", dataIndex: "status", render(status) { return status === 1 ? "进行中" : "行程结束"; } }, { title: "开始时间", dataIndex: "start_time", render: Utils.formateDate }, { title: "结束时间", dataIndex: "end_time", render: Utils.formateDate }, { title: "订单金额", dataIndex: "total_fee" }, { title: "实付金额", dataIndex: "user_pay" } ]; const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 19 } }; return ( <div> <Card> <BaseForm formList={this.formList} filterSubmit={this.handerFilter} /> </Card> <Card style={{ marginTop: 10 }}> <Button type="primary" onClick={this.openDetail}> 订单详情 </Button> <Button type="primary" onClick={this.handerFinsh}> 结束订单 </Button> </Card> <div className="content-wrap"> <ETable columns={columns} dataSource={this.state.list} pagination={this.state.pagination} selectedRowKeys={this.state.selectedRowKeys} updataSelectItem={Utils.updataSelectItem.bind(this)} rowSelection='checkbox' selectedIds={this.state.selectedIds} selectItem={this.state.selectedItem} /> </div> <Modal title="结束订单" visible={this.state.orderVisible} onCancel={() => { this.setState({ orderVisible: false }); }} onOk={this.handerOK} width={600} > <Form> <FormItem label="车辆编号" {...formItemLayout}> {this.state.orderInfo.bike_sn} </FormItem> <FormItem label="剩余电量" {...formItemLayout}> {this.state.orderInfo.battery + "%"} </FormItem> <FormItem label="行程开始时间" {...formItemLayout}> {this.state.orderInfo.start_time} </FormItem> <FormItem label="当前位置" {...formItemLayout}> {this.state.orderInfo.location} </FormItem> </Form> </Modal> </div> ); } } <file_sep>import React, { Component } from "react"; import "./../style/common.less"; class Nomatch extends Component { render() { return ( <div className="nofound"> <span>未找到该页面</span> </div> ); } } export default Nomatch; <file_sep>import React, { Component } from "react"; import { Select } from "antd"; const Option = Select.Option; export default { // 时间格式化 formateDate(time) { if (!time) return ""; let date = new Date(time); let month = date.getMonth() + 1 >= 10 ? date.getMonth() : "0" + (date.getMonth() + 1); let day = date.getDate() >= 10 ? date.getDate() : "0" + date.getDate(); let getSeconds = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds(); return ( date.getFullYear() + "-" + month + "-" + day + "-" + date.getHours() + ":" + date.getMinutes() + ":" + getSeconds ); }, // 分页 pagination(data, callback) { let page = { onChange: current => { callback(current); }, current: data.result.page, pageSize: data.result.page_size, total: data.result.total_count, showTotal: () => { return `共${data.result.total_count}条`; } }; return page; }, // 封装下拉选项 getOptionList(data) { if (!data) { return []; } let options = []; data.map(item => { options.push( <Option value={item.id} key={item.id}> {item.name} </Option> ); }); return options; }, // 单选或多选,选中的数据 updataSelectItem(keys, items,selectedIds) { if (selectedIds) { this.setState({ selectedRowKeys: keys, selectedItem: items, selectedIds }); } else { this.setState({ selectedRowKeys: keys, selectedItem: items, }); } } }; <file_sep>import React, { Component } from "react"; import "./ui.less"; import { Card, Carousel } from "antd"; class ICarousel extends Component { onChange=()=>{ } render() { return ( <div> <Card title="文字背景轮播" className='card-warp'> <Carousel afterChange={this.onChange} autoplay effect='fade'> <div> <h3>1</h3> </div> <div> <h3>2</h3> </div> <div> <h3>3</h3> </div> <div> <h3>4</h3> </div> </Carousel> , </Card> <Card title="图片轮播" className='slider-wrap'> <Carousel afterChange={this.onChange} autoplay effect='fade' > <div> <img src='/carousel-img/carousel-1.jpg'></img> </div> <div> <img src='/carousel-img/carousel-2.jpg'></img> </div> <div> <img src='/carousel-img/carousel-3.jpg'></img> </div> </Carousel> , </Card> </div> ); } } export default ICarousel; <file_sep>import React, { Component } from "react"; import { Card, Button, Modal } from "antd"; import { Editor } from "react-draft-wysiwyg"; import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css"; import draftToHtml from "draftjs-to-html"; class Rich extends Component { state = { showRichText: false, editorState: "" }; onEditorStateChange = editorState => { this.setState({ editorState }); }; handerClear = editorState => { this.setState({ editorState: "" }); }; handerGet = () => { this.setState({ showRichText: true }); }; contentchange = contentchange => { this.setState({ contentchange }); }; render() { const { editorState } = this.state; return ( <div> <Card> <Button onClick={this.handerClear} type="primary"> 清空内容 </Button> <Button onClick={this.handerGet} type="primary"> 获取html内容 </Button> </Card> <Card title="富文本"> <Editor editorState={editorState} onContentStateChange={this.contentchange} onEditorStateChange={this.onEditorStateChange} /> </Card> <Modal title="富文本" visible={this.state.showRichText} onCancel={() => { this.setState({ showRichText: false }); }} footer={null} > {draftToHtml(this.state.contentchange)} </Modal> </div> ); } } export default Rich; <file_sep>import React, { Component } from "react"; import "./ui.less"; import { Card, Button, Radio, notification } from "antd"; class Notification extends Component { handerClick=(type,direction)=>{ if (direction) { notification.config({ placement:direction }) } notification[type]({ message: "提示信息", description: "描述的内容" }) } render() { return ( <div> <Card title="通知提醒框" className="card-warp"> <Button type="primary" onClick={()=>this.handerClick('success','topLeft')}> success </Button> <Button type="primary" onClick={()=>this.handerClick('info','topRight')}> info </Button> <Button type="primary" onClick={()=>this.handerClick('warning','bottomLeft')}> warning </Button> <Button type="primary" onClick={()=>this.handerClick('error','bottomRight')}> error </Button> </Card> </div> ); } } export default Notification;
b60903bb1f7ce42387a912c99f503c2d631f54e7
[ "JavaScript" ]
14
JavaScript
xupeihong/imoocdemo
83b79d4572b484331160a01ce414f8f98190ef48
243f1b3b5dcc94cf01c20c602b122367b456c694
refs/heads/master
<file_sep>package com.sebas.mov_cup_america_2020_1007352431; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText etUsuario, etContra; Button boAcceder, boRegistrar; String usuario, contraseña; String nombre, contra; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etUsuario=findViewById(R.id.mainEdtUsuario); etContra=findViewById(R.id.mainEdtContr); boAcceder=findViewById(R.id.mainBtnAcceder); boRegistrar=findViewById(R.id.mainBtnRegistrarse); nombre="sebas"; contra="123"; boAcceder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (etUsuario.getText().toString().equals(nombre) && etContra.getText().toString().equals(contra)){ Toast.makeText(MainActivity.this, "Bienvenido "+nombre, Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this,Opciones.class); startActivity(i); }else { Toast.makeText(MainActivity.this, "Verificar Datos", Toast.LENGTH_SHORT).show(); } } }); boRegistrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,Registro.class); startActivity(intent); } }); } }
6c646ab7180e510bc1a7839804d52bdb5cdc1daa
[ "Java" ]
1
Java
sebastian332/MOVCUP_AMERICA_2020_1007352431
4c73d747530fb0a36bbaacc04a32d965d7246348
f77e5f9f8a7cca0ed18fdb3348b67eb136d9941c
refs/heads/master
<repo_name>Umeraftab7747/nodeJsPratice<file_sep>/model/user.js const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/Study", { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true, }); const Userdata = mongoose.model("userDB", { name: String, email: String, password: String, }); module.exports = Userdata; <file_sep>/routes/index.js var express = require("express"); var router = express.Router(); var Userdata = require("../model/user"); var Image = require("../model/image"); var multer = require("multer"); var path = require("path"); // middle ware to upload var storage = multer.diskStorage({ destination: "./public/uploads/", filename: function (req, file, cb) { cb( null, file.fieldname + "-" + Date.now() + path.extname(file.originalname) ); }, }); var upload = multer({ storage: storage }).single("upload"); // /* GET home page. */ router.get("/", function (req, res, next) { res.render("index", { title: "Express" }); }); /* GET All users. */ router.get("/Users", function (req, res, next) { Userdata.find({}) .then((user) => { res.json({ status: "200", data: user }); }) .catch((err) => { res.json({ status: "404", msg: "Internal error, please try again later", }); }); }); // signUp router.post("/signUp", function (req, res) { var data = req.body; Userdata.create({ name: data.name, email: data.email, password: <PASSWORD>, image: "abc.jpg", }) .then((user) => { res.json({ status: "200", data: user, msg: "Your account successfully created please Sign In.", }); }) .catch((err) => { res.json({ status: "404", msg: err.message }); }); }); // signIn route router.post("/signin", function (req, res) { let data = req.body; Userdata.findOne({ email: data.email, password: <PASSWORD> }) .then((user) => { console.log(user); if (user) { res.json({ status: "200", data: "sucessfull Singin" }); } else { res.json({ status: "404", msg: "User not found" }); } }) .catch((err) => { res.json({ status: "404", msg: err.message }); }); }); // Images route router.get("/image", function (req, res) { res.render("image", { title: "Express" }); }); router.post("/image", upload, function (req, res, next) { let data = req.file.filename; console.log(data); Image.create({ image: data, }) .then() .catch(); res.render("image", { title: "Express" }); }); module.exports = router;
36eb201674de538d23ada7ed033794cbfeb07b68
[ "JavaScript" ]
2
JavaScript
Umeraftab7747/nodeJsPratice
d7b22e9e8a78f64d36bd2b6e946fb043a3bc5701
46f37d7b9766655a5fbf35e9756cdf50c09330df
refs/heads/master
<file_sep>const mongoose= require("mongoose"); const Schema = mongoose.Schema({ id:String, uzytkownik:mongoose.Types.ObjectId, nazwa_uzytkownika:String, email:String, password:String, }); module.exports = mongoose.model("admini",Schema,"admini");<file_sep> module.exports = { modelka:"modelka", klient:"klient", klub:"klub", admin:"admin", };<file_sep>const express = require("express"); const router = express.Router(); const validator = require("express-validator"); const anonsValidator = require("../validators/anonsValidator"); const anonse = require("../Schemes/anonse"); const parser = require("../utils/formObjectParser"); const uzytkownicy = require("../Schemes/uzytkownicy"); const modelki = require("../Schemes/modelki"); const uslugi = require("../Schemes/uslugi"); const hash = require("../utils/hash"); const cipher = require("../utils/cipher"); const miasta = require("../Schemes/miasta"); const fetch = require("node-fetch"); const mongoose = require("mongoose"); router.get("/:identifier/:model?", async (req, res) => { const lista = await uslugi.find(); const values = req.params.identifier != "nowy" ? await anonse.findOne({ _id: cipher.decrypt(req.params.identifier.toString()) }) : {}; const identifier = req.params.model != null ? `/${req.params.identifier}/${req.params.model}` : `/${req.params.identifier}`; if (values == null) res.render("anonse_empty.pug", { uslugi: lista, identifier: identifier }); else res.render("anonse.pug", { uslugi: lista, values: values, identifier: identifier }); }); router.get("/:id", (req, res) => {}); // renderowanie ogloszenia router.post("/:identifier/:model?", anonsValidator, (req, res) => { if (!validator.validationResult(req).isEmpty()) { res.render("error.pug", { error: "Błędnie wypełniony formularz!" }); return; } if ( req.session.user == null || (req.session.account_type != "modelka" && req.session.account_type != "klub") ) { res.render("error.pug", { error: "Nie masz uprawnień do tej czynności" }); return; } else { (async () => { const dni = [ "poniedzialek", "wtorek", "sroda", "czwartek", "piatek", "sobota", "niedziela", "swieta" ]; let dniObject = {}; let id; if (req.session.account_type == "modelka") { const user = await uzytkownicy.findOne({ email: req.session.user, typ_konta: req.session.account_type }); if (user == null) { res.render("error.pug", { error: "Błąd podczas wykonywania działania. Spróbuj ponownie później" }); return; } else id = user._id; } else if (req.params.model.length != 0) id = cipher.decrypt(req.params.model); else { res.render("Error on server side, try again later"); return; } const modelka = await modelki.findOne({ uzytkownik: id }); dni.forEach(dzien => { const tmp = parser(req.body, dzien); dniObject[dzien] = Object.entries(tmp).length > 0 ? tmp : { od: 0, do: 0 }; Object.keys(req.body).forEach(entry => { if (entry.includes(dzien)) delete req.body[entry]; }); }); const obj = new Object({ ...req.body, modelka: modelka._id, godziny_pracy: { ...dniObject }, data_modyfikacji: new Date() }); if (req.params.identifier == "nowy") { anonse.create(obj, async err => { if (err) res.render("error.pug", { error: err }); else { const one = await miasta.findOne({ nazwa: req.body.adres_miasto }); if (one == null) { const link = `https://eu1.locationiq.com/v1/search.php?key=${process.env.API_KEY}&q=${req.body.adres_miasto},${req.body.adres_wojewodztwo}&format=json`; const response = await fetch(link); const json = await response.json(); miasta.create({ nazwa: req.body.adres_miasto, lat: json[0].lat, lon: json[0].lon, premium: 0 }); } res.redirect("/"); } }); } else { const anons = await anonse.findOne({ _id: cipher.decrypt(req.params.identifier), modelka: modelka._id }); delete obj._id; if (anons == null) { res.render("error.pug", { error: "Error, try again later" }); return; } Object.keys(obj).forEach(key => { anons[key] = obj[key]; }); anons.save(); res.redirect("/"); } })(); } }); module.exports = router; <file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema({ id: String, tytul: String, tresc: String, data_dodania: Date, email: String, telefon: String, telefon_2: String, strona_www: String, wlasny_lokal: String, cena_za_30: Number, cena_za_60: Number, cena_za_90: Number, cena_za_noc: Number, wyjazdy: String, koszt_dojazdu: Number, godziny_pracy: { poniedzialek: { od: Number, do: Number }, wtorek: { od: Number, do: Number }, sroda: { od: Number, do: Number }, czwartek: { od: Number, do: Number }, piatek: { od: Number, do: Number }, sobota: { od: Number, do: Number }, niedziela: { od: Number, do: Number }, swieta: { od: Number, do: Number } }, uslugi: [String], adres_miasto: String, adres_wojewodztwo: String, data_modyfikacji: Date, modelka: mongoose.Types.ObjectId }); module.exports = mongoose.model("anonse", Schema, "anonse"); <file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema({ wyroznione: Boolean, tytul: String, tresc: String, telefon: String, email: String, adres: String, pokaz_adres: Boolean, video: String }); module.exports = mongoose.model("ogloszenia", Schema, "ogloszenia"); <file_sep>const mongoose = require("mongoose"); const { MongooseAutoIncrementID } = require("mongoose-auto-increment-reworked"); const Schema = mongoose.Schema({ nazwa: String, lat: String, lon: String, wojewodztwo: String, premium: Number }); Schema.plugin(MongooseAutoIncrementID.plugin, { modelName: "miasta" }); module.exports = mongoose.model("miasta", Schema, "miasta"); <file_sep> const haversine = (start_lat,start_lon,end_lat,end_lon)=>{ const R = 6371; const toRadians = (degrees) =>{ return degrees * Math.PI/180; }; const lat1 = toRadians(start_lat); const lat2 = toRadians(end_lat); const delta_lat = toRadians(end_lat-start_lat); const delta_lon = toRadians(end_lon-start_lon); const a = Math.pow(Math.sin(delta_lat/2),2) + Math.cos(lat1)* Math.cos(lat2)* Math.pow(Math.sin(delta_lon)/2,2); const c = 2* Math.atan2(Math.sqrt(a),Math.sqrt(1-a)); const d = R*c; return Math.ceil(d); } module.exports = haversine;<file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema({ modelki: [ { modelka: mongoose.Types.ObjectId, do: Date, zasieg: String } ], ogloszenia: [ { ogloszenie: mongoose.Types.ObjectId, do: Date, zasieg: String } ] }); module.exports = mongoose.model("wyroznieni", Schema, "wyroznieni"); <file_sep>const crypto = require("crypto"); const randomstring = require("randomstring"); class cipher { constructor() { this.algorithm = "aes-256-ctr"; this.password = <PASSWORD>; } encrypt(text) { const coder = crypto.createCipher(this.algorithm, this.password); const crypted = coder.update(text, "utf-8", "hex"); return crypted + coder.final("hex"); } decrypt(text) { const decoder = crypto.createDecipher(this.algorithm, this.password); const decrypted = decoder.update(text, "hex", "utf-8"); return decrypted + decoder.final("utf-8"); } } module.exports = new cipher(); <file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema( { id:Number, nazwa:String, kraj:String, }); module.exports = mongoose.model("wojewodztwa",Schema);<file_sep>const mongoose = require("mongoose"); const { MongooseAutoIncrementID } = require("mongoose-auto-increment-reworked"); const Schema = mongoose.Schema({ id: Number, nazwa_pl: String, nazwa_eng: String, nazwa_de: String }); Schema.plugin(MongooseAutoIncrementID.plugin, { modelName: "uslugi" }); module.exports = mongoose.model("uslugi", Schema, "uslugi"); <file_sep>const express = require("express"); const router = express.Router(); const ogloszenia = require("../Schemes/ogloszenia"); router.get("/", (req, res) => { const response = ogloszenia.find(); res.render("ogloszenia.pug", { ogloszenia: response }); }); router.post("/dodaj", (req, res) => { ogloszenia.create({ ...req.body }); }); module.exports = router; <file_sep>const mongoose = require("mongoose"); const Schema = mongoose.Schema({ id: Number, nazwa: String }); module.exports = mongoose.model("kraje", Schema, "kraje"); <file_sep>const express = require("express"); const router = express.Router(); const uzytkownicy = require("../Schemes/uzytkownicy"); const panel_modelki = require("./panel/panel_modelki"); const panel_klubu = require("./panel/panel_klubu"); const anonse = require("../Schemes/anonse"); const modelki = require("../Schemes/modelki"); const cipher = require("../utils/cipher"); const uslugi = require("../Schemes/uslugi"); router.get("/:identifier?", async (req, res) => { if (req.session.user == null) { res.render("error.pug", { error: "Nie jesteś zalgowany" }); return; } if (req.session.account_type == "admin") { res.redirect("/adminPanel"); return; } const uzytkownik = await uzytkownicy.findOne({ email: req.session.user, typ_konta: req.session.account_type }); const modelkiLista = await modelki.find({ uzytkownik: uzytkownik._id }); const condition = []; modelkiLista.forEach(entry => { entry.identifier = cipher.encrypt(entry._id.toString()); condition.push(entry._id); }); const anons = condition.length > 0 ? await anonse.find({ modelka: { $in: condition } }) : {}; if (anons.length > 0) anons.forEach(one => { one.identifier = cipher.encrypt(one._id.toString()); }); res.render("panel_uzytkownika.pug", { language: req.session.language.logowanie, anonse: anons, modelki: modelkiLista, typ: req.session.account_type }); }); module.exports = router; <file_sep>const crypto = require("crypto"); module.exports = (sentence)=>{ return crypto.createHash("sha256").update(sentence).digest("hex"); }<file_sep>Projekt nad którym obecnie pracuję. Z powodu charakteru tego projektu nie mogę załączyć plików pug. Projekt w trakcie rozwoju. Uwaga!!! Przez to, że dane z bazy będą wyświetlane w panelu administratora, pola w dokumentach nazywane są w języku polskim, dlatego dla porządku nazwy zmiennych też są w języku polskim (czułem potrzebę wytłumaczenia, że normalnie używam angielskich nazw 🤣) <file_sep>const express = require("express"); const router = express.Router(); const jezyki = require("../Schemes/jezyki"); router.get("/", (req, res) => { res.send(jezyki.find()); }); router.post("/dodaj", (req, res) => { const nazwa = req.body.nazwa; if (nazwa == null) res.render("../public/error.pug", { error: "Niekompletny formularz" }); else if (jezyki.findOne({ nazwa: nazwa }) != null) res.render(("error.pug", { error: "Taki język jest już w bazie danych" })); else { jezyki.create({ nazwa: nazwa }); res.redirect("/"); } }); router.post("/:id", (req, res) => { jezyki.delete({ id: req.params.id }); }); router.get("/:id", (req, res) => { const jezyk = jezyki.findOne({ id: req.params.id }); if (jezyk == null) res.render("error.pug", { error: "Nie znaleziono takiego języka w bazie" }); else res.send(jezyk); // zmien potem na renderowanie strony jezyka }); module.exports = router; <file_sep>const { check } = require("express-validator"); module.exports = [ check("imie") .isString() .notEmpty(), check("wiek").notEmpty(), check("wzrost"), check("kolor_oczu"), check("dlugosc_wlosow"), check("kolor_wlosow"), check("orientacja"), check("owlosienie_lonowe"), check("waga"), check("biust") ]; <file_sep>const express = require("express"); const router = express.Router(); const kluby = require("../Schemes/kluby"); const modelki = require("../Schemes/modelki"); const uzytkownicy = require("../Schemes/uzytkownicy"); const admini = require("../Schemes/admini"); const weryfikacja = require("../Schemes/weryfikacja"); const accountTypes = require("../utils/accountTypes"); const mail = require("../utils/mailing"); const hash = require("../utils/hash"); const mongoose = require("mongoose"); const { check, validationResult } = require("express-validator"); const loginValidator = require("../validators/loginValidator"); const registerValidator = require("../validators/rejestracjaValidator"); const przywracanie = require("../Schemes/przywracanie_hasla"); router.get("/rejestracja/:type", (req, res) => { res.render("rejestracja.pug", { language: JSON.parse(JSON.stringify(req.session.language.logowanie)), type: req.params.type }); }); router.post("/rejestracja", registerValidator, (req, res) => { if (!validationResult(req).isEmpty()) { res.send(validationResult(req)); return; } else { if ( req.body.type != "modelka" && req.body.type != "klub" && req.body.type != "uzytkownik" ) { res.render("error.pug", { error: "Wystąpił błąd, spróbuj później" }); return; } (async () => { const one = await uzytkownicy .findOne({ email: req.body.email }) .catch(err => console.log(err)); if (one != null) { res.send("Jest taki user"); return; } else { if (req.body.haslo === req.body.haslo_powtorzenie) { const doc = await uzytkownicy.create({ email: req.body.email, haslo: req.body.haslo, typ_konta: req.body.type, punkty: 0 }); const verify = await weryfikacja.create({ link: hash(req.body.email), user: doc._id }); mail( { from: process.env.EMAIL, to: "<EMAIL>", subject: process.env.SUBJECT, html: `<a href=${process.env.DOMENA}/uzytkownicy/weryfikacja/${ req.body.type }/${hash(req.body.email)}>${process.env.DOMENA}/uzytkownicy/${ req.body.type }/${hash(req.body.email)}</a>` }, res ); } else { res.render("error.pug", { error: "Hasła nie są takie same" }); return; } } })(); } }); router.get("/weryfikacja/:id", (req, res) => { (async () => { const id = req.params.id; if (id == null) { res.render("error.js", { error: "Błąd podczas weryfikacji. Spróbuj ponownie później" }); return; } const obj = await weryfikacja.findOne({ link: id }); uzytkownicy.findOneAndUpdate( { _id: obj.user }, { $set: { konto_potwierdzone: true } }, (err, doc) => { if (err != null) { res.render("error.pug", { error: err }); return; } else { console.log(doc); } } ); })(); }); router.get("/login", (req, res) => res.render("login.pug", { language: JSON.parse(JSON.stringify(req.session.language.logowanie)) }) ); router.get("/login/:error", (req, res) => { res.render("login.pug", { error: req.params.error, language: JSON.parse(JSON.stringify(req.session.language.logowanie)) }); }); router.post("/login", loginValidator, (req, res) => { (async () => { const validationError = validationResult(req); if (!validationError.isEmpty()) { res.redirect("/uzytkownicy/login/Wypełnij formularz"); return; } const condition = { email: req.body.email, haslo: req.body.password }; let user = await uzytkownicy.findOne(condition); if (user != null) { req.session.user = req.body.email; req.session.account_type = await user.typ_konta; res.redirect(`/`); } else res.render("login.pug", { language: req.session.language.logowanie, error: "Niepoprawne dane" }); })(); }); router.get("/przywracanie", (req, res) => res.render("przywracanie.pug", { language: JSON.parse(JSON.stringify(req.session.language.logowanie)) }) ); router.post("/przywracanie", (req, res) => { if (req.body.email != null) { (async () => { const user = await uzytkownicy.findOne({ email: req.body.email }); if (user == null) { res.render("przywracanie.pug", { language: JSON.parse(JSON.stringify(req.session.language.logowanie)), error: "Nie ma takiego użytkownika" }); return; } const przywrocony = await przywracanie.create( { uzytkownik: user._id, link: hash(req.body.email) }, err => { if (err != null) res.render("error.pug", { error: "Wystąpił błąd, spróbuj ponownie później" }); else { mail( { from: process.env.EMAIL, to: "<EMAIL>", subject: process.env.SUBJECT, html: `<a href=${ process.env.DOMENA }/uzytkownicy/przywracanie/${hash(req.body.email)}>${ process.env.DOMENA }/uzytkownicy/przywracanie/${hash(req.body.email)}</a>` }, res ); } res.render("error.pug", { error: "Na twój adres email wysłaliśmy link do przywracania hasła" }); return; } ); })(); } else res.render("przywracanie.pug", { language: JSON.parse(JSON.stringify(req.session.language.logowanie)), error: "Nie wpisałeś email" }); }); router.get("/przywracanie/:id", async (req, res) => { const przywroc = await przywracanie.findOne({ link: req.params.id }); if (przywroc == null) { res.render({ error: "Nie znaleziono takiego id zapytania" }); return; } else { res.render("changePassword.pug", { id: req.params.id, language: JSON.parse(JSON.stringify(req.session.language.logowanie)) }); } }); router.post("/przywracanie/:id", (req, res) => { (async () => { const przywroc = await przywracanie.findOne({ link: req.params.id }); if (przywroc == null) { res.render("error.pug", { error: "Wystąpił błąd. Spróbuj ponownie później" }); return; } uzytkownicy.findOneAndUpdate( { _id: przywroc.uzytkownik }, { $set: { haslo: req.body.haslo } }, err => { if (err) { res.render("error.pug", { error: "Wystąpił błąd. Spróbuj ponownie później" }); return; } else przywracanie.deleteMany({ link: req.params.id }, () => { res.redirect("/"); }); } ); })(); }); router.get("/wybor", (req, res) => { res.render("wybor.pug", {}); }); module.exports = router; <file_sep>const { check } = require("express-validator"); module.exports = [ check("tytul").notEmpty(), check("tresc").notEmpty(), check("telefon").notEmpty(), check("telefon_2").optional(), check("adres_wojewodztwo") .isString() .notEmpty(), check("adres_miasto") .notEmpty() .isString(), check("wlasny_lokal").notEmpty(), check("wyjazdy") .notEmpty() .isString() ]; <file_sep>module.exports = (obj, name) => { let value = new Object(); Object.keys(obj).forEach(entry => { string = entry.replace(/[^a-zA-Z0-9]/g, ""); if (string.includes(name)) { string = string.replace(name, ""); value[string] = obj[entry]; } }); return value; }; <file_sep>const express = require("express"); const router = express.Router(); const miasta = require("../Schemes/miasta"); const path = require("path"); router.post("/dodaj", (req, res) => { const nazwa = req.body.nazwa; const nazwa_wojewodztwa = req.body.nazwa_wojewodztwa; if (nazwa == null || nazwa_wojewodztwa == null) res.render("error.pug", { error: "Niekompletny formularz" }); if ( miasta.findOne({ miasto: nazwa, wojewodztwo: { nazwa: nazwa_wojewodztwa } }) != null ) res.render("error.pug", { error: "Takie miasto już znaduje się w bazie danych!" }); miasta.create({ miasto: nazwa, wojewodztwa: { nazwa: nazwa_wojewodztwa }, premium: 0 }); }); router.get("/usun/:id", (req, res) => { miasta.remove({ id: req.params.id }); res.redirect("/"); }); module.exports = router;
bbf0ea7bdcc68c08882dbeefc737bc8c3f4c5a40
[ "JavaScript", "Markdown" ]
22
JavaScript
krymus42/currentProject
da7e6d87667140b0c1395793bf330dd97426c157
83512b44971b933b6a25b34c69f25cad33f21c76
refs/heads/master
<file_sep>package com.itheima.dbassit; import javax.sql.DataSource; import java.sql.*; /** * @Description: java类作用描述 * @Author: wangch * @CreateDate: 2019/1/4 10:33 * @Version: 1.0 */ public class DBAssit { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public int update(String sql, Object... params){ Connection conn=null; PreparedStatement ps=null; try { conn=dataSource.getConnection(); ps=conn.prepareStatement(sql); ParameterMetaData pd = ps.getParameterMetaData(); //执行参数的个数 int count = pd.getParameterCount(); if(params==null){ throw new NullPointerException("没有执行的语句"); }if(params.length!=count){ throw new RuntimeException("参数个数不一致"); } for (int i=0;i<count;i++){ ps.setObject(i+1,params[i]); } int res=ps.executeUpdate(); return res; } catch (SQLException e) { e.printStackTrace(); }finally { close(conn,ps,null); } return 0; } public void close(Connection conn, PreparedStatement ps, ResultSet res){ try { if(conn!=null){ conn.close(); } if(ps!=null){ ps.close(); } if(res!=null){ res.close(); } } catch (SQLException e) { e.printStackTrace(); } } } <file_sep>import com.itheima.dao.IAccountDao; import com.itheima.domain.Account; import com.itheima.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * @Description: java类作用描述 * @Author: wangch * @CreateDate: 2018/12/28 0:42 * @Version: 1.0 */ public class DemoTest { InputStream in=null; SqlSession sqlSession=null; IAccountDao dao=null; @Before public void init() throws Exception { in=Resources.getResourceAsStream("sqlMapperConfig.xml"); SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in); sqlSession = factory.openSession(); dao = sqlSession.getMapper(IAccountDao.class); } @After public void destory() throws IOException { sqlSession.commit(); in.close(); sqlSession.close(); } /** * 查询账户的信息 */ @Test public void testFindAll(){ List<Account> accounts = dao.findAll(); for (Account account : accounts) { System.out.println(account); } } } <file_sep>package com.itheima.service; import com.itheima.domain.Account; import java.util.List; public interface IAccountService { /** * 添加账户信息 * * @param account */ void insert(Account account); /** * 更改账户信息 * * @param account */ void update(Account account); /** * 删除账户信息 * * @param id */ void delete(Integer id); /** * 查询所有的账户信息 * * @return */ List<Account> findAll(); } <file_sep>package com.itheima.dao; import com.itheima.domain.User; /** * @Description: java类作用描述 * @Author: wangch * @CreateDate: 2019/1/2 19:10 * @Version: 1.0 */ public interface IUserDao { /** * 更新用户信息 * @param user */ void update (User user); } <file_sep>import com.itheima.dao.AccountDao; import com.itheima.dao.IUserDao; import com.itheima.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; /** * @Description: java类作用描述 * @Author: wangch * @CreateDate: 2018/12/28 0:42 * @Version: 1.0 */ public class DemoTest { InputStream in=null; SqlSession sqlSession=null; IUserDao dao=null; @Before public void init() throws Exception { in=Resources.getResourceAsStream("sqlMapperConfig.xml"); SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in); sqlSession = factory.openSession(); dao = sqlSession.getMapper(IUserDao.class); } @After public void destory() throws IOException { sqlSession.commit(); in.close(); sqlSession.close(); } /** * 更改用户信息 */ @Test public void testFindAll(){ User user=new User(); user.setId(48); user.setAddress("海南"); user.setUsername("辉少"); // user.setBirthday(new Date()); user.setSex("男"); dao.update(user); } } <file_sep>package com.itheima.dao.impl; import com.itheima.dao.IAccountDao; import com.itheima.dbassit.DBAssit; import com.itheima.domain.Account; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.sql.SQLException; import java.util.List; /** * @Description: java类作用描述 * @Author: wangch * @CreateDate: 2019/1/4 9:27 * @Version: 1.0 */ public class AccountDaoImpl implements IAccountDao { private QueryRunner runner; public void setRunner(QueryRunner runner) { this.runner = runner; } public void insert(Account account) { try { runner.update("insert account values(null,?,?)",account.getName(),account.getMoney()); } catch (SQLException e) { e.printStackTrace(); } } public void update(Account account) { try { runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId()); } catch (SQLException e) { e.printStackTrace(); } } public void delete(Integer id) { try { runner.update("delete account where id=?",id); } catch (SQLException e) { e.printStackTrace(); } } public List<Account> findAll() { try { return runner.query("select * from account",new BeanListHandler<Account>(Account.class)); } catch (SQLException e) { e.printStackTrace(); } return null; } } <file_sep>import com.itheima.dao.IUserDao; import com.itheima.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @Description: java类作用描述 * @Author: wangch * @CreateDate: 2018/12/28 0:42 * @Version: 1.0 */ public class DemoTest { InputStream in=null; SqlSession sqlSession=null; IUserDao dao=null; @Before public void init() throws Exception { in=Resources.getResourceAsStream("sqlMapperConfig.xml"); SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in); sqlSession = factory.openSession(); dao = sqlSession.getMapper(IUserDao.class); } @After public void destory() throws IOException { sqlSession.commit(); in.close(); sqlSession.close(); } @Test public void testFind(){ List<User> list = dao.findAll(); for (User user : list) { System.out.println(list); } } @Test public void update(){ User user=new User(48,"wang",new Date(),"男","河南"); dao.updateUser(user); } @Test public void testInsert(){ User user=new User(null,"wang",new Date(),"男","河南"); System.out.println("保存之前"+user); dao.insert(user); System.out.println("保存之后"+user); } @Test public void testFindbyId(){ List<Integer> list=new ArrayList<Integer>(); list.add(43); list.add(45); list.add(46); List<User> users = dao.findbyId(list); for (User user : users) { System.out.println(user); } } } <file_sep>package com.itheima.dao; import com.itheima.domain.Account; import com.itheima.domain.Role; import com.itheima.domain.User; import org.apache.ibatis.annotations.Param; import sun.security.util.Password; import java.util.List; public interface AccountDao { /** * 查询账户的用户信息 * @return */ // List<Account> findAll(); /* *//** * 查询用户包含的所有账户 * @return *//* List<User> findAll();*/ /* *//** * 查询角色所包含的用户 * @return *//* List<Role> findAll(); */ /** * 查询每个用户所参与的角色 * @return */ List<User> findAll(); void upate(User user); }
5408f8751eb92cdcd99eac0392ef379efdd49f51
[ "Java" ]
8
Java
huidashaoye/mycode
21c01676c0e275fa89074dfaffd25ade07d90255
166137f19d39d2d4bf7c63b34060ca482d3ac92d
refs/heads/master
<repo_name>liamm14/golang-analytics<file_sep>/packets/main.go package main import ( "fmt" "log" "strings" "time" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" ) var ( device = "en0" snapshotLen int32 = 1024 promiscuous = false err error timeout = 30 * time.Second handle *pcap.Handle ) func main() { // Open device handle, err = pcap.OpenLive(device, snapshotLen, promiscuous, timeout) if err != nil { log.Fatal(err) } defer handle.Close() targetIP1 := "" targetIP2 := "" targetMAC1 := "" targetMAC2 := "" packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) for packet := range packetSource.Packets() { if isIPTarget(packet, targetIP1, targetIP2) { printPacketInfo(packet) } if isMacTarget(packet, targetMAC1, targetMAC2) { printPacketInfo(packet) } } } func isMacTarget(packet gopacket.Packet, targetMAC1 string, targetMAC2 string) bool { ethernetLayer := packet.Layer(layers.LayerTypeEthernet) if ethernetLayer != nil { ethernetPacket, _ := ethernetLayer.(*layers.Ethernet) if ethernetPacket.SrcMAC.String() == targetMAC1 && ethernetPacket.DstMAC.String() == targetMAC2 { return true } if ethernetPacket.DstMAC.String() == targetMAC1 && ethernetPacket.SrcMAC.String() == targetMAC2 { return true } } return false } func isIPTarget(packet gopacket.Packet, targetIP1 string, targetIP2 string) bool { ipLayer := packet.Layer(layers.LayerTypeIPv4) if ipLayer != nil { ip, _ := ipLayer.(*layers.IPv4) if ip.SrcIP.String() == targetIP1 && ip.DstIP.String() == targetIP2 { return true } if ip.DstIP.String() == targetIP1 && ip.SrcIP.String() == targetIP2 { return true } } return false } func printPacketInfo(packet gopacket.Packet) { fmt.Println("******packet******") // Let's see if the packet is an ethernet packet ethernetLayer := packet.Layer(layers.LayerTypeEthernet) if ethernetLayer != nil { fmt.Println("Ethernet layer detected.") ethernetPacket, _ := ethernetLayer.(*layers.Ethernet) fmt.Println("Source MAC: ", ethernetPacket.SrcMAC) fmt.Println("Destination MAC: ", ethernetPacket.DstMAC) // Ethernet type is typically IPv4 but could be ARP or other fmt.Println("Ethernet type: ", ethernetPacket.EthernetType) fmt.Println() } // Let's see if the packet is IP (even though the ether type told us) ipLayer := packet.Layer(layers.LayerTypeIPv4) if ipLayer != nil { fmt.Println("IPv4 layer detected.") ip, _ := ipLayer.(*layers.IPv4) // IP layer variables: fmt.Printf("From %s to %s\n", ip.SrcIP, ip.DstIP) fmt.Println("Protocol: ", ip.Protocol) fmt.Println() } // Let's see if the packet is TCP tcpLayer := packet.Layer(layers.LayerTypeTCP) if tcpLayer != nil { fmt.Println("TCP layer detected.") tcp, _ := tcpLayer.(*layers.TCP) // TCP layer variables: fmt.Printf("From port %d to %d\n", tcp.SrcPort, tcp.DstPort) fmt.Println() } // Iterate over all layers, printing out each layer type fmt.Println("All packet layers:") for _, layer := range packet.Layers() { fmt.Println("- ", layer.LayerType()) } // When iterating through packet.Layers() above, // if it lists Payload layer then that is the same as // this applicationLayer. applicationLayer contains the payload applicationLayer := packet.ApplicationLayer() if applicationLayer != nil { fmt.Println("Application layer/Payload found.") fmt.Printf("%s\n", applicationLayer.Payload()) // Search for a string inside the payload if strings.Contains(string(applicationLayer.Payload()), "HTTP") { fmt.Println("HTTP found!") } } // Check for errors if err := packet.ErrorLayer(); err != nil { fmt.Println("Error decoding some part of the packet:", err) } } <file_sep>/twitter/main.go package main import ( "encoding/json" "fmt" "log" "os" "os/signal" "syscall" "github.com/dghubble/go-twitter/twitter" "github.com/dghubble/oauth1" ) // Config : config struct for twitter keys type Config struct { APIKEY string `json:"apiKey"` APISECRET string `json:"apiSecret"` ACCESSTOKENKEY string `json:"accessTokenKey"` ACCESSTOKENSECRET string `json:"accessTokenSecret"` } // LoadConfiguration : loads config from json file func LoadConfiguration(file string) Config { var config Config configFile, errFile := os.Open(file) defer configFile.Close() if errFile != nil { fmt.Println("Error opening file", errFile.Error()) } jsonParser := json.NewDecoder(configFile) errParse := jsonParser.Decode(&config) if errParse != nil { fmt.Println("Error opening file", errParse.Error()) } return config } func main() { configuration := LoadConfiguration("conf.json") config := oauth1.NewConfig(configuration.APIKEY, configuration.APISECRET) token := oauth1.NewToken(configuration.ACCESSTOKENKEY, configuration.ACCESSTOKENSECRET) httpClient := config.Client(oauth1.NoContext, token) // Twitter client client := twitter.NewClient(httpClient) demux := twitter.NewSwitchDemux() tweetCount := 0 // Print tweets received from stream demux.Tweet = func(tweet *twitter.Tweet) { // fmt.Println(tweet.Text) fmt.Println("tweet count:", tweetCount) tweetCount++ } params := &twitter.StreamSampleParams{ StallWarnings: twitter.Bool(true), } // Get a sample stream of tweets stream, err := client.Streams.Sample(params) // Get demux to handle stream of tweets go demux.HandleChan(stream.Messages) // Wait for SIGINT and SIGTERM (HIT CTRL-C) ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) log.Println(<-ch) log.Println(err) stream.Stop() }
bdf49279092508f86c117f6eeb6b142fb03e4560
[ "Go" ]
2
Go
liamm14/golang-analytics
f9562cc59c90320c67cf16edbdd61a1d5d06b324
c1765875636f359a6fc065272ac87204722277b0
refs/heads/master
<repo_name>HelloWOrld4625/node-someware<file_sep>/lib/waterfall.js /** * Created by HelloWOrld4625 on 2/12/15. */ var _ = require('lodash'); var async = require('async'); function makeCallback(self, iterator, last) { var callback = function () { // on error var err = _.first(arguments); if (err) return call(last, self, arguments); // get next function var next = iterator.next(); // if last if (!next) return call(last, self, arguments); var args = _.tail(arguments); async.nextTick(function () { call(next, self, args, makeCallback(self, next, last)); }); }; callback.finish = function () { var args = Array.apply(Array, arguments); args.unshift(null); return call(last, self, args); }; callback.skip = function () { // on error var skip = _.first(arguments); // get next function var next = iterator.next(); for (var i = 0; i< skip; i++) { next = next.next(); } // if last if (!next) return call(last, self, arguments); var args = _.tail(arguments); async.nextTick(function () { call(next, self, args, makeCallback(self, next, last)); }); }; return callback; } function call(func, self, args, cb) { if (cb) args.push(cb); return func.apply(self, args); } module.exports = function(functions, options) { return function () { var callback = _.last(arguments); var args = _.slice(arguments, 0, arguments.length - 1); var self = this; var start = async.iterator(functions); call(start, self, args, makeCallback(self, start, callback)); }; }; <file_sep>/test/npm-run.js var should = require('should'); describe('parallel', require('./parallel')); describe('waterfall', require('./waterfall'));<file_sep>/lib/parallel.js /** * Created by HelloWOrld4625 on 2/12/15. */ var _ = require('lodash'); var async = require('async'); function apply(self, func, args) { return function () { var argsWithCallback = _.clone(args); argsWithCallback.push(arguments[0]);; return func.apply(self, argsWithCallback); } } module.exports = function(functions, options) { return function () { var callback = _.last(arguments); var args = _.slice(arguments, 0, arguments.length - 1); var self = this; if (functions.length == 0) throw new Error('Someware need at least one function.'); if (functions[0] instanceof Function) { functions = _.map(functions, function (func) { return apply(self, func, args); }); } else if (functions[0] instanceof Object) { functions = functions[0]; functions = _.mapValues(functions, function (func) { return apply(self, func, args); }); } async.parallel(functions, callback); }; }; <file_sep>/test/parallel.js /** * Created by HelloWOrld4625 on 2/12/15. */ var should = require('should'); module.exports = function () { describe('parallel/[functions]', function () { }); var a = function (err, result) { }; var b = function asdf(err, result) { }; };
3aa0c5aec37141a31ae570158ea68cb4ae14cbbb
[ "JavaScript" ]
4
JavaScript
HelloWOrld4625/node-someware
ff1c4637374c0269d7d0183efa0e483698bf2db7
21da62799b87cac96ad20686c221eabd33e61b20
refs/heads/main
<repo_name>SuichiNagi/PHP-with-MYSQL<file_sep>/Email Validation with DB/index.php <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</title> <style> body{ font-family: sans-serif; } form{ border: 2px solid; padding: 35px 15px 0; margin: 0 auto; height: 150px; width: 250px; } input{ margin: 15px 5px 0; } input.email{ width: 230px; } input.button{ padding: 5px; } p{ color: red; } </style> </head> <body> <form action="process.php" method="POST"> Please enter a valid email address: <input class="email" type="text" name="email" value="<?= @$_SESSION['email_value']; ?>"> <input class="button" type="submit" name="submit" value="Submit"> <?= "<p>".@$_SESSION['email_error']."</p>"; ?> </form> <?php unset($_SESSION['message']); unset($_SESSION['email_error']); unset($_SESSION['email_value']); ?> </body> </html><file_sep>/Quoting Dojo/process.php <?php session_start(); require('new-connection.php'); if(isset($_POST['submit'])){ $name = $_POST['name']; $quotes = $_POST['quotes']; if($_POST['name'] == ''){ $_SESSION['name_error'] = 'Please enter your name'; } if($_POST['quotes'] == ''){ $_SESSION['quotes_error'] = 'Please add some quotes'; } if($_POST['name'] AND $_POST['quotes'] != ''){ $mysqli->query("INSERT INTO users(fname, quote, created_at) VALUES('$name', '$quotes', NOW())") or die($mysqli->error); header('Location: main.php'); exit; } header('Location: index.php'); exit; } if(isset($_POST['skip'])){ header('Location: main.php'); } ?><file_sep>/Login and Registration/connection.php <?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_DATABASE', 'login_registration'); $connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE); if($connection->connect_errno) { die("Failed to connect to MySQL: (" . $connection->connect_errno . ")" . $connection->connect_error); } //use when expecting multiple results function fetch_all($query) { $data = array(); global $connection; $result = $connection->query($query); while($row = mysqli_fetch_assoc($result)); { $data[] = $row; } return $data; } //use when expecting a single result function fetch_record($query) { global $connection; $result = $connection->query($query); return mysql_fetch_assoc($result); } //use to run INSERT/DELETE/UPDATE, queries that don't return a value function run_mysql_query($query) { global $connection; $result = $connection->query($query); return $connection->insert_id; } function escape_this_string($string) { global $connection; return $connection->real_escape_string($string); } ?><file_sep>/Login and Registration/process.php <?php session_start(); require('connection.php'); if(isset($_POST['action']) && $_POST['action'] == 'register') { //call to function register_user($_POST); //actual POST } elseif(isset($_POST['action']) && $_POST['action'] == 'login') { login_user($_POST); //actual POST } else { session_destroy(); header('location: index.php'); die(); } function register_user($post) //a parameter called post { //--------------Begin Validation Check-------------------// $_SESSION['errors'] = array(); if(empty($post['first_name'])) { $_SESSION['errors'][] = "first name can't be blank!"; } if(strlen($post['first_name']) < 2) { $_SESSION['errors'][] = "first name must be 2 character long each!"; } if(empty($post['last_name'])) { $_SESSION['errors'][] = "last name can't be blank!"; } if(strlen($post['last_name']) < 2) { $_SESSION['errors'][] = "last name must be 2 character long each!"; } if(!preg_match("/^[a-zA-Z -]*$/", $post['first_name'])){ $_SESSION['errors'][] = "no special character in first name"; } if(!preg_match("/^[a-zA-Z -]*$/", $post['last_name'])){ $_SESSION['errors'][] = "no special character in last name"; } if(strlen($post['password']) <= 8) { $_SESSION['errors'][] = "minimum length of password is 8!"; } if(empty($post['password'])) { $_SESSION['errors'][] = "password field is required!"; } if($post['password'] !== $post['confirm_password']) { $_SESSION['errors'][] = "password must match!"; } if(!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) { $_SESSION['errors'][] = "please use a valid email address!"; } //------------------End of Validation Check-----------------// if(count($_SESSION['errors']) > 0) // If I have any errors at all! { header('location: index.php'); die(); } else //insert the data into the database { $password = md5($_POST['password']); $email = escape_this_string($_POST['email']); $query = "INSERT INTO users(first_name, last_name, password, email, created_at, updated_at) VALUES('{$post['first_name']}','{$post['last_name']}','$password','$email', NOW(), NOW())"; run_mysql_query($query); $_SESSION['success_message'] = 'User successfully created!'; header('location: index.php'); die(); } } function login_user($post) //a parameter called post { $password = md5($_POST['password']); $email = escape_this_string($_POST['email']); $query = "SELECT * FROM users WHERE password = <PASSWORD>' AND email = '$email'"; $user = fetch_all($query); if(count($user) > 0) { $_SESSION['user_id'] = $user[0]['id']; $_SESSION['first_name'] = $user[0]['first_name']; $_SESSION['logged_in'] = TRUE; header('location: success.php'); } else { $_SESSION['errors'][] = "can't find user with those credentials"; header('location: index.php'); die(); } } ?><file_sep>/Email Validation with DB/success.php <?php session_start(); require('new-connection.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Success</title> <style> div{ border: 2px solid black; margin: 0 auto; text-align: center; padding: 15px; width: 550px; height: 50px; } div.failed{ background: red; } div.success{ background: rgb(106,168,78); } h1{ text-align: center; } table{ margin: 0 auto; width: 600px; padding: 15px; } td{ text-align: center; } td h4{ display: inline-block; margin-right: 20px; } .delete{ background: crimson; color: white; padding: 5px; cursor: pointer; border: 1px solid black; text-decoration: none; } </style> </head> <body> <h2><?= $_SESSION['message']; ?></h2> <h1>Email Addresses Entered</h1> <table> <?php $query = "SELECT id, email, created_at FROM users"; $query_run = mysqli_query($connection, $query); while($row = mysqli_fetch_array($query_run)) { ?> <tr> <td><h3><?= $row['email']; ?> </h3></td> <td><h4><?= $row['created_at']; ?></h4></td> <td><a href="delete.php?rn=$result[id]" class="delete">Delete</a></td><br> </tr> <?php } ?> </table> </body> </html><file_sep>/The Wall/process.php <?php session_start(); require('new-connection.php'); $_SESSION['errors'] = array(); if(isset($_POST['action']) && $_POST['action'] == 'create_message'){ $mysqli->query("INSERT INTO messages(user_id, message, created_at, updated_at) VALUES ('{$_SESSION['user_id']}', '{$_POST['message']}', NOW(), NOW())") or die ($mysqli->error); header('location: main.php'); } elseif(isset($_POST['action']) && $_POST['action'] == 'create_comment'){ $mysqli->query("INSERT INTO comments(message_id, user_id, comment, created_at, updated_at) VALUES ('{$_POST['message_id']}', '{$_SESSION['user_id']}', '{$_POST['comment']}', NOW(), NOW())") or die ($mysqli->error); header('location: main.php'); } if(isset($_POST['action']) && $_POST['action'] == 'register'){ if(empty($_POST['fname'])){ $_SESSION['errors'][] = "first name can't be blank!"; } if(empty($_POST['lname'])){ $_SESSION['errors'][] = "last name can't be blank!"; } if(!preg_match("/^[a-zA-Z -]*$/", $_POST['fname'])){ $_SESSION['errors'][] = "don't use number or special character in first name!"; } if(!preg_match("/^[a-zA-Z -]*$/", $_POST['lname'])){ $_SESSION['errors'][] = "don't use number or special character in first name!"; } if(empty($_POST['email'])){ $_SESSION['errors'][] = "email can't be blank!"; } if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { $_SESSION['errors'][] = "please use a valid email address!"; } if(empty($_POST['password'])) { $_SESSION['errors'][] = "password field is required!"; } if(strlen($_POST['password']) <= 8) { $_SESSION['errors'][] = "minimum length of password is 8!"; } if($_POST['password'] !== $_POST['confirm_password']) { $_SESSION['errors'][] = "password must match!"; } if(count($_SESSION['errors']) > 0) // If I have any errors at all! { header('location: index.php'); die(); } else //insert the data into the database { $encrypted_password = md5($_POST['password']); $mysqli->query("INSERT INTO users(first_name, last_name, email, password, created_at, updated_at) VALUES('{$_POST['fname']}','{$_POST['lname']}','{$_POST['email']}','{$encrypted_password}', NOW(), NOW())") or die ($mysqli->error); $_SESSION['success_message'] = 'User successfully created!'; header('location: index.php'); die(); } } if(isset($_POST['action']) && $_POST['action'] == 'login'){ if(empty($_POST['email'])){ $_SESSION['errors'][] = 'email required!'; } if(empty($_POST['password'])){ $_SESSION['errors'][] = 'password required!'; } header('location: index.php'); if (!empty($_POST['email']) and !empty($_POST['password'])) { $encrypted_password = md5($_POST['password']); $query = "SELECT * FROM users WHERE users.email = '{$_POST['email']}' AND users.password = '{$encrypted_<PASSWORD>}'"; $result = $mysqli->query($query); $user = $result->fetch_assoc(MYSQLI_ASSOC); if (count($user) > 0) { $_SESSION['user_id'] = $user['id']; $_SESSION['first_name'] = $user['first_name']; $_SESSION['logged_in'] = TRUE; header('location: main.php'); } else { $_SESSION['errors'][] ="Wrong email or invalid password"; header('location: index.php'); } } } ?><file_sep>/MySQL Connection/connection.php <?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); //set DB_PASS as 'root' if you're using mac define('DB_DATABASE', 'mysql'); //make sure to set your database //connect to database host $connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE); var_dump($connection); ?><file_sep>/Connecting/connection.php <?php /*--------------------BEGINNING OF THE CONNECTION PROCESS------------------*/ //define constants for db_host, db_user, db_pass, and db_database //adjust the values below to match your database settings define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); //set DB_PASS as '<PASSWORD>' if you're using mac define('DB_DATABASE', 'mysql'); //make sure to set your database //connect to database host $connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE); if($connection->connect_errno) { die("Failed to connect to MySQL: (" . $connection->connect_errno . ") " . $connection->connect_error); } /*-------------------------END OF CONNECTION PROCESS!---------------------*/ $users = $connection->query("SELECT * FROM user"); foreach($users as $user) { var_dump($user); } ?> <file_sep>/The Wall/main.php <?php session_start(); require('new-connection.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div><h1>Coding Dojo</h1> <?php echo "{$_SESSION['first_name']}"; ?><br> <?php echo "<a href='index.php'>LOG OFF!</a>" ?> </div> <h1>This is my wall!</h1> <h2>Post a message</h2> <form action="process.php" method="POST"> <input type="hidden" name="action" value="create_message"> <textarea name="message" placeholder="Post a message"></textarea> <input type="submit" value="Create a message"> </form> <?php $query = "SELECT messages.*, users.first_name, users.last_name FROM messages LEFT JOIN users ON users.id = messages.user_id ORDER BY id DESC"; $result = $mysqli->query($query); $messages = $result->fetch_all(MYSQLI_ASSOC); var_dump($messages); ?> <?php foreach($messages as $message) { ?> <h2>Message from <?= $message['first_name'] ?> <?= $message['last_name'] ?> (<?= $message['created_at'] ?>)</h2> <p><?= $message['message'] ?></p> <?php $query = "SELECT comments.*, users.first_name, users.last_name FROM comments LEFT JOIN users ON users.id = comments.user_id WHERE comments.message_id = {$message['id']}"; $result = $mysqli->query($query); $comments = $result->fetch_all(MYSQLI_ASSOC); var_dump($comments); ?> <?php foreach($comments as $comment) { ?> <h3>Comment from <?= $comment['first_name'] ?> <?= $comment['last_name'] ?> (<?= $comment['created_at'] ?>)</h3> <p><?= $comment['comment'] ?></p> <?php } ?> <h3>Post a comment</h3> <form action="process.php" method="POST"> <input type="hidden" name="action" value="create_comment"> <input type="hidden" name="message_id" value="<?php $message['id'] ?>"> <textarea name="comment" placeholder="Post a comment"></textarea> <input type="submit" value="Create a comment"> </form> <?php } ?> </body> </html><file_sep>/Email Validation with DB/new-connection.php <?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_DATABASE', 'email-verification'); $connection = new mysqli("localhost", "root", "", "email-verification"); if($connection->connect_errno) { die("Failed to connect to MySQL: (" . $connection->connect_errno . ") " . $connection->connect_error); } function run_mysql_query($query) { global $connection; $result = mysqli_query($connection, $query); if(preg_match("/insert/i", $query)) { return mysqli_insert_id($connection); } return $result; } ?><file_sep>/Quoting Dojo/main.php <?php require('new-connection.php'); $result = $mysqli->query('SELECT *, DATE_FORMAT(created_at, "%r %M %d %Y") AS formatted_date FROM users ORDER BY created_at DESC') or die($mysqli->error); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Quotes for the today</title> </head> <style> *{ margin: 0; padding: 0; box-sizing: border-box; } section{ height: 600px; width: 800px; margin: 0 auto ; padding: 20px; } section{ overflow: scroll; } h1{ text-align: center; font-size: 40px; margin-bottom: 15px; } div{ margin: 10px 0; } .quote-box{ border-bottom: 1px solid black; } h2{ margin: 15px 0; } p{ text-align: center; } </style> <body> <h1>Here are the awesome quotes!</h1> <section> <div> <?php while($output = $result->fetch_assoc()): ?> <div class="quote-box"> <h2>"<?= $output['quote']; ?>"</h2> <p>-<?= $output['fname']; ?> at <?= $output['formatted_date']; ?></p> </div> <?php endwhile; ?> </div> <?php function pre_r($array){ echo '<pre>'; print_r($array); echo '</pre>'; } ?> </section> </body> </html><file_sep>/Quoting Dojo/new-connection.php <?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_DATABASE', 'dojo-quotes'); $mysqli = new mysqli('localhost', 'root', '', 'dojo-quotes') or die(mysqli_error($mysqli)); ?><file_sep>/Quoting Dojo/index.php <?php session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dojo Quotes</title> <style> *{ padding: 0; margin: 0; box-sizing: border-box; } section{ margin: 20px auto 0; border: 1px solid black; width: 700px; height: 650px; padding: 15px; } section h1{ text-align: center; font-size: 35px; margin: 55px 0; } section form p{ font-size: 25px; display: inline; vertical-align: top; margin: 15px 0; } textarea{ border: 2px solid black; } .txtname{ border: 2px solid black; height: 30px; width: 200px; margin-bottom: 10px; } .button{ cursor: pointer; margin-top: 5px; margin-left: 190px; padding: 5px; box-shadow: 3px 3px black; border: 2px solid black; } .error{ text-align: center; color: red; } </style> </head> <body> <section> <h1>Welcome to QoutingDojo</h1> <form action="process.php" method="post"> <p>Your Name:</p> <input class="txtname" type="text" name="name"><br> <h5 class="error"><?= @$_SESSION['name_error'];?></h5></br> <p>Your Quote:</p> <textarea rows="20" cols="70" name="quotes"></textarea><br> <h5 class="error"><?= @$_SESSION['quotes_error'];?></h5></br> <input class="button" type="submit" name="submit" value="Add my quote!"> <input class="button" type="submit" name="skip" value="Skip to quotes!"></br> </form> </section> <?php unset($_SESSION['name_error']); unset($_SESSION['quotes_error']); ?> </body> </html><file_sep>/Email Validation with DB/process.php <?php session_start(); require('new-connection.php'); $query = "INSERT INTO users (email, created_at) VALUES('{$_POST['email']}', NOW())"; if(isset($_POST['submit'])) { if (empty($_POST["email"])) { $_SESSION['email_error'] = "Email is required"; } elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) { $_SESSION['email_error'] = "Invalid Email Format"; } $_SESSION['email_value'] = $_POST['email']; if ($_POST['email'] !== '' AND filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) { if(run_mysql_query($query)) { $_SESSION['message'] = "<div class='success'>The email address you entered (".$_POST['email'].") is a VALID email address! Thank you!</div>"; } else { $_SESSION['message'] = "<div class='failed'>Failed to add new email/ Email already added</div>"; } header('Location: success.php'); exit; } header('Location: index.php'); exit; } var_dump(run_mysql_query($query)); ?>
978b4d1a620d7c5962f290a18f8a03c0456b36e8
[ "PHP" ]
14
PHP
SuichiNagi/PHP-with-MYSQL
d0686b1a8573e06f3f4be444f6a40e91498587c7
b0eb4a81948b66c77adcf47d5fb0a3da77712e57
refs/heads/master
<file_sep># Arduino-Sensor-Interface <file_sep>double c1; double c2; int o1 =4; int o2 =5; int o3 =6; int o4 =7; void setup () { pinMode(2,INPUT); pinMode(3,INPUT); digitalWrite(o1,LOW); digitalWrite(o2,LOW); digitalWrite(o3,LOW); digitalWrite(o4,LOW); pinMode(o1,OUTPUT); pinMode(o2,OUTPUT); pinMode(o3,OUTPUT); pinMode(o4,OUTPUT); Serial.begin(9600); } void loop() { //c1[0] = pulseIn(2, HIGH); c1 = pulseIn(2, HIGH); c2 = pulseIn(3, HIGH); Serial.print(c1); Serial.print(" - "); Serial.println(c2); double hare = c1; if (hare > 1612) { digitalWrite (4, HIGH); } else { digitalWrite(4,LOW); } double krishna = c1; //Serial.println(krishna); if (krishna <= 1297 ) { digitalWrite (5, HIGH); } else { digitalWrite(5,LOW); } double harehare = c2; //Serial.println(harehare); if (harehare > 1790) { digitalWrite (6, HIGH); } else { digitalWrite(6,LOW); } double ram = c2; Serial.println(ram); if (ram <= 1156 ) { digitalWrite (7, HIGH); } else { digitalWrite(7,LOW); } }
900661274daefd9767e199a31c97076a7b92c2e2
[ "Markdown", "C++" ]
2
Markdown
karan1199/Arduino-Sensor-Interface
4eba5baeb5c83e1ae3baa5dcfd297f3b35319547
e9fecff7ff783b6ece42d4ee131e2cdcd1f3a446
refs/heads/master
<file_sep>package poller import ( "fmt" "os" "strconv" "strings" "golang.org/x/crypto/bcrypt" "golang.org/x/term" ) // PrintRawMetrics prints raw json from the UniFi Controller. This is currently // tied into the -j CLI arg, and is probably not very useful outside that context. func (u *UnifiPoller) PrintRawMetrics() (err error) { split := strings.SplitN(u.Flags.DumpJSON, " ", 2) filter := &Filter{Kind: split[0]} // Allows you to grab a controller other than 0 from config. if split2 := strings.Split(filter.Kind, ":"); len(split2) > 1 { filter.Kind = split2[0] filter.Unit, _ = strconv.Atoi(split2[1]) } // Used with "other" if len(split) > 1 { filter.Path = split[1] } // As of now we only have one input plugin, so target that [0]. m, err := inputs[0].RawMetrics(filter) fmt.Println(string(m)) return err } // PrintPasswordHash prints a bcrypt'd password. Useful for the web server. func (u *UnifiPoller) PrintPasswordHash() (err error) { pwd := []byte(u.Flags.HashPW) if u.Flags.HashPW == "-" { fmt.Print("Enter Password: ") pwd, err = term.ReadPassword(int(os.Stdin.Fd())) if err != nil { return fmt.Errorf("reading stdin: %w", err) } fmt.Println() // print a newline. } hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost) fmt.Println(string(hash)) return err //nolint:wrapcheck } <file_sep>package poller import ( "strings" "sync" "time" ) var ( // These are used ot keep track of loaded input plugins. inputs []*InputPlugin // nolint: gochecknoglobals inputSync sync.RWMutex // nolint: gochecknoglobals ) // Input plugins must implement this interface. type Input interface { Initialize(Logger) error // Called once on startup to initialize the plugin. Metrics(*Filter) (*Metrics, error) // Called every time new metrics are requested. Events(*Filter) (*Events, error) // This is new. RawMetrics(*Filter) ([]byte, error) } // InputPlugin describes an input plugin's consumable interface. type InputPlugin struct { Name string Config interface{} // Each config is passed into an unmarshaller later. Input } // Filter is used for metrics filters. Many fields for lots of expansion. type Filter struct { Type string Term string Name string Role string Kind string Path string Text string Unit int Pass bool Skip bool Time time.Time Dur time.Duration } // NewInput creates a metric input. This should be called by input plugins // init() functions. func NewInput(i *InputPlugin) { inputSync.Lock() defer inputSync.Unlock() if i == nil || i.Input == nil { panic("nil output or method passed to poller.NewOutput") } inputs = append(inputs, i) } // InitializeInputs runs the passed-in initializer method for each input plugin. func (u *UnifiPoller) InitializeInputs() error { inputSync.RLock() defer inputSync.RUnlock() for _, input := range inputs { // This must return, or the app locks up here. if err := input.Initialize(u); err != nil { return err } } return nil } // Events aggregates log messages (events) from one or more sources. func (u *UnifiPoller) Events(filter *Filter) (*Events, error) { inputSync.RLock() defer inputSync.RUnlock() events := Events{} for _, input := range inputs { if filter != nil && filter.Name != "" && !strings.EqualFold(input.Name, filter.Name) { continue } e, err := input.Events(filter) if err != nil { return &events, err } // Logs is the only member to extend at this time. events.Logs = append(events.Logs, e.Logs...) } return &events, nil } // Metrics aggregates all the measurements from filtered inputs and returns them. // Passing a null filter returns everything! func (u *UnifiPoller) Metrics(filter *Filter) (*Metrics, error) { inputSync.RLock() defer inputSync.RUnlock() metrics := &Metrics{} for _, input := range inputs { if filter != nil && filter.Name != "" && !strings.EqualFold(input.Name, filter.Name) { continue } m, err := input.Metrics(filter) if err != nil { return metrics, err } metrics = AppendMetrics(metrics, m) } return metrics, nil } // AppendMetrics combines the metrics from two sources. func AppendMetrics(existing *Metrics, m *Metrics) *Metrics { if existing == nil { return m } if m == nil { return existing } existing.SitesDPI = append(existing.SitesDPI, m.SitesDPI...) existing.Sites = append(existing.Sites, m.Sites...) existing.ClientsDPI = append(existing.ClientsDPI, m.ClientsDPI...) existing.RogueAPs = append(existing.RogueAPs, m.RogueAPs...) existing.Clients = append(existing.Clients, m.Clients...) existing.Devices = append(existing.Devices, m.Devices...) return existing } // Inputs allows output plugins to see the list of loaded input plugins. func (u *UnifiPoller) Inputs() (names []string) { inputSync.RLock() defer inputSync.RUnlock() for i := range inputs { names = append(names, inputs[i].Name) } return names } <file_sep>package poller import ( "fmt" "sync" ) var ( // These are used to keep track of loaded output plugins. outputs []*Output // nolint: gochecknoglobals outputSync sync.RWMutex // nolint: gochecknoglobals errNoOutputPlugins = fmt.Errorf("no output plugins imported") errAllOutputStopped = fmt.Errorf("all output plugins have stopped, or none enabled") ) // Collect is passed into output packages so they may collect metrics to output. type Collect interface { Logger Metrics(*Filter) (*Metrics, error) Events(*Filter) (*Events, error) // These get used by the webserver output plugin. Poller() Poller Inputs() []string Outputs() []string } // Output defines the output data for a metric exporter like influx or prometheus. // Output packages should call NewOutput with this struct in init(). type Output struct { Name string Config interface{} // Each config is passed into an unmarshaller later. Method func(Collect) error // Called on startup for each configured output. } // NewOutput should be called by each output package's init function. func NewOutput(o *Output) { outputSync.Lock() defer outputSync.Unlock() if o == nil || o.Method == nil { panic("nil output or method passed to poller.NewOutput") } outputs = append(outputs, o) } // Poller returns the poller config. func (u *UnifiPoller) Poller() Poller { return *u.Config.Poller } // InitializeOutputs runs all the configured output plugins. // If none exist, or they all exit an error is returned. func (u *UnifiPoller) InitializeOutputs() error { count, errChan := u.runOutputMethods() defer close(errChan) if count == 0 { return errNoOutputPlugins } // Wait for and return an error from any output plugin. for err := range errChan { if err != nil { return err } if count--; count == 0 { return errAllOutputStopped } } return nil } func (u *UnifiPoller) runOutputMethods() (int, chan error) { // Output plugin errors go into this channel. err := make(chan error) outputSync.RLock() defer outputSync.RUnlock() for _, o := range outputs { go func(o *Output) { err <- o.Method(u) // Run each output plugin }(o) } return len(outputs), err } // Outputs allows other output plugins to see the list of loaded output plugins. func (u *UnifiPoller) Outputs() (names []string) { outputSync.RLock() defer outputSync.RUnlock() for i := range outputs { names = append(names, outputs[i].Name) } return names } <file_sep>// +build windows package poller // DefaultConfFile is where to find config if --config is not prvided. const DefaultConfFile = `C:\ProgramData\unifi-poller\up.conf` // DefaultObjPath is useless in this context. Bummer. const DefaultObjPath = "PLUGINS_DO_NOT_WORK_ON_WINDOWS_SOWWWWWY" <file_sep>// +build darwin freebsd netbsd openbsd package poller // DefaultConfFile is where to find config if --config is not prvided. const DefaultConfFile = "/etc/unifi-poller/up.conf,/usr/local/etc/unifi-poller/up.conf" // DefaultObjPath is the path to look for shared object libraries (plugins). const DefaultObjPath = "/usr/local/lib/unifi-poller" <file_sep>module github.com/unpoller/poller go 1.16 require ( github.com/spf13/pflag v1.0.6-0.20201009195203-85dd5c8bc61c golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 // indirect golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b golift.io/cnfg v0.0.7 golift.io/version v0.0.2 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) <file_sep># poller ## UniFi Poller Core This module ties the inputs together with the outputs. Aggregates metrics on request. Provides CLI app and args parsing. # Ideal This library has no notion of "UniFi" or controllers, or Influx, or Prometheus. This library simply provides an input interface and an output interface. Each interface uses an `[]interface{}` type, so any type of data can be used. That is to say, you could write input and output plugins that work with, say, Cisco gear, or any other network (or even non-network) data. The existing plugins should provide ample example of how to use this library, but at some point the godoc will improve. # Features - Automatically unmarshal's plugin config structs from config file and/or env variables. - Initializes all "imported" plugins on startup. - Provides input plugins a Logger, requires an interface for Metrics and Events retrieval. - Provides Output plugins an interface to retrieve Metrics and Events, and a Logger. - Provides automatic aggregation of Metrics and Events from multiple sources. <file_sep>package poller import ( "fmt" "os" "path" "plugin" "strings" "time" "github.com/spf13/pflag" "golift.io/cnfg" "golift.io/cnfg/cnfgfile" ) const ( // AppName is the name of the application. AppName = "unpoller" // ENVConfigPrefix is the prefix appended to an env variable tag name. ENVConfigPrefix = "UP" ) // UnifiPoller contains the application startup data, and auth info for UniFi & Influx. type UnifiPoller struct { Flags *Flags *Config } // Flags represents the CLI args available and their settings. type Flags struct { ConfigFile string DumpJSON string HashPW string ShowVer bool *pflag.FlagSet } // Metrics is a type shared by the exporting and reporting packages. type Metrics struct { TS time.Time Sites []interface{} Clients []interface{} SitesDPI []interface{} ClientsDPI []interface{} Devices []interface{} RogueAPs []interface{} } // Events defines the type for log entries. type Events struct { Logs []interface{} } // Config represents the core library input data. type Config struct { *Poller `json:"poller" toml:"poller" xml:"poller" yaml:"poller"` } // Poller is the global config values. type Poller struct { Plugins []string `json:"plugins" toml:"plugins" xml:"plugin" yaml:"plugins"` Debug bool `json:"debug" toml:"debug" xml:"debug,attr" yaml:"debug"` Quiet bool `json:"quiet" toml:"quiet" xml:"quiet,attr" yaml:"quiet"` } // LoadPlugins reads-in dynamic shared libraries. // Not used very often, if at all. func (u *UnifiPoller) LoadPlugins() error { for _, p := range u.Plugins { name := strings.TrimSuffix(p, ".so") + ".so" if name == ".so" { continue // Just ignore it. uhg. } if _, err := os.Stat(name); os.IsNotExist(err) { name = path.Join(DefaultObjPath, name) } u.Logf("Loading Dynamic Plugin: %s", name) if _, err := plugin.Open(name); err != nil { return fmt.Errorf("opening plugin: %w", err) } } return nil } // ParseConfigs parses the poller config and the config for each registered output plugin. func (u *UnifiPoller) ParseConfigs() error { // Parse core config. if err := u.parseInterface(u.Config); err != nil { return err } // Load dynamic plugins. if err := u.LoadPlugins(); err != nil { return err } if err := u.parseInputs(); err != nil { return err } return u.parseOutputs() } // getFirstFile returns the first file that exists and is "reachable". func getFirstFile(files []string) (string, error) { var err error for _, f := range files { if _, err = os.Stat(f); err == nil { return f, nil } } return "", fmt.Errorf("finding file: %w", err) } // parseInterface parses the config file and environment variables into the provided interface. func (u *UnifiPoller) parseInterface(i interface{}) error { // Parse config file into provided interface. if err := cnfgfile.Unmarshal(i, u.Flags.ConfigFile); err != nil { return fmt.Errorf("cnfg unmarshal: %w", err) } // Parse environment variables into provided interface. if _, err := cnfg.UnmarshalENV(i, ENVConfigPrefix); err != nil { return fmt.Errorf("env unmarshal: %w", err) } return nil } // Parse input plugin configs. func (u *UnifiPoller) parseInputs() error { inputSync.Lock() defer inputSync.Unlock() for _, i := range inputs { if err := u.parseInterface(i.Config); err != nil { return err } } return nil } // Parse output plugin configs. func (u *UnifiPoller) parseOutputs() error { outputSync.Lock() defer outputSync.Unlock() for _, o := range outputs { if err := u.parseInterface(o.Config); err != nil { return err } } return nil } <file_sep>// +build !windows,!darwin,!freebsd package poller // DefaultConfFile is where to find config if --config is not prvided. const DefaultConfFile = "/config/unifi-poller.conf,/etc/unifi-poller/up.conf" // DefaultObjPath is the path to look for shared object libraries (plugins). const DefaultObjPath = "/usr/lib/unifi-poller" <file_sep>// Package poller provides the CLI interface to setup unifi-poller. package poller import ( "fmt" "log" "os" "strings" "github.com/spf13/pflag" "golift.io/version" ) // New returns a new poller struct. func New() *UnifiPoller { return &UnifiPoller{Config: &Config{Poller: &Poller{}}, Flags: &Flags{}} } // Start begins the application from a CLI. // Parses cli flags, parses config file, parses env vars, sets up logging, then: // - dumps a json payload OR - executes Run(). func (u *UnifiPoller) Start() error { log.SetOutput(os.Stdout) log.SetFlags(log.LstdFlags) u.Flags.Parse(os.Args[1:]) if u.Flags.ShowVer { fmt.Println(version.Print(AppName)) return nil // don't run anything else w/ version request. } if u.Flags.HashPW != "" { return u.PrintPasswordHash() } cfile, err := getFirstFile(strings.Split(u.Flags.ConfigFile, ",")) if err != nil { return err } u.Flags.ConfigFile = cfile if u.Flags.DumpJSON == "" { // do not print this when dumping JSON. u.Logf("Loading Configuration File: %s", u.Flags.ConfigFile) } // Parse config file and ENV variables. if err := u.ParseConfigs(); err != nil { return err } return u.Run() } // Parse turns CLI arguments into data structures. Called by Start() on startup. func (f *Flags) Parse(args []string) { f.FlagSet = pflag.NewFlagSet(AppName, pflag.ExitOnError) f.Usage = func() { fmt.Printf("Usage: %s [--config=/path/to/up.conf] [--version]", AppName) f.PrintDefaults() } f.StringVarP(&f.HashPW, "encrypt", "e", "", "This option bcrypts a provided string. Useful for the webserver password. Use - to be prompted.") f.StringVarP(&f.DumpJSON, "dumpjson", "j", "", "This debug option prints a json payload and exits. See man page for more info.") f.StringVarP(&f.ConfigFile, "config", "c", DefaultConfFile, "Poller config file path. Separating multiple paths with a comma will load the first config file found.") f.BoolVarP(&f.ShowVer, "version", "v", false, "Print the version and exit.") _ = f.FlagSet.Parse(args) // pflag.ExitOnError means this will never return error. } // Run picks a mode and executes the associated functions. This will do one of three things: // 1. Start the collector routine that polls unifi and reports to influx on an interval. (default) // 2. Run the collector one time and report the metrics to influxdb. (lambda) // 3. Start a web server and wait for Prometheus to poll the application for metrics. func (u *UnifiPoller) Run() error { if u.Flags.DumpJSON != "" { u.Config.Quiet = true if err := u.InitializeInputs(); err != nil { return err } return u.PrintRawMetrics() } if u.Debug { log.SetFlags(log.Lshortfile | log.Lmicroseconds | log.Ldate) u.LogDebugf("Debug Logging Enabled") } log.Printf("[INFO] UniFi Poller v%v Starting Up! PID: %d", version.Version, os.Getpid()) if err := u.InitializeInputs(); err != nil { return err } return u.InitializeOutputs() } <file_sep>package poller import ( "fmt" "log" ) // Log the command that called these commands. const callDepth = 2 // Logger is passed into input packages so they may write logs. type Logger interface { Logf(m string, v ...interface{}) LogErrorf(m string, v ...interface{}) LogDebugf(m string, v ...interface{}) } // Logf prints a log entry if quiet is false. func (u *UnifiPoller) Logf(m string, v ...interface{}) { if !u.Quiet { _ = log.Output(callDepth, fmt.Sprintf("[INFO] "+m, v...)) } } // LogDebugf prints a debug log entry if debug is true and quite is false. func (u *UnifiPoller) LogDebugf(m string, v ...interface{}) { if u.Debug && !u.Quiet { _ = log.Output(callDepth, fmt.Sprintf("[DEBUG] "+m, v...)) } } // LogErrorf prints an error log entry. func (u *UnifiPoller) LogErrorf(m string, v ...interface{}) { _ = log.Output(callDepth, fmt.Sprintf("[ERROR] "+m, v...)) }
d3bec17b0700b30cde3ef87c1b7ed7f58cc4bc90
[ "Markdown", "Go Module", "Go" ]
11
Go
unifi-poller/poller
50161c195d5e410759e84915343094af9e586769
535a307047c63c7e89e0dec21d2f24b19554669e
refs/heads/master
<repo_name>lechodiman/chat-for-dogs<file_sep>/functions/dogs-api/handler.js "use strict"; const fecth = require("node-fetch"); module.exports.hello = async event => { const res = await fetch( "https://dog.ceo/api/breeds/image/random/3" ).then(res => res.json()); console.log("hola"); return { statusCode: 200, body: JSON.stringify(res, null, 2) }; }; <file_sep>/src/App.js import "./App.css"; import React from "react"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import ChatRoom from "./components/ChatRoom"; import History from "./components/History"; import Navbar from "./components/Navbar"; import BottomNav from "./components/BottomNav"; const App = () => { return ( <Router> <Navbar></Navbar> <Switch> <Route exact path="/" component={ChatRoom}></Route> <Route exact path="/history" component={History}></Route> </Switch> <BottomNav></BottomNav> </Router> ); }; export default App; <file_sep>/src/components/Messages/Messages.js import React from "react"; import MessageItem from "./MessageItem"; import List from "@material-ui/core/List"; const Messages = ({ messages }) => { return ( <List> {messages.map((message, index) => ( <MessageItem key={index} message={message}></MessageItem> ))} </List> ); }; export default Messages; <file_sep>/src/firebase.js import firebase from "firebase/app"; import "firebase/database"; import config from "./config/firebaseConfig"; // Initialize Firebase firebase.initializeApp(config); export const db = firebase.database(); <file_sep>/.github/PULL_REQUEST_TEMPLATE.md ## Description This PR will: - ## What kind of change does this PR introduce? <!--- Go over all the following points, and put an `x` in all the boxes that apply. --> - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Code style update - [ ] Refactor - [ ] Build-related changes - [ ] Other, please describe: ## Checklist: <!--- Go over all the following points, and put an `x` in all the boxes that apply. --> - [ ] It's submitted to `dev`, **not** the `master` branch. - [ ] I have updated the documentation accordingly. - [ ] I have added tests to cover my changes. ## Notes for reviewer: <!--- Things the reviewer should know --> - <file_sep>/src/hooks/useNickname.js import { useState } from 'react'; import { db } from '../firebase'; const useNickname = () => { const [nickname, setNickname] = useState(''); const [joined, setJoined] = useState(false); const uploadNickname = e => { db.ref() .child('nicknames') .push({ nickname }); setJoined(true); }; return { nickname, setNickname, uploadNickname, joined }; }; export default useNickname; <file_sep>/src/components/Messages/MessageForm.js import React from "react"; import Avatar from "@material-ui/core/Avatar"; import Grid from "@material-ui/core/Grid"; import TextField from "@material-ui/core/TextField"; const MessageForm = ({ avatar, message, onMessageChange, onMessageSubmit }) => { return ( <Grid container justify="center" alignItems="center"> <Avatar alt="my-photo" src={avatar} /> <TextField label="Message" value={message} onChange={onMessageChange} onKeyDown={onMessageSubmit} margin="normal" /> </Grid> ); }; export default MessageForm; <file_sep>/src/hooks/useDogs.js import { useState, useEffect } from 'react'; import axios from 'axios'; const useDogs = () => { const [images, setImages] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { const fetchDogs = async () => { const res = await axios.get(`https://dog.ceo/api/breeds/image/random/3`); return res.data.message; }; setLoading(true); fetchDogs().then(dogs => { setImages(dogs); setLoading(false); }); }, []); return { images, loading }; }; export default useDogs; <file_sep>/src/components/ChatRoom.js import React, { useState, Fragment } from 'react'; import Welcome from './Welcome'; import Messages from './Messages/Messages'; import MessageForm from './Messages/MessageForm'; import Container from '@material-ui/core/Container'; import useNickname from '../hooks/useNickname'; import useMessages from '../hooks/useMessages'; import useMessage from '../hooks/useMessage'; const ChatRoom = () => { const [avatar, setAvatar] = useState(''); const { nickname, setNickname, uploadNickname, joined } = useNickname(); const { messages } = useMessages(); const { message, setMessage, saveMessage } = useMessage(); const handleNameChange = e => setNickname(e.target.value); const handleAvatarChange = avatar => setAvatar(avatar); const handleMessageChange = e => setMessage(e.target.value); const handleKeyDown = e => { const date = new Date(); const messageDoc = { sender: nickname, avatar, message, date: date.toString() }; if (e.key === 'Enter') { saveMessage(messageDoc); setMessage(''); } }; return ( <Container maxWidth="sm"> {!joined ? ( <Welcome nickname={nickname} onNicknameChange={handleNameChange} avatar={avatar} onAvatarChange={handleAvatarChange} onClick={uploadNickname} ></Welcome> ) : ( <Fragment> <Messages messages={messages}></Messages> <MessageForm avatar={avatar} message={message} onMessageChange={handleMessageChange} onMessageSubmit={handleKeyDown} ></MessageForm> </Fragment> )} </Container> ); }; export default ChatRoom; <file_sep>/README.md # Welcome to Chat for Dogs 👋 ![Version](https://img.shields.io/badge/version-0.1.0-blue.svg?cacheSeconds=2592000) [![Documentation](https://img.shields.io/badge/documentation-yes-brightgreen.svg)](https://github.com/lechodiman/chat-for-dogs#readme) [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/lechodiman/chat-for-dogs/graphs/commit-activity) > React chat app designed for dogs ### 🏠 [Homepage](https://github.com/lechodiman/chat-for-dogs) ## Install ```sh yarn ``` ## Usage ```sh yarn start ``` ## Run tests ```sh yarn test ``` ## Author 👤 **<NAME>** - Github: [@lechodiman](https://github.com/lechodiman) ## Show your support Give a ⭐️ if this project helped you! --- _This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_ <file_sep>/.github/ISSUE_TEMPLATE.md ## Environment <!--- Provide information about the environment in which this error happened--> ## Steps to Reproduce <!--- Provide a link to a live example, or an unambiguous set of steps to --> <!--- reproduce this bug. Include code to reproduce, if relevant --> 1. ## Expected Behavior <!--- Tell us what should happen --> ## Actual Behavior <!--- Tell us what happens instead --> ## Screenshots <!--- If applicable --> ## Description <!--- Provide a more detailed introduction to the issue itself, and why you consider it to be a bug -->
b45e341962fe048e94445806a033b427eb2b125a
[ "JavaScript", "Markdown" ]
11
JavaScript
lechodiman/chat-for-dogs
564c88479e496cdd6c6e800448864f5c7250ec40
03696829f0881db5117250001e04eb449083e78e
refs/heads/master
<repo_name>nishilv2/hungry_snake<file_sep>/main.py __author__ = 'lenovo' from snake_game import SnakeGame from Tkinter import * tk = Tk() def start(): snake_game = SnakeGame(tk, 500) tk.mainloop() if __name__ == "__main__": start()<file_sep>/snake_game.py __author__ = 'lenovo' from snake import Snake from random import randint import tkMessageBox from Tkinter import * from api import Api class SnakeGame(object): def __init__(self, tk, speed): self.food = (randint(0, 20), randint(0, 20)) self.speed = speed self.snake = Snake() self.tk = tk self.button = Button(tk, text="start game!", command=self.run) self.canvas = Canvas(tk, width=410, height=410, bg="black") self.button.pack() self.canvas.pack() self.tk.bind("<KeyPress-Up>", self.up_event) self.tk.bind("<KeyPress-Down>", self.down_event) self.tk.bind("<KeyPress-Right>", self.right_event) self.tk.bind("<KeyPress-Left>", self.left_event) def run(self): if self.snake.eat(self.food): eat_flag = 1 self.food = None else: eat_flag = 0 self.snake.move(eat_flag) if self.not_over(): self.canvas.delete("all") self.draw_food() self.draw_snake() self.tk.after(self.speed, self.run) else: r = tkMessageBox.showinfo("Oh,game over!") if r == "ok": sys.exit() def not_over(self): if self.is_rush_wall() or self.is_rush_self(): return 0 else: return 1 def draw_snake(self): for i in range(0, self.snake.body.__len__()): x0, y0 = Api.position_to_pix(self.snake.body[i][0], self.snake.body[i][1]) x1 = x0+10 y1 = y0+10 self.canvas.create_rectangle(x0, y0, x1, y1, fill="white", outline=None, width=0) if i != (self.snake.body.__len__()-1): x2, y2 = Api.position_to_pix(self.snake.body[i+1][0], self.snake.body[i+1][1]) x3 = (x0 + x2)/2 y3 = (y0 + y2)/2 x4 = x3+10 y4 = y3+10 self.canvas.create_rectangle(x3, y3, x4, y4, fill="white", outline=None, width=0) def change_snake_direction(self, direction): r = self.snake.change_direction(direction) if not r: print "you can't do that" def up_event(self, event): self.change_snake_direction("up") print "up" def down_event(self, event): self.change_snake_direction("down") print "down" def right_event(self, event): self.change_snake_direction("right") print "right" def left_event(self, event): self.change_snake_direction("left") print "left" def food_exist(self): if self.food is None: return 0 else: return 1 def draw_food(self): if not self.food_exist(): world = [] for i in range(0, 21): for j in range(0, 21): world.insert(-1, (i, j)) for item in self.snake.body: world.remove(item) self.food = world[randint(0, world.__len__()-1)] x0, y0 = Api.position_to_pix(self.food[0], self.food[1]) x1 = x0+10 y1 = y0+10 self.canvas.create_rectangle(x0, y0, x1, y1, fill="white", outline=None, width=0) def is_rush_wall(self): if (self.snake.body[0][0] >= 0) and (self.snake.body[0][0] <= 20): if (self.snake.body[0][1] >= 0) and (self.snake.body[0][1] <= 20): return 0 else: return 1 else: return 1 def is_rush_self(self): result = 0 for i in range(1, self.snake.body.__len__()): if self.snake.body[0] == self.snake.body[i]: result = 1 break return result<file_sep>/snake.py __author__ = 'lenovo' class Snake(object): def __init__(self): self.body = [(13, 12), (12, 12), (11, 12)] self.direction = "right" def move(self, eat_flag): head_new_x = None head_new_y = None if self.direction == "right": head_new_x = self.body[0][0]+1 head_new_y = self.body[0][1] elif self.direction == "left": head_new_x = self.body[0][0]-1 head_new_y = self.body[0][1] elif self.direction == "up": head_new_x = self.body[0][0] head_new_y = self.body[0][1]-1 elif self.direction == "down": head_new_x = self.body[0][0] head_new_y = self.body[0][1]+1 head_new = (head_new_x, head_new_y) self.body.insert(0, head_new) if not eat_flag: self.body.pop() def eat(self, food): if (self.body[0][0] == food[0]) and (self.body[0][1] == food[1]): return 1 else: return 0 def change_direction(self, direction): if direction == "right": if self.direction != "left": self.direction = direction return 1 else: return 0 elif direction == "left": if self.direction != "right": self.direction = direction return 1 else: return 0 elif direction == "up": if self.direction != "down": self.direction = direction return 1 else: return 0 elif direction == "down": if self.direction != "up": self.direction = direction return 1 else: return 0 else: return 0<file_sep>/api.py __author__ = 'lenovo' class Api(object): @staticmethod def pix_to_position(x, y): pass @staticmethod def position_to_pix(x, y): return (x*2)*10, (y*2)*10
340acd22c68f0e7f8b80358d05e67125145ff290
[ "Python" ]
4
Python
nishilv2/hungry_snake
5d03b2951c004950e88255f51f054e4a4831f1d6
821555d107d305230048f1d391790624607cff3e
refs/heads/master
<file_sep>package org.team751.commands.drivetrain; import org.team751.commands.CommandBase; /** * * @author Programmer */ public class DisableClosedLoopDrive extends CommandBase { /** * */ public DisableClosedLoopDrive() { // Use requires() here to declare subsystem dependencies requires(drivetrain); } // Called just before this Command runs the first time protected void initialize() { drivetrain.setClosedLoopEnabled(false); } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.team751.commands.drivetrain; /** * Drive the robot in special mode (slowed down) * @author <NAME> */ public class JoystickDriveSpecialMode extends JoystickDrive { protected void execute(){ double x = oi.getDriveJoystick().getX(); double y = oi.getDriveJoystick().getY(); x *= 0.6;//reduce values y *= 0.35; drivetrain.arcadeDrive(y, x); } } <file_sep>package org.team751.sensors; import edu.wpi.first.wpilibj.AnalogChannel; /** * * @author samcrow */ public class Ultrasonic extends AnalogChannel{ /** * Constructor * @param channel The analog channel */ public Ultrasonic(int channel) { super(channel); setAverageBits(10);//Set up a lot of averaging to reduce the effect of noise and voltage spikes } /** * Calculate and return the distance in inches sensed by the sensor * @return The number of inches to the nearest object detected by the sensor */ public double getDistance () { double voltage = getAverageVoltage(); double distance = voltage * 84.4489 + -3.5425; return distance; } } <file_sep>package org.team751.util.logging; import com.sun.squawk.util.MathUtils; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.DriverStationLCD.Line; import java.io.PrintStream; import java.util.Date; /** * This class handles logging and/or reporting of messages * @author <NAME> */ public class Logger { private static Logger instance; private static final PrintStream console = System.out; private static final PrintStream errorConsole = System.err; private final DriverStationLCDConsole dsConsole = new DriverStationLCDConsole(); private Config config = new Config(); private LogFile file; private Logger(){ file = new LogFile(); } /** * Log a message * @param message The information to log. This is often in the form of a * String. Otherwise, it will be converted to a String with its toString() * method. * @param level The log level that applies to this message */ public void log(Object message, LogLevel level){ String messageString = getPrefix() + getString(message); if(level.equals(LogLevel.kStatus)){ if(config.statusToConsole){ console.println(messageString); } if(config.statusToDriverStationDisplay){ dsConsole.println(messageString); } if(config.statusToLogFile){ file.println(messageString, level); } } if(level.equals(LogLevel.kDebug)){ if(config.debugToConsole){ console.println(messageString); } if(config.debugToDriverStationDisplay){ dsConsole.println(messageString); } if(config.debugToLogFile){ file.println(messageString, level); } } if(level.equals(LogLevel.kWarning)){ if(config.warningToConsole){ errorConsole.println(messageString); } if(config.warningToDriverStationDisplay){ dsConsole.println(messageString); } if(config.warningToLogFile){ file.println(messageString, level); } } if(level.equals(LogLevel.kError)){ if(config.errorToConsole){ errorConsole.println(messageString); } if(config.errorToDriverStationDisplay){ dsConsole.println(messageString); } if(config.errorToLogFile){ //not yet implemented } } } /** * Log a message * @param message The information to log. * @param level The log level that applies to this message. */ public void log(boolean message, LogLevel level){ log(String.valueOf(message), level); } /** * Log a message * @param message The information to log. * @param level The log level that applies to this message. */ public void log(char message, LogLevel level){ log(String.valueOf(message), level); } /** * Log a message * @param message The information to log. * @param level The log level that applies to this message. */ public void log(char[] message, LogLevel level){ log(String.valueOf(message), level); } /** * Log a message * @param message The information to log. * @param level The log level that applies to this message. */ public void log(double message, LogLevel level){ log(String.valueOf(message), level); } /** * Log a message * @param message The information to log. * @param level The log level that applies to this message. */ public void log(float message, LogLevel level){ log(String.valueOf(message), level); } /** * Log a message * @param message The information to log. * @param level The log level that applies to this message. */ public void log(int message, LogLevel level){ log(String.valueOf(message), level); } /** * Log a message * @param message The information to log. * @param level The log level that applies to this message. */ public void log(long message, LogLevel level){ log(String.valueOf(message), level); } /** * Get the one instance of the Logger * @return the instance */ public static Logger getInstance(){ if(instance == null){ instance = new Logger(); } return instance; } /** * Convert any Object into a String. * @param input The input Object * @return the object if it is a String, or a string representation of that object */ private String getString(Object input){ if(input instanceof String){ return (String) input; }else{ return input.toString(); } } /** * Get the log prefix, indicating the timestamp, to be prepended to each message * @return The prefix */ private String getPrefix(){ return "["+System.currentTimeMillis()+" "+ MathUtils.round(DriverStation.getInstance().getMatchTime())+"] "; } /** * Handles interface with the driver station display to use it like * a console */ private class DriverStationLCDConsole { /** The number of addressable lines on the driver station display */ private static final int kLineCount = 5; private DriverStationLCD lcd = DriverStationLCD.getInstance(); /** * An array of Strings representing the current contents of the display, * with 0 = the 2nd line from the top. The contents of the top line * are not stored. */ private String[] lines = new String[kLineCount - 1]; public DriverStationLCDConsole(){ for(int i = 0; i < lines.length; i++){ lines[i] = "";//Initialize each line as an empty string } } /** * Print a line of text onto the bottom line of the driver station display * @param line The text to print */ public void println(String line){ //Shift each existing line up lcd.println(Line.kUser2, 1, lines[0]);//Replace the top line with the contents of the line 2nd from top lcd.println(Line.kUser3, 1, lines[1]);//Replace the 2nd line with the contents of the 3d line lcd.println(Line.kUser4, 1, lines[2]);//Replace the 3d line with the contents of the 4th line lcd.println(Line.kUser5, 1, lines[3]);//Replace the 4th line with the contents of the 5th line //Print the new message on the 5th line lcd.println(Line.kUser6, 1, line); //Shift the array contents down one index (up one line) for(int i = 1; i < lines.length; i++){ lines[i-1] = lines[i]; } lines[lines.length - 1] = line;//Put the new line into the highest index in the array } } } <file_sep>package org.team751.subsystems; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.command.Subsystem; import org.team751.RobotMap; /** * Subsystem for the top segment of the nommer * @author <NAME> */ public class Nommer2Top extends Subsystem { private SpeedController topConveyor = new Victor(RobotMap.nommerTopRollerVictor); /** Ratio of power to apply to the top conveyor segment */ private static final double kConveyorPower = 1; protected void initDefaultCommand() { } /** * Move balls up */ public void feedUp() { topConveyor.set(kConveyorPower); } /** * Move balls down */ public void feedDown() { topConveyor.set(-kConveyorPower); } /** * Stop the top conveyor */ public void stop() { topConveyor.set(0); } } <file_sep># Team 751 2012 Robot Code # This code controls Team 751's 2012 competition robot. It is based on the Command-Based Robot template. The history of this repository is available at https://code.google.com/p/team751robotcode/ Everything is located in the `org.team751` package and its subpackages. More information on the command-based system is available at http://wpilib.screenstepslive.com/s/3120/m/7952 ## Files ## `Robot2012.java` contains the core functions. It does not contain much actual code. It uses the commmand system for its actual logic. `OI.java` holds the two `Joystick` objects for the two joysticks on the operator console and maps the joystick buttons to robot commands. In autonomous mode, it starts the autonomous command group. `RobotMap.java` defines the PWM, digital I/O, and analog channels that various components of the robot connect to. The subsystems directory contains subsystem classes for various robot subsystems. Each subsystem class holds motor controllers, relays, and/or sensors that its subsystem uses. The commands directory contains many commands that control the subsystem logic. They are organized in subdirectories corresponding to different robot subsystems. Of particular importance is `Autonomous.java`, which is the `CommandGroup` that defines the set of commands to execute during the autonomous period. The `sensors` and `util` directories contain utility classes for additional functions and sensors that are not in the wpilibj library. <file_sep>package org.team751.subsystems; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.command.Subsystem; import org.team751.RobotMap; /** * The subsystem for the bottom segment of the nommer, including * the intake roller * @author <NAME> */ public class Nommer2Bottom extends Subsystem { Relay intakeRoller = new Relay(RobotMap.nommerIntakeRoller); SpeedController lowerConveyor = new Victor(RobotMap.lowerNommerVictor); /** The ratio (0-1) of power to apply to the conveyor motor */ protected static final double kConveyorPower = 1; protected void initDefaultCommand() { } /** * Set the intake roller and lower conveyor to pull balls in */ public void intake() { intakeRoller.set(Relay.Value.kForward); lowerConveyor.set(kConveyorPower); } /** * Set the intake roller and lower conveyor to push balls out */ public void eject() { intakeRoller.set(Relay.Value.kReverse); lowerConveyor.set(-kConveyorPower); } /** * Stop the intake roller and lower conveyor */ public void stop() { intakeRoller.set(Relay.Value.kOff); lowerConveyor.set(0); } } <file_sep>package org.team751.commands.bridgepush; import edu.wpi.first.wpilibj.Timer; import org.team751.commands.CommandBase; /** * This command momentarily lowers the bridge mechanism. It terminates after one * cycle but does not stop the motor. This can be used with Button::whileHeld() * to lower the bridge while a button is held down. * @author <NAME> */ public class BridgePushMomentaryExtend extends CommandBase { Timer timer = new Timer(); public BridgePushMomentaryExtend() { // Use requires() here to declare subsystem dependencies requires(bridgePush); } // Called just before this Command runs the first time protected void initialize() { timer.start(); } // Called repeatedly when this Command is scheduled to run protected void execute() { if(!bridgePush.bottomLimitSwitchPressed()){ bridgePush.rotateDown(); }else{ bridgePush.stop(); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return timer.get() > 0.1; } // Called once after isFinished returns true protected void end() { bridgePush.stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { end(); } } <file_sep>package org.team751.util; import edu.wpi.first.wpilibj.Timer; /** * Makes the WPIlib timer different so that its status can be accessed. * @author <NAME> */ public class AccessibleTimer extends Timer { private boolean isRunning = false; public synchronized void start() { super.start(); isRunning = true; } public synchronized void stop() { super.stop(); isRunning = false; } public boolean isRunning(){ return isRunning; } } <file_sep>package org.team751.sensors; import edu.wpi.first.wpilibj.DigitalInput; /** * Interfaces with a limit switch. * The switch should be wired with ground to the common terminal and the digital * I/O line to the normally open terminal. * This class inverts values properly so that when the switch is pressed and * the circuit between ground and the digital input is closed, the get() function * returns true. * @author <NAME> */ public class LimitSwitch extends DigitalInput { /** * Obligatory constructor. See the DigitalInput constructor documentation. * @param channel The digital I/O channel to use */ public LimitSwitch(int channel){ super(channel); } /** * Determine if the limit switch is pressed * @return True if the limit switch is pressed, otherwise false */ public boolean get(){ return !super.get(); } } <file_sep>package org.team751; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.JoystickButton; import org.team751.commands.bridgepush.BridgePushMomentaryExtend; import org.team751.commands.bridgepush.BridgePushMomentaryRetract; import org.team751.commands.drivetrain.DisableSlowMode; import org.team751.commands.drivetrain.EnableSlowMode; import org.team751.commands.nommer2.Feed; import org.team751.commands.nommer2.NommerEject; import org.team751.commands.nommer2.NommerIntake; import org.team751.commands.shooter.*; /** * Contains structure and mappings for the operator interface.<br /> * * Shooter theory of operation: <ol> <li>Drive to the shooting position</li> * <li>Press the forward button to automatically set target speed &amp; * angle</li> <li>Start holding down the back button to turn the shooter on</li> * <li>Pull the trigger to shoot</li> <li>Release the back button to turn the * shooter off</li> </ol> */ public class OI { // Process operator interface input here. /** * The joystick used for driving */ private Joystick driveJoystick = new Joystick(1); /** * The joystick used for system operation */ private Joystick operatorJoystick = new Joystick(2);//Changed to 2 from 3 /** * Get a reference to the joystick used for driving. * * @return The joystick */ public Joystick getDriveJoystick() { return driveJoystick; } /** * Get a reference to the joystick used for system operation. * * @return The joystick */ public Joystick getOperatorJoystick() { return operatorJoystick; } //Shoot: Trigger private JoystickButton driverTrigger = new JoystickButton(driveJoystick, 1); //Power up: right side button on top private JoystickButton operator5 = new JoystickButton(operatorJoystick, 5); //Power down: left side button on top private JoystickButton operator4 = new JoystickButton(operatorJoystick, 4); //Set auto power: forward button on top private JoystickButton operator3 = new JoystickButton(operatorJoystick, 3); //Closed-loop drive enable: forward button on top private JoystickButton driver3 = new JoystickButton(driveJoystick, 3); //Closed-loop drive diable: back button on top private JoystickButton driver2 = new JoystickButton(driveJoystick, 2); //Nommer on/intake: base left side forward button private JoystickButton operator6 = new JoystickButton(operatorJoystick, 6); //Nommer off/reject: base left side back button private JoystickButton operator7 = new JoystickButton(operatorJoystick, 7); //Shooter button: back button on top (Hold down to turn shooter on, release to turn it off) private JoystickButton operator2 = new JoystickButton(operatorJoystick, 2); private JoystickButton operatorTrigger = new JoystickButton(operatorJoystick, 1); //Shooter angle controls //Shooter angle up: Base right side back button private JoystickButton operator11 = new JoystickButton(operatorJoystick, 11); //Shooter angle down: Base right side forward button private JoystickButton operator10 = new JoystickButton(operatorJoystick, 10); private JoystickButton driver6 = new JoystickButton(driveJoystick, 6); private JoystickButton driver7 = new JoystickButton(driveJoystick, 7); /** * Construct the operator interface and link buttons to commands */ public OI() { operator5.whenPressed(new ManualShooterPowerUp()); operator4.whenPressed(new ManualShooterPowerDown()); operator3.whenPressed(new AutomaticShooterSet()); driverTrigger.whileHeld(new Feed());//Right stick trigger driver3.whenPressed(new EnableSlowMode()); driver2.whenPressed(new DisableSlowMode()); operator6.whileHeld(new NommerIntake());//Left stick button 6 operator7.whileHeld(new NommerEject());//Left stick button 7 operatorTrigger.whileHeld(new Feed()); operator2.whenPressed(new ShooterOn()); operator2.whenReleased(new ShooterOff()); operator11.whileHeld(new ManualShooterAngleUp()); operator10.whileHeld(new ManualShooterAngleDown()); driver6.whileHeld(new BridgePushMomentaryExtend()); driver7.whileHeld(new BridgePushMomentaryRetract()); } } <file_sep>package org.team751.util; import edu.wpi.first.wpilibj.Relay; import java.util.Timer; import java.util.TimerTask; import org.team751.util.logging.LogLevel; import org.team751.util.logging.Logger; /** * Implements delays for reversing a Relay * @author <NAME> */ public class SlowStartRelay extends Relay { private Value lastValue = Value.kOff; private Value slowStartingValue = null; private Timer timer = new Timer(); private RelaySetTask task = new RelaySetTask(Value.kOff); /** * Mandatory single overriden constructor * @param channel */ public SlowStartRelay(int channel){ super(channel); } public void set(Value value) { if((lastValue.equals(Value.kForward) && value.equals(Value.kReverse)) || (lastValue.equals(Value.kReverse) && value.equals(Value.kForward))){ //Changing directions Logger.getInstance().log("Changing directions to "+value, LogLevel.kDebug); slowStartingValue = value; task = null; task = new RelaySetTask(value); timer.schedule(task, 500);//Schedule the thingy to be set in x miliseconds } else if(slowStartingValue != null){ //Waiting for slow start //Do nothing }else{ Logger.getInstance().log("Setting relay as usual to "+value, LogLevel.kDebug); super.set(value); } lastValue = value; } private class RelaySetTask extends TimerTask { private Value value; public RelaySetTask(Value value){ this.value = value; Logger.getInstance().log("RelaySetTask initializing to set to "+value, LogLevel.kDebug); } public void run() { superSet(value); Logger.getInstance().log("RelaySetTask setting relay to "+value, LogLevel.kDebug); slowStartingValue = null; } } /** * Sets the value in the superclass without doing timing changes * @param value */ private void superSet(Value value){ super.set(value); } }
68349d054695d863c7625e203df91d09d192071c
[ "Markdown", "Java" ]
12
Java
team751/2012-Robot-Code
b6e296986a2b7d52fcf6db0fb19f515d1ea272ac
a1eb837404637441fadf24b49f3386a5eeb3589f
refs/heads/master
<file_sep>LOGFILE=$(dirname $0)/logs/node-zk-browser.log export ZK_HOST="172.16.17.32:2181" nohup node $(dirname $0)/app.js 2>&1 >>$LOGFILE &
e2bff1ad3d0e2d910c97db78f672d2940d6a1c40
[ "Shell" ]
1
Shell
zhimei360/node-zk-browser
5d4a179aae92cf500cc45f3dba78d32c6cf171ec
9ff8864c055ff7fea4af6c89be6c84faabe87829
refs/heads/master
<repo_name>dador92/ExData_Plotting1<file_sep>/load_data.R ## load_data.R ## Loads and cleans the data from the Household Power Consumption ## data set. Since all four drawing scripts need this functionality, ## it made sense to drop this functionality into a separate script ## for reuse. ## USAGE: graphing scripts should initially load this script and call load_data() ## IMPORTANT: data set does not get loaded or reloaded unless: ## (a) data set is missing from global envrionment, or ## (b) call to load_data() has the startClean arg equal to TRUE library(curl) library(readr) library(data.table) library(dplyr) library(lubridate) ## load_data() loads the data set into a global variable called house.power ## startClean marks whether the data should be freshly downloaded and read in load_data <- function(startClean=FALSE) { # definitions zipfile <- "exdata_data_household_power_consumption.zip" datafile <- "household_power_consumption.txt" # 0. clean up the environment if (startClean) { if (file.exists(zipfile)) file.remove(zipfile) if (file.exists(datafile)) file.remove(datafile) if (exists("house.power", envir = .GlobalEnv)) rm("house.power", envir = .GlobalEnv) } # 1. download the zip file if necessary if (! file.exists(zipfile)) { sourceUrl <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip" curl_download(url=sourceUrl, destfile=zipfile, quiet=FALSE) } # 2. unzip the data file if necessary if (! file.exists(datafile)) { unzip(zipfile, exdir="./") } # 3. read in and clean up the data set if (exists("house.power", envir = .GlobalEnv)) { print("data set already loaded") } else { print("loading data set from file") # define readable column names colnames = c( "date.time", # date & time columns will get collpased "time", "global.active.pwr", "global.reactive.pwr", "voltage", "intensity", "smtr.kitchen", # kitchen with dishwasher, oven, microwave "smtr.laundry", # laundry room with washing-machine, umble-drier, refrigerator, light "smtr.hvac" # electric water-heater, air-conditioner ) # speed up fread by defining initial column classes colclasses = c( "character", # date.time "character", # time "double", # global.active.pwr "double", # global.reactive.pwr "double", # voltage "double", # intensity "numeric", # smtr.kitchen "numeric", # smtr.laundry "numeric" # smtr.hvac ) # read in the file and clean it up house.power <<- # a. read in the file fread( datafile, sep=";", col.names=colnames, colClasses=colclasses, skip=66637, # skipping up until 2007-02-01 nrows=2880, # only reading thru 2007-02-02 na.strings=c("NA", "?")) %>% # b. convert the sub-meters to integers mutate_at(c("smtr.kitchen", "smtr.laundry", "smtr.hvac"), as.integer) %>% # c. convert the strings for date & time into a usable POSIXct variable mutate(date.time = parse_date_time(paste(date.time, time), "%d/%m/%Y %T", exact=TRUE)) %>% # d. drop the time variable -- it's now in date.time select(-time) # review the structure str(house.power) } return(TRUE) }<file_sep>/plot2.R ## plot2.R ## creates and save the graphic titled plot2.png as defined by the assignment # libraries # nothing -- taken care in load_data.R # load the data set source("load_data.R") load_data() # set up the device file.plot2 <- "./plot2.png" png(file=file.plot2, width=480, height=480) # plot the graph lab.x.axis <- "Day" lab.y.axis <- "Global Active Power (kilowatts)" with(house.power, plot(date.time, global.active.pwr, type="l", xlab=lab.x.axis, ylab=lab.y.axis)) # close the device/PNG file dev.off()<file_sep>/plot3.R ## plot3.R ## creates and save the graphic titled plot3.png as defined by the assignment ## NOTE TO GRADERS: ## I have changed the legend text labels to better describe what the graph displays. ## I feel that SQL-type labels like "Sub_metering_2" inhibit analysis. ## In order to display the legend in full, I had to move the legend to the top center, ## and hide the delimiting box (which was too narrow). # libraries # nothing -- taken care in load_data.R # load the data set source("load_data.R") load_data() # set up the device file.plot3 = "./plot3.png" png(file=file.plot3, width=480, height=480) # plot the graph lab.x.axis <- "Day" lab.y.axis <- "Energy Sub Metering" with(house.power, { plot(date.time, smtr.kitchen, type="l", col="black", xlab=lab.x.axis, ylab=lab.y.axis); lines(date.time, smtr.laundry, type="l", col="red"); lines(date.time, smtr.hvac, type="l", col="blue") }) legend.full <- c("kitchen", "laundry", "hvac") legend("topright", legend=legend.full, col=c("black", "red", "blue"), lty = 1) # close the device/PNG file dev.off()<file_sep>/plot1.R ## plot1.R ## creates and save the graphic titled plot1.png as defined by the assignment # libraries # nothing -- taken care in load_data.R # load the data set source("load_data.R") load_data() # set up the device file.plot1 <- "./plot1.png" png(file=file.plot1, width=480, height=480) # plot the graph lab.x.axis <- "Global Active Power (kilowatts)" hist(house.power$global.active.pwr, main="Global Active Power", xlab=lab.x.axis, col="red") # close the device/PNG file dev.off()<file_sep>/plot4.R ## plot4.R ## creates and save the graphic titled plot4.png as defined by the assignment ## NOTE TO GRADERS: ## I have changed one of the legend text labels to better describe what the graph displays. ## I feel that SQL-type labels like "Sub_metering_2" inhibit analysis. ## In order to display the legend in full, I had to move the legend to the top center, ## and hide the delimiting box (which was too narrow). # libraries # nothing -- taken care in load_data.R # load the data set source("load_data.R") load_data() # set up the device file.plot4 <- "./plot4.png" png(file=file.plot4, width=480, height=480) # plot the graph par(mfrow = c(2, 2), mar = c(4, 4, 2, 2), oma = c(1, 1, 1, 1)) lab.x.axis <- "Day" with(house.power, { plot(date.time, global.active.pwr, type="l", xlab=lab.x.axis, ylab="Global Active Power") plot(date.time, voltage, type="l", xlab=lab.x.axis, ylab="Voltage") plot(date.time, smtr.kitchen, type="l", col="black", xlab=lab.x.axis, ylab="Energy Sub Metering") lines(date.time, smtr.laundry, type="l", col="red") lines(date.time, smtr.hvac, type="l", col="blue") legend("topright", legend=c("kitchen", "laundry", "hvac"), col=c("black", "red", "blue"), lty = 1) plot(date.time, global.reactive.pwr, type="l", xlab=lab.x.axis, ylab="Global Reactive Power") }) # close the device/PNG file dev.off()
073a07d8d37017fca46e3fd446e7248126260043
[ "R" ]
5
R
dador92/ExData_Plotting1
16632344956b06422286548af66e97288f4e2107
6b37743b1d3096720c831b72c67b53287d8cc2ec
refs/heads/master
<file_sep>// Load up necessary libraries const Discord = require("discord.js"); const fs = require("fs"); let request = require(`request`); // This is your client. Some people call it `bot`, some people call it `self`, // some might call it `cootchie`. Either way, when you see `client.something`, or `bot.something`, // this is what we're refering to. Your client. const client = new Discord.Client(); client.dexEntries = require("./entries/dexEntries.json") const pokemonList = require("./info/pokemonList.json") var pokemonArray = pokemonList.list; // Here we load the config.json file that contains our token and our prefix values. const config = require("./config.json"); // config.token contains the bot's token // config.prefix contains the message prefix. client.on("ready", () => { // This event will run if the bot starts, and logs in, successfully. console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`); // Example of changing the bot's playing game to something useful. `client.user` is what the // docs refer to as the "ClientUser". client.user.setActivity(`Serving ${client.guilds.size} servers`); }); //Currently unused client.on("guildCreate", guild => { // This event triggers when the bot joins a guild. console.log(`New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`); client.user.setActivity(`Serving ${client.guilds.size} servers`); }); //Currently unused client.on("guildDelete", guild => { // this event triggers when the bot is removed from a guild. console.log(`I have been removed from: ${guild.name} (id: ${guild.id})`); client.user.setActivity(`Serving ${client.guilds.size} servers`); }); client.on("message", async message => { // This event will run on every single message received, from any channel or DM. // It's good practice to ignore other bots. This also makes your bot ignore itself // and not get into a spam loop (we call that "botception"). if(message.author.bot) return; // Also good practice to ignore any message that does not start with our prefix, // which is set in the configuration file. if(message.content.indexOf(config.prefix) !== 0) return; // Here we separate our "command" name, and our "arguments" for the command. // e.g. if we have the message "+say Is this the real life?" , we'll get the following: // command = say // args = ["Is", "this", "the", "real", "life?"] const args = message.content.slice(config.prefix.length).trim().split('\n'); var command = args.shift().toLowerCase(); command = command.replace(/\s+/g, ''); //Add a Pokemon to the dex if(command === "addpoke") { basicInfo = args[0].split(' '); if(args[0].match(/[a-zA-Z0-9:-]+,\sthe\s[a-zA-Z0-9:-\s]+\sPokemon/) === null || args.length !== 2) { message.channel.send("Adding a Pokemon must have the following format:\n<Pokemon_Name>, the <Species_Name> Pokemon\n<Description>"); return; } var pokemon = basicInfo[0].substring(0, basicInfo[0].length-1); if(pokemonArray.indexOf(pokemon) === -1) { message.channel.send(pokemon + " is not a real Pokemon, try again in a few years"); } var species = ""; console.log(basicInfo) for(var i = 2; i < basicInfo.length-1; i++) { species = species + basicInfo[i] + " "; } client.dexEntries[pokemon] = { "number": pokemonArray.indexOf(pokemon)+1, "species":species, "description":args[1] } fs.writeFile("./entries/dexEntries.json", JSON.stringify(client.dexEntries, null, 4), err => { if(err) throw err; }) var imageFound = false; message.attachments.forEach(a => { request(a.url).pipe(fs.createWriteStream(`./images/${pokemon}.png`)); imageFound = true; message.channel.send("Pokemon saved"); }); if(!imageFound) { message.channel.send("An image of this Pokemon is needed"); } } if(command === "getpoke") { var pokemon = args[0]; if(client.dexEntries[pokemon] === undefined) { message.channel.send("This Pokemon has not been discovered") } else { var output = pokemon + ", the " + client.dexEntries[pokemon].species + "Pokemon\n" + client.dexEntries[pokemon].description message.channel.send(output, {files: [`./images/${pokemon}.png`]}) } } if(command === "deletepoke") { var pokemon = args[0]; client.dexEntries[pokemon] = undefined; fs.writeFile("./entries/dexEntries.json", JSON.stringify(client.dexEntries, null, 4), err => { if(err) throw err; }) message.channel.send(pokemon + " has been deleted") } }); client.login(config.token);
06708a9b2a3b00bacfb4b3f64ff6f4b3ca300c8e
[ "JavaScript" ]
1
JavaScript
RSN-Bran/doriot-bot
0a33daf5da38af4f56ed784fce84fbb6d513c1ad
b6d87170a5e2428cece1a0ff3812758e2cb229bd
refs/heads/master
<file_sep># 选择排序 def selectSort(arr): """ 选择排序是一种简单直观的排序算法。 它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。 以此类推,直到所有元素均排序完毕。 稳定性:不稳定 时间复杂度:O(n²) """ for i in range(len(arr)): min_index = i for j in range(i+1, len(arr)): if arr[min_index] > arr[j]: min_index = j arr[min_index], arr[i] = arr[i], arr[min_index] arr = [12, 11, 13, 5, 6] selectSort(arr) print("排序后的数组:") for data in arr: print("%d" % data) <file_sep># 二分查找 def binarySearch(arr, l, r, x): """ 从中间开始查找,如果相等则返回下标,如果中间数大于查找数,则查找左边,如果中间数小于查找数,则查找右边 时间复杂度 o(log(n)) """ if r >= l: mid = int((l+r)/2) if arr[mid] > x: return binarySearch(arr, l, mid-1, x) elif arr[mid] < x: return binarySearch(arr, mid+1, r, x) else: return mid else: return -1 # 测试数组 arr = [3, 4] x = 4 result = binarySearch(arr, 0, len(arr)-1, x) if result == -1: print("元素不在数组中") else: print("元素在数组中的索引为%d" % result) <file_sep># 希尔排序 def shellSort(arr): """ 希尔排序是插入排序的一种更高效的改进版本 先将整个待排序的记录序列分割成为若干子序列分别进行直接插入排序,待整个序列中的记录"基本有序"时,再对全体记录进行依次直接插入排序。 稳定性:不稳定 时间复杂度O (nlogn) """ n=len(arr) mid=int(n/2) while mid>0: for i in range(mid,n): temp=arr[i] j=i while j>=mid and arr[j-mid]>temp: arr[j]=arr[j-mid] j-=mid arr[j]=temp mid=int(mid/2) arr = [12, 11, 13, 5, 6] shellSort(arr) print("排序后的数组:") for data in arr: print("%d" % data)<file_sep># 归并排序 def mergerSort(arr, l, r): """ 把序列分成元素尽可能相等的两半。 把两半元素分别进行排序。 把两个有序表合并成一个。 稳定性:稳定 时间复杂度O (nlogn) """ if l < r: m = int((l+r)/2) mergerSort(arr, l, m) mergerSort(arr, m+1, r) merge(arr,l,m,r) def merge(arr, l, m, r): n1 = m-l+1 n2 = r-m # 创建临时数组 L = [0]*n1 R = [0]*n2 # 拷贝数据到临时数组 arrays L[] 和 R[] for i in range(0, n1): L[i] = arr[l+i] for j in range(0, n2): R[j] = arr[j+m+1] # 归并临时数组到 arr[l..r] i = 0 # 初始化第一个子数组的索引 j = 0 # 初始化第二个子数组的索引 k = l # 初始归并子数组的索引 while i < n1 and j < n2: if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # 拷贝 L[] 的保留元素 while i < n1: arr[k] = L[i] i += 1 k += 1 # 拷贝 R[] 的保留元素 while j < n2: arr[k] = R[j] j += 2 k += 1 arr = [12, 11, 13, 5, 6] mergerSort(arr, 0, len(arr)-1) print("排序后的数组:") for data in arr: print("%d" % data) <file_sep># 冒泡排序 def bubbleSort(arr): """ 冒泡排序也是一种简单直观的排序算法。 它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成 每一轮都会确定后面最大的数 稳定性:稳定 时间复杂度:O(n²) """ for i in range(len(arr)): for j in range(len(arr)-i-1): if arr[j]>arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j] arr = [12, 11, 13, 5, 6] bubbleSort(arr) print("排序后的数组:") for data in arr: print("%d" % data)<file_sep># 快速排序 def quickSort(arr, low, high): """ 首先任意选取一个数据(通常选用数组的第一个数)作为基准值,然后将所有比它小的数都放到它左边,所有比它大的数都放到它右边,这个过程称为一趟快速排序 然后基准值的左右两边分成两个子数组,递归排序两个数组 稳定性:不稳定 时间复杂度O (nlogn) """ if low < high: mid_index = partition(arr, low, high) quickSort(arr, low, mid_index-1) quickSort(arr, mid_index+1, high) def partition(arr, low, high): mid_index = low key = arr[mid_index] # 选第一个做为基准 while low < high: while key <= arr[high] and high > mid_index: high = high-1 arr[mid_index], arr[high] = arr[high], arr[mid_index] mid_index = high while key >= arr[low] and low < mid_index: low = low+1 arr[mid_index], arr[low] = arr[low], arr[mid_index] mid_index = low return mid_index arr = [12, 11, 13, 5, 6] quickSort(arr,0,len(arr)-1) print("排序后的数组:") for data in arr: print("%d" % data) <file_sep># 堆排序 def headSort(arr): """ 堆排序是指利用堆这种数据结构所设计的一种排序算法。 堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。 稳定性:不稳定 时间复杂度O (nlogn) """ n=len(arr) #构建一个大堆 for i in range(n,-1,-1): heapify(arr,n,i) for i in range(n-1,0,-1): arr[0],arr[i]=arr[i],arr[0] heapify(arr,i,0) def heapify(arr,n,i): largest=i l=2*i+1 r=2*i+2 if l<n and arr[i]<arr[l]: largest=l if r<n and arr[largest]<arr[r]: largest=r if largest!=i: arr[i],arr[largest]=arr[largest],arr[i] heapify(arr,n,largest) arr = [12, 11, 13, 5, 6] headSort(arr) print("排序后的数组:") for data in arr: print("%d" % data)
3cccb2cd8adae181dfa042196ef33b5ae9e8e727
[ "Python" ]
7
Python
zhuliyi10/algorithm
ea5d1c68017169396d04c5bd6b49295d4c43f769
f1c88f1793c32289e7681634b60bf3c19047c382
refs/heads/main
<repo_name>JAS0NHUANG/JH-REACT-BLOG<file_sep>/src/components/pages/NewPost/NewPost.jsx import React, {useState, useContext} from 'react'; import {useHistory} from 'react-router-dom'; import styled from 'styled-components'; import {addNewPost, getMe} from '../../../utils/WebAPI'; import {setAuthToken} from '../../../utils/utils'; import AuthContext from '../../../utils/context'; const FormInput = styled.input` text-align: left; margin: 15px; width: 80%; `; const FormTextarea = styled.textarea` text-align: left; margin: 15px; width: 80%; resize: none; height: 500px; `; const ErrorMessage = styled.div` color: #cf3476; `; export default function Login() { const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const [errorMessage, setErrorMessage] = useState(''); const history = useHistory(); function handleSubmit(event) { event.preventDefault(); setErrorMessage(''); async function runAddNewPost() { // const userData = await getMe(); // if (userData.ok === 0) return setErrorMessage(userData.message); // need auth token so no need to check user here const data = await addNewPost(event.target.title.value, event.target.body.value); if (data.ok === 0) return setErrorMessage(data.message); history.push('/'); } runAddNewPost(); } function handleChange(event) { if (event.target.name === 'title') { setTitle(event.target.value); } else { setBody(event.target.value); } } return ( <form onSubmit={handleSubmit}> <div>Add New Post</div> {errorMessage && <ErrorMessage>{errorMessage}</ErrorMessage>} <div> <label> <FormInput type="text" name="title" value={title} onChange={handleChange} placeholder="Title" /> </label> </div> <div> <label> <FormTextarea name="body" value={body} onChange={handleChange} /> </label> </div> <div> <button type="submit">Send</button> </div> </form> ); } <file_sep>/README.md # [JH-REACT-BLOG](https://jas0nhuang.github.io/JH-REACT-BLOG/dist/#/) <file_sep>/src/components/SiteRouter/SiteRouter.jsx import React from 'react'; import {HashRouter as Router, Switch, Route, Link} from 'react-router-dom'; import Home from '../pages/Home'; import Post from '../pages/Post'; import About from '../pages/About'; import Category from '../pages/Category'; import Login from '../pages/Login'; import NewPost from '../pages/NewPost'; import Register from '../pages/Register'; import Header from '../Header'; import Footer from '../Footer'; function SiteRouter() { return ( <Router> <Header /> <main> <Switch> <Route exact path="/"> <Home /> </Route> <Route exact path="/post/:id"> <Post /> </Route> <Route path="/About"> <About /> </Route> <Route path="/Category"> <Category /> </Route> <Route path="/Register"> <Register /> </Route> <Route path="/Login"> <Login /> </Route> <Route path="/NewPost"> <NewPost /> </Route> </Switch> </main> <Footer /> </Router> ); } export default SiteRouter; <file_sep>/script.sh npm init -y sudo npm install -g yarn yarn add webpack webpack-cli webpack-dev-server @babel/core @babel/preset-env babel-loader react react-dom @babel/preset-react html-webpack-plugin styled-components mkdir src touch src/index.js src/App.js src/index.html webpack.config.js .babelrc .gitignore sed -i '/scripts/a \ \ \ \ "start": "webpack serve --mode development --env development --hot",\n\ \ \ \ "build": "webpack --mode production",' package.json echo "const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: './src/index.js', output: { path: path.join(__dirname, '/dist'), filename: 'bundle.[hase].js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ] }" > webpack.config.js echo "{ 'presets': ['@babel/preset-env', '@babel/preset-react'] }" > .babelrc echo "import React from 'react' function App() { return(<h1>My React App!</h1>) } export default App" > src/App.js echo "import React from 'react' import ReactDOM from 'react-dom' import App from './App.js' ReactDOM.render(<App />, document.getElementById('root'))" > src/index.js echo "<!DOCTYPE html> <html> <div id='root'> </div> </html>" > src/index.html echo "node_modules/ *.log logs dist/" > .gitignore <file_sep>/src/components/Header/Header.jsx import React from 'react'; import styled from 'styled-components'; import {Link, useLocation} from 'react-router-dom'; const HeaderContainer = styled.header` width: 100%; position: fixed; top: 0; z-index: 99; `; const HeaderWrapper = styled.div` margin: auto; width: 100%; max-width: 1080px; height: 64px; background: #fff; display: flex; justify-content: space-between; align-items: center; `; const Logo = styled(Link)` margin: 15px; padding: 12px; font-size: 24px; border-radius: 7px; text-decoration: none; color: #222; cursor: pointer; :hover { background: #999; color: #fff; font-weight: bold; } ${props => props.$active && ` background: #999; color: #fff; font-weight: bold; `} `; const HeaderNav = styled.nav` margin: 15px; display: flex; justify-content: space-between; align-items: center; `; const HeaderNavItem = styled(Link)` margin: 10px; padding: 10px; border-radius: 5px; text-decoration: none; color: #222; cursor: pointer; :hover { background: #999; color: #fff; font-weight: bold; } ${props => props.$active && ` background: #999; color: #fff; font-weight: bold; `} `; export default function Header() { const location = useLocation(); return ( <HeaderContainer> <HeaderWrapper> <Logo to="/" $active={location.pathname === '/'}> JH </Logo> <HeaderNav> <HeaderNavItem to="/Category" $active={location.pathname === '/Category'}> Category </HeaderNavItem> <HeaderNavItem to="/About" $active={location.pathname === '/About'}> About </HeaderNavItem> </HeaderNav> </HeaderWrapper> </HeaderContainer> ); } <file_sep>/src/components/pages/Login/Login.jsx import React, {useState, useContext} from 'react'; import {useHistory} from 'react-router-dom'; import styled from 'styled-components'; import {login, getMe} from '../../../utils/WebAPI'; import {setAuthToken} from '../../../utils/utils'; import AuthContext from '../../../utils/context'; const FormInput = styled.input` text-align: left; margin: 15px; `; const ErrorMessage = styled.div` color: #cf3476; `; export default function Login() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [errorMessage, setErrorMessage] = useState(''); const history = useHistory(); const {setUser} = useContext(AuthContext); function handleSubmit(event) { event.preventDefault(); setErrorMessage(''); async function runLogin() { const data = await login(event.target.username.value, event.target.password.value); if (data.ok === 0) return setErrorMessage(data.message); setAuthToken(data.token); const userData = await getMe(); setUser(userData.data); history.push('/'); } runLogin(); } function handleChange(event) { if (event.target.name === 'username') { setUsername(event.target.value); } else { setPassword(event.target.value); } } return ( <form onSubmit={handleSubmit}> <div>Login</div> {errorMessage && <ErrorMessage>{errorMessage}</ErrorMessage>} <div> <label> Username: <input type="text" name="username" value={username} onChange={handleChange} /> </label> </div> <div> <label htmlFor="password"> Password: <input type="password" name="password" value={password} onChange={handleChange} /> </label> </div> <div> <button type="submit">Login</button> </div> </form> ); } <file_sep>/src/components/pages/About/About.jsx import React from 'react'; import styled from 'styled-components'; export default function About() { return ( <div> <h1>About</h1> <div><NAME></div> </div> ); } <file_sep>/src/components/pages/Category/Category.jsx import React from 'react'; import styled from 'styled-components'; export default function About() { return ( <div> <h1>Category</h1> <div>Under construction...</div> </div> ); }
104c89420bb81975d6879536c97eb3151650d7e7
[ "JavaScript", "Markdown", "Shell" ]
8
JavaScript
JAS0NHUANG/JH-REACT-BLOG
3ce37073695cbeccee9f313716d8b698ceaded02
269dcade49fd0bab59041a01d64d6f873de11647
refs/heads/master
<file_sep>package combos; public class Torus extends Board { // Default constructor public Torus() { super(); } // Constructor public Torus(int i, int j) { super(i,j); } @Override public void evaluateBoard(String board) { if (board.charAt(0) == '1') { // Efficiency // Converts binary representation of board into array // for easier processing int[][] arr = new int[getRows()][getCols()]; int i = 0; int j = 0; for (int x = 0; x < board.length(); x++) { if (j == getCols()) { j = 0; i++; } if (board.charAt(x) == '1') { arr[i][j] += 4; evaluateTile(i, j, arr); } else { arr[i][j] += 0; } j++; } // Evaluates whether or not the array is a determining set int detTiles = 0; for (int x = 0; x < arr.length; x++) { for (int y = 0; y < arr[0].length; y++) { if (arr[x][y] >= 3) { detTiles++; } } } // If it's a determining set, we'll add it to our ArrayList of // minimum determining sets which we can access using the get // method found in the abstract superclass Board if (detTiles == getBoardSize()) { addMinSet(board.toString()); } } } // Recursive method to evaluate tiles public void evaluateTile(int i, int j, int[][] arr) { if (j <= getCols() - 2) { // east arr[i][j + 1] += 1; if (arr[i][j + 1] == 3) { evaluateTile(i, j + 1, arr); } } else if (j + 1 == getCols()) { arr[i][0] += 1; if (arr[i][0] == 3) { evaluateTile(i, 0, arr); } } if (j > 0) { // west arr[i][j - 1] += 1; if (arr[i][j - 1] == 3) { evaluateTile(i, j - 1, arr); } } else if (j == 0) { arr[i][getCols() - 1] += 1; if (arr[i][getCols() - 1] == 3) { evaluateTile(i, getCols() - 1, arr); } } if (i <= getRows() - 2) { // south arr[i + 1][j] += 1; if (arr[i + 1][j] == 3) { evaluateTile(i + 1, j, arr); } } else if (i + 1 == getRows()) { arr[0][j] += 1; if (arr[0][j] == 3) { evaluateTile(0, j, arr); } } if (i > 0) { // north arr[i - 1][j] += 1; if (arr[i - 1][j] == 3) { evaluateTile(i - 1, j, arr); } } else if (i == 0) { arr[getRows() -1][j] += 1; if (arr[getRows() - 1][j] == 3) { evaluateTile(getRows() - 1, j, arr); } } } @Override int findMinSetSize() { if (getRows() > getCols()) { return getRows() - 1; } else { return getCols() - 1; } } } <file_sep># Minimum Determining Set Algorithm This is a Java implementation of a minimum determining set algorithm developed for knot theory research. Can compute minimum determining sets on both torus and planar mosaic boards, as well as evaluate a binary string representation of a tiled board.
4e68129f14af694d32b3bdf8f9d70ce4e7ef96b6
[ "Markdown", "Java" ]
2
Java
eden-ski/minimum-determining-set-java
4c96fa8abbdf07de31cff1f35191b414dcddfcd6
3668b30db945233130414ff066e41c72deb9199f
refs/heads/master
<file_sep>/// <reference path="./tsd.d.ts" /> import {bootstrap} from 'angular2/platform/browser'; import {AppComponent} from './app.component'; var electron = require("electron"); var ipcRenderer = electron.ipcRenderer; bootstrap(AppComponent);<file_sep>'use strict'; module.exports = function (grunt) { grunt.initConfig({ mochaTest: { test: { options: { reporter: 'spec', quiet: false }, src: ['bin/test/**/*.js'] } }, copy: { client: { files: [ { expand: true, flatten: true, src: './src/client/static/*', dest: './app/' } ] } } }); // These plugins provide necessary tasks grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.registerTask('typescript-server', 'compile app and tests', function() { var done = this.async(); grunt.util.spawn({ grunt: false, cmd: "tsc", args: ["-p", "./src/server", "-sourcemap"], opts: { stdio: "inherit" } }, function(err, result, stderr) { grunt.log.ok('successfully transpiled typescript (server)!'); done(); }); }); grunt.registerTask('typescript-client', 'compile app and tests', function() { var done = this.async(); grunt.util.spawn({ grunt: false, cmd: "tsc", args: ["-p", "./src/client", "-sourcemap"], opts: { stdio: "inherit" } }, function(err, result, stderr) { grunt.log.ok('successfully transpiled typescript (client)!'); done(); }); }); // Task aliases grunt.registerTask('test', ['typescript', 'mochaTest']); // Default task grunt.registerTask('default', ['test']); grunt.registerTask('build', ['copy:client', 'typescript-server', 'typescript-client']); };<file_sep>/// <reference path="../../node_modules/angular2/typings/tsd.d.ts" /> /// <reference path="../../typings/github-electron/github-electron.d.ts" /> /// <reference path="../../node_modules/angular2/typings/node/node.d.ts" /> <file_sep>import {Component} from 'angular2/core'; var electron = require("electron"); var ipcRenderer = electron.ipcRenderer; @Component({ selector: 'my-app', template: '<h1>My First Angular 2 App {{title}}</h1>' }) export class AppComponent { public title = "custom title"; constructor(){ var response = ipcRenderer.sendSync('channel', 'ping'); console.log(response); } }<file_sep>## setup * npm install * cd src/server && tsd install * npm start ## deploy * download prebuilt electron binary * node_modules -> resources/ * client/ server/ index.html package.json -> resources/default_app/ ## Backend Debugging (VSCode only) * see launch.json && tasks.json insode .vscode * just hit F5 * breakpoints do only work in .js files but breakpoint are mapped to the source files (ts) ## Frontend Debugging * use built in Electron / Chromium debugger<file_sep>/// <reference path="./tsd.d.ts" /> 'use strict'; import * as electron from "electron"; const app = electron.app; const BrowserWindow = electron.BrowserWindow; const ipcMain = electron.ipcMain; var mainWindow: Electron.BrowserWindow = null; app.on("window-all-closed", () => { if(process.platform != "darwin"){ app.quit(); } }); app.on("ready", () => { mainWindow = new BrowserWindow({width: 1280, height: 786}); mainWindow.loadURL('file://' + __dirname + '/../index.html'); // Open the DevTools. mainWindow.webContents.openDevTools(); ipcMain.on('channel', (event, arg) => { event.returnValue = 'pong'; }); });
6a90364176d3b02ef602b8cf840c33ab2aa50680
[ "JavaScript", "TypeScript", "Markdown" ]
6
TypeScript
Finkes/electron-angular2-typescript
1d507b765b1849083489cc299197aa853bbcdaf0
6a8bb599d1dd4dd6a862e32053334f06676c0281
refs/heads/master
<repo_name>GreenJ97/IBM-SpeechToText<file_sep>/Assets/SpeechToTextScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using IBM.Watson.SpeechToText.V1; using IBM.Cloud.SDK; using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Authentication.Iam; using IBM.Cloud.SDK.Utilities; using IBM.Cloud.SDK.DataTypes; public class SpeechToTextScript : MonoBehaviour { #region SET THESE VARIABLES IN THE INSPECTOR [Tooltip("The services URL (optional)")] [SerializeField] private string _serviceUrl; [Header("IAM Authentication")] [Tooltip("The IAM apikey")] [SerializeField] private string _iamApikey; [Header("Parameters")] [Tooltip("The Model to use. This deafaults to en-US_BroadbandModel")] [SerializeField] private string _recognizeModel; //For the Recognize models list go to: https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models #endregion private int _recordingRoutine = 0; private string _microphoneID = null; private AudioClip _recording = null; private int _recordingBufferSize = 1; private int _recordingHZ = 22050; private SpeechToTextService _service; private string[] _keywordsSetHere; private string _currentKeyword; private string _finalTranscript; void Start() { LogSystem.InstallDefaultReactors(); Runnable.Run(CreateService()); } private IEnumerator CreateService() { if (string.IsNullOrEmpty(_iamApikey)) { throw new IBMException("Please provide IAM apikey for this service"); } IamAuthenticator authenticator = new IamAuthenticator(apikey: _iamApikey); while (!authenticator.CanAuthenticate()) yield return null; _service = new SpeechToTextService(authenticator); if (!string.IsNullOrEmpty(_serviceUrl)) { _service.SetServiceUrl(_serviceUrl); } Active = true; StartRecording(); } public bool Active { get { return _service.IsListening; } set { if (value && !_service.IsListening) { _service.RecognizeModel = (string.IsNullOrEmpty(_recognizeModel) ? "en-US_BroadbandModel" : _recognizeModel); _service.DetectSilence = true; _service.EnableWordConfidence = true; _service.SilenceThreshold = 0.01f; _service.MaxAlternatives = 1; _service.EnableInterimResults = true; _service.OnError = OnError; _service.InactivityTimeout = -1; _service.WordAlternativesThreshold = null; _service.EndOfPhraseSilenceTime = null; _service.Keywords = _keywordsSetHere; _service.KeywordsThreshold = 0.01f; _service.StartListening(OnRecognize, OnRecognizeSpeaker); } else if (!value && _service.IsListening) { _service.StopListening(); } } } private void StartRecording() { if (_recordingRoutine == 0) { UnityObjectUtil.StartDestroyQueue(); _recordingRoutine = Runnable.Run(RecordingHandler()); } } private void StopRecording() { if (_recordingRoutine != 0) { Microphone.End(_microphoneID); Runnable.Stop(_recordingRoutine); _recordingRoutine = 0; } } private void OnError(string error) { Active = false; Log.Debug("SpeechToTextScript.OnError()", "Error!{0}", error); } private IEnumerator RecordingHandler() { Log.Debug("SpeechToTextScript.RecordingHandler()", "devices: {0}", Microphone.devices); _recording = Microphone.Start(_microphoneID, true, _recordingBufferSize, _recordingHZ); yield return null; if (_recording == null) { StopRecording(); yield break; } bool bFirstBlock = true; int midPoint = _recording.samples / 2; float[] samples = null; while (_recordingRoutine != 0 && _recording != null) { int writePos = Microphone.GetPosition(_microphoneID); if (writePos > _recording.samples || !Microphone.IsRecording(_microphoneID)) { Log.Error("SpeechToTextScript.RecordingHandler()", "Microphone Disconnected"); StopRecording(); yield break; } if ((bFirstBlock && writePos >= midPoint) || (!bFirstBlock && writePos < midPoint)) { samples = new float[midPoint]; _recording.GetData(samples, bFirstBlock ? 0 : midPoint); AudioData record = new AudioData(); record.MaxLevel = Mathf.Max(Mathf.Abs(Mathf.Min(samples)), Mathf.Max(samples)); record.Clip = AudioClip.Create("Recording", midPoint, _recording.channels, _recordingHZ, false); record.Clip.SetData(samples, 0); _service.OnListen(record); bFirstBlock = !bFirstBlock; } else { int remaining = bFirstBlock ? (midPoint - writePos) : (_recording.samples - writePos); float timeRemaining = (float)remaining / (float)_recordingHZ; yield return new WaitForSeconds(timeRemaining); } } yield break; } private void OnRecognize(SpeechRecognitionEvent result) { if (result != null && result.results.Length > 0) { foreach (var res in result.results) { foreach (var alt in res.alternatives) { string text = string.Format("{0}", alt.transcript); Log.Debug("SpeechtoTextScript.OnRecognize()", text); _finalTranscript = text; } if (res.keywords_result != null && res.keywords_result.keyword != null) { foreach (var keyword in res.keywords_result.keyword) { string text = string.Format("{0}", keyword.normalized_text); Log.Debug("SpeechtoTextScript.OnRecognize()", text + " Keyword Detected"); _currentKeyword = text; } } } } } private void OnRecognizeSpeaker(SpeakerRecognitionEvent result) { //if (result != null) //{ // foreach (SpeakerLabelsResult labelResult in result.speaker_labels) // { // Log.Debug("SpeechtoTextScript.OnRecognizeSpeaker()", string.Format("speaker result: {0} | confidence: {3} | from: {1} | to: {2}", labelResult.speaker, labelResult.from, labelResult.to, labelResult.confidence)); // } //} } public void SetKeywords(string[] theKeywords) { _keywordsSetHere = theKeywords; } public string GetCurrentKeyword() { return _currentKeyword; } public string GetFinalTranscript() { return _finalTranscript; } } //Was in OnRecognize //if (result != null && result.results.Length > 0) //{ // foreach (var res in result.results) // { //foreach (var alt in res.alternatives) //{ // string text = string.Format("{0}, {1}\n", alt.transcript, res.final/* ? "Final" : "Interim", alt.confidence*/); // Log.Debug("SpeechtoTextScript.OnRecognize()", text); //} //if (res.keywords_result != null && res.keywords_result.keyword != null) //{ // foreach (var keyword in res.keywords_result.keyword) // { // Log.Debug("SpeechtoTextScript.OnRecognize()", "keyword: {0}, confidence: {1}, start time: {2}, end time: {3}", keyword.normalized_text, keyword.confidence, keyword.start_time, keyword.end_time); // } //} //if (res.word_alternatives != null) //{ // foreach (var wordAlternative in res.word_alternatives) // { // Log.Debug("SpeechtoTextScript.OnRecognize()", "Word alternatives found. Start time: {0} | EndTime: {1}", wordAlternative.start_time, wordAlternative.end_time); // foreach (var alternative in wordAlternative.alternatives) // Log.Debug("SpeechtoTextScript.OnRecognize()", "\t word: {0} | confidence: {1}", alternative.word, alternative.confidence); // } //} //} // }<file_sep>/Assets/ColorChangeScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ColorChangeScript : MonoBehaviour { public GameObject STT; private SpeechToTextScript _theSpeechToText; private Renderer _renderer; private string finalTranscript; private string[] keywordStrings; private string theActiveKeyword; // Start is called before the first frame update void Start() { _theSpeechToText = STT.GetComponent<SpeechToTextScript>(); _renderer = this.GetComponent<Renderer>(); keywordStrings = new string[3] { "blue", "yellow", "red" }; _theSpeechToText.SetKeywords(keywordStrings); } // Update is called once per frame void Update() { CheckColour(); } public void CheckColour() { theActiveKeyword = _theSpeechToText.GetCurrentKeyword(); if(string.Equals(theActiveKeyword, keywordStrings[0])) { _renderer.material.SetColor("_Color", Color.blue); } if(string.Equals(theActiveKeyword, keywordStrings[1])) { _renderer.material.SetColor("_Color", Color.yellow); } if(string.Equals(theActiveKeyword, keywordStrings[2])) { _renderer.material.SetColor("_Color", Color.red); } } //public void CheckColour() //{ // finalTranscript = _theSpeechToText.GetFinalTranscript(); // if (string.Equals(finalTranscript, "blue ")) // { // _renderer.material.SetColor("_Color", Color.blue); // } // if (string.Equals(finalTranscript, "yellow ")) // { // _renderer.material.SetColor("_Color", Color.yellow); // } // if (string.Equals(finalTranscript, "red ")) // { // _renderer.material.SetColor("_Color", Color.red); // } //} }
68a5e0e93ca4f5e4a5c3b21a77b41fb6990eb689
[ "C#" ]
2
C#
GreenJ97/IBM-SpeechToText
ac14ca41ab3de4119c648f3dabae466db2706498
e1103669ac59ca3ced1f09f0e363d0502d23cd10
refs/heads/master
<repo_name>Kara9125/Control-Flow-Lab<file_sep>/login.js var userLogin = { userName: "Kara", password: "<PASSWORD>" } var password; for (var i = 0; i < 3; i++) { password = prompt("Enter password for " + userLogin.userName); if (password === userLogin.password) { console.log("That is the correct password!"); break; } else { console.log("That is the wrong password! Try again!"); if (i === 2) { alert("No more password attempts!"); } } }
079de3080001c4375a76e9268923d23116a70d75
[ "JavaScript" ]
1
JavaScript
Kara9125/Control-Flow-Lab
c0033ba40f9a08d0e8fbf1a6d64233ac54bfd090
66b99c9b193b470a32154128058c06796583a447
refs/heads/main
<file_sep>using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using RestSharp; using System; using System.Collections.Generic; using System.Net; using System.Threading; using UserBugredApi.Helpers; using UserBugredApi.Models; namespace UserBugredApi { class CreateCompanyTest { RequestHelper requestUrl; [SetUp] public void Setup() { requestUrl = new RequestHelper("http://users.bugred.ru/tasks/rest/createcompany"); } [Test] public void CreateCompanyValid() { // register new company owner DoRegister registerOwnerData = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = Utils.GetNameRandom() }; Thread.Sleep(500); Utils.RegisterUserByEmail(registerOwnerData); // register new user1 for company DoRegister registerUser1 = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = Utils.GetNameRandom() }; Thread.Sleep(500); Utils.RegisterUserByEmail(registerUser1); // register new user2 for company DoRegister registerUser2 = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = Utils.GetNameRandom() }; Thread.Sleep(500); Utils.RegisterUserByEmail(registerUser2); CreateCompanyInput companyInput = new CreateCompanyInput() { CompanyName = Utils.GetNameRandom(), CompanyType = "ООО", CompanyUsers = new List<string>() { registerUser1.email, registerUser2.email }, EmailOwner = registerOwnerData.email }; var postDataJson = JsonConvert.SerializeObject(companyInput); IRestResponse response = requestUrl.SendPostRequest(postDataJson); CreateCompanyOutput companyOutput = JsonConvert.DeserializeObject<CreateCompanyOutput>(response.Content); Assert.AreEqual("success", companyOutput.StatusType); Assert.AreEqual(companyInput.CompanyType, companyOutput.companyData.Type); Assert.AreEqual(companyInput.CompanyName, companyOutput.companyData.Name); Assert.AreEqual(companyInput.CompanyUsers, companyOutput.companyData.Users); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } [TestCase ("<EMAIL>")] public void CreateCompanyInvalidOwner(string ownerEmail) { // register new user1 for company DoRegister registerUser1 = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = Utils.GetNameRandom() }; Thread.Sleep(500); Utils.RegisterUserByEmail(registerUser1); CreateCompanyInput companyInput = new CreateCompanyInput() { CompanyName = Utils.GetNameRandom(), CompanyType = "ООО", CompanyUsers = new List<string>() { registerUser1.email }, EmailOwner = ownerEmail }; var postDataJson = JsonConvert.SerializeObject(companyInput); IRestResponse response = requestUrl.SendPostRequest(postDataJson); CreateCompanyOutput companyOutput = JsonConvert.DeserializeObject<CreateCompanyOutput>(response.Content); Assert.AreEqual("error", companyOutput.StatusType); Assert.AreEqual($"Пользователь не найден c email_owner {ownerEmail}", companyOutput.Message); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } } } <file_sep>using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using RestSharp; using System; using System.Collections.Generic; using System.Net; using System.Threading; using UserBugredApi.Helpers; using UserBugredApi.Models; namespace UserBugredApi { class AddAvatar { RequestHelper requestUrl; [SetUp] public void Setup() { requestUrl = new RequestHelper("http://users.bugred.ru/tasks/rest/addavatar"); } [Test] public void AddAvatarTest() { string email = "<EMAIL>"; string avatar = "H:/!VisualStrudio/ApiRestLection/BugredApiTest/avatar.png"; IRestResponse response = requestUrl.AddAvatar(email,avatar); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserBugredApi.Models { class CreateCompanyInput { [JsonProperty("company_name")] public string CompanyName { get; set; } [JsonProperty("company_type")] public string CompanyType { get; set; } [JsonProperty("company_users")] public List<string> CompanyUsers { get; set; } [JsonProperty("email_owner")] public string EmailOwner { get; set; } } } <file_sep>using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using RestSharp; using System; using System.Collections.Generic; using System.Net; using System.Threading; using UserBugredApi.Helpers; using UserBugredApi.Models; namespace UserBugredApi { class CreateUserWithTasks { RequestHelper requestUrl; [SetUp] public void Setup() { requestUrl = new RequestHelper("http://users.bugred.ru/tasks/rest/createuserwithtasks"); } [Test] public void CreateUserWithTasksValid() { CreateUserWithTasksInput createUserWithTasksInput = new CreateUserWithTasksInput() { Email = Utils.GetEmailRandom(), Name = Utils.GetNameRandom(), Tasks = new List<Task>() { new Task { Title = "Тестовая таска1 " + Utils.GetNameRandom(), Description = "Тестовое описание таски 1 " + Utils.GetNameRandom() }, new Task { Title = "Тестовая таска2 " + Utils.GetNameRandom(), Description = "Тестовое описание таски 2 " + Utils.GetNameRandom() } }, Companies = new List<int> { 19, 20 }, Hobby = "Стрельба из лука, Настолки", Adres = "адрес 1", Name1 = "<NAME>", Surname1 = "Иванов", Fathername1 = "Петров", Cat = "Маруся", Dog = "Ушастый", Parrot = "Васька", Cavy = "Кто ты?", Hamster = "Хомяк", Squirrel = "Белая горячка к нам пришла", Phone = "333 33 33", Inn = "123456789012", Gender = "m", Birthday = "01.01.1900", Date_start = "11.11.2000" }; Thread.Sleep(500); var postDataJson = JsonConvert.SerializeObject(createUserWithTasksInput); IRestResponse response = requestUrl.SendPostRequest(postDataJson); CreateUserWithTasksOutput createUserWithTasksOutput = JsonConvert.DeserializeObject<CreateUserWithTasksOutput>(response.Content); Assert.AreEqual(expected: null, actual: createUserWithTasksOutput.type); // если ошибка то будет поле type с текстом ошибки Assert.AreEqual(createUserWithTasksInput.Email, createUserWithTasksOutput.email); for (int i = 0; i < createUserWithTasksInput.Tasks.Count - 1; i++) { Assert.AreEqual(createUserWithTasksInput.Tasks[i].Title, createUserWithTasksOutput.tasks[i].name); } Assert.AreEqual(createUserWithTasksInput.Name, createUserWithTasksOutput.name); Assert.AreEqual(createUserWithTasksInput.Name1, createUserWithTasksOutput.name1); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserBugredApi.Models { class CreateUserWithTasksOutput { [JsonProperty("type")] public string type { get; set; } [JsonProperty("name")] public string name { get; set; } [JsonProperty("name1")] public string name1 { get; set; } [JsonProperty("hobby")] public string hobby { get; set; } [JsonProperty("surname1")] public string surname1 { get; set; } [JsonProperty("fathername1")] public string fathername1 { get; set; } [JsonProperty("cat")] public string cat { get; set; } [JsonProperty("dog")] public string dog { get; set; } [JsonProperty("parrot")] public string parrot { get; set; } [JsonProperty("cavy")] public string cavy { get; set; } [JsonProperty("hamster")] public string hamster { get; set; } [JsonProperty("squirrel")] public string squirrel { get; set; } [JsonProperty("phone")] public string phone { get; set; } [JsonProperty("adres")] public string adres { get; set; } [JsonProperty("gender")] public string gender { get; set; } [JsonProperty("date_start")] public DateStart date_start { get; set; } [JsonProperty("date_updated")] public DateUpdated date_updated { get; set; } [JsonProperty("birthday")] public Birthday birthday { get; set; } [JsonProperty("role")] public List<string> role { get; set; } = new List<string>(); [JsonProperty("date_register")] public DateRegister date_register { get; set; } [JsonProperty("date")] public string date { get; set; } [JsonProperty("email")] public string email { get; set; } [JsonProperty("by_user")] public string by_user { get; set; } [JsonProperty("companies")] public List<Company> companies { get; set; } = new List<Company>(); [JsonProperty("tasks")] public List<TaskOutput> tasks { get; set; } = new List<TaskOutput>(); } public class DateStart { [JsonProperty("sec")] public string sec { get; set; } [JsonProperty("usec")] public string usec { get; set; } } public class DateUpdated { [JsonProperty("sec")] public string sec { get; set; } [JsonProperty("usec")] public string usec { get; set; } } public class Birthday { [JsonProperty("sec")] public string sec { get; set; } [JsonProperty("usec")] public string usec { get; set; } } public class DateRegister { [JsonProperty("sec")] public string sec { get; set; } [JsonProperty("usec")] public string usec { get; set; } } public class Company { [JsonProperty("name")] public string name { get; set; } [JsonProperty("id")] public string id { get; set; } } public class TaskOutput { [JsonProperty("name")] public string name { get; set; } [JsonProperty("id")] public string id { get; set; } } } <file_sep>using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using RestSharp; using System; using System.Collections.Generic; using System.Net; using System.Threading; using UserBugredApi.Helpers; using UserBugredApi.Models; namespace UserBugredApi { public class DoRegisterTests { RequestHelper requestUrl; [SetUp] public void Setup() { requestUrl = new RequestHelper("http://users.bugred.ru/tasks/rest/doregister"); } [Test] public void DoRegisterValidDataPostRequest() { DoRegister doRegisterData = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = Utils.GetNameRandom() }; Thread.Sleep(500); var postDataJson = JsonConvert.SerializeObject(doRegisterData); IRestResponse response = requestUrl.SendPostRequest(postDataJson); JObject json = JObject.Parse(response.Content); Assert.AreEqual(doRegisterData.email, json["email"]?.ToString()); Assert.AreEqual(doRegisterData.name, json["name"]?.ToString()); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } [Test] public void DoRegisterNullEmail() { DoRegister doRegisterData = new DoRegister() { email = "", password = <PASSWORD>(), name = Utils.GetNameRandom() }; Thread.Sleep(500); var postDataJson = JsonConvert.SerializeObject(doRegisterData); IRestResponse response = requestUrl.SendPostRequest(postDataJson); JObject json = JObject.Parse(response.Content); Assert.AreEqual("error", json["type"]?.ToString()); Assert.AreEqual("Некоректный email", json["message"]?.ToString()); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } [Test] public void DoRegisterNullName() { DoRegister doRegisterData = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = "" }; Thread.Sleep(500); var postDataJson = JsonConvert.SerializeObject(doRegisterData); IRestResponse response = requestUrl.SendPostRequest(postDataJson); JObject json = JObject.Parse(response.Content); Assert.AreEqual("error", json["type"]?.ToString()); Assert.AreEqual("поле фио является обязательным", json["message"]?.ToString()); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } [Test] public void DoRegisterNullPassword() { DoRegister doRegisterData = new DoRegister() { email = Utils.GetEmailRandom(), password ="", name = Utils.GetNameRandom() }; Thread.Sleep(500); var postDataJson = JsonConvert.SerializeObject(doRegisterData); IRestResponse response = requestUrl.SendPostRequest(postDataJson); JObject json = JObject.Parse(response.Content); Assert.AreEqual("error", json["type"]?.ToString()); Assert.AreEqual("Некоректный пароль", json["message"]?.ToString()); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } [Test] public void DoRegisterAlreadyUsedEmail() { DoRegister doRegisterData = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = Utils.GetNameRandom() }; Thread.Sleep(500); var postDataJson = JsonConvert.SerializeObject(doRegisterData); requestUrl.SendPostRequest(postDataJson); DoRegister doRegisterUsedEmailData = new DoRegister() { email = doRegisterData.email, password = <PASSWORD>(), name = Utils.GetNameRandom() }; var postDataUsedEmailJson = JsonConvert.SerializeObject(doRegisterUsedEmailData); IRestResponse response = requestUrl.SendPostRequest(postDataUsedEmailJson); JObject json = JObject.Parse(response.Content); Assert.AreEqual("error", json["type"]?.ToString()); Assert.AreEqual($"email {doRegisterUsedEmailData.email} уже есть в базе", json["message"]?.ToString()); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } [Test] public void DoRegisterAlreadyUsedName() { DoRegister doRegisterData = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = Utils.GetNameRandom() }; Thread.Sleep(500); var postDataJson = JsonConvert.SerializeObject(doRegisterData); requestUrl.SendPostRequest(postDataJson); DoRegister doRegisterUsedEmailData = new DoRegister() { email = Utils.GetEmailRandom(), password = <PASSWORD>(), name = doRegisterData.name }; var postDataUsedEmailJson = JsonConvert.SerializeObject(doRegisterUsedEmailData); IRestResponse response = requestUrl.SendPostRequest(postDataUsedEmailJson); JObject json = JObject.Parse(response.Content); Assert.AreEqual("error", json["type"]?.ToString()); Assert.AreEqual($"Текущее ФИО {doRegisterUsedEmailData.name} уже есть в базе", json["message"]?.ToString()); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } [Test] public void DoRegisterValidDataGetRequest() { Dictionary<string, string> DoRegisterData = new Dictionary<string, string>() { { "email", Utils.GetEmailRandom()}, { "password", <PASSWORD>()}, { "name", Utils.GetNameRandom()}, }; IRestResponse response = requestUrl.SendGetRequest(DoRegisterData); JObject json = JObject.Parse(response.Content); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UserBugredApi.Models; using UserBugredApi.Helpers; using RestSharp; using Newtonsoft.Json; namespace UserBugredApi.Helpers { static class Utils { static public Random rnd = new Random(); static public string GetNameRandom() { return "GomoTrio" + rnd.Next(11, 99) + rnd.Next(11, 99) + DateTime.Now.ToString("hhmmssMMddyy"); } static public string GetEmailRandom() { return DateTime.Now.ToString("hhmmssMMddyy") + rnd.Next(11, 99) + rnd.Next(11, 99) + "@gom<EMAIL>.com"; } static public string GetPassword() { return "<PASSWORD>"; } static public void RegisterUserByEmail(DoRegister doRegisterData) { RequestHelper requestUrl = new RequestHelper("http://users.bugred.ru/tasks/rest/doregister"); var postDataJson = JsonConvert.SerializeObject(doRegisterData); requestUrl.SendPostRequest(postDataJson); } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserBugredApi.Models { class CreateCompanyOutput { [JsonProperty("type")] public string StatusType { get; set; } [JsonProperty("message")] public string Message { get; set; } [JsonProperty("id_company")] public int IdCompany { get; set; } [JsonProperty("company")] public CompanyData companyData { get; set; } } class CompanyData { [JsonProperty("name")] public string Name; [JsonProperty("type")] public string Type; [JsonProperty("inn")] public string Inn; [JsonProperty("ogrn")] public string Ogrn; [JsonProperty("kpp")] public string Kpp; [JsonProperty("phone")] public string Phone; [JsonProperty("adress")] public string Adress; [JsonProperty("users")] public List<string> Users; } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserBugredApi.Models { public class DoRegister { [JsonProperty("email")] public string email; [JsonProperty("name")] public string name; [JsonProperty("password")] public string password; } } <file_sep># BugredApiTest http://users.bugred.ru/ Написать API автотесты для 4 запросов. <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserBugredApi.Models { public class CreateUser { [JsonProperty("email")] public string email; [JsonProperty("name")] public string name; [JsonProperty("tasks")] List<string> tasks; [JsonProperty("companies")] List<string> companies; [JsonProperty("hobby")] public string hobby; [JsonProperty("adres")] public string adres; [JsonProperty("name1")] public string name1; [JsonProperty("surname1")] public string surname1; [JsonProperty("fathername1")] public string fathername1; [JsonProperty("cat")] public string cat; [JsonProperty("dog")] public string dog; [JsonProperty("parrot")] public string parrot; [JsonProperty("cavy")] public string cavy; [JsonProperty("hamster")] public string hamster; [JsonProperty("squirrel")] public string squirrel; [JsonProperty("phone")] public string phone; [JsonProperty("inn")] public string inn; [JsonProperty("gender")] public string gender; [JsonProperty("birthday")] public string birthday; [JsonProperty("date_start")] public string date_start; } } <file_sep>using Newtonsoft.Json.Linq; using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserBugredApi.Helpers { public class RequestHelper { private IRestClient _client; public RequestHelper(string requestUrl) { _client = new RestClient(requestUrl); } public IRestResponse SendGetRequest(Dictionary<string, string> parameters) { RestRequest request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); foreach (var param in parameters) { request.AddParameter(param.Key, param.Value); } IRestResponse response = _client.Execute(request); return response; } public IRestResponse AddAvatar(string email, string avatar) { RestRequest request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json") .AddHeader("Content-Type", "multipart/form-data") .AddParameter("email", email) .AddFile("avatar", avatar) .AddParameter("multipart/form-data", "avatar", ParameterType.RequestBody); IRestResponse response = _client.Execute(request); return response; } public IRestResponse SendPostRequest(string postBody) { RestRequest request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/json"); request.AddJsonBody(postBody); IRestResponse response = _client.Execute(request); return response; } } }
f7fcd73fe6d09e8f68c6f5e2a7d943d7280782f2
[ "Markdown", "C#" ]
12
C#
Kizliak/BugredApiTest
ef150454cf2e378fda43c8f860e89f76befbba97
fb993c2f073ebe9d48f4a83027a4bc1d51992179
refs/heads/master
<file_sep>-- Change DELIMITER to $$ DELIMITER $$ -- Create tax_get_taxes stored procedure DROP PROCEDURE IF EXISTS tax_get_taxes $$ CREATE PROCEDURE tax_get_taxes() BEGIN SELECT tax_id, tax_type, tax_percentage FROM tax ORDER BY tax_id; END$$ -- Create tax_get_tax_details stored procedure DROP PROCEDURE IF EXISTS tax_get_tax_details $$ CREATE PROCEDURE tax_get_tax_details(IN inTaxId INT) BEGIN SELECT tax_id, tax_type, tax_percentage FROM tax WHERE tax_id = inTaxId; END$$ -- Create catalog_get_categories stored procedure DROP PROCEDURE IF EXISTS catalog_get_categories $$ CREATE PROCEDURE catalog_get_categories() BEGIN SELECT category_id, name, description, department_id FROM category ORDER BY category_id; END$$ -- Create catalog_get_category_details stored procedure DROP PROCEDURE IF EXISTS catalog_get_category_details $$ CREATE PROCEDURE catalog_get_category_details(IN inCategoryId INT) BEGIN SELECT category_id, name, description, department_id FROM category WHERE category_id = inCategoryId; END$$ -- Create catalog_get_departments_list stored procedure DROP PROCEDURE IF EXISTS catalog_get_departments_list $$ CREATE PROCEDURE catalog_get_departments_list() BEGIN SELECT department_id, name, description FROM department ORDER BY department_id; END$$ -- Create catalog_get_department_details stored procedure DROP PROCEDURE IF EXISTS catalog_get_department_details $$ CREATE PROCEDURE catalog_get_department_details(IN inDepartmentId INT) BEGIN SELECT department_id, name, description FROM department WHERE department_id = inDepartmentId; END$$ -- Create catalog_get_products_on_department stored procedure -- Issue with DISTINCT https://stackoverflow.com/a/5391642 DROP PROCEDURE IF EXISTS catalog_get_products_on_department $$ CREATE PROCEDURE catalog_get_products_on_department( IN inDepartmentId INT, IN inShortProductDescriptionLength INT, IN inProductsPerPage INT, IN inStartItem INT) BEGIN PREPARE statement FROM "SELECT p.product_id, p.name, IF(LENGTH(p.description) <= ?, p.description, CONCAT(LEFT(p.description, ?), '...')) AS description, p.price, p.discounted_price, p.thumbnail FROM product p INNER JOIN product_category pc ON p.product_id = pc.product_id INNER JOIN category c ON pc.category_id = c.category_id WHERE (p.display = 2 OR p.display = 3) AND c.department_id = ? GROUP BY p.product_id ORDER BY p.display DESC LIMIT ?, ?"; SET @p1 = inShortProductDescriptionLength; SET @p2 = inShortProductDescriptionLength; SET @p3 = inDepartmentId; SET @p4 = inStartItem; SET @p5 = inProductsPerPage; EXECUTE statement USING @p1, @p2, @p3, @p4, @p5; END$$ -- Create shopping_cart_add_product stored procedure DROP PROCEDURE IF EXISTS shopping_cart_add_product $$ CREATE PROCEDURE shopping_cart_add_product(IN inCartId CHAR(32), IN inProductId INT, IN inAttributes VARCHAR(1000)) BEGIN DECLARE productQuantity INT; -- Obtain current shopping cart quantity for the product SELECT quantity FROM shopping_cart WHERE cart_id = inCartId AND product_id = inProductId AND attributes = inAttributes INTO productQuantity; -- Create new shopping cart record, or increase quantity of existing record IF productQuantity IS NULL THEN INSERT INTO shopping_cart(item_id, cart_id, product_id, attributes, quantity, added_on) VALUES (NULL, inCartId, inProductId, inAttributes, 1, NOW()); ELSE UPDATE shopping_cart SET quantity = quantity + 1, buy_now = true WHERE cart_id = inCartId AND product_id = inProductId AND attributes = inAttributes; END IF; END$$ -- Create catalog_count_products_on_catalog stored procedure DROP PROCEDURE IF EXISTS catalog_count_products_on_catalog $$ CREATE PROCEDURE catalog_count_products_on_catalog() BEGIN SELECT COUNT(*) AS products_on_catalog_count FROM product; END$$ -- Create catalog_get_products_on_catalog stored procedure DROP PROCEDURE IF EXISTS catalog_get_products_on_catalog $$ CREATE PROCEDURE catalog_get_products_on_catalog( IN inShortProductDescriptionLength INT, IN inProductsPerPage INT, IN inStartItem INT) BEGIN PREPARE statement FROM "SELECT product_id, name, IF(LENGTH(description) <= ?, description, CONCAT(LEFT(description, ?), '...')) AS description, price, discounted_price, thumbnail FROM product ORDER BY display DESC LIMIT ?, ?"; SET @p1 = inShortProductDescriptionLength; SET @p2 = inShortProductDescriptionLength; SET @p3 = inStartItem; SET @p4 = inProductsPerPage; EXECUTE statement USING @p1, @p2, @p3, @p4; END$$ -- Create catalog_count_products_on_department stored procedure DROP PROCEDURE IF EXISTS catalog_count_products_on_department $$ CREATE PROCEDURE catalog_count_products_on_department(IN inDepartmentId INT) BEGIN SELECT DISTINCT COUNT(*) AS products_on_department_count FROM product p INNER JOIN product_category pc ON p.product_id = pc.product_id INNER JOIN category c ON pc.category_id = c.category_id WHERE (p.display = 2 OR p.display = 3) AND c.department_id = inDepartmentId; END$$ -- Create catalog_get_products_on_department stored procedure DROP PROCEDURE IF EXISTS catalog_get_products_on_department $$ CREATE PROCEDURE catalog_get_products_on_department( IN inDepartmentId INT, IN inShortProductDescriptionLength INT, IN inProductsPerPage INT, IN inStartItem INT) BEGIN PREPARE statement FROM "SELECT DISTINCT p.product_id, p.name, IF(LENGTH(p.description) <= ?, p.description, CONCAT(LEFT(p.description, ?), '...')) AS description, p.price, p.discounted_price, p.thumbnail FROM product p INNER JOIN product_category pc ON p.product_id = pc.product_id INNER JOIN category c ON pc.category_id = c.category_id WHERE (p.display = 2 OR p.display = 3) AND c.department_id = ? ORDER BY p.display DESC LIMIT ?, ?"; SET @p1 = inShortProductDescriptionLength; SET @p2 = inShortProductDescriptionLength; SET @p3 = inDepartmentId; SET @p4 = inStartItem; SET @p5 = inProductsPerPage; EXECUTE statement USING @p1, @p2, @p3, @p4, @p5; END$$ -- Create shopping_cart_get_products stored procedure DROP PROCEDURE IF EXISTS shopping_cart_get_products $$ CREATE PROCEDURE shopping_cart_get_products(IN inCartId CHAR(32)) BEGIN SELECT sc.item_id, p.name, sc.attributes, COALESCE(NULLIF(p.discounted_price, 0), p.price) AS price, sc.quantity, sc.product_id, p.thumbnail AS image, COALESCE(NULLIF(p.discounted_price, 0), p.price) * sc.quantity AS subtotal FROM shopping_cart sc INNER JOIN product p ON sc.product_id = p.product_id WHERE sc.cart_id = inCartId AND sc.buy_now ORDER BY sc.item_id ASC; END$$ -- Create orders_get_order_short_details stored procedure DROP PROCEDURE IF EXISTS orders_get_order_short_details $$ CREATE PROCEDURE orders_get_order_short_details(IN inOrderId INT) BEGIN SELECT o.order_id, o.total_amount, o.created_on, o.shipped_on, o.status, c.name, c.customer_id FROM orders o INNER JOIN customer c ON o.customer_id = c.customer_id WHERE o.order_id = inOrderId; END$$ -- Create orders_get_order_info stored procedure DROP PROCEDURE IF EXISTS orders_get_order_info $$ CREATE PROCEDURE orders_get_order_info(IN inOrderId INT) BEGIN SELECT o.order_id, o.total_amount, o.created_on, o.shipped_on, o.status, o.comments, o.customer_id, o.auth_code, o.reference, o.shipping_id, s.shipping_type, s.shipping_cost, o.tax_id, t.tax_type, t.tax_percentage, c.customer_id FROM orders o INNER JOIN customer c ON o.customer_id = c.customer_id INNER JOIN tax t ON t.tax_id = o.tax_id INNER JOIN shipping s ON s.shipping_id = o.shipping_id WHERE o.order_id = inOrderId; END$$ -- Create shopping_cart_get_saved_products stored procedure DROP PROCEDURE IF EXISTS shopping_cart_get_saved_products $$ CREATE PROCEDURE shopping_cart_get_saved_products(IN inCartId CHAR(32)) BEGIN SELECT sc.item_id, p.name, sc.attributes, p.thumbnail as image, COALESCE(NULLIF(p.discounted_price, 0), p.price) AS price FROM shopping_cart sc INNER JOIN product p ON sc.product_id = p.product_id WHERE sc.cart_id = inCartId AND NOT sc.buy_now; END$$ -- Create customer_update_account stored procedure DROP PROCEDURE IF EXISTS customer_update_account $$ CREATE PROCEDURE customer_update_account(IN inCustomerId INT, IN inName VARCHAR(50), IN inEmail VARCHAR(100), IN inPassword VARCHAR(50), IN inDayPhone VARCHAR(100), IN inEvePhone VARCHAR(100), IN inMobPhone VARCHAR(100)) BEGIN IF inPassword IS NULL OR inPassword = '' THEN -- Don't update password UPDATE customer SET name = inName, email = inEmail, day_phone = inDayPhone, eve_phone = inEvePhone, mob_phone = inMobPhone WHERE customer_id = inCustomerId; ELSE UPDATE customer SET name = inName, email = inEmail, password = in<PASSWORD>, day_phone = inDayPhone, eve_phone = inEvePhone, mob_phone = inMobPhone WHERE customer_id = inCustomerId; END IF; END$$ -- Create catalog_get_products_on_department stored procedure DROP PROCEDURE IF EXISTS catalog_get_products_on_department $$ CREATE PROCEDURE catalog_get_products_on_department( IN inDepartmentId INT, IN inShortProductDescriptionLength INT, IN inProductsPerPage INT, IN inStartItem INT) BEGIN PREPARE statement FROM "SELECT p.product_id, p.name, IF(LENGTH(p.description) <= ?, p.description, CONCAT(LEFT(p.description, ?), '...')) AS description, p.price, p.discounted_price, p.thumbnail FROM product p INNER JOIN product_category pc ON p.product_id = pc.product_id INNER JOIN category c ON pc.category_id = c.category_id WHERE c.department_id = ? GROUP BY p.product_id ORDER BY p.display DESC LIMIT ?, ?"; SET @p1 = inShortProductDescriptionLength; SET @p2 = inShortProductDescriptionLength; SET @p3 = inDepartmentId; SET @p4 = inStartItem; SET @p5 = inProductsPerPage; EXECUTE statement USING @p1, @p2, @p3, @p4, @p5; END$$ -- Change back DELIMITER to ; DELIMITER ; <file_sep>var authUtils = require('../../utils/auth'); /* Extract authentication token and add it to the request object */ exports.extractToken = function(req, res, next){ var headerKey = 'Bearer'; if (req.headers['user-key']) { var parts = req.headers['user-key'].split(' '); if (parts.length === 2 && parts[0] === headerKey) { req['token'] = parts[1]; } } next(); }; /* Verify token */ exports.verifyToken = function(req, res, next){ if (req.token) { var decoded = authUtils.verifyToken(req.token); if (decoded === false) { // Token invalid / expired / etc res.status(401).json({ status: 401, code: 'AUT_02', message: 'Access Unauthorized.' }); } else { req['customerData'] = decoded; next(); } } else { // Token not specified res.status(401).json({ status: 401, code: 'AUT_01', message: 'Authorization code is empty.' }); } }; <file_sep>var chai = require('chai'); var assert = require('chai').assert; var chaiHttp = require('chai-http'); var app = require('../app'); // Configure chai chai.use(chaiHttp); chai.should(); describe("Orders", () => { // Create an order describe("POST /orders", () => { it("Create an order without a User-Key header", (done) => { chai.request(app) .post('/orders') .end((err, res) => { assert.equal(res.status, 401, 'respond with status 401 when the User-Key header is empty'); assert.equal(res.body.code, 'AUT_01', 'AUT_01 code for an empty User-Key header'); done(); }); }); it("Create an order without an invalid User-Key header", (done) => { chai.request(app) .post('/orders') .set('User-Key', 'Bearer ' + new Date().getTime()) .end((err, res) => { assert.equal(res.status, 401, 'respond with status 401 when the User-Key header is invalid'); assert.equal(res.body.code, 'AUT_02', 'AUT_02 code for an invalid User-Key header'); done(); }); }); it("Create an order with an empty cart id", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Create order chai.request(app) .post('/orders') .set('User-Key', res.body.accessToken) .send({}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the cart id field is empty'); assert.equal(res.body.field, 'cart_id', 'display failed field'); assert.equal(res.body.code, 'ORD_02', 'ORD_02 code for a required order field'); done(); }); }); }); it("Create an order with an empty shipping id", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Create order chai.request(app) .post('/orders') .set('User-Key', res.body.accessToken) .send({cart_id: 'example'}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the shipping id field is empty'); assert.equal(res.body.field, 'shipping_id', 'display failed field'); assert.equal(res.body.code, 'ORD_02', 'ORD_02 code for a required order field'); done(); }); }); }); it("Create an order with an invalid shipping id", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Create order chai.request(app) .post('/orders') .set('User-Key', res.body.accessToken) .send({cart_id: 'example', shipping_id: 'example'}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the shipping id field is invalid'); assert.equal(res.body.field, 'shipping_id', 'display failed field'); assert.equal(res.body.code, 'ORD_03', 'ORD_03 code for an invalid order field'); done(); }); }); }); it("Create an order with an empty tax id", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Create order chai.request(app) .post('/orders') .set('User-Key', res.body.accessToken) .send({cart_id: 'example', shipping_id: 1}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the tax id field is empty'); assert.equal(res.body.field, 'tax_id', 'display failed field'); assert.equal(res.body.code, 'ORD_02', 'ORD_02 code for a required order field'); done(); }); }); }); it("Create an order with an invalid tax id", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Create order chai.request(app) .post('/orders') .set('User-Key', res.body.accessToken) .send({cart_id: 'example', shipping_id: 1, tax_id: 'example'}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the tax id field is invalid'); assert.equal(res.body.field, 'tax_id', 'display failed field'); assert.equal(res.body.code, 'ORD_03', 'ORD_03 code for an invalid order field'); done(); }); }); }); }); // Get an order describe("GET /orders/{order_id}", () => { it("Get an order without a User-Key header", (done) => { chai.request(app) .get('/orders/1') .end((err, res) => { assert.equal(res.status, 401, 'respond with status 401 when the User-Key header is empty'); assert.equal(res.body.code, 'AUT_01', 'AUT_01 code for an empty User-Key header'); done(); }); }); it("Get an order without an invalid User-Key header", (done) => { chai.request(app) .get('/orders/1') .set('User-Key', 'Bearer ' + new Date().getTime()) .end((err, res) => { assert.equal(res.status, 401, 'respond with status 401 when the User-Key header is invalid'); assert.equal(res.body.code, 'AUT_02', 'AUT_02 code for an invalid User-Key header'); done(); }); }); }); }); <file_sep>var express = require('express'); var multer = require('multer'); var upload = multer(); var router = express.Router(); var shoppingcartController = require('../controllers/shoppingcartController'); /** * @swagger * tags: * - name: shoppingcart * description: Everything about shopping cart */ /** * @swagger * components: * schemas: * CartWithProduct: * type: array * items: * $ref: '#/components/schemas/Product' */ /** * Generete the unique cart id * * * @swagger * paths: * /shoppingcart/generateUniqueId: * get: * summary: Generete the unique cart id * description: Generete the unique cart id * tags: [shoppingcart] * produces: * - application/json * responses: * 200: * description: Json Object with unique Cart ID * content: * application/json: * schema: * properties: * cart_id: * type: string * example: 2PzavCD7BKG0 */ router.get('/generateUniqueId', shoppingcartController.generateUniqueId); /** * Add a Product in the cart * * * @swagger * paths: * /shoppingcart/add: * post: * summary: Add a Product in the cart * description: Add a Product in the cart * tags: [shoppingcart] * produces: * - application/json * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * cart_id: * description: Cart ID * type: string * product_id: * description: Product ID * type: integer * attributes: * description: Attributes * type: string * required: * - cart_id * - product_id * - attributes * responses: * 200: * description: Return a array of products in the cart * content: * application/json: * schema: * $ref: '#/components/schemas/CartWithProduct' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. * Empty cart id: * code: CRT_02 * message: Cart id can't be blank * field: cart_id * status: 400 * Empty product id: * code: CRT_02 * message: Product id can't be blank * field: product_id * status: 400 * Invalid product id: * code: CRT_03 * message: Product id is not a number * field: product_id * status: 400 * Empty attributes: * code: CRT_02 * message: Attributes can't be blank * field: attributes * status: 400 */ router.post('/add', upload.none(), shoppingcartController.addProductToCart); /** * Get List of Products in Shopping Cart * * * @swagger * paths: * /shoppingcart/{cart_id}: * get: * summary: Get List of Products in Shopping Cart * description: Get List of Products in Shopping Cart * tags: [shoppingcart] * produces: * - application/json * parameters: * - in: path * name: cart_id * required: true * schema: * type: string * responses: * 200: * description: Return a array of products in the cart. * content: * application/json: * schema: * $ref: '#/components/schemas/CartWithProduct' */ router.get('/:cart_id([a-zA-Z0-9]+)', shoppingcartController.getCartProductList); /* Update the cart by item */ /** * Update the cart by item * * * @swagger * paths: * /shoppingcart/update/{item_id}: * put: * summary: Update the cart by item * description: Update the cart by item * tags: [shoppingcart] * produces: * - application/json * parameters: * - in: path * name: item_id * required: true * schema: * type: integer * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * quantity: * description: Item Quantity * type: integer * required: * - quantity * responses: * 200: * description: Return a array of products in the cart. * content: * application/json: * schema: * $ref: '#/components/schemas/CartWithProduct' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * Empty quantity: * code: CRT_02 * message: Quantity can't be blank * field: quantity * status: 400 * Invalid quantity: * code: CRT_03 * message: Quantity is not a number * field: quantity * status: 400 */ router.put('/update/:item_id([0-9]+)', upload.none(), shoppingcartController.updateCartByItem); /** * Empty cart * * * @swagger * paths: * /shoppingcart/empty/{cart_id}: * delete: * summary: Empty cart * description: Empty cart * tags: [shoppingcart] * produces: * - application/json * parameters: * - in: path * name: cart_id * required: true * schema: * type: string * responses: * 200: * description: Return a empty Array. */ router.delete('/empty/:cart_id([a-zA-Z0-9]+)', shoppingcartController.emptyCartById); /** * Move a product to cart * * * @swagger * paths: * /shoppingcart/moveToCart/{item_id}: * get: * summary: Move a product to cart * description: Move a product to cart * tags: [shoppingcart] * produces: * - application/json * parameters: * - in: path * name: item_id * required: true * schema: * type: integer * responses: * 200: * description: No data. */ router.get('/moveToCart/:item_id([0-9]+)', shoppingcartController.moveProductToCart); /** * Return a total Amount from Cart * * * @swagger * paths: * /shoppingcart/totalAmount/{cart_id}: * get: * summary: Return a total Amount from Cart * description: Return a total Amount from Cart * tags: [shoppingcart] * produces: * - application/json * parameters: * - in: path * name: cart_id * required: true * schema: * type: string * responses: * 200: * description: Return the total amount * content: * application/json: * schema: * properties: * total_amount: * type: string * example: "20.00" */ router.get('/totalAmount/:cart_id([a-zA-Z0-9]+)', shoppingcartController.getCartTotalAmount); /** * Save a Product for later * * * @swagger * paths: * /shoppingcart/saveForLater/{item_id}: * get: * summary: Save a Product for later * description: Save a Product for later * tags: [shoppingcart] * produces: * - application/json * parameters: * - in: path * name: item_id * required: true * schema: * type: integer * responses: * 200: * description: No data. */ router.get('/saveForLater/:item_id([0-9]+)', shoppingcartController.saveProductForLater); /* Get Products saved for later */ /** * Get Products saved for later * * * @swagger * paths: * /shoppingcart/getSaved/{cart_id}: * get: * summary: Get Products saved for later * description: Get Products saved for later * tags: [shoppingcart] * produces: * - application/json * parameters: * - in: path * name: cart_id * required: true * schema: * type: string * responses: * 200: * description: Return a object of item salved. * content: * application/json: * schema: * properties: * item_id: * type: string * example: 1 * name: * type: string * example: Haute Couture * attributes: * type: string * example: "{}" * image: * type: string * example: haute-couture-thumbnail.gif * price: * type: string * example: "14.95" */ router.get('/getSaved/:cart_id([a-zA-Z0-9]+)', shoppingcartController.getProductsSavedForLater); /** * Remove a product in the cart * * * @swagger * paths: * /shoppingcart/removeProduct/{item_id}: * delete: * summary: Remove a product in the cart * description: Remove a product in the cart * tags: [shoppingcart] * produces: * - application/json * parameters: * - in: path * name: item_id * required: true * schema: * type: integer * responses: * 200: * description: No data. */ router.delete('/removeProduct/:item_id([0-9]+)', shoppingcartController.removeProductFromCart); module.exports = router; <file_sep>var db = require('../index'); exports.getTaxes = function() { return db.knex.raw('CALL tax_get_taxes();').then(function(data) { data = data[0][0]; return {count: data.length, rows: data}; }).catch(function(reason) { return {}; }); }; exports.getTaxById = function(taxId) { return db.knex.raw('CALL tax_get_tax_details(?);', [taxId]).then(function(data) { data = data[0][0]; if (data.length === 0) { // Not found throw 'The tax with this ID does not exist.'; } return data[0]; }).catch(function(reason) { return { error: { status: 404, code: 'TAX_01', message: reason } }; }); }; <file_sep>var Shoppingcart = require('../db/models/shoppingcart'); var response = require('./../utils/response.js'); var forms = require('../forms/forms'); /* Generete the unique CART ID */ exports.generateUniqueId = function(req, res) { Shoppingcart.generateUniqueId().then(function(data) { response.sendResponse(data, req, res); }); }; /* Add a Product in the cart */ exports.addProductToCart = function(req, res) { var error = forms.validateForm(forms.cartConstraints, req.body, 'CRT'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Shoppingcart.addProductToCart( req.body.cart_id, req.body.product_id, req.body.attributes).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get List of Products in Shopping Cart */ exports.getCartProductList = function(req, res) { Shoppingcart.getCartProductList(req.params.cart_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Update the cart by item */ exports.updateCartByItem = function(req, res) { var error = forms.validateForm(forms.updateItemConstraints, req.body, 'CRT'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Shoppingcart.updateCartByItem(req.params.item_id, req.body.quantity).then(function(data) { response.sendResponse(data, req, res); }); }; /* Empty cart */ exports.emptyCartById = function(req, res) { Shoppingcart.emptyCartById(req.params.cart_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Move a product to cart */ exports.moveProductToCart = function(req, res) { Shoppingcart.moveProductToCart(req.params.item_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Return a total Amount from Cart */ exports.getCartTotalAmount = function(req, res) { Shoppingcart.getCartTotalAmount(req.params.cart_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Save a Product for later */ exports.saveProductForLater = function(req, res) { Shoppingcart.saveProductForLater(req.params.item_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Products saved for later */ exports.getProductsSavedForLater = function(req, res) { Shoppingcart.getProductsSavedForLater(req.params.cart_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Remove a product in the cart */ exports.removeProductFromCart = function(req, res) { Shoppingcart.removeProductFromCart(req.params.item_id).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var db = require('../index'); exports.getDepartmentList = function() { return db.knex.raw('CALL catalog_get_departments();').then(function(data) { data = data[0][0]; return {count: data.length, rows: data}; }).catch(function(reason) { return {}; }); }; exports.getDepartmentById = function(departmentId) { return db.knex.raw('CALL catalog_get_department_details(?);', [departmentId]).then(function(data) { data = data[0][0]; if (data.length === 0) { // Not found throw 'The department with this ID does not exist.'; } return data[0]; }).catch(function(reason) { return { error: { status: 404, code: 'DEP_01', message: reason } }; }); }; <file_sep>var Attribute = require('../db/models/attribute'); var response = require('./../utils/response.js'); /* Get Attribute list */ exports.getAttributes = function(req, res) { Attribute.getAttributes().then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Attribute by ID */ exports.getAttributeById = function(req, res) { Attribute.getAttributeById(req.params.attribute_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Values Attribute from Atribute */ exports.getAttributeValues = function(req, res) { Attribute.getAttributeValues(req.params.attribute_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get all Attributes with Produt ID */ exports.getProductAttributes = function(req, res) { Attribute.getProductAttributes(req.params.product_id).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var express = require('express'); var multer = require('multer'); var upload = multer(); var router = express.Router(); var authMiddleware = require('../routes/middlewares/auth'); var customerController = require('../controllers/customerController'); /** * @swagger * tags: * - name: customers * description: Everything about customers */ /** * @swagger * components: * securitySchemes: * ApiKeyAuth: * type: apiKey * in: header * name: USER-KEY */ /** * @swagger * components: * schemas: * Error: * properties: * code: * type: string * example: USR_2 * message: * type: string * example: Example field is required * field: * type: string * example: example * status: * type: integer * example: 400 */ /** * @swagger * components: * schemas: * Customer: * properties: * customer_id: * type: integer * example: 11 * name: * type: string * example: <NAME>, * email: * type: string * example: <EMAIL> * credit_card: * type: string * example: XXXXXXXX5100, * address_1: * type: string * example: Stand 1 Ext 1 * address_2: * type: string * example: Ext 1 * city: * type: string * example: Pretoria * region: * type: string * example: Gauteng * postal_code: * type: string * example: "0001" * country: * type: string * example: South Africa * shipping_region_id: * type: integer * example: 4 * day_phone: * type: string * example: "+27210000000" * eve_phone: * type: string * example: "+27110000000" * mob_phone: * type: string * example: "+27620000000" */ /** * @swagger * components: * schemas: * CustomerRegister: * properties: * customer: * $ref: '#/components/schemas/Customer' * accessToken: * type: string * example: Bearer <KEY> * expires_in: * type: string * example: 24h */ /** * Register a Customer * * * @swagger * * paths: * /customers: * post: * summary: Register a Customer * description: Register a Customer * tags: [customers] * produces: * - application/json * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * name: * description: User's name. * type: string * email: * description: User's email. * type: string * password: * description: User's password. * type: string * required: * - name * - email * - password * responses: * 200: * description: Return a Customer object with credentials * content: * application/json: * schema: * $ref: '#/components/schemas/CustomerRegister' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * Empty name: * code: USR_02 * message: Name can't be blank * field: name * status: 400 * Empty email: * code: USR_02 * message: Email can't be blank * field: email * status: 400 * Invalid email: * code: USR_03 * message: Email is not a valid email * field: email * status: 400 * Empty password: * code: USR_02 * message: Password can't be blank * field: password * status: 400 * Email already exists: * status: 400 * field: email * code: USR_01 * message: The email already exists. */ router.post('/', upload.none(), customerController.registerCustomer); /** * Customer Login * * * @swagger * * paths: * /customers/login: * post: * summary: Sign in for shopping * description: Customer Login * tags: [customers] * produces: * - application/json * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * email: * description: User's email. * type: string * password: * description: User's password. * type: string * required: * - email * - password * responses: * 200: * description: Return a Customer object with credentials * content: * application/json: * schema: * $ref: '#/components/schemas/CustomerRegister' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * Empty email field: * code: USR_2 * message: Email can't be blank * field: email * status: 400 * Email invalid: * code: USR_3 * message: Email is not a valid email * field: email * status: 400 * Empty password field: * code: USR_02 * message: Password can't be blank * field: password * status: 400 * Invalid email and password combination: * status: 400 * code: USR_01 * message: Email or Password is invalid. */ router.post('/login', upload.none(), customerController.loginCustomer); /** * Customer Login with Facebook * * * @swagger * paths: * /customers/facebook: * post: * summary: Sign in with a facebook login token * description: Customer Login with Facebook * tags: [customers] * produces: * - application/json * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * access_token: * description: Token generated from your facebook login. * type: string * required: * - access_token * responses: * 200: * description: Return a Customer object with credentials * content: * application/json: * schema: * $ref: '#/components/schemas/CustomerRegister' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * Empty access token: * code: USR_02 * message: Access token can't be blank * field: access_token * status: 400 * Invalid access token: * status: 400 * code: USR_01, * message: Facebook login failed. */ router.post('/facebook', upload.none(), customerController.facebookLoginCustomer); /** * Update the address from customer * * * @swagger * paths: * /customers/address: * put: * summary: Update the address from customer * description: Update the address from customer * tags: [customers] * produces: * - application/json * security: * - ApiKeyAuth: [] * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * address_1: * description: Address 1 * type: string * address_2: * description: Address 2 * type: string * city: * description: City. * type: string * region: * description: Region * type: string * postal_code: * description: Postal Code * type: string * country: * description: Country * type: string * shipping_region_id: * description: Shipping Region ID. * type: integer * required: * - address_1 * - city * - region * - postal_code * - country * - shipping_region_id * responses: * 200: * description: Return a Customer object * content: * application/json: * schema: * $ref: '#/components/schemas/Customer' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. * Empty address 1: * code: USR_02 * message: Address 1 can't be blank * field: address_1 * status: 400 * Empty city: * code: USR_02 * message: City can't be blank * field: city * status: 400 * Empty region: * code: USR_02 * message: Region can't be blank * field: region * status: 400 * Empty postal code: * code: USR_02 * message: Postal code can't be blank * field: postal_code * status: 400 * Empty country: * code: USR_02 * message: Country can't be blank * field: country * status: 400 * Empty shipping region id: * code: USR_02 * message: Shipping region id can't be blank * field: shipping_region_id * status: 400 * Invalid shipping region id: * code: USR_03 * message: Shipping region id is not a number * field: shipping_region_id * status: 400 */ router.put('/address', [upload.none(), authMiddleware.verifyToken], customerController.updateCustomerAddress); /** * Update credit card * * * @swagger * paths: * /customers/creditCard: * put: * summary: Update credit card * description: Update credit card * tags: [customers] * produces: * - application/json * security: * - ApiKeyAuth: [] * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * credit_card: * description: Credit Card * type: string * required: * - credit_card * responses: * 200: * description: Return a Customer object * content: * application/json: * schema: * $ref: '#/components/schemas/Customer' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. * Empty credit card: * code: USR_02 * message: Credit card can't be blank * field: credit_card * status: 400 */ router.put('/creditCard', [authMiddleware.verifyToken], customerController.updateCustomerCreditCard); module.exports = router; <file_sep>var express = require('express'); var router = express.Router(); var categoryController = require('../controllers/categoryController'); /** * @swagger * tags: * - name: categories * description: Everything about categories */ /** * @swagger * components: * schemas: * Category: * properties: * category_id: * type: integer * example: 1 * name: * type: string * example: French * description: * type: string * example: "The French have always had an eye for beauty. One look at the T-shirts below and you'll see that same appreciation has been applied abundantly to their postage stamps. Below are some of our most beautiful and colorful T-shirts, so browse away! And don't forget to go all the way to the bottom - you don't want to miss any of them!" * department_id: * type: integer * example: 1 */ /** * @swagger * components: * schemas: * CategoryBasic: * properties: * category_id: * type: integer * example: 1 * department_id: * type: integer * example: 1 * name: * type: string * example: French */ /** * Get Categories * * * @swagger * paths: * /categories: * get: * summary: Get Categories * description: Get Categories * tags: [categories] * produces: * - application/json * parameters: * - in: query * name: order * schema: * type: string * description: "Sorting a field. Allowed fields: 'category_id', 'name'." * - in: query * name: page * schema: * type: integer * description: "Inform the page. Starting with 1. Default: 1" * - in: query * name: limit * schema: * type: integer * description: "Limit per page, Default: 20." * responses: * 200: * description: Return a list with count (total categories) and the rows of Categories * content: * application/json: * schema: * properties: * count: * type: integer * example: 20 * rows: * type: array * items: * $ref: '#/components/schemas/Category' */ router.get('/', categoryController.getCategoryList); /** * Get Category by ID * * * @swagger * paths: * /categories/{category_id}: * get: * summary: Get Category by ID * description: Get Category by ID * tags: [categories] * produces: * - application/json * parameters: * - in: path * name: category_id * required: true * schema: * type: integer * responses: * 200: * description: Return a object of Category * content: * application/json: * schema: * $ref: '#/components/schemas/Category' * 404: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ router.get('/:category_id([0-9]+)', categoryController.getCategoryById); /** * Get Categories of a Product * * * @swagger * paths: * /categories/inProduct/{product_id}: * get: * summary: Get Categories of a Product * description: Get Categories of a Product * tags: [categories] * produces: * - application/json * parameters: * - in: path * name: product_id * required: true * schema: * type: integer * responses: * 200: * description: Return a array of Category Objects * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/CategoryBasic' * 404: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ router.get('/inProduct/:product_id([0-9]+)', categoryController.getProductCategories); /** * Get Categories of a Department * * * @swagger * paths: * /categories/inDepartment/{department_id}: * get: * summary: Get Categories of a Department * description: Get Categories of a Department * tags: [categories] * produces: * - application/json * parameters: * - in: path * name: department_id * required: true * schema: * type: integer * responses: * 200: * description: Return a array of Category Objects * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/Category' * 404: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ router.get('/inDepartment/:department_id([0-9]+)', categoryController.getDepartmentCategories); module.exports = router; <file_sep> exports.sendResponse = function(data, req, res) { // if (typeof data === 'object' && data && ('error' in data)) { res.status(data['error']['status'] || 400).json(data['error']); } else { res.json(data); } }; exports.sendErrorResponse = function(data, req, res) { res.status(data.status).json(data); }; exports.sendValidateResponse = function(errors, ext, req, res) { var error = errors.array()[0]; return exports.sendResponse({ status: 400, code: ext + '_01', message: error.param + ': ' + error.msg }, req, res); }; <file_sep>var Category = require('../db/models/category'); var response = require('./../utils/response.js'); /* Get Categories */ exports.getCategoryList = function(req, res) { Category.getCategoryList().then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Category by ID */ exports.getCategoryById = function(req, res) { Category.getCategoryById(req.params.category_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Categories of a Product */ exports.getProductCategories = function(req, res) { Category.getProductCategories(req.params.product_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Categories of a Department */ exports.getDepartmentCategories = function(req, res) { Category.getDepartmentCategories(req.params.department_id).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var Department = require('../db/models/department'); var response = require('./../utils/response.js'); /* Get Departments */ exports.getDepartmentList = function(req, res) { Department.getDepartmentList().then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Department by ID */ exports.getDepartmentById = function(req, res) { Department.getDepartmentById(req.params.department_id).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var randomstring = require("randomstring"); var db = require('../index'); exports.generateUniqueId = function() { var uniqueId = randomstring.generate(12); return db.knex.raw( 'SELECT cart_id FROM shopping_cart WHERE cart_id = ? LIMIT 1;', [uniqueId]).then(function(data) { if (data[0].length === 0) { // Uniqueid is valid return {cart_id: uniqueId}; // FIXME cache value } return exports.generateUniqueId(); }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.getCartProductList = function(cartId) { return db.knex.raw('CALL shopping_cart_get_products(?);', [cartId]).then(function(data) { data = data[0][0]; return data; }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.addProductToCart = function(cartId, productId, attributes) { try { attributes = JSON.parse(attributes); } catch { attributes = {}; } attributes = JSON.stringify(attributes); return db.knex.raw( 'CALL shopping_cart_add_product(?, ?, ?);', [cartId, productId, attributes]).then(function(data) { return exports.getCartProductList(cartId); }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.updateCartByItem = function(itemId, quantity) { return db.knex.raw('CALL shopping_cart_update(?, ?);', [itemId, quantity]).then(function(data) { return db.knex.raw( 'SELECT cart_id FROM shopping_cart WHERE item_id = ? LIMIT 1;', [itemId]).then(function(data) { return exports.getCartProductList(data[0][0].cart_id); }); }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.emptyCartById = function(cartId) { return db.knex.raw('CALL shopping_cart_empty(?);', [cartId]).then(function(data) { return ; }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.moveProductToCart = function(itemId) { return db.knex.raw('CALL shopping_cart_move_product_to_cart(?);', [itemId]).then(function(data) { return ; }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.saveProductForLater = function(itemId) { return db.knex.raw('CALL shopping_cart_save_product_for_later(?);', [itemId]).then(function(data) { return ; }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.getProductsSavedForLater = function(cartId) { return db.knex.raw('CALL shopping_cart_get_saved_products(?);', [cartId]).then(function(data) { data = data[0][0]; return data; }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.getCartTotalAmount = function(cartId) { return db.knex.raw('CALL shopping_cart_get_total_amount(?);', [cartId]).then(function(data) { data = data[0][0]; return data[0]; }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; exports.removeProductFromCart = function(itemId) { return db.knex.raw('CALL shopping_cart_remove_product(?);', [itemId]).then(function(data) { return ; }).catch(function(reason) { return { error: { status: 400, code: 'CRT_01', message: reason } }; }); }; <file_sep>var response = require('./../utils/response.js'); var Order = require('../db/models/order'); var forms = require('../forms/forms'); /* Create a Order */ exports.createOrder = function(req, res) { var error = forms.validateForm(forms.orderConstraints, req.body, 'ORD'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Order.createOrder( req.customerData.id, req.body.cart_id, req.body.shipping_id, req.body.tax_id, req.customerData.email).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Info about Order */ exports.getOrderInfo = function(req, res) { Order.getOrderInfo(req.params.order_id, req.customerData.id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get orders by Customer */ exports.getCustomerOrders = function(req, res) { Order.getCustomerOrders(req.customerData.id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Info about Order */ exports.getOrderDetails = function(req, res) { Order.getOrderDetails(req.params.orderId, req.customerData.id).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multer(); var authMiddleware = require('../routes/middlewares/auth'); var orderController = require('../controllers/orderController'); /** * @swagger * tags: * - name: orders * description: Everything about orders */ /** * Create a Order * * * @swagger * paths: * /orders: * post: * summary: Create a Order * description: Create a Order * tags: [orders] * produces: * - application/json * security: * - ApiKeyAuth: [] * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * cart_id: * description: Cart ID * type: string * shipping_id: * description: Shipping ID * type: integer * tax_id: * description: Tax ID * type: string * required: * - cart_id * - shipping_id * - tax_id * responses: * 200: * description: Return the Order ID * content: * application/json: * schema: * properties: * orderId: * type: integer * example: 1 * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. * Empty cart id: * code: USR_02 * message: Cart id can't be blank * field: cart_id * status: 400 * Empty shipping id: * code: USR_02 * message: Shipping id can't be blank * field: shipping_id * status: 400 * Invalid shipping id: * code: USR_03 * message: Shipping id is not a number * field: shipping_id * status: 400 * Empty tax id: * code: USR_02 * message: Tax id can't be blank * field: tax_id * status: 400 * Invalid tax id: * code: USR_03 * message: Tax id is not a number * field: tax_id * status: 400 */ router.post('/', [upload.none(), authMiddleware.verifyToken], orderController.createOrder); /* Get Info about Order */ /** * Get Info about Order * * * @swagger * paths: * /orders/{order_id}: * get: * summary: Get Info about Order * description: Get Info about Order * tags: [orders] * produces: * - application/json * security: * - ApiKeyAuth: [] * parameters: * - in: path * name: order_id * required: true * schema: * type: integer * responses: * 200: * description: Return a object of Order. * content: * application/json: * schema: * properties: * order_id: * type: integer * example: 1 * total_amount: * type: string * example: "14.95" * created_on: * type: string * example: "2019-06-12T10:24:31.000Z" * shipped_on: * type: string * example: "2019-06-12T10:24:31.000Z" * status: * type: integer * example: 1 * comments: * type: string * example: "Order # 18" * customer_id: * type: integer * example: 1 * auth_code: * type: string * example: tok_<KEY>" * reference: * type: string * example: "ch_1EkUYzE8uV3JQbVkbkZkkglW" * shipping_id: * type: integer * example: 4 * shipping_type: * type: string * example: "By air (7 days, $25)" * shipping_cost: * type: string * example: 25 * tax_id: * type: integer * example: 2 * tax_type: * type: string * example: "No Tax" * tax_percentage: * type: integer * example: 0 * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. * 403: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 403 * code: ORD_03 * message: Access denied */ router.get('/:order_id([0-9]+)', [authMiddleware.verifyToken], orderController.getOrderInfo); /** * Get orders by Customer * * * @swagger * paths: * /orders/inCustomer: * get: * summary: Get orders by Customer * description: Get orders by Customer * tags: [orders] * produces: * - application/json * security: * - ApiKeyAuth: [] * responses: * 200: * description: Return a array of Orders * content: * application/json: * schema: * $ref: '#/components/schemas/Customer' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. */ router.get('/inCustomer', [authMiddleware.verifyToken], orderController.getCustomerOrders); /** * Get Info about Order * * * @swagger * paths: * /orders/shortDetail/{order_id}: * get: * summary: Get Info about Order * description: Get Info about Order * tags: [orders] * produces: * - application/json * security: * - ApiKeyAuth: [] * parameters: * - in: path * name: order_id * required: true * schema: * type: integer * responses: * 200: * description: Return a object of Order. * content: * application/json: * schema: * properties: * order_id: * type: integer * example: 1 * total_amount: * type: string * example: "14.95" * created_on: * type: string * example: "2019-06-12T10:24:31.000Z" * shipped_on: * type: string * example: "2019-06-12T10:24:31.000Z" * status: * type: integer * example: 1 * name: * type: string * example: "Test" * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. * 403: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 403 * code: ORD_03 * message: Access denied */ router.get('/shortDetail/:orderId([0-9]+)', [authMiddleware.verifyToken], orderController.getOrderDetails); module.exports = router; <file_sep>var Product = require('../db/models/product'); var response = require('./../utils/response.js'); var forms = require('../forms/forms'); /* Get All Products */ exports.getProducts = function(req, res) { Product.getProducts( req.query.page, req.query.limit, req.query.description_length).then(function(data) { response.sendResponse(data, req, res); }); }; /* Search products */ exports.searchProducts = function(req, res) { var error = forms.validateForm(forms.searchConstraints, req.query, 'PRD'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Product.searchProducts( req.query.query_string, req.query.all_words, req.query.page, req.query.limit, req.query.description_length).then(function(data) { response.sendResponse(data, req, res); }); }; /* Product by ID */ exports.getProductById = function(req, res) { Product.getProductInfoById(req.params.product_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get a lit of Products of Categories */ exports.getCategoryProducts = function(req, res) { Product.getCategoryProducts( req.params.category_id, req.query.page, req.query.limit, req.query.description_length).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get a list of Products on Department */ exports.getDepartmentProducts = function(req, res) { Product.getDepartmentProducts( req.params.department_id, req.query.page, req.query.limit, req.query.description_length).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get details of a Product */ exports.getProductDetails = function(req, res) { Product.getProductDetailsById(req.params.product_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get locations of a Product */ exports.getProductLocations = function(req, res) { Product.getProductLocations(req.params.product_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Get reviews of a Product */ exports.getProductReviews = function(req, res) { Product.getProductReviews(req.params.product_id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Add Product Review */ exports.addProductReviews = function(req, res) { var error = forms.validateForm(forms.reviewConstraints, req.query, 'PRD'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Product.addProductReviews( 1 /* FIXME */, req.params.product_id, req.body.review, req.body.rating).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var db = require('../index'); exports.getShippingRegions = function() { return db.knex.raw('CALL customer_get_shipping_regions();').then(function(data) { data = data[0][0]; return {count: data.length, rows: data}; }).catch(function(reason) { return {}; }); }; exports.getShippingRegionById = function(shippingRegionId) { return db.knex.raw('CALL orders_get_shipping_info(?);', [shippingRegionId]).then(function(data) { console.log(data[0]); data = data[0][0]; return data; }).catch(function(reason) { return { error: { status: 404, code: 'REG_01', message: reason } }; }); }; <file_sep>var express = require('express'); var router = express.Router(); var shippingController = require('../controllers/shippingController'); /** * @swagger * tags: * - name: shipping * description: Everything about shipping */ /** * Return shippings regions * * * @swagger * paths: * /shipping/regions: * get: * summary: Return shippings regions * description: Return shippings regions * tags: [shipping] * produces: * - application/json * responses: * 200: * description: Return a list of Shippings Regions * content: * application/json: * schema: * type: array * items: * properties: * shipping_region_id: * type: integer * example: 1 * shipping_region: * type: string * example: Please select */ router.get('/regions', shippingController.getShippingRegions); /** * Get shipping by shipping region ID * * * @swagger * paths: * /shipping/regions/{shipping_region_id}: * get: * summary: Get shipping by shipping region ID * description: Get shipping by shipping region ID * tags: [shipping] * produces: * - application/json * parameters: * - in: path * name: shipping_region_id * required: true * schema: * type: integer * responses: * 200: * description: An object of the shipping region * content: * application/json: * schema: * type: array * items: * properties: * shipping_id: * type: integer * example: 1 * shipping_type: * type: string * example: "Next Day Delivery ($20)" * shipping_cost: * type: string * example: "20" * shipping_region_id: * type: string * example: 2 */ router.get('/regions/:shipping_region_id([0-9]+)', shippingController.getShippingRegionById); module.exports = router; <file_sep>var Tax = require('../db/models/tax'); var response = require('./../utils/response.js'); /* Get All Taxes */ exports.getTaxes = function(req, res) { Tax.getTaxes().then(function(data) { response.sendResponse(data, req, res); }); }; /* Get Tax by ID */ exports.getTaxById = function(req, res) { Tax.getTaxById(req.params.tax_id).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var chai = require('chai'); var assert = require('chai').assert; var chaiHttp = require('chai-http'); var app = require('../app'); // Configure chai chai.use(chaiHttp); chai.should(); describe("Shopping Cart", () => { // Generate a Unique Id describe("GET /shoppingcart/generateUniqueId", () => { it("Generate the unique cart id", (done) => { chai.request(app) .get('/shoppingcart/generateUniqueId') .end((err, res) => { assert.equal(res.status, 200, 'respond with status 200 everytime, no reason for this to fail'); assert.property(res.body, 'cart_id', 'contains the cart id'); done(); }); }); }); }); <file_sep>var express = require('express'); var router = express.Router(); var departmentController = require('../controllers/departmentController'); /** * @swagger * tags: * - name: departments * description: Everything about departments */ /** * @swagger * components: * schemas: * Department: * properties: * department_id: * type: integer * example: 1 * name: * type: string * example: Regional * description: * type: string * example: "Proud of your country? Wear a T-shirt with a national symbol stamp!" */ /** * Get Departments * * * @swagger * paths: * /departments: * get: * summary: Get Departments * description: Get Departments * tags: [departments] * produces: * - application/json * responses: * 200: * description: A Array of Object Department * content: * application/json: * schema: * properties: * count: * type: integer * example: 20 * rows: * type: array * items: * $ref: '#/components/schemas/Department' */ router.get('/', departmentController.getDepartmentList); /** * Get Department by ID * * * @swagger * paths: * /departments/{department_id}: * get: * summary: Get Department by ID * description: Get Department by ID * tags: [departments] * produces: * - application/json * parameters: * - in: path * name: department_id * required: true * schema: * type: integer * responses: * 200: * description: A object of Department * content: * application/json: * schema: * $ref: '#/components/schemas/Department' * 404: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' */ router.get('/:department_id([0-9]+)', departmentController.getDepartmentById); module.exports = router; <file_sep>var mailgun = require("mailgun-js"); var stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY); var db = require('../index'); var mg = mailgun({apiKey: process.env.MAILGUN_API_KEY, domain: process.env.MAILGUN_DOMAIN}); exports.chargeOrder = function(orderId, token, amount, description, currency, email) { return stripe.charges.create({ amount: amount, currency: currency, description: description, source: token }).then(function(data) { var status = 2; if (data.status == 'succeeded') { status = 1; } var reference = data.id; return db.knex.raw( 'CALL orders_update_order(?, ?, ?, ?, ?)', [orderId, status, description, token, reference]).then(function(callData) { var mailData = { from: process.env.FROM_EMAIL_ADDRESS, to: email, subject: 'Payment successfully processed', text: 'Payment for your order has been successfully processed.' }; mg.messages().send(mailData, function (error, body) { }); return data; }).catch(function(reason) { return { error: { status: 400, code: 'STP_03', message: reason } }; }); }); var b = [orderId, status, comments, authCode, reference]; }; <file_sep># www.themba.xyz/v1/docs/ ## Tests `npm test` ## Docs www.themba.xyz/v1/docs/ ## Libraries - express - jsonwebtoken - knex - mailgun-js - randomstring - stripe - swagger-jsdoc - swagger-ui-express - validate.js - chai - mocha <file_sep>var express = require('express'); var multer = require('multer'); var upload = multer(); var router = express.Router(); var authMiddleware = require('../routes/middlewares/auth'); var stripeController = require('../controllers/stripeController'); /** * @swagger * tags: * - name: stripe * description: Everything about stripe */ /** * This method receive a front-end payment and create a chage * * * @swagger * paths: * /stripe/charge: * post: * summary: This method receive a front-end payment and create a chage * description: You can send a cart informations and payment token (https://stripe.com/docs/api/tokens). * tags: [stripe] * produces: * - application/json * security: * - ApiKeyAuth: [] * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * stripeToken: * description: "The API token, you can use this example to get it: https://stripe.com/docs/stripe-js/elements/quickstart" * type: string * order_id: * description: The order ID recorded before (Check the Order Documentation) * type: integer * description: * description: Description of the order * type: string * amount: * description: "Amount in cents, only numbers like: 999" * type: integer * currency: * description: "Check here the options: https://stripe.com/docs/currencies, the default" * type: string * required: * - stripeToken * - order_id * - description * - amount * responses: * 200: * description: Object from Stripe * content: * application/json: * schema: * properties: * orderId: * type: integer * example: 1 * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. * Empty stripe token: * code: USR_02 * message: Stripe token can't be blank * field: stripeToken * status: 400 * Empty order id: * code: USR_02 * message: Order id can't be blank * field: order_id * status: 400 * Invalid order id: * code: USR_03 * message: Order id is not a number * field: order_id * status: 400 * Empty description: * code: USR_02 * message: Description can't be blank * field: description * status: 400 * Empty amount: * code: USR_02 * message: Amount can't be blank * field: amount * status: 400 * Invalid amount: * code: USR_03 * message: Amount is not a number * field: amount * status: 400 */ router.post('/charge', [upload.none(), authMiddleware.verifyToken], stripeController.createCharge); /** * Endpoint that provide a synchronization * * * @swagger * paths: * /stripe/webhooks: * post: * summary: Endpoint that provide a synchronization * description: "You need put this endpoint in the stripe webhooks (https://dashboard.stripe.com/account/webhooks), so get there the end-point secrete key." * tags: [stripe] * produces: * - application/json * responses: * 200: * description: This endpoint is used by Stripe. */ router.post('/webhooks', stripeController.handleWebhooks); module.exports = router; <file_sep>var express = require('express'); var router = express.Router(); var multer = require('multer'); var upload = multer(); var authMiddleware = require('../routes/middlewares/auth'); var productController = require('../controllers/productController'); /** * @swagger * tags: * - name: products * description: Everything about products */ /** * @swagger * components: * schemas: * ProductDetail: * properties: * product_id: * type: integer * example: 10 * name: * type: string * example: Haute Couture * description: * type: string * example: This stamp publicized the dress making industry. Use it to celebrate the T-shirt industry! * price: * type: string * example: "15.99" * discounted_price: * type: string * example: "14.95" * image: * type: string * example: haute-couture.gif * image_2: * type: string * example: haute-couture-2.gif */ /** * @swagger * components: * schemas: * ProductLocations: * properties: * category_id: * type: integer * example: 1 * category_name: * type: string * example: French * department_id: * type: integer * example: 1 * department_name: * type: string * example: Regional */ /** * @swagger * components: * schemas: * Review: * properties: * name: * type: string * example: Example * review: * type: string * example: Example * rating: * type: integer * example: 5 * created_on: * type: string * example: "2019-02-17 13:57:29" */ /** * @swagger * components: * schemas: * ProductComplete: * properties: * product_id: * type: integer * example: 10 * name: * type: string * example: Haute Couture * description: * type: string * example: This stamp publicized the dress making industry. Use it to celebrate the T-shirt industry! * price: * type: string * example: "15.99" * discounted_price: * type: string * example: "14.95" * image: * type: string * example: haute-couture.gif * image_2: * type: string * example: haute-couture-2.gif * thumbnail: * type: string * example: haute-couture-thumbnail.gif * display: * type: integer * example: 0 */ /** * @swagger * components: * schemas: * Product: * properties: * product_id: * type: integer * example: 10 * name: * type: string * example: Haute Couture * description: * type: string * example: This stamp publicized the dress making industry. Use it to celebrate the T-shirt industry! * price: * type: string * example: "15.99" * discounted_price: * type: string * example: "14.95" * thumbnail: * type: string * example: haute-couture-thumbnail.gif */ /** * Get All Products * * * @swagger * paths: * /products: * get: * summary: Get All Products * description: Get All Products * tags: [products] * produces: * - application/json * parameters: * - in: query * name: page * schema: * type: integer * description: "Inform the page. Starting with 1. Default: 1" * - in: query * name: limit * schema: * type: integer * description: "Limit per page, Default: 20." * - in: query * name: description_length * schema: * type: integer * description: "Limit of the description, Default: 200." * responses: * 200: * description: Return the total of products and a list of Products in row. * content: * application/json: * schema: * properties: * count: * type: integer * example: 20 * rows: * type: array * items: * $ref: '#/components/schemas/Product' */ router.get('/', productController.getProducts); /** * Search products * * * @swagger * paths: * /products/search: * get: * summary: Search products * description: Search products * tags: [products] * produces: * - application/json * parameters: * - in: query * name: query_string * required: true * schema: * type: string * description: "Query to search" * - in: query * name: all_words * schema: * type: string * description: "All words or no. Default: on" * - in: query * name: page * schema: * type: integer * description: "Inform the page. Starting with 1. Default: 1" * - in: query * name: limit * schema: * type: integer * description: "Limit per page, Default: 20." * - in: query * name: description_length * schema: * type: integer * description: "Limit of the description, Default: 200." * responses: * 200: * description: Return the total of products and a list of Products in row. * content: * application/json: * schema: * properties: * count: * type: integer * example: 20 * rows: * type: array * items: * $ref: '#/components/schemas/Product' */ router.get('/search', productController.searchProducts); /** * Product by ID * * * @swagger * paths: * /products/{product_id}: * get: * summary: Product by ID * description: Product by ID * tags: [products] * produces: * - application/json * parameters: * - in: path * name: product_id * required: true * schema: * type: integer * responses: * 200: * description: Return a complete Product Object * content: * application/json: * schema: * $ref: '#/components/schemas/ProductComplete' * 404: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * Product not found: * status: 404 * code: PRO_03 * message: The product with this ID does not exist. */ router.get('/:product_id([0-9]+)', productController.getProductById); /** * Get a lit of Products of Categories * * * @swagger * paths: * /products/inCategory/{category_id}: * get: * summary: Get a lit of Products of Categories * description: Get a lit of Products of Categories * tags: [products] * produces: * - application/json * parameters: * - in: path * name: category_id * required: true * schema: * type: string * description: "Category ID" * - in: query * name: page * schema: * type: integer * description: "Inform the page. Starting with 1. Default: 1" * - in: query * name: limit * schema: * type: integer * description: "Limit per page, Default: 20." * - in: query * name: description_length * schema: * type: integer * description: "Limit of the description, Default: 200." * responses: * 200: * description: Return a list of Product Objects * content: * application/json: * schema: * properties: * count: * type: integer * example: 20 * rows: * type: array * items: * $ref: '#/components/schemas/Product' */ router.get('/inCategory/:category_id([0-9]+)', productController.getCategoryProducts); /** * Get a list of Products on Department * * * @swagger * paths: * /products/inDepartment/{department_id}: * get: * summary: Get a list of Products on Department * description: Get a list of Products on Department * tags: [products] * produces: * - application/json * parameters: * - in: path * name: department_id * required: true * schema: * type: string * description: "Department ID" * - in: query * name: page * schema: * type: integer * description: "Inform the page. Starting with 1. Default: 1" * - in: query * name: limit * schema: * type: integer * description: "Limit per page, Default: 20." * - in: query * name: description_length * schema: * type: integer * description: "Limit of the description, Default: 200." * responses: * 200: * description: Return a list of Product Objects * content: * application/json: * schema: * properties: * count: * type: integer * example: 20 * rows: * type: array * items: * $ref: '#/components/schemas/Product' */ router.get('/inDepartment/:department_id([0-9]+)', productController.getDepartmentProducts); /** * Get details of a Product * * * @swagger * paths: * /products/{product_id}/details: * get: * summary: Get details of a Product * description: Get details of a Product * tags: [products] * produces: * - application/json * parameters: * - in: path * name: product_id * required: true * schema: * type: integer * responses: * 200: * description: Return a Product Detail Object * content: * application/json: * schema: * $ref: '#/components/schemas/ProductDetail' * 404: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * Product not found: * status: 404 * code: PRO_03 * message: The product with this ID does not exist. */ router.get('/:product_id([0-9]+)/details', productController.getProductDetails); /** * Get locations of a Product * * * @swagger * paths: * /products/{product_id}/locations: * get: * summary: Get locations of a Product * description: Get locations of a Product * tags: [products] * produces: * - application/json * parameters: * - in: path * name: product_id * required: true * schema: * type: integer * description: Product ID * responses: * 200: * description: Return locations of products. * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/ProductLocations' */ router.get('/:product_id([0-9]+)/locations', productController.getProductLocations); /** * Get reviews of a Product * * * @swagger * paths: * /products/{product_id}/reviews: * get: * summary: Get reviews of a Product * description: Get reviews of a Product * tags: [products] * produces: * - application/json * parameters: * - in: path * name: product_id * required: true * schema: * type: integer * description: Product ID * responses: * 200: * description: Return a list of reviews * content: * application/json: * schema: * type: array * items: * $ref: '#/components/schemas/Review' */ router.get('/:product_id([0-9]+)/reviews', productController.getProductReviews); /** * Add Product Review * * * @swagger * paths: * /products/{product_id}/reviews: * post: * summary: Add Product Review * description: Add Product Review * tags: [products] * produces: * - application/json * security: * - ApiKeyAuth: [] * parameters: * - in: path * name: product_id * required: true * schema: * type: integer * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * product_id: * description: Product ID * type: integer * review: * description: Review text of product * type: string * rating: * description: Rating of product * type: integer * required: * - product_id * - review * - rating * responses: * 200: * description: No data. * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. */ router.post('/:product_id([0-9]+)/reviews', [upload.none(), authMiddleware.verifyToken], productController.addProductReviews); module.exports = router; <file_sep>var express = require('express'); var multer = require('multer'); var upload = multer(); var router = express.Router(); var authMiddleware = require('../routes/middlewares/auth'); var customerController = require('../controllers/customerController'); /** * Update a customer * * * @swagger * paths: * /customer: * put: * summary: Update a customer * description: Update a customer * tags: [customers] * produces: * - application/json * security: * - ApiKeyAuth: [] * requestBody: * required: true * content: * application/x-www-form-urlencoded: * schema: * type: object * properties: * name: * description: Customer's name. * type: string * email: * description: Customer's email. * type: string * password: * description: Customer's password. * type: string * day_phone: * description: Customer's day phone. * type: string * eve_phone: * description: Customer's eve phone. * type: string * mob_phone: * description: Customer's mob phone. * type: string * required: * - name * - email * responses: * 200: * description: Return a Customer object * content: * application/json: * schema: * $ref: '#/components/schemas/Customer' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. * Empty name: * code: USR_02 * message: Name can't be blank * field: name * status: 400 * Empty email: * code: USR_02 * message: Email can't be blank * field: email * status: 400 * Invalid email: * code: USR_03 * message: Email is not a valid email * field: email * status: 400 * Invalid day phone: * code: USR_03 * message: Day phone format invalid, only numeric values allowed * field: day_phone * status: 400 * Invalid eve phone: * code: USR_03 * message: Eve phone format invalid, only numeric values allowed * field: eve_phone * status: 400 * Invalid mob phone: * code: USR_03 * message: Mob phone format invalid, only numeric values allowed * field: mob_phone * status: 400 */ router.put('/', [upload.none(), authMiddleware.verifyToken], customerController.updateCustomer); /** * Get a customer by ID. The customer is getting by Token. * * * @swagger * paths: * /customer: * get: * summary: Get a customer * description: Get a customer * tags: [customers] * produces: * - application/json * security: * - ApiKeyAuth: [] * responses: * 200: * description: Return a Customer object * content: * application/json: * schema: * $ref: '#/components/schemas/Customer' * 400: * description: Returns an error object * content: * application/json: * schema: * $ref: '#/components/schemas/Error' * examples: * User Key empty: * status: 401 * code: AUT_01 * message: Authorization code is empty. * User Key invalid: * status: 401 * code: AUT_02 * message: Access Unauthorized. */ router.get('/', [authMiddleware.verifyToken], customerController.getCustomer); module.exports = router; <file_sep>var createError = require('http-errors'); var express = require('express'); var cors = require('cors'); var swaggerUi = require('swagger-ui-express'); var swaggerJSDoc = require('swagger-jsdoc'); var bodyParser = require('body-parser'); var multer = require('multer'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); require('dotenv').config(); var categoriesRouter = require('./routes/categories'); var departmentsRouter = require('./routes/departments'); var attributesRouter = require('./routes/attributes'); var productsRouter = require('./routes/products'); var customersRouter = require('./routes/customers'); var customerRouter = require('./routes/customer'); var ordersRouter = require('./routes/orders'); var shoppingcartRouter = require('./routes/shoppingcart'); var shippingRouter = require('./routes/shipping'); var stripeRouter = require('./routes/stripe'); var taxRouter = require('./routes/tax'); var authMiddleware = require('./routes/middlewares/auth'); var app = express(); // CORS app.use(cors()); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'twig'); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded // // https://stackoverflow.com/a/12008719 app.use(logger('dev')); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(authMiddleware.extractToken); var swaggerOptions = { definition: { openapi: "3.0.2", info: { title: 'T-Shirt Shop API', version: '1.0.0' }, servers: [{ url: '/' + process.env.API_VERSION + '/' }] }, apis: ['./routes/*.js'] }; // Initialize swagger-jsdoc -> returns validated swagger spec in json format var swaggerSpec = swaggerJSDoc(swaggerOptions); app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); app.use('/categories', categoriesRouter); app.use('/departments', departmentsRouter); app.use('/attributes', attributesRouter); app.use('/products', productsRouter); app.use('/customers', customersRouter); app.use('/customer', customerRouter); app.use('/orders', ordersRouter); app.use('/shoppingcart', shoppingcartRouter); app.use('/shipping', shippingRouter); app.use('/stripe', stripeRouter); app.use('/tax', taxRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; var port = 3000; var server = app.listen(port, () => { console.log(`Listening on http://localhost:${port}`); }); <file_sep>var validate = require("validate.js"); var loginConstraints = { email: { presence: {allowEmpty: false}, email: true }, password: { presence: {allowEmpty: false} } }; exports.loginConstraints = loginConstraints; var facebookLoginConstraints = { access_token: { presence: {allowEmpty: false} } }; exports.facebookLoginConstraints = facebookLoginConstraints; var registerConstraints = { name: { presence: {allowEmpty: false} }, email: { presence: {allowEmpty: false}, email: true }, password: { presence: {allowEmpty: false} } }; exports.registerConstraints = registerConstraints; var customerConstraints = { name: { presence: {allowEmpty: false} }, email: { presence: {allowEmpty: false}, email: true }, day_phone: { presence: false, format: { pattern: /(\+?\d{6,22})?/, message: "format invalid, only numeric values allowed" } }, eve_phone: { presence: false, format: { pattern: /(\+?\d{6,22})?/, message: "format invalid, only numeric values allowed" } }, mob_phone: { presence: false, format: { pattern: /(\+?\d{6,22})?/, message: "format invalid, only numeric values allowed" } }, password: { presence: false } }; exports.customerConstraints = customerConstraints; var addressConstraints = { address_1: { presence: {allowEmpty: false} }, city: { presence: {allowEmpty: false} }, region: { presence: {allowEmpty: false} }, postal_code: { presence: {allowEmpty: false} }, country: { presence: {allowEmpty: false} }, shipping_region_id: { presence: {allowEmpty: false}, numericality: {onlyInteger: true} } }; exports.addressConstraints = addressConstraints; var creditCardConstraints = { credit_card: { presence: {allowEmpty: false} } }; exports.creditCardConstraints = creditCardConstraints; var orderConstraints = { cart_id: { presence: {allowEmpty: false} }, shipping_id: { presence: {allowEmpty: false}, numericality: {onlyInteger: true} }, tax_id: { presence: {allowEmpty: false}, numericality: {onlyInteger: true} } }; exports.orderConstraints = orderConstraints; var cartConstraints = { cart_id: { presence: {allowEmpty: false} }, product_id: { presence: {allowEmpty: false}, numericality: {onlyInteger: true} }, attributes: { presence: {allowEmpty: false} } }; exports.cartConstraints = cartConstraints; var reviewConstraints = { product_id: { presence: {allowEmpty: false} }, review: { presence: {allowEmpty: false} }, rating: { presence: {allowEmpty: false}, numericality: {onlyInteger: true} } }; exports.reviewConstraints = reviewConstraints; var updateItemConstraints = { quantity: { presence: {allowEmpty: false}, numericality: {onlyInteger: true} } }; exports.updateItemConstraints = updateItemConstraints; var searchConstraints = { query_string: { presence: {allowEmpty: false} } }; exports.searchConstraints = searchConstraints; var stripeConstraints = { stripeToken: { presence: {allowEmpty: false} }, order_id: { presence: {allowEmpty: false}, numericality: {onlyInteger: true} }, description: { presence: {allowEmpty: false} }, amount: { presence: {allowEmpty: false}, numericality: {onlyInteger: true} } }; exports.stripeConstraints = stripeConstraints; function validateForm(constraints, data, section) { var errors = validate(data, constraints, {format: "detailed"}); section = section || 'GEN'; if (errors) { var error = errors[0]; var errorResponse = { code: error.validator == 'presence' ? section + '_02' : section + '_03', message: error.error, field: error.attribute, status: 400 }; return errorResponse; } return false; } exports.validateForm = validateForm; <file_sep>var db = require('../index'); exports.getProducts = function(page, limit, descriptionLength) { page = parseInt(page) || 1; limit = parseInt(limit) || 20; descriptionLength = parseInt(descriptionLength) || 200; var startItem = (page - 1) * limit; return db.knex.raw('CALL catalog_count_products_on_catalog();', []).then(function(data) { var productsCount = data[0][0][0]['products_on_catalog_count']; return db.knex.raw( 'CALL catalog_get_products_on_catalog(?, ?, ?);', [descriptionLength, limit, startItem]).then(function(data) { data = data[0][0]; return {count: productsCount, rows: data}; }).catch(function(reason) { return {}; }); }); }; exports.searchProducts = function(searchString, allWords, page, limit, descriptionLength) { if (searchString === undefined || searchString === '') { // Query string is a required field return Promise.resolve({ error: { status: 400, code: 'PRO_01', message: 'A search string is required.' } }); } allWords = allWords === 'off' ? allWords : 'on'; page = parseInt(page) || 1; limit = parseInt(limit) || 20; descriptionLength = parseInt(descriptionLength) || 200; var startItem = (page - 1) * limit; return db.knex.raw( 'CALL catalog_count_search_result(?, ?);', [searchString, allWords]).then(function(data) { var productsCount = data[0][0][0]['count(*)']; console.log([searchString, allWords, descriptionLength, limit, startItem]); return db.knex.raw( 'CALL catalog_search(?, ?, ?, ?, ?);', [searchString, allWords, descriptionLength, limit, startItem]).then(function(data) { data = data[0][0]; return {count: productsCount, rows: data}; }).catch(function(reason) { return {}; }); }); }; exports.getProductDetailsById = function(productId) { return db.knex.raw('CALL catalog_get_product_details(?);', [productId]).then(function(data) { data = data[0][0]; if (data.length === 0) { // Not found throw 'The product with this ID does not exist.'; } return data[0]; }).catch(function(reason) { return { error: { status: 404, code: 'PRO_01', message: reason } }; }); }; exports.getProductInfoById = function(productId) { return db.knex.raw('CALL catalog_get_product_info(?);', [productId]).then(function(data) { data = data[0][0]; if (data.length === 0) { // Not found throw 'The product with this ID does not exist.'; } return data[0]; }).catch(function(reason) { return { error: { status: 404, code: 'PRO_01', message: reason } }; }); }; exports.getCategoryProducts = function(categoryId, page, limit, descriptionLength) { page = parseInt(page) || 1; limit = parseInt(limit) || 20; descriptionLength = parseInt(descriptionLength) || 200; var startItem = (page - 1) * limit; return db.knex.raw( 'CALL catalog_count_products_in_category(?);', [categoryId]).then(function(data) { var productsCount = data[0][0][0]['categories_count']; return db.knex.raw( 'CALL catalog_get_products_in_category(?, ?, ?, ?);', [categoryId, descriptionLength, limit, startItem]).then(function(data) { data = data[0][0]; return {count: productsCount, rows: data}; }).catch(function(reason) { return {}; }); }); }; exports.getDepartmentProducts = function(departmentId, page, limit, descriptionLength) { page = parseInt(page) || 1; limit = parseInt(limit) || 20; descriptionLength = parseInt(descriptionLength) || 200; var startItem = (page - 1) * limit; return db.knex.raw( 'CALL catalog_count_products_on_department(?);', [departmentId]).then(function(data) { var productsCount = data[0][0][0]['products_on_department_count']; return db.knex.raw( 'CALL catalog_get_products_on_department(?, ?, ?, ?);', [departmentId, descriptionLength, limit, startItem]).then(function(data) { data = data[0][0]; return {count: productsCount, rows: data}; }).catch(function(reason) { return {}; }); }); }; exports.getProductLocations = function(productId) { return db.knex.raw('CALL catalog_get_product_locations(?);', [productId]).then(function(data) { data = data[0][0]; return data; }).catch(function(reason) { return {}; }); }; exports.getProductReviews = function(productId) { return db.knex.raw('CALL catalog_get_product_reviews(?);', [productId]).then(function(data) { data = data[0][0]; return data; }).catch(function(reason) { return {}; }); }; exports.addProductReviews = function(customerId, productId, review, rating) { return db.knex.raw( 'CALL catalog_create_product_review(?, ?, ?, ?);', [customerId, productId, review, rating]).then(function(data) { data = data[0][0]; return ; }).catch(function(reason) { return {}; }); }; <file_sep>var response = require('./../utils/response.js'); var Customer = require('../db/models/customer'); var forms = require('../forms/forms'); /* Update a customer */ exports.updateCustomer = function(req, res) { var error = forms.validateForm(forms.customerConstraints, req.body, 'USR'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Customer.updateCustomer( req.customerData.id, req.body.name || '', req.body.email || '', req.body.password || <PASSWORD>, req.body.day_phone || '', req.body.eve_phone || '', req.body.mob_phone || '' ).then(function(data) { res.json(data); }); }; /* Get a customer by ID. The customer is getting by Token. */ exports.getCustomer = function(req, res) { Customer.getCustomerInfoById(req.customerData.id).then(function(data) { response.sendResponse(data, req, res); }); }; /* Register a Customer */ exports.registerCustomer = function(req, res) { var error = forms.validateForm(forms.registerConstraints, req.body, 'USR'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Customer.registerCustomer(req.body.name, req.body.email, req.body.password).then(function(data) { response.sendResponse(data, req, res); }); }; /* Sign in in the Shopping. */ exports.loginCustomer = function(req, res) { var error = forms.validateForm(forms.loginConstraints, req.body, 'USR'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Customer.loginCustomer(req.body.email, req.body.password).then(function(data) { response.sendResponse(data, req, res); }); }; /* Sign in with a facebook login token. */ exports.facebookLoginCustomer = function(req, res) { var error = forms.validateForm(forms.facebookLoginConstraints, req.body, 'USR'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Customer.facebookLoginCustomer(req.body.access_token).then(function(data) { response.sendResponse(data, req, res); }); }; /* Update the address from customer */ exports.updateCustomerAddress = function(req, res) { var error = forms.validateForm(forms.addressConstraints, req.body, 'USR'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Customer.updateCustomerAddress( req.customerData.id, req.body.address_1 || '', req.body.address_2 || '', req.body.city || '', req.body.region || '', req.body.postal_code || '', req.body.country || '', req.body.shipping_region_id || '' ).then(function(data) { res.json(data); }); }; /* Update credit card */ exports.updateCustomerCreditCard = function(req, res) { var error = forms.validateForm(forms.creditCardConstraints, req.body, 'USR'); if (error !== false) { return response.sendErrorResponse(error, req, res); } Customer.updateCustomerCreditCard(req.customerData.id, req.body.credit_card).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var Shipping = require('../db/models/shipping'); var response = require('./../utils/response.js'); /* Return shippings regions */ exports.getShippingRegions = function(req, res) { Shipping.getShippingRegions().then(function(data) { response.sendResponse(data, req, res); }); }; /* Return shippings regions */ exports.getShippingRegionById = function(req, res) { Shipping.getShippingRegionById(req.params.shipping_region_id).then(function(data) { response.sendResponse(data, req, res); }); }; <file_sep>var chai = require('chai'); var assert = require('chai').assert; var chaiHttp = require('chai-http'); var app = require('../app'); // Configure chai chai.use(chaiHttp); chai.should(); describe("Stripe", () => { it("Charge order on stripe with an empty stripe token", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Charge order chai.request(app) .post('/stripe/charge') .set('User-Key', res.body.accessToken) .send({}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the stripe token field is empty'); assert.equal(res.body.field, 'stripeToken', 'display failed field'); assert.equal(res.body.code, 'STP_02', 'STP_02 code for a required stripe field'); done(); }); }); }); it("Charge order on stripe with an empty order id", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Charge order chai.request(app) .post('/stripe/charge') .set('User-Key', res.body.accessToken) .send({stripeToken: new Date().getTime()}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the order id field is empty'); assert.equal(res.body.field, 'order_id', 'display failed field'); assert.equal(res.body.code, 'STP_02', 'STP_02 code for a required stripe field'); done(); }); }); }); it("Charge order on stripe with an invalid order id", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Charge order chai.request(app) .post('/stripe/charge') .set('User-Key', res.body.accessToken) .send({stripeToken: new Date().getTime(), order_id: 'invalid'}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the order id field is invalid'); assert.equal(res.body.field, 'order_id', 'display failed field'); assert.equal(res.body.code, 'STP_03', 'STP_03 code for a required stripe field'); done(); }); }); }); it("Charge order on stripe with an empty description", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Charge order chai.request(app) .post('/stripe/charge') .set('User-Key', res.body.accessToken) .send({stripeToken: new Date().getTime(), order_id: 1}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the description field is empty'); assert.equal(res.body.field, 'description', 'display failed field'); assert.equal(res.body.code, 'STP_02', 'STP_02 code for a required stripe field'); done(); }); }); }); it("Charge order on stripe with an empty amount", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Charge order chai.request(app) .post('/stripe/charge') .set('User-Key', res.body.accessToken) .send({stripeToken: new Date().getTime(), order_id: 1, description: new Date().getTime()}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the amount field is empty'); assert.equal(res.body.field, 'amount', 'display failed field'); assert.equal(res.body.code, 'STP_02', 'STP_02 code for a required stripe field'); done(); }); }); }); it("Charge order on stripe with an invalid amount", (done) => { // Login first chai.request(app) .post('/customers/login') .send({email: process.env.TEST_USER_EMAIL, password: <PASSWORD>}) .end((err, res) => { // Charge order chai.request(app) .post('/stripe/charge') .set('User-Key', res.body.accessToken) .send({stripeToken: new Date().getTime(), order_id: 1, description: new Date().getTime(), amount: 'invalid'}) .end((err, res) => { assert.equal(res.status, 400, 'respond with status 400 when the amount field is invalid'); assert.equal(res.body.field, 'amount', 'display failed field'); assert.equal(res.body.code, 'STP_03', 'STP_03 code for an invalid stripe field'); done(); }); }); }); }); <file_sep>var response = require('./../utils/response.js'); var StripePayment = require('../db/models/stripe'); var forms = require('../forms/forms'); /* This method receive a front-end payment and create a chage. */ exports.createCharge = function(req, res) { var error = forms.validateForm(forms.stripeConstraints, req.body, 'STP'); if (error !== false) { return response.sendErrorResponse(error, req, res); } StripePayment.chargeOrder( req.body.order_id, req.body.stripeToken, req.body.amount, req.body.description, req.body.currency, req.customerData.email).then(function(data) { response.sendResponse(data, req, res); }); }; /* Endpoint that provide a synchronization */ exports.handleWebhooks = function(req, res) { response.sendResponse({ title: 'Endpoint that provide a synchronization' }, req, res); };
8cde6e08faeff97896a45f546ec1087462c43f43
[ "JavaScript", "SQL", "Markdown" ]
34
SQL
sibande/tshirtshop-api
28bfa0d42b21505a12b66750d8c355afc80e24f0
3ff9edfa91b32b2be89adfd54c1edb081e930120
refs/heads/master
<repo_name>koolmint/dproid<file_sep>/README.md # dproid under development <file_sep>/android/src/org/koolmint/dproid/ViewArticleFragment.java package org.koolmint.dproid; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import android.app.Fragment; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class ViewArticleFragment extends Fragment { public static final String ARG_WR_ID="org.koolmint.dproid.wr_id"; public static final String PAGE_URL="http://dvdprime.donga.com/g5/bbs/board.php?bo_table=comm&wr_id="; public static final String TAG="org.koolmint.dproid"; private TextView testTextView; private Handler hndl=new Handler(); private StringBuilder buff; private ProgressDialog progressDlg; private String content; @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View v=inflater.inflate(R.layout.fragment_view_article, parent, false); testTextView=(TextView)v.findViewById(R.id.test_text_view); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args=getArguments(); final String targetURL=PAGE_URL + args.getInt(ARG_WR_ID); buff=new StringBuilder(); progressDlg=ProgressDialog.show(getActivity(), null, "wait..."); progressDlg.show(); new Thread(new Runnable() { @Override public void run() { try { HttpURLConnection conn=(HttpURLConnection)new URL(targetURL).openConnection(); conn.setUseCaches(false);; conn.setReadTimeout(10*1000); conn.setRequestProperty("User-Agent", "Mozilla/5.0"); if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String line=""; while((line=reader.readLine()) != null) buff.append(line); } else { // not HTTP_OK } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Document doc=Jsoup.parse(buff.toString()); final Element title=doc.select("h1#bo_v_title").first(); Element author=doc.select("a.sv_member").first(); Pattern p=Pattern.compile("<!-- 본문 내용 시작 \\{ -->(.*?)<!-- \\} 본문 내용 끝 -->"); Matcher m=p.matcher(buff.toString()); if(m.find()) { content=m.group(1).replaceAll("<div id=\"bo_v_con\"></div>", "").trim(); content=content.replaceAll("<p>", "").replaceAll("</p>", "\\\n"); } hndl.post(new Runnable() { @Override public void run() { testTextView.setText(content); if(progressDlg.isShowing()) progressDlg.dismiss(); } }); } }).start(); } public static ViewArticleFragment newInstance(int wr_id) { Bundle args=new Bundle(); args.putInt(ARG_WR_ID, wr_id); ViewArticleFragment fragment=new ViewArticleFragment(); fragment.setArguments(args); return fragment; } }
f6184e3199e321576c71ca60180ed00751b4a535
[ "Markdown", "Java" ]
2
Markdown
koolmint/dproid
744e1d6708b0aff78dae637e3b40e8c276b2a3da
204324dfa1011fe16f60da08730b54b3b6f0b910
refs/heads/master
<repo_name>bastiaanschonhage/docker-rabbitmq-cluster<file_sep>/README.adoc Thanks to <NAME> https://github.com/bijukunjummen for most of the work. I have just updated it to RabbitMQ 3.8 (with Erlang 22.2 and CentOS 8.3) This folder structure contains the Dockerfiles for building RabbitMQ cluster - the number of nodes are completely customizable using https://docs.docker.com/compose/[docker-compose] docker-compose.yml file. Structure: ========== There are 3 folders. 1. base - this is the base Dockerfile which builds on a CentOS image and installs the RabbitMQ binaries on the image 2. server - This builds on the base image and has the startup script for bring up a RabbitMQ server 4. cluster - This contains a https://docs.docker.com/compose/[docker-compose] definition file(docker-compose.yml) for brining up the rabbitmq cluster. Use `docker-compose up -d` to bring up the cluster. Building the Images: =============================== Just run the `build-images.sh` script to create the RabbitMQ docker container images. Running the Cluster: =============================== Once the images are built, boot up the cluster using the `docker-compose.yml` configuration provided in cluster folder: [source] ---- cd cluster docker-compose up -d ---- By default 3 nodes are started up this way see `docker-compose.yml` If needed, additional nodes can be added to this file. If the entire cluster comes up, the management console can be accessed at http://<dockerip>:15672 and http://<dockerip>:15673 (also works for `localhost`) The username/password are specified in `docker-compose.yml`: `myuser/mypass` and the connection host should look like this: `dockerip:5672,dockerip:5673,dockerip:5674` <file_sep>/base/Dockerfile FROM centos:8 RUN yum install -y wget unzip tar RUN rpm -Uvh https://github.com/rabbitmq/erlang-rpm/releases/download/v22.2.1/erlang-22.2.1-1.el8.x86_64.rpm RUN yum install -y erlang RUN rpm --import http://www.rabbitmq.com/rabbitmq-signing-key-public.asc RUN yum install -y https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.8.2/rabbitmq-server-3.8.2-1.el8.noarch.rpm RUN /usr/sbin/rabbitmq-plugins list <<<'y' RUN /usr/sbin/rabbitmq-plugins enable --offline rabbitmq_mqtt rabbitmq_stomp rabbitmq_management rabbitmq_management_agent rabbitmq_federation rabbitmq_federation_management <<<'y' #CMD /usr/sbin/rabbitmq-server <file_sep>/build-images.sh TAG="3.8.2" docker build -t bastiaanschonhage/rabbitmq-base:$TAG base docker build -t bastiaanschonhage/rabbitmq-server:$TAG server
bd0f20621bfbff809ad90f98f95691cfb163b188
[ "Dockerfile", "AsciiDoc", "Shell" ]
3
AsciiDoc
bastiaanschonhage/docker-rabbitmq-cluster
d9d8bfd8517102d74df878acc94f0327f1d71be3
e01d06c556c6fa831857fb0efff6fb984d74af98
refs/heads/master
<repo_name>cloudwrokgroup/thy<file_sep>/src/main/resources/application.properties server.port=9090 spring.thymeleaf.cache=false spring.thymeleaf.enabled=true spring.devtools.restart.enabled=true spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/blog_db?characterEncoding=utf8&createDatabaseIfNotExist=true&verifyServerCertificate=false&useSSL=false&requireSSL=false spring.datasource.username=admin spring.datasource.password=<PASSWORD> spring.jpa.properties.hibernate.hbm2ddl.auto=update<file_sep>/src/main/java/com/demo/persistence/Testing.java package com.demo.persistence; public class Testing { }
3b06baa51e31751899d9efdab63b1cb970b68fa5
[ "Java", "INI" ]
2
INI
cloudwrokgroup/thy
55f5d120aa4f1308c56369bbe9c7e0b2b836dc6e
210b83380297934db174ba239c2877a214af7730
refs/heads/master
<repo_name>JulianGombos/ConsoleGame<file_sep>/ConsoleGame/ClassBase.h #pragma once #include <string> using namespace std; class ClassBase { private: protected: string className; int healthModifier, attackModifier, defenseModifier, speedModifier; public: ClassBase(); ClassBase(int, int, int, int); ~ClassBase(); virtual void setHealthModifier(int) = 0; virtual void setAttackModifier(int) = 0; virtual void setDefenseModifier(int) = 0; virtual void setSpeedModifier(int) = 0; virtual string getClassName() = 0; virtual int getHealthModifier() = 0; virtual int getAttackModifier() = 0; virtual int getDefenseModifier() = 0; virtual int getSpeedModifier() = 0; };<file_sep>/ConsoleGame/player.h #pragma once #include <string> #include "ClassBase.h" #include "Warrior.h" #include "Inventory.h" using namespace std; class Player { private: const int DEFAULT_PLAYER_HEALTH = 10; const int DEFAULT_PLAYER_ATTACK = 10; const int DEFAULT_PLAYER_DEFENSE = 10; const int DEFAULT_PLAYER_SPEED = 10; string name; int health, attack, defense, speed, money; ClassBase* playerClass; Inventory* playerInventory; public: Player(); Player(Player*); Player(string); Player(string, int); //This can be expanded if more player defined properties are created that are set up in character creation ~Player(); //Mutators for player stats void setHealth(int); void setAttack(int); void setDefense(int); void setSpeed(int); void setMoney(int); //Mutator for player class void setClass(int); //Accessor for player name const string getName(); //Accessors for current player stats const int getHealth(); const int getAttack(); const int getDefense(); const int getSpeed(); const int getMoney(); //Accessors for default player stats const int getDefaultHealth(); const int getDefaultAttack(); const int getDefaultDefense(); const int getDefaultSpeed(); //Accessor for player inventory Inventory* getPlayerInventory(); //Accessor for player class ClassBase* getClass(); //Accessor for player class name const string getClassName(); }; <file_sep>/ConsoleGame/player.cpp #include "player.h" Player::Player() { name = "null"; health = 10; attack = 10; defense = 10; speed = 10; playerInventory = new Inventory(); } Player::Player(Player *tempPlayer) { this->name = tempPlayer->name; this->health = tempPlayer->health; this->attack = tempPlayer->attack; this->defense = tempPlayer->defense; this->speed = tempPlayer->speed; this->money = tempPlayer->money; this->playerClass = tempPlayer->playerClass; this->playerInventory = tempPlayer->playerInventory; } Player::Player(string tempName) { name = tempName; playerInventory = new Inventory(); } Player::Player(string tempName, int classSelection) { playerInventory = new Inventory(); name = tempName; switch (classSelection) { case 0: {playerClass = new Warrior(); } } } Player::~Player() { delete playerClass; delete playerInventory; } void Player::setHealth(int x) { health = x; } void Player::setAttack(int x) { attack = x; } void Player::setDefense(int x) { defense = x; } void Player::setSpeed(int x) { speed = x; } void Player::setMoney(int x) { money += x; } void Player::setClass(int x) { switch (x) { case 0: playerClass = new Warrior(); } } const string Player::getName() { return name; } const int Player::getHealth() { return health; } const int Player::getAttack() { return attack; } const int Player::getDefense() { return defense; } const int Player::getSpeed() { return speed; } const int Player::getMoney() { return money; } const int Player::getDefaultHealth() { return DEFAULT_PLAYER_HEALTH; } const int Player::getDefaultAttack() { return DEFAULT_PLAYER_ATTACK; } const int Player::getDefaultDefense() { return DEFAULT_PLAYER_DEFENSE; } const int Player::getDefaultSpeed() { return DEFAULT_PLAYER_SPEED; } Inventory * Player::getPlayerInventory() { return playerInventory; } ClassBase* Player::getClass() { return playerClass; } const string Player::getClassName() { return playerClass->getClassName(); } <file_sep>/ConsoleGame/main.cpp //C++ library includes #include <iostream> #include <math.h> #include <conio.h> #include <stdlib.h> #include <string> #include <fstream> //User defined class includes #include "player.h" #include "Shop.h" //User defined library full of static functions #include "StaticsLibrary.h" //User defined global resources #include "GlobalResources.h" //User defined features related to the engine of the game #include "Engine.h" using namespace std; //Functions that handles all initial startup events when game is launched Player* startup(); //Function that imports and prints title screen to console void titleScreen(); //Function that handles character creation setup Player* characterCreation(); //Function adds some default items to the player's inventory. Currently those items are based on the warrior class void addDefaultGameItems(Player*, Shop*); //Function displays introduction story void intro(); //Initializing the engine Engine* engine = new Engine(); int main() { Player* player; Shop* gameShop = new Shop(); //player = startup(); player = new Player(startup()); addDefaultGameItems(player, gameShop); Statics::pause(); //Main game loop //Realistically, there probably wont be a game loop. Everything is going to follow a particular order. //The only "game loops" there will be are for battles since combat will constantly loop until its over while (!engine->getQuit()) { } Statics::pause("Press any key to exit the game..."); return 0; } Player* startup() { Statics::clearScreen(); titleScreen(); intro(); //This needs to be cleaned up when the story has been thought out return characterCreation(); } void titleScreen() { string titleScreenNameArray[7]; string fileInput; ifstream iFile ("TitleScreenName.txt"); if (iFile.is_open()) { int i = 0; while (getline(iFile, fileInput)) { titleScreenNameArray[i] = fileInput; i++; } iFile.close(); } else cout << "Unable to open file: TitleScreenName.txt"; for (int i = 0; i < 7; i++) { cout << titleScreenNameArray[i] << endl; } cout << "\n**Remember you can quit at any time by typing 'quit' when prompted for input**\n"; Statics::pause("\nPress any key to start the game!"); } Player* characterCreation() { string name, classSelection; Statics::clearScreen(); cout << "We would like to know some more about you.\n"; do { cout << "Please adventurer, tell us your name?\n" << "Input: "; cin >> name; } while (engine->checkQuit(name)); Player* tempPlayer = new Player(name); cout << "That is a fine name!\n"; bool validClass = false; while (!validClass) { do { cout << "\nAdventurer, what role would you like to train in?\n" << "W = Warrior\n" << "Input: "; cin >> classSelection; } while (engine->checkQuit(classSelection)); switch (classSelection.at(0)) { case 'W': case 'w': { tempPlayer->setClass(0); validClass = true; break; } default: cout << "\nNot a class option\n"; } } tempPlayer->setHealth(tempPlayer->getDefaultHealth() * tempPlayer->getClass()->getHealthModifier()); tempPlayer->setAttack(tempPlayer->getDefaultAttack() * tempPlayer->getClass()->getAttackModifier()); tempPlayer->setDefense(tempPlayer->getDefaultDefense() * tempPlayer->getClass()->getDefenseModifier()); tempPlayer->setSpeed(tempPlayer->getDefaultSpeed() * tempPlayer->getClass()->getSpeedModifier()); tempPlayer->setMoney(1000); return tempPlayer; } void addDefaultGameItems(Player* player, Shop* shop) { player->getPlayerInventory()->addItem(shop->getBuyItem(0)); player->getPlayerInventory()->addItem(shop->getBuyItem(21)); player->getPlayerInventory()->addItem(shop->getBuyItem(27)); player->getPlayerInventory()->addItem(shop->getBuyItem(27)); } void intro() { Statics::clearScreen(); cout << "Insert some fancy introduction to the story of the game here. Probably should start thinking about the story\n" << "and what its actually going to be. After this introduction, it will direct the player to character customization.\n"; Statics::pause("\nPress any key to continue to character customization..."); } <file_sep>/ConsoleGame/Weapon.h #pragma once #include <string> #include "BuyItem.h" using namespace std; class Weapon : public BuyItem { private: int attackModifier; public: Weapon(); Weapon(string, int, int); //Additional parameters should be added here for other weapon stats added //Additional Constructors for the other weapon types like bows. etc. ~Weapon(); int getItemPrice(); string getItemName(); int getAttackModifier(); };<file_sep>/ConsoleGame/Inventory.h #pragma once #include <vector> #include "BuyItem.h" using namespace std; class Inventory { private: //Constant integer for the maximum size of a player inventory const int MAX_INVENTORY_SIZE = 10; //The vector which represents the inventory will hold type base class for all objects purchasable vector<BuyItem*> playerInventory; //Iterator for playerInventory that can be used by any class function to iterate through playerInventory vector<BuyItem*>::iterator it; public: //Constructor and destructor Inventory(); ~Inventory(); int getMaxInventorySize(); int getCurrentInventorySize(); vector<BuyItem*> getInventory(); void displayInventory(); bool isInventoryFull(); bool isInventoryEmpty(); void addItem(BuyItem*); void removeItem(int); //This will probably change once this functionality is implemented in the shop };<file_sep>/ConsoleGame/GlobalResources.cpp #include "GlobalResources.h" Global::Global() { quit = false; } void Global::setQuit(bool tempQuit) { quit = tempQuit; } bool Global::getQuit() { return quit; } <file_sep>/ConsoleGame/Potion.cpp #include "Potion.h" Potion::Potion() { itemName = "null"; itemPrice = 0; healAmount = 0; } Potion::~Potion() { } Potion::Potion(string tempItemName, int tempItemPrice, int tempItemHealAmount) { itemName = tempItemName; itemPrice = tempItemPrice; healAmount = tempItemHealAmount; } int Potion::getItemPrice() { return itemPrice; } string Potion::getItemName() { return itemName; } int Potion::getHealAmount() { return healAmount; } <file_sep>/ConsoleGame/Potion.h #pragma once #include "BuyItem.h" using namespace std; class Potion : public BuyItem { private: int healAmount; public: Potion(); Potion(string, int, int); ~Potion(); int getItemPrice(); string getItemName(); int getHealAmount(); }; <file_sep>/ConsoleGame/Shop.h #pragma once #include <vector> #include <random> #include "BuyItem.h" #include "player.h" using namespace std; class Shop { private: const int MAX_SHOP_SIZE = 10; BuyItem* allBuyItems[50]; //The size of the array needs to change later when the total game items are determined vector<BuyItem*> currentShopItems; vector<BuyItem*>::iterator it; string shopTitleNameArray[7]; void importBuyItems(); void displayShopItems(); void displayShopTitle(); public: //Constructor and destructor Shop(); ~Shop(); void fillShopItems(); void setupShopTitle(); void loadShop(Player*); BuyItem* getBuyItem(int); };<file_sep>/ConsoleGame/Inventory.cpp #include "Inventory.h" #include <iostream> Inventory::Inventory() { } Inventory::~Inventory() { } int Inventory::getMaxInventorySize() { return MAX_INVENTORY_SIZE; } int Inventory::getCurrentInventorySize() { return playerInventory.size(); } vector<BuyItem*> Inventory::getInventory() { return playerInventory; } void Inventory::displayInventory() { for (int i = 0; i < this->playerInventory.size(); i++) { cout << "[" << i+1 << "] " << this->playerInventory[i]->getItemName() << endl; } } bool Inventory::isInventoryFull() { if (this->getCurrentInventorySize() == MAX_INVENTORY_SIZE) { return true; } else { return false; } } bool Inventory::isInventoryEmpty() { if (this->getCurrentInventorySize() == 0) { return true; } else { return false; } } void Inventory::addItem(BuyItem* itemToAdd) { if (isInventoryFull()) { cout << "Inventory is full!\n"; } else { this->playerInventory.push_back(itemToAdd); } } void Inventory::removeItem(int x) { it = this->playerInventory.begin(); if (x == 1) { this->playerInventory.erase(this->playerInventory.begin()); } else if (x == MAX_INVENTORY_SIZE) { this->playerInventory.pop_back(); } else { for (int i = 0; i < x; i++, it++) { if (i == (x - 1)) { this->playerInventory.erase(it); break; } } } } <file_sep>/ConsoleGame/Shop.cpp #include "Shop.h" #include "Weapon.h" #include "Armor.h" #include "Potion.h" #include "BattleTools.h" #include "player.h" #include "StaticsLibrary.h" #include <iostream> #include <fstream> #include <string> #include <iomanip> void Shop::importBuyItems() { //Create all the BuyItems in the game. Probably import from a text file string fileInput; char itemType; ifstream iFile("BuyItems.txt"); if (iFile.is_open()) { int counter = 0; string inputs[10]; while (!iFile.eof()) { iFile.get(itemType); switch (itemType) { case 'W': { //Weapons iFile.get(itemType); //This throws away the newline after the char. VERY IMPORTANT for (int i = 0; i < 3; i++) { getline(iFile, inputs[i]); } allBuyItems[counter] = new Weapon(inputs[0], stoi(inputs[1]), stoi(inputs[2])); break; } case 'A': { //Armor iFile.get(itemType); for (int i = 0; i < 4; i++) { getline(iFile, inputs[i]); } allBuyItems[counter] = new Armor(inputs[0], stoi(inputs[1]), stoi(inputs[2]), stoi(inputs[3])); break; }; case 'P': { //Potions iFile.get(itemType); for (int i = 0; i < 3; i++) { getline(iFile, inputs[i]); } allBuyItems[counter] = new Potion(inputs[0], stoi(inputs[1]), stoi(inputs[2])); break; }; case 'B': { //Battle Tools iFile.get(itemType); for (int i = 0; i < 3; i++) { getline(iFile, inputs[i]); } allBuyItems[counter] = new BattleTools(inputs[0], stoi(inputs[1]), stoi(inputs[2])); break; }; } counter++; } iFile.close(); } else cout << "Unable to open file: BuyItems.txt"; } Shop::Shop() { setupShopTitle(); importBuyItems(); } Shop::~Shop() { } void Shop::fillShopItems() { //Random generator in range for each type of BuyItem //Example: weapons consume indicies 0-10, armour 11-20,... //Shop can have like 10 items total. There could be certain amount of each type filled into the shop. for (int i = 0; i < 32; i++) { //The 32 needs to be changed to a const that has the max buyItem size currentShopItems.push_back(allBuyItems[i]); } } void Shop::displayShopItems() { /* Name Price Stats(Modifiers) <1> Weapon1 30g +25 attack <2> Health Pot 15g Heals 15 HP */ for (int i = 0; i < 32; i++) { //The 32 needs to be changed to a const that has the max buyItem size cout << "[" << i+1 << "] " << setw(20) << left << currentShopItems[i]->getItemName() << "\t" << currentShopItems[i]->getItemPrice() << "g" << endl; } } void Shop::setupShopTitle() { string fileInput; ifstream iFile("ShopTitle.txt"); if (iFile.is_open()) { int i = 0; while (getline(iFile, fileInput)) { shopTitleNameArray[i] = fileInput; i++; } iFile.close(); } else cout << "Unable to open file: ShopTitle.txt"; } void Shop::displayShopTitle() { for (int i = 0; i < 7; i++) { cout << shopTitleNameArray[i] << endl; } cout << "Name\t\t\t\t" << "Price\t" << "Stat Modifier\n"; } void Shop::loadShop(Player* player) { //Function called everytime player gets to the shop. This will load and display the shop //Probably will want to display the items in the player's inventory as well Statics::clearScreen(); displayShopTitle(); displayShopItems(); cout << "\nPlayer Inventory\n--------------------------------------------------------\n"; player->getPlayerInventory()->displayInventory(); } BuyItem * Shop::getBuyItem(int index) { return allBuyItems[index]; } <file_sep>/ConsoleGame/StaticsLibrary.cpp #include "StaticsLibrary.h" #include "Engine.h" #include <iostream> void Statics::pause() { cout << "Press any key to continue...\n"; cin.ignore(); cin.get(); } void Statics::pause(string displayMessage) { cout << displayMessage << endl; cin.ignore(); cin.get(); } void Statics::clearScreen() { system("CLS"); //Function from stdlib that clears the console screen and resets cursor to top left } <file_sep>/ConsoleGame/Warrior.cpp #include "Warrior.h" Warrior::Warrior() { className = "Warrior"; setHealthModifier(DEFAULT_HEALTH_MODIFIER); setAttackModifier(DEFAULT_ATTACK_MODIFIER); setDefenseModifier(DEFAULT_DEFENSE_MODIFIER); setSpeedModifier(DEFAULT_SPEED_MODIFIER); } Warrior::Warrior(int tempPlayerHealth, int tempPlayerAttack, int tempPlayerDefense, int tempPlayerSpeed) { //The arguments here need to be redone. Not sure what this constructor should actually modify } Warrior::~Warrior() { } void Warrior::setHealthModifier(int tempHealth) { healthModifier += tempHealth; } void Warrior::setAttackModifier(int tempAttack) { attackModifier += tempAttack; } void Warrior::setDefenseModifier(int tempDefense) { defenseModifier += tempDefense; } void Warrior::setSpeedModifier(int tempSpeed) { speedModifier += tempSpeed; } string Warrior::getClassName() { return className; } int Warrior::getHealthModifier() { return healthModifier; } int Warrior::getAttackModifier() { return attackModifier; } int Warrior::getDefenseModifier() { return defenseModifier; } int Warrior::getSpeedModifier() { return speedModifier; } <file_sep>/ConsoleGame/Engine.h #pragma once #include <string> #include <iostream> using namespace std; class Engine { private: bool quit; public: Engine(); //Accessors and mutators for quit variable void setQuit(bool); bool getQuit(); //Called everytime user is asked for input to check if they want to quit the game //Returns 0 for inputString equal to anything else than quit //Returns 1 if user decides not to quit int checkQuit(string); //Function that handles quitting the game void quitGame(); };<file_sep>/ConsoleGame/StaticsLibrary.h #pragma once #include <conio.h> #include <stdlib.h> #include <iostream> #include <string> using namespace std; class Statics { public: //Pauses program and waits for next input to continue static void pause(); //Overload of pause function which allows for a custom message to be displayed to screen when waiting for pause static void pause(string); //Clears the console screen and resets cursor to top left static void clearScreen(); }; <file_sep>/ConsoleGame/Warrior.h #pragma once #include "ClassBase.h" using namespace std; class Warrior : public ClassBase { private: const int DEFAULT_HEALTH_MODIFIER = 10; const int DEFAULT_ATTACK_MODIFIER = 10; const int DEFAULT_DEFENSE_MODIFIER = 10; const int DEFAULT_SPEED_MODIFIER = 10; //There are modifier variables for each stat in the base class. Those modifiers change depending on certain player attributes. public: Warrior(); Warrior(int, int, int, int); ~Warrior(); //These functions modify and return the attribute modifiers. They dont actually set the player attributes. //They are used to calculate the changes to the player attributes. //The value passed as a parameter to these functions are how much the modifier should be changed by, not the actual value the modifier should be set to. void setHealthModifier(int); void setAttackModifier(int); void setDefenseModifier(int); void setSpeedModifier(int); string getClassName(); int getHealthModifier(); int getAttackModifier(); int getDefenseModifier(); int getSpeedModifier(); }; <file_sep>/ConsoleGame/ClassBase.cpp #include "ClassBase.h" ClassBase::ClassBase() { healthModifier = 0; attackModifier = 0; defenseModifier = 0; speedModifier = 0; } ClassBase::ClassBase(int tempHealth, int tempAttack, int tempDefense, int tempSpeed) { healthModifier = tempHealth; attackModifier = tempAttack; defenseModifier = tempDefense; speedModifier = tempSpeed; } ClassBase::~ClassBase() { } <file_sep>/ConsoleGame/BattleTools.h #pragma once #include "BuyItem.h" using namespace std; class BattleTools : public BuyItem { private: int damage; public: BattleTools(); BattleTools(string, int, int); ~BattleTools(); int getItemPrice(); string getItemName(); int getDamage(); }; <file_sep>/ConsoleGame/Weapon.cpp #include "Weapon.h" Weapon::Weapon() { itemName = "null"; itemPrice = 0; attackModifier = 0; } Weapon::Weapon(string tempName, int tempItemPrice, int tempAttackModifier) { itemName = tempName; itemPrice = tempItemPrice; attackModifier = tempAttackModifier; } Weapon::~Weapon() { } int Weapon::getItemPrice() { return itemPrice; } string Weapon::getItemName() { return itemName; } int Weapon::getAttackModifier() { return attackModifier; } <file_sep>/README.md # ConsoleGame <file_sep>/ConsoleGame/Engine.cpp #include "Engine.h" Engine::Engine() { quit = false; } void Engine::setQuit(bool tempQuit) { this->quit = tempQuit; } bool Engine::getQuit() { return quit; } int Engine::checkQuit(string inputString) { setQuit(true); if (inputString == "quit" || inputString == "Quit") { char input; while (quit) { cout << "\nAre you sure you want to quit? ('Y' for yes, 'N' for no)\n" << "Input: "; cin >> input; switch (input) { case 'Y': case 'y': {quitGame(); } case 'N': case 'n': {setQuit(false); return 1; } default: cout << "Not a valid option\n"; } } } else { return 0; } } void Engine::quitGame() { //Probably have other stuff here for saving before quitting exit(0); } <file_sep>/ConsoleGame/Armor.h #pragma once #include "BuyItem.h" using namespace std; class Armor : public BuyItem { private: //Inherited members //int itemPrice //string itemName int defenseModifier; int speedModifier; public: Armor(); Armor(string, int , int, int); ~Armor(); int getDefenseModifier(); int getSpeedModifier(); //Inherited pure virtual functions int getItemPrice(); string getItemName(); };<file_sep>/ConsoleGame/GlobalResources.h #pragma once class Global { private: //This bool controls the main game loop. Used to terminate the program bool quit; public: Global(); void setQuit(bool); bool getQuit(); }; <file_sep>/ConsoleGame/BuyItem.cpp #include "BuyItem.h" BuyItem::BuyItem() { itemPrice = 0; itemName = "null"; } BuyItem::~BuyItem() { } <file_sep>/ConsoleGame/BuyItem.h #pragma once #include <string> using namespace std; class BuyItem { protected: int itemPrice; string itemName; public: //Constructor and destructor BuyItem(); ~BuyItem(); virtual int getItemPrice() = 0; virtual string getItemName() = 0; }; <file_sep>/ConsoleGame/Armor.cpp #include "Armor.h" Armor::Armor() { itemName = "null"; itemPrice = 0; defenseModifier = 0; speedModifier = 0; } Armor::Armor(string tempItemName, int tempItemPrice, int tempDefenseModifier, int tempSpeedModifier) { itemName = tempItemName; itemPrice = tempItemPrice; defenseModifier = tempDefenseModifier; speedModifier = tempSpeedModifier; } Armor::~Armor() { } int Armor::getDefenseModifier() { return defenseModifier; } int Armor::getSpeedModifier() { return speedModifier; } int Armor::getItemPrice() { return itemPrice; } string Armor::getItemName() { return itemName; } <file_sep>/ConsoleGame/BattleTools.cpp #include "BattleTools.h" BattleTools::BattleTools() { itemName = "null"; itemPrice = 0; damage = 0; } BattleTools::BattleTools(string tempItemName, int tempItemPrice, int tempDamage) { itemName = tempItemName; itemPrice = tempItemPrice; damage = tempDamage; } BattleTools::~BattleTools() { } int BattleTools::getItemPrice() { return itemPrice; } string BattleTools::getItemName() { return itemName; } int BattleTools::getDamage() { return damage; }
1cf617b7c9f51ed1e7a5f3f37317a3633e648b37
[ "Markdown", "C++" ]
28
C++
JulianGombos/ConsoleGame
72ca3e7f999fdbb49de277c57d58186a8c9253b3
9f66599189c6f55febddfc21d75f0ec3d76b27eb
refs/heads/master
<file_sep>package org.odhs.happydinner.res; public class Resource { public static final String app_name = "Happy Dinner Aramark Korea"; public static final String layout_main = "/layout/main.fxml"; public static final String font_nanumSquareB = "/font/NanumSquare_acB.ttf"; public static final String font_nanumSquareEB = "/font/NanumSquare_acEB.ttf"; public static final String font_nanumSquareR = "/font/NanumSquare_acR.ttf"; public static final String drawable_app_icon = "/drawable/app_icon.png"; public static final String style = "/style/style.css"; } <file_sep>rootProject.name = 'happydinner' <file_sep>package org.odhs.happydinner.model; import com.google.gson.annotations.SerializedName; public class DimiBob { public DimiBob() {} public DimiBob(String breakfast, String lunch, String dinner, String snack, String date) { this.breakfast = breakfast; this.lunch = lunch; this.dinner = dinner; this.snack = snack; this.date = date; } @Override public String toString() { return "아침 : " + breakfast + "\n점심 : " + lunch + "\n저녁 : " + dinner + "\n날짜 : " + date + "\n"; } @SerializedName("breakfast") public String breakfast; @SerializedName("lunch") public String lunch; @SerializedName("dinner") public String dinner; @SerializedName("snack") public String snack; @SerializedName("date") public String date; } <file_sep>package org.odhs.happydinner.util; import java.net.InetSocketAddress; import java.net.Socket; public class NetManager { public static boolean isConnect() { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress("1.1.1.1", 80); try { socket.connect(address, 1000); return true; } catch(Exception e) { // e.printStackTrace(); return false; } } } <file_sep>package org.odhs.happydinner.main; import org.odhs.happydinner.ui.Main; public class HappyDinner { public static void main(String[] args) { Main.begin(args); } }<file_sep>package org.odhs.happydinner.listener; import retrofit2.HttpException; public interface ApiCallback<T> { void onSuccess(T value); void onFail(Throwable t); } <file_sep># HappyDinner - 급식 보는 프로그램 ### 소개 * 한국디지털미디어고등학교 17기 WP 오동호 * 2019년 1학기 JAVA 수행평가 * **Intellij Idea 2019.1.3**에서 개발되었습니다. * **JDK 11.0.2**에서 컴파일되었습니다. ## 사용 라이브러리 * retrofit2 2.5.0 * retrofit2 converter-gson 2.5.0 * javafx 11.0.2
d1300f02e2ac11fe83ae8fa91faaffad1a05020c
[ "Markdown", "Java", "Gradle" ]
7
Java
gliserin/HappyDinner
d7dfb382d2eac09d40bf81d48fc7d40ef8f00ca7
3f5b3fd547bbf0c1f642e31c26e32fd17a05edfe
refs/heads/master
<file_sep>package com.crud.tasks.mapper; public class NoTaskFindException extends Exception{ }
d568e000d4f2955c3e428f54b5f1227dab1a59a5
[ "Java" ]
1
Java
MatiDabrowski/SpringWeb
ff9a8be25f5a13d411740d358be01320d86968a1
2262ab5526431ae777b13f2265f5bafb878e2618
refs/heads/master
<file_sep><?php namespace PhatKoalaBase\ServiceManager\EntityManager; /** * Class EntityService * @package PhatKoalaBase\ServiceManager\EntityManager */ class EntityService implements EntityInterface { public function getEntityManager() { // TODO: Implement getEntityManager() method. } }<file_sep><?php namespace PhatKoalaBase\ServiceManager\RepositoryManager; use Zend\EventManager\EventManager; /** * Class RepositoryEventManager * @package PhatKoalaBase\ServiceManager\RepositoryManager */ class RepositoryEventManager extends EventManager implements RepositoryInterface { }<file_sep><?php namespace PhatKoalaBase\ServiceManager\EntityManager; /** * Interface EntityInterface * @package PhatKoalaBase\ServiceManager\EntityManager */ interface EntityInterface { }<file_sep><?php namespace PhatKoalaBase\ServiceManager\RepositoryManager; use Zend\ServiceManager\AbstractPluginManager; use Zend\ServiceManager\Exception; /** * Class RepositoryManager * @package PhatKoalaBase\ServiceManager\RepositoryManager */ class RepositoryManager extends AbstractPluginManager { /** * Validate the plugin * * Checks that the repository loaded is either a valid callback or an instance of RepositoryInterface. * * @param mixed $plugin * @throws \Exception */ public function validatePlugin($plugin) { if ($plugin instanceof RepositoryInterface) { // we're okay return; } throw new \Exception(sprintf( 'Plugin of type %s is invalid; must implement %s\RepositoryInterface', (is_object($plugin) ? get_class($plugin) : gettype($plugin)), __NAMESPACE__ )); } }<file_sep><?php namespace PhatKoalaBase\ServiceManager\EntityManager; use Zend\Mvc\Service\AbstractPluginManagerFactory; use Zend\ServiceManager\ServiceLocatorInterface; /** * Class EntityServiceFactory * @package PhatKoalaBase\ServiceManager\EntityManager */ class EntityServiceFactory extends AbstractPluginManagerFactory { const PLUGIN_MANAGER_CLASS = 'PhatKoalaBase\ServiceManager\EntityManager\EntityManager'; public function createService(ServiceLocatorInterface $serviceLocator) { $plugins = parent::createService($serviceLocator); return $plugins; } }<file_sep><?php namespace PhatKoalaBase\Form\Element; /** * Class ObjectManagerAwareTrait * @package PhatKoalaBase\Form\Element */ trait ObjectManagerAwareTrait { /** * Inject object manager * * @param $objectManager * @return mixed */ public function setObjectManager(ObjectManager $objectManager) { $this->getProxy()->setObjectManager($objectManager); } }<file_sep><?php namespace PhatKoalaBase; return array( 'service_manager' => array( 'factories' => array( 'entity_manager' => 'PhatKoalaBase\ServiceManager\EntityManager\EntityServiceFactory', 'repository_manager' => 'PhatKoalaBase\ServiceManager\RepositoryManager\RepositoryServiceFactory', ), 'invokables' => array( 'password_service' => 'PhatKoalaBase\Service\PasswordService', ), ), 'service_listener_options' => array( // array( // 'service_manager' => 'EntityManager', // 'config_key' => 'entity_manager', // 'interface' => __NAMESPACE__.'\ServiceManager\EntityManager\EntityInterface', // 'method' => 'getEntityManagerConfig' // ), // array( // 'service_manager' => $stringServiceManagerName, // 'config_key' => $stringConfigKey, // 'interface' => $stringOptionalInterface, // 'method' => $stringRequiredMethodName, // ), ), );<file_sep><?php namespace PhatKoalaBase\ServiceManager\RepositoryManager; /** * Interface RepositoryInterface * @package PhatKoalaBase\ServiceManager\RepositoryManager */ interface RepositoryInterface { }<file_sep><?php namespace PhatKoalaBase\Form\Element; use Zend\InputFilter\InputProviderInterface; /** * Class InputProviderTrait * @package PhatKoalaBase\Form\Element */ trait InputProviderTrait { /** * @var array */ protected $inputSpecification = array(); /** * @return array */ public function getInputSpecification() { return $this->inputSpecification; } /** * @param array $inputSpecification * @return InputProviderTrait */ public function setInputSpecification($inputSpecification) { $this->inputSpecification = $inputSpecification; return $this; } }<file_sep><?php namespace PhatKoalaBase\Form\Element; /** * Interface ConfigAwareInterface * @package PhatKoalaBase\Form\Element */ interface ConfigAwareInterface { /** * @param array $config * @return mixed */ public function setConfig(array $config); }<file_sep><?php namespace PhatKoalaBase\Form\Element; use Zend\Filter\Word\UnderscoreToCamelCase; /** * Class ConfigAwareTrait * @package PhatKoalaBase\Form\Element */ trait ConfigAwareTrait { /** * @param array $config */ public function setConfig(array $config) { $filter = new UnderscoreToCamelCase(); foreach ($config as $key => $val) { $method = 'set'.ucfirst($filter->filter($key)); if (method_exists($this, $method)) { $this->$method($val); } } } }<file_sep><?php namespace PhatKoalaBase\ServiceManager\RepositoryManager; /** * Class RepositoryService * @package PhatKoalaBase\ServiceManager\RepositoryManager */ class RepositoryService implements RepositoryInterface { public function getRepositoryManager() { // TODO: Implement getRepositoryManager() method. } }<file_sep><?php namespace PhatKoalaBase; return array();<file_sep><?php return array( 'config_provider' => array( 'PhatKoalaUser\Form\Element\User\UsernameElement' => array( 'input_specification' => array( 'filters' => array( array( 'name' => 'string_trim', ), ), 'validators' => array( array( 'name' => 'string_length', 'options' => array( 'min' => 8 ), ), ), ), ), ), );<file_sep># PhatKoalaBase Abstract functionality used within PhatKoala modules <file_sep><?php namespace PhatKoalaBase\Service; use Zend\Crypt\Password\PasswordInterface; /** * Interface PasswordServiceInterface * @package PhatKoalaBase\Service */ interface PasswordServiceInterface extends PasswordInterface { }<file_sep><?php namespace PhatKoalaBase\ServiceManager\EntityManager; use Zend\ServiceManager\AbstractPluginManager; use Zend\ServiceManager\Exception; /** * Class EntityManager * @package PhatKoalaBase\ServiceManager\EntityManager */ class EntityManager extends AbstractPluginManager { /** * Validate the plugin * * Checks that the entity loaded is either a valid callback or an instance of EntityInterface. * * @param mixed $plugin * @throws \Exception */ public function validatePlugin($plugin) { if ($plugin instanceof EntityInterface) { // we're okay return; } throw new \Exception(sprintf( 'Plugin of type %s is invalid; must implement %s\EntityInterface', (is_object($plugin) ? get_class($plugin) : gettype($plugin)), __NAMESPACE__ )); } }<file_sep><?php namespace PhatKoalaBase\ServiceManager\RepositoryManager; use Zend\Mvc\Service\AbstractPluginManagerFactory; use Zend\ServiceManager\ServiceLocatorInterface; /** * Class RepositoryServiceFactory * @package PhatKoalaBase\ServiceManager\RepositoryManager */ class RepositoryServiceFactory extends AbstractPluginManagerFactory { const PLUGIN_MANAGER_CLASS = 'PhatKoalaBase\ServiceManager\RepositoryManager\RepositoryManager'; public function createService(ServiceLocatorInterface $serviceLocator) { $plugins = parent::createService($serviceLocator); return $plugins; } }<file_sep><?php namespace PhatKoalaBase\Service; use Zend\Crypt\Password\Bcrypt; /** * Class PasswordService * @package PhatKoalaBase\Service */ class PasswordService extends Bcrypt implements PasswordServiceInterface { }<file_sep><?php namespace PhatKoalaBase\ServiceManager\EntityManager; use Zend\EventManager\EventManager; /** * Class EntityEventManager * @package PhatKoalaBase\ServiceManager\EntityManager */ class EntityEventManager extends EventManager implements EntityInterface { }<file_sep><?php namespace PhatKoalaBase; use PhatKoalaBase\Form\Element\ConfigAwareInterface; use PhatKoalaBase\Form\Element\ObjectManagerAwareInterface; use Zend\ModuleManager\ModuleManager; /** * Class Module * @package PhatKoalaBase */ class Module { /** * @return array */ public function getConfig() { return array_merge_recursive( include __DIR__.'/../../config/module.config.php', include __DIR__.'/../../config/provider.config.php', include __DIR__.'/../../config/router.config.php' ); } /** * @return array */ public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } /** * Expected to return \Zend\ServiceManager\Config object or array to * seed such an object. * * @return array|\Zend\ServiceManager\Config */ public function getFormElementConfig() { return array( 'initializers' => array( function ($instance, $sm) { if ($instance instanceof ObjectManagerAwareInterface) { $instance->setObjectManager($sm->getServiceLocator()->get('Doctrine\ORM\EntityManager')); } }, function ($instance, $sm) { if ($instance instanceof ConfigAwareInterface) { $config = $sm->getServiceLocator()->get('Config'); $key = get_class($instance); if (isset($config['config_provider'][$key])) { $instance->setConfig($config['config_provider'][$key]); } } }, ), ); } /** * @param ModuleManager $moduleManager */ public function init(ModuleManager $moduleManager) { $serviceListener = $moduleManager ->getEvent() ->getParam('ServiceManager') ->get('ServiceListener'); $serviceListener ->addServiceManager( 'EntityManager', 'entity_manager', __NAMESPACE__.'\ServiceManager\EntityManager\EntityInterface', 'getEntityManagerConfig' ); $serviceListener ->addServiceManager( 'RepositoryManager', 'repository_manager', __NAMESPACE__.'\ServiceManager\RepositoryManager\RepositoryInterface', 'getRepositoryManagerConfig' ); } } <file_sep><?php /** * @author <NAME> <<EMAIL>> */ namespace PhatKoalaBase\Service; use Zend\Filter\Word\UnderscoreToCamelCase; /** * Class OptionService * @package PhatKoalaBase\Service */ class OptionService { public function __construct(array $options) { $filter = new UnderscoreToCamelCase(); foreach ($options as $key => $val) { $method = 'set'.ucfirst($filter->filter($key)); if (method_exists($this, $method)) { $this->$method($val); } } } }<file_sep><?php namespace PhatKoalaBase\Form\Element; use Doctrine\Common\Persistence\ObjectManager; /** * Interface ObjectManagerAwareInterface * @package PhatKoalaBase\Form\Element */ interface ObjectManagerAwareInterface { /** * @param ObjectManager $objectManager * @return mixed */ public function setObjectManager(ObjectManager $objectManager); }
c1db97301a28e0e90fefb64c021d0247d5408a7e
[ "Markdown", "PHP" ]
23
PHP
bigstylee/PhatKoalaBase
a4281fedf9121c2d37fa0fd797819d7ecca7933d
84fdb2cec2dab38f323e2138f4e8b5f6848baaa8
refs/heads/master
<file_sep>jquery-plugins ========== ## What is this? **jquery-plugins** are JavaScript plug-ins for jquery. Each library is documented, and none are minified. If you want a minified version, please feel free to run the code through a minifier - I happen to like YUI Compressor. It is my intention to only commit un-minified versions to this repo so that all of the comments are intact and other engineers can easily see what I'm doing, how I'm doing it, and *most importantly*, why I'm doing it. ## Plug-ins in the collection ### *cjl-sortedtable* Creates a sorted (and sortable) table directly from markup, enabling the developer to maintain their *progressive enhancement* practice. The sort order may be specified either in the markup, using a `data-sort` attribute on the table, or in the script call. The first column is set in the sort order by a click on the column header. Columns can be added to the multi-column sort order with a shift+click. Clicking a column already in the sort order toggles the sort order between ascending and descending. In the abscence of text in a column header, column names are defaulted to 'col_' followed by the zero-based column index. For example, the first column is col_0 and the third column is col_2. Because column names will default to a non-empty string, the table can be sorted using the default column names, e.g., `*instance*.sort([{name:'col_0', dir:1}])`. It is ***strongly*** recommended that column names be provided in the markup, however, as the lack of column names will break accessibility rules. The table sort order can be specified in the markup by providing the `data-sort` attribute. The `data-sort` attribute contains a comma-separated list of column names with a direction indicator - either '+' (ascending) or '-' (descending). For example, if your table contains a column called 'Longitude' and you wish to sort the locations east to west simply use `data-sort="Longitude-"` to sort the data. If the column is unlabeled, use the default column name, e.g., `data-sort="col_0+,col_1+"`. Columns can be excluded from the sort order by either specifying an array of column names in the `settings` object array property `exclude`, e.g., {exclude:['Email', 'Telephone']} or in the markup by providing the `data-sort-exclude` attribute for the column and setting it to "true", e.g., &lt;th data-sort-exclude="true"&gt;Email&lt;/th&gt; or by setting the `data-sort-exclude` attribute on the table to a comma-separated list, e.g., &lt;table id="contacts" data-sort-exclude="Email, Telephone"&gt;. Columns to be used in sorting may be identified in the the constructor either as an object array, $('#contacts').sortedtable([{name:'Surname'}, {name:'Given Name', dir:'descending'}]) or as a property of the `settings` object, e.g, $('#contacts').sortedtable({sort:[{name:'Surname'}, {name:'Given Name', dir:'descending'}], exclude:['Email', 'Telephone']}) #### Syntax: *object* $(*selector*).sortedtable([*object[]* keys]) *object* $(*selector*).sortedtable([*object* settings]) ##### Events - ***sort*** is fired when data sorting is started. Use `on` to subscribe to the event. Use `this` within the handler to access the table element, e.g. `var $self = $(this); $self.addClass('sorting');` - ***sorted*** is fired when data sorting is completed. Use `on` to subscribe to the event. Use `this` within the handler to access the table element, e.g. `var $self = $(this); $self.removeClass('sorting');` ##### Properties - ***object* *instance*.body**: The table body - ***string* *instance*.foot**: The table footer - ***string* *instance*.head**: The table header - ***node* *instance*.elem**: jQuery element reference to table ##### Methods - ***void* *instance*.clearSort**: Clears the sort keys - ***void* *instance*.sort([*object[]* sortOn[, *boolean* retain]])**: Sorts the data in the table body using the sort keys provided in the data-sort attribute of the table and the <em>sortOn</em> object array (each object in the array should contain a 'name' and 'dir' property, see `*instance*.sorts`), retaining the existing sort order if <em>retain</em> is specified. ##### Examples - $('#airports').sortedtable([{name:'Country', dir:'descending'}, {name:'City', dir:1}]); - $('#airports').sortedtable([{name:'Longitude'}]); - $('#airports').sortedtable(); #### Requires: - jquery #### Demo: - [The Cathmhaol](http://prototypes.cathmhaol.com/sortedtable-jquery/) <file_sep>/** * */ (function($) { $.fn.sortedtable = function(config) { /** * @property {object} body - jQuery selection */ this.body = null; /** * @property {string} foot - HTML containing table footer */ this.foot = null; /** * @property {string} head - HTML containing table header */ this.head = null; /** * @property {node} elem - jQuery element reference to table */ this.elem = $(this); /** * Clears the sort keys * @returns {void} * @function clearSort */ this.clearSort = function() { SORTS = [ ]; setSortAttribute(); }; /** * Sorts the data in the table body * @returns {void} * @function sort * @param {object[]} sortOn - Each object in the arguments should contain a 'name' and 'dir' property * @param {boolean} retain - Retain existing sort columns */ this.sort = function(sortOn, retain) { var counter , index , is_set , key , ord , sort_keys ; // trigger an event to indicate start of sort this.trigger('sort'); // make sure sortOn is an array sortOn = ($.isArray(sortOn)) ? sortOn : (sortOn ? [sortOn] : [ ]); // get any existing sort order getSortAttribute(); sort_keys = SORTS; // set sort keys if (!retain) { ME.clearSort(); } for (index = 0; index < sortOn.length; index += 1) { key = sortOn[index]; is_set = false; if (key.name) { // check if the column is already set as a sort and we're toggling the direction for (counter = 0; counter < sort_keys.length; counter += 1) { if (key.name === sort_keys[counter].name) { if (retain) { SORTS[counter].dir *= -1; is_set = true; break; } else { key.dir = sort_keys[counter].dir * -1; break; } } } if (!is_set) { // set the sort order flag ord = (key.dir || key.direction); if (parseFloat(ord) === 1 || parseFloat(ord) === -1) { ord = parseFloat(ord); } else if ((/^asc/i).test(ord || 'asc')) { ord = 1; } else { ord = -1; } // add the sort key to the collection SORTS.push({ name: key.name, dir: ord }); } } } // assign a local variable for scope sort_keys = SORTS; // only perform a sort if we have sort keys if (sort_keys.length) { DATA.sort(function(a, b) { var c = 0 , col , compareA , compareB , isfirst = 0 , ipv4 = /^(\d+)\.(\d+)\.(\d+)\.(\d+)(\:\d+)?$/ , hex = /^[a-f0-9]{1,}$/i ; function ipv4normalized(match, p1, p2, p3, p4, p5, offset, string) { var s = [ ] , c ; // normalize the IPv4 address s.push(('000'+p1).substr(-3)); s.push(('000'+p2).substr(-3)); s.push(('000'+p3).substr(-3)); s.push(('000'+p4).substr(-3)); s = s.join('.'); // normalize the port if (p5) { s += ':' + ('00000'+p5.replace(/\:/, '')).substr(-5); } return s; } while (c < sort_keys.length && isfirst === 0) { col = sort_keys[c].name; // use the sort key if it's not excluded if ($.inArray(col, settings.exclude) < 0) { compareA = a[col]; compareB = b[col]; // convert A and B if they're a special type if (compareA === undefined || compareB === undefined) { c += 1; continue; } else if (!isNaN(compareA) && !isNaN(compareB)) { compareA = compareA * 1; compareB = compareB * 1; } else if (ipv4.test(compareA) && ipv4.test(compareB)) { compareA = compareA.replace(ipv4, ipv4normalized); compareB = compareB.replace(ipv4, ipv4normalized); } else if (hex.test(compareA.replace(/\s/g, '')) && hex.test(compareB.replace(/\s/g, ''))) { compareA = parseInt(compareA, 16); compareB = parseInt(compareB, 16); } // return the order based on the compared values if (compareA > compareB) { isfirst = (sort_keys[c].dir || 1) * 1; } else if (compareA < compareB) { isfirst = (sort_keys[c].dir || 1) * -1; } else { c += 1; } } } return isfirst; }); // only render if we've change the order ME.body.html(renderBody()); // reattach the click handlers since we've reset the elements bodyHandlers(); // set the data attribute to maintain sort keys setSortAttribute(); // set the sorted class setSortedClass(); } // trigger event indicating sort is complete this.trigger('sorted'); }; /** * Assigns handlers for sorting * @returns {void} * @param {JQuerySelection} $cell */ function assignHandler($cell) { var $label = $cell.prop('tagName').toLowerCase(); $label = ($label === 'th') ? $cell.text() : 'column ' + $cell.index(); $label = ($label || 'column ' + ($cell.index() + 1)); $cell.attr('aria-label', 'Sort by ' + $label); $cell.attr('role', 'button'); $cell.attr('tabindex', 0); $cell.on('click', cellClicked); $cell.on('keypress', cellKeyed); } /** * Reattaches handlers to TD nodes after nodes have been replaced * @returns {void} */ function bodyHandlers() { var rows; if (!ME.head.length) { rows = ME.body.children('tr'); rows.each(function() { $(this).children('td').each(function(index) { var $col = $(this); if (!checkExclude($col)) { // add the sort handler assignHandler($col); } }); }); } } /** * The click handler for a table cell * @returns {void} * @param {Event} evt */ function cellClicked(evt) { var $cell = $(this) , $label = $cell.prop('tagName').toLowerCase() , $text = $cell.text() ; $label = ($label === 'th' && $text) ? $text : 'col_' + $cell.index(); evt.preventDefault(); evt.stopPropagation(); ME.sort({name:$label}, evt.shiftKey); } /** * The keypress handler for a table cell * @returns {void} * @param {Event} evt */ function cellKeyed(evt) { var $cell = $(this) , $key = evt.which , $label = $cell.prop('tagName').toLowerCase() , $text = $cell.text() ; // do a sort if the key entered is enter (13) or space (32) if ($key === 13 || $key === 32) { $label = ($label === 'th' && $text) ? $text : 'col_' + $cell.index(); evt.preventDefault(); evt.stopPropagation(); ME.sort({name:$label}, evt.shiftKey); } } /** * Adds the item to the excluded array if it is not already tracked * @returns {void} * @param {string|JQuerySelection} $cell */ function checkExclude($cell) { var $label , $exclude = false ; // if the function is called with a string, automatically exclude it if (typeof $cell === 'string') { $label = $cell.replace(/^\s*|\s*$/g, ''); $exclude = true; } else { $label = $cell.prop('tagName').toLowerCase(); $label = ($label === 'th') ? $cell.text() : 'column ' + $cell.index(); $exclude = ($cell.attr('data-sort-exclude') || '').toLowerCase() === 'true'; } if ($label) { // add the column if we need to exclude it if ($.inArray($label, settings.exclude) < 0 && $exclude) { settings.exclude.push($label); } return ($.inArray($label, settings.exclude) > -1); } return false; } /** * Reads the number of columns in the table * @returns {integer} */ function getColumnCount() { var cols = 0; ME.elem.children('tbody').children('tr').each(function(){ var inrow = 0; $(this).children('td').each(function(){ var colSpan = $(this).attr('colspan'); inrow += (colSpan || 1); }); cols = Math.max(cols, inrow); }); return cols; } /** * Sets the object array containing sort keys * @returns {void} */ function getSortAttribute() { var c , sort_keys = (ME.elem.attr('data-sort') || '').split(',') , parsed , pattern = /^\s*([\w\-]+)([\+\-])\s*$/ , ret = [ ] ; for (c = 0; c < sort_keys.length; c += 1) { parsed = pattern.exec(sort_keys[c]) if (parsed) { ret.push({name:parsed[1], dir:(/^(asc|\+)/i).test(parsed[2]) ? 1 : -1}); } } // update the sort keys array SORTS = ret; } /** * Returns all the markup of the provided node * @returns {string} * @param {JQuerySelection} $node */ function outerHtml($node) { var markup = ''; if ($node && $node.length) { markup = $('<div />').append($node.clone()).html(); } return markup.replace(/\>\s*\</g, '><'); } /** * Reads the table markup into a dataset and sort instructions * @returns {void} */ function parse() { // table rows are contained by a thead, tbody, or tfoot // rows not contained are put in a virtual tbody so check // for a thead or tfoot but don't worry about a tbody var $tbl_th = ME.elem.find('th:first').parent() , $snippet , index ; ME.body = ME.elem.children('tbody').children('tr'); ME.head = ME.elem.children('thead'); // only do something when we have a table to parse if (ME.body.length) { // set any excluded sort columns $snippet = (ME.elem.attr('data-sort-exclude') || '').split(','); for (index = 0; index < $snippet.length; index += 1) { checkExclude($snippet[index]); } // set the header if (!ME.head.length) { if ($tbl_th.length) { // get the html of the header row and wrap it in a thead $snippet = '<thead>' + outerHtml($tbl_th) + '</thead>'; // remove the header row from the body ME.body.each(function() { // if the header is in the body, drop it if ($(this).is($tbl_th)) { $tbl_th.remove(); } }); } else { $snippet = '<thead>'; for (index = getColumnCount(); index > 0; index -= 1) { $snippet += '<th></th>'; } $snippet += '</thead>'; } // append the new header row to the table and reset the header ME.elem.prepend($snippet); ME.head = ME.elem.children('thead'); } // set the footer to the footer node ME.foot = ME.elem.children('tfoot'); // configure the columns for sorting if (ME.head.length) { ME.head.children('tr').children().each(function() { var $col = $(this); // add the column to the columns collection COLS.push($col); // set the sort indicator color INDICATOR_COLOR = $col.css('color'); // add the sort indicator $col.append('<span class="indicator"></span>'); // handle exclusion if (!checkExclude($col)) { // add the sort handler assignHandler($col); $col.addClass('sorter'); } else { $col.addClass('sorter disabled'); } // disable selection of the column $col.attr('unselectable', 'on') .css('user-select', 'none') .on('selectstart', false); }); COL_COUNT = COLS.length; } // create the dataset to be sorted ME.body.each(function() { var obj , propCount = 0 ; $(this).children('td').each(function(index) { // default the column name to the zero-based index var colName = (COLS[index] || '').length ? COLS[index].text() : 'col_' + index , $cell = $(this) ; // check to see if we should be excluding it from the sort order checkExclude($cell); colName = colName || 'col_' + index; obj = obj || { }; obj[colName] = $cell.text(); propCount += 1; }); if (obj) { obj.html = outerHtml($(this)); DATA.push(obj); COL_COUNT = Math.max(COL_COUNT, propCount); } }); // reset the body ME.body = ME.elem.children('tbody') } return; } /** * Returns the HTML of the table body string * @returns {string} */ function renderBody() { var i , s = [ ] ; // loop through the data for the body for (i = 0; i < DATA.length; i += 1) { s.push(DATA[i].html); } return s.join('\n'); } /** * Sets the data-sort attribute on the table using the sort keys * @returns {void} */ function setSortAttribute() { var c , s = [ ] ; for (c = 0; c < SORTS.length; c += 1) { s.push(SORTS[c].name + (SORTS[c].dir === 1 ? '+' : '-')); } // update the sort indicator ME.elem.attr('data-sort', s.join(',')); } /** * Sets the class on sorted columns, i.e., 'sorted' and 'asc' or 'desc' * @returns {void} */ function setSortedClass() { // loop through the columns in the header and remove the 'sorted' and 'asc'|'desc' class // add the appropriate class(es) if the column has a sort key in SORTS var $head = $(ME.head) , $key = null , $keys = SORTS , $style = $('#cjl-sortable-style') , $tr ; if ($head.length) { // add the style if it's not present if (!$style.length) { // set the style $(document.head).append( '<style id="cjl-sortable-style" type="text/css">' + '.cjl-sortable .sorter {' + 'cursor:pointer;' + 'font-weight:bold;' + 'height:1.2em;' + 'overflow:hidden;' + 'text-align:left;' + '}' + '.cjl-sortable .sorter:hover {' + 'outline:2px auto -webkit-focus-ring-color;' + '}' + '.cjl-sortable .sorter.disabled {' + 'font-weight:normal;' + '}' + '.cjl-sortable .sorter.disabled:hover {' + 'outline:none;' + '}' + '.cjl-sortable .indicator {' + 'display:inline-block;' + 'float:right;' + 'height:0;' + 'margin-left:0.5em;' + 'position:relative;' + 'width:0;' + 'border-bottom:none;' + 'border-left:0.5em solid transparent;' + 'border-right:0.5em solid transparent;' + 'border-top:none;' + '}' + '.cjl-sortable .sorted-asc .indicator {' + 'top:0.2em;' + 'border-bottom:0 solid transparent;' + 'border-top:0.5em solid ' + INDICATOR_COLOR + ';' + '}' + '.cjl-sortable .sorted-desc .indicator {' + 'top:0.3em;' + 'border-bottom:0.5em solid ' + INDICATOR_COLOR + ';' + 'border-top:0 solid transparent;' + '}' + '</style>' ); } // adjust for different markup (thead vs. no thead) $tr = $head.children('tr'); $tr = $tr.length ? $tr : $head; // loop through the column headings $tr.children().each(function() { var $col = $(this) , $colName = $col.text() , index ; // use the default property name if the column heading is blank $colName = $colName || 'col_' + $col.index(); // remove any existing identifiers $col.removeClass('sorted-asc'); $col.removeClass('sorted-desc'); // check to see if the column is in the sort keys for (index = 0; index < $keys.length; index += 1) { $key = $keys[index]; if ($colName === $key.name && $.inArray($colName, settings.exclude) < 0) { $col.addClass('sorted-' + ($key.dir === 1 ? 'asc' : 'desc')); } } }); } return; } var ME = this , INDICATOR_COLOR = 'rgb(0, 0, 0)' // Color of the text in the header, used as the color for the up/down arrow , DATA = [ ] // Array of objects representing table rows , COL_COUNT = 0 // Count of columns , COLS = [ ] // Names of columns in the table, defaults to col_{index} , SORTS = [ ] // Sort keys. Object contains 'name' and 'dir', which is 1 (ascending) or -1 (descending) , settings // The settings passed in to the object , keys = [ ] // Object array containing sort order ; // handle an array passed in instead of an object if ($.isArray(config)) { keys = config; config = { }; } // initialize the settings settings = $.extend({ sort: keys, exclude: [ ] }, config); // initialize parse(); // sort according to order specified in the call if ($.isArray(settings.sort)) { ME.sort(settings.sort, true); } // return the extended jquery object return ME; }; }(jQuery));
9eaa96345b9866c05ee25743b85f206afe475490
[ "Markdown", "JavaScript" ]
2
Markdown
hrobertking/jquery-plugins
70d970d6976d8edaa4ef80b4dc816dc8bb2fc1cc
169af8c6a5fb19fbaa68eb5b5cdb93815fe77f10
refs/heads/master
<repo_name>p773/Blog<file_sep>/app/Http/Controllers/PagesController.php <?php namespace App\Http\Controllers; use App\Page; use App\Category; use App\Http\Requests; use App\Model; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class PagesController extends Controller { public function Index () { $pages = Page::paginate(4); return view ('show')->with('pages',$pages); } public function getAbout () { } public function getContact () { return "Hello contact page"; } public function getShow () { $pages = Page::paginate(4); return view ('show')->with('pages',$pages); } public function show () { //$post = Page::find($id); //$pages = Page::all(); $pages = Page::paginate(4); return view ('show')->with('pages', $pages); } public function create () { return view('create'); } public function store (Request $request) { $request->validate([ 'title' => 'required', 'slug' => 'required', 'content' => 'required|min:3', ]); //dd($request->all()); $Page = new Page; $Page->title = request('title'); $Page->slug = request('slug'); $Page->content = request('content'); $Page->save; Page::create($request->all()); return redirect('/create'); } public function Cat () { //$post = Page::find($id); $categories = Category::all(); return view ('create')->with('categories', $categories); } public function showcat ($category) { //var_dump($category); //die; $pages = Page::where('slug', $category) //->take(10) //->get() ->paginate(4); //var_dump($pages); //die; return view ('showcat')->with('pages', $pages); //$post = Page::find($id); //$pages = Page::all(); //$cat = $_GET['cat']; //$pages = Page::find($category); } }<file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/about', function () { return view('about'); }); Route::get('/categories', function () { return view('categories'); }); //Route::get('/{slug}', function ($slug) { //return 'stronie'.$slug; //} ); Route::get('/create', 'PagesController@create'); Route::post('/create', 'PagesController@store'); Route::post('/show', 'PagesController@show'); //Route::post('/create', 'PagesController@cat'); Route::get('/create', 'PagesController@cat'); Route::get('/categories', 'CategoriesController@'); //Route::get('/showcat', 'PagesController@'); Route::get('/show', function () { return view('show'); }); Route::resource('show', 'PagesController'); Route::resource('showcat/', 'PagesController'); Route::resource('categories', 'CategoriesController'); //Route::resource('categories', 'PagesController'); //Route::post('/categories', 'CategoriesController'); //Route::post('/showcat', 'PagesController@showcat'); Route::get('showcat/{category}', 'PagesController@showcat'); //Route::get('switchinfo/{prisw}/{secsw}', 'SwitchinfoController@functionname'); //Route::get('/wizytaszczegoly/{id}', 'VisitController@visitDetails')->name('visit.visitDetails') Route::get('showcat/{category?}', function ($category) { return 'category '.$category; });<file_sep>/app/Http/Controllers/CategoriesController.php <?php namespace App\Http\Controllers; use App\Category; use App\Http\Requests; use App\Model; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class CategoriesController extends Controller { public function Index () { //$post = Page::find($id); $categories = Category::all(); return view ('categories')->with('categories', $categories); } public function category () { } }
844a2496de118223f8f228a1a3c2f58a05b3561f
[ "PHP" ]
3
PHP
p773/Blog
c216579e8d9c650f7844033b2d4ec880fadb0148
62e4e420872f5bc0fd20d4ae67b5ca369c3391da
refs/heads/master
<repo_name>johndpope/swift-midi<file_sep>/LUMI/Message.swift import Foundation /// An individual message sent to or from a MIDI endpoint. /// For the complete specification, visit http://www.midi.org/techspecs/Messages.php public enum Message { // Channel voice messages case NoteOff(channel: UInt8, key: UInt8, velocity: UInt8) case NoteOn(channel: UInt8, key: UInt8, velocity: UInt8) case Aftertouch(channel: UInt8, key: UInt8, pressure: UInt8) case ControlChange(channel: UInt8, controller: UInt8, value: UInt8) case ProgramChange(channel: UInt8, programNumber: UInt8) case ChannelPressure(channel: UInt8, pressure: UInt8) case PitchBend(channel: UInt8, pitch: UInt16) } <file_sep>/Playgrounds/MIDI.playground/Pages/Page1.xcplaygroundpage/Contents.swift @testable import LUMI import AudioToolbox import XCPlayground let hardware = Hardware() hardware.onSetupChanged { let names = hardware.connectedDeviceNames() } let message = MIDIPacket() let children = Mirror(reflecting: message.data).children for child in children { child.value } var instrument: UInt8 = 0 /* var musicPlayer = UnsafeMutablePointer<MusicPlayer>.alloc(1) NewMusicPlayer(musicPlayer) var sequence = UnsafeMutablePointer<COpaquePointer>.alloc(1) NewMusicSequence(sequence) MusicSequenceSetSequenceType(sequence.memory, MusicSequenceType.Seconds) MusicPlayerSetSequence(musicPlayer.memory, sequence.memory) var tempoTrack = UnsafeMutablePointer<MusicTrack>.alloc(1) MusicSequenceGetTempoTrack(sequence.memory, tempoTrack) MusicTrackNewExtendedTempoEvent(tempoTrack.memory, 0, 60) var chordsTrack = UnsafeMutablePointer<MusicTrack>.alloc(1) MusicSequenceNewTrack(sequence.memory, chordsTrack) */ var processingGraph: AUGraph = nil withUnsafeMutablePointer(&processingGraph) { NewAUGraph($0) } print(Mirror(reflecting: hardware).children) for val in Mirror(reflecting: hardware).children { print(val.value) } var cd = AudioComponentDescription( componentType: OSType(kAudioUnitType_MusicDevice), componentSubType: OSType(kAudioUnitSubType_DLSSynth), componentManufacturer: OSType(kAudioUnitManufacturer_Apple), componentFlags: 0, componentFlagsMask: 0) var samplerNode: AUNode = 0 withUnsafeMutablePointer(&samplerNode) { AUGraphAddNode(processingGraph, &cd, $0) } var ioUnitDescription = AudioComponentDescription( componentType: OSType(kAudioUnitType_Output), componentSubType: OSType(kAudioUnitSubType_DefaultOutput), componentManufacturer: OSType(kAudioUnitManufacturer_Apple), componentFlags: 0, componentFlagsMask: 0) var ioNode: AUNode = 0 withUnsafeMutablePointer(&ioNode) { AUGraphAddNode(processingGraph, &ioUnitDescription, $0) } AUGraphOpen(processingGraph) var samplerUnit = UnsafeMutablePointer<AudioUnit>.alloc(1) AUGraphNodeInfo(processingGraph, samplerNode, nil, samplerUnit) var ioUnit = UnsafeMutablePointer<AudioUnit>.alloc(1) AUGraphNodeInfo(processingGraph, ioNode, nil, ioUnit) var ioUnitOutputElement:AudioUnitElement = 0 var samplerOutputElement:AudioUnitElement = 0 AUGraphConnectNodeInput(processingGraph, samplerNode, samplerOutputElement, ioNode, ioUnitOutputElement) AUGraphInitialize(processingGraph) AUGraphStart(processingGraph) hardware.addMessageObserverForDeviceNamed("Samson Carbon49 ") { (message: Message) -> Void in switch message { case .NoteOn(let channel, let key, let velocity): XCPlaygroundPage.currentPage.captureValue(key, withIdentifier: "key") XCPlaygroundPage.currentPage.captureValue(velocity, withIdentifier: "velocity") key MusicDeviceMIDIEvent(samplerUnit.memory, UInt32(0x90 | channel), UInt32(key), UInt32(velocity), 0) /* var channel = UnsafeMutablePointer<MIDIChannelMessage>.alloc(1) channel.initialize(MIDIChannelMessage(status: 0xC0, data1: instrument, data2: 0, reserved: 0)) MusicTrackNewMIDIChannelEvent(chordsTrack.memory, 0, channel) var message = UnsafeMutablePointer<MIDINoteMessage>.alloc(1) message.initialize(MIDINoteMessage(channel: 0, note: key, velocity: 127, releaseVelocity: 0, duration: 1)) MusicTrackNewMIDINoteEvent(chordsTrack.memory, 0, message) MusicPlayerStart(musicPlayer.memory) */ case .NoteOff(let channel, let key, let velocity): key MusicDeviceMIDIEvent(samplerUnit.memory, UInt32(0x80 | channel), UInt32(key), UInt32(velocity), 0) case .ControlChange(let channel, let controller, let value): if controller == 10 { // Instrument change. MusicDeviceMIDIEvent(samplerUnit.memory, UInt32(0xC0 | channel), UInt32(value), 0, 0) } else if controller == 7 { // Volume MusicDeviceMIDIEvent(samplerUnit.memory, UInt32(0xB0 | channel), UInt32(0x07), UInt32(value), 0) } instrument = value controller channel case .PitchBend(let channel, let pitch): pitch default: print("bob") break } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true <file_sep>/LUMI/CoreMIDI/MIDIPacket+SequenceType.swift import CoreMIDI /** The returned generator will enumerate each value of the provided tuple. */ func generatorForTuple(tuple: Any) -> AnyGenerator<Any> { let children = Mirror(reflecting: tuple).children return anyGenerator(children.generate().lazy.map { $0.value }.generate()) } /** Allows a MIDIPacket to be iterated through with a for statement. Example usage: let packet: MIDIPacket for message in packet { // message is a Message } */ extension MIDIPacket: SequenceType { public func generate() -> AnyGenerator<Message> { var generator = generatorForTuple(self.data) var index: UInt16 = 0 return anyGenerator { if index >= self.length { return nil } func pop() -> UInt8 { assert(index < self.length) index++ return generator.next() as! UInt8 } let byte = pop() if (byte & 0x80) == 0x80 { // Status byte let message = byte & 0xF0 let channel = byte & 0x0F switch message { case 0x80: return .NoteOff(channel: channel, key: pop(), velocity: pop()) case 0x90: return .NoteOn(channel: channel, key: pop(), velocity: pop()) case 0xA0: return .Aftertouch(channel: channel, key: pop(), pressure: pop()) case 0xB0: return .ControlChange(channel: channel, controller: pop(), value: pop()) case 0xC0: return .ProgramChange(channel: channel, programNumber: pop()) case 0xD0: return .ChannelPressure(channel: channel, pressure: pop()) case 0xE0: // From http://www.midi.org/techspecs/Messages.php // The pitch bender is measured by a fourteen bit value. The first data byte contains the // least significant 7 bits. The second data bytes contains the most significant 7 bits. let low = UInt16(pop() & 0x7F) let high = UInt16(pop() & 0x7F) return .PitchBend(channel: channel, pitch: (high << 7) | low) default: assert(false, "Unimplemented message \(byte)") return nil } } assert(false, "Unimplemented message \(byte)") return nil } } }
d6cd46ae52e299d2e86f6aa3be3aa08f38e82f5d
[ "Swift" ]
3
Swift
johndpope/swift-midi
67901cc7a6e93938910c8b66914ca6ddf46f0dab
e125cd1024fb39afc6966dd0ccf0ba060f62d3ee
refs/heads/master
<file_sep>""" Project 4C Canvas Analyzer CISC108 Honors Fall 2019 Access the Canvas Learning Management System and process learning analytics. Edit this file to implement the project. To test your current solution, run the `test_my_solution.py` file. Refer to the instructions on Canvas for more information. "I have neither given nor received help on this assignment." author: <NAME> """ __version__ = 7 # 1) main import canvas_requests def main(name): user = canvas_requests.get_user(name) print_user_info(user) courses = canvas_requests.get_courses(name) courses = filter_available_courses(courses) print_courses(courses) course_ids = get_course_ids(courses) course_id = choose_course(course_ids) submissions = canvas_requests.get_submissions(name,course_id) summarize_points(submissions) summarize_groups(submissions) #plot_scores(submissions) #plot_grade_trends(submissions) # 2) print_user_info def print_user_info(user): print("Name: " + user["name"]) print("Title: " + user["title"]) print("Primary Email: " + user["primary_email"]) print("Bio: " + user["bio"]) bio = { "name": "<NAME>", "title": "Student", "primary Email": "<EMAIL>", "bio": "Interested in Magic, Learning, and House Elf Rights" } # 3) filter_available_courses def filter_available_courses(courses): available_courses = [] for course in courses: if course["workflow_state"] == "available": available_courses.append(course) return available_courses # 4) print_courses def print_courses(courses): for course in courses: print(str(course["id"]) + " : " + course["name"]) # 5) get_course_ids def get_course_ids(courses): course_ids = [] for course in courses: course_ids.append(course["id"]) return course_ids # 6) choose_course def choose_course(course_ids): chosen_course = input("Pick a course id:") chosen_course = int(chosen_course) while chosen_course not in course_ids: chosen_course = int(input("Pick a course id:")) return chosen_course # 7) summarize_points def summarize_points(submissions): possible = 0 points_obtained = 0 for submission in submissions: if submission["score"] is not None: points_possible = submission["assignment"]["points_possible"] group_weight = submission["assignment"]["group"]["group_weight"] possible = possible + (points_possible * group_weight) points_obtained = points_obtained + (submission["score"] * group_weight) print("Points possible so far: " + str(possible)) print("Points obtained: " + str(points_obtained)) print("Current grade: " + str(round((points_obtained/possible) * 100))) # 8) summarize_groups def summarize_groups(submissions): group_score = {} group_points = {} for submission in submissions: if submission["score"] is not None: group_name = submission["assignment"]["group"]["name"] if group_name not in group_score: group_score[group_name] = 0 group_points[group_name] = 0 group_score[group_name] = group_score[group_name] + submission["score"] group_points[group_name] = group_points[group_name] + submission["assignment"]["points_possible"] for name in group_score: score, points = group_score[name],group_points[name] print("*", name, round(100 * score/points)) # 9) plot_scores #def plot_scores(submissions): # grade = 0 # for submission in submissions: # if submission["score"] is not None: # grade = (submission["score"] * 100)/(submission["assignment"]["points_possible"]) # 10) plot_grade_trends # Keep any function tests inside this IF statement to ensure # that your `test_my_solution.py` does not execute it. if __name__ == "__main__": main('hermione') # main('ron') # main('harry') # https://community.canvaslms.com/docs/DOC-10806-4214724194 # main('YOUR OWN CANVAS TOKEN (You know, if you want)')<file_sep># -*- coding: utf-8 -*- """ Created on Sun Nov 12 12:12:37 2017 @author: acbart """ __version__ = 7 import canvas_requests import matplotlib.pyplot as plt from datetime import datetime # 1 def print_user_info(user): ''' Prints information about the user such as their name and title. Parameters: user (str): A user token Returns: None ''' print("Name:", user['name']) print("Title:", user['title']) print("Primary Email:", user['primary_email']) print("Bio:", user['bio']) # 2 def filter_available_courses(courses): ''' Removes courses that are not available to the user. Parameters: courses (list of dict): A list of course dictionaries Returns: list of dict ''' valid = [] for course in courses: if course['workflow_state'] == 'available': valid.append(course) return valid # 3 def print_courses(courses): """ Iterates through the list of courses and prints the ID and name of each course Parameters: courses (list of dict): A list of course dictionaries Returns: None """ for course in courses: print("\t", course["id"], ":", course["name"]) # 4 def get_course_ids(courses): """ Iterates through the list of courses and extracts out their IDs. Parameters: courses (list of dict): A list of course dictionaries Returns: list of int """ ids = [] for course in courses: ids.append(course['id']) return ids # 5 def choose_course(course_ids): """ Prompts the user for a course ID and then returns it if it is one of the valid course IDs given. Parameters: course_ids (list of int): A list of course IDs Returns: int """ PROMPT = "Choose a course from the list above:" chosen = None while chosen not in course_ids: chosen = int(input(PROMPT)) return chosen # 6 def summarize_points(submissions): """ Prints out summary statistics for the student, including: How many points they have obtained How many points were possible in the course Their current final grade in the course Parameters: submissions (list of dict): A list of submission dictionaries Returns: None """ possible = 0 score = 0 for sub in submissions: if sub['score'] is not None: points_possible = sub['assignment']['points_possible'] group_weight = sub['assignment']['group']['group_weight'] possible += points_possible * group_weight score += sub['score'] * group_weight print("Points possible so far:", possible) print("Points obtained:", score) print("Current grade:", round(100 * score / possible)) # 7 def summarize_groups(submissions): """ Prints out the students' current grade for each group category. Parameters: submissions (list of dict): A list of submission dictionaries Returns: None """ group_score = {} group_points = {} for sub in submissions: if sub['score'] is not None: group_name = sub['assignment']['group']['name'] if group_name not in group_score: group_score[group_name] = 0 group_points[group_name] = 0 group_score[group_name] += sub['score'] group_points[group_name] += sub['assignment']['points_possible'] for name in group_score: score, points = group_score[name], group_points[name] print("*", name, ":", round(100 * score / points)) # 8 def plot_scores(submissions): ''' Makes a histogram of the students' scores across all submitted assignments. Parameters: submissions (list of dict): A list of submission dictionaries Returns: None ''' percent_scores = [] for s in submissions: if s['assignment']['points_possible'] and s['score'] != None: percent_score = 100 * s['score'] / s['assignment']['points_possible'] percent_scores.append(percent_score) plt.hist(percent_scores) plt.title("Distribution of Grades") plt.xlabel("Grades") plt.ylabel("Number of Assignments") plt.show() # Helper function def parse_date(a_date): ''' Converts a date/time from a string into a datetime object. The string representation is assumed to be the regular Canvas one: YYYY/MM/DDTHH:MM:DDZ Parameters: a_date (str): A string representation of a date Returns: datetime: A Python datetime object ''' return datetime.strptime(a_date, "%Y-%m-%dT%H:%M:%SZ") # 8 def plot_grade_trends(submissions): ''' For a given course and user, creates plots of a students' submissions in a course. Parameters: submissions (list of dict): A list of submission dictionaries Returns: None ''' weighted_score = 0 max_weighted_score = 0 ungraded_max = 0 running_low = [] running_high = [] running_max = [] for s in submissions: # Group weighted_modifier = s['assignment']['group']['group_weight'] # Score score = 0 if s['score']: score = s['score'] weighted_score += score * weighted_modifier # Points possible points_possible = s['assignment']['points_possible'] if not s['graded_at']: ungraded_max += points_possible * weighted_modifier else: ungraded_max += score * weighted_modifier max_weighted_score += points_possible * weighted_modifier # Running sums running_low.append(100 * weighted_score) running_max.append(100 * max_weighted_score) running_high.append(100 * ungraded_max) print(running_max) print(max_weighted_score) # Normalize by maximum score running_high = [s / max_weighted_score for s in running_high] running_low = [s / max_weighted_score for s in running_low] running_max = [s / max_weighted_score for s in running_max] # Dates running_dates = [] for s in submissions: running_dates.append(parse_date(s['assignment']['due_at'])) # Plot trends plt.plot(running_dates, running_high, label="Highest", linestyle='--') plt.plot(running_dates, running_low, label="Lowest", linestyle='--') plt.plot(running_dates, running_max, label="Maximum") # Graphical styling plt.xticks(rotation=45) plt.legend(loc=(0, .5)) plt.ylabel("Grade") plt.title("Grade Trend") plt.show() # 10 def main(user_id): ''' For a given user, displays information about one of their canvas courses. Parameters: user (str): A user token Returns: None ''' # User user = canvas_requests.get_user(user_id) print_user_info(user) # Course courses = canvas_requests.get_courses(user_id) available_courses = filter_available_courses(courses) print_courses(available_courses) course_ids = get_course_ids(available_courses) course_id = choose_course(course_ids) # Submissions submissions = canvas_requests.get_submissions(user_id, course_id) # Statistics summarize_points(submissions) summarize_groups(submissions) # Plots plot_scores(submissions) plot_grade_trends(submissions) if __name__ == "__main__": main('hermione')
d5b81df1c63cfd382cc51936aad7e29a166e385e
[ "Python" ]
2
Python
cuprehan/cisc108_canvas_analyzer
cc3950015f85faf09dc60a18f4d2201214177237
94fa8a264111f40597ba3c0907b25a48b96c7cdf
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, Validators, FormGroup } from '@angular/forms'; import { EmplyeeserviceService } from '../services/user-service'; import { User, Role } from '../models/user'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.css'] }) export class RegisterComponent implements OnInit { Title = new FormControl(''); PhoneNumber = new FormControl(''); Email = new FormControl(''); Password = new FormControl(''); datasaved = false; regUser : User; constructor(private employeeservice: EmplyeeserviceService) { } ngOnInit() { this.setFormState(); } setFormState(): void { this.regUser = new User(); this.regUser.Id = 0; this.regUser.RoleId = Role.Customer; this.regUser.Email = this.Email.value; this.regUser.Title = this.Title.value; this.regUser.PhoneNumber = this.PhoneNumber.value; this.regUser.Password = <PASSWORD>; } onSubmit() { this.setFormState(); let employee = this.regUser; this.createemployee(employee); this.regUser = new User(); } createemployee(employee: User) { this.employeeservice.createemployee(employee).subscribe( (data) => { if (data != null) { localStorage.setItem('currentUser', data.profileDetails); localStorage.setItem('currentUserToken', data.tokenString); localStorage.setItem('IsLoggedIn', 'true'); localStorage.setItem('currentUserRole', data.profileDetails.roleId); } this.Email.setValue(""); this.Password.setValue(""); this.Title.setValue(""); this.PhoneNumber.setValue(""); window.location.href = '/home'; }, (error) => { //window.alert(error.error); if (error.status == 401) { localStorage.setItem('IsLoggedIn', 'false'); window.location.href = '/login'; } else window.alert(error.error.error); } ) } } <file_sep>import { Component, OnInit, NgZone } from '@angular/core'; import { EmplyeeserviceService } from '../services/user-service'; import { FormControl } from '@angular/forms'; import { BillItem } from '../models/user'; import { error } from '@angular/compiler/src/util'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { SearchText = new FormControl(''); BillItems = []; Products = []; SubTotal = 0; ItemCount = 0; Discount = new FormControl(0); VAT = new FormControl(0); Total = 0; json = { }; constructor(private employeeservice: EmplyeeserviceService, private ngZone: NgZone) { } ngOnInit() { this.SearchText.setValue(""); this.GetProducts(this.json); this.GetCategories(this.json); window['angularComponentReference'] = { component: this, zone: this.ngZone, CancelSaleFunction: () => this.Cancel(), ConfirmSaleFunction: () => this.ConfirmSale({}) }; } GetProducts(jsonData: any) { jsonData.Title = this.SearchText.value; jsonData.CategoryId = this.employeeservice.CategorySelected; this.employeeservice.GetAllProducts(jsonData).subscribe( (data) => { if (data != null) { this.employeeservice.Products = data.data; } }, (error) => { //window.alert(error.error); if (error.status == 401) { localStorage.setItem('IsLoggedIn', 'false'); window.location.href = '/login'; } else window.alert(error.error.error); }) } GetCategories(jsonData: any) { this.employeeservice.GetAllCategories(jsonData).subscribe( (data) => { if (data != null) { this.employeeservice.Categories = data.data; } }, (error) => { //window.alert(error.error); if (error.status == 401) { localStorage.setItem('IsLoggedIn', 'false'); window.location.href = '/login'; } else window.alert(error.error.error); } ) } onKey(event: any) { this.SearchText.setValue(event.target.value); this.GetProducts(this.json); } ChangeCategory(category: any) { if (category != null) { this.employeeservice.CategorySelected = category.id } else { this.employeeservice.CategorySelected = 0; } this.GetProducts(this.json); } IsSelected(category: any) { if (this.employeeservice.CategorySelected == category.id) return true; else return false; } SelectProduct(product: any) { let item = this.employeeservice.BillItems.find(ob => ob.id === product.id); if (!item) { product.quantity = 1; this.employeeservice.BillItems.push(product); } else { item.quantity += 1; } this.CalculateSubTotal(); } IncreaseQuantity(product: any) { let item = this.employeeservice.BillItems.find(ob => ob.id === product.id); if (!item) { product.quantity = 1; this.employeeservice.BillItems.push(product); } else { item.quantity += 1; } this.CalculateSubTotal(); } DecreaseQuantity(product: any) { let item = this.employeeservice.BillItems.find(ob => ob.id === product.id); if (!item) { product.quantity = 1; this.employeeservice.BillItems.push(product); } else { item.quantity -= 1; if (item.quantity == 0) { this.employeeservice.BillItems = this.employeeservice.BillItems.filter(a => a.id !== item.id); } } this.CalculateSubTotal(); } RemoveItem(product: any) { let item = this.employeeservice.BillItems.find(ob => ob.id === product.id); if (item) { this.employeeservice.BillItems = this.employeeservice.BillItems.filter(a => a.id !== item.id); } this.CalculateSubTotal(); } CalculateSubTotal() { this.SubTotal = 0; this.ItemCount = 0; this.employeeservice.BillItems.forEach(item => this.SubTotal += item.quantity * item.unitPrice); this.Total = this.SubTotal - (this.Discount.value * this.SubTotal / 100) + (this.VAT.value * this.SubTotal / 100); this.employeeservice.BillItems.forEach(item => this.ItemCount += item.quantity); } Cancel() { this.employeeservice.BillItems = []; this.SubTotal = 0; this.Total = 0; this.ItemCount = 0; this.Discount.setValue(0); this.VAT.setValue(0); } ConfirmSale(jsonData: any) { if (this.employeeservice.BillItems.length == 0) { return; } jsonData = {}; jsonData.InvoiceNumber = ""; jsonData.DateOfSale = Date.now; jsonData.DiscountPercent = this.Discount.value; jsonData.VAT = this.VAT.value; jsonData.SubTotal = this.SubTotal; jsonData.InvoiceTotal = this.Total; jsonData.BillItems = []; this.employeeservice.BillItems.forEach(item => { let newItem = new BillItem() newItem.ProductId = item.id; newItem.Quantity = item.quantity; jsonData.BillItems.push(newItem) }); if (jsonData.DiscountPercent > 100 || jsonData.VAT > 100) { window.alert("Discount and VAT can not be greater than 100%"); return; } this.employeeservice.AddInvoice(jsonData).subscribe(data => { window.alert("Your Order is Successfull\nYour GrandTotal is " + this.Total + " EUR"); this.GetProducts(this.json); this.Cancel(); }, (error) => { if (error.status == 401) { localStorage.setItem('IsLoggedIn', 'false'); window.location.href = '/login'; } else window.alert(error.error.error); }); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; import { User, Role } from '../models/user'; @Injectable({ providedIn: 'root' }) export class EmplyeeserviceService { Products = []; Categories = []; CategorySelected = 0; BillItems = []; url = 'http://localhost:1100/' constructor(private http: HttpClient) { } createemployee(user: User): Observable<any> { //this.sendAjaxCall('Account/RegisterUser', user); return this.sendAjaxCall(this.url + 'Account/RegisterUser', user); } loginUser(user: User): Observable<any> { return this.sendAjaxCall(this.url + 'Account/LogOn', user); } logOutUser(): Observable<any> { return this.sendAjaxCall(this.url + 'Account/LogOff', {}); } GetAllProducts(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Product/GetAll', jsonData); } GetAllCategories(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Category/GetAll', jsonData); } AddInvoice(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Invoice/Add', jsonData); } AddProduct(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Product/Add', jsonData); } AddCategory(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Category/Add', jsonData); } EditCategory(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Category/edit', jsonData); } EditProduct(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Product/edit', jsonData); } DeleteProduct(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Product/delete', jsonData); } DeleteCategory(jsonData: any): Observable<any> { return this.sendAjaxCall(this.url + 'Category/Delete', jsonData); } sendAjaxCall(requestUrl: string, jsonData: Object): Observable<any> { var currentUserToken = localStorage.getItem('currentUserToken'); var httpOptions = { headers: <HttpHeaders>new HttpHeaders({ 'Authorization': `Bearer ${currentUserToken ? currentUserToken : ''}` }) }; return this.http.post<User>(requestUrl, jsonData, httpOptions); } } <file_sep> import { Component, OnInit } from '@angular/core'; import { EmplyeeserviceService } from '../services/user-service'; import { User, Role } from '../models/user'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { Email = new FormControl(''); Password = new FormControl(''); datasaved = false; loggingUser: User; constructor(private employeeservice: EmplyeeserviceService) { } ngOnInit() { this.setFormState(); } setFormState(): void { this.loggingUser = new User(); this.loggingUser.Email = this.Email.value; this.loggingUser.Password = this.Password.value; } onSubmit() { this.setFormState(); let employee = this.loggingUser; this.Login(employee); this.loggingUser = new User(); } Login(employee: User) { this.employeeservice.loginUser(employee).subscribe( (data) => { if (data != null) { localStorage.setItem('currentUser', data.profileDetails); localStorage.setItem('currentUserToken', data.tokenString); localStorage.setItem('IsLoggedIn', 'true'); localStorage.setItem('currentUserRole', data.profileDetails.roleId); } this.Email.setValue(""); this.Password.setValue(""); window.location.href = '/home'; }, (error) => { //window.alert(error.error); if (error.status == 401) { localStorage.setItem('IsLoggedIn', 'false'); window.location.href = '/login'; } else window.alert(error.error.error); } ) } } <file_sep>export class User { Id: number; Title: string; Email: string; Password: string; PhoneNumber: string; RoleId : Role } export enum Role { None = 0, Admin = 1, Customer = 2 } export class BillItem { ProductId: number; Quantity: number; } <file_sep>import { Category } from './category'; export class Product { constructor( Id: number, Title: string, UnitPrice: number, AvailableQuantity: number, ImageName: string, CategoryId: number, Category: Category, ) {} } <file_sep>import { Component, OnInit } from '@angular/core'; import { HomeComponent } from '../home.component'; import { AppComponent } from 'src/app/app.component'; import { Product } from 'src/app/models/product'; import { Category } from 'src/app/models/category'; import { EmplyeeserviceService } from 'src/app/services/user-service'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-admin', templateUrl: './admin.component.html', styleUrls: ['./admin.component.css'] }) export class AdminComponent implements OnInit { product = new Product(0,'',0,0,'',0,null); category = new Category(0,''); ProductList = []; CategoryList = []; json: {}; constructor(private app: AppComponent, private employeeservice: EmplyeeserviceService) { this.app.ShowProductDiv = false; } ngOnInit() { this.app.isAdminPage = true; this.app.AdminPageText = 'Home'; this.GetProducts(); this.GetCategories(); } ShowCategories() { this.app.ShowProductDiv = false; } ShowProducts() { this.app.ShowProductDiv = true; } GetShowProductValue() { return this.app.ShowProductDiv; } GetProducts() { this.employeeservice.GetAllProducts({}).subscribe( (data) => { if (data != null) { this.ProductList = data.data; } }, (error) => { if (error.status == 401) { localStorage.setItem('IsLoggedIn', 'false'); window.location.href = '/login'; } else window.alert(error.error.error); }) } GetCategories() { this.employeeservice.GetAllCategories({}).subscribe( (data) => { if (data != null) { this.CategoryList = data.data; } }, (error) => { if (error.status == 401) { localStorage.setItem('IsLoggedIn', 'false'); window.location.href = '/login'; } else window.alert(error.error.error); } ) } productForm = new FormGroup({ id: new FormControl(0, Validators.required), categoryId: new FormControl('', Validators.required), Title: new FormControl('', Validators.required), UnitPrice: new FormControl(0, Validators.required), AvailableQuantity: new FormControl(0, Validators.required) }); get f() { return this.productForm.controls; } AddProduct() { this.employeeservice.AddProduct(this.productForm.value).subscribe(result => { this.GetProducts(); this.ClearProductForm(); }, (error) => { if (error.status == 401) { window.location.href = '/login'; } else window.alert(error.error.error); }) } editProduct(data: any) { if (data) { this.productForm.controls['id'].setValue(data.id); this.productForm.controls['Title'].setValue(data.title); this.productForm.controls['categoryId'].setValue(data.categoryId); this.productForm.controls['UnitPrice'].setValue(data.unitPrice); this.productForm.controls['AvailableQuantity'].setValue(data.availableQuantity); } } updateProduct() { this.employeeservice.EditProduct(this.productForm.value).subscribe(result => { this.GetProducts(); this.ClearProductForm(); }, (error) => { if (error.status == 401) { window.location.href = '/login'; } else window.alert(error.error.error); }) } ClearProductForm() { this.productForm.controls['id'].setValue(0); this.productForm.controls['Title'].setValue(''); this.productForm.controls['categoryId'].setValue(0); this.productForm.controls['UnitPrice'].setValue(0); this.productForm.controls['AvailableQuantity'].setValue(0); this.productForm.markAsUntouched(); } deleteProduct(data: any) { this.employeeservice.DeleteProduct(data).subscribe(result => { this.GetProducts(); }, (error) => { if (error.status == 401) { window.location.href = '/login'; } else window.alert(error.error.error); }) } categoryForm = new FormGroup({ id: new FormControl(0, Validators.required), Title: new FormControl('', Validators.required), }); get c() { return this.categoryForm.controls; } AddCategory() { this.employeeservice.AddCategory(this.categoryForm.value).subscribe(result => { this.GetCategories(); this.ClearCategoryForm(); }, (error) => { if (error.status == 401) { window.location.href = '/login'; } else window.alert(error.error.error); }) } editCategory(data: any) { if (data) { this.categoryForm.controls['id'].setValue(data.id); this.categoryForm.controls['Title'].setValue(data.title); } } updateCategory() { if (this.categoryForm.valid) { this.employeeservice.EditCategory(this.categoryForm.value).subscribe(result => { this.GetCategories(); this.ClearCategoryForm(); }, (error) => { if (error.status == 401) { window.location.href = '/login'; } else window.alert(error.error.error); }) } } ClearCategoryForm() { this.categoryForm.controls['id'].setValue(0); this.categoryForm.controls['Title'].setValue(''); this.categoryForm.markAsUntouched(); } deleteCategory(data: any) { this.employeeservice.DeleteCategory(data).subscribe(result => { this.GetCategories(); }, (error) => { if (error.status == 401) { window.location.href = '/login'; } else window.alert(error.error.error); }) } changeWebsite(e) { //console.log(e.target.value); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { EmplyeeserviceService } from './services/user-service'; import { LocationStrategy } from '@angular/common'; import { Role } from './models/user'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { isLoggedIn = false; isAdmin = false; isAdminPage = false; AdminPageText = 'Admin Panel'; public ShowProductDiv = false; constructor(private employeeservice: EmplyeeserviceService) { } ngOnInit() { this.getLoggedInValue(); this.GetAdminValue(); this.GetAdminPageText(); } getLoggedInValue() { if ((localStorage.getItem('IsLoggedIn') || '') === 'true') this.isLoggedIn = true; else this.isLoggedIn = false; } GetAdminValue() { if (((localStorage.getItem('currentUserRole') || '') === ('' + Role.Admin)) && this.isLoggedIn) this.isAdmin = true; else this.isAdmin = false; } ToggleAdminPage() { if (this.isAdminPage) { this.isAdminPage = false; window.location.href = '/home'; } else { this.isAdminPage = true; window.location.href = '/home/admin'; } this.GetAdminPageText(); } GetAdminPageText(){ if (this.isAdminPage) { this.AdminPageText = 'Home'; } else { this.AdminPageText = 'Admin Panel'; } } LogOut() { localStorage.setItem('IsLoggedIn', 'false'); this.employeeservice.logOutUser().subscribe( (data) => { window.location.href = '/login'; }, (error) => { if (error.status == 401) { window.location.href = '/login'; } else window.alert(error.error.error); } ); } LogIn() { localStorage.setItem('IsLoggedIn', 'true'); this.isLoggedIn = true; } title = 'POSWeb'; }
36da9f11cdcee6065ed0f70e79cb38b282f47248
[ "TypeScript" ]
8
TypeScript
Rajni500/POSWeb
4c7d7cb77bebe7cde4be6144c4f69d3ab870d8b2
88a39e4810697cf78ce97dd8743670bcdeabd27d
refs/heads/master
<repo_name>ali4desgin/alhonofapp<file_sep>/app/src/main/java/com/alhonof/app/Api/Links.java package com.alhonof.app.Api; public class Links { public static String base_url = "http://192.168.127.12/app10/"; public static String login_url = base_url + "login.php"; public static String register_url = base_url + "register.php"; public static String profile_url = base_url + "profile.php"; public static String get_info = base_url + "user.php"; public static String change_info = base_url + "edituser.php"; public static String password = base_url + "password.php"; } <file_sep>/app/src/main/java/com/alhonof/app/RegisterStep2.java package com.alhonof.app; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.alhonof.app.Api.Links; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class RegisterStep2 extends AppCompatActivity { SharedPref sharedPref; EditText carnameID,carmodelID,carnumberID,issuedateID,expiredateID; Button doneButton; String user_id = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_step2); sharedPref =new SharedPref(RegisterStep2.this); // Intent intent = getIntent(); user_id = sharedPref.getString("user_id"); // // if(user_id.isEmpty()){ // // Intent intent2 = new Intent(RegisterStep2.this, RegisterActivity.class); // intent2.putExtra("user_id",user_id); // startActivity(intent2); // } doneButton = findViewById(R.id.doneID); issuedateID = findViewById(R.id.issuedateID); carnumberID = findViewById(R.id.carnumberID2); carmodelID = findViewById(R.id.carmodeID2); carnameID = findViewById(R.id.carnameID2); expiredateID = findViewById(R.id.expiredateID); doneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { regsiter(); } }); } public void regsiter(){ String issue = issuedateID.getText().toString(); String expire = expiredateID.getText().toString(); String number = carnumberID.getText().toString(); String name = carnameID.getText().toString(); String model = carmodelID.getText().toString(); if(issue.isEmpty() || expire.isEmpty() || number.isEmpty() || name.isEmpty() || model.isEmpty() ){ Toast.makeText(RegisterStep2.this,"All field should be not empty",Toast.LENGTH_LONG).show(); }else { register_progress(name,number,model,issue,expire); } } public void register_progress(final String name,final String number,final String model,final String issue, final String expire){ RequestQueue queue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.POST,Links.register_url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); if(jsonObject.getBoolean("res")){ Intent intent = new Intent(RegisterStep2.this,HomeActivity.class); startActivity(intent); }else{ Toast.makeText(RegisterStep2.this,jsonObject.getString("message"),Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> map = new HashMap(); map.put("car_name",name); map.put("car_number",number); map.put("car_model", model); map.put("issue_date",issue); map.put("expire_date",expire); map.put("user_id",user_id); map.put("step","2"); return map; } }; queue.add(stringRequest); } } <file_sep>/app/src/main/java/com/alhonof/app/UsernameEditActivity.java package com.alhonof.app; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.alhonof.app.Api.Links; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class UsernameEditActivity extends AppCompatActivity { String user_id; SharedPref sharedPref; Button saveBtn,cancelBtn; EditText usernameEd; TextView usernameTxtView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_username_edit); sharedPref = new SharedPref(UsernameEditActivity.this); user_id = sharedPref.getString("user_id"); setUiElements(); setUiElementEvenets(); loadData(); } @SuppressLint("WrongViewCast") private void setUiElements(){ saveBtn = findViewById(R.id.saveBtnID); cancelBtn = findViewById(R.id.cancelBtn); usernameEd = findViewById(R.id.usernameEditTxt); usernameTxtView = findViewById(R.id.usernameTxt); } private void setUiElementEvenets() { saveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!usernameEd.getText().toString().isEmpty()){ change(); } } }); cancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(UsernameEditActivity.this,SettingsActivity.class); startActivity(intent); } }); } private void change(){ RequestQueue queue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.POST,Links.change_info, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); if(jsonObject.getBoolean("res")){ Intent intent = new Intent(UsernameEditActivity.this,SettingsActivity.class); startActivity(intent); }else{ Toast.makeText(UsernameEditActivity.this,jsonObject.getString("message"),Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> map = new HashMap(); map.put("user_id",user_id); map.put("key","username"); map.put("value",usernameEd.getText().toString()); return map; } }; // Add the request to the RequestQueue. queue.add(stringRequest); } private void loadData(){ RequestQueue queue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.POST,Links.get_info, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); if(jsonObject.getBoolean("res")){ String userstr = jsonObject.getString("user"); JSONObject user = new JSONObject(userstr); usernameTxtView.setText(user.getString("username")); }else{ Toast.makeText(UsernameEditActivity.this,jsonObject.getString("message"),Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> map = new HashMap(); map.put("user_id",user_id); return map; } }; // Add the request to the RequestQueue. queue.add(stringRequest); } } <file_sep>/app/src/main/java/com/alhonof/app/GeneralAdapter.java package com.alhonof.app; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; public class GeneralAdapter extends BaseAdapter { ArrayList<String> list = new ArrayList<String>(); Context context; GeneralAdapter(Context context){ list.add("Stop Warinings"); list.add("Stop Sending SMS"); this.context = context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { view = LayoutInflater.from(context).inflate(R.layout.general_list_row,viewGroup,false); TextView textView = view.findViewById(R.id.textView3); textView.setText(list.get(i)); return view; } } <file_sep>/app/src/main/java/com/alhonof/app/SettingsActivity.java package com.alhonof.app; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; public class SettingsActivity extends AppCompatActivity { ListView listView,listView2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); listView = findViewById(R.id.accountListView); listView2 = findViewById(R.id.accountListView2); AccountListViewAdapter accountListViewAdapter = new AccountListViewAdapter(SettingsActivity.this); listView.setAdapter(accountListViewAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (i==0){ Intent intent = new Intent(SettingsActivity.this,UsernameEditActivity.class); startActivity(intent); }else if (i==1){ Intent intent = new Intent(SettingsActivity.this,PhoneEditActivity.class); startActivity(intent); }else if (i==2){ Intent intent = new Intent(SettingsActivity.this,PasswordEditActivity.class); startActivity(intent); }else if (i==3){ Intent intent = new Intent(SettingsActivity.this,CountryEditActivity.class); startActivity(intent); } } }); GeneralAdapter generalAdapter = new GeneralAdapter(SettingsActivity.this); listView2.setAdapter(generalAdapter); } } <file_sep>/app/src/main/java/com/alhonof/app/RegisterActivity.java package com.alhonof.app; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.bigkoo.pickerview.MyOptionsPickerView; import com.alhonof.app.Api.Links; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class RegisterActivity extends AppCompatActivity { private Button ToRegisterStep2; SharedPref sharedPref; EditText usernameID,passwordID,emailID,confirmpasswordID,phoneID; TextView cityTxt; String city = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); ToRegisterStep2 = (Button) findViewById(R.id.ToRegisterStep2); usernameID = (EditText) findViewById(R.id.carnameID2); emailID = (EditText) findViewById(R.id.emailID); confirmpasswordID = (EditText) findViewById(R.id.confirmpasswordID2); passwordID = (EditText) findViewById(R.id.passwordID2); phoneID = (EditText) findViewById(R.id.phoneID); cityTxt = (TextView) findViewById(R.id.cityTxt); sharedPref =new SharedPref(RegisterActivity.this); final MyOptionsPickerView singlePicker = new MyOptionsPickerView(RegisterActivity.this); final ArrayList<String> items = new ArrayList<String>(); items.add("الرياض"); items.add("المدينة"); items.add("مكة"); items.add("جدة"); singlePicker.setPicker(items); singlePicker.setTitle("Choose city"); singlePicker.setCyclic(false); singlePicker.setSelectOptions(0); singlePicker.setOnoptionsSelectListener(new MyOptionsPickerView.OnOptionsSelectListener() { @Override public void onOptionsSelect(int options1, int option2, int options3) { cityTxt.setText(items.get(options1)); city = items.get(options1); // singleTVOptions.setText("Single Picker " + items.get(options1)); //Toast.makeText(RegisterActivity.this, "" + items.get(options1), Toast.LENGTH_SHORT).show(); //vMasker.setVisibility(View.GONE); } }); cityTxt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { singlePicker.show(); } }); ToRegisterStep2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { regsiter(); } }); } public void regsiter(){ String username = usernameID.getText().toString(); String password = <PASSWORD>(); String confirmpassword = confirmpasswordID.getText().toString(); String phone = phoneID.getText().toString(); String email = emailID.getText().toString(); if(username.isEmpty() || password.isEmpty() || confirmpassword.isEmpty() || phone.isEmpty() || email.isEmpty() || city.isEmpty()){ Toast.makeText(RegisterActivity.this,"All field should be not empty",Toast.LENGTH_LONG).show(); }else { if(!password.matches(confirmpassword)){ Toast.makeText(RegisterActivity.this,"password should match confirm password",Toast.LENGTH_LONG).show(); }else{ register_progress(email,username,phone,city,password); } } } public void register_progress(final String email,final String username,final String phone,final String city, final String password){ RequestQueue queue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.POST,Links.register_url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); Toast.makeText(RegisterActivity.this,jsonObject.getString("message"),Toast.LENGTH_LONG).show(); if(jsonObject.getBoolean("res")){ String id = jsonObject.getString("user_id"); Intent intent = new Intent(RegisterActivity.this,RegisterStep2.class); intent.putExtra("user_id",id); sharedPref.saveToShared("user_id",id); startActivity(intent); }else{ Toast.makeText(RegisterActivity.this,jsonObject.getString("message"),Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(RegisterActivity.this,error.toString(),Toast.LENGTH_LONG).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> map = new HashMap(); map.put("email",email); map.put("password",<PASSWORD>); map.put("username",username); map.put("city",city); map.put("phone",phone); map.put("step","1"); return map; } }; // Add the request to the RequestQueue. queue.add(stringRequest); } } <file_sep>/app/src/main/java/com/alhonof/app/CountryEditActivity.java package com.alhonof.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; public class CountryEditActivity extends AppCompatActivity { ListView countryList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_country_edit); countryList = findViewById(R.id.countryList); CountryAdapter countryAdapter = new CountryAdapter(CountryEditActivity.this); countryList.setAdapter(countryAdapter); } }
d3aebb9692c652534ec12dbc15600cb112187fa0
[ "Java" ]
7
Java
ali4desgin/alhonofapp
c970d2f8af37f7f2b9739631aadc8b8c74102b79
9812f76ae2dc715c04772c12e0847ce8d0171714
refs/heads/master
<repo_name>Egardoz01/PhoneNumbersDictionary<file_sep>/PhoneNumbersDictionary/Data/OrganizationFilesRepositiry.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public class OrganizationFilesRepositiry { private readonly SqlConnection _conn; public OrganizationFilesRepositiry(SqlConnection conn) { _conn = conn; } public int Add(OrganizationFile file) { string query; query = String.Format("INSERT INTO OrganizationFile (Path,Name,OrganizationId) VALUES ('{0}','{1}',{2})", file.Path, file.Name, file.OrganizaionId); SqlCommand cmd = new SqlCommand(query, _conn); return cmd.ExecuteNonQuery(); } public int Remove(OrganizationFile file) { string query; query = String.Format("DELETE FROM OrganizationFile WHERE Id={0}", file.Id); SqlCommand cmd = new SqlCommand(query, _conn); return cmd.ExecuteNonQuery(); } public List<OrganizationFile> GetFilesByOrganizationId(int id) { List<OrganizationFile> files = new List<OrganizationFile>(); string query = "SELECT * FROM OrganizationFile WHERE OrganizationId=" + id; SqlCommand cmd = new SqlCommand(query, _conn); var reader = cmd.ExecuteReader(); while (reader.Read()) { OrganizationFile phone = new OrganizationFile(reader); files.Add(phone); } return files; } public void RemoveByOrganizationId(int Id) { string query = "DELETE FROM OrganizationFile WHERE OrganizationId=" + Id; SqlCommand cmd = new SqlCommand(query, _conn); cmd.ExecuteNonQuery(); } } } <file_sep>/PhoneNumbersDictionary/Data/Models/Organization.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public class Organization { public int Id { get; set; } public string Name { get; set; } public string Location { get; set; } public string Profile { get; set; } public string PhotoPath { get; set; } public List<PhoneNumber> PhoneNumbers { get; set; } public List<PhoneNumber> PhoneNumbersToAdd { get; set; }//все списки нужны, чтобы эффективно динамически управлять данными public List<PhoneNumber> PhoneNumbersToEdit{ get; set; } public List<PhoneNumber> PhoneNumbersToRemove { get; set; } public List<AdditionalInfo> AdditionalInfos { get; set; } public List<AdditionalInfo> AdditionalInfosToAdd { get; set; } public List<AdditionalInfo> AdditionalInfosToEdit { get; set; } public List<AdditionalInfo> AdditionalInfosToRemove { get; set; } public List<OrganizationFile> OrganizationFiles { get; set; } public List<OrganizationFile> OrganizationFilesToAdd { get; set; } public List<OrganizationFile> OrganizationFilesToRemove { get; set; } public Organization() { PhoneNumbersToAdd = new List<PhoneNumber>(); PhoneNumbersToEdit = new List<PhoneNumber>(); PhoneNumbersToRemove = new List<PhoneNumber>(); AdditionalInfosToAdd = new List<AdditionalInfo>(); AdditionalInfosToRemove = new List<AdditionalInfo>(); AdditionalInfosToEdit = new List<AdditionalInfo>(); OrganizationFiles = new List<OrganizationFile>(); OrganizationFilesToAdd = new List<OrganizationFile>(); OrganizationFilesToRemove = new List<OrganizationFile>(); } public Organization(SqlDataReader reader) :this() { Id = (int)reader["Id"]; Name = (string)reader["Name"]; Profile = (string)reader["Profile"]; Location = (string)reader["Location"]; PhotoPath = (string)reader["Photo"]; } public override string ToString() { return Name+" - "+Profile; } } } <file_sep>/PhoneNumbersDictionary/Filters/OrganizationBasicFilter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { class OrganizationBasicFilter :IOrganizationFilter { public string GetCountQuery() { return "SELECT COUNT (*) FROM Organization"; } public string GetQuery() { return ""; } public string GetSelectQuery() { return "SELECT * FROM Organization"; } } } <file_sep>/PhoneNumbersDictionary/Db.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Windows.Forms; namespace PhoneNumbersDictionary { public class Db { public SqlConnection _conn { get; private set; } public OrganizationRepository OrganizationRepository { get; private set; } public PhoneNumberRepository PhoneNumberRepository { get; private set; } public OrganizationFilesRepositiry OrganizationFilesRepositiry { get; private set; } public AdditionalInfoRepository AdditionalInfoRepository { get; private set; } public Db() { GetConnection(); OrganizationRepository = new OrganizationRepository(_conn); PhoneNumberRepository = new PhoneNumberRepository(_conn); AdditionalInfoRepository = new AdditionalInfoRepository(_conn); OrganizationFilesRepositiry = new OrganizationFilesRepositiry(_conn); } private static string GetConnectionString() { return @"Data Source=(localdb)\MSSQLLocalDB; AttachDbFilename=D:\Documents\Visual Studio 2019\Projects\PhoneNumbersDictionary\PhoneNumbersDictionary\PhoneNumbersDictionary.mdf; Initial Catalog = PhoneNumbersDictionary; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False;MultipleActiveResultSets=True;"; } public SqlConnection GetConnection() { if (_conn != null) { return _conn; } string sConnection = GetConnectionString(); _conn = new SqlConnection(sConnection); try { _conn.Open(); } catch (Exception ex) { MessageBox.Show("Ошибка при подключении к базе данных: " + ex.Message); } return _conn; } public int AddOrganization(Organization org) { int id = OrganizationRepository.Add(org); foreach (var phone in org.PhoneNumbersToAdd) { phone.OrganizaionId = id; PhoneNumberRepository.Add(phone); } foreach (var info in org.AdditionalInfosToAdd) { info.OrganizaionId = id; AdditionalInfoRepository.Add(info); } foreach (var file in org.OrganizationFilesToAdd) { file.OrganizaionId = id; OrganizationFilesRepositiry.Add(file); } return id; } public void EditOrganization(Organization org) { OrganizationRepository.Edit(org); int id = org.Id; foreach (var phone in org.PhoneNumbersToAdd) { phone.OrganizaionId = id; PhoneNumberRepository.Add(phone); } foreach (var phone in org.PhoneNumbersToEdit) { PhoneNumberRepository.Edit(phone); } foreach (var phone in org.PhoneNumbersToRemove) { PhoneNumberRepository.Remove(phone); } foreach (var info in org.AdditionalInfosToAdd) { info.OrganizaionId = id; AdditionalInfoRepository.Add(info); } foreach (var info in org.AdditionalInfosToEdit) { AdditionalInfoRepository.Edit(info); } foreach (var info in org.AdditionalInfosToRemove) { AdditionalInfoRepository.Remove(info); } foreach (var file in org.OrganizationFilesToAdd) { file.OrganizaionId = id; OrganizationFilesRepositiry.Add(file); } foreach (var file in org.OrganizationFilesToRemove) { deleteFile(file.Path); OrganizationFilesRepositiry.Remove(file); } } public List<Organization> GetOrganizations(IOrganizationFilter filter, int offset=0, int limit=100) { List<Organization> orgs = OrganizationRepository.GetOrganizations(filter.GetSelectQuery() + " ORDER BY Id OFFSET "+ offset + " ROWS FETCH NEXT "+limit+" ROWS ONLY;"); return orgs; } public int GetOrganizationsCount(IOrganizationFilter filter) { SqlCommand cmd = new SqlCommand(filter.GetCountQuery(), _conn); return (int)cmd.ExecuteScalar(); } public void LoadOrganizationData(Organization org) { org.PhoneNumbers = PhoneNumberRepository.GetPhoneNumbersByOrganizationId(org.Id); org.AdditionalInfos = AdditionalInfoRepository.GetAdditionalInfosByOrganizationId(org.Id); org.OrganizationFiles = OrganizationFilesRepositiry.GetFilesByOrganizationId(org.Id); } public string copyFileLocally(Organization org, string path) { try { string newPath; newPath = Directory.GetCurrentDirectory(); newPath = Path.Combine(newPath, "Files"); if (!Directory.Exists(newPath)) Directory.CreateDirectory(newPath); newPath = Path.Combine(newPath, org.Id.ToString()); if (!Directory.Exists(newPath)) Directory.CreateDirectory(newPath); newPath = Path.Combine(newPath, Guid.NewGuid().ToString()+ Path.GetExtension(path)); File.Copy(path, newPath); return newPath; } catch (Exception ex) { MessageBox.Show("Ошибка при копировании файла " + ex.Message); } return ""; } public void deleteFile(string path) { if (File.Exists(path)) { try { File.Delete(path); } catch(Exception ex) { MessageBox.Show("Ошибка при удалени файла "+ ex.Message); } } } public void RemoveOrganization(Organization org) { PhoneNumberRepository.RemoveByOrganizationId(org.Id); OrganizationFilesRepositiry.RemoveByOrganizationId(org.Id); AdditionalInfoRepository.RemoveByOrganizationId(org.Id);//Удаляем всю информацию, связанную с организацией OrganizationRepository.RemoveByOrganizationId(org.Id);//удаляем саму организацию } } } <file_sep>/PhoneNumbersDictionary/Data/Models/PhoneNumber.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public class PhoneNumber { public int Id { get; set; } public string Name { get; set; } public string PhoneNumberstr { get; set; } public int OrganizaionId { get; set; } public override string ToString() { return Name+": "+PhoneNumberstr; } public PhoneNumber() { } public PhoneNumber(PhoneNumber phone) { Id = phone.Id; Name = phone.Name; PhoneNumberstr = phone.PhoneNumberstr; OrganizaionId = phone.OrganizaionId; } public PhoneNumber(SqlDataReader reader) { Id = (int)reader["Id"]; Name = (string)reader["Name"]; PhoneNumberstr = (string)reader["PhoneNumber"]; OrganizaionId = (int)reader["OrganizationId"]; } } } <file_sep>/PhoneNumbersDictionary/MainForm.cs using System; using System.Windows.Forms; namespace PhoneNumbersDictionary { public partial class MainForm : Form { private readonly Db db; private int pageSize; private int curPage; private IOrganizationFilter lastFilter; public MainForm() { InitializeComponent(); db = new Db(); } private void btnAddOrganization_Click(object sender, EventArgs e) { OrganizationForm form = new OrganizationForm(db); form.ShowDialog(); LoadAllOrganizations(); } private void LoadAllOrganizations() { curPage = 1; LoadOrganizationsByFilter(new OrganizationBasicFilter()); } private void LoadOrganizationsByFilter(IOrganizationFilter filter) { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; var watch = System.Diagnostics.Stopwatch.StartNew(); lastFilter = filter; pageSize = int.Parse(txtbxPageSIze.Text); int amount = db.GetOrganizationsCount(filter); lblOrgCount.Text = String.Format("По вашему запросу найдено {0} организаций",amount ); lblCurPage.Text = String.Format("Страница {0} из {1}",curPage, (amount+pageSize-1)/pageSize); if (curPage == 1) btnPrevPage.Enabled = false; else btnPrevPage.Enabled = true; if (curPage * pageSize >= amount) btnNextPage.Enabled = false; else btnNextPage.Enabled = true; lbOrganizations.Items.Clear(); lbOrganizations.Items.AddRange(db.GetOrganizations(filter, (curPage-1)*pageSize, pageSize).ToArray()); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Arrow; watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; lblExecutionTime.Text = "Выполнение запроса заняло "+elapsedMs/1000.0 +" секунд"; } private void MainForm_Load(object sender, EventArgs e) { LoadAllOrganizations(); } private void lbOrganizations_DoubleClick(object sender, EventArgs e) { Organization org = (Organization)lbOrganizations.SelectedItem; OrganizationForm form = new OrganizationForm(db,org); form.ShowDialog(); LoadAllOrganizations(); } private void btnOrgSearch_Click(object sender, EventArgs e) { OrganizationFilterByData filter = new OrganizationFilterByData(); filter.orgName = txtbxOrgName.Text; filter.orgNameComplete = rbNameComplete.Checked; filter.orgLocation = txtbxOrgLocation.Text; filter.orgLocationComplete = rbLocationComplete.Checked; filter.orgProfile = txtbxOrgProfile.Text; filter.orgProfileComplete = rbProfileComplete.Checked; LoadOrganizationsByFilter(filter); } private void btnShowAll_Click(object sender, EventArgs e) { curPage = 1; LoadAllOrganizations(); } private void btnPhoneSearch_Click(object sender, EventArgs e) { curPage = 1; OrganizationFilterByPhone filter = new OrganizationFilterByPhone(); filter.PhoneNumber = txtbxPhoneNumber.Text; filter.CompleteMatch = rbPhoneCompleteMatch.Checked; filter.IncludeOldNumbers = cbPhoneOldNumbers.Checked; LoadOrganizationsByFilter(filter); } private void btnSearchByInfo_Click(object sender, EventArgs e) { curPage = 1; OrganizationFilterByInfo filter = new OrganizationFilterByInfo(); filter.InfoData = txtbxInfoData.Text; filter.InfoType = txtbxInfoType.Text; filter.DataCompleteMatch = rbInfoDataComplete.Checked; filter.TypeCompleteMatch = rbInoTypeComlete.Checked; LoadOrganizationsByFilter(filter); } private void btnSearchByFile_Click(object sender, EventArgs e) { curPage = 1; OrganizationFilerByFile filter = new OrganizationFilerByFile(); filter.Filename = txtbxFileName.Text; filter.FilenameCompleteMatch = rbFileComleteMatch.Checked; LoadOrganizationsByFilter(filter); } private void txtbxPageSIze_Leave(object sender, EventArgs e) { int temp; if (!int.TryParse(txtbxPageSIze.Text, out temp)) { MessageBox.Show("Вводимое значение должно быть числом"); txtbxPageSIze.Focus(); } else { LoadOrganizationsByFilter(lastFilter); } } private void btnNextPage_Click(object sender, EventArgs e) { curPage++; LoadOrganizationsByFilter(lastFilter); } private void btnPrevPage_Click(object sender, EventArgs e) { curPage--; LoadOrganizationsByFilter(lastFilter); } } } <file_sep>/PhoneNumbersDictionary/PhoneNumberDialog.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PhoneNumbersDictionary { public partial class PhoneNumberDialog : Form { public PhoneNumber PhoneNumber { get; set; } public PhoneNumberDialog(PhoneNumber phone=null) { InitializeComponent(); PhoneNumber = phone; if (PhoneNumber == null) PhoneNumber = new PhoneNumber(); else { txtbxPhoneNumber.Text = PhoneNumber.PhoneNumberstr; txtbxtName.Text = PhoneNumber.Name; } } private void button1_Click(object sender, EventArgs e) { if (!doCheck()) return; PhoneNumber.Name = txtbxtName.Text; PhoneNumber.PhoneNumberstr = txtbxPhoneNumber.Text; DialogResult = DialogResult.OK; Close(); } private bool doCheck() { if (txtbxPhoneNumber.Text == "") { lblErrors.Text = "Номер телефона не может быть пустым"; lblErrors.Visible = true; return false; } if (txtbxtName.Text == "") { lblErrors.Text = "Имя контакта не может быть пустым"; lblErrors.Visible = true; return false; } return true; } } } <file_sep>/DbTest1/Program.cs using PhoneNumbersDictionary; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DbTest1 { class Program { static void Main(string[] args) { Db db = new Db(); int cnt_organizations = 1000000; int cnt_items = 1; int next_step = 1; for (int j = 1; j <= cnt_organizations; j++) { Organization org = new Organization(); org.Name = "Test Organization " + j; org.Location = "test Location " + j; org.Profile = "Test Profile " + j; for (int i = 0; i < cnt_items; i++) { PhoneNumber phone = new PhoneNumber(); phone.Name = "Test Phone " + i + " " + j; phone.PhoneNumberstr = "+712345"; org.PhoneNumbersToAdd.Add(phone); } for (int i = 0; i < cnt_items; i++) { AdditionalInfo info = new AdditionalInfo(); info.InfoData = "Test data " + i + " " + j; info.InfoType = "Test Type " + i + " " + j; org.AdditionalInfosToAdd.Add(info); } for (int i = 0; i < cnt_items; i++) { OrganizationFile file = new OrganizationFile(); file.Name = "test file name " + i + " " + j; file.Path = "test file path " + i + " " + j; org.OrganizationFilesToAdd.Add(file); } db.AddOrganization(org); if (next_step <= j * 100 / cnt_organizations) { Console.WriteLine(next_step + "% DONE"); next_step += 1; } } } } } <file_sep>/PhoneNumbersDictionary/Data/Models/AdditionalInfo.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public class AdditionalInfo { public int Id { get; set; } public string InfoType { get; set; } public string InfoData { get; set; } public int OrganizaionId { get; set; } public override string ToString() { return InfoType + ": " + InfoData; } public AdditionalInfo() { } public AdditionalInfo(AdditionalInfo info) { Id = info.Id; InfoData = info.InfoData; InfoType = info.InfoType; OrganizaionId = info.OrganizaionId; } public AdditionalInfo(SqlDataReader reader) { Id = (int)reader["Id"]; InfoType = (string)reader["InfoType"]; InfoData = (string)reader["InfoData"]; OrganizaionId = (int)reader["OrganizationId"]; } } } <file_sep>/PhoneNumbersDictionary/Filters/OrganizationFilterByPhone.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public class OrganizationFilterByPhone: IOrganizationFilter { public string PhoneNumber { get; set; } public bool CompleteMatch { get; set; } public bool IncludeOldNumbers { get; set; } public string GetCountQuery() { return "SELECT COUNT(DISTINCT Organization.id) " + GetQuery(); } public string GetQuery() { string query = "FROM Organization,PhoneNumber WHERE Organization.Id = PhoneNumber.OrganizationId "; if (PhoneNumber != "") { query+= " AND PhoneNumber.PhoneNumber "; if (CompleteMatch) query += "= '" + PhoneNumber + "' "; else query += "LIKE '%" + PhoneNumber + "%' "; } if (!IncludeOldNumbers) query += "AND PhoneNumber.Active=1"; return query; } public string GetSelectQuery() { return "SELECT DISTINCT Organization.Id, Organization.Name, Organization.Location, Organization.Profile, Organization.Photo " + GetQuery(); } } } <file_sep>/PhoneNumbersDictionary/Filters/OrganizationFilerByFile.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { class OrganizationFilerByFile:IOrganizationFilter { public string Filename; public bool FilenameCompleteMatch; public string GetCountQuery() { return "SELECT COUNT(DISTINCT Organization.id) " + GetQuery(); } public string GetQuery() { string query = "FROM OrganizationFile, Organization WHERE Organization.Id = OrganizationFile.OrganizationId AND OrganizationFile.Name "; if (FilenameCompleteMatch) query += "= '" + Filename + "'"; else query += "LIKE '%" + Filename + "%'"; return query; } public string GetSelectQuery() { return "SELECT DISTINCT Organization.Id, Organization.Name, Organization.Location, Organization.Profile, Organization.Photo " + GetQuery(); } } } <file_sep>/PhoneNumbersDictionary/Filters/IOrganizationFilter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public interface IOrganizationFilter { string GetQuery(); string GetCountQuery(); string GetSelectQuery(); } } <file_sep>/PhoneNumbersDictionary/Filters/OrganizationFilterByInfo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { class OrganizationFilterByInfo :IOrganizationFilter { public string InfoType { get; set; } public string InfoData { get; set; } public bool TypeCompleteMatch { get; set; } public bool DataCompleteMatch { get; set; } public string GetCountQuery() { return "SELECT COUNT(DISTINCT Organization.id) " + GetQuery(); } public string GetQuery() { string query = "FROM Organization,AdditionalInfo WHERE Organization.Id = AdditionalInfo.OrganizationId "; if (InfoType != "") { query += " AND AdditionalInfo.InfoType "; if (TypeCompleteMatch) query += "= '" + InfoType + "' "; else query += "LIKE '%" + InfoType + "%' "; } if (InfoType != "") { query += " AND AdditionalInfo.InfoData "; if (DataCompleteMatch) query += "= '" + InfoData + "'"; else query += "LIKE '%" + InfoData + "%'"; } return query; } public string GetSelectQuery() { return "SELECT DISTINCT Organization.Id, Organization.Name, Organization.Location, Organization.Profile, Organization.Photo " + GetQuery(); } } } <file_sep>/PhoneNumbersDictionary/Data/Models/OrganizationFile.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public class OrganizationFile { public int Id { get; set; } public string Path { get; set; } public string Name { get; set; } public int OrganizaionId { get; set; } public override string ToString() { return Name; } public OrganizationFile() { } public OrganizationFile(OrganizationFile file) { Id = file.Id; Name = file.Name; Path = file.Path; OrganizaionId = file.OrganizaionId; } public OrganizationFile(SqlDataReader reader) { Id = (int)reader["Id"]; Name = (string)reader["Name"]; Path = (string)reader["Path"]; OrganizaionId = (int)reader["OrganizationId"]; } } } <file_sep>/PhoneNumbersDictionary/AdditionalInfoDialog.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PhoneNumbersDictionary { public partial class AdditionalInfoDialog : Form { public AdditionalInfo AdditionalInfo; public AdditionalInfoDialog(AdditionalInfo info = null) { InitializeComponent(); AdditionalInfo = info; if (AdditionalInfo != null) { txtbxInfoData.Text = AdditionalInfo.InfoData; txtbxInfoType.Text = AdditionalInfo.InfoType; } else AdditionalInfo = new AdditionalInfo(); } private void btnOK_Click(object sender, EventArgs e) { if (!doCeck()) return; AdditionalInfo.InfoData = txtbxInfoData.Text; AdditionalInfo.InfoType = txtbxInfoType.Text; DialogResult = DialogResult.OK; Close(); } private bool doCeck() { if (txtbxInfoType.Text == "") { lblErrors.Text = "Название доп. информации не может быть пустым"; lblErrors.Visible = true; return false; } if (txtbxInfoData.Text == "") { lblErrors.Text = "Значение доп. информции не может быть пустым"; lblErrors.Visible = true; return false; } return true; } } } <file_sep>/PhoneNumbersDictionary/Data/OrganizationRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace PhoneNumbersDictionary { public class OrganizationRepository { private readonly SqlConnection _conn; public OrganizationRepository(SqlConnection conn) { _conn = conn; } public int Add(Organization org) { string query; query = String.Format("INSERT INTO Organization (Name,Location,Profile) output INSERTED.ID VALUES ('{0}','{1}','{2}')", org.Name,org.Location,org.Profile); SqlCommand cmd = new SqlCommand(query,_conn); return (int)cmd.ExecuteScalar(); } public int Edit(Organization org) { string query; query = String.Format("UPDATE Organization SET Name ='{0}', Location = '{1}', Profile = '{2}', Photo='{3}' WHERE Id={4}", org.Name, org.Location,org.Profile, org.PhotoPath, org.Id); SqlCommand cmd = new SqlCommand(query, _conn); return cmd.ExecuteNonQuery(); } public List<Organization> GetOrganizations(string query) { List<Organization> orgs = new List<Organization>(); SqlCommand cmd = new SqlCommand(query,_conn); var reader = cmd.ExecuteReader(); while (reader.Read()) { Organization org = new Organization(reader); orgs.Add(org); } return orgs; } public void RemoveByOrganizationId(int Id) { string query = "DELETE FROM Organization WHERE Id=" + Id; SqlCommand cmd = new SqlCommand(query, _conn); cmd.ExecuteNonQuery(); } public Organization GetById(int Id) { string query = "SELECT * FROM Organization WHERE Id=" + Id; SqlCommand cmd = new SqlCommand(query, _conn); var reader = cmd.ExecuteReader(); Organization org; while (reader.Read()) { org = new Organization(reader); return org; } return null; } } } <file_sep>/PhoneNumbersDictionary/OrganizationForm.cs using System; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; namespace PhoneNumbersDictionary { public partial class OrganizationForm : Form { private readonly Db db; private Organization org; private bool _edit=false; public OrganizationForm(Db database, Organization organization = null) { db = database; InitializeComponent(); AddContextMenu(); if (organization == null) { org = new Organization(); } else { org = organization; FillOrganizationData(); _edit = true; lblMain.Text = "Данные об Организации:"; btnRemoveOrganization.Visible = true; } } private void AddContextMenu() { ContextMenu menu_phone = new ContextMenu(); MenuItem editItem = new MenuItem(); editItem.Text = "Изменить"; editItem.Click += new EventHandler(EditPhoneNumberItem); MenuItem removeItem = new MenuItem(); removeItem.Text = "Удалить"; removeItem.Click += new EventHandler(RemovePhoneNumberItem); menu_phone.MenuItems.Add(editItem); menu_phone.MenuItems.Add(removeItem); lbPhoneNumbers.ContextMenu = menu_phone; ContextMenu menu_info = new ContextMenu(); MenuItem editItem2 = new MenuItem(); editItem2.Text = "Изменить"; editItem2.Click += new EventHandler(EditInfoItem); MenuItem removeItem2 = new MenuItem(); removeItem2.Text = "Удалить"; removeItem2.Click += new EventHandler(RemoveInfoItem); menu_info.MenuItems.Add(editItem2); menu_info.MenuItems.Add(removeItem2); lbAdditionalInfo.ContextMenu = menu_info; ContextMenu menu_file = new ContextMenu(); MenuItem openItem = new MenuItem(); openItem.Text = "Изменить"; openItem.Click += new EventHandler(OpenFileItem); MenuItem removeItem3 = new MenuItem(); removeItem3.Text = "Удалить"; removeItem3.Click += new EventHandler(RemoveFileItem); menu_file.MenuItems.Add(openItem); menu_file.MenuItems.Add(removeItem3); lbFiles.ContextMenu = menu_file; } private void FillOrganizationData() { db.LoadOrganizationData(org); if (File.Exists(org.PhotoPath)) { try { pbOrgPhoto.Image = new Bitmap(org.PhotoPath); pbOrgPhoto.SizeMode = PictureBoxSizeMode.StretchImage; } catch (Exception ex) { MessageBox.Show("Ошибка при загрузке изображения "+ex.Message); } } txtbxName.Text = org.Name; txtbxProfile.Text = org.Profile; txtbxLocation.Text = org.Location; foreach (var phone in org.PhoneNumbers) { lbPhoneNumbers.Items.Add(phone); } foreach (var info in org.AdditionalInfos) { lbAdditionalInfo.Items.Add(info); } foreach (var file in org.OrganizationFiles) { lbFiles.Items.Add(file); } } private void btnAddPhoneNumber_Click(object sender, EventArgs e) { PhoneNumberDialog dlg = new PhoneNumberDialog(); dlg.ShowDialog(); if (dlg.DialogResult == DialogResult.OK) { lbPhoneNumbers.Items.Add(dlg.PhoneNumber); org.PhoneNumbersToAdd.Add(dlg.PhoneNumber); } } private void btnAddInfo_Click(object sender, EventArgs e) { AdditionalInfoDialog dlg = new AdditionalInfoDialog(); dlg.ShowDialog(); if (dlg.DialogResult == DialogResult.OK) { lbAdditionalInfo.Items.Add(dlg.AdditionalInfo); org.AdditionalInfosToAdd.Add(dlg.AdditionalInfo); } } private void btnAddOrganization_Click(object sender, EventArgs e) { if (txtbxName.Text == "") { MessageBox.Show("Название организации не может быть пустым", "Ошибка"); return; } org.Name = txtbxName.Text; org.Profile = txtbxProfile.Text; org.Location = txtbxLocation.Text; if (!_edit) { db.AddOrganization(org); } else { db.EditOrganization(org); } MessageBox.Show("Организация " + org.Name + " Успешно Сохранена"); Close(); } private void EditPhoneNumberItem(object sender, EventArgs e) { PhoneNumber phone = (PhoneNumber)lbPhoneNumbers.SelectedItem; if (phone != null) { PhoneNumberDialog dialog = new PhoneNumberDialog(new PhoneNumber(phone)); dialog.ShowDialog(); if (dialog.DialogResult == DialogResult.OK) { if (org.PhoneNumbersToAdd.Contains(phone)) { org.PhoneNumbersToAdd.Remove(phone); org.PhoneNumbersToAdd.Add(dialog.PhoneNumber); } else { org.PhoneNumbersToEdit.RemoveAll(p => p.Id == dialog.PhoneNumber.Id); org.PhoneNumbersToEdit.Add(dialog.PhoneNumber); } lbPhoneNumbers.Items[lbPhoneNumbers.SelectedIndex] = dialog.PhoneNumber; } } } private void RemovePhoneNumberItem(object sender, EventArgs e) { PhoneNumber phone = (PhoneNumber)lbPhoneNumbers.SelectedItem; if (phone != null) { var result = MessageBox.Show("Вы действительно хотите удалить выбранный номер телефона?", "Удаление Номера Телефона", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { lbPhoneNumbers.Items.Remove(phone); org.PhoneNumbersToEdit.RemoveAll(p => p.Id == phone.Id); var item = org.PhoneNumbersToAdd.FirstOrDefault(p => p.Name == phone.Name && p.PhoneNumberstr == phone.PhoneNumberstr); if (item != null) org.PhoneNumbersToAdd.Remove(item); if (org.Id != 0) org.PhoneNumbersToRemove.Add(phone); } } } private void EditInfoItem(object sender, EventArgs e) { AdditionalInfo info = (AdditionalInfo)lbAdditionalInfo.SelectedItem; if (info != null) { AdditionalInfoDialog dialog = new AdditionalInfoDialog(new AdditionalInfo(info)); dialog.ShowDialog(); if (dialog.DialogResult == DialogResult.OK) { if (org.AdditionalInfosToAdd.Contains(info)) { org.AdditionalInfosToAdd.Remove(info); org.AdditionalInfosToAdd.Add(dialog.AdditionalInfo); } else { org.AdditionalInfosToEdit.RemoveAll(p => p.Id == dialog.AdditionalInfo.Id); org.AdditionalInfosToEdit.Add(dialog.AdditionalInfo); } lbAdditionalInfo.Items[lbAdditionalInfo.SelectedIndex] = dialog.AdditionalInfo; } } } private void RemoveInfoItem(object sender, EventArgs e) { AdditionalInfo info = (AdditionalInfo)lbAdditionalInfo.SelectedItem; if (info != null) { var result = MessageBox.Show("Вы действительно хотите удалить выбранную дополнительную информацию?", "Удаление доп. информации", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { lbAdditionalInfo.Items.Remove(info); org.AdditionalInfosToEdit.RemoveAll(p => p.Id == info.Id); var item = org.AdditionalInfosToAdd.FirstOrDefault(p => p.InfoData == info.InfoData && p.InfoType == info.InfoType); if (item != null) org.AdditionalInfosToAdd.Remove(item); if (org.Id != 0) org.AdditionalInfosToRemove.Add(info); } } } private void RemoveFileItem(object sender, EventArgs e) { OrganizationFile file = (OrganizationFile)lbFiles.SelectedItem; if (file != null) { var result = MessageBox.Show("Вы действительно хотите удалить выбранный файл?", "Удаление файла", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { lbFiles.Items.Remove(file); var item = org.OrganizationFilesToAdd.FirstOrDefault(p => p.Path == file.Path); if (item != null) org.OrganizationFilesToAdd.Remove(item); if (org.Id != 0) org.OrganizationFilesToRemove.Add(file); } } } private void OpenFileItem(object sender, EventArgs e) { OrganizationFile file = (OrganizationFile)lbFiles.SelectedItem; if (file != null) { if (File.Exists(file.Path)) { try { System.Diagnostics.Process.Start(file.Path); } catch (Exception ex) { MessageBox.Show("Ошибка при открытии файла "+ ex.Message); } } else { MessageBox.Show("Файл не найден"); } } } private void btnRemoveOrganization_Click(object sender, EventArgs e) { var result = MessageBox.Show("Вы уверены?", "Удалить Организацию", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { db.RemoveOrganization(org); MessageBox.Show("Организация " + org.Name + " Была успешно удалена"); Close(); } } private void btnBrowsePhoto_Click(object sender, EventArgs e) { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Добавить изображение"; dlg.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG"; if (dlg.ShowDialog() == DialogResult.OK) { string localPath = db.copyFileLocally(org, dlg.FileName); if(pbOrgPhoto.Image!=null) pbOrgPhoto.Image.Dispose(); pbOrgPhoto.Image = new Bitmap(localPath); pbOrgPhoto.SizeMode = PictureBoxSizeMode.StretchImage; db.deleteFile(org.PhotoPath); org.PhotoPath = localPath; } } } private void btnAddFile_Click(object sender, EventArgs e) { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Добавить файл"; if (dlg.ShowDialog() == DialogResult.OK) { string localPath = db.copyFileLocally(org, dlg.FileName); OrganizationFile file = new OrganizationFile(); file.Name = Path.GetFileName(dlg.FileName); file.Path = localPath; org.OrganizationFilesToAdd.Add(file); lbFiles.Items.Add(file); } } } } } <file_sep>/PhoneNumbersDictionary/Filters/OrganizationFilterByData.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public class OrganizationFilterByData: IOrganizationFilter { public string orgName; public bool orgNameComplete; public string orgLocation; public bool orgLocationComplete; public string orgProfile; public bool orgProfileComplete; public string GetCountQuery() { return "SELECT COUNT (*) " + GetQuery(); } public string GetQuery() { string query="FROM Organization WHERE "; query += "Name "; if (orgNameComplete) query += "='" +orgName +"' "; else query += "LIKE '%" + orgName + "%' "; query += "AND "; query += "Location "; if (orgLocationComplete) query += "='" + orgLocation + "' "; else query += "LIKE '%" + orgLocation + "%' "; query += "AND "; query += "Profile "; if (orgProfileComplete) query += "='" + orgProfile + "' "; else query += "LIKE '%" + orgProfile + "%' "; return query; } public string GetSelectQuery() { return "SELECT * " + GetQuery(); } } } <file_sep>/DbTest1/DbTest.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PhoneNumbersDictionary; using System.Data.SqlClient; using Xunit; namespace DbTest1 { public class DbTest { [Fact] public void ComplexTestDatabase() { Db db = new Db(); SqlConnection conn = db.GetConnection(); int orgsBefore = GetRowsNumber("Organization", conn); int phonesBefore = GetRowsNumber("PhoneNumber", conn); int infosBefore = GetRowsNumber("AdditionalInfo", conn); int filessBefore = GetRowsNumber("OrganizationFile", conn);//Смотрим сколько было записей int cnt_orgs = 10; int cnt_items = 5; List<Organization> orgs = AddOrganizations(cnt_orgs, cnt_items, db); int orgsAfter = GetRowsNumber("Organization", conn); int phonesAfter = GetRowsNumber("PhoneNumber", conn); int infosAfter = GetRowsNumber("AdditionalInfo", conn); int filessAfter = GetRowsNumber("OrganizationFile", conn); Assert.Equal(orgsAfter, orgsBefore + cnt_orgs); Assert.Equal(phonesAfter, phonesBefore + cnt_orgs* cnt_items); Assert.Equal(infosAfter, infosBefore + cnt_orgs * cnt_items); Assert.Equal(filessAfter, filessBefore + cnt_orgs * cnt_items);//Проверяем всё ли добавилось foreach (Organization org in orgs)//Проверяем, что добавилось то, что мы хотели добавить { Organization tmp = db.OrganizationRepository.GetById(org.Id); db.LoadOrganizationData(tmp); Assert.Equal(tmp.Id, org.Id); Assert.Equal(tmp.Name, org.Name); Assert.Equal(tmp.Location, org.Location); Assert.Equal(tmp.Profile, org.Profile); Assert.Equal(tmp.PhoneNumbers.Count, org.PhoneNumbersToAdd.Count); Assert.Equal(tmp.AdditionalInfos.Count, org.AdditionalInfosToAdd.Count); Assert.Equal(tmp.OrganizationFiles.Count, org.OrganizationFilesToAdd.Count); for (int i = 0; i < tmp.PhoneNumbers.Count; i++) { PhoneNumber phone1 = tmp.PhoneNumbers[i]; PhoneNumber phone2 = org.PhoneNumbersToAdd[i]; Assert.Equal(phone1.Name, phone2.Name); Assert.Equal(phone1.PhoneNumberstr, phone2.PhoneNumberstr); Assert.Equal(phone1.OrganizaionId, phone2.OrganizaionId); } for (int i = 0; i < tmp.AdditionalInfos.Count; i++) { AdditionalInfo info1 = tmp.AdditionalInfos[i]; AdditionalInfo info2 = org.AdditionalInfosToAdd[i]; Assert.Equal(info1.InfoData, info2.InfoData); Assert.Equal(info1.InfoType, info2.InfoType); Assert.Equal(info1.OrganizaionId, info2.OrganizaionId); } for (int i = 0; i < tmp.OrganizationFiles.Count; i++) { OrganizationFile file1 = tmp.OrganizationFiles[i]; OrganizationFile file2 = org.OrganizationFilesToAdd[i]; Assert.Equal(file1.Name, file2.Name); Assert.Equal(file1.Path, file2.Path); Assert.Equal(file1.OrganizaionId, file2.OrganizaionId); } } foreach (Organization org in orgs) { db.RemoveOrganization(org); } orgsAfter = GetRowsNumber("Organization", conn); phonesAfter = GetRowsNumber("PhoneNumber", conn); infosAfter = GetRowsNumber("AdditionalInfo", conn); filessAfter = GetRowsNumber("OrganizationFile", conn); Assert.Equal(orgsAfter, orgsBefore); Assert.Equal(phonesAfter, phonesBefore); Assert.Equal(infosAfter, infosBefore); Assert.Equal(filessAfter, filessBefore);//Проверяем всё ли удалилось } private int GetRowsNumber(string table, SqlConnection conn) { string query = "SELECT COUNT(*) FROM " + table; SqlCommand cmd = new SqlCommand(query, conn); return (int)cmd.ExecuteScalar(); } public List<Organization> AddOrganizations(int cnt_organizations, int cnt_items, Db db) { List<Organization> orgs = new List<Organization>(); for (int j = 1; j <= cnt_organizations; j++) { Organization org = new Organization(); org.Name = "Test Organization " + j; org.Location = "test Location " + j; org.Profile = "Test Profile " + j; for (int i = 0; i < cnt_items; i++) { PhoneNumber phone = new PhoneNumber(); phone.Name = "Test Phone " + i + " " + j; phone.PhoneNumberstr = "+712345" + i + " " + j; org.PhoneNumbersToAdd.Add(phone); } for (int i = 0; i < cnt_items; i++) { AdditionalInfo info = new AdditionalInfo(); info.InfoData = "Test data " + i + " " + j; info.InfoType = "Test Type " + i + " " + j; org.AdditionalInfosToAdd.Add(info); } for (int i = 0; i < cnt_items; i++) { OrganizationFile file = new OrganizationFile(); file.Name = "test file name " + i + " " + j; file.Path = "test file path " + i + " " + j; org.OrganizationFilesToAdd.Add(file); } org.Id = db.AddOrganization(org); orgs.Add(org); } return orgs; } } } <file_sep>/PhoneNumbersDictionary/Data/AdditionalInfoRepository.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhoneNumbersDictionary { public class AdditionalInfoRepository { private readonly SqlConnection _conn; public AdditionalInfoRepository(SqlConnection conn) { _conn = conn; } public int Add(AdditionalInfo info) { string query; query = String.Format("INSERT INTO AdditionalInfo (InfoType,InfoData,OrganizationId) VALUES ('{0}','{1}',{2})", info.InfoType, info.InfoData, info.OrganizaionId); SqlCommand cmd = new SqlCommand(query, _conn); return cmd.ExecuteNonQuery(); } public int Edit(AdditionalInfo info) { string query; query = String.Format("UPDATE AdditionalInfo SET InfoType ='{0}', InfoData = '{1}' WHERE Id={2}", info.InfoType, info.InfoData, info.Id); SqlCommand cmd = new SqlCommand(query, _conn); return cmd.ExecuteNonQuery(); } public int Remove(AdditionalInfo info) { string query; query = String.Format("DELETE FROM AdditionalInfo WHERE Id={0}", info.Id); SqlCommand cmd = new SqlCommand(query, _conn); return cmd.ExecuteNonQuery(); } public List<AdditionalInfo> GetAdditionalInfosByOrganizationId(int id) { List<AdditionalInfo> infos= new List<AdditionalInfo>(); string query = "SELECT * FROM AdditionalInfo where OrganizationId=" + id; SqlCommand cmd = new SqlCommand(query, _conn); var reader = cmd.ExecuteReader(); while (reader.Read()) { AdditionalInfo info = new AdditionalInfo(reader); infos.Add(info); } return infos; } public void RemoveByOrganizationId(int Id) { string query = "DELETE FROM AdditionalInfo WHERE OrganizationId=" + Id; SqlCommand cmd = new SqlCommand(query, _conn); cmd.ExecuteNonQuery(); } } }
d07a8ff595ac0230123b3b254684782599d16e35
[ "C#" ]
20
C#
Egardoz01/PhoneNumbersDictionary
6202bc7468c9a5066868f51c3e4e068e5550d2c2
2d5e96f12ec94725c9b532e931d2abd55cf41a6f
refs/heads/master
<file_sep><?php function connect(){ $conexao = mysqli_connect("localhost","root",""); $banco=mysqli_select_db($conexao, "agenda"); if (!$conexao) { die("Erro na conexão!"); }else{ return $conexao; } } ?><file_sep><?php include 'conexao.php'; if (isset($_GET["acao"])) { switch ($_GET["acao"]) { case 1: // Verifica se existe a variável txtnome $nome = isset($_GET["txtnome"]) ? $_GET["txtnome"] : ''; // Conexao com o banco de dados $conexao = connect(); // Verifica se a variável está vazia if (empty($nome)) { $sql = "SELECT * FROM contato"; } else { //$nome .="%"; $sql = "SELECT * FROM contato WHERE nome like '%$nome%'"; } sleep(1); $result = mysqli_query($conexao, $sql); $cont = mysqli_affected_rows($conexao); // Verifica se a consulta retornou linhas if ($cont > 0) { // Atribui o código HTML para montar uma tabela $tabela = "<table border='1'> <thead> <tr> <th>ID</th><th>NOME</th> <th>TELEFONE</th> <th>CELULAR</th> <th>EMAIL</th> </tr> </thead> <tbody> <tr>"; $return = "$tabela"; // Captura os dados da consulta e inseri na tabela HTML while ($linha = mysqli_fetch_array($result)) { $return.= "<td>" . utf8_encode($linha["ID"]) . "</td>"; $return.= "<td>" . utf8_encode($linha["NOME"]) . "</td>"; $return.= "<td>" . utf8_encode($linha["FONE"]) . "</td>"; $return.= "<td>" . utf8_encode($linha["CELULAR"]) . "</td>"; $return.= "<td>" . utf8_encode($linha["EMAIL"]) . "</td>"; $return.= "<td><input type='button' data-val='". utf8_encode($linha["ID"]) ."' class='edit'></td>"; $return.= "</tr>"; } echo $return.="</tbody></table>"; } else { // Se a consulta não retornar nenhum valor, exibi mensagem para o usuário echo "Não foram encontrados registros!"; } break; case 2: $nome = isset($_GET["txtnome"]) ? $_GET["txtnome"] : ''; // Conexao com o banco de dados $conexao = connect(); // Verifica se a variável está vazia if (empty($nome)) { $sql = "SELECT * FROM contato"; } else { $nome .= "%"; $sql = "SELECT * FROM contato WHERE nome like '$nome'"; } sleep(1); $result = mysqli_query($conexao, $sql); $cont = mysqli_affected_rows($conexao); // Verifica se a consulta retornou linhas if ($cont > 0) { // Montagem do json dentro de data $json = '{"data":['; // Captura os dados da consulta e insere no json while ($linha = mysqli_fetch_array($result)) { $json.= '{"nome":"' . utf8_encode($linha["NOME"]) . '",'; $json.= '"fone":"' . utf8_encode($linha["FONE"]) . '",'; $json.= '"celular":"' . utf8_encode($linha["CELULAR"]) . '",'; $json.= '"email":"' . utf8_encode($linha["EMAIL"]).'"'; $json.= "},"; } $json = substr($json, 0, -1); $json.="]}"; echo $json; } else { // Se a consulta não retornar nenhum valor, exibi mensagem para o usuário echo "Não foram encontrados registros!"; } break; case 0: $nome = isset($_GET["txtnome"]) ? $_GET["txtnome"] : ''; $telefone = isset($_GET["telefone"]) ? $_GET["telefone"] : ''; $celular = isset($_GET["celular"]) ? $_GET["celular"] : ''; $email = isset($_GET["email"]) ? $_GET["email"] : ''; // Conexao com o banco de dados $conexao = connect(); // Verifica se a variável está vazia if (empty($nome)) { echo "ERRO FALTA NOME"; } else { $sql = "INSERT INTO contato(nome, fone, celular, email) VALUES('".$nome."','".$telefone."','".$celular."','".$email."')"; } sleep(1); $result = mysqli_query($conexao, $sql); $cont = mysqli_affected_rows($conexao); // Verifica se a consulta retornou linhas if ($cont) { echo "Cadastro efetuado"; } else { // Se a consulta não retornar nenhum valor, exibi mensagem para o usuário echo "Não foram encontrados registros!"; } break; default: echo "Ação não encontrada"; break; } }else{ echo "<script>console.log('ação não enviada')</script>"; } ?> <file_sep> -- phpMyAdmin SQL Dump -- version 3.5.2.2 -- http://www.phpmyadmin.net -- -- Servidor: localhost -- Tempo de Geração: 16/03/2015 às 23:56:43 -- Versão do Servidor: 5.1.66 -- Versão do PHP: 5.2.17 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Banco de Dados: `u272327061_agend` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `contato` -- CREATE TABLE IF NOT EXISTS `contato` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `NOME` varchar(100) DEFAULT NULL, `FONE` varchar(15) NOT NULL, `CELULAR` varchar(15) NOT NULL, `EMAIL` varchar(50) DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=18 ; -- -- Extraindo dados da tabela `contato` -- INSERT INTO `contato` (`ID`, `NOME`, `FONE`, `CELULAR`, `EMAIL`) VALUES (2, 'PEDRO', '37469322', '85501890', '<EMAIL>'), (3, 'PEDRO', '37469322', '85501890', '<EMAIL>'), (4, 'PEDRO', '37469322', '85501890', '<EMAIL>'), (5, 'Alexandre', '12345678', '87654321', '<EMAIL>'), (6, 'Dieguinho', '12345678', '87654321', '<EMAIL>'), (7, 'Daniel', '12345678', '87654321', '<EMAIL>'), (8, NULL, '12345678', '', NULL), (12, 'fabio', '12345678', '87654321', '<EMAIL>'), (13, 'keit', '12345678', '87654321', '<EMAIL>'), (14, 'teste', '5845', '454654', 'sada@adsad'), (15, 'testets', 'sadsad', 'dsadsa', 'dsadsa'), (16, 'Thiago', '768758756858656', '58658658658', '<EMAIL>'), (17, 'felipe', '987987', '979879', '<EMAIL>'); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/** * Função para criar um objeto XMLHTTPRequest */ function CriaRequest() { try{ request = new XMLHttpRequest(); }catch (IEAtual){ try{ request = new ActiveXObject("Msxml2.XMLHTTP"); } catch(IEAntigo){ try{ request = new ActiveXObject("Microsoft.XMLHTTP"); }catch(falha){ request = false; } } } if (!request) alert("Seu Navegador não suporta Ajax!"); else return request; } /** * Função para enviar os dados */ function getDados(nome, result, callback) { var xmlreq = CriaRequest(); // Exibi a imagem de progresso result.html('<img height="250" width="250" src="loading.gif"/>'); // Iniciar uma requisição xmlreq.open("GET", "contato.php?acao="+ 1 +"&txtnome=" + nome, true); // Atribui uma função para ser executada sempre que houver uma mudança de ado xmlreq.onreadystatechange = function(){ // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4) if (xmlreq.readyState == 4) { // Verifica se o arquivo foi encontrado com sucesso if (xmlreq.status == 200) { callback(xmlreq.responseText); }else{ callback("Erro: " + xmlreq.statusText); } } }; xmlreq.send(null); } function getDadosJson(nome, result, callback) { // Declaração de Variáveis var xmlreq = CriaRequest(); // Exibi a imagem de progresso result.html('<img height="250" width="250" src="loading.gif"/>'); // Iniciar uma requisição xmlreq.open("GET", "contato.php?acao="+ 2 +"&txtnome=" + nome, true); // Atribui uma função para ser executada sempre que houver uma mudança de ado xmlreq.onreadystatechange = function(){ // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4) if (xmlreq.readyState == 4) { // Verifica se o arquivo foi encontrado com sucesso if (xmlreq.status == 200) { callback(xmlreq.responseText); }else{ callback("Erro: " + xmlreq.statusText); } } }; xmlreq.send(null); } function addReg(nome, telefone, celular, email,callback){ var xmlreq = CriaRequest(); // Iniciar uma requisição xmlreq.open("GET", "contato.php?acao="+ 0 +"&txtnome=" + nome+"&telefone="+telefone+"&celular="+celular+"&email="+email, true); // Atribui uma função para ser executada sempre que houver uma mudança de ado xmlreq.onreadystatechange = function(){ // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4) if (xmlreq.readyState == 4) { // Verifica se o arquivo foi encontrado com sucesso if (xmlreq.status == 200) { callback(xmlreq.responseText); }else{ callback("Erro: " + xmlreq.statusText); } } }; xmlreq.send(null); }
f9e18cc94cf1bc998810ad022a087833211ca361
[ "JavaScript", "SQL", "PHP" ]
4
PHP
opedro/phpajax
2eaa7978e753e86b4af4c245bdf999d16cdcf9e8
36cd4a2282f969c56eaefbcc236c8adff452c213
refs/heads/master
<file_sep>package ohm.softa.a08.services; import com.google.gson.Gson; import ohm.softa.a08.api.OpenMensaAPI; import ohm.softa.a08.model.Meal; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import java.util.List; public class OpenMensaAPIService { private static OpenMensaAPIService instance; private OpenMensaAPI api; private OpenMensaAPIService() { } public static OpenMensaAPIService getInstance() { if (instance == null) { instance = new OpenMensaAPIService(); } return instance; } public OpenMensaAPI getApi() { if (api == null) { var gson = new Gson(); /* initialize Retrofit instance */ var retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("http://openmensa.org/api/v2/") .build(); /* create OpenMensaAPI instance */ api = retrofit.create(OpenMensaAPI.class); } return api; } } <file_sep>package filtering; import ohm.softa.a08.model.Meal; import java.util.ArrayList; import java.util.List; public class CategoryFilter extends FilterBase { private String category; private boolean include; public CategoryFilter(String category, boolean include) { this.category = category; this.include = include; } @Override protected boolean includeMeal(Meal m) { if (include) { if (m.getCategory().equals(category)) return true; return false; } if (m.getCategory().equals(category)) return false; return true; } }
bab01b4a8148487e841581451f34c42bf298dbf0
[ "Java" ]
2
Java
brewormly/08-singleton-factory-strategy-jfx
e25fc4a85ea6cc9f367859ce94b5f607b956b8ce
e2e1db8d35856fc297bb9de1c7a759ec543ae705
refs/heads/master
<repo_name>heyonemusic/sms<file_sep>/db.php <?php require_once 'recount.php'; $dbh = new PDO('mysql:host=localhost;dbname=sms', 'root', 'root'); $data = [ 'symbols' => $symbols, 'count' => $count, ]; $sql = "INSERT INTO sms (symbols, count) VALUES (:symbols, :count)"; $stmt= $dbh->prepare($sql); $stmt->execute($data); return $stmt;<file_sep>/translit.js const checkbox = document.getElementById('translit') checkbox.addEventListener('change', (event) => { if (event.target.checked) { let formData = $('#text').serialize(); $.ajax({ url: 'translit_cyrillic.php', type: "POST", data: formData, success: function(data) { $('#text').val(data); } }); } else { let formData = $('#text').serialize(); $.ajax({ url: 'translit_latin.php', type: "POST", data: formData, success: function(data) { $('#text').val(data); } }); } })<file_sep>/recount.php <?php function get_encode($textString) { if(preg_match("/[А-Яа-я]/", $textString)) { return 1; } elseif(preg_match("/[A-Za-z]/", $textString)) { return 0; } return -1; } function str_split_unicode($str, $l = 1) { if ($l > 0) { $ret = array(); $len = mb_strlen($str, "UTF-8"); for ($i = 0; $i < $len; $i += $l) { $ret[] = mb_substr($str, $i, $l, "UTF-8"); } return $ret; } return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY); } $textString = $_POST['text']; $symbols = mb_strlen($textString); echo 'Количество символов: ' . $symbols; echo '<br>'; $encode = get_encode($textString); $ops = [ [160,153], [70,67] ]; $result = str_split_unicode($textString, $ops[$encode][intval($symbols>$ops[$encode][0])]); $count = count($result); echo 'Количество SMS: ' . $count;<file_sep>/recount.js $('#text').keyup(function(event) { event.preventDefault(); $.ajax({ url: 'recount.php', method: 'post', data: $(this).serialize(), success: function(data){ $('.results').html(data); } }); });
fbb97d7483e4ab22610f84103d05f8ca0c2fb0c6
[ "JavaScript", "PHP" ]
4
PHP
heyonemusic/sms
b47cf4563d2b78c38525b2daddff2d282923c4a3
6c669f9ada934609ff3ac07d7165007cc3b7f255
refs/heads/main
<repo_name>wasmup/loadcpu<file_sep>/README.md # Load All cores of a CPU for load testing ```sh go install -ldflags=-s go get -ldflags=-s -u -v github.com/wasmup/loadcpu loadcpu -h loadcpu -n 1 -t 60 ``` Output: ``` Usage of loadcpu: -n int number of goroutines to start (default the number of logical CPUs usable by the current process) -t int number of seconds to wait for goroutines. (default 10) ``` <file_sep>/main.go package main import ( "flag" "fmt" "runtime" "time" ) func main() { var n, t int flag.IntVar(&n, "n", runtime.NumCPU(), "number of goroutines to start") flag.IntVar(&t, "t", 10, "number of seconds to wait for goroutines.") flag.Parse() fmt.Print("Starting goroutines: ") for i := 0; i < n; i++ { fmt.Print(i+1, " ") go useOneCPUcore() } fmt.Println("\nWait (second) ...") for i := t; i > 0; i-- { fmt.Print("\r ", i, " ") time.Sleep(1 * time.Second) } fmt.Println("\nDone.") } func useOneCPUcore() { for { runtime.Gosched() } } <file_sep>/go.mod module loadcpu go 1.16 <file_sep>/Makefile .PHONY: all all: go install -ldflags=-s
35abd022a9f348b35ee72ef5c0fcd873b7c4467d
[ "Markdown", "Go Module", "Go", "Makefile" ]
4
Markdown
wasmup/loadcpu
29152a4daee7bac806d48253218af18296005005
99345eb6ba297a1469461e0f60399c08b66e0429
refs/heads/master
<file_sep>#include <ESP8266HTTPClient.h> #include <ESP8266WiFi.h> // WiFi config const char ssid[] = "Connectify-me"; const char password[] = "<PASSWORD>"; // WiFiClient object WiFiClient client; void setup() { pinMode(0,OUTPUT); // Initialize Serial Serial.begin(9600); delay(100); // Connect to WiFi Serial.print("Connecting to "); Serial.print(ssid); WiFi.begin(ssid, password); while ( WiFi.status() != WL_CONNECTED ) { delay(500); Serial.print("."); } Serial.println(); // Show that we are connected Serial.println("Connected!"); } void loop() { if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status HTTPClient http; //Declare an object of class HTTPClient http.begin("http://dry-brook-43259.herokuapp.com/bulbs/status"); //Specify request destination int httpCode = http.GET(); //Send the request if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); if(payload == "ON"){ //Print the response payload digitalWrite(0,HIGH); Serial.println("Should Glow the Blub"); }else{ digitalWrite(0,LOW); Serial.println("Should not Glow the Blub"); } http.end(); //Close connection } //Send a request every 10 seconds } }#include <ESP8266HTTPClient.h> #include <ESP8266WiFi.h> // WiFi config const char ssid[] = "Connectify-me"; const char password[] = "<PASSWORD>"; // WiFiClient object WiFiClient client; void setup() { pinMode(0,OUTPUT); // Initialize Serial Serial.begin(9600); delay(100); // Connect to WiFi Serial.print("Connecting to "); Serial.print(ssid); WiFi.begin(ssid, password); while ( WiFi.status() != WL_CONNECTED ) { delay(500); Serial.print("."); } Serial.println(); // Show that we are connected Serial.println("Connected!"); } void loop() { if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status HTTPClient http; //Declare an object of class HTTPClient http.begin("http://dry-brook-43259.herokuapp.com/bulbs/status"); //Specify request destination int httpCode = http.GET(); //Send the request if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); if(payload == "ON"){ //Print the response payload digitalWrite(0,HIGH); Serial.println("Should Glow the Blub"); }else{ digitalWrite(0,LOW); Serial.println("Should not Glow the Blub"); } http.end(); //Close connection } //Send a request every 10 seconds } }
3f8bb0373935183846cf0463c43a86775ce1ea19
[ "C++" ]
1
C++
iamsss/Iot-Home-Automation-Basics
099adb59b690d5965300385f75d00bf221ddce02
b6b9b33173f5cb144cf2dd0e0ba6347ccbdb636f
refs/heads/master
<file_sep># APIgoalsapp API untuk setyourgoalsapp (link repo FE Apps: https://github.com/ikrom/goalsapp-cordova) goalsapp.heliohost.org dokumentasi: bit.ly/API_goalsapp <file_sep><?php header( 'Access-Control-Allow-Origin: *'); if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)) $_POST = (array)json_decode(file_get_contents('php://input'), true); function base64_to_jpeg($base64_string, $output_file) { $ifp = fopen($output_file, "wb"); $data = explode(',', $base64_string); fwrite($ifp, base64_decode($data[1])); fclose($ifp); return $output_file; } if(!empty($_POST['TYPE'])){ // koneksi database $host = "localhost"; // lokasi database $user = "revoreva_goalsap"; // nama username $pass = "<PASSWORD>"; // password database $dbname = "revoreva_goalsapp"; // nama database yang digunakan $cn = mysqli_connect( $host, $user, $pass, $dbname ); //url/login/email/password if ( $_POST['TYPE'] == "login" ) { $query = "SELECT AKUN_ID, EMAIL, USERNAME, REKENING, FOTO from AKUN where AKUN.EMAIL = \"" . $_POST['EMAIL'] . "\" AND AKUN.PASSWORD = \"" . $_POST['PASSWORD'] . "\" limit 1"; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; $ada = 1; } if($ada == 1) echo '{"status":200, "message":"login sukses", "data":' . json_encode( $var ) . '}'; else echo '{"status":300, "message":"login gagal"}'; } else if ( $_POST['TYPE'] == "get_account" ) { $query = "SELECT EMAIL, USERNAME, PASSWORD, FOTO from AKUN where AKUN.AKUN_ID = \"" . $_POST['AKUN_ID'] . "\" limit 1"; $result = mysqli_query( $cn, $query ); $var = array(); while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; } echo '{"status":200, "message":"get data sukses", "data":' . json_encode( $var ) . '}'; } else if($_POST['TYPE'] == 'register'){ //register/username/email/password/foto if(!empty($_POST['FOTO'])){ $foto = $_POST['FOTO']; $nama = uniqid().'.jpg'; $img = base64_to_jpeg($foto, $nama); rename(''.$nama, 'uploads/'.$nama); $path = "http://goalsapp.heliohost.org/uploads/".$img; } else { $path = 'img/photo.png'; } $query = "INSERT INTO AKUN(USERNAME, EMAIL, PASSWORD, FOTO) VALUES (\"" . $_POST['USERNAME'] . "\",\"" . $_POST['EMAIL'] . "\",\"" . $_POST['PASSWORD'] . "\",\"" . $path . "\")"; $result = mysqli_query( $cn, $query ); if($result){ $query = "SELECT AKUN_ID, EMAIL, USERNAME, REKENING, FOTO from AKUN where AKUN.EMAIL = \"" . $_POST['EMAIL'] . "\" AND AKUN.USERNAME = \"" . $_POST['USERNAME'] . "\" AND AKUN.PASSWORD = \"" . $_POST['PASSWORD'] . "\" limit 1"; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; } echo '{"status":200, "message":"registrasi sukses", "data":' . json_encode( $var ) . '}'; } else echo '{"status":300, "message":"registrasi gagal"}'; } else if($_POST['TYPE'] == 'update_account'){ if($_POST['UPDATE_FOTO'] == 1){ $foto = $_POST['FOTO']; $nama = uniqid().'.jpg'; $img = base64_to_jpeg($foto, $nama); rename(''.$nama, 'uploads/'.$nama); $path = "http://goalsapp.heliohost.org/uploads/".$img; $query = "UPDATE AKUN SET EMAIL = \"" . $_POST['EMAIL'] . "\", PASSWORD = \"" . $_POST['PASSWORD'] . "\", FOTO = \"" . $path . "\" WHERE AKUN_ID = " . $_POST['AKUN_ID']; } else $query = "UPDATE AKUN SET EMAIL = \"" . $_POST['EMAIL'] . "\", PASSWORD = \"" . $_POST['PASSWORD'] . "\" WHERE AKUN_ID = " . $_POST['AKUN_ID']; $result = mysqli_query( $cn, $query ); if($result){ $query = "SELECT EMAIL, FOTO from AKUN where AKUN.AKUN_ID = \"" . $_POST['AKUN_ID'] . "\" limit 1"; $result = mysqli_query( $cn, $query ); $var = array(); while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; } echo '{"status":200, "message":"update akun sukses", "data":' . json_encode( $var ) . '}'; } else echo '{"status":300, "message":"update akun gagal"}'; } else if($_POST['TYPE'] == 'delete_target'){ $query = "DELETE FROM TARGET WHERE TARGET_ID = \"" . $_POST['TARGET_ID'] . "\""; $result = mysqli_query( $cn, $query ); if($result){ echo '{"status":200, "message":"hapus data sukses"}'; } else echo '{"status":200, "message":"hapus data gagal"}'; } else if($_POST['TYPE'] == 'budget'){ $query = "UPDATE AKUN SET REKENING = \"" . $_POST['REKENING'] . "\" WHERE AKUN_ID = " . $_POST['AKUN_ID']; $result = mysqli_query( $cn, $query ); if($result){ echo '{"status":200, "message":"penambahan data keuangan sukses", "rekening": "' . $_POST['REKENING'] . '"}'; } else echo '{"status":300, "message":"penambahan data keuangan gagal"}'; } else if($_POST['TYPE'] == 'list_target'){ //list_target/AKUN_ID $query = "SELECT TARGET_ID, NAMA, FOTO, SALDO, HARGA, DUE_DATE FROM TARGET WHERE AKUN_ID = " . $_POST['AKUN_ID'] . " ORDER BY TARGET_ID ASC"; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; $ada = 1; } if($ada == 1) echo '{"status":200, "message":"get list target sukses", "data":' . json_encode( $var ) . '}'; else echo '{"status":300, "message":"get list target gagal"}'; } else if($_POST['TYPE'] == 'add_goal'){ //register/username/email/password/foto if(!empty($_POST['FOTO'])){ $foto = $_POST['FOTO']; $nama = uniqid().'.jpg'; $img = base64_to_jpeg($foto, $nama); rename(''.$nama, 'uploads/'.$nama); $path = "http://goalsapp.heliohost.org/uploads/".$img; } else { $path = 'img/thing.png'; } $query = "INSERT INTO TARGET(AKUN_ID, NAMA, HARGA, DUE_DATE, FOTO) VALUES (" . $_POST['AKUN_ID'] . ",\"" . $_POST['NAMA'] . "\",\"" . $_POST['HARGA'] . "\",\"" . $_POST['DUE_DATE'] . "\",\"" . $path . "\")"; $result = mysqli_query( $cn, $query ); if($result){ $query = "SELECT NAMA, TARGET_ID, FOTO, SALDO, HARGA, DUE_DATE FROM TARGET WHERE AKUN_ID = " . $_POST['AKUN_ID'] . ' AND NAMA = "' . $_POST['NAMA'] . '" AND HARGA = "' . $_POST['HARGA'] . '"'; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; } echo '{"status":200, "message":"penambahan goal sukses", "data":' . json_encode( $var ) . '}'; } else echo '{"status":300, "message":"penambahan goal gagal"}'; } else if($_POST['TYPE'] == 'add_nabung'){ //ngurangi rekening akun, nambah saldo di target, //INSERT INTO log_transaksi: akun_id, target_id, kategori_transaksi_id = 8, nama, jumlah, jenis = 1 (out), tanggal //UPDATE AKUN SET rekening = new amount //UPDATE TARGET SET SALDO = new amount $query = "INSERT INTO LOG_TRANSAKSI(AKUN_ID, TARGET_ID, KATEGORI_TRANSAKSI_ID, NAMA, JUMLAH, JENIS, TANGGAL) VALUES (" . $_POST['AKUN_ID'] . "," . $_POST['TARGET_ID'] . "," . "8" . ",\"" . $_POST['NAMA_BARANG'] . "\",\"" . $_POST['JUMLAH_NABUNG'] . "\"," . "1" . ",\"" . $_POST['TANGGAL'] . "\")"; $result = mysqli_query( $cn, $query ); if($result){ $INITIAL_REKENING = $_POST['REKENING']; $NEW_AMOUNT = intval($_POST['REKENING']) - intval($_POST['JUMLAH_NABUNG']); $NEW_REKENING = $NEW_AMOUNT; $query = "UPDATE AKUN SET REKENING = \"" . $NEW_AMOUNT . "\" WHERE AKUN_ID = " . $_POST['AKUN_ID']; $result = mysqli_query( $cn, $query ); if($result){ $NEW_AMOUNT = intval($_POST['SALDO_AWAL']) + intval($_POST['JUMLAH_NABUNG']); $query = "UPDATE TARGET SET SALDO = \"" . $NEW_AMOUNT . "\" WHERE TARGET_ID = " . $_POST['TARGET_ID']; $result = mysqli_query( $cn, $query ); if($result){ $query = "SELECT TARGET_ID, FOTO, SALDO, HARGA, DUE_DATE FROM TARGET WHERE AKUN_ID = " . $_POST['AKUN_ID']; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; } echo '{"status":200, "message":"menabung sukses", "rekening": "' . $NEW_REKENING . '", "data":' . json_encode( $var ) . '}'; } else{ $query = "UPDATE AKUN SET REKENING = \"" . $INITIAL_REKENING . "\" WHERE AKUN_ID = " . $_POST['AKUN_ID']; $result = mysqli_query( $cn, $query ); echo '{"status":300, "message":"menabung gagal", "rekening":"' . $INITIAL_REKENING . '"}'; } } else echo '{"status":300, "message":"menabung gagal", "rekening":"' . $INITIAL_REKENING . '"}'; // echo '{"status":200, "message":"get list target sukses", "data":' . json_encode( $var ) . '}'; } else echo '{"status":300, "message":"menabung gagal", "rekening":"' . $INITIAL_REKENING . '"}'; } else if($_POST['TYPE'] == 'add_transaksi'){ //ngurangi rekening akun, nambah saldo di target, //INSERT INTO log_transaksi: akun_id, kategori_transaksi_id, nama, jumlah, jenis, tanggal //UPDATE AKUN SET rekening = new amount $INITIAL_REKENING = $_POST['REKENING']; $query = "INSERT INTO LOG_TRANSAKSI(AKUN_ID, KATEGORI_TRANSAKSI_ID, NAMA, JUMLAH, JENIS, TANGGAL, NOTE, `WITH`, LOCATION, REMINDER) VALUES (" . $_POST['AKUN_ID'] . "," . $_POST['KATEGORI_TRANSAKSI_ID'] . ",\"" . $_POST['NAMA'] . "\",\"" . $_POST['JUMLAH'] . "\"," . $_POST['JENIS'] . ",\"" . $_POST['TANGGAL'] . "\",\"" . $_POST['NOTE'] . "\",\"" . $_POST['WITH'] . "\",\"" . $_POST['LOCATION'] . "\",\"" . $_POST['REMINDER'] . "\")"; $result = mysqli_query( $cn, $query ); if($result){ if($_POST['JENIS'] == '1' || ($_POST['JENIS'] == '0' && $_POST['KATEGORI_TRANSAKSI_ID'] == '15')) $NEW_AMOUNT = intval($_POST['REKENING']) - intval($_POST['JUMLAH']); else $NEW_AMOUNT = intval($_POST['REKENING']) + intval($_POST['JUMLAH']); $NEW_REKENING = $NEW_AMOUNT; $query = "UPDATE AKUN SET REKENING = \"" . $NEW_AMOUNT . "\" WHERE AKUN_ID = " . $_POST['AKUN_ID']; $result = mysqli_query( $cn, $query ); if($result){ echo '{"status":200, "message":"tambah data transaksi sukses", "rekening": "' . $NEW_REKENING . '"}'; } else echo '{"status":300, "message":"tambah data transaksi gagal (2)", "rekening":"' . $INITIAL_REKENING . '"}'; // echo '{"status":200, "message":"get list target sukses", "data":' . json_encode( $var ) . '}'; } else echo '{"status":300, "message":"tambah data transaksi gagal (1): ' . $query . ' ", "rekening":"' . $INITIAL_REKENING . '"}'; } else if($_POST['TYPE'] == 'get_transaksi'){ //list_target/AKUN_ID $query = "SELECT LOG_TRANSAKSI.JENIS, LOG_TRANSAKSI.LOG_TRANSAKSI_ID AS ID, LOG_TRANSAKSI.NAMA AS NAMA_TRANSAKSI, LOG_TRANSAKSI.JUMLAH, KATEGORI_TRANSAKSI.KATEGORI_TRANSAKSI_ID AS KATEGORI_TRANSAKSI_ID, KATEGORI_TRANSAKSI.NAMA AS KATEGORI, KATEGORI_TRANSAKSI.FOTO FROM LOG_TRANSAKSI, KATEGORI_TRANSAKSI WHERE LOG_TRANSAKSI.AKUN_ID = " . $_POST['AKUN_ID'] . " AND LOG_TRANSAKSI.TARGET_ID = 0 AND KATEGORI_TRANSAKSI.KATEGORI_TRANSAKSI_ID = LOG_TRANSAKSI.KATEGORI_TRANSAKSI_ID AND LOG_TRANSAKSI.TANGGAL = DATE(DATE_ADD(NOW(), INTERVAL 14 HOUR))"; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; $ada = 1; } if($ada == 1) echo '{"status":200, "message":"get list transaksi sukses", "data":' . json_encode( $var ) . '}'; else echo '{"status":300, "message":"get list transaksi gagal/tidak ada"}'; } else if($_POST['TYPE'] == 'get_transaksi_day'){ //list_target/AKUN_ID $query = "SELECT LOG_TRANSAKSI.JENIS, LOG_TRANSAKSI.LOG_TRANSAKSI_ID AS ID, LOG_TRANSAKSI.NAMA AS NAMA_TRANSAKSI, LOG_TRANSAKSI.JUMLAH, KATEGORI_TRANSAKSI.KATEGORI_TRANSAKSI_ID AS KATEGORI_TRANSAKSI_ID, KATEGORI_TRANSAKSI.NAMA AS KATEGORI, KATEGORI_TRANSAKSI.FOTO FROM LOG_TRANSAKSI, KATEGORI_TRANSAKSI WHERE LOG_TRANSAKSI.AKUN_ID = " . $_POST['AKUN_ID'] . " AND LOG_TRANSAKSI.TARGET_ID = 0 AND KATEGORI_TRANSAKSI.KATEGORI_TRANSAKSI_ID = LOG_TRANSAKSI.KATEGORI_TRANSAKSI_ID AND LOG_TRANSAKSI.TANGGAL = \"" . $_POST['TANGGAL'] . "\""; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; $ada = 1; } if($ada == 1) echo '{"status":200, "message":"get list transaksi sukses", "data":' . json_encode( $var ) . '}'; else echo '{"status":300, "message":"get list transaksi gagal/tidak ada"}'; } else if($_POST['TYPE'] == 'get_transaksi_month'){ //list_target/AKUN_ID $query = "SELECT LOG_TRANSAKSI.JENIS, LOG_TRANSAKSI.LOG_TRANSAKSI_ID AS ID, LOG_TRANSAKSI.NAMA AS NAMA_TRANSAKSI, LOG_TRANSAKSI.JUMLAH, KATEGORI_TRANSAKSI.KATEGORI_TRANSAKSI_ID AS KATEGORI_TRANSAKSI_ID, KATEGORI_TRANSAKSI.NAMA AS KATEGORI, KATEGORI_TRANSAKSI.FOTO, DAY(LOG_TRANSAKSI.TANGGAL) AS DAY FROM LOG_TRANSAKSI, KATEGORI_TRANSAKSI WHERE LOG_TRANSAKSI.AKUN_ID = " . $_POST['AKUN_ID'] . " AND LOG_TRANSAKSI.TARGET_ID = 0 AND KATEGORI_TRANSAKSI.KATEGORI_TRANSAKSI_ID = LOG_TRANSAKSI.KATEGORI_TRANSAKSI_ID AND MONTH(LOG_TRANSAKSI.TANGGAL) = \"" . $_POST['MONTH'] . "\" ORDER BY DAY"; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; $ada = 1; } if($ada == 1) echo '{"status":200, "message":"get list transaksi sukses", "data":' . json_encode( $var ) . '}'; else echo '{"status":300, "message":"get list transaksi gagal/tidak ada"}'; } else if($_POST['TYPE'] == 'get_target'){ //list_target/AKUN_ID $query = "SELECT NAMA, TARGET_ID, FOTO, SALDO, HARGA, DUE_DATE FROM TARGET WHERE TARGET_ID = " . $_POST['TARGET_ID']; $result = mysqli_query( $cn, $query ); $var = array(); $ada = 0; while ( $obj = mysqli_fetch_object( $result ) ) { $var[] = $obj; $ada = 1; } if($ada) echo '{"status":200, "message":"get goal sukses", "data":' . json_encode( $var ) . '}'; else echo '{"status":200, "message":"get goal gagal / tidak ada"}'; } } else { echo '{"status":404, "message":"get data gagal"}'; } ?>
c4c6a9c5da5b280b7af9261ccc748b4319324fcd
[ "Markdown", "PHP" ]
2
Markdown
revoreva/APIgoalsapp
4f49d0530f69acbb84399b95a2dbc0891d3b0c8b
8d5bd5e6bee9f287c38553e733d9cce7e83bb002
refs/heads/main
<repo_name>AntKerf/Tasks<file_sep>/Clusterizer/Source/Cluster.h #pragma once #include <Windows.h> //boost #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/ptree.hpp> //opencv #include <opencv2/core.hpp> #include <opencv2/opencv.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc/imgproc_c.h> #include <opencv2/highgui.hpp> #include <opencv2/highgui/highgui_c.h> #include <opencv2/core/types_c.h> //std, stl #include <iostream> #include <list> #include <deque> using namespace cv; using namespace std; class Clusterize { private: Mat image_; list<CvPoint> points_; deque<deque<CvPoint>> clusters_; deque<CvPoint> clustersCentres_; //for icon & text position // not used for fast calculations boost::filesystem::path saveDir_; boost::filesystem::path nameImg_; boost::filesystem::path currentFile_; boost::filesystem::path rootDir_; //directory with .exe in which to look for the config //settings will be taken from config //initialized in case the config is deleted //in the fast compute mode the cluster centers are not calculated. //points are connected to the first suitable cluster (not the fact that the nearest one) bool FLAG_fastCompute_ = false; //if clusters are connected, then they are merged into one // //this flag can turn it off / on bool FLAG_hasMerge_ = true; //this flag controls the display of the window bool FLAG_canDisplay_ = false; //this flag controls the rendering of the count points in cluster bool FLAG_hasText_ = true; //rendering cluster icons bool FLAG_hasIcon_ = true; //rendering point bool FLAG_hasPoints_ = true; //rendering lines bool FLAG_hasLines_ = false; int textScale_ = 5; int radius_ = 10; public: //read config & init variables Clusterize(); //freeing resources ~Clusterize(); //execution of console arguments // init from arguments Clusterize(int& argc, char* argv[]) noexcept(false); //getters int getHeight(); int getWidth(); string getSaveDir(); string getNameImage(); string getCurrentFile(); list<CvPoint> getPoints(); deque<deque<CvPoint>> getClusters(); deque<CvPoint> getClustersCentres(); bool getFlagFastCompute(); bool getFlagMerge(); bool getFlagDisplay(); bool getFlagText(); bool getFlagIcon(); bool getFlagPoints(); bool getFlagLines(); int getTextScale(); int getRadius(); //setters void setImage(const string& filename); void setRadius(const int radius); void setSaveDir(const string& path); void setNameImage(const string& filename); void setTextScale(const int scale); void useFastCompute(bool state=false); void useMerge(bool state=true); void useDisplay(bool state=false); void useDrawingText(bool state=true); void useDrawingIcons(bool state=true); void useDrawingPoints(bool state=true); void useDrawingLines(bool state=false); //methods void printHelp(); //combine the points from points_ to clusters void combine() noexcept(false); void reCombine(); //defines which cluster the point belongs to void identifyPoint(const CvPoint& p); void identifyPoint(float x, float y); //add point to queue points which used in combine/recombine( void addPoint(float x, float y); void addPoint(const CvPoint& p); void clearClusters(); void clearPoint(); //draw clusters on image_ void draw(); //display if true; draw() anyway void draw(bool); //save image to saveDir_ with name nameImg_ (.jpg) void save(); private: //ucalculates cluster centers, not used for quick calculations void _computeClustersCenter(); //returns the minimum distance from a point to a cluster point float _computeMinDistanceToCluster(const deque<CvPoint>& cluster, const CvPoint& p); //read config file "ClusterConfig.xml" in .exe directory void readConfig(string path); //creates a config if it is not found or invalid void createConfig(string path); //UICallbacks static bool _is_jpg(string filename); static void _myMouseCallback(int event, int x, int y, int flags, void* param); static void _radiusCallback(int pos, void* param); static void _fontCallback(int pos, void* param); static void _clearCallback(int pos, void* param); static void _textCallback(int pos, void* param); static void _pointsCallback(int pos, void* param); static void _iconsCallback(int pos, void* param); static void _linesCallback(int pos, void* param); static void _mergeCallback(int pos, void* param); static void _fastCallback(int pos, void* param); }; <file_sep>/Vectorizer/Source/main.cpp #include <iostream> #include <boost/filesystem.hpp> #include "Vectorize.h" using namespace std; // function for console control void menu(Vectorize&); void menuSettings(Vectorize&); int main(int argc, char* argv[]) { Vectorize vr; try { if (argc > 1) //opened via console arguments vr = Vectorize(argc, argv); else { //opened via .exe without arguments menu(vr); } } catch (exception ex) { cout << "\nError: " << ex.what() << endl << endl; menu(vr); } catch (...) { cout << "Uknown error" << endl; menu(vr); } return 0; } void menu(Vectorize& vr) { int option = 0; cout << "1: Set image path\n" << "2: Display image\n" << "3: Settings\n" << "4: Save\n" << "5: Menu\n" << "6: Exit\n" << endl; cin >> option; switch (option) { case 1: { string path; cout << "Enter path to image " "('D:/MyPicture/Example.jpg')\n" "Your path to image: "; cin >> path; vr.setImage(std::move(path)); vr.draw(); menu(vr); break; } case 2: vr.display(); menu(vr); break; case 3: { menuSettings(vr); break; } case 4: { string answer; cout << "Specify the save path ?(y\\n)\n" "Current save dir: " << vr.getSaveDir() << endl; cin >> answer; if (answer == "y") { string path; cout << "Enter path to save directory: "; cin >> path; vr.setSaveDir(std::move(path)); vr.save(); } else if (answer == "n") { vr.save(); } else { cout << "Your answer is not recognized :/" << endl;; } menu(vr); break; } case 5: { menu(vr); break; } case 6: { cout << "Good Luck! I`am turn off." << endl;; return; break; } default: menu(vr); break; } } void menuSettings(Vectorize& vr) { int option = 0; cout << std::boolalpha << "\n1: use Skelet:" << vr.getOptionSkelet() << "\n2: use Contour:" << vr.getOptionContour() << "\n3: use Object:" << vr.getOptionObject() << "\n4: Menu" << endl; cin >> option; switch (option) { case 1: { vr.useSkelet(!vr.getOptionSkelet()); menuSettings(vr); break; } case 2: { vr.useContour(!vr.getOptionContour()); menuSettings(vr); break; } case 3: { vr.useObject(!vr.getOptionObject()); menuSettings(vr); break; } case 4: { menu(vr); break; } default: menuSettings(vr); break; } }<file_sep>/Vectorizer/Source/Vectorize.h #pragma once #include <Windows.h> //boost #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/ptree.hpp> //opencv #include <opencv2/core.hpp> #include <opencv2/opencv.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc/imgproc_c.h> #include <opencv2/highgui.hpp> #include <opencv2/highgui/highgui_c.h> #include <opencv2/core/types_c.h> //stl #include <vector> class Vectorize { private: //variable cv::Mat image_; cv::Mat originalImage_; bool hasSkelet_= true; bool hasContour_= false; bool hasObject_ = false; bool isDisplayed_ = false; boost::filesystem::path saveDir_; boost::filesystem::path name_; public: //read config Vectorize(); //init with console arguments Vectorize(int argc, char* argv[]); //freeing resources ~Vectorize(); //setters void setImage(std::string filename); void setSaveDir(std::string saveDirectory); void useSkelet(bool state); void useContour(bool state); void useObject(bool state); //getters std::string getSaveDir(); bool getOptionSkelet(); bool getOptionContour(); bool getOptionObject(); //methods void draw(); void display(); void save(); private: void readConfig(std::string path); void createConfig(std::string path); void thinningObjects();//get object skelet void contouringObjects(); void thinning(const cv::Mat& in, cv::Mat& out); void thinningIteration(cv::Mat& img, int iter); //UICallbacks static void _objectCallback(int pos, void* param); static void _contourCallback(int pos, void* param); static void _skeletCallback(int pos, void* param); };<file_sep>/Vectorizer/Readme.md # Clusterizer ## Описание Vectorizer - На вход принимает бинарный растр с черными объектами на нем, может возращать скелет этих обьектов (линии проходящие по центру объекта, векторно описывающие его форму),контуры объектов или все вместе. Растр и параметры могут задаваться через конфиг в папке с .exe/аргументы командной строки/консольное меню приложения/панели инструментов в окне отображения растра. Реализованно с помощью OpenCV & Boost. [Более подробно](https://github.com/AntKerf/Tasks/tree/main/Vectorizer). ## Управление Приложение может быть из консоли с аргументами: -i 'path To Image' | Задает путь к растру -o | Включает отрисовку объектов на растре -c | Включает отрисовку контуров объектов на растре -s | Включает отрисовку скелета объектов на растре -!o | Отключает отрисовку объектов на растре -!c | Отключает отрисовку контуров на растре -!s | Отключает отрисовку скелета на растре -d | Просмотр изображения -saveDir 'save Dir' | Устанавливает путь для сохранения растров -h | показывает справку, помощь Приложение может быть запущено через .exe, в этом случает запуститься консольное меню с выбором команд Так же в окне отображения можно открыть панель настроек(верхний правый значок) Панель инструментов позволяет: 'Object' - отображение объектов на растре 'Contour' - отображение контура объекта на растре 'Skelet' - отображение скелета объекта на растре ## Файлы В папке 'Source' содержатся исходники кода на C++. Проект может быть собран через CMake. [Подробнее](https://github.com/AntKerf/Tasks/wiki/Build). ## Скриншот ![Clusterizer](https://i.ibb.co/Xy8V4vj/Screenshot-38.png) <file_sep>/Vectorizer/CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(Vectorizer) set(SOURCE_FILE Source/main.cpp Source/Vectorize.cpp Source/Vectorize.h) add_executable(Vectorizer ${SOURCE_FILE}) option(HAVE_BOOST "CMake try the find Boost package" OFF) option(HAVE_OPENCV "CMake try the find OpenCV package" OFF) ###################_find_package ###################_Boost::filesystem if(HAVE_BOOST) set(Boost_USE_STATIC_LIBS ON) find_package( Boost COMPONENTS filesystem REQUIRED ) else() message("without BOOST") message("For the project to work, you must manually specify the directory with BOOST libraries!!!") endif() ############################################################# ###################_OpenCV if(HAVE_OPENCV) find_package( OpenCV REQUIRED ) else() message("without OpenCV") message("For the project to work, you must manually specify the directory with OpenCV libraries!!!") endif() ############################################################## ###################_link_package ###################_Boost::filesystem if(HAVE_BOOST) if(NOT Boost_FOUND) message(SEND_ERROR "Failed to find Boost::filesystem") return() else() include_directories(${Boost_INCLUDE_DIRS}) target_link_libraries(Vectorizer ${Boost_LIBRARIES}) endif() endif() ################################################################ ##################_OpenCV if(HAVE_OPENCV) if(NOT OpenCV_FOUND) message(SEND_ERROR "Failed to find OpenCV") return() else() include_directories( ${OpenCV_INCLUDE_DIRS} ) target_link_libraries(Vectorizer ${OpenCV_LIBS}) endif() endif() ##########################################################<file_sep>/Vectorizer/Source/Vectorize.cpp #include "Vectorize.h" using namespace std; using namespace cv; Vectorize::Vectorize() : image_(Mat(500, 500, CV_8UC1(3), Scalar(255, 255, 255))),//new white 500*500 image originalImage_(Mat(500, 500, CV_8UC1(3), Scalar(255, 255, 255)))//new white 500*500 image { try { WCHAR path[500]; GetModuleFileNameW(NULL, path, 500); //find .exe path //work in windows only boost::filesystem::path rootDir_ = boost::filesystem::path(path).parent_path(); //directory with .exe //default directory for save images saveDir_ = (boost::filesystem::system_complete(rootDir_.string() + "/Vectorize Images/")); //if config exists if (boost::filesystem::is_regular_file(rootDir_.string() + "/VectorConfig.xml")) { readConfig(rootDir_.string() + "/VectorConfig.xml"); } else // create new config file; { createConfig(rootDir_.string() + "/VectorConfig.xml"); } } catch (Exception& ex) { cout << "Init error: " << ex.what() << endl; } catch (...) { cout << "Init error: " << endl; } } Vectorize::Vectorize(int argc, char* argv[]) : Vectorize() { bool _canDisplay = false; for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "-i") == 0) { //image init if (++i < argc) { setImage(argv[i]); } else throw std::invalid_argument("Image not found"); } else if (strcmp(argv[i], "-o") == 0) { hasObject_ = true; } else if (strcmp(argv[i], "-c") == 0) { hasContour_ = true; } else if (strcmp(argv[i], "-s") == 0) { hasSkelet_ = true; } else if (strcmp(argv[i], "-!o") == 0) { hasObject_ = false; } else if (strcmp(argv[i], "-!c") == 0) { hasContour_ = false; } else if (strcmp(argv[i], "-!s") == 0) { hasSkelet_ = false; } else if (strcmp(argv[i], "-d") == 0) { _canDisplay = true; } else if (strcmp(argv[i], "-saveDir") == 0) { if (++i < argc) setSaveDir(argv[i]); else throw std::invalid_argument("Save directory not found"); } else if (strcmp(argv[i], "-h") == 0) { // printHelp(); } } draw(); if (_canDisplay) display(); save(); } Vectorize::~Vectorize() { //freeing resources image_.release(); originalImage_.release(); destroyAllWindows(); } void Vectorize::setImage(std::string filename) { if (boost::filesystem::is_regular_file(filename))//if real and jpg file { originalImage_ = imread(filename, CV_8UC1(3)); // Read the file threshold(originalImage_, originalImage_, 127, 255, THRESH_BINARY);//only black & white name_ = boost::filesystem::path(filename).filename(); auto i = name_.string().find(".", 0); name_ = name_.string().substr(0, i); } else throw std::invalid_argument("Path to image is invalid"); } void Vectorize::setSaveDir(std::string saveDirectory) { saveDir_ = boost::filesystem::system_complete( boost::filesystem::path(saveDirectory).append("/")); } void Vectorize::useSkelet(bool state) { hasSkelet_ = state; } void Vectorize::useContour(bool state) { hasContour_ = state; } void Vectorize::useObject(bool state) { hasObject_ = state; } std::string Vectorize::getSaveDir() { return saveDir_.string(); } bool Vectorize::getOptionSkelet() { return hasSkelet_; } bool Vectorize::getOptionContour() { return hasContour_; } bool Vectorize::getOptionObject() { return hasObject_; } void Vectorize::display() { namedWindow("Display window", CV_WINDOW_AUTOSIZE); // Create a window for display. createButton("Object", _objectCallback, this, QT_CHECKBOX, hasObject_); createButton("Contour", _contourCallback, this, QT_CHECKBOX, hasContour_); createButton("Skelet", _skeletCallback, this, QT_CHECKBOX, hasSkelet_); imshow("Display window", image_); isDisplayed_ = true; while (getWindowProperty("Display window", WND_PROP_VISIBLE)) { int key = waitKey(1000); // Wait for a keystroke in the window if (key == 27) break; } destroyWindow("Display window"); isDisplayed_ = false; } void Vectorize::save() { if (!boost::filesystem::is_directory(saveDir_)) //create new dir if current dir not found boost::filesystem::create_directory(saveDir_); if (name_.empty())//set data\time to image name { string temp_name = saveDir_.string() + "Vector_" + boost::posix_time::to_iso_string( boost::posix_time::second_clock::local_time()) + ".jpg"; if (cv::imwrite(temp_name, image_)) cout << "Image saved: " << temp_name << endl; else cout << "Save error" << endl; } else { string temp_name = saveDir_.string() + name_.string() + boost::posix_time::to_iso_string( boost::posix_time::second_clock::local_time()) + ".jpg"; if (cv::imwrite(temp_name, image_)) cout << "Image saved: " << temp_name<< endl; else cout << "Save error" << endl; } } void Vectorize::readConfig(std::string path) { try { boost::property_tree::ptree Config; boost::property_tree::read_xml(path, Config); //read xml in .exe directory Config = Config.get_child("SettingsList"); hasSkelet_ = Config.get<bool>("Skelet"); hasContour_ = Config.get<bool>("Contour"); hasObject_ = Config.get<bool>("Object"); } //if bad config file - recreate to default catch (boost::wrapexcept<boost::property_tree::ptree_bad_path> ex) { createConfig(path); } } void Vectorize::createConfig(std::string path) { boost::property_tree::ptree Config; boost::property_tree::ptree Settings; Settings.add<bool>("Skelet", hasSkelet_); Settings.add<bool>("Contour", hasContour_); Settings.add<bool>("Object", hasObject_); Config.add_child("SettingsList", Settings); auto write_settings = boost::property_tree::xml_writer_make_settings<string>('\t', 1); boost::property_tree::write_xml(path, Config, std::locale(), write_settings); } void Vectorize::thinningObjects() { Mat _prev = Mat::zeros(originalImage_.size(), CV_8UC1); thinning(~originalImage_, _prev); if (hasObject_) add(image_, _prev, image_); else addWeighted(image_, 0.5, ~_prev, 0.5, 1, image_); } void Vectorize::contouringObjects() { //Extract the contours so that vector<vector<Point> > _contours; vector<Vec4i> _hierarchy; findContours(~originalImage_, _contours, _hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE); Mat _cnt_img = Mat::zeros(originalImage_.size(), CV_8UC1); drawContours(_cnt_img, _contours, -1, Scalar(255, 255, 255), 3, LINE_AA, _hierarchy, _contours.size()); addWeighted(image_, 0.5, ~_cnt_img, 0.5, 1, image_); } void Vectorize::draw() { if (hasObject_) image_ = originalImage_.clone(); // draw object on result image else image_ = (Mat(500, 500, CV_8UC1(3), Scalar(255, 255, 255))); if (hasContour_) { contouringObjects(); } if (hasSkelet_) { thinningObjects(); } if (isDisplayed_) imshow("Display window", image_); } void Vectorize::thinningIteration(cv::Mat& img, int iter) { CV_Assert(img.channels() == 1); CV_Assert(img.depth() != sizeof(uchar)); CV_Assert(img.rows > 3 && img.cols > 3); cv::Mat marker = cv::Mat::zeros(img.size(), CV_8UC1); int nRows = img.rows; int nCols = img.cols; if (img.isContinuous()) { nCols *= nRows; nRows = 1; } int x, y; uchar* pAbove; uchar* pCurr; uchar* pBelow; uchar* nw, * no, * ne; // north (pAbove) uchar* we, * me, * ea; uchar* sw, * so, * se; // south (pBelow) uchar* pDst; // initialize row pointers pAbove = NULL; pCurr = img.ptr<uchar>(0); pBelow = img.ptr<uchar>(1); for (y = 1; y < img.rows - 1; ++y) { // shift the rows up by one pAbove = pCurr; pCurr = pBelow; pBelow = img.ptr<uchar>(y + 1); pDst = marker.ptr<uchar>(y); // initialize col pointers no = &(pAbove[0]); ne = &(pAbove[1]); me = &(pCurr[0]); ea = &(pCurr[1]); so = &(pBelow[0]); se = &(pBelow[1]); for (x = 1; x < img.cols - 1; ++x) { // shift col pointers left by one (scan left to right) nw = no; no = ne; ne = &(pAbove[x + 1]); we = me; me = ea; ea = &(pCurr[x + 1]); sw = so; so = se; se = &(pBelow[x + 1]); int A = (*no == 0 && *ne == 1) + (*ne == 0 && *ea == 1) + (*ea == 0 && *se == 1) + (*se == 0 && *so == 1) + (*so == 0 && *sw == 1) + (*sw == 0 && *we == 1) + (*we == 0 && *nw == 1) + (*nw == 0 && *no == 1); int B = *no + *ne + *ea + *se + *so + *sw + *we + *nw; int m1 = iter == 0 ? (*no * *ea * *so) : (*no * *ea * *we); int m2 = iter == 0 ? (*ea * *so * *we) : (*no * *so * *we); if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0) pDst[x] = 1; } } img &= ~marker; } void Vectorize::_objectCallback(int pos, void* param) { auto vr = (Vectorize*)param; vr->hasObject_ = pos; vr->draw(); } void Vectorize::_contourCallback(int pos, void* param) { auto vr = (Vectorize*)param; vr->hasContour_ = pos; vr->draw(); } void Vectorize::_skeletCallback(int pos, void* param) { auto vr = (Vectorize*)param; vr->hasSkelet_ = pos; vr->draw(); } /** * Function for thinning the given binary image * * Parameters: * src The source image, binary with range = [0,255] * dst The destination image */ void Vectorize::thinning(const cv::Mat& in, cv::Mat& out) { out = in.clone(); out /= 255; // convert to binary image cv::Mat prev = cv::Mat::zeros(out.size(), CV_8UC1); cv::Mat diff; do { thinningIteration(out, 0); thinningIteration(out, 1); cv::absdiff(out, prev, diff); out.copyTo(prev); } while (cv::countNonZero(diff) > 0); out *= 255; } <file_sep>/Clusterizer/Source/main.cpp  #include "Cluster.h" #include <iostream> #include <boost/filesystem.hpp> using namespace std; /* Initialization is available via cmd arguments : -i ".../pic.jpg" // initialize the bitmap - p 10 20 // add a point with coordinates x = 10 y = 20 - r 10 // Set the radius of union between points // default 10 - s ".../img/" // Set the path to save // the default Clusterize Image folder in the .exe folder - d // display raster window (opencv) - h // show commands */ // function for console control void menu(Clusterize&); void menuSettings(Clusterize&); int main(int argc, char* argv[]) { Clusterize cl; try { if (argc > 1) //opened via console arguments cl = Clusterize(argc, argv); else { //opened via .exe without arguments menu(cl); } } catch (exception ex) { cout << "\nError: " << ex.what() << endl << endl; menu(cl); } system("pause"); return 0; } void menu(Clusterize& cl) { int option = 0; cout << "\n1: Set image path" << "\n2: Display image" << "\n3: Add point" << "\n4: Settings" << "\n5: Save" << "\n6: Menu" << "\n7: Exit" << endl; cin >> option; switch (option) { case 1: { string path; cout << "Enter path to image " "('D:/MyPicture/Example.jpg')\n" "Your path to image: "; cin >> path; cl.setImage(std::move(path)); menu(cl); break; } case 2: cl.draw(true); menu(cl); break; case 3: { CvPoint p; cout << "Enter x:"; cin >> p.x; cout << "Enter y:"; cin >> p.y; cl.addPoint(std::move(p)); cl.reCombine(); menu(cl); break; } case 4: { menuSettings(cl); break; } case 5: { string answer; cout << "Specify the save path ?(y\\n)\n" "Current save dir: " << cl.getSaveDir() << endl; cin >> answer; if (answer == "y") { string path; cout << "Enter path to save directory: "; cin >> path; cl.setSaveDir(std::move(path)); cl.save(); } else if (answer == "n") { cl.save(); } else { cout << "Your answer is not recognized :/" << endl;; } menu(cl); break; } case 6: menu(cl); break; case 7: cout << "Good Luck! I`am turn off." << endl;; return; break; default: menu(cl); break; } } void menuSettings(Clusterize& cl) { int option = 0; cout << std::boolalpha << "\n1: Fast Compute: " << cl.getFlagFastCompute() << "\n2: Merging clusters: " << cl.getFlagMerge() << "\n3: Auto Display: " << cl.getFlagDisplay() << "\n4: Text: " << cl.getFlagText() << "\n5: Icons: " << cl.getFlagIcon() << "\n6: Points: " << cl.getFlagPoints() << "\n7: Lines:" << cl.getFlagLines() << "\n8: Text Scale: " << cl.getTextScale() << "\n9: Radius : " << cl.getRadius() << "\n10: Menu" << endl; cin >> option; switch (option) { case 1: { cl.useFastCompute(!cl.getFlagFastCompute()); menuSettings(cl); break; } case 2: { cl.useMerge(!cl.getFlagMerge()); menuSettings(cl); break; } case 3: { cl.useDisplay(!cl.getFlagDisplay()); menuSettings(cl); break; } case 4: { cl.useDrawingText(!cl.getFlagText()); menuSettings(cl); break; } case 5: { cl.useDrawingLines(!cl.getFlagLines()); menuSettings(cl); break; } case 6: { cl.useDrawingPoints(!cl.getFlagPoints()); menuSettings(cl); break; } case 7: { cl.useDrawingLines(!cl.getFlagLines()); menuSettings(cl); break; } case 8: { int _scale; cout << "Enter TextScale: "; cin >> _scale; cl.setTextScale(_scale); menuSettings(cl); break; } case 9: { int _radius; cout << "Enter radius:"; cin >> _radius; cl.setRadius(_radius); menuSettings(cl); break; } case 10: { menu(cl); break; } default: menuSettings(cl); break; } }<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(Tasks) add_subdirectory(Clusterizer/) add_subdirectory(Vectorizer/) add_custom_target(Tasks) add_dependencies(Tasks Clusterizer Vectorizer) <file_sep>/Clusterizer/ReadMe.md # Clusterizer ## Описание Clusterizer - Производит кластеризацию пространственных данных. На вход поступает какой либо растр(.jpg), выполняющий роль фона, и точки в пределах растра. Ближайщие друг к другу точки объединяются в кластер. Расстояние объединения можно изменять. На растре кластеры отображаются разными цветами и могут иметь свои иконки с указанием количества точек в них. Отображение кластеров может настраиваться с помощью конфига в папке с .exe/аргумеентов командной строки/консольного меню/панели инструментов в окне отображения растра. Имеет два режима объединения. 1: Сливание кластеров включено. Когда два кластера имеют точку которая подходит по растоянию к ним обоим то они сливаются в один. 2: Сливание кластеров отключено. Когда два кластера имеют точку подходящщую по растоянию к ним обоим они не сливаются. Точка остается в кластере "ближайщего соседа". Реализованно с помощью OpenCV & Boost. ## Управление Приложение может быть из консоли с аргументами: -i 'path To Image' | Задает путь к растру -p x y | Устанавливает точку на растре с координатами x:y -r m | Задает радиус объединения m, растояние от точки в зоне которого она будет искать "соседей" -s 'save directory' | Задает путь для сохранения растра -d | отображает окно просмотра растра -h | показывает справку, помощь Приложение может быть запущено через .exe, в этом случает запуститься консольное меню с выбором команд Есть возможно не задавать все точки через консоль, а поставить их вручную на растре в окно оторбажения растра с помощью Ctrl + ЛКМ. Для изменения радиуса объединения снизу присутсвует TrackBar 'Radius'. Так же в окне отображения можно открыть панель настроек(верхний правый значок) Панель инструментов позволяет: 'Fonst size' - регулирует размер шрифта 'Clear' - очистка всех точек и кластеров 'Points' - отображение точек на растре 'Text' - отображение текстовой информации, количества точек в кластере 'Clusters' - отображение иконок кластера 'Lines' - соединяет точки кластера линиями и отображает 'Merging clusters' - переключение между режимами слияния кластеров 'Fast compute' - режим быстрого вычисления. В режиме быстрого вычесления не вычесляютя центры кластеров и иконки кластеров и текст оторбражается на последней входящей в кластер точке. ## Файлы В папке 'Source' содержатся исходники кода на C++. Проект может быть собран через CMake. [Подробнее](https://github.com/AntKerf/Tasks/wiki/Build). ## Скриншот ![Clusterizer](https://i.ibb.co/60J7HLc/image.png) <file_sep>/README.md # Tasks Various tasks for programming practice ## Описание Данный репозиторий содержит в себе 2 проекта Clusterizer & Vectorizer #### Clusterizer Clusterizer - Производит кластеризацию пространственных данных. На вход поступает какой либо растр(.jpg), выполняющий роль фона, и точки в пределах растра. Ближайщие друг к другу точки объединяются в кластер. Расстояние объединения можно изменять. На растре кластеры отображаются разными цветами и могут иметь свои иконки с указанием количества точек в них. Отображение кластеров может настраиваться с помощью конфига в папке с .exe/аргумеентов командной строки/консольного меню/панели инструментов в окне отображения растра. Имеет два режима объединения. 1: Сливание кластеров включено. Когда два кластера имеют точку которая подходит по растоянию к ним обоим то они сливаются в один. 2: Сливание кластеров отключено. Когда два кластера имеют точку подходящщую по растоянию к ним обоим они не сливаются. Точка остается в кластере "ближайщего соседа". Реализованно с помощью OpenCV & Boost. [Более подробно](https://github.com/AntKerf/Tasks/tree/main/Clusterizer). #### Vectorizer Vectorizer - На вход принимает бинарный растр с черными объектами на нем, может возращать скелет этих обьектов(линии проходящие по центру объекта, векторно описывающие его форму),контуры объектов или все вместе. Растр и параметры могут задаваться через конфиг в папке с .exe/аргументы командной строки/консольное меню приложения/панели инструментов в окне отображения растра.Реализованно с помощью OpenCV & Boost. [Более подробно](https://github.com/AntKerf/Tasks/tree/main/Vectorizer). #### CMake В корневой папке репозитория имеется CMakeLists.txt который позволяет собрать оба проекта сразу. Так же каждый проект имеет свой CMakeLists.txt что опозволяет собрать определнный проект. [Более подробно](https://github.com/AntKerf/Tasks/wiki/Build). #### Зависимости Для работы проекта необходим OpenCV собранный с привязкой к QT,для отображения окна просмотра и панели инструментов. Так же необоходим Boost::filesystem, Boost::algorithm, Boost::date_time, Boost::property_tree. ## Сборка Этапы сборки проекта описаны [здесь](https://github.com/AntKerf/Tasks/wiki/Build). <file_sep>/Clusterizer/Source/Cluster.cpp #include "Cluster.h" Clusterize::Clusterize() : // default settings points_(NULL), image_(cv::Mat(500, 500, CV_8UC(3), cv::Scalar(255, 255, 255))),//new white 500*500 image currentFile_(), nameImg_() { try { WCHAR path[500]; GetModuleFileNameW(NULL, path, 500); //find .exe path //work in windows only rootDir_ = boost::filesystem::path(path).parent_path(); //directory with .exe //default directory for save images saveDir_ = (boost::filesystem::system_complete(rootDir_.string() + "/Clusterize Images/")); //if config exists if (boost::filesystem::is_regular_file(rootDir_.string() + "/ClusterConfig.xml")) { readConfig(rootDir_.string() + "/ClusterConfig.xml"); } else // create new config file; { createConfig(rootDir_.string() + "/ClusterConfig.xml"); } } catch (Exception& ex) { cout << "Init error: " << ex.what() << endl; } catch (...) { cout << "Init error: " << endl; } } Clusterize::Clusterize(int& argc, char* argv[]) noexcept(false) : Clusterize() { for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "-i") == 0) { //image init if (++i < argc) { setImage(argv[i]); } else throw std::invalid_argument("Image not found"); } else if (strcmp(argv[i], "-p") == 0) { //point init float x; float y; if (++i < argc && (x = atof(argv[i]))) if (++i < argc && (y = atof(argv[i]))) addPoint(x, y); else throw std::invalid_argument("Invalid point y argument"); else throw std::invalid_argument("Invalid point x argument"); } else if (strcmp(argv[i], "-r") == 0) { //init radius float r_tmp; if (++i < argc && (r_tmp = atof(argv[i]))) setRadius(r_tmp); else throw std::invalid_argument("Invalid radius argument"); } else if (strcmp(argv[i], "-s") == 0) { //init save path if (++i < argc) setSaveDir(argv[i]); else throw std::invalid_argument("Save directory not found"); } else if (strcmp(argv[i], "-d") == 0) { //display win with image FLAG_canDisplay_ = true; } else if (strcmp(argv[i], "-h") == 0) { printHelp(); } } combine(); draw(FLAG_canDisplay_); save(); } Clusterize::~Clusterize() { //freeing resources image_.release(); destroyAllWindows(); } void Clusterize::useDisplay(bool state) { FLAG_canDisplay_ = state; } void Clusterize::useDrawingText(bool state) { FLAG_hasText_ = state; } void Clusterize::useDrawingIcons(bool state) { FLAG_hasIcon_ = state; } void Clusterize::useDrawingPoints(bool state) { FLAG_hasPoints_ = state; } void Clusterize::useDrawingLines(bool state) { FLAG_hasLines_ = state; } void Clusterize::printHelp() { cout << "=================Clusterizer 0.1=====================" << endl; cout << "-i 'file path'\t:Select jpg image." << endl; cout << "-p x y\t\t:Add point." << endl; cout << "-s 'dir path'\t:Specify the save path." << endl; cout << "-r x\t\t:Set the point union radius." << endl; cout << "-d \t\t:Display win with image." << endl; cout << "=====================================================" << endl; } int Clusterize::getHeight() { return image_.rows; } int Clusterize::getWidth() { return image_.cols; } string Clusterize::getSaveDir() { return saveDir_.string(); } string Clusterize::getNameImage() { return nameImg_.string(); } string Clusterize::getCurrentFile() { return currentFile_.string(); } list<CvPoint> Clusterize::getPoints() { return points_; } deque<deque<CvPoint>> Clusterize::getClusters() { return clusters_; } deque<CvPoint> Clusterize::getClustersCentres() { return clustersCentres_; } bool Clusterize::getFlagFastCompute() { return FLAG_fastCompute_; } bool Clusterize::getFlagMerge() { return FLAG_hasMerge_; } bool Clusterize::getFlagDisplay() { return FLAG_canDisplay_; } bool Clusterize::getFlagText() { return FLAG_hasText_; } bool Clusterize::getFlagIcon() { return FLAG_hasIcon_; } bool Clusterize::getFlagPoints() { return FLAG_hasPoints_; } bool Clusterize::getFlagLines() { return FLAG_hasLines_; } int Clusterize::getTextScale() { return textScale_; } int Clusterize::getRadius() { return radius_; } void Clusterize::setImage(const string& filename) { if (boost::filesystem::is_regular_file(filename) && _is_jpg(filename))//if real and jpg file { image_ = imread(filename, IMREAD_COLOR); // Read the file nameImg_ = boost::filesystem::path(filename).filename(); currentFile_ = boost::filesystem::path(filename); } else throw std::invalid_argument("Path to image is invalid"); } void Clusterize::setRadius(const int radius) { radius_ = radius; } void Clusterize::setSaveDir(const string& path) { saveDir_ = boost::filesystem::system_complete( boost::filesystem::path(path).append("/")); } void Clusterize::setNameImage(const string& filename) { nameImg_ = filename; } void Clusterize::setTextScale(const int scale) { textScale_ = scale; } void Clusterize::useFastCompute(bool state) { FLAG_fastCompute_ = state; } void Clusterize::useMerge(bool state) { FLAG_hasMerge_ = state; } //combine points into a cluster void Clusterize::combine() noexcept(false) { if (!image_.empty()) { //image validate if (clusters_.empty()) { //init clusters deque<list<CvPoint>::iterator> itForDelete; //points to be removed from list deque<CvPoint> newCluster; while (!points_.empty()) { newCluster.push_back(points_.front()); points_.pop_front(); for (size_t i = 0; i < newCluster.size(); i++) { for (auto itPoint = points_.begin(); itPoint != points_.end(); itPoint++) { //compute distance between points if (sqrtf( powf(newCluster[i].x - itPoint->x, 2) + powf(newCluster[i].y - itPoint->y, 2)) <= radius_) { newCluster.push_back(*itPoint); itForDelete.push_back(itPoint); } } for (size_t i = 0; i < itForDelete.size(); i++) { points_.erase(itForDelete[i]); } itForDelete.clear(); } clusters_.push_back(newCluster); newCluster.clear(); } } else { //otherwise, map the point to an existing cluster, if clusters already exist for (size_t i = 0; i < points_.size(); i++) { identifyPoint(points_.front()); points_.pop_front(); } } if (!FLAG_fastCompute_) { _computeClustersCenter(); } } else throw std::logic_error("Image not set."); } //parsing a cluster into points and combine() void Clusterize::reCombine() { for (auto cluster : clusters_) { for (auto point : cluster) { points_.push_back(point); } } clusters_.clear(); if (FLAG_hasMerge_) combine(); else { for (auto point : points_) identifyPoint(point); points_.clear(); } } void Clusterize::_computeClustersCenter() { clustersCentres_.clear(); CvPoint calculatedCenter; for (size_t i = 0; i < clusters_.size(); i++) //all clusters { calculatedCenter = cvPoint(0, 0); for (size_t j = 0; j < clusters_[i].size(); j++) //all points { calculatedCenter.x += clusters_[i][j].x; calculatedCenter.y += clusters_[i][j].y; } calculatedCenter.x /= clusters_[i].size(); calculatedCenter.y /= clusters_[i].size(); clustersCentres_.push_back(calculatedCenter); } } float Clusterize::_computeMinDistanceToCluster(const deque<CvPoint>& cluster, const CvPoint& p) { //without STL /* float min_radius = radius_ + 1; for (size_t i = 0; i < cluster.size(); i++) //all points in clusters { float compare_radius = (sqrtf( powf(cluster[i].x - p.x, 2) + powf(cluster[i].y - p.y, 2))); if (compare_radius <= min_radius) min_radius = compare_radius; } return min_radius; */ //with STL auto near_point = min_element(cluster.begin(), cluster.end(), [&](const CvPoint& a, const CvPoint& b) //lambda { return ((sqrtf(powf(a.x - p.x, 2) + powf(a.y - p.y, 2))) < (sqrtf(powf(b.x - p.x, 2) + powf(b.y - p.y, 2)))); }); return (sqrtf(powf(near_point->x - p.x, 2) + powf(near_point->y - p.y, 2))); } void Clusterize::readConfig(string path) { try { boost::property_tree::ptree Config; boost::property_tree::read_xml(path, Config); //read xml in .exe directory Config = Config.get_child("SettingsList"); FLAG_fastCompute_ = Config.get<bool>("fastCompute"); FLAG_hasMerge_ = Config.get<bool>("merge"); FLAG_canDisplay_ = Config.get<bool>("dislay"); FLAG_hasText_ = Config.get<bool>("text"); FLAG_hasIcon_ = Config.get<bool>("icon"); FLAG_hasPoints_ = Config.get<bool>("points"); FLAG_hasLines_ = Config.get<bool>("lines"); radius_ = Config.get<int>("radius"); textScale_ = Config.get<int>("textScale"); } //if bad config file - recreate to default catch (boost::wrapexcept<boost::property_tree::ptree_bad_path> ex) { createConfig(path); } } void Clusterize::createConfig(string path) { boost::property_tree::ptree Config; boost::property_tree::ptree Settings; Settings.add<bool>("fastCompute", FLAG_fastCompute_); Settings.add<bool>("merge", FLAG_hasMerge_); Settings.add<bool>("display", FLAG_canDisplay_); Settings.add<bool>("text", FLAG_hasText_); Settings.add<bool>("icon", FLAG_hasIcon_); Settings.add<bool>("points", FLAG_hasPoints_); Settings.add<bool>("lines", FLAG_hasLines_); Settings.add<int>("radius", radius_); Settings.add<int>("textScale", textScale_); Config.add_child("SettingsList", Settings); auto write_settings = boost::property_tree::xml_writer_make_settings<string>('\t', 1); boost::property_tree::write_xml(path, Config, std::locale(), write_settings); } void Clusterize::identifyPoint(const CvPoint& p) { //find min distance between point and all points in clusters auto near_cluster = min_element(clusters_.begin(), clusters_.end(), [&](const auto& a, const auto& b) //lambda { float aR = _computeMinDistanceToCluster(a, p); float bR = _computeMinDistanceToCluster(b, p); return aR < bR; }); if (near_cluster != clusters_.end() && _computeMinDistanceToCluster(*near_cluster, p) <= radius_) near_cluster->push_back(p); else { deque<CvPoint> newCluster{ p }; clusters_.push_back(newCluster); } if (!FLAG_fastCompute_) _computeClustersCenter(); } void Clusterize::identifyPoint(float x, float y) { CvPoint newPoint = cvPoint(x, y); identifyPoint(newPoint); } void Clusterize::addPoint(float x, float y) { points_.push_back(cvPoint(x, y)); } void Clusterize::addPoint(const CvPoint& p) { points_.push_back(p); } void Clusterize::clearClusters() { clusters_.clear(); } void Clusterize::clearPoint() { if (!points_.empty()) points_.clear(); } void Clusterize::draw() { // clear for draw fresh data if (!currentFile_.empty()) image_ = imread(currentFile_.string(), IMREAD_COLOR); else image_ = Mat(cv::Mat(500, 500, CV_8UC(3), cv::Scalar(255, 255, 255))); for (size_t i = 0; i < clusters_.size(); i++) { RNG rng(clusters_.size() - i); Vec3b color(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));//random color if (FLAG_hasLines_) { for (size_t j = 0; j < clusters_[i].size() - 1; j++) { line(image_, clusters_[i][j], clusters_[i][j + 1], color + Vec3b(rng.uniform(50, 100), rng.uniform(50, 100), rng.uniform(50, 100))); } } if (FLAG_hasIcon_) { //draw cluster icon if (FLAG_fastCompute_) //icon on last point of cluster circle(image_, clusters_[i][0], radius_ + clusters_[i].size() / 2, color - Vec3b(rng.uniform(0, 100), rng.uniform(0, 100), rng.uniform(0, 100))); else //icon on cluster center circle(image_, clustersCentres_[i], radius_ + clusters_[i].size() / 2, color - Vec3b(rng.uniform(0, 100), rng.uniform(0, 100), rng.uniform(0, 100))); } if (FLAG_hasPoints_) { //draw points for (auto point : clusters_[i]) { image_.at<Vec3b>(point) = color; } } if (FLAG_hasText_) { //draw count points in cluster if (FLAG_fastCompute_) { putText(image_, to_string(clusters_[i].size()), //count points in cluster clusters_[i][0], //text on last point cluster FONT_HERSHEY_DUPLEX, (textScale_ / 10.0), color - Vec3b(rng.uniform(50, 100), rng.uniform(50, 100), rng.uniform(50, 100)), 0); } else { putText(image_, to_string(clusters_[i].size()), //count points in cluster clustersCentres_[i], //text on cluster center FONT_HERSHEY_DUPLEX, (textScale_ / 10.0), color - Vec3b(rng.uniform(50, 100), rng.uniform(50, 100), rng.uniform(50, 100)), 0); } } } //display after update if (FLAG_canDisplay_) { imshow("Display window", image_); // Show our image inside it. displayStatusBar("Display window", "Clusters: " + to_string(clusters_.size()), 2000); //display count clusters into status bar } } void Clusterize::draw(bool display) { FLAG_canDisplay_ = display; draw(); if (display) { namedWindow("Display window", CV_GUI_NORMAL); // Create a window for display. setMouseCallback("Display window", _myMouseCallback, this); createTrackbar("Radius", "Display window", &radius_, image_.cols / 2, _radiusCallback, this); //set MAX value for radius //image_.width()/2 default //tools panel createTrackbar("Font size", "", &textScale_, 40, _fontCallback, this); //set MAX value for font scale // 40 default createButton("Clear", _clearCallback, this, QT_PUSH_BUTTON); createButton("Points", _pointsCallback, this, QT_CHECKBOX, FLAG_hasPoints_); createButton("Text", _textCallback, this, QT_CHECKBOX, FLAG_hasText_); createButton("Clusters", _iconsCallback, this, CV_CHECKBOX, FLAG_hasIcon_); createButton("Lines", _linesCallback, this, CV_CHECKBOX, FLAG_hasLines_); createButton("Merging clusters", _mergeCallback, this, CV_CHECKBOX, FLAG_hasMerge_); createButton("Fast compute", _fastCallback, this, QT_CHECKBOX, FLAG_fastCompute_); while (getWindowProperty("Display window", WND_PROP_VISIBLE)) { int key = waitKey(1000); // Wait for a keystroke in the window if (key == 27) break; } destroyWindow("Display window"); } } void Clusterize::save() { if (!boost::filesystem::is_directory(saveDir_)) //create new dir if current dir not found boost::filesystem::create_directory(saveDir_); if (nameImg_.empty())//set data\time to image name { string temp_name = saveDir_.string() + "Cluster_" + boost::posix_time::to_iso_string( boost::posix_time::second_clock::local_time()) + ".jpg"; if (cv::imwrite(temp_name, image_)) cout << "Image saved: " << temp_name << endl; else cout << "Save error" << endl; } else if (cv::imwrite(saveDir_.string() + nameImg_.string(), image_)) cout << "Image saved: " << saveDir_.string() + nameImg_.string() << endl; else cout << "Save error" << endl; } bool Clusterize::_is_jpg(string filename) { return boost::algorithm::iends_with(filename, ".jpg") || boost::algorithm::iends_with(filename, ".jpeg"); } void Clusterize::_myMouseCallback(int event, int x, int y, int flags, void* param) { Clusterize* cl = (Clusterize*)param; switch (flags + event) { case CV_EVENT_MOUSEMOVE: break; case 10: //ctrl + LButtonDown || MButtonFlag + MButtonUP if (cl->FLAG_hasMerge_) { cl->addPoint(x, y); cl->reCombine(); } else { cl->identifyPoint(x, y); } cl->draw(); return; break; case CV_EVENT_MBUTTONDOWN: /* cl->deletePoint(x,y); cl->draw(); break; TODO:add delete point function */ case CV_EVENT_LBUTTONUP: break; } } void Clusterize::_radiusCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->reCombine(); cl->draw(); } void Clusterize::_clearCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->clearClusters(); cl->clearPoint(); cl->draw(); } void Clusterize::_pointsCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->FLAG_hasPoints_ = pos; cl->draw(); } void Clusterize::_textCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->FLAG_hasText_ = pos; cl->draw(); } void Clusterize::_fontCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->draw(); } void Clusterize::_iconsCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->FLAG_hasIcon_ = pos; cl->draw(); } void Clusterize::_linesCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->FLAG_hasLines_ = pos; cl->draw(); } void Clusterize::_mergeCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->FLAG_hasMerge_ = pos; cl->reCombine(); cl->draw(); } void Clusterize::_fastCallback(int pos, void* param) { Clusterize* cl = (Clusterize*)param; cl->FLAG_fastCompute_ = pos; cl->reCombine(); cl->draw(); }
f59273d70c6108c0677b7d8b29ee8d9f99e87491
[ "Markdown", "CMake", "C++" ]
11
C++
AntKerf/Tasks
451f33e98d4ed236dfb86a637f8a430aaf0ea7b9
2777f8a71c2c05d16a859f9d085479db64524a58
refs/heads/master
<file_sep>from Tkinter import * from tkMessageBox import * root=Tk() root.config(bg='pink') root.title('Hotel management -Food world') global a1 global a2 global a3 global a4 global a5 global a6 a1=0 a2=0 a3=0 a4=0 a5=0 a6=0 Label(root,text="Hotel Managment",font="times 30 bold",bg="pink",height=1,width=20).grid(row=0,column=0,columnspan=6) p=PhotoImage(file="nwewel.gif") l=Label(root,image=p).grid(row=1,column=1,rowspan=2,columnspan=4) Label(root,text="Submitted By :-",font="times 15 bold underline",bg="pink",fg="red").grid(row=8,column=0,sticky='W') Label(root,text="Name :-",font="times 15 bold",bg="pink",fg="blue").grid(row=9,column=0,sticky='W') Label(root,text="<NAME> ",font="times 15 bold",bg="pink",fg="blue").grid(row=9,column=5,sticky='W') Label(root,text="Branch :-",font="times 15 bold",bg="pink",fg="blue").grid(row=10,column=0,sticky='W') Label(root,text="C.S.E",font="times 15 bold",bg="pink",fg="blue").grid(row=10,column=5,sticky='W') Label(root,text="Enr.Number :-",font="times 15 bold",fg="blue",bg="pink").grid(row=11,column=0,sticky='W') Label(root,text="161B168 ",font="times 15 bold",bg="pink",fg="blue").grid(row=11,column=5,sticky='W') Label(root,text="Submitted To :-",font="times 15 bold underline",bg="pink",fg="red").grid(row=12,column=5) Label(root,text="Dr.<NAME> ",font="times 15 bold",bg="pink",fg="blue").grid(row=13,column=5,sticky='E') def fun1(): window=Toplevel() window.title('Hotel Management') window.config(bg="pink") Label(window,text="Welcome in K.K Plaza",font="times 25 italic bold",bd=10,bg="pink",height=1,width=15).grid(row=0,column=1,columnspan=4) p=PhotoImage(file="new.gif") l=Label(window,image=p).grid(row=1,column=1,rowspan=4,columnspan=4) Label(window,text="Food world",font="times 15 italic bold",fg="blue",height=1,width=15).grid(row=4,column=2,columnspan=2) def fun(): x=askyesnocancel('order','Do you want eat anything') print x if x==True: Label(window,text="Click below for the Menu card ",font="times 20 italic bold",bg="pink").grid(row=6,column=1,columnspan=4) def fun2(): Label(window,text="We Have For You",font="times 20 bold italic",bg="orange",fg="blue",height=1,width=15).grid(row=8,column=1,columnspan=4) def fun3(): hot=Toplevel() hot.title('HOT SOUPS') hot.config(bg='violet') Label(hot,text="HOT SOUPS AVAILABLE ARE ",font="times 25 bold italic",bg="green",height=1,width=25).grid(row=0,column=1,columnspan=6) Label(hot,text="Items",font="times 20 bold italic",bg="red").grid(row=1,column=0,columnspan=2) Label(hot,text="Price",font="times 20 bold italic",bg="red").grid(row=1,column=5,columnspan=4) v1=IntVar() v2=IntVar() v3=IntVar() v4=IntVar() v5=IntVar() v6=IntVar() Checkbutton(hot,text=' Cream Of Tomato Soup',variable=v1,onvalue='50',bg='violet').grid(row=4,column=1,columnspan=4,sticky='W') Label(hot,text="50",font="times 20 bold italic",bg='violet').grid(row=4,column=5,columnspan=4) Checkbutton(hot,text=' Russian Broth Soup',variable=v2,onvalue='100',bg='violet').grid(row=6,column=1,columnspan=4,sticky='W') Label(hot,text="100",font="times 20 bold italic",bg='violet').grid(row=6,column=5,columnspan=4) Checkbutton(hot,text=' Hot & Sour Veg. & Non Veg',variable=v3,onvalue='75',bg='violet').grid(row=8,column=1,columnspan=4,sticky='W') Label(hot,text="75",font="times 20 bold italic",bg='violet').grid(row=8,column=5,columnspan=4) Checkbutton(hot,text=' Clear Soup Veg. & Non Veg ',variable=v4,onvalue='80',bg='violet').grid(row=9,column=1,columnspan=4,sticky='W') Label(hot,text="80",font="times 20 bold italic",bg='violet').grid(row=9,column=5,columnspan=4) Checkbutton(hot,text=' Sweet Corn Veg. & Non Veg',variable=v5,onvalue='150',bg='violet').grid(row=10,column=1,columnspan=4,sticky='W') Label(hot,text="150",font="times 20 bold italic",bg='violet').grid(row=10,column=5,columnspan=4) Checkbutton(hot,text=' Man Chow Veg. & Non Veg',variable=v6,onvalue='90',bg='violet').grid(row=12,column=1,columnspan=4,sticky='W') Label(hot,text="90",font="times 20 bold italic",bg='violet').grid(row=12,column=5,columnspan=4) def fun3a(): global a1 a1= v1.get()+v2.get()+v3.get()+ v4.get()+v5.get()+ v6.get() Label(hot,text="Your Total Ammount Rs. "+str (a1),font="times 20 bold italic",bg='violet').grid(row=18,column=0,columnspan=4) Button(hot,text="bill",font="times 20 bold italic",bg='violet',command=fun3a).grid(row=17,column=5,columnspan=4) hot.mainloop() def fun4(): drink=Toplevel() drink.title('BEVERAGES') drink.config(bg='violet') Label(drink,text=" BEVERAGES AVAILABLE ARE ",font="times 25 bold italic",bg="green",height=1,width=25).grid(row=0,column=1,columnspan=6) Label(drink,text="Items",font="times 20 bold italic",bg="red").grid(row=1,column=0,columnspan=2) Label(drink,text="Price",font="times 20 bold italic",bg="red").grid(row=1,column=5,columnspan=4) v7=IntVar() v8=IntVar() v9=IntVar() v10=IntVar() v11=IntVar() Checkbutton(drink,text=' Mineral Water',variable=v7,onvalue='18',bg='violet').grid(row=2,column=1,columnspan=4,sticky='W') Label(drink,text="18",font="times 20 bold italic",bg='violet').grid(row=2,column=5,columnspan=4) Checkbutton(drink,text=' Masala Tea/Coffee',variable=v8,onvalue='30',bg='violet').grid(row=6,column=1,columnspan=4,sticky='W') Label(drink,text="30",font="times 20 bold italic",bg='violet').grid(row=6,column=5,columnspan=4) Checkbutton(drink,text=' Milk Shake ',variable=v9,onvalue='30',bg='violet').grid(row=8,column=1,columnspan=4,sticky='W') Label(drink,text="30",font="times 20 bold italic",bg='violet').grid(row=8,column=5,columnspan=4) Checkbutton(drink,text=' Cold coffee',variable=v10,onvalue='80',bg='violet').grid(row=9,column=1,columnspan=4,sticky='W') Label(drink,text="80",font="times 20 bold italic",bg='violet').grid(row=9,column=5,columnspan=4) Checkbutton(drink,text=' Sweet lassi',variable=v11,onvalue='60',bg='violet').grid(row=12,column=1,columnspan=4,sticky='W') Label(drink,text="60",font="times 20 bold italic",bg='violet').grid(row=12,column=5,columnspan=4) def fun4a(): global a2 a2= v7.get()+v8.get()+v9.get()+ v10.get()+v11.get() Label(drink,text="Your Total Ammount Rs. "+str (a2),font="times 20 bold italic",bg='violet').grid(row=18,column=0,columnspan=4) Button(drink,text="bill",font="times 20 bold italic",bg='violet',command=fun4a).grid(row=17,column=5,columnspan=4) drink.mainloop() def fun5(): snacks=Toplevel() snacks.title('SNACKS') snacks.config(bg='violet') Label(snacks,text=" SNACKS AVAILABLE ARE ",font="times 25 bold italic",bg="green",height=1,width=25).grid(row=0,column=1,columnspan=6) Label(snacks,text="Items",font="times 20 bold italic",bg="red").grid(row=1,column=0,columnspan=2) Label(snacks,text="Price",font="times 20 bold italic",bg="red").grid(row=1,column=5,columnspan=4) v12=IntVar() v13=IntVar() v14=IntVar() v15=IntVar() Checkbutton(snacks,text=' Aloo Chana Chaat',variable=v12,onvalue='150',bg='violet').grid(row=4,column=1,columnspan=4,sticky='W') Label(snacks,text="150",font="times 20 bold italic",bg='violet').grid(row=4,column=5,columnspan=4) Checkbutton(snacks,text=' Paneer Pakora',variable=v13,onvalue='60',bg='violet').grid(row=5,column=1,columnspan=4,sticky='W') Label(snacks,text="60(2 pcs)",font="times 20 bold italic",bg='violet').grid(row=5,column=5,columnspan=4) Checkbutton(snacks,text=' French Fries',variable=v14,onvalue='90',bg='violet').grid(row=6,column=1,columnspan=4,sticky='W') Label(snacks,text="90",font="times 20 bold italic",bg='violet').grid(row=6,column=5,columnspan=4) Checkbutton(snacks,text=' Pizza ',variable=v15,onvalue='250',bg='violet').grid(row=7,column=1,columnspan=4,sticky='W') Label(snacks,text="250",font="times 20 bold italic",bg='violet').grid(row=7,column=5,columnspan=4) def fun5a(): global a3 a3= v12.get()+v13.get()+v14.get()+ v15.get() Label(snacks,text="Your Total Ammount Rs. "+str (a3),font="times 20 bold italic",bg='violet').grid(row=18,column=0,columnspan=4) Button(snacks,text="bill",font="times 20 bold italic",bg='violet',command=fun5a).grid(row=17,column=5,columnspan=4) snacks.mainloop() def fun6(): nonveg=Toplevel() nonveg.title('nonveg') nonveg.config(bg='violet') Label(nonveg,text=" NONVEG'S AVAILABLE ARE",font="times 25 bold italic",bg="green",height=1,width=25).grid(row=0,column=1,columnspan=6) Label(nonveg,text="Items",font="times 20 bold italic",bg="red").grid(row=1,column=0,columnspan=2) Label(nonveg,text="Price",font="times 20 bold italic",bg="red").grid(row=1,column=5,columnspan=4) v16=IntVar() v17=IntVar() v18=IntVar() v19=IntVar() v20=IntVar() Checkbutton(nonveg,text='Chilly Chicken Gravy',variable=v16,onvalue='200',bg='violet').grid(row=2,column=1,columnspan=4,sticky='W') Label(nonveg,text="200",font="times 20 bold italic",bg='violet').grid(row=2,column=5,columnspan=4) Checkbutton(nonveg,text='Hong Kong Chicken',variable=v17,onvalue='250',bg='violet').grid(row=3,column=1,columnspan=4,sticky='W') Label(nonveg,text="250",font="times 20 bold italic",bg='violet').grid(row=3,column=5,columnspan=4) Checkbutton(nonveg,text='Chilly Fish Curry',variable=18,onvalue='180',bg='violet').grid(row=5,column=1,columnspan=4,sticky='W') Label(nonveg,text="180",font="times 20 bold italic",bg='violet').grid(row=5,column=5,columnspan=4) Checkbutton(nonveg,text='Chicken Manchurian',variable=v19,onvalue='150',bg='violet').grid(row=8,column=1,columnspan=4,sticky='W') Label(nonveg,text="150",font="times 20 bold italic",bg='violet').grid(row=8,column=5,columnspan=4) Checkbutton(nonveg,text='Roasted Chicken',variable=v20,onvalue='160',bg='violet').grid(row=6,column=1,columnspan=4,sticky='W') Label(nonveg,text="160",font="times 20 bold italic",bg='violet').grid(row=6,column=5,columnspan=4) def fun6a(): global a4 a4= v16.get()+v17.get()+v18.get()+ v19.get()+v20.get() Label(nonveg,text="Your Total Ammount Rs. "+str (a4),font="times 20 bold italic",bg='violet').grid(row=18,column=0,columnspan=5) Button(nonveg,text="bill",font="times 20 bold italic",bg='violet',command=fun6a).grid(row=17,column=5,columnspan=4) def fun7(): veg=Toplevel() veg.title('veg') veg.config(bg='violet') Label(veg,text="VEG'S AVAILABLE ARE",font="times 25 bold italic",bg="green",height=1,width=25).grid(row=0,column=1,columnspan=6) Label(veg,text="Items",font="times 20 bold italic",bg="red").grid(row=1,column=0,columnspan=2) Label(veg,text="Price",font="times 20 bold italic",bg="red").grid(row=1,column=5,columnspan=4) v21=IntVar() v22=IntVar() v23=IntVar() v24=IntVar() v25=IntVar() Checkbutton(veg,text='<NAME>',variable=v21,onvalue='160',bg='violet').grid(row=2,column=1,columnspan=4,sticky='W') Label(veg,text="160",font="times 20 bold italic",bg='violet').grid(row=2,column=5,columnspan=4) Checkbutton(veg,text='<NAME>',variable=v22,onvalue='190',bg='violet').grid(row=3,column=1,columnspan=4,sticky='W') Label(veg,text="190",font="times 20 bold italic",bg='violet').grid(row=3,column=5,columnspan=4) Checkbutton(veg,text='<NAME>',variable=23,onvalue='180',bg='violet').grid(row=5,column=1,columnspan=4,sticky='W') Label(veg,text="180",font="times 20 bold italic",bg='violet').grid(row=5,column=5,columnspan=4) Checkbutton(veg,text='Paneer Do Pyaza',variable=v24,onvalue='150',bg='violet').grid(row=8,column=1,columnspan=4,sticky='W') Label(veg,text="150",font="times 20 bold italic",bg='violet').grid(row=8,column=5,columnspan=4) Checkbutton(veg,text='Chhola sabji',variable=v25,onvalue='160',bg='violet').grid(row=6,column=1,columnspan=4,sticky='W') Label(veg,text="160",font="times 20 bold italic",bg='violet').grid(row=6,column=5,columnspan=4) def fun7a(): global a5 a5= v21.get()+v22.get()+v23.get()+ v24.get()+v25.get() Label(veg,text="Your Total Ammount Rs. "+str (a5),font="times 20 bold italic",bg='violet').grid(row=18,column=0,columnspan=4) Button(veg,text="bill",font="times 20 bold italic",bg='violet',command=fun7a).grid(row=17,column=5,columnspan=4) def fun8(): chapati=Toplevel() chapati.title('chapati') chapati.config(bg='violet') Label(chapati,text=" CHAPATI'S AVAILABLE ARE",font="times 25 bold italic",bg="green",height=1,width=25).grid(row=0,column=1,columnspan=6) Label(chapati,text="Items",font="times 20 bold italic",bg="red").grid(row=1,column=0,columnspan=2) Label(chapati,text="Price",font="times 20 bold italic",bg="red").grid(row=1,column=5,columnspan=4) v26=IntVar() v27=IntVar() v28=IntVar() Checkbutton(chapati,text='Plane Roti(10)',variable=v26,onvalue='8',bg='violet').grid(row=2,column=1,columnspan=4,sticky='W') Label(chapati,text="60",font="times 20 bold italic",bg='violet').grid(row=2,column=5,columnspan=4) Checkbutton(chapati,text='Rumali Roti(5)',variable=v27,onvalue='50',bg='violet').grid(row=5,column=1,columnspan=4,sticky='W') Label(chapati,text="50",font="times 20 bold italic",bg='violet').grid(row=5,column=5,columnspan=4) Checkbutton(chapati,text='Butter Roti(5)',variable=v28,onvalue='12',bg='violet').grid(row=7,column=1,columnspan=4,sticky='W') Label(chapati,text="60",font="times 20 bold italic",bg='violet').grid(row=7,column=5,columnspan=4) def fun8a(): global a6 a6= v26.get()+v27.get()+v28.get() Label(chapati,text="Your Total Ammount Rs. "+str (a6),font="times 20 bold italic",bg='violet').grid(row=18,column=0,columnspan=4) Button(chapati,text="bill",font="times 20 bold italic",bg='violet',command=fun8a).grid(row=17,column=5,columnspan=4) def fun9(): bill=Toplevel() bill.title('Bill') bill.config(bg='violet') global a1 global a2 global a3 global a4 global a5 global a6 a=a1+a2+a3+a4+a5+a6 Label(bill,text="Your Bill ",font ="times 20 bold italic underline",bg='violet').grid(row=0,column=1,columnspan=4) Label(bill,text="Your Total Ammount Rs. "+str (a),font="times 20 bold italic",bg='violet').grid(row=1,column=1,columnspan=4) p=PhotoImage(file="thanku.gif") l=Label(bill,image=p).grid(row=4,column=2,rowspan=2,columnspan=2) a=Label(bill,text="Thanks for Visiting Here... ",bg="violet",font="times 20 bold italic",height=2,width=25,) a.grid(row=8,column=1,columnspan=4) Button(window,text="HOT SOUPS",font="times 15 bold italic" ,command=fun3,bg="violet").grid(row=10,column=1,columnspan=2,sticky='W') Button(window,text="BEVERAGES",font="times 15 bold italic" ,command=fun4,bg="violet").grid(row=10,column=3,columnspan=2,sticky='W') Button(window,text="SNACKS",font="times 15 bold italic",command=fun5,bg="violet" ).grid(row=16,column=1,columnspan=2,sticky='W') Button(window,text="NON VEG's",font="times 15 bold italic",command=fun6 ,bg="violet").grid(row=13,column=3,columnspan=2,sticky='W') Button(window,text="VEG'S",font="times 15 bold italic",command=fun7,bg="violet" ).grid(row=13,column=1,columnspan=2,sticky='W') Button(window,text="CHAPATI",font="times 15 bold italic",command=fun8,bg="violet" ).grid(row=16,column=3,columnspan=2,sticky='W') Button(window,text="BILL",font="times 15 bold italic",command=fun9 ).grid(row=20,column=2,columnspan=2,sticky='W') Button(window,text="Menu Card",font="times 20 bold",command=fun2).grid(row=7,column=1,columnspan=4) if x==False: y=askyesno('order','Do you want to drink') print y if y==True: Label(window,text="What u want drink",font="times 25 bold italic",bg="green").grid(row=6,column=1,columnspan=4) Label(window,text="Items",font="times 20 bold italic",bg="red").grid(row=8,column=1,sticky='W') Label(window,text="Price",font="times 20 bold italic",bg="red").grid(row=8,column=4) v1=IntVar() v2=IntVar() v3=IntVar() v4=IntVar() v5=IntVar() Checkbutton(window,text='Coffe',variable=v1,onvalue='50',bg='pink').grid(row=9,column=1,sticky='W') Label(window,text="50",font="times 20 bold italic",bg='pink').grid(row=9,column=4) Checkbutton(window,text=' Cold Coffe',variable=v2,onvalue='100',bg='pink').grid(row=10,column=1,sticky='W') Label(window,text="100",font="times 20 bold italic",bg='pink').grid(row=10,column=4) Checkbutton(window,text=' Tea',variable=v3,onvalue='25',bg='pink').grid(row=11,column=1,sticky='W') Label(window,text="25",font="times 20 bold italic",bg='pink').grid(row=11,column=4) Checkbutton(window,text=' Soup',variable=v4,onvalue='80',bg='pink').grid(row=12,column=1,sticky='W') Label(window,text="80",font="times 20 bold italic",bg='pink').grid(row=12,column=4) Checkbutton(window,text='Water ',variable=v5,onvalue='20',bg='pink').grid(row=14,column=1,sticky='W') Label(window,text="20",font="times 20 bold italic",bg='pink').grid(row=14,column=4) def sum(): a7=v1.get()+v2.get()+v3.get()+v4.get()+v5.get() Label(window,text="Yours Total Ammount Rs. " +str (a),font="times 20 bold italic",bg='violet').grid(row=20,column=0,columnspan=5) a=Label(window,text="Thanks for Visiting Here... ",bg="pink",font="times 20 bold italic",height=2,width=25,) a.grid(row=21,column=1,columnspan=4) Button(window,text="BILL",font="times 15 bold",fg="blue",command=sum ).grid(row=18,column=2,columnspan=2) if y==False: a=Label(window,text="Give a Chance to surve you\n Thanks for Visiting Here... ",bg="pink",font="times 20 bold italic",height=2,width=25,) a.grid(row=7,column=1,columnspan=4) if x==None: a=Label(window,text="Give a Chance to surve you\n Thanks for Visiting Here... ",font="times 20 bold italic",height=2,width=25,bg='pink') a.grid(row=7,column=1,columnspan=4) Button(window,text="Click Here...",command=fun,height=1,width=15).grid(row=5,column=2,columnspan=2) window.mainloop() Button(root,text="Proceed To Project..",fg="blue",font="20",command=fun1).grid(row=20,column=2,columnspan=3) root.mainloop() <file_sep># python- python GUI drop down menu for Hotel managment
f0bb81607c967ffa672109e7d503d939df894e5a
[ "Markdown", "Python" ]
2
Python
ratneshkumarrajak/python-hotel-management-dropdown-menu
c34a5f49a249f4f0df2ff0a38ce16df421102d42
7838ac77b0f2c1648422b56241142146769a4155
refs/heads/master
<file_sep>// 对axios进行处理 import axios from 'axios' // 引入路由实例对象 import router from '../router' // 引入elementui的提示 import { Message } from 'element-ui' // 引入第三方包,处理安全整数 import JSONBig from 'json-bigint' // 请求拦截,统一注入token axios.interceptors.request.use(function (config) { let token = window.localStorage.getItem('user-token') config.headers['Authorization'] = `Bearer ${token}` return config }, function () { // 执行请求失败 }) // 后台数据 到达 响应拦截之前走的一个函数 axios.defaults.transformResponse = [function (data) { return data ? JSONBig.parse(data) : data // JSONbig.parse 替换 JSON.parse 保证数字的正确 }] // 响应式拦截 axios.interceptors.response.use(function (response) { // 解决当data不存在时,报错的情况 return response.data ? response.data : {} }, function (error) { // 执行请求失败 let status = error.response.status // 获取失败的状态码 let message = '未知错误' switch (status) { case 400: message = '输入信息有误!' break case 403: message = '403 refresh_token未携带或已过期' break case 507: message = '服务器数据库异常' break case 401: message = 'token过期或未出' window.localStorage.clear() // 清空缓存 router.push('/login') // this.$router.push() break case 404: message = '手机号不正确' break default: break } Message({ message }) // 不再进入catch 终止错误 return new Promise(function () {}) // 终止当前的错误 }) export default axios <file_sep>// 统一管理组件 import LayoutAside from './home/layout-aside' import LayoutHeader from './home/layout-header' import Bread from './common/bread' import { quillEditor } from 'vue-quill-editor' import CoverImage from './publish/cover-image' import SelectImage from './publish/select-image' import 'quill/dist/quill.core.css' import 'quill/dist/quill.snow.css' import 'quill/dist/quill.bubble.css' export default { install (Vue) { Vue.component('layout-aside', LayoutAside) Vue.component('layout-header', LayoutHeader) Vue.component('bread-crumb', Bread) Vue.component('quill-editor', quillEditor) // 全局注册富文本编辑器 Vue.component('cover-image', CoverImage) // 注册一个封面组件 Vue.component('select-image', SelectImage) // 注册一个封面组件 } }
b0a0d44f59781f0bc13a2cbae0bedee04b140a50
[ "JavaScript" ]
2
JavaScript
0jinyingjie0/89heimatoutiao
7476e506fc86caa47236de8c4e559947c5671211
bbb0937a13f26181227ca6837808bc75d714a617
refs/heads/master
<file_sep>var fs = require("fs"); var formidable = require("formidable"); var path = require('path'); var md5 = require('MD5'); var dataFormat = require('dataformat'); var bodyParser = require('body-parser'); var config = require('../config'); var images = require("images"); //上传图片 var upload = function(req,res) { console.log(req.body.textureMD5); fs.readFile(req.files.file.path, function(err, data) { var textureMD5 = req.body.textureMD5; var serverid = req.body.serverid; var playerid=req.body.playerid; var index = req.body.index; if(!err && textureMD5==md5(data)) { if(serverid && playerid) { var first = serverid; var second=Math.floor(parseInt(playerid) / config.field_max); var third = Math.floor(parseInt(playerid) % config.field_max / config.field_min); var tmp_path=req.files.file.path; console.log('save md5=='+textureMD5); var save_folder = config.upload_real + "/" +first.toString()+ "/"+second.toString() + "/" + third.toString(); var save_path = save_folder+"/"+serverid.toString()+"_"+playerid.toString()+"_"+index.toString()+".jpg"; var json_path = save_folder + "/" + serverid.toString() + "_" + playerid.toString() + ".json"; console.log("save_path=" + save_path); if(mkdirsSync(save_folder,0777)) { fs.rename(tmp_path, save_path, function(err) { if (err) { saveResult(res, 'false'); console.log("upload photon err=" + err); } else { saveJson(index,textureMD5,json_path); saveResult(res,'true'); } }); } else saveResult(res,'false'); } else saveResult(res,'false'); } else saveResult(res,'false'); }); }; var setHeadIcons=function(req,res)//设置小头像 { var first = req.body.serverid; var second=Math.floor(parseInt(req.body.playerid) / config.field_max); var third = Math.floor(parseInt(req.body.playerid) % config.field_max / config.field_min); console.log("setHeadIcons"); var save_folder = config.upload_real + "/" +first.toString()+ "/"+second.toString() + "/" + third.toString(); var bigTexture_path = save_folder+"/"+ req.body.serverid.toString()+"_"+req.body.playerid.toString()+"_"+req.body.index+".jpg"; var save_path = save_folder+"/"+ req.body.serverid.toString()+"_"+req.body.playerid.toString()+"_headicon.jpg"; var json_path = save_folder+"/"+ req.body.serverid.toString()+"_"+req.body.playerid.toString()+".json"; fs.exists(bigTexture_path,function(exists)//大图存在 { if(exists) { console.log("exists"+save_path); images(bigTexture_path).size(config.headicon_size,config.headicon_size).save(save_path,{quality : 70}); images.gc(); fs.readFile(save_path, function(err, buf) { fs.exists(json_path,function(exists)//保存json { if(exists) { fs.readFile(json_path,'utf8',function(err,data) { if(!err) { var result=JSON.parse(data); result.headicon=md5(buf); result.headiconindex=req.body.index; var final=JSON.stringify(result); console.log(final); fs.writeFile(json_path,final,function(err) { saveResult(res,'true'); }) } }) } else { console.log("json not exists!!!!="+json_path); saveResult(res,'false'); } }); }); } else { console.log("json not exists!!!!="+json_path); saveResult(res,'false'); } }); } var deletePhoto=function(req,res) { var serverid = req.body.serverid; var playerid=req.body.playerid; var index = req.body.index; if(serverid && playerid && index) { var first = serverid; var second=Math.floor(parseInt(playerid) / config.field_max); var third = Math.floor(parseInt(playerid) % config.field_max / config.field_min); var save_folder = config.upload_real + "/" +first.toString()+ "/"+second.toString() + "/" + third.toString(); var save_path = save_folder+"/"+serverid.toString()+"_"+playerid.toString()+"_"+index.toString()+".jpg"; var json_path = save_folder+"/"+ serverid.toString()+"_"+playerid.toString()+".json"; fs.unlink(save_path, function(err) { if(err) console.log(err.toString()); }); saveJson(index,'0',json_path); saveResult(res,'true'); } } function saveJson(index,value,filepath) { fs.exists(filepath,function(exists) { if(exists)//存在,写入 { fs.readFile(filepath,'utf8',function(err,data){ if(err) console.log("false"); else { var result=JSON.parse(data); if(index>result.data.length) { for(i=result.data.length;i<index;i++) { result.data[i]='0'; } } result.data[index-1]=value; if( result.headicon==index && value=='0') result.headicon='0'; var final=JSON.stringify(result); fs.writeFile(filepath,final,function(err){ if(err) console.log('---'); else console.log('------'); }) } }); } else //不存在,创建 { var array=new Array(); for(i=0;i<config.photo_max;i++) { if(i+1==index) array[i]=value; else array[i]='0'; } var jsondata = {data:array,headicon:0}; var final = JSON.stringify(jsondata); fs.writeFile(filepath, final,function(err){ if(err) console.log('写文件操作失败'); else console.log('写文件操作成功'); }); } }); } var downloadPhoto = function(req,res) { var serverid = req.body.serverid; var playerid=req.body.playerid; var index = req.body.index; if(index==10086) { console.log('10086'); } var textureMD5 = req.body.textureMD5; if(serverid && playerid && index) { var first = serverid; var second=Math.floor(parseInt(playerid) / config.field_max); var third = Math.floor(parseInt(playerid) % config.field_max / config.field_min); var save_folder = config.upload_real + "/" +first.toString()+ "/"+second.toString() + "/" + third.toString(); var save_path = save_folder+"/"+serverid.toString()+"_"+playerid.toString()+"_"+index.toString()+".jpg"; fs.exists(save_path,function(exists) { if(exists) { fs.readFile(save_path,function(err,data) { console.log('download md5 ='+md5(data)); if(textureMD5 &&md5(data) == textureMD5) { saveResult(res,"same"); } else { res.setHeader("Content-Type", "image/jpg"); res.writeHead(200, "Ok"); res.write(data,"binary"); //格式必须为 binary,否则会出错 res.end(); } }); } else saveResult(res,'false'); }); } } var downloadBigHeadPhoto = function(req,res)//下载头像对应的大图 { var serverid = req.body.serverid; var playerid=req.body.playerid; //var index; var first = serverid; var second=Math.floor(parseInt(playerid) / config.field_max); var third = Math.floor(parseInt(playerid) % config.field_max / config.field_min); var save_folder = config.upload_real + "/" +first.toString()+ "/"+second.toString() + "/" + third.toString(); var json_path = save_folder+"/"+ serverid.toString()+"_"+playerid.toString()+".json"; //index=config.headicon_index; if(mkdirsSync(save_folder,0777)) { fs.exists(json_path,function(exists) { if(exists)//存在,写入 { fs.readFile(json_path,'utf8',function(err,data) { if(err) { console.log("false"); saveResult(res,'false'); } else { var jsonData = JSON.parse(data); var index = jsonData.headiconindex; if(serverid && playerid) { var save_path = save_folder+"/"+serverid.toString()+"_"+playerid.toString()+"_"+index+".jpg"; fs.exists(save_path,function(exists) { if(exists) { fs.readFile(save_path,function(err,data) { res.setHeader("Content-Type", "image/jpg"); res.writeHead(200, "Ok"); res.write(data,"binary"); //格式必须为 binary,否则会出错 console.log("下载头像成功"); res.end(); }); } else { saveResult(res,'false'); } }); } } }); } else //不存在,返回false { saveResult(res,'false'); } }); } } var downloadHeadPhoto = function(req,res) { var serverid = req.body.serverid; var playerid=req.body.playerid; //var index; var first = serverid; var second=Math.floor(parseInt(playerid) / config.field_max); var third = Math.floor(parseInt(playerid) % config.field_max / config.field_min); var save_folder = config.upload_real + "/" +first.toString()+ "/"+second.toString() + "/" + third.toString(); var json_path = save_folder+"/"+ serverid.toString()+"_"+playerid.toString()+".json"; //index=config.headicon_index; if(serverid && playerid) { var save_path = save_folder+"/"+serverid.toString()+"_"+playerid.toString()+"_headicon.jpg"; fs.exists(save_path,function(exists) { if(exists) { fs.readFile(save_path,function(err,data) { res.setHeader("Content-Type", "image/jpg"); res.writeHead(200, "Ok"); res.write(data,"binary"); //格式必须为 binary,否则会出错 console.log("下载头像成功"); res.end(); }); } else { saveResult(res,'false'); } }); } } var downloadJson=function(req,res) { var serverid = req.body.serverid; var playerid=req.body.playerid; var finalJson; if(serverid && playerid) { var first = serverid; var second=Math.floor(parseInt(playerid) / config.field_max); var third = Math.floor(parseInt(playerid) % config.field_max / config.field_min); var save_folder = config.upload_real + "/" +first.toString()+ "/"+second.toString() + "/" + third.toString(); var json_path = save_folder+"/"+ serverid.toString()+"_"+playerid.toString()+".json"; console.log(json_path); if(mkdirsSync(save_folder,0777)) { fs.exists(json_path,function(exists) { if(exists)//存在,写入 { fs.readFile(json_path,'utf8',function(err,data) { if(err) console.log("false"); else { var jsonData = JSON.parse(data); jsonData.photomax=config.photo_max; var final=JSON.stringify(jsonData); saveResult(res,final); } }); } else //不存在,创建 { console.log("创建json,playerid="+playerid); var array=new Array(); for(i=0;i<config.photo_max;i++) { array[i]='0'; } var jsondata = {data:array,headicon:0,photomax:config.photo_max}; finalJson = JSON.stringify(jsondata); //fs.writeFile(json_path, finalJson,function(err) //{ // if(err) // console.log('写文件操作失败'); // else // console.log('写文件操作成功'); //}); console.log("creat json = "+finalJson); saveResult(res,finalJson); } }); } } } function saveResult(res,data) { res.writeHead(200); res.write(data); res.end(); } //创建多层文件夹 同步 function mkdirsSync(dirname, mode) { if(fs.existsSync(dirname)) { return true; } else { if(mkdirsSync(path.dirname(dirname), mode)) { fs.mkdirSync(dirname, mode); return true; } } } //上传舞团团徽 var uploaddancegrouptexture = function(req,res) { fs.readFile(req.files.file.path, function(err, data) { var serverid = req.body.serverid; var groupid=req.body.groupid; if(!err) { if(serverid && groupid) { var first = serverid; var second=Math.floor(parseInt(groupid) / config.field_max); var third = Math.floor(parseInt(groupid) % config.field_max / config.field_min); var tmp_path=req.files.file.path; //console.log('save md5=='+textureMD5); var save_folder = config.upload_groupimagepath + "/" + first.toString() + "/" + second.toString() + "/" + third.toString(); var save_path = save_folder+"/"+serverid.toString()+"_"+groupid.toString()+".jpg"; //var json_path = save_folder+"/"+ serverid.toString()+"_"+groupid.toString()+".json"; if(mkdirsSync(save_folder,0777)) { fs.rename(tmp_path, save_path, function(err) { if (err) { saveResult(res,'false'); console.log("upload photon err"); } else { saveResult(res,'true'); } }); } else saveResult(res,'false'); } else saveResult(res,'false'); } else saveResult(res,'false'); }); }; //下载舞团团徽 var downloaddancegrouptexture = function(req,res) { var serverid = req.body.serverid; var groupid=req.body.groupid; var first = serverid; var second=Math.floor(parseInt(groupid) / config.field_max); var third = Math.floor(parseInt(groupid) % config.field_max / config.field_min); var save_folder = config.upload_groupimagepath + "/" + first.toString() + "/" + second.toString() + "/" + third.toString(); if(serverid && groupid) { var save_path = save_folder+"/"+serverid.toString()+"_"+groupid.toString()+".jpg"; fs.exists(save_path,function(exists) { if(exists) { fs.readFile(save_path,function(err,data) { res.setHeader("Content-Type", "image/jpg"); res.writeHead(200, "Ok"); res.write(data,"binary"); //格式必须为 binary,否则会出错 console.log("下载舞团团徽成功"); res.end(); }); } else { saveResult(res,'false'); } }); } }; //删除舞团团徽 var deleteloaddancegrouptexture = function(req,res) { var serverid = req.body.serverid; var groupid = req.body.groupid; if (serverid && groupid) { var first = serverid; var second = Math.floor(parseInt(groupid) / config.field_max); var third = Math.floor(parseInt(groupid) % config.field_max / config.field_min); var save_folder = config.upload_groupimagepath + "/" + first.toString() + "/" + second.toString() + "/" + third.toString(); var save_path = save_folder + "/" + serverid.toString() + "_" + groupid.toString() +".jpg"; fs.unlink(save_path, function (err) { if (err) console.log(err.toString()); }); saveResult(res, 'true'); } }; exports.upload=upload; exports.setHeadIcon=setHeadIcons; exports.deletePhoto=deletePhoto; exports.downloadPhoto=downloadPhoto; exports.downloadJson=downloadJson; exports.downloadHeadPhoto=downloadHeadPhoto; exports.downloadBigHeadPhoto=downloadBigHeadPhoto; exports.uploaddancegrouptexture=uploaddancegrouptexture; exports.downloaddancegrouptexture=downloaddancegrouptexture; exports.deleteloaddancegrouptexture=deleteloaddancegrouptexture;<file_sep>var fs = require("fs"); var formidable = require("formidable"); var path = require('path'); var md5 = require('MD5'); var dataFormat = require('dataformat'); var bodyParser = require('body-parser'); var config = require('../config'); var images = require("images"); var getnoticecontent = function(req,res) { var reqmd5 = req.body.md5; var save_path = config.upload_notice + "/notice.txt"; console.log(save_path); fs.exists(save_path,function(exists) { if(exists)//存在,读取 { fs.readFile(save_path,'utf8',function(err,data) { if(err) { saveResult(res,"none"); } else { console.log(reqmd5+"----"+md5(data)); if(reqmd5==md5(data)) { saveResult(res,"same"); } else { saveResult(res,data); } } }); } else //不存在,创建 { saveResult(res,"none"); } }); }; var getnoticeimage = function(req,res) { var reqmd5 = req.body.md5; console.log(reqmd5); var save_path = config.upload_notice + "/notice.png"; console.log(save_path); fs.exists(save_path,function(exists) { if(exists)//存在,读取 { fs.exists(save_path,function(exists) { if(exists) { fs.readFile(save_path,function(err,data) { if(reqmd5==md5(data)) { saveResult(res,'same'); } else { res.setHeader("Content-Type", "image/png"); res.writeHead(200, "Ok"); res.write(data,"binary"); //格式必须为 binary,否则会出错 console.log("下载舞团团徽成功"); res.end(); } }); } else { saveResult(res,'none'); } }); } else //不存在,创建 { saveResult(res,"none"); } }); }; function saveResult(res,data) { res.writeHead(200); res.write(data); res.end(); } exports.getnoticecontent=getnoticecontent; exports.getnoticeimage=getnoticeimage;<file_sep>var config = require('./config'); var express = require('express'); var apiRouter=require('./api-router'); var bodyparser=require('body-parser'); var cluster=require('cluster'); var numcpus=require('os').cpus().length; var http = require('http'); var app=express(); app.use(express.static('public')); app.use(bodyparser.urlencoded({ extended: false })); app.use(bodyparser.json()); app.use('/',apiRouter); if(cluster.isMaster) { console.log("master start...."); for(var i=0;i<numcpus;i++){ cluster.fork(); } cluster.on('listening',function(worker,address){ console.log('listening:worker'+worker.process.pid+',port:'+address.port); }); cluster.on('exit',function(worker,address,signal){ console.log('worker'+worker.process.pid +'died'); cluster.fork(); }); } else { var server = app.listen(config.port, function () { var host = server.address().address; var port = server.address().port; console.log('app listening at http://%s:%s', host, port); }); } module.exports = app;<file_sep>var express = require('express'); var imageController = require('./api/image-controller'); var noticeController = require('./api/notice-controller'); var config = require('./config'); var bodyParser = require('body-parser'); var app=express(); var router = express.Router(); var multipart = require('connect-multiparty'); //在处理模块中引入第三方解析模块 var multipartMiddleware = multipart(); router.get('/test',function(req,res){ console.log("test ok"); res.send('test ok'); }); router.post('/photo/upload',multipartMiddleware,function(req,res){ console.log('start upload'); imageController.upload(req,res); }); router.post('/photo/setheadicon',function(req,res){ console.log('start setheadicon'); imageController.setHeadIcon(req,res); }); router.post('/photo/deletephoto',function(req,res){ console.log('start setheadicon'); imageController.deletePhoto(req,res); }); router.post('/photo/downloadphoto',function(req,res){ console.log('start downloadphoto'); imageController.downloadPhoto(req,res); }); router.post('/photo/downloadheadphoto',function(req,res){ console.log('start downloadheadphoto'); imageController.downloadHeadPhoto(req,res); }); router.post('/photo/downloadjson',function(req,res){ console.log('start downloadjson'); imageController.downloadJson(req,res); }); router.post('/photo/downloadBigHeadPhoto',function(req,res){ console.log('start downloadBigHeadPhoto'); imageController.downloadBigHeadPhoto(req,res); }); router.post('/photo/uploaddancegrouptexture',multipartMiddleware, function (req, res) { console.log('start uploaddancegrouptexture'); imageController.uploaddancegrouptexture(req, res); }); router.post('/photo/downloaddancegrouptexture', function (req, res) { console.log('start downloaddancegrouptexture'); imageController.downloaddancegrouptexture(req, res); }); router.post('/photo/deleteloaddancegrouptexture', function (req, res) { console.log('start deleteloaddancegrouptexture'); imageController.deleteloaddancegrouptexture(req, res); }); router.post('/notice/getnoticecontent', function (req, res) { noticeController.getnoticecontent(req, res); }); router.post('/notice/getnoticeimage', function (req, res) { noticeController.getnoticeimage(req, res); }); module.exports = router;
43445689112e55cdd6ba2d4c4a956940601d4afe
[ "JavaScript" ]
4
JavaScript
jbtxwd/webserver
e9c63d1f8e423df1848b36c3479c4d055b17cedb
961c45e69b49bdc0208fe7944981d1c63c4268ee
refs/heads/main
<file_sep>//<NAME> // student number: 19021316 // Program: vibot // Question 1 - A function to compute the Area and Circumference of sequence #include <iostream> #include <iostream> #define PI 3.14159 using namespace std; int main() { float radius, area, circum; cout << "\nInput the radius(1/2 of diameter) of a circle:"; cin >> radius; // Area of a circle=PI*radius*radius // circumference of a circle=2*PI*radius circum = 2*PI*radius; area = PI*(radius*radius); cout << "\nThe area of the circle is:" << area <<endl; cout << "\nThe circumference of the circle is:" << circum <<endl; return 0; } <file_sep>// Problem 5 - A Function to compute Truth table with operators AND & OR using three variables #include <iostream> #include<cmath> #include<conio.h> using namespace std; bool Truth_Table() { bool result; int x, y, z; cout << "\nThe AND and OR Operator for three inputs" <<endl; cout << "The Logical Operator OR :" <<endl; cout << "| x | y | z |result" <<endl; for(x = 0; x<=1; x++) { for (y = 0; y<=1; y++) { for (z = 0; z<=1; z++){ result = x || y || z; cout << "| " << x << " | " << y <<" | " << z <<" | " <<result <<endl; } } } cout << " \nThe Logical Operator AND " <<endl; for(x = 0; x<=1; x++) { for (y = 0; y<=1; y++) { for (z = 0; z<=1; z++){ result= x && y && z; cout << "| " << x << " | " << y <<" | " << z <<" | " << result <<endl; } } } return 0; } int main() { cout<<"\nTruth table for AND and OR Logical Operators"<<endl; Truth_Table(); return 0; } <file_sep>// Problem 2 - A function to find the Maximum and Minimum values of a set of numbers #include <iostream> #include <stdio.h> int main (void) { // Determine Maximum and Minimum Value int Arr[10] = {28,8,7,14,11,25,32,40,13,35}; int Max_val = Arr[0]; int Min_val = Arr[0]; int i; for(i = 1; i < 10; i++) { if(Max_val < Arr[i]) Max_val = Arr[i]; if(Min_val > Arr[i]) Min_val = Arr[i]; } std::cout << "\nThe Minimum value is : \n" << Min_val <<std::endl; std::cout << "\nThe Maximum value is = \n" << Max_val <<std::endl; return 0; } <file_sep>// Problem 3 - A function to compute Fibonacci sequence #include <iostream> using namespace std; void print_Fibonacci(int input); int Fibonacci(int input){ if (input ==0 || input ==1) { return input; } else { return Fibonacci(input -1)+ Fibonacci(input -2); } } int main() { int input, j=0; cout<< " Please, enter the rank of sequence:"; cin>>input; for (int i=1; i<=input; i++) { int result=Fibonacci(j); cout<<result<< " "; j++; } } <file_sep>// Problem 4 - A function to display Multiplication Table of a Number #include <iostream> using namespace std; int main() { int number, multiplier; cout << "Enter a number"; cin >> number; for (multiplier=1; multiplier<=10; multiplier++){ cout << number << "*" << multiplier << " = " << ( number * multiplier ) <<endl; } return 0; }
2335982bb74d63291a1242799213469a82b5f4c0
[ "C++" ]
5
C++
richie-git/SOFTWARE-ENGINEERING-TP1-ASSIGNMENT
8e0b8baf0c421b1c14234e560ad19936c282cc78
5570925d2a27fd9f3f0a50d80000f45845f41a29
refs/heads/master
<file_sep>## SCG Assignment - Vue CLI Project (Frond-end) ### Installation ``` bash # clone the project git clone https://github.com/sarapmax/zf3-scg-assignment.git # install npm depencencies npm install # serve with hot reload at localhost:8080 npm run dev ``` ### Demonstration > The web includes 4 pages. (1) Sequence solution page (data received from the API) ![page1](./src/assets/screenshots/page1.png) (2) Equation solution page (data received from the API) ![page2](./src/assets/screenshots/page2.png) (3) Line Bot instruction page ![page3](./src/assets/screenshots/page3.png) (4) Google MAPs page (data received from Google Maps APIs) ![page4](./src/assets/screenshots/page4.png) <file_sep>import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import SequenceSolution from '@/components/SequenceSolution' import EquationSolution from '@/components/EquationSolution' import GoogleApiMaps from '@/components/GoogleApiMaps' import LineBot from '@/components/LineBot' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld }, { path: '/sequence-solution', name: 'SequenceSolution', component: SequenceSolution }, { path: '/equation-solution', name: 'EquationSolution', component: EquationSolution }, { path: '/google-api-maps', name: 'GoogleApiMaps', component: GoogleApiMaps }, { path: '/line-bot', name: 'LineBot', component: LineBot } ] })
5ffec9b174a4df5d97ba73044a030019676b07e7
[ "Markdown", "JavaScript" ]
2
Markdown
sarapmax/vue-scg-assignment
5e89677ade1078690337f3e5fd57b08a95a997b9
f11240369315423a798a3b93c5b181d7bf386e74
refs/heads/master
<file_sep>export interface TextEditorOptions { key: string; placeholderText: string; attribution: boolean; charCounterCount: boolean; charCounterMax: number; heightMin: number; toolbarButtons: Array<string>; toolbarButtonsXS: Array<string>; toolbarButtonsSM: Array<string>; toolbarButtonsMD: Array<string>; }<file_sep>export enum TextEditorToolbarButtons { Bold = 'bold', Italic = 'italic', Underline = 'underline', StrikeThrough = 'strikeThrough', Subscript = 'subscript', Superscript = 'superscript', InsertTable = 'insertTable', VerticalSeparator = '|', HorizontalSeparator = '-', ParagraphFormat = 'paragraphFormat', Align = 'align', Undo = 'undo', Redo = 'redo', Html = 'html', FontFamily = 'fontFamily', FontSize = 'fontSize', TextColor = 'textColor', BackgroundColor = 'backgroundColor', InlineClass = 'inlineClass', InlineStyle = 'inlineStyle', ClearFormatting = 'clearFormatting', InsertLink = 'insertLink', InsertImage = 'insertImage', InsertVideo = 'insertVideo', Emoticons = 'emoticons', FontAwesome = 'fontAwesome', SpecialCharacters = 'specialCharacters', Embedly = 'embedly', InsertFile = 'insertFile', InsertHr = 'insertHR', Fullscreen = 'fullscreen', Print = 'print', GetPDF = 'getPDF', Spellchecker = 'spellChecker', SelectAll = 'selectAll', Outdent = 'outdent', Indent = 'indent' } export const defaultTextEditorToolbarButtons = [ TextEditorToolbarButtons.Bold, TextEditorToolbarButtons.Italic, TextEditorToolbarButtons.Underline, TextEditorToolbarButtons.StrikeThrough, TextEditorToolbarButtons.Subscript, TextEditorToolbarButtons.Superscript, TextEditorToolbarButtons.InsertTable, TextEditorToolbarButtons.VerticalSeparator, TextEditorToolbarButtons.ParagraphFormat, TextEditorToolbarButtons.Align, TextEditorToolbarButtons.Undo, TextEditorToolbarButtons.Redo ]; <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import 'froala-editor/js/plugins.pkgd.min.js'; import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { TextEditorComponent } from './shared/text-editor/text-editor.component'; import { HomeComponent } from './home/home.component'; import { SharedModule } from './shared/shared.module'; const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'user', loadChildren: () => import('./user/user.module').then(m => m.UserModule) }, { path: '', pathMatch: 'full', redirectTo: 'home' }, { path: '*', redirectTo: 'home' }, ]; @NgModule({ declarations: [ AppComponent, HomeComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot(routes), FroalaEditorModule.forRoot(), FroalaViewModule.forRoot(), SharedModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, forwardRef, Input, SimpleChanges, OnInit, OnChanges, Output, EventEmitter } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { TextEditorOptions } from './text-editor-options'; import { TextEditorToolbarButtons, defaultTextEditorToolbarButtons } from './text-editor-toolbar-buttons.enum'; @Component({ selector: 'app-text-editor', templateUrl: './text-editor.component.html', styleUrls: ['./text-editor.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TextEditorComponent), multi: true } ] }) export class TextEditorComponent implements ControlValueAccessor, OnInit, OnChanges { @Input() placeholderText = 'Insert text here...'; @Input() showCharacterCount = false; @Input() characterCountMax = 1000; @Input() heightMin = 300; @Input() toolbarButtons: Array<TextEditorToolbarButtons> = defaultTextEditorToolbarButtons; @Output() contentChanged = new EventEmitter<any>(); public model: any; public editorOptions: TextEditorOptions; public isInitialized = true; private froalaControl: any; constructor() { } ngOnInit() { this.updateEditorOptions(); } ngOnChanges(changes: SimpleChanges) { this.updateEditorOptions(); } // Begin ControlValueAccesor methods. public onChange = (_) => {}; public onTouched = () => {}; // Form model content changed. public writeValue(content: any): void { this.model = content; } public registerOnChange(fn: (_: any) => void): void { this.onChange = fn; } public registerOnTouched(fn: () => void): void { this.onTouched = fn; } // End ControlValueAccesor methods. public initialize(initControls: any) { this.froalaControl = initControls; if (this.froalaControl) { this.froalaControl.initialize(); } } public onContentChanged(content: any) { if (this.onChange) { this.onChange(content); } this.contentChanged.emit(content); } private updateEditorOptions() { if (!this.toolbarButtons) { this.toolbarButtons = defaultTextEditorToolbarButtons; } this.editorOptions = { key: '<KEY>', placeholderText: this.placeholderText, attribution: false, charCounterCount: this.showCharacterCount, charCounterMax: this.characterCountMax, heightMin: this.heightMin, toolbarButtons: this.toolbarButtons, toolbarButtonsXS: this.toolbarButtons, toolbarButtonsSM: this.toolbarButtons, toolbarButtonsMD: this.toolbarButtons }; if (this.froalaControl) { const editor = this.froalaControl.getEditor(); if (editor) { this.isInitialized = false; if (editor.opts) { editor.opts = Object.assign(editor.opts, this.editorOptions); } this.froalaControl.destroy(); this.initialize(this.froalaControl); this.isInitialized = true; } } } } <file_sep>import { NgModule } from '@angular/core'; import { TextEditorComponent } from './text-editor/text-editor.component'; import { FroalaEditorModule, FroalaViewModule } from 'angular-froala-wysiwyg'; @NgModule({ declarations: [ TextEditorComponent ], imports: [ FroalaEditorModule, FroalaViewModule ], exports: [ TextEditorComponent ] }) export class SharedModule {} <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, FormControl } from '@angular/forms'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent implements OnInit { public characterCountMax = 100; public form: FormGroup; public textFormControlName = 'textFormControl'; public textFormControl: FormControl; public textEditor1Value: string; public textEditor2Value: string; constructor(private fb: FormBuilder) { } ngOnInit() { this.textFormControl = this.fb.control(''); this.form = this.fb.group({ [this.textFormControlName]: this.textFormControl }); } public onContentChanged(content: any) { this.textEditor1Value = content; } public onSubmit() { this.textEditor2Value = this.form.get(this.textFormControlName).value; } }
b4c6a032eaaac5da23e7b6a75fcb36d3e26d0089
[ "TypeScript" ]
6
TypeScript
latchezar-kostov-ascendlearning-com/froala_problem
7c4c2c8a77a7b41a7e696778b1c59ecf932b7551
f63da1ff807b0666b98b8ce55261bba3f98d69f0
refs/heads/master
<repo_name>dwirandyh/swiftui-travelling-app<file_sep>/Travelling APp/Travelling APp/Home/ContentView.swift // // ContentView.swift // Travelling APp // // Created by <NAME> on 21/02/20. // Copyright © 2020 <EMAIL>. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { TabView { HomeView().tabItem { Image("home").font(.title) } Text("activity").tabItem { Image("activity").font(.title) } Text("search").tabItem{ Image("search").font(.title) } Text("person").tabItem{ Image("Setting").font(.title) } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep>/Travelling APp/Travelling APp/Home/HomeView.swift // // HomeView.swift // Travelling APp // // Created by <NAME> on 21/02/20. // Copyright © 2020 <EMAIL>. All rights reserved. // import SwiftUI struct HomeView: View { var body: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 12){ HStack{ Button(action: {}) { Image("menu").renderingMode(.original) } Spacer() Button(action: {}) { Image("Profile").renderingMode(.original) } } Text("Find more").fontWeight(.heavy).font(.largeTitle).padding(.top, 15) HStack{ Button(action: {}) { Text("Experience").fontWeight(.heavy).foregroundColor(.black) } Spacer() Button(action: {}) { Text("Adventures").foregroundColor(.gray) } Spacer() Button(action:{}){ Text("Activities").foregroundColor(.gray) } }.padding([.top, .bottom], 15) MiddleView() BottomView() Spacer() }.padding() } } struct HomeView_Previews: PreviewProvider { static var previews: some View { HomeView() } } struct BottomView: View { var body: some View{ VStack{ HStack{ Text("What you want ?").fontWeight(.heavy) Spacer() Button(action: {}){ Text("View All").foregroundColor(.gray) } }.padding([.top, .bottom], 15) ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 35){ Button(action:{}){ VStack(spacing: 8){ Image("mcard1").renderingMode(.original) Text("Hiking").foregroundColor(.gray) } } Button(action:{}){ VStack(spacing: 8){ Image("mcard2").renderingMode(.original) Text("Ski").foregroundColor(.gray) } } Button(action:{}){ VStack(spacing: 8){ Image("mcard1").renderingMode(.original) Text("Sky Diving").foregroundColor(.gray) } } Button(action:{}){ VStack(spacing: 8){ Image("mcard1").renderingMode(.original) Text("Skate Board").foregroundColor(.gray) } } } }.padding(.leading, 20) .padding([.top, .bottom], 15) } } } struct MiddleView : View { @State var show = false var body: some View{ ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 15){ VStack(alignment: HorizontalAlignment.leading, spacing: 5){ Button(action: { }){ Image("Card1").renderingMode(.original) } Text("Fishing Time").fontWeight(.heavy) HStack(spacing: 5){ Image("map").renderingMode(.original) Text("Vancouver, CA").foregroundColor(.gray) } } VStack(alignment: HorizontalAlignment.leading, spacing: 5){ Button(action: { self.show.toggle() }){ Image("Card2").renderingMode(.original) } Text("Forest Camping").fontWeight(.heavy) HStack(spacing: 5){ Image("map").renderingMode(.original) Text("Klojen, ID").foregroundColor(.gray) } } } }.sheet(isPresented: $show) { DetailView() } } } <file_sep>/Travelling APp/Travelling APp/Home/DetailView.swift // // DetailView.swift // Travelling APp // // Created by <NAME> on 21/02/20. // Copyright © 2020 <EMAIL>. All rights reserved. // import SwiftUI struct DetailView: View { var body: some View { VStack{ Image("topbg").resizable().frame(height: 500).aspectRatio(1.35, contentMode: .fill) .frame(width: UIScreen.main.bounds.width, height: 500).offset(y: -200).padding(.bottom, -200) GeometryReader{geo in VStack(){ DetailTop() DetailMiddle() DetailBottom() Spacer() } }.background(Color.white) .clipShape(Rounded()) .padding(.top, -75) Spacer() } } } struct DetailTop: View { var body: some View{ VStack(alignment: HorizontalAlignment.leading, spacing: 10) { HStack{ VStack{ Text("Forest").fontWeight(.heavy).font(.largeTitle) Text("Camping").fontWeight(.heavy).font(.largeTitle) } Spacer() Text("$229").foregroundColor(Color("bg")).font(.largeTitle) } }.padding() } } struct DetailMiddle : View { var body: some View { VStack(alignment: HorizontalAlignment.leading, spacing: 10){ HStack(spacing: 5){ Image("map").renderingMode(.original) Text("Kecamatan Klojen").foregroundColor(Color("bg")) Spacer() } HStack{ ForEach(0..<5){_ in Image(systemName: "star.fill").font(.body).foregroundColor(.yellow) } } Text("People").fontWeight(.heavy) Text("Number of People In Your Group").foregroundColor(.gray) HStack(spacing: 6){ ForEach(0..<5){i in Button(action:{}){ Text("\(i + 1)").foregroundColor(.white).padding(20) }.background(i == 0 ? Color("bg") : Color.gray) .cornerRadius(8) } } }.padding(.horizontal, 15) } } struct DetailBottom: View { var body: some View{ VStack(alignment: HorizontalAlignment.leading, spacing: 10) { Text("Description").fontWeight(.heavy) Text("Forest Camping Experience and Meanings Key elements of camping experience include nature, social interaction, and comfort/convenience. The most common associated meanings are restoration, family functioning") HStack(spacing: 8){ Button(action:{}){ Image("Save").renderingMode(.original) } Button(action:{}){ HStack{ Text("Book You Experience") Image("arrow").renderingMode(.original) }.foregroundColor(.white) .padding() }.background(Color("bg")) .cornerRadius(8) } }.padding(.top, 15) } } struct Rounded: Shape { func path(in rect: CGRect) -> Path { let path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 40, height: 40)) return Path(path.cgPath) } } struct DetailView_Previews: PreviewProvider { static var previews: some View { DetailView() } } <file_sep>/README.md # swiftui-travelling-app Travelling App Design with SwiftUI
d2b59559a13e3cd721dfeb397c6449f84de240a6
[ "Swift", "Markdown" ]
4
Swift
dwirandyh/swiftui-travelling-app
26f5ab3b69a3907c27d9e16769d364ada8a939d7
93e28a8a7c6dafc5c39a6efc12f545a67669c133
refs/heads/master
<file_sep># Playlist Youtube Go – Aprenda a Programar (Curso) https://www.youtube.com/playlist?list=PLCKpcjBB_VlBsxJ9IseNxFllf-UFEXOdg >> Capítulos - 1 - 2 - 3 # Exercícios realizados 1) https://play.golang.org/p/2BupCtzk2E4 2) https://play.golang.org/p/LOip7_w9ytn 3) https://play.golang.org/p/kFZurcbreW5 4) https://play.golang.org/p/W53m7DSZld3 5) https://play.golang.org/p/Kdj3xVYLITF 6) Prova: a. https://docs.google.com/forms/u/0/d/e/1FAIpQLSchZktObQvMOW0HThOow4alvRYtkSAcpjLR2urxz8gZoxaXjw/formResponse >> Capítulos - 4 (Fundamentos da programação) - 5 (Exercícios) Geração dos computadores iniciou com o ENIAC como a primeira geração criada nos anos 40. Composto com válvulas termiônicas e depois evoluído para transistores. ○ Obs.: As válvulas tinham como condutores os gases de depois os transistores utilizaram de condutores elétricos. Para entendimento mais aprofundado sobre a história dos computadores e sua evolução ver o filme Alan Turing (The Immitation Game). Apresentação complementar: https://docs.google.com/presentation/d/1aVytiGOBVDMISFW-ZARJ5iFY1osU2XJIw0hQpNICXm8/edit#slide=id.g1e92cb3441_0_264 Tipos em GO: # Strings https://blog.golang.org/strings # Sistemas numéricos https://docs.google.com/document/d/1GqXpubhMMIr4Sy5xwgiPIDh5PGVmVpF2u0c9vDrvykE/ # IOTA - Go Lang https://golang.org/ref/spec Toddy - Resolução com Iota e visualizando o passeio dos bits para os lados e mostrando seu resultado em decimal https://play.golang.org/p/7MOnbhx4R4 Conceitos https://splice.com/blog/iota-elegant-constants-golang/ https://medium.com/learning-the-go-programming-language/bit-hacking-with-go-e0acee258827 # Exercícios realizados 1) https://play.golang.org/p/39-fx9ofpeE 2) https://play.golang.org/p/8g-1ubhUWeS 3) https://play.golang.org/p/LZSCArHIeVk 4) https://play.golang.org/p/HhLnFgt_Qvs 5) https://play.golang.org/p/twogk7PJrX2 6) https://play.golang.org/p/6LHX24QuypN 7) Prova: a. CleanForm: https://docs.google.com/forms/d/e/1FAIpQLSchSZmzSvOu8lC9hfgLGkxsjEbW9pN5B10LBWJzJ676u0KVSA/viewform b. ResponseForm: https://docs.google.com/forms/d/e/1FAIpQLSchSZmzSvOu8lC9hfgLGkxsjEbW9pN5B10LBWJzJ676u0KVSA/viewscore?viewscore=AE0zAgBF8PTkE6a6TuU0UvV7IHzfEc8kYVJSnh5ddJyUU5ZRW5pican8iRRHcsQgmtp6P8g >> Capítulos - 6 - 7 # Anotações: Estrutura de controle de repetição https://gobyexample.com/for https://golang.org/ref/spec#For_statements Desafio surpresa https://play.golang.org/p/Y0PZrwRU13A # Exercícios realizados 1) https://play.golang.org/p/2owMVaqMIcg 2) https://play.golang.org/p/1jiKBnP_RR5 - string https://play.golang.org/p/gL6iXZWkLNv - Unicode point https://play.golang.org/p/Ju9bfX8ChNg - Unicode point 3x 3) https://play.golang.org/p/Tr7hI3ih_tn 4) https://play.golang.org/p/zO7FwxyiTYP 5) https://play.golang.org/p/jZv8gvEiwX5 6) https://play.golang.org/p/EK8Ljk6hJ4J 7) https://play.golang.org/p/EK8Ljk6hJ4J 8) https://play.golang.org/p/VK4RPghvXCQ 9) https://play.golang.org/p/Q3p_lNFX8W5 10) https://play.golang.org/p/4qVqVHPBANL >> Capítulos - Agrupamento de dados. - 8 - 9 # Anotações - Arrays: ○ Em GO utilizamos o slice para representar o "Array". O slice tem como elemento "subjacente" o Array nativo. Porém, o Slice ele não tem um limite prédefinido de elementos. Já o Array tem um tamanho finito quando é declarado. § Ex.: slice := []int{1, 2, 3, 4, 5} vs array := [5]{1, 2, 3, 4, 5} ○ Para deletar o valor de uma slice é fatiando a fatia. § Ex.: {bolo, café, chá, pao}, se eu quiser tirar o pao do cardápio eu sobrescrevo os elementos com append selecionando a faixa de [0:3] ficando {bolo, café, chá}. O 3 não é incluso. ○ comma ok idiom, ex.: example, ok := example["joao"]; if example, ok; !ok ; { fmt.Println("not exist")} ○ map : ex.: ``` example := map[string]int { "Joao": 35, "Jose": 45, } ``` ○ Para adicionar elementos em map apenas atribua. Ex.: example["Maria"] = 58 ○ Podemos o range com map para percorrer o key, value pairs. Ex.: for key, value := range example {fmt.Println(key, value)}, blablabla ○ Podemos deletar um item, ex.: delete(example, "Joao') # Exercícios Realizados 1) https://play.golang.org/p/VgX53rV5cJN 2) https://play.golang.org/p/AaHNGHN_3lY 3) https://play.golang.org/p/MwAsZmfCIkL 4) https://play.golang.org/p/vbai2XlaYh6 5) https://play.golang.org/p/nmnIt0aoxoc 6) https://play.golang.org/p/r0vuPZDDqft https://play.golang.org/p/qmsN2tkMSTw - com for 7) https://play.golang.org/p/onZAKbgcGCF 8) https://play.golang.org/p/_Js0ZGaC4pW 9) https://play.golang.org/p/BpSpJ7rmuU9 10) https://play.golang.org/p/7-q8na1CJOT - deletando um elemento do map >> Capítulos - Structs - 10 - 11 # Anotações Structs são um tipo de estruturas de dados. Então serve para definir uma estrutura com vários tipos diferentes de dados, se for o caso. Ex.: struct ------------------------------------------------------------------------ ``` type cliente struct { nome string, cpf int, maiordezoitoanos bool, } primeiroCliente = cliente{"Gabriel", 9999999999, true} segundoCliente = cliente{ nome: "Malutrom", cpf: 9999999999, maiordezoitoanos: true } fmt.Println(primeiroCliente) fmt.Println(segundoCliente) ``` ------------------------------------------------------------------------ # Exercícios realizados 1) https://play.golang.org/p/RUT4vTiJO3P 2) https://play.golang.org/p/KhcUkksLb6p - Inacabado... Continuar https://play.golang.org/p/lndO2sFQ1n3 - Mais coerente 3) https://play.golang.org/p/162Z7VQsusX 4) https://play.golang.org/p/lSRILesNrHf >> Capítulos - Funções - 12 - 13 # Anotações Ver mais sobre: funções anônimas: Funções auto contidas, normalmente já passa um valor no ato da função. closure: Declarações fora do escopo, usando o valor fora do escopo dentro de um return de uma outra função callbak: Função que recebe um retorno de uma outra função. Retornar aos vídeos sobre esses assuntos. # Exercícios realizados 1) https://play.golang.org/p/0ZAc_PJxRZ1 2) https://play.golang.org/p/05p5w0Imxc4 3) https://play.golang.org/p/5QfihiuMD5m 4) https://play.golang.org/p/_5X0gvrqY_p 5) https://play.golang.org/p/TM9gEWYlps7 6) https://play.golang.org/p/fPiYG2ANkyQ 7) https://play.golang.org/p/nrrNiffcWl7 8) https://play.golang.org/p/tGrUC4lY5MS 9) https://play.golang.org/p/TudU1-96jpf 10) https://play.golang.org/p/HXd3QWyeEV8 11) Tenho que fazer um vídeo sobre funções... Capítulos - Ponteiros - 14 - 15 # Anotações Direference: & <- para saber o endereço na memória e * para saber o valor representado de uma dado endereço da memória (&). Exemplo.: x := 10 y := &x <- endereço na memória *y <- extrai o valor do endereço da memória. O Ponteiro é uma variável que armazena o endereço na memória. Existe uma economia de performance quando vc altera o valor diretamente no endereço na memória. Ao invés de fazer um cópia do valor. # Exercícios realizados 1) https://play.golang.org/p/sdAqqDW1j4s https://play.golang.org/p/DUWBGM0smLi 2) https://play.golang.org/p/BJzqJ52q9ZC Capítulos - Aplicações - 16 - 17 # Anotações golang.org/pkg/ godoc.org Método chaining é um conceito de ligar um médodo no outro. Ou seja, você pode criar uma instância de um objeto para acessar seus métodos. No entanto, ao invés de criar a instância. Você pode acessar o método diretamente. Exemplos.: # Acessando diretamente: json.NewEncoder(os.Stdout).Encode(<entrada>) # Criando instância: myinstance := json.NewEncoder(os.Stdout) myinstance.Encode(<entrada>) testes por minha conta: https://play.golang.com/p/-aZJWUoHLa0 # Exercícios realizados 1) https://play.golang.org/p/jFFFzmhModr https://play.golang.org/p/hZs-Qb0vuDH <- Ellen Korbes 2) https://play.golang.org/p/svs900DUWO6 3) https://play.golang.org/p/oOpD_H7Ly4w <- sem method chaning https://play.golang.org/p/5zdi3rqQ3MG <- com method chaning 4) https://play.golang.org/p/Ig3g-RPkLtp <- sort(Ints|Strings) 5) https://play.golang.org/p/G_4QFTfaxVV <- estou aqui.. Incompleto. https://play.golang.org/p/iADkwOYU1JI <- Done! Capítulos - Concorrência e Ambiente de desenvolvimento - 18 - 19 - 20 # Anotações - Concorrência e Ambiente de desenvolvimento . Concorrência não tem relação com paralelismo. São coisas diferentes. . A concorrência é o design, a forma, o conceito, a forma de pensar, no código que será escrito. Dito isso, a gente escreve código para agir de forma concorrente. Então, faz todo sentido instruir o seu programa através de funções agir de forma concorrente. . O paralelismo surgirá dependendo da arquitetura de processamento do computador. Ou seja, é algo encapsulado. Que nós não temos "acesso" o runtime da linguagem se encarrega de pegar suas funções escritas de forma concorrente "executá-las" paralelamente dependendo dos núcleos de processadores. Aqui entra o conceito das goroutines. Pode-se entender goroutines como uma espécie de threads em seu conceito. No entanto, existe uma diferença em sua execução das goroutines pelo runtime do golang. >>threads https://pt.wikipedia.org/wiki/Thread_(computa%C3%A7%C3%A3o) Apesar de podermos utilizar quantas goroutines eu quiser e deixar que o runtime do GO assuma a responsabilidade desta gerência. Eu preciso tornar a execução de forma "syncrona". Ou seja, enviar as goroutines para execução e ter uma forma de esperar pelas suas tarefas serem concluídas. Exemplo.: Tenho várias funções que precisam ser executadas de forma concorrente. Nesse caso, aciono o go func para todas elas e imponho uma forma de tratar com sync.WaitGroup. `Ou seja, envia todos os foguetes, não sei o que eles estão fazendo. Mais espere pela conclusão de suas tarefas.`` >>Data races - Condição de corrida ou concorrência. É preciso definir um mutex ou exclusão mútua como definição. Pois quando estamos contruindo um programa que utiliza-se de funções concorrentes. Espera-se que tratemos o uso de memória compartilhada, garantindo que a goroutine e/ou thread não acessem e alterem valores diretamente no endereço de memória de forma sincronizada. O que poderá retornar um erro inesperado. Ou seja, Condição de corrida. Para tratar essa condição normalmente utiliza-se o mutex. Conforme falado acima. Ele funciona como uma espécie de lock obrigando a próxima thread aguardar na fila. # Anotações - Ambiente de desenvolvimento . Compilação cruzada. Em GO podemos compilar o programa para N sistemas operacionais. Em Go isso é possível. Utilizamos: - GOOS - GOARCH . packages. Organizando seu programa em packages. Artigo: https://rakyll.org/style-packages/ - Podemos importar packages ou referenciá-los em outros package para usar as funções. Isso é muito útil para legebilidade do código, visão limpa e organização. Além do conceito DRY para reuso de código. # Exercícios realizados 1) https://147896@github.com/147896/estudando-golang.git:src/20_exercicios-ninja-9/01/main.go 2) https://147896@github.com/147896/estudando-golang.git:src/20_exercicios-ninja-9/02/main.go 3) https://147896@github.com/147896/estudando-golang.git:src/20_exercicios-ninja-9/03/main.go 4) https://147896@github.com/147896/estudando-golang.git:src/20_exercicios-ninja-9/04/main.go 5) https://147896@github.com/147896/estudando-golang.git:src/20_exercicios-ninja-9/05/main.go 6) https://147896@github.com/147896/estudando-golang.git:src/20_exercicios-ninja-9/06/main.go >> Minhas brincadeiras, tentando usar para um contexto prático.. https://stackoverflow.com/questions/14668850/list-directory-in-go <- Isso aqui é um bom começo... - A ideia aqui é criar uma função que liste o conteúdo de um dado diretório de forma concorrente. Ou seja, para listar um diretório eu não preciso esperar o listar de forma sincrona. Eu coloco isso dentro de uma goroutine function informando um número de wait groups que é exatamente o length da lista retornada. - Outra coisa, é que depois que tivermos um resultado esperado no statement acima. Como estaremos focando em um caso específico. No caso o terraform init -reconfigure e o terraform plan. Precisamos iterar sobre a lista de diretórios acima e rodar esses comandos do terraform também de forma assíncrona usando goroutines. Capítulos - Canais (Channel) - 21 # Anotações - ... . Canais é uma forma de você trocar informações intra goroutines. É um meio de comunicação entre goroutines para possibilitar a transmissão de informações. **Lembrando que a func main também é uma goroutine.** . Canais bidirecionais (send and receiver). Consultar.: https://stackoverflow.com/questions/13596186/whats-the-point-of-one-way-channels-in-go send e receiver são tipos diferentes. Ou seja, existem macanismos para checar os tipos protegendo, de certa forma, a escrita em um canal que é do tipo leitura. E vice-versa. <-chan == receive chan<- == send . Quando declaro um canal send e um receive uma delas obrigatoriamente precisa ser uma goroutine. Ou seja, precisam concorrer. . Range e close em canais normalmente são usados. Servem para iterar sobre itens que irão escrever sobre o canal e o close é utilizado após a conclusão do loop para informar para o canal que não existem mais itens a serem enviados. . Exemplos utilizando o https://play.golang.com # iterando sobre um channel: https://play.golang.com/p/rTaHevkMXMr # uso do select (similar ao switch case só que para canais): 1. https://play.golang.com/p/wMNdJByPBx- 2. https://play.golang.com/p/HRgToy4umnZ 3. https://play.golang.com/p/DRuYhJNLf00 <- o select pode tratar multicanais para enviar e/ou receber. # Exercícios realizados 1) https://play.golang.org/p/xO9iOSsbmWH # com buffer https://play.golang.org/p/2D84B7z781O # com go func 2) https://play.golang.org/p/QHxrG8UEiuq 3) http://play.golang.org/p/eoH1ZQC2gQg obs.: fiz e pensei de forma correta. Porém estava retornando o erro deadlock goroutines. Isso porque tinha me esquecido de fechar o channel com close(channel).<file_sep>Curso de Golang com <NAME>. <file_sep>package main import ( "fmt" "sync" "runtime" ) var wg sync.WaitGroup func main() { fmt.Println("goroutines inicial.: ", runtime.NumGoroutine()) bolastelecena := 100 wg.Add(bolastelecena) for i := 1; i <= bolastelecena; i++ { go func() { runtime.Gosched() fmt.Println("Bola N˚.:", i) wg.Done() }() go fmt.Println("Enquanto estão tentando sortear a bola, vamos fazer outras coisas...") } fmt.Println("goroutines finais.: ", runtime.NumGoroutine()) wg.Wait() } <file_sep>package main import ( "fmt" "sync" "sync/atomic" "runtime" ) var wg sync.WaitGroup var mux sync.Mutex var count int32 const qtdgoroutines = 100 func main() { goroutines(qtdgoroutines) wg.Wait() fmt.Println("contador.: ", count, "\nQtd de Goroutines.: ", qtdgoroutines) } func goroutines(num int) { wg.Add(num) for i := 1; i <= num; i++ { go func () { v := &count atomic.AddInt32(v, 1) fmt.Println(*v) runtime.Gosched() wg.Done() }() } } <file_sep>package main import ( "fmt" ) type pessoa struct { nome string sobrenome string idade int dizendocoisas []string } func (s *pessoa) falar() { fmt.Printf("Meu nome completo é %v %v e tenho %v anos\n- %v\n", s.nome, s.sobrenome, s.idade, s.dizendocoisas) } type humanos interface { falar() } func dizerAlgumaCoisa(s humanos) { s.falar() } func main() { p1 := pessoa{ nome: "Gabriel", sobrenome: "Ribas", idade: 32, dizendocoisas: []string{"Uma das coisas mais fantásticas que existem é comer pão com ovo e iogurte.", "Sem contar o famoso miojo com toddy.", "Minha vida é comer essas delícias..."}, } p1.falar() // Aqui esta usando o metodo falar que faz um ponteiro. Entao esta implicito. (&p1).falar() //dizerAlgumaCoisa(p1) // Isso aqui nao funciona. porque é um ponteiro dizerAlgumaCoisa(&p1) // Isso aqui funciona porque está referenciando o ponteiro. Pois o receiver é um ponteiro. } <file_sep>package main import ( "fmt" "sync" "runtime" ) var wg sync.WaitGroup var mux sync.Mutex var count int const qtdgoroutines = 100 func main() { goroutines(qtdgoroutines) wg.Wait() fmt.Println("contador.: ", count, "\nQtd de Goroutines.: ", qtdgoroutines) } func goroutines(num int) { wg.Add(num) for i := 1; i <= num; i++ { go func () { mux.Lock() v := count runtime.Gosched() v++ count = v mux.Unlock() wg.Done() }() } } <file_sep>package main import ( "fmt" "sync" "runtime" ) var wg sync.WaitGroup var count int func main() { gos := 10000 goroutines(gos) runtime.Gosched() fmt.Println("contador.: ", count, "\nQtd de Goroutines.: ", runtime.NumGoroutine()) wg.Wait() } func goroutines(num int) { j := num wg.Add(j) for i := 1; i <= j; i++ { go func (x int) { v := count runtime.Gosched() v++ count = v wg.Done() }(i) } }
4af243377040a3cfd9c47e1c48edede9969d8b60
[ "Markdown", "Go" ]
7
Markdown
gabrielsribas/estudando-golang
f0193987c03187205d927aa05e4c9a2a4c5c4870
eb03fd27c61585e7676fbcd4c43d3285c279e5b3
refs/heads/master
<repo_name>Fireflywater/4.3.1-practice-pigdice<file_sep>/README.md # _4.3.1 Practice, Pig Dice_ #### _Exercise in vidya, 8/5/2019_ #### By _**<NAME>**_ ## Description _I'm not totally happy with how this ended up. But it does work. If it works, it's good enough for me!_ ## Specs/Behaviors object PlayingField() Contains 1 array for players, and 1 int for turn count. Current player is determined by ( turn count % total players ) object Player() Contains a name and 2 ints. Name is only used for flavor, ints hold the 2 scoring variables function PlayingField.turnAlpha(p) "Alpha" turn, if player chooses to rolls outputs roll and adds it to player temp total if it's not 1 outputs nothing if it is 1 and moves to next player function PlayingField.turnOmega(p) "Omega" turn, if player chooses to hold moves temp total to perm total and moves to next player function PlayingField.refreshDisplay() refreshes the html page to have up-to-date values function PlayingField.generateInterface() builds interface based on a template for a per-player basis technically supports max_safe_interger, but built for 3 players maximum function PlayingField.checkVictory() determines if anyone's permScore is over 100 constantly called, shouldn't lead into ties disables buttons once victory is made ## Setup/Installation Requirements * _It's an HTML_ * _Download the folder provided_ * _Navigate to the folder containing 'index.html'_ * _Run 'index.html' with your favorite web browser (Firefox, Chrome, Edge)_ ## Known Bugs _Unknown_ ## Support and contact details _I am <NAME>, please hestitate to call me at <<EMAIL>_ ## Technologies Used _GIT, Notepad, HTML, CSS, Bootstrap, Javascript, jQuery_ ### License Copyright (c) 2019 **_<NAME>_** This project is licensed under the terms of the MIT license.<file_sep>/js/scripts.js function PlayingField() { this.players = []; this.turn = 0; }; function Player(name) { this.name = name; this.tempScore = 0; this.permScore = 0; }; PlayingField.prototype.turnAlpha = function (p) { var player = this.players[p]; var roll = Math.ceil(Math.random() * 6); $("#rollOutput" + p).text(roll); if (roll === 1) { // YOU FAILED player.tempScore = 0; this.turn += 1; return "rip"; }; player.tempScore += roll; return roll; }; PlayingField.prototype.turnOmega = function(p) { var player = this.players[p]; player.permScore += player.tempScore; player.tempScore = 0; this.turn += 1; }; PlayingField.prototype.refreshDisplay = function() { $(".allButtons").hide() for (var i = 0; i<this.players.length; i++) { var player = this.players[i]; $("#nameOutput" + i).text(player.name); $("#tempOutput" + i).text(player.tempScore); $("#permOutput" + i).text(player.permScore); $("#buttons" + this.turn%this.players.length).show(); }; }; PlayingField.prototype.generateInterface = function() { for (var i = 0; i<this.players.length; i++) { var newPlayerInterface = $("#template").clone(); newPlayerInterface.find(".name").text(this.players[i].name); newPlayerInterface.find("#tempOutput").attr("id","tempOutput" + i); newPlayerInterface.find("#permOutput").attr("id","permOutput" + i); newPlayerInterface.find("#rollOutput").attr("id","rollOutput" + i); newPlayerInterface.find("#buttons").attr("id","buttons" + i); $("#playingRows").append(newPlayerInterface); }; $("#template").hide(); $("#victoly").hide(); }; PlayingField.prototype.checkVictory = function() { var literallyWho = "nobody" for (var i = 0; i<this.players.length; i++) { if (this.players[i].permScore >= 100) { literallyWho = i; break; }; }; if (!isNaN(literallyWho)) { $(".allButtons").hide(); $("#victoly").show(); $("#victoly span").text(this.players[literallyWho].name); }; }; $(document).ready(function() { var field = new PlayingField(); var p1 = new Player("<NAME>"); field.players.push(p1); var p2 = new Player("<NAME>"); field.players.push(p2); var p3 = new Player("Ahaha p3!"); field.players.push(p3); field.generateInterface(); field.refreshDisplay(0); $("button").click(function() { var curP = field.turn%field.players.length; if ($(this).attr("id") == "roll") { var t = field.turnAlpha(curP); } else if ($(this).attr("id") == "hold") { var t = field.turnOmega(curP); }; field.refreshDisplay(curP); field.checkVictory(); }); });
9927c05a2c6bf1363644e750d803f8d6cb2e2fa8
[ "Markdown", "JavaScript" ]
2
Markdown
Fireflywater/4.3.1-practice-pigdice
7af956aab1a6a7bdfc9d6ae5a670362328aa234b
fc4652e433aabc4aa369ada35b24ea88f8a12430
refs/heads/master
<file_sep>const Rx = require('rxjs'); const $ = require('jquery'); let speed = .01; let zoom = -1000; let sceneRedColor = 210; let sceneGreenColor = 210; let sceneBlueColor = 210; let objectWidth = 100; let objectHeight = 100; let objectDepth = 100; let objectRedColor = 255; let objectGreenColor = 0; let objectBlueColor = 0; let ambientLightRed = 255; let ambientLightGreen = 0; let ambientLightBlue = 255; let ambientIntensity = 80; const controls = { getSpeed: function() { return speed; }, getZoom: function() { return zoom; }, getSceneRedColor: function() { return decimalToHexString(parseInt(sceneRedColor)); }, getSceneGreenColor: function() { return decimalToHexString(parseInt(sceneGreenColor)); }, getSceneBlueColor: function() { return decimalToHexString(parseInt(sceneBlueColor)); }, getXScale: function() { return objectWidth/100; }, getYScale: function() { return objectHeight/100; }, getZScale: function() { return objectDepth/100; }, getObjectRedColor: function() { return decimalToHexString(parseInt(objectRedColor)); }, getObjectGreenColor: function() { return decimalToHexString(parseInt(objectGreenColor)); }, getObjectBlueColor: function() { return decimalToHexString(parseInt(objectBlueColor)); }, getAmbientRedColor: function() { return decimalToHexString(parseInt(ambientLightRed)); }, getAmbientGreenColor: function() { return decimalToHexString(parseInt(ambientLightGreen)); }, getAmbientBlueColor: function() { return decimalToHexString(parseInt(ambientLightBlue)); }, getAmbientIntensity: function() { return ambientIntensity; } }; exports.controls = controls; /* Utilities */ function decimalToHexString(number) { let finalNumber = ''; if (number < 0) { number = 0xFFFFFF + number + 1; } finalNumber = number.toString(16).toUpperCase(); if (number < 16) { finalNumber = '0' + finalNumber; } return finalNumber; } /* Bootstrap Code - binds the inputs to the values. */ (function setupObjectWidthInput() { const objectInput = document.querySelector('threejs-control'); Rx.Observable.fromEvent(objectInput, 'change').subscribe( function(event) { objectWidth = objectInput.objectWidth*4; objectHeight = objectInput.objectHeight*4; objectDepth = objectInput.objectDepth*4; sceneRedColor = objectInput.sceneRedColor; sceneGreenColor = objectInput.sceneGreenColor; sceneBlueColor = objectInput.sceneBlueColor; objectRedColor = objectInput.objectRed; objectBlueColor = objectInput.objectBlue; objectGreenColor = objectInput.objectGreen; speed = objectInput.speed/100; zoom = objectInput.zoom*-100; ambientLightRed = objectInput.ambientRed; ambientLightGreen = objectInput.ambientGreen; ambientLightBlue = objectInput.ambientBlue; ambientIntensity = objectInput.ambientIntensity; } ); })(); (function setupAbientInputs() { const redInput = document.getElementById('lightAmbientRed'); const greenInput = document.getElementById('lightAmbientGreen'); const blueInput = document.getElementById('lightAmbientBlue'); const lightAmbientInput = document.getElementById('lightAmbientIntensity'); redInput.value = ambientLightRed; blueInput.value = ambientLightBlue; greenInput.value = ambientLightGreen; lightAmbientInput.value = ambientIntensity; Rx.Observable.fromEvent(redInput, 'change').subscribe( function(event) { ambientLightRed = event.target.value; } ); Rx.Observable.fromEvent(greenInput, 'change').subscribe( function(event) { ambientLightGreen = event.target.value; } ); Rx.Observable.fromEvent(blueInput, 'change').subscribe( function(event) { ambientLightBlue = event.target.value; } ); Rx.Observable.fromEvent(lightAmbientInput, 'change').subscribe( function(event) { ambientIntensity = event.target.value; } ); })(); (function setUpMenuShowHide() { const hideMenuHandler = function(evt) { const attrTypeName = evt.target.attributes['attr-type']; $(evt.target).hide(); $('.'+attrTypeName.value+'-row-attribute').hide(); $('#'+attrTypeName.value+'Shower').show(); } const showMenuHandler = function(evt) { const attrTypeName = evt.target.attributes['attr-type']; $(evt.target).hide(); $('.'+attrTypeName.value+'-row-attribute').hide(); $('.'+attrTypeName.value+'-row-attribute').show(); $('#'+attrTypeName.value+'Hider').show(); } Rx.Observable.fromEvent(controlsHider, 'click').subscribe(hideMenuHandler); Rx.Observable.fromEvent(sceneHider, 'click').subscribe(hideMenuHandler); Rx.Observable.fromEvent(objectHider, 'click').subscribe(hideMenuHandler); Rx.Observable.fromEvent(lightsHider, 'click').subscribe(hideMenuHandler); Rx.Observable.fromEvent(controlsShower, 'click').subscribe(showMenuHandler); Rx.Observable.fromEvent(sceneShower, 'click').subscribe(showMenuHandler); Rx.Observable.fromEvent(objectShower, 'click').subscribe(showMenuHandler); Rx.Observable.fromEvent(lightsShower, 'click').subscribe(showMenuHandler); })(); <file_sep>var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './app.js', output: { filename: 'dest/bundle.js' }, plugins: [new HtmlWebpackPlugin({template: './template.html'})] } <file_sep>const THREE = require('three'); const Rx = require('rxjs'); const controls = require('./controls.js').controls; const calcInterval = Rx.Observable.interval(100); const rendererDefinition = { canvas: document.getElementById('myCanvas'), antialias: true }; const camera = new THREE.PerspectiveCamera(35, window.innerWidth/window.innerHeight, 0.1, 10000); // camera.position(0,0,0); const renderer = new THREE.WebGLRenderer(rendererDefinition); renderer.setSize(window.innerWidth, window.innerHeight); const scene = new THREE.Scene(); scene.background = new THREE.Color( 0x666666 ); const light = new THREE.AmbientLight(0xffffff, 0.5); scene.add(light); const light1 = new THREE.PointLight(0xffffff, 0.5); scene.add(light1); const geometry = new THREE.CubeGeometry(100, 100, 100); const material = new THREE.MeshLambertMaterial({color:0xffcccc}); const mesh = new THREE.Mesh(geometry, material); const group = new THREE.Group(); group.add(mesh); scene.add(group); mesh.material.color.setHex( 0x00ff00 ); let controlsSettings = {}; controlsInfoParser(); function controlsInfoParser() { let sceneColor = '0x' + controls.getSceneRedColor() + controls.getSceneGreenColor() + controls.getSceneBlueColor(); sceneColor = parseInt(sceneColor); const xRotationSpeed = controls.getSpeed(); const yRotationSpeed = controls.getSpeed(); const zRotationSpeed = controls.getSpeed(); const xScale = controls.getXScale(); const yScale = controls.getYScale(); const zScale = controls.getZScale(); let objectColor = '0x' + controls.getObjectRedColor() + controls.getObjectGreenColor() + controls.getObjectBlueColor(); objectColor = parseInt(objectColor); let ambientColor = '0x' + controls.getAmbientRedColor() + controls.getAmbientGreenColor() + controls.getAmbientBlueColor(); let ambientIntensity = controls.getAmbientIntensity(); ambientColor = parseInt(ambientColor); const zoom = controls.getZoom(); const background = new THREE.Color( sceneColor ); controlsSettings = { sceneColor: sceneColor, xRotationSpeed: xRotationSpeed, yRotationSpeed: yRotationSpeed, zRotationSpeed: zRotationSpeed, background: background, zoom: zoom, xScale: xScale, yScale: yScale, zScale: zScale, objectColor: objectColor, ambientColor: ambientColor, ambientIntensity: ambientIntensity/100 }; } calcInterval.subscribe(controlsInfoParser); function render() { mesh.material.color.setHex( controlsSettings.objectColor ); scene.background = controlsSettings.background; group.rotation.x += controlsSettings.xRotationSpeed; group.rotation.y += controlsSettings.yRotationSpeed; group.position.set(0,0,controlsSettings.zoom); mesh.scale.x = controlsSettings.xScale; mesh.scale.y = controlsSettings.yScale; mesh.scale.z = controlsSettings.zScale; light.color.setHex(controlsSettings.ambientColor); light.intensity = controlsSettings.ambientIntensity; renderer.render(scene, camera); requestAnimationFrame(render); } render();
ee901531a521dd3ceb293226dbf2a3a90c81d21c
[ "JavaScript" ]
3
JavaScript
martytheparty/threejs-practice
4710c23edb219c0d7fc8d2e3ec88b78acb26f335
1544c76a781acd8885d3789092c18fcc10346889
refs/heads/master
<file_sep>const svnUltimate = require('node-svn-ultimate'); const ProgressBar = require('progress'); const fs = require('fs'); const config = require('./config/config.js'); const ask = require('./lib/ask'); const encodingType = 'utf8'; const options = { username: config.id, password: <PASSWORD> } var commitMessage = ''; var splitData = []; var targetData = []; var answer = 'Y'; //checkout용 progress-bar var bar = new ProgressBar('First of all, you have to checkout repository: :bar', { complete: '.' , incomplete: ' ' , total: 250 }); //initFlag파일 읽기. 최초에는 true값이, 이후에는 false값이 들어온다. let getInitStatus = (filePath, tyoe) => { return new Promise((resolve, reject) => { fs.readFile(filePath, tyoe, function(error, data){ if(error) reject(error); console.log('Don\'t you have repository? ' + data); (data==="true")? resolve(true): resolve(false); }); }); }; //initFlag파일에 대해 message값으로 수정한다. 최초수행시 true값을 false로 수정하여 체크아웃등을 미연에 방지한다. let setInitStatus = (filePath, message, tyoe) => { return new Promise((resolve, reject) => { fs.writeFile(filePath, message, tyoe, function(error){ if(error) reject(error); console.log('I\'ll Change your initialize status value. => ' + message); resolve(); }); }); }; //svn checkout. svn경로와 받을 디렉토리를 정의해준다. (최초에 레포지토리 없는 경우에만 수행할 것) let getSourceCheckOut = () => { return new Promise((resolve, reject) => { svnUltimate.commands.checkout( config.url, config.repo, function(error) { if(error) reject(error); console.log('Checkout finished.'); resolve(); }); }) }; //svn cleanup let cleanUp = () => { return new Promise((resolve, reject) => { svnUltimate.commands.cleanup( config.repo, options, function(error){ if(error) reject(error); console.log('CleanUp finished.'); resolve(); }); }); }; //svn update to head let updateToHead = () => { return new Promise((resolve, reject) => { svnUltimate.commands.update( config.repo, options, function(error) { if(error) reject(error); console.log( "Update finished." ); resolve(); }); }); }; let getFileContents = () => { return new Promise((resolve, reject) => { fs.readFile( config.source, encodingType, function(error, data){ if(error) reject(error); console.log('First, I\'ll check your source file list.'); resolve(data); }); }) } //svn merge source let merge = () => { let tempData = splitData[0].split('/').join('\\'); let targetURL = config.repo + '\\' + tempData; let option = { params: [targetURL] } return new Promise((resolve, reject) => { svnUltimate.commands.merge( targetData, option, function(error) { if(error) reject(error); console.log( "Merge finished." ); resolve(); }); }); }; //initFlag값에 따라 checkout을 받고 안받고 결정한다. 추후에는 레포지토리 디렉토리 검사로 변경할 것 async function initFlagProcess(){ let initFlag = await getInitStatus('./config/initFlag', encodingType); if(initFlag){ let timer = setInterval(function(){ bar.tick(); if (bar.complete) { console.log('\nalmost done. wait for it.\n'); clearInterval(timer); } }, 1500); await setInitStatus('./config/initFlag', 'false', encodingType); await getSourceCheckOut(); } await cleanUp(); } async function updateProcess(){ await updateToHead(); } async function readFileContents(){ let data = await getFileContents(); console.log('\n' + data + '\n-------------------------------------------------------------------'); answer = await ask.readLine('Is this right your merge source list? (Y/N)'); if(answer === 'Y' || answer === 'y'){ splitData = data.split('\n'); commitMessage = splitData[0]; splitData = splitData.slice(1); for(let i=0; i<splitData.length; i++){ targetData[i] = config.trunkUrl + splitData[i]; console.log(splitData[i]); } } else{ return; } } async function mergeProcess(){ await merge(); } //메인함수 var next = initFlagProcess().then(() => { console.log('Initialize job is done. Let\'s do update to head in your repository.'); }); next.then(() => { updateProcess().then(() => { console.log('Update job is done. Let\'s do merge job. Are you ready?'); return true; }).then(() => { readFileContents().then(() => { mergeProcess(); }).then(() => { console.log('Merge job is done.') }); });; }); next.then(() => { }); <file_sep># svn-auto-merge svn auto merge system<file_sep>module.exports = { 'url': 'svn://10.10.10.10/', 'id': 'test', 'pw': 'test#1234', 'repo': 'D:\\repo', };
9e46062b7142b505d7f6cbac4f7bf9b93e2460b2
[ "JavaScript", "Markdown" ]
3
JavaScript
skylogin/svn-auto-merge
25d76300a730dbdac13ea3fe5b89ec01a3e90f21
ffae8da0fba01b13ea2aeab5e5092628d1eaa376
refs/heads/master
<file_sep># ChatAssistant Simple chat assistant app based on WolframAlpha short answers API with voice search For more information about WolframAlpha visit their site https://www.wolframalpha.com/ <file_sep>rootProject.name = "Chat Assistant" include ':app' <file_sep>package com.example.chatassistant import android.view.View import android.widget.ListView import androidx.test.espresso.Espresso.onData import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.doesNotExist import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.platform.app.InstrumentationRegistry import org.hamcrest.CoreMatchers.* import org.hamcrest.Description import org.hamcrest.TypeSafeMatcher import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @LargeTest @RunWith(AndroidJUnit4::class) class ThirdLessonInstrumentedTest { @get:Rule var activityScenarioRule = ActivityScenarioRule(MainActivity::class.java) @Test fun testClearMenuItemCleanList() { onView( withId(R.id.text_input_edit) ).perform( replaceText("How big is the universe?"), pressImeActionButton() ) Thread.sleep(5000L) onView( withId(R.id.action_clear) ).perform( click() ) onView( withId(R.id.pods_list) ).check( matches( hasItems(0) ) ) } @Test fun testClearMenuItemCleanRequestField() { onView( withId(R.id.text_input_edit) ).perform( replaceText("How big is the universe?"), pressImeActionButton() ) Thread.sleep(5000L) onView( withId(R.id.action_clear) ).perform( click() ) onView( withId(R.id.text_input_edit) ).check( matches( withText("") ) ) } @Test fun testRequest() { onView( withId(R.id.text_input_edit) ).perform( replaceText("How big is the universe?"), pressImeActionButton() ) Thread.sleep(5000L) onView( withId(R.id.pods_list) ).check( matches( hasItems(3) ) ) onData( anything() ).inAdapterView( withId(R.id.pods_list) ).atPosition( 0 ).onChildView( withId(R.id.title) ).check( matches( withText("Interpretation") ) ) } @Test fun testProgressBar() { onView( withId(R.id.text_input_edit) ).perform( replaceText("Hello World"), pressImeActionButton() ) onView( withId(R.id.progress_bar) ).check( matches( isDisplayed() ) ) // Better to use IdlingResource Thread.sleep(5000L) onView( withId(R.id.progress_bar) ).check( matches( not(isDisplayed()) ) ) } @Test fun testSnackBarIsDisplayed() { InstrumentationRegistry.getInstrumentation().uiAutomation.apply { executeShellCommand("svc wifi disable") executeShellCommand("svc data disable") } Thread.sleep(1000L) onView( withId(R.id.text_input_edit) ).perform( replaceText("Hello World"), pressImeActionButton() ) Thread.sleep(1000L) onView( withId(com.google.android.material.R.id.snackbar_text) ).check( matches( isDisplayed() ) ) InstrumentationRegistry.getInstrumentation().uiAutomation.apply { executeShellCommand("svc wifi enable") executeShellCommand("svc data enable") } Thread.sleep(1000L) } @Test fun testSnackBarHasAction() { InstrumentationRegistry.getInstrumentation().uiAutomation.apply { executeShellCommand("svc wifi disable") executeShellCommand("svc data disable") } Thread.sleep(1000L) onView( withId(R.id.text_input_edit) ).perform( replaceText("Hello World"), pressImeActionButton() ) Thread.sleep(1000L) onView( withId(com.google.android.material.R.id.snackbar_action) ).check( matches( allOf( isDisplayed(), withText(android.R.string.ok) ) ) ) InstrumentationRegistry.getInstrumentation().uiAutomation.apply { executeShellCommand("svc wifi enable") executeShellCommand("svc data enable") } Thread.sleep(1000L) } @Test fun testSnackAction() { onView( withId(R.id.text_input_edit) ).perform( replaceText(""), pressImeActionButton() ) Thread.sleep(5000L) onView( withId(com.google.android.material.R.id.snackbar_action) ).perform( click() ).check( doesNotExist() ) } @Test fun testEditTextError() { onView( withId(R.id.text_input_edit) ).perform( replaceText("п!!,,**$$№@@@"), pressImeActionButton() ) // Better to use IdlingResource Thread.sleep(5000L) onView( withId(R.id.text_input_edit) ).check( matches( hasErrorText( InstrumentationRegistry.getInstrumentation().targetContext .getText(R.string.error_do_not_understand).toString() ) ) ) } } fun hasItems(expectedCount: Int) = object : TypeSafeMatcher<View>() { override fun describeTo(description: Description?) { description?.appendText("ListView has $expectedCount items") } override fun matchesSafely(view: View?): Boolean { val actualCount = (view as? ListView)?.adapter?.count if (actualCount == null) { return false } return expectedCount == actualCount } }
cf75bc991d0b0aad48d4dfc3bc17c7fe9c7f61c2
[ "Markdown", "Kotlin", "Gradle" ]
3
Markdown
fedulovs/ChatAssistant
b9f5cc3b839fc62220a49bccbe8616742880b37f
a3bd06733cb2ccdbcf8fdb106bc9566d31afe9ef
refs/heads/master
<file_sep>import os from flask import Flask, abort, jsonify, request from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from auth.auth import AuthError, requires_auth from database.models import Actor, Movie, setup_db app = Flask(__name__) setup_db(app) CORS(app) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS') return response # Routes @app.route('/') def index(): return "Casting Agency API" @app.route('/movies') @requires_auth(permission='get:movies') def receive_movies(payload): data = Movie.query.all() movies = [movie.format() for movie in data] return jsonify({ "success": True, "movies": movies }) @app.route('/actors') @requires_auth(permission='get:actors') def receive_actors(payload): data = Actor.query.all() actors = [actor.format() for actor in data] return jsonify({ "success": True, "actors": actors }) @app.route('/movies', methods=['POST']) @requires_auth(permission='post:movies') def create_new_movie(payload): body = request.get_json() movie_id = body.get('id', None) title = body.get('title', None) release_date = body.get('release_date', None) if title is not None and title != '': movie = Movie(id=movie_id, title=title, release_date=release_date) movie.insert() else: abort(400) return jsonify({ "success": True, "movie": movie.format() }) @app.route('/actors', methods=['POST']) @requires_auth(permission='post:actors') def create_new_actor(payload): body = request.get_json() actor_id = body.get('id', None) name = body.get('name', None) age = body.get('age', None) gender = body.get('gender', None) if name != '' and name is not None: actor = Actor(id=actor_id, name=name, gender=gender, age=age) actor.insert() else: abort(400) return jsonify({ "success": True, "actor": actor.format() }) @app.route('/movies/<int:movie_id>', methods=['PATCH']) @requires_auth(permission='patch:movies') def edit_movie(payload, movie_id): movie = Movie.query.filter(Movie.id == movie_id).one_or_none() if movie is None: abort(404) body = request.get_json() new_title = body.get('title', None) if new_title != '' and new_title is not None: movie.title = new_title new_release_date = body.get('release_date', None) if new_release_date != '' and new_release_date is not None: movie.release_date = new_release_date movie.update() return jsonify({ "success": True, "movie": movie.format() }) @app.route('/actors/<int:actor_id>', methods=['PATCH']) @requires_auth(permission='patch:actors') def edit_actor(payload, actor_id): actor = Actor.query.filter(Actor.id == actor_id).one_or_none() if actor is None: abort(404) body = request.get_json() new_name = body.get('name', None) if new_name != '' and new_name is not None: actor.name = new_name new_age = body.get('age', None) if new_age != '' and new_age is not None: actor.age = new_age new_gender = body.get('gender', None) if new_gender != '' and new_gender is not None: actor.gender = new_gender new_movie_connection = body.get('movie_id', None) if new_movie_connection != '' and new_movie_connection is not None: actor.movie_id = new_movie_connection actor.update() return jsonify({ "success": True, "actor": actor.format() }) @app.route('/actors/<int:actor_id>', methods=['DELETE']) @requires_auth(permission='delete:actors') def delete_actor(payload, actor_id): actor = Actor.query.filter(Actor.id == actor_id).one_or_none() if actor is None: abort(404) actor.delete() return jsonify({ "success": True, "deleted": actor.format() }) @app.route('/movies/<int:movie_id>', methods=['DELETE']) @requires_auth(permission='delete:movies') def delete_movie(payload, movie_id): movie = Movie.query.filter(Movie.id == movie_id).one_or_none() if movie is None: abort(404) movie.delete() return jsonify({ "success": True, "deleted": movie.format() }) # Error Handling @app.errorhandler(400) def bad_request(error): return jsonify({ 'success': False, 'error': 400, 'message': 'Bad request' }), 400 @app.errorhandler(404) def not_found(error): return jsonify({ 'success': False, 'error': 404, 'message': 'Not found' }), 404 @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "Unprocessable entity" }), 422 @app.errorhandler(500) def server_error(error): return jsonify({ 'success': False, 'error': 500, 'message': 'Internal server error' }), 500 @app.errorhandler(AuthError) def auth_error(error): return jsonify({ 'success': False, 'error': error.status_code, 'message': error.error }), error.status_code <file_sep>alembic==1.4.1 asgiref==3.2.5 click==7.1.1 dj-database-url==0.5.0 Django==3.0.4 django-heroku==0.3.1 ecdsa==0.15 Flask==1.1.1 Flask-Cors==3.0.8 Flask-Migrate==2.5.3 Flask-Script==2.0.6 Flask-SQLAlchemy==2.4.1 gunicorn==20.0.4 itsdangerous==1.1.0 Jinja2==2.11.1 jose==1.0.0 Mako==1.1.2 MarkupSafe==1.1.1 psycopg2==2.8.4 psycopg2-binary==2.8.4 pyasn1==0.4.8 python-dateutil==2.8.1 python-dotenv==0.12.0 python-editor==1.0.4 python-jose==3.1.0 pytz==2019.3 rsa==4.0 six==1.14.0 SQLAlchemy==1.3.15 sqlparse==0.3.1 Werkzeug==1.0.0 whitenoise==5.0.1 <file_sep>import json import os from dotenv import load_dotenv from flask_sqlalchemy import SQLAlchemy from sqlalchemy import (Column, DateTime, Enum, ForeignKey, Integer, String, create_engine) load_dotenv('.env') db = SQLAlchemy() database_path = os.getenv('DATABASE_URL') def setup_db(app, database_path=database_path): app.config.from_pyfile('settings.py') db.app = app db.init_app(app) db.create_all() class Movie(db.Model): __tablename__ = 'movie' id = Column(Integer, primary_key=True) title = Column(String, nullable=False) release_date = Column(DateTime, nullable=True) def insert(self): db.session.add(self) db.session.commit() def update(self): db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def format(self): return { 'id': self.id, 'title': self.title, 'release_date': self.release_date } class Actor(db.Model): __tablename__ = 'actor' id = Column(Integer, primary_key=True) name = Column(String, nullable=False) age = Column(Integer, nullable=True) gender = Column(db.Enum('female', 'male', 'other', name='GenderTypes'), default=None, nullable=True) movies = db.relationship('Movie', backref='actor', lazy=True) movie_id = Column(Integer, ForeignKey('movie.id'), nullable=True) def insert(self): db.session.add(self) db.session.commit() def update(self): db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def format(self): return { 'id': self.id, 'name': self.name, 'age': self.age, 'gender': self.gender, 'movie_id': self.movie_id } <file_sep>from os import getenv SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL') DATABASE_TEST_URL = getenv('DATABASE_TEST_URL') SQLALCHEMY_TRACK_MODIFICATIONS = getenv('SQLALCHEMY_TRACK_MODIFICATIONS') <file_sep>import json import os import unittest from dotenv import load_dotenv from flask_sqlalchemy import SQLAlchemy from app import app from database.models import Actor, Movie, setup_db from test_data import (edited_actor_info, edited_movie_info, new_actor_info, new_movie_info) load_dotenv('.env') database_path = os.getenv('DATABASE_TEST_URL') assistant_token = os.getenv('ASSISTANT_TEST_TOKEN') director_token = os.getenv('DIRECTOR_TEST_TOKEN') producer_token = os.getenv('PRODUCER_TEST_TOKEN') class TriviaTestCase(unittest.TestCase): def setUp(self): self.app = app self.client = self.app.test_client setup_db(self.app, database_path) self.app.config["SQLALCHEMY_DATABASE_URI"] = database_path with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) self.db.create_all() def tearDown(self): pass def set_headers(self, token=None): if token is None: return {} else: return { 'Authorization': 'Bearer ' + token } # GET-methods def test_get_movies(self, token=assistant_token): response = self.client().get('/movies', headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertTrue(len(data['movies'])) def test_get_movies_without_auth(self): response = self.client().get('/movies') self.assertEqual(response.status_code, 401) def test_get_actors(self, token=assistant_token): response = self.client().get('/actors', headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertTrue(len(data['actors'])) def test_get_actors_without_auth(self): response = self.client().get('/actors') self.assertEqual(response.status_code, 401) # POST-methods def test_try_to_create_actor_without_auth(self): info = new_actor_info response = self.client().post('/actors', json=info) self.assertEqual(response.status_code, 401) def test_try_to_create_actor_without_permission(self, token=assistant_token): info = new_actor_info response = self.client().post('/actors', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 403) self.assertEqual(data['message'], 'Access denied') def test_try_to_create_actor_with_empty_values(self, token=director_token): info = {'name': ''} response = self.client().post('/actors', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 400) self.assertEqual(data['message'], 'Bad request') def test_create_actor(self, token=director_token): info = new_actor_info response = self.client().post('/actors', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertEqual(info['id'], data['actor']['id']) self.assertEqual(info['name'], data['actor']['name']) self.assertEqual(info['gender'], data['actor']['gender']) def test_try_to_create_movie_without_auth(self): info = new_movie_info response = self.client().post('/movies', json=info) self.assertEqual(response.status_code, 401) def test_try_to_create_movie_without_permission(self, token=assistant_token): info = new_movie_info response = self.client().post('/movies', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 403) self.assertEqual(data['message'], 'Access denied') def test_try_to_create_movie_with_empty_values(self, token=producer_token): info = {'title': ''} response = self.client().post('/movies', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 400) self.assertEqual(data['message'], 'Bad request') def test_create_movie(self, token=producer_token): info = new_movie_info response = self.client().post('/movies', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertEqual(info, data['movie']) # PATCH-methods def test_try_to_edit_actor_without_auth(self): info = edited_actor_info response = self.client().patch('/actors/3', json=info) self.assertEqual(response.status_code, 401) def test_try_to_edit_actor_without_permission(self, token=assistant_token): info = edited_actor_info response = self.client().patch('/actors/3', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 403) self.assertEqual(data['message'], 'Access denied') def test_edit_actor(self, token=director_token): info = edited_actor_info response = self.client().patch('/actors/3', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertEqual(info['name'], data['actor']['name']) self.assertEqual(info['movie_id'], data['actor']['movie_id']) def test_try_to_edit_movie_without_auth(self): info = edited_movie_info response = self.client().patch('/movies/3', json=info) self.assertEqual(response.status_code, 401) def test_try_to_edit_movie_without_permission(self, token=assistant_token): info = edited_movie_info response = self.client().patch('/movies/3', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 403) self.assertEqual(data['message'], 'Access denied') def test_edit_movie(self, token=director_token): info = edited_movie_info response = self.client().patch('/movies/3', json=info, headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertEqual(info['title'], data['movie']['title']) # DELETE-methods def test_try_to_delete_actor_without_auth(self): response = self.client().delete('/actors/10') self.assertEqual(response.status_code, 401) def test_try_to_delete_nonexistent_actor(self, token=director_token): response = self.client().delete('/actors/100', headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 404) self.assertEqual(data['message'], 'Not found') def test_try_to_delete_actor_without_permission(self, token=assistant_token): response = self.client().delete('/actors/100', headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 403) self.assertEqual(data['message'], 'Access denied') def test_delete_actor(self, token=director_token): response = self.client().delete('/actors/10', headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertTrue(len(data['deleted'])) def test_try_to_delete_movie_without_auth(self): response = self.client().delete('/movies/10') self.assertEqual(response.status_code, 401) def test_try_to_delete_nonexistent_movie(self, token=producer_token): response = self.client().delete('/movies/100', headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 404) self.assertEqual(data['message'], 'Not found') def test_try_to_delete_movie_without_permission(self, token=director_token): response = self.client().delete('/movies/100', headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 403) self.assertEqual(data['message'], 'Access denied') def test_delete_movie(self, token=producer_token): response = self.client().delete('/movies/10', headers=self.set_headers(token)) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertTrue(len(data['deleted'])) if __name__ == '__main__': unittest.main() <file_sep># Casting Agency API Casting Agency API is an app, provided to simplify process of creating movies and managing and assigning actors to those movies The application can: 1. Create, edit, delete and retrieve movies records 2. Create, edit, delete and retrieve actors records 3. Link actors to movies records The app is hosted on https://casitng-agency-api.herokuapp.com/ ## ROLES #### Casting Assistant - Can view actors and movies #### Casting Director - All permissions a Casting Assistant has - Add or delete an actor from the database - Modify actors or movies #### Executive Producer - All permissions a Casting Director has - Add or delete a movie from the database To check roles and endpoints use test tokens from `.env` ## ENDPOINTS #### GET '/movies' - Fetches a list of movies objects - Requires authorisation: yes - Request arguments: None - Returns: 'movies' an array of objects 'success' a boolean value, which depends on successfulness of the request ``` { "movies": [ { "id": 6, "release_date": "2016-08-31", "title": "La La Land" } ], "success": true } ``` #### GET '/actors' - Fetches a list of actors objects - Requires authorisation: yes - Request arguments: None - Returns: 'actors' an array of objects 'success' a boolean value, which depends on successfulness of the request ``` { "actors": [ { "age": 41, "gender": "male", "id": 7, "movie_id": null, "name": "<NAME>" } ], "success": true } ``` #### POST '/actors' - Creates new actor's record - Requires authorisation: yes - Request Arguments: name (actor's name, string - required argument), age (actor's age, integer), gender (actor's gender, string) - Returns: 'actor' an array of a created object 'success' a boolean value, which depends on successfulness of the request #### POST '/movies' - Creates new movie record - Requires authorisation: yes - Request Arguments: title (movies name, string - required argument), release_date (movies release date, datetime object or string) - Returns: 'movie' an array of a created object 'success' a boolean value, which depends on successfulness of the request #### PATCH '/movies/<int:movie_id>' - Edits movies record - Requires authorisation: yes - Request Arguments: title (movies title, string), release_date (movies release date, datetime object or string). All arguments are not required - Returns: 'movie' an array of an edited object 'success' a boolean value, which depends on successfulness of the request #### PATCH '/actors/<int:actor_id>' - Edits actor's record - Requires authorisation: yes - Request Arguments: name (actor's name, string), age (actor's age, integer), gender (actor's gender, string), movie_id (movie_id for which the actor is assigned). All arguments are not required - Returns: 'actor' an array of an edited object 'success' a boolean value, which depends on successfulness of the request #### DELETE '/actors/<int:actor_id>' - Deletes actor by id - Requires authorisation: yes - Request Arguments: actor_id (required) - Returns: 'deleted' an array of a deleted object 'success' a boolean value, which depends on successfulness of the request ``` "deleted": [ { "age": 33, "gender": null, "id": 1, "movie_id": null, "name": "<NAME>" } ``` #### DELETE '/movies/<int:movie_id>' - Deletes movie by id - Requires authorisation: yes - Request Arguments: movie_id (required) - Returns: 'deleted' an array of a deleted object 'success' a boolean value, which depends on successfulness of the request ## To run the app locally: 1. Create and activate virtualenv ``` python3 -m venv venv source venv/bin/activate ``` 2. Install dependencies ``` pip install -r requirements.txt ``` 3. Setup a database ``` createdb agency psql agency < database/agency.psql ``` 4. Run the server in debug mode (will restart on each code change) ``` export FLASK_DEBUG=True flask run ``` 5. Navigate to http://localhost:5000/ 6. To run the tests, execute ``` dropdb agency_test createdb agency_test psql agency_test < database/agency.psql python test_app.py ``` <file_sep>new_actor_info = { 'id': 10, 'name': '<NAME>', 'gender': 'female' } edited_actor_info = { 'name': '<NAME>', 'movie_id': 3 } new_movie_info = { 'id': 10, 'title': 'James Bond Adventures XXVI', 'release_date': '2025-05-01' } edited_movie_info = { 'title': 'Jurassic Park II' }
758b745c838e80c0e6c54e0652e1a4e0d71501d3
[ "Markdown", "Python", "Text" ]
7
Python
aldoha/casting-agency-api
13f155cad6d651714c227699d9f81859f838d7bd
8ba09bca00ff38f925d62e8891128b5068271a0f
refs/heads/main
<file_sep>#include<stdio.h> #include<dirent.h> #include<string.h> #include<sys/stat.h> #include<sys/types.h> #include<time.h> #include<ctype.h> #include<stdlib.h> extern int errno; int main(int argc, char *argv[]){ errno = 0; char *flag = argv[1], *args = argv[2]; if(strlen(args) == 0){ printf("%s\n", "File name not given"); return 0; } if(strlen(flag) == 0){ int check = mkdir(args, 0); if(check == -1){ perror("Error"); } else{ chmod(args, 0777); } } else if(strlen(flag) == 1){ if(flag[0] == 'v'){ int check = mkdir(args, 0); if(check == -1){ perror("Error"); } else{ chmod(args, 0777); printf("Created directory \"%s\"\n", args); } } else if(flag[0] == 'm'){ int ptr = 0, ptr_mode; char *mode = (char*)malloc(100*sizeof(char)); for(int i = 0; args[i] != '\0' && args[i] != ' '; i++){ mode[i] = args[i]; if(isdigit(mode[i]) == 0){ printf("Invalid flag value\n"); return 0; } ptr++; mode[i + 1] = '\0'; } int len = (int) strlen(mode); mode_t sum = 0; for(int i = 0; i < len; i++){ int p = 1; for(int j = 0; j < len - i - 1; j++){ p *= 8; } sum += p*(mode[i] - '0'); } char *filename = (char*)malloc(100*sizeof(char)); while(args[ptr] != '\0' && args[ptr] == ' ') ptr++; int ptr2 = 0; for(int i = ptr; args[i] != '\0'; i++){ filename[ptr2] = args[i]; ptr2++; } sum = strtol(mode, NULL, 8); int check = mkdir(filename, 0); if(check == -1){ perror("Error"); } else{ chmod(filename, sum); } } else{ printf("Invalid flag\n"); } } else{ printf("%s\n", "Invalid flag"); } return 0; } //end<file_sep>#include<stdio.h> #include<dirent.h> #include<string.h> #include<sys/stat.h> #include<sys/types.h> #include<time.h> #include<stdlib.h> #define si 200 int main(int argc, char *argv[]){ char *flag = argv[1], *args = argv[2]; if(strlen(args) == 0){ if(strlen(flag) == 0){ char *buffer = (char*)malloc(si*sizeof(char)); while(strcmp(buffer, "quit\n") != 0){ fgets(buffer, si, stdin); printf("%s", buffer); } } else if(strlen(flag) == 1){ // TODO handle flags if(flag[0] == 'b'){ int line_no = 1; char *buffer = (char*)malloc(si*sizeof(char)); while(strcmp(buffer, "quit\n") != 0){ fgets(buffer, si, stdin); if(strcmp(buffer, "\n") != 0){ printf(" %d %s", line_no, buffer); line_no++; } else{ printf("\n"); } } } else if(flag[0] == 'n'){ int line_no = 1; char *buffer = (char*)malloc(si*sizeof(char)); while(strcmp(buffer, "quit\n") != 0){ fgets(buffer, si, stdin); printf(" %d %s", line_no, buffer); line_no++; } } } else{ printf("%s\n", "Invalid flag"); } } else{ FILE *file = fopen(args, "r"); if(file == NULL){ printf("%s\n", "No such file"); return 0; } if(strlen(flag) == 0){ char *buffer = (char*)malloc(si*sizeof(char)); while(fgets(buffer, si, file)){ printf("%s", buffer); } } else if(strlen(flag) == 1){ if(flag[0] == 'b'){ int line_no = 1; char *buffer = (char*)malloc(si*sizeof(char)); while(fgets(buffer, si, file)){ if(strcmp(buffer, "\n") != 0){ printf(" %d %s", line_no, buffer); line_no++; } else{ printf("\n"); } } } else if(flag[0] == 'n'){ int line_no = 1; char *buffer = (char*)malloc(si*sizeof(char)); while(fgets(buffer, si, file)){ printf(" %d %s", line_no, buffer); line_no++; } } } else{ printf("%s\n", "Invalid flag"); } } return 0; } //end<file_sep>#include<stdio.h> #include<unistd.h> #include<limits.h> #include<stdlib.h> #include<string.h> #include<ctype.h> #include<unistd.h> #include<fcntl.h> #define si 300 char cur_dir[PATH_MAX]; char* history_dir; char* ls_dir; char* date_dir; char* cat_dir; char* mkdir_dir; char* rm_dir; extern int errno; void get_everything(char* input_line, char* command, char* flag, char* args){ int ptr = 0, ptr_command = 0, ptr_flag = 0, ptr_args = 0; if(strcmp(input_line, "") == 0){ return; } while(input_line[ptr] != '\0' && input_line[ptr] == ' ') ptr++; // Remove leading spaces while(input_line[ptr] != '\0' && input_line[ptr] != ' '){ // Retrieve command command[ptr_command] = input_line[ptr]; ptr++; ptr_command++; } command[ptr_command] = '\0'; if(ptr_command > 0){ if(command[ptr_command - 1] == '\n'){ command[ptr_command - 1] = '\0'; } } for(int i = 0; command[i] != '\0'; i++){ command[i] = tolower(command[i]); } while(input_line[ptr] != '\0' && input_line[ptr] == ' ') ptr++; // Remove middle spaces if(input_line[ptr] == '\0'){ return; } if(input_line[ptr] == '-'){ ptr++; while(input_line[ptr] != '\0' && input_line[ptr] != ' '){ // Retrieve flag flag[ptr_flag] = input_line[ptr]; ptr++; ptr_flag++; } } while(input_line[ptr] != '\0' && input_line[ptr] == ' ') ptr++; // Remove middle spaces while(input_line[ptr] != '\0'){ // Retrieve args args[ptr_args] = input_line[ptr]; ptr++; ptr_args++; } if(ptr_args > 0){ if(args[ptr_args - 1] == '\n'){ args[ptr_args - 1] = '\0'; } } if(ptr_flag > 0){ if(flag[ptr_flag - 1] == '\n'){ flag[ptr_flag - 1] = '\0'; } } } void print_init(){ char dir[PATH_MAX]; getcwd(dir, sizeof(dir)); printf("%s >>> ", dir); } void set_paths(){ history_dir = "/Users/parth_mac/Desktop/parth_19069/OS_2/history.txt"; ls_dir = "/Users/parth_mac/Desktop/parth_19069/OS_2/ls"; date_dir = "/Users/parth_mac/Desktop/parth_19069/OS_2/date"; cat_dir = "/Users/parth_mac/Desktop/parth_19069/OS_2/cat"; mkdir_dir = "/Users/parth_mac/Desktop/parth_19069/OS_2/mkdir"; rm_dir = "/Users/parth_mac/Desktop/parth_19069/OS_2/rm"; } void external_commands(char* command, char* flag, char* args){ int child_id; if((child_id = fork()) == 0){ // Child process: handle all external commands here if(strcmp(command, "ls") == 0){ execl(ls_dir, command, flag, args, NULL); } else if(strcmp(command, "date") == 0){ execl(date_dir, command, flag, args, NULL); } else if(strcmp(command, "cat") == 0){ execl(cat_dir, command, flag, args, NULL); } else if(strcmp(command, "mkdir") == 0){ execl(mkdir_dir, command, flag, args, NULL); } else if(strcmp(command, "rm") == 0){ execl(rm_dir, command, flag, args, NULL); } else{ printf("Invalid command\n"); } exit(0); } else{ // Parent process int status; waitpid(child_id, &status, 0); } } int main(){ set_paths(); while(1){ print_init(); char *input_line = (char*)malloc(si*sizeof(char)); fgets(input_line, si, stdin); char *command, *flag, *args; command = (char*)malloc(si*sizeof(char)); flag = (char*)malloc(si*sizeof(char)); args = (char*)malloc(si*sizeof(char)); get_everything(input_line, command, flag, args); FILE *history = fopen(history_dir, "a+"); if(history == NULL){ printf("%s\n", "Error: Couldn't load history."); } else{ fprintf(history, "%s", input_line); fclose(history); } // printf("%s %s %s\n", command, flag, args); if(strcmp(command, "cd") == 0){ // cd command if(strlen(flag) > 1){ printf("Invalid flags\n"); continue; } if(strlen(flag) == 0){ int check; if(strlen(args) == 0) { chdir("/Users/parth_mac"); check = 0; } else check = chdir(args); if(check == -1){ perror("Error"); } continue; } else if(strlen(flag) == 1){ if(flag[0] == 'h'){ FILE *help = fopen("/Users/parth_mac/desktop/parth_19069/OS_2/cd_help.txt", "r"); if(help == NULL){ printf("No help file found\n"); continue; } char *buf = (char*)calloc(500, sizeof(char)); while(fgets(buf, 500, help)){ printf("%s", buf); } printf("\n"); fclose(help); } else if(flag[0] == 'P'){ int check; if(strlen(args) == 0) { chdir("/Users/parth_mac"); check = 0; } else check = chdir(args); if(check == -1){ perror("Error"); } continue; } else{ printf("Invalid flag\n"); } } } if(strcmp(command, "pwd") == 0){ // pwd command if(strlen(args) != 0){ printf("pwd has no arguments\n"); continue; } if(strlen(flag) > 1){ printf("%s\n", "Error: Invalid flag"); } else if(strlen(flag) == 1){ if(flag[0] == 'P'){ char dir[PATH_MAX]; if(getcwd(dir, sizeof(dir)) == NULL){ perror("Error"); } else printf("%s\n", dir); } else if(flag[0] == 'h'){ FILE *pwd = fopen("/Users/parth_mac/Desktop/parth_19069/OS_2/pwd_help.txt", "r"); if(pwd == NULL){ printf("No help file found\n"); continue; } char *buf = (char*)calloc(500, sizeof(char)); while(fgets(buf, 500, pwd)){ printf("%s", buf); } printf("\n"); fclose(pwd); } else{ printf("Invalid flag\n"); } } else{ char dir[PATH_MAX]; if(getcwd(dir, sizeof(dir)) == NULL){ perror("Error"); } else printf("%s\n", dir); } continue; } if(strcmp(command, "echo") == 0){ // echo command int len = 0; for(int i = 0; args[i] != '\0'; i++){ len++; } len--; while(len >= 0 && args[len] == ' '){ args[len] = '\0'; len--; } if(strlen(flag) == 0){ for(int i = 0; args[i] != '\0'; i++){ if((i == 0 && args[i] == '"') || (args[i + 1] == '\0' && args[i] == '"')) continue; printf("%c", args[i]); } printf("\n"); } else if(strlen(flag) == 1){ // flag -n if(flag[0] == 'n'){ for(int i = 0; args[i] != '\0'; i++){ if((i == 0 && args[i] == '"') || (args[i + 1] == '\0' && args[i] == '"')) continue; printf("%c", args[i]); } } else if(flag[0] == 'e'){ // flag -e char *targs = (char*)malloc(si*sizeof(char)); int ptr = 0; for(int i = 0; args[i] != '\0'; i++){ if((i == 0 && args[i] == '"') || (args[i + 1] == '\0' && args[i] == '"')) continue; if(args[i] == '\\' && args[i + 1] == 'n'){ targs[ptr] = '\n'; i++; } else targs[ptr] = args[i]; ptr++; } printf("%s\n", targs); } else{ printf("%s\n", "Error: Invalid flag"); } } else{ printf("%s\n", "Error: Invalid flag"); } continue; } if(strcmp(command, "history") == 0){ // History command if(strlen(flag) == 0){ // Display history if(strlen(args) != 0){ printf("%s\n", "Error: Invalid command"); continue; } FILE *history = fopen(history_dir, "r"); if(history == NULL){ printf("%s\n", "Error: Couldn't load history."); continue; } char *data = (char*)malloc(si*sizeof(char)); while(fgets(data, si, history) != NULL){ printf("%s", data); } fclose(history); } else if(strlen(flag) == 1){ // Clear history if(flag[0] == 'c'){ if(strlen(args) != 0){ printf("%s\n", "Error: Invalid command"); continue; } FILE *history = fopen(history_dir, "w"); if(history == NULL){ printf("%s\n", "Error: Couldn't load history."); continue; } char *data = (char*)malloc(si*sizeof(char)); fprintf(history, ""); fclose(history); } else if(flag[0] == 's'){ FILE *history = fopen(history_dir, "a+"); if(history == NULL){ printf("%s\n", "Error: Couldn't load history."); continue; } char *add = (char*)malloc(si*sizeof(char)); int ptr = 0; for(int i = 0; args[i] != '\0'; i++){ if(args[i] == '"') continue; add[ptr] = args[i]; ptr++; } add[ptr] = '\n'; fprintf(history, "%s", add); fclose(history); } } continue; } if(strcmp(command, "exit") == 0){ if(strlen(args) != 0 || strlen(flag) != 0){ printf("%s\n", "Error: Invalid command"); continue; } break; } else{ external_commands(command, flag, args); } } } //end<file_sep>#include<stdio.h> #include<dirent.h> #include<string.h> #include<sys/stat.h> #include<sys/types.h> #include<time.h> #include<unistd.h> extern int errno; int main(int argc, char *argv[]){ errno = 0; char *flag = argv[1], *args = argv[2]; struct stat file_stat; if(strlen(args) == 0){ printf("%s\n", "File name not given"); return 0; } if(strlen(flag) == 0){ int check = unlink(args); if(check == -1){ perror("Error"); } } else if(strlen(flag) == 1){ if(flag[0] == 'd'){ int check = remove(args); if(check == -1){ perror("Error"); } } else if(flag[0] == 'v'){ int check = unlink(args); if(check == -1){ perror("Error"); } else{ printf("Removed file %s\n", args); } } else{ printf("Invalid flag\n"); } } else{ printf("%s\n", "Invalid flag"); } return 0; } //end<file_sep>run: shell ls date cat mkdir rm ./shell shell: ls date cat mkdir rm gcc-10 shell.c -o shell ls: ls.c gcc-10 ls.c -o ls date: date.c gcc-10 date.c -o date cat: cat.c gcc-10 cat.c -o cat mkdir: mkdir.c gcc-10 mkdir.c -o mkdir rm: cat.c gcc-10 rm.c -o rm<file_sep>#include<stdio.h> #include<dirent.h> #include<string.h> #include<sys/stat.h> #include<sys/types.h> #include<time.h> int main(int argc, char *argv[]){ char *flag = argv[1], *args = argv[2]; if(strlen(args) != 0){ printf("%s\n", "Error: Date has no arguments"); return 0; } if(strlen(flag) == 0){ time_t t = time(NULL); struct tm *tm = localtime(&t); char s[100]; strftime(s, sizeof(s), "%a %b %d %T %Z %Y", tm); printf("%s\n", s); } else if(strlen(flag) == 1){ if(flag[0] == 'u'){ time_t t = time(NULL); struct tm *tm = gmtime(&t); char s[100]; strftime(s, sizeof(s), "%a %b %d %T %Z %Y", tm); printf("%s\n", s); } else if(flag[0] == 'R'){ time_t t = time(NULL); struct tm *tm = gmtime(&t); char s[100]; strftime(s, sizeof(s), "%a, %d %b %Y %T %z", tm); printf("%s (UTC)\n", s); } else{ printf("Invalid flag\n"); } } return 0; } //end<file_sep>#include<stdio.h> #include<dirent.h> #include<string.h> #include<sys/stat.h> #include<sys/types.h> #include<time.h> #include<stdlib.h> extern int errno; int main(int argc, char *argv[]){ struct dirent *entry; struct stat file_stat; char *flag = argv[1], *args = argv[2]; DIR *dir; if(strlen(args) == 0) dir = opendir("."); else dir = opendir(args); if(dir == NULL){ dir = opendir("."); while((entry = readdir(dir))){ if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; if(strcmp(entry->d_name, args) == 0){ printf("%s\n", args); return 0; } } printf("%s\n", "No such directory"); return 0; } if(strlen(flag) > 1){ printf("%s\n", "Invalid flag"); return 0; } if(strlen(flag) == 0){ while((entry = readdir(dir))){ if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; printf("%s\n", entry->d_name); } printf("\n"); return 0; } else{ if(flag[0] == 'a'){ while((entry = readdir(dir))){ printf("%s\n", entry->d_name); } printf("\n"); } else if(flag[0] == 'l'){ while((entry = readdir(dir))){ if(strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; // printf("%d\n", entry->d_type); char * temp = (char*)malloc(200*sizeof(char)); if(strlen(args) != 0)strcpy(temp, args); else strcpy(temp, "."); strcat(temp, "/"); strcat(temp, entry->d_name); int check = stat(temp, &file_stat); if(check == -1){ perror("Error"); return 0; } printf((S_ISDIR(file_stat.st_mode)) ? "d" : "-"); printf((file_stat.st_mode & S_IRUSR) ? "r" : "-"); printf((file_stat.st_mode & S_IWUSR) ? "w" : "-"); printf((file_stat.st_mode & S_IXUSR) ? "x" : "-"); printf((file_stat.st_mode & S_IRGRP) ? "r" : "-"); printf((file_stat.st_mode & S_IWGRP) ? "w" : "-"); printf((file_stat.st_mode & S_IXGRP) ? "x" : "-"); printf((file_stat.st_mode & S_IROTH) ? "r" : "-"); printf((file_stat.st_mode & S_IWOTH) ? "w" : "-"); printf((file_stat.st_mode & S_IXOTH) ? "x" : "-"); printf(" "); printf(" %d ", file_stat.st_uid); printf(" %d ", file_stat.st_gid); printf(" %lld ", file_stat.st_size); char str[32]; strftime(str, sizeof(str), "%c", localtime(&file_stat.st_atime)); printf(" %s ", str); printf("%s\n", entry->d_name); } } else{ printf("%s\n", "Invalid flag"); } return 0; } } // end<file_sep># BashShell Created a mini shell for linux. It can carry out basic commands like echo, cat, cd, mkdir, rmdir, etc (5 internal + 5 external commands with 2 options for each command). The shell is written in C using system calls to execute the commands. Note that you may need to change some hard-coded paths in source code for some commands to work.
5e72521652345fb08fffc2d0e81eb6f7ca9feed0
[ "Markdown", "C", "Makefile" ]
8
C
parth19069/BashShell
eaf94c7913a5820e2e8b51d52e115460ab101ffd
136d419e09cf7c9717c31848b31881511722f438
refs/heads/master
<repo_name>davidgonsaga/rateable<file_sep>/src/Models/VoteStatus.php <?php namespace Webeleven\Rateable\Models; abstract class VoteStatus { const NOT_VOTED = 0; const POSITIVE_VOTED = 1; const NEGATIVE_VOTED = 2; }<file_sep>/src/Services/RateService.php <?php namespace Webeleven\Rateable\Services; use Webeleven\Rateable\Interfaces\RateRepositoryInterface; use Webeleven\Rateable\Interfaces\RatingOwner; use Webeleven\Rateable\Interfaces\UserProvider; class RateService { private $rateRepository; private $userProvider; public function __construct(RateRepositoryInterface $rateRepository, UserProvider $userProvider) { $this->rateRepository = $rateRepository; $this->userProvider = $userProvider; } public function save($data) { if (! $this->hasOwner($data)) { $data = $this->applyOwnerData($data); } return $this->rateRepository->save($data); } private function hasOwner(array $data) { return isset($data['owner_id']) || isset($data['owner_name']) || isset($data['owner_email']); } private function applyOwnerData($data) { $user = $this->userProvider->getUser(); if (! $user instanceof RatingOwner) { throw new \Exception('User must implement RatingOwner interface'); } $data['owner_id'] = ($user) ? $user->getId() : ''; $data['owner_name'] = ($user) ? $user->getName() : 'Anônimo'; $data['owner_email'] = ($user) ? $user->getEmail() : ''; return $data; } public function update($rate_id, array $data = []) { return $this->rateRepository->update($rate_id, $data); } public function delete($rate_id) { return $this->rateRepository->delete($rate_id); } public function find($rate_id) { return $this->rateRepository->find($rate_id); } public function getAll($limit = null, $skip = 0) { return $this->rateRepository->getAll($limit, $skip); } public function getAllByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0) { return $this->rateRepository->getAllByResourceIdAndType($resource_id, $resource_type, $limit, $skip); } public function getRatePointsDiscriminated($resource_id, $resource_type) { return $this->rateRepository->getRatePointsDiscriminated($resource_id, $resource_type); } }<file_sep>/src/Controllers/VoteController.php <?php namespace Webeleven\Rateable\Controllers; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\Cookie; use Illuminate\Support\Facades\Response; use Webeleven\Rateable\Services\VoteService; class VoteController extends Controller { private $voteService; public function __construct(VoteService $voteService) { $this->voteService = $voteService; } public function increasePositiveVotes($comment_id, Request $request) { $key = $comment_id . '_positive_vote'; if (! $request->cookie($key)) { try { $this->voteService->increasePositiveVotes($comment_id); return Response::json([ 'actionWasPerformed' => 1 ])->withCookie(cookie()->forever($key, true)); } catch (\Exception $e) { return Response::json([ 'message' => $e->getMessage() ]); } } return Response::json([ 'actionWasPerformed' => 2 ]); } public function decreasePositiveVotes($comment_id, Request $request) { $key = $comment_id . '_positive_vote'; if ($request->cookie($key)) { try { $this->voteService->decreasePositiveVotes($comment_id); return Response::json([ 'actionWasPerformed' => 1 ])->withCookie(Cookie::forget($key)); } catch (\Exception $e) { return Response::json([ 'message' => $e->getMessage() ]); } } return Response::json([ 'actionWasPerformed' => 2 ]); } public function increaseNegativeVotes($comment_id, Request $request) { $key = $comment_id . '_negative_vote'; if (! $request->cookie($key)) { try { $this->voteService->increaseNegativeVotes($comment_id); return Response::json([ 'actionWasPerformed' => 1 ])->withCookie(cookie()->forever($key, true)); } catch (\Exception $e) { return Response::json([ 'message' => $e->getMessage() ]); } } return Response::json([ 'actionWasPerformed' => 2 ]); } public function decreaseNegativeVotes($comment_id, Request $request) { $key = $comment_id . '_negative_vote'; if ($request->cookie($key)) { try { $this->voteService->decreaseNegativeVotes($comment_id); return Response::json([ 'actionWasPerformed' => 1 ])->withCookie(Cookie::forget($key)); } catch (\Exception $e) { return Response::json([ 'message' => $e->getMessage() ]); } } return Response::json([ 'actionWasPerformed' => 2 ]); } }<file_sep>/src/Controllers/RateController.php <?php namespace Webeleven\Rateable\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Response; use Webeleven\Rateable\Models\RatePublishStatus; use Webeleven\Rateable\Services\RateService; class RateController extends BaseController { private $rateService; public function __construct(RateService $rateService) { $this->rateService = $rateService; } public function save(Request $request) { try { $data = $request->all(); return Response::json($this->rateService->save($data)); } catch (\Exception $e) { return Response::json([ 'message' => $e->getMessage() ], 403); } } public function getAll(Request $request) { $data = $request->all(); $limit = $this->getLimit($data); $skip = $this->getSkip($data); return Response::json($this->rateService->getAll($limit, $skip)); } public function getAllByResourceIdAndType($resource_id, $resource_type, Request $request) { $data = $request->all(); $limit = $this->getLimit($data); $skip = $this->getSkip($data); $rates = $this->rateService->getAllByResourceIdAndType($resource_id, $resource_type, $limit, $skip); return Response::json([ 'rates' => $rates, 'total' => $rates->count() ]); } public function getRatePointsDiscriminated($resource_id, $resource_type) { $ratesDiscriminated = $this->rateService->getRatePointsDiscriminated($resource_id, $resource_type); return Response::json([ 'ratesDiscriminated' => $ratesDiscriminated, 'total' => $ratesDiscriminated->sum('quantity') ]); } } <file_sep>/src/Models/Comment.php <?php namespace Webeleven\Rateable\Models; use Illuminate\Database\Eloquent\Model; class Comment extends Model { protected $table = 'webeleven_comments'; protected $fillable = ['rating_id', 'title', 'description', 'published']; public function rate() { return $this->hasOne(Rate::class, 'id', 'rating_id'); } }<file_sep>/src/Controllers/RateAverageController.php <?php namespace Webeleven\Rateable\Controllers; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\Response; use Webeleven\Rateable\Services\Calculator\RateAverageCalculator; use Webeleven\Rateable\Services\RateService; class RateAverageController extends Controller { private $rateService; private $averageCalculator; public function __construct(RateService $rateService, RateAverageCalculator $averageCalculator) { $this->rateService = $rateService; $this->averageCalculator = $averageCalculator; } public function getOfAllRates() { $rates = $this->rateService->getAll(); return Response::json($this->averageCalculator->getAverageRate($rates)); } public function getByResourceIdAndType($resource_id, $resource_type) { $rates = $this->rateService->getAllByResourceIdAndType($resource_id, $resource_type); return Response::json($this->averageCalculator->getAverageRate($rates)); } }<file_sep>/src/Repositories/BaseRepository.php <?php namespace Webeleven\Rateable\Repositories; abstract class BaseRepository { protected function applyLimitAndOffsetIfNecessary($query, $limit, $skip) { if ($skip > 0) { $query->skip($skip); } if (! empty($limit)) { $query->take($limit); } return $query; } }<file_sep>/src/Models/Rate.php <?php namespace Webeleven\Rateable\Models; use Illuminate\Database\Eloquent\Model; class Rate extends Model { protected $table = 'webeleven_ratings'; protected $fillable = ['resource_id', 'resource_type', 'owner_id', 'owner_name', 'owner_email', 'rating']; public function comments() { return $this->hasMany(Comment::class, 'webeleven_comments.rating_id', 'webeleven_rates.id'); } public function getResourceResolver() { $resolverEntity = config('rateable.resource_resolver'); if (empty($resolverEntity)) { throw new \Exception('Resource Resolver is not valid'); } return app($resolverEntity)->getResolver(); } public function getResource() { $resolver = $this->getResourceResolver(); return $resolver($this); } } <file_sep>/src/Interfaces/VoteRepositoryInterface.php <?php namespace Webeleven\Rateable\Interfaces; interface VoteRepositoryInterface { public function increasePositiveVotes($comment_id); public function decreasePositiveVotes($comment_id); public function increaseNegativeVotes($comment_id); public function decreaseNegativeVotes($comment_id); }<file_sep>/src/Interfaces/RatingOwner.php <?php namespace Webeleven\Rateable\Interfaces; interface RatingOwner { public function getName(); public function getId(); public function getEmail(); }<file_sep>/src/Services/VoteService.php <?php namespace Webeleven\Rateable\Services; use Webeleven\Rateable\Interfaces\VoteRepositoryInterface; class VoteService { private $voteRepository; public function __construct(VoteRepositoryInterface $voteRepository) { $this->voteRepository = $voteRepository; } public function increasePositiveVotes($comment_id) { return $this->voteRepository->increasePositiveVotes($comment_id); } public function decreasePositiveVotes($comment_id) { return $this->voteRepository->decreasePositiveVotes($comment_id); } public function increaseNegativeVotes($comment_id) { return $this->voteRepository->increaseNegativeVotes($comment_id); } public function decreaseNegativeVotes($comment_id) { return $this->voteRepository->decreaseNegativeVotes($comment_id); } }<file_sep>/src/Services/Calculator/RateAverageCalculator.php <?php namespace Webeleven\Rateable\Services\Calculator; use Illuminate\Database\Eloquent\Collection; class RateAverageCalculator { private $totalPoints; private $numberOfRates; public function getAverageRate(Collection $rateCollection) { if ($rateCollection->isEmpty()) { return [ 'average' => 0, 'total' => 0 ]; } $this->numberOfRates = $rateCollection->count(); $this->totalPoints = $rateCollection->sum('rating'); return [ 'average' => $this->calculateAverageRate(), 'total' => $this->numberOfRates ]; } protected function calculateAverageRate() { return round(($this->totalPoints / $this->numberOfRates) * 2) / 2; } }<file_sep>/src/Services/DefaultUserProvider.php <?php namespace Webeleven\Rateable\Services; use Illuminate\Support\Facades\Auth; use Webeleven\Rateable\Interfaces\UserProvider; class DefaultUserProvider implements UserProvider { public function getUser() { return Auth::user(); } }<file_sep>/config/rateable.php <?php return [ 'auth_middleware' => \Webeleven\Rateable\Middleware\DefaultRateableAuth::class, 'user_provider' => \Webeleven\Rateable\Services\DefaultUserProvider::class ];<file_sep>/src/RateableServiceProvider.php <?php namespace Webeleven\Rateable; use Illuminate\Support\ServiceProvider; use Webeleven\Rateable\Interfaces\UserProvider; use Webeleven\Rateable\Middleware\RateableAuth; class RateableServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { if (! $this->app->routesAreCached()) { require __DIR__.'/routes.php'; } $this->publishes([ __DIR__.'/../config/rateable.php' => config_path('rateable.php') ], 'config'); // $this->publishes([ // __DIR__.'/migrations/' => database_path('migrations') // ], 'migrations'); $this->app['router']->middleware('rateable.auth', RateableAuth::class); $this->app->singleton(RateableAuth::class, function () { return $this->app->make($this->app['config']->get('rateable.auth_middleware')); }); $this->app->singleton(UserProvider::class, function () { return $this->app->make($this->app['config']->get('rateable.user_provider')); }); } /** * Register the application services. * * @return void */ public function register() { $this->app->singleton('Webeleven\Rateable\Interfaces\RateRepositoryInterface', 'Webeleven\Rateable\Repositories\RateRepository'); $this->app->singleton('Webeleven\Rateable\Interfaces\CommentRepositoryInterface', 'Webeleven\Rateable\Repositories\CommentRepository'); $this->app->singleton('Webeleven\Rateable\Interfaces\VoteRepositoryInterface', 'Webeleven\Rateable\Repositories\VoteRepository'); } } <file_sep>/src/Repositories/RateRepository.php <?php namespace Webeleven\Rateable\Repositories; use Illuminate\Support\Facades\DB; use Webeleven\Rateable\Models\Rate; use Webeleven\Rateable\Interfaces\RateRepositoryInterface; class RateRepository extends BaseRepository implements RateRepositoryInterface { public function save($data) { return Rate::create($data); } public function update($rate_id, array $data = []) { return !! Rate::where('id', '=', $rate_id)->update($data); } public function delete($rate_id) { return !! Rate::where('id', '=', $rate_id)->delete(); } public function find($rate_id) { return Rate::find($rate_id); } public function getAll($limit = null, $skip = 0) { $query = Rate::query(); $query = $this->applyLimitAndOffsetIfNecessary($query, $limit, $skip); return $query->get(); } public function getAllByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0) { $query = Rate::where('resource_id', '=', $resource_id) ->where('resource_type', '=', $resource_type); $query = $this->applyLimitAndOffsetIfNecessary($query, $limit, $skip); return $query->get(); } public function getRatePointsDiscriminated($resource_id, $resource_type) { return Rate::select(DB::raw('rating, COUNT(id) AS quantity')) ->where('resource_id', '=', $resource_id) ->where('resource_type', '=', $resource_type) ->groupBy('rating')->get(); } }<file_sep>/src/Repositories/CommentRepository.php <?php namespace Webeleven\Rateable\Repositories; use Illuminate\Support\Facades\DB; use Webeleven\Rateable\Interfaces\CommentRepositoryInterface; use Webeleven\Rateable\Models\Comment; use Webeleven\Rateable\Models\CommentPublishStatus; class CommentRepository extends BaseRepository implements CommentRepositoryInterface { public function save($data) { return Comment::create($data); } public function changePublishStatus($resource_id, $publish_status) { return Comment::where('id', '=', $resource_id) ->update([ 'published' => $publish_status ]); } public function delete($comment_id) { return Comment::find($comment_id)->delete(); } public function find($comment_id) { return Comment::with('rate')->where('id', '=', $comment_id)->get(); } public function getAll($limit = null, $skip = 0) { $query = Comment::with('rate'); $query = $this->applyLimitAndOffsetIfNecessary($query, $limit, $skip); return $query->get(); } public function getAllByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0) { $query = Comment::with('rate')->whereHas('rate', function($query) use($resource_id, $resource_type) { $query ->where('resource_id', '=', $resource_id) ->where('resource_type', '=', $resource_type); }); $query = $this->applyLimitAndOffsetIfNecessary($query, $limit, $skip); return $query->get(); } public function getPublishedByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0) { $query = Comment::with('rate')->whereHas('rate', function($query) use($resource_id, $resource_type) { $query ->where('resource_id', '=', $resource_id) ->where('resource_type', '=', $resource_type); })->where('published', CommentPublishStatus::PUBLISHED); $query = $this->applyLimitAndOffsetIfNecessary($query, $limit, $skip); return $query->get(); } public function getUnpublishedByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0) { $query = Comment::with('rate')->whereHas('rate', function($query) use($resource_id, $resource_type) { $query ->where('resource_id', '=', $resource_id) ->where('resource_type', '=', $resource_type); })->where('published', CommentPublishStatus::NOT_PUBLISHED); $query = $this->applyLimitAndOffsetIfNecessary($query, $limit, $skip); return $query->get(); } }<file_sep>/src/routes.php <?php Route::group(['prefix' => 'rateable', 'as' => 'rateable.', 'namespace' => 'Webeleven\\Rateable\\Controllers', 'middleware' => ['rateable.auth']], function () { Route::group(['prefix' => 'ratings', 'as' => 'rating.'], function () { Route::post('/save', 'RateController@save')->name('save'); Route::get('/list', 'RateController@getAll')->name('list'); Route::get('/by-resource/{resource_id}/{resource_type}', 'RateController@getAllByResourceIdAndType'); }); Route::group(['prefix' => 'comments', 'as' => 'comment.'], function () { Route::post('/save', 'CommentController@save')->name('save'); Route::post('/{comment_id}/increase_positives', 'VoteController@increasePositiveVotes'); Route::post('/{comment_id}/decrease_positives', 'VoteController@decreasePositiveVotes'); Route::post('/{comment_id}/increase_negatives', 'VoteController@increaseNegativeVotes'); Route::post('/{comment_id}/decrease_negatives', 'VoteController@decreaseNegativeVotes'); Route::get('/find/{comment_id}', 'CommentController@find'); Route::get('/list', 'CommentController@getAll')->name('list'); Route::get('/by-resource/{resource_id}/{resource_type}', 'CommentController@getAllByResourceIdAndType'); Route::get('/by-resource/{resource_id}/{resource_type}/published', 'CommentController@getPublishedByResourceIdAndType'); Route::get('/by-resource/{resource_id}/{resource_type}/unpublished', 'CommentController@getUnpublishedByResourceIdAndType'); }); Route::group(['prefix' => 'averages', 'as' => 'averages.'], function () { Route::get('/all', 'RateAverageController@getOfAllRates'); Route::get('/by-resource/{resource_id}/{resource_type}', 'RateAverageController@getByResourceIdAndType'); }); Route::group(['prefix' => 'points', 'as' => 'points.'], function () { Route::get('/by-resource/{resource_id}/{resource_type}', 'RateController@getRatePointsDiscriminated'); }); });<file_sep>/src/Services/CommentService.php <?php namespace Webeleven\Rateable\Services; use Webeleven\Rateable\Interfaces\CommentRepositoryInterface; use Webeleven\Rateable\Models\CommentPublishStatus; class CommentService { private $commentRepository; public function __construct(CommentRepositoryInterface $commentRepository) { $this->commentRepository = $commentRepository; } public function save(array $data = []) { return $this->commentRepository->save($data); } public function delete($comment_id) { return $this->commentRepository->delete($comment_id); } public function publish($comment_id) { try { return !! $this->commentRepository->changePublishStatus($comment_id, CommentPublishStatus::PUBLISHED); } catch (\Exception $e) { return $e->getMessage(); } } public function unpublish($comment_id) { try { return !! $this->commentRepository->changePublishStatus($comment_id, CommentPublishStatus::NOT_PUBLISHED); } catch (\Exception $e) { return $e->getMessage(); } } public function find($comment_id) { return $this->commentRepository->find($comment_id); } public function getAll($limit = null, $skip = 0) { return $this->commentRepository->getAll($limit, $skip); } public function getAllByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0) { return $this->commentRepository->getAllByResourceIdAndType($resource_id, $resource_type, $limit, $skip); } public function getPublishedByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0) { $comments = $this->commentRepository->getPublishedByResourceIdAndType($resource_id, $resource_type, $limit, $skip); return $comments; } public function getUnpublishedByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0) { return $this->commentRepository->getUnpublishedByResourceIdAndType($resource_id, $resource_type, $limit, $skip); } }<file_sep>/src/Interfaces/UserProvider.php <?php namespace Webeleven\Rateable\Interfaces; interface UserProvider { public function getUser(); }<file_sep>/src/Interfaces/CommentRepositoryInterface.php <?php namespace Webeleven\Rateable\Interfaces; interface CommentRepositoryInterface { public function save($data); public function delete($comment_id); public function changePublishStatus($resource_id, $publish_status); public function find($comment_id); public function getAll($limit = null, $skip = 0); public function getAllByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0); public function getPublishedByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0); public function getUnpublishedByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0); }<file_sep>/README.md ## Instalação Para instalar, adicione o seguinte trecho de código ems eu composer.json: ```javascript "repositories": [ { "type": "vcs", "url": "https://github.com/Webeleven/rateable" } ], "require": { ... "webeleven/rateable": "v1.0" }, ``` Depois de alterar seu composer.json, adiocione o ServiceProvider do pacote no seu config/app.php conforme a linha abaixo: ```php Webeleven\Rateable\RateableServiceProvider::class, ``` ## Vendor Publish Execute o comando abaixo para transferir as configs e migrations do pacote para seu projeto: ```shell php artisan vendor:publish --provider="Webeleven\Rateable\RateableServiceProvider" ``` ## Migrations Para executar as *migrations* do pacote é necessário executar manualmente no seu console o comando abaixo: ```shell php artisan migrate --path=./vendor/webeleven/rateable/src/migrations ``` ## Middleware e Provider O pacote fornece uma implementação padrão para as middlwares de autenticação e provedor de usuário autenticado do site. Caso haja necessidade, é possível alterar as implementações das interfaces para uma já criada pelo desenvolvedor do site pelo arquivo config/rateable.php: ```php return [ 'auth_middleware' => \Webeleven\Rateable\Middleware\DefaultRateableAuth::class, 'user_provider' => \Webeleven\Rateable\Services\DefaultUserProvider::class ]; ``` ## Path da interface Middleware: ```php Webeleven\Rateable\MiddlewareRateableAuth.php ``` ## Path da interface de Provedor de usuário: ```php Webeleven\Rateable\Interfaces\UserProvider.php ``` <file_sep>/src/Controllers/BaseController.php <?php namespace Webeleven\Rateable\Controllers; use Illuminate\Routing\Controller; abstract class BaseController extends Controller { protected function getLimit($data) { return isset($data['limit']) ? $data['limit'] : null; } protected function getSkip($data) { return isset($data['skip']) ? $data['skip'] : 0; } }<file_sep>/src/Controllers/CommentController.php <?php namespace Webeleven\Rateable\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cookie; use Illuminate\Support\Facades\Response; use Webeleven\Rateable\Models\VoteStatus; use Webeleven\Rateable\Services\CommentService; class CommentController extends BaseController { private $commentService; public function __construct(CommentService $commentService) { $this->commentService = $commentService; } public function save(Request $request) { try { $data = $request->all(); return Response::json($this->commentService->save($data)); } catch (\Exception $e) { return Response::json([ 'message' => $e->getMessage() ]); } } public function find($comment_id) { $comment = $this->commentService->find($comment_id); $comment = $this->applyCommentVoteStatus($comment); return Response::json([ 'comment' => $comment ]); } public function getAll(Request $request) { $data = $request->all(); $limit = $this->getLimit($data); $skip = $this->getSkip($data); $comments = $this->commentService->getAll($limit, $skip); return Response::json([ 'comments' => $comments, 'total' => count($comments) ]); } public function getAllByResourceIdAndType($resource_id, $resource_type, Request $request) { $data = $request->all(); $limit = $this->getLimit($data); $skip = $this->getSkip($data); $comments = $this->commentService->getAllByResourceIdAndType($resource_id, $resource_type, $limit, $skip); return Response::json([ 'comments' => $comments, 'total' => count($comments) ]); } public function getPublishedByResourceIdAndType($resource_id, $resource_type, Request $request) { $data = $request->all(); $limit = $this->getLimit($data); $skip = $this->getSkip($data); $comments = $this->commentService->getPublishedByResourceIdAndType($resource_id, $resource_type, $limit, $skip); $comments = $this->applyCommentVoteStatus($comments); return Response::json([ 'comments' => $comments, 'total' => count($comments) ]); } public function getUnpublishedByResourceIdAndType($resource_id, $resource_type, Request $request) { $data = $request->all(); $limit = $this->getLimit($data); $skip = $this->getSkip($data); $comments = $this->commentService->getUnpublishedByResourceIdAndType($resource_id, $resource_type, $limit, $skip); return Response::json([ 'comments' => $comments, 'total' => count($comments) ]); } private function applyCommentVoteStatus($comments) { foreach ($comments as $comment) { if (Cookie::get($comment->id . '_positive_vote')) { $comment->voted = VoteStatus::POSITIVE_VOTED; } else if (Cookie::get($comment->id . '_negative_vote')) { $comment->voted = VoteStatus::NEGATIVE_VOTED; } else { $comment->voted = VoteStatus::NOT_VOTED; } } return $comments; } }<file_sep>/src/Repositories/VoteRepository.php <?php namespace Webeleven\Rateable\Repositories; use Webeleven\Rateable\Interfaces\VoteRepositoryInterface; use Webeleven\Rateable\Models\Comment; class VoteRepository implements VoteRepositoryInterface { public function increasePositiveVotes($comment_id) { return !! Comment::where('id', '=', $comment_id)->increment('positive_votes'); } public function decreasePositiveVotes($comment_id) { return !! Comment::where('id', '=', $comment_id)->decrement('positive_votes'); } public function increaseNegativeVotes($comment_id) { return !! Comment::where('id', '=', $comment_id)->increment('negative_votes'); } public function decreaseNegativeVotes($comment_id) { return !! Comment::where('id', '=', $comment_id)->decrement('negative_votes'); } }<file_sep>/src/Middleware/DefaultRateableAuth.php <?php namespace Webeleven\Rateable\Middleware; use Closure; class DefaultRateableAuth implements RateableAuth { public function handle($request, Closure $next, $guard = null) { return $next($request); } }<file_sep>/src/Interfaces/RateRepositoryInterface.php <?php namespace Webeleven\Rateable\Interfaces; interface RateRepositoryInterface { public function save($data); public function update($rate_id, array $data = []); public function delete($rate_id); public function find($rate_id); public function getAll($limit = null, $start = 0); public function getAllByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0); public function getRatePointsDiscriminated($resource_id, $resource_type); }<file_sep>/src/Models/CommentPublishStatus.php <?php namespace Webeleven\Rateable\Models; abstract class CommentPublishStatus { const PUBLISHED = 1; const NOT_PUBLISHED = 0; public static function getStatuses() { return [ CommentPublishStatus::PUBLISHED => 'Publicado', CommentPublishStatus::NOT_PUBLISHED => 'Não Publicado' ]; } }<file_sep>/src/migrations/2016_08_05_170900_create_webeleven_comments_table.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateWebelevenCommentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('webeleven_comments', function (Blueprint $table) { $table->increments('id'); $table->integer('rating_id'); $table->string('title', 35); $table->text('description'); $table->integer('positive_votes')->unsigned(); $table->integer('negative_votes')->unsigned(); $table->timestamps(); $table->boolean('published'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('webeleven_comments'); } }
850cd2a65ddaf0d3c29ec0ac80df76f3d1604f92
[ "Markdown", "PHP" ]
29
PHP
davidgonsaga/rateable
2e5b57786d2c7edcc622baab5ca7dd4bbf354f9b
980215291274661e53e2af857bea8820a0c102b2
refs/heads/master
<repo_name>dtaylor73/react-chatlog<file_sep>/src/App.js import React from 'react'; import './App.css'; import chatMessages from './data/messages.json'; import ChatEntry from './components/ChatEntry'; import ChatLog from './components/ChatLog'; const App = () => { console.log(chatMessages); let firstSender = chatMessages[0].sender; let secondSender = chatMessages[1].sender; return ( <div id="App"> <header id="App-header"> <h1>{`Chat between ${firstSender} and ${secondSender}`}</h1> </header> <main> <section className="chat-log"> <ChatLog entries={chatMessages}/> </section> </main> </div> ); }; export default App; <file_sep>/src/components/ChatLog.js import React from 'react'; import './ChatLog.css'; import ChatEntry from './ChatEntry'; const ChatLog = (props) => { const entries = props.entries; const entryComponents = entries.map((entry, i) => { return ( <div className="chat-log"> <ChatEntry entry={entry} key={i}/> </div> ); }); return entryComponents; }; export default ChatLog;
32ee43fafeaf5e18c36756d8e8f31b4fccb8c77b
[ "JavaScript" ]
2
JavaScript
dtaylor73/react-chatlog
bc7ea1169eb52b3ed09f6f97837c21130b9e7e50
3221ab8b8edb07d037cb60fd6ee06efc09d65354
refs/heads/master
<file_sep>You can find me at https://github.com/Haffy/3-3-Compiler # 3<3 Compiler ## A compiler using JS to Cafezinho language. ### To Run be sure that nodejs is installed sudo apt-get install nodejs sudo apt-get install nodejs-legacy sudo apt-get install npm ### Now install jison and used packages npm install jison npm install fs ### Open the dir cd 3-3-Compiler ### To generate grammar.js use jison grammar.jison # To run an example node codegen.js geracaoCodigo/fatorialCorreto.txt * #### This will return the code in JS, then copy the code, you can run this code in https://jsfiddle.net/ , paste the code in the javascript area; * #### Open the browser console with right click anywhere and inspect element, then click in console tab. * #### Now click in run on jsfiddle * #### Now you can cry a lot because we dont have a symbol table yet, all that we do is translate(using a AST - abstract sintax tree), from cafezinho to JavaScript. ## Thanx; kisses; vlw flw. <file_sep>var parser = require('./grammar').parser; if (process.argv.length < 3) { console.log('Usage: node ' + process.argv[1] + ' FILENAME'); process.exit(1); } // Read the file and print its contents. var fs = require('fs'), filename = process.argv[2]; fs.readFile(filename, 'utf8', function(err, program) { if (err) throw err; console.log('\n************************ CODIGO EM CAFEZINHO\n'+program+'\n\n\n\n'); /* programa-node id-node vector-node declfuncvar-node declprog-node intconst-node declvar-node notype-id-node notype-vector-node declfunc-node listaparametros-node nosize-vector-node listaparametroscont-node listadeclvar-node int-node car-node listacomando-nodew comando-vazio-node comando-expr-node comando-retorne-node comando-leia-node comando-escreva-node comando-novalinha-node comando-seentao-node comando-seentaosenao comando-enquanto-node assignexpr-node assignexpr-vector-node or-node and-node equals-node dif-node 'less-node' 'greater-node' 'greater-equals-node' 'less-equals-node' 'plus-node' 'minus-node' 'multiplication-node' 'division-node' 'modulus-node' 'negation-node' 'no-node' 'access-vector-node' 'function-node' access-vector-node' notype-id-node' 'string-node' 'listexpr-node' */ function main() { var ast = parser.parse(program); console.log('#################### ARVORE SINTATICA ABSTRATA\n\n'); console.log(ast); console.log('\n\n\n') // console.log(ast) var source = codegen(ast); console.log('##################### CODIGO EM JS\n\n'+source+'\n\n'); } function codegen(ast) { if (ast) switch (ast[0]) { case 'programa-node': return codegen(ast[2]) + '\nmain =function()' + codegen(ast[3]) + '\nmain(); ' case 'id-node': return "var " + ast[1].name; case 'vector-node': return "var " + ast[1].name + "= new Array(" + codegen(ast[1].size) + ")"; case 'declfuncvar-node': return codegen(ast[3]) + codegen(ast[4]) + '\n' + codegen(ast[5]); case 'declprog-node': return codegen(ast[2]) + '\n'; case 'intconst-node': return ast[1].val; case 'declvar-node': return ' , ' + codegen(ast[2]) + codegen(ast[3]); case 'notype-id-node': return ast[1].name; case 'notype-vector-node': return ast[1].name + "= new Array(" + codegen(ast[1].size) + ")"; case 'declfunc-node': return '=function(' + codegen(ast[2]) + ')' + codegen(ast[3]); case 'listaparametros-node': return codegen(ast[2]); case 'listaparametroscont-node': return codegen(ast[2]) + ' , ' + codegen(ast[3]); case 'nosize-vector-node': return ast[1].name; case 'bloco-listacomando-node': return '{\n' + codegen(ast[2]) + '\n' + codegen(ast[3]) + '\n}\n'; case 'bloco-node': return '{\n' + codegen(ast[2]) + '\n}\n'; case 'listadeclvar-node': return codegen(ast[2]) + ' ' + codegen(ast[3]) + ';\n' + codegen(ast[4]); case 'comando-node': return codegen(ast[2]) + ';\n'; case 'listacomando-node': return codegen(ast[2]) + ' ' + codegen(ast[3]); case 'intconst-node': return ast[1].val; case 'carconst-node': return ast[1].val; case 'comando-vazio-node': return ';'; case 'comando-expr-node': return codegen(ast[2]) + ';\n'; case 'comando-retorne-node': return 'return ' + codegen(ast[2]); case 'comando-leia-node': return codegen(ast[2]) + '=parseInt(prompt());\n'; case 'comando-escreva-node': return 'console.log(' + codegen(ast[2]) + ');\n'; case 'comando-novalinha-node': return ' '; case 'comando-seentao-node': return 'if(' + codegen(ast[2]) + '){\n' + codegen(ast[3]) + '}\n'; case 'comando-seentaosenao': return 'if(' + codegen(ast[2]) + '){\n' + codegen(ast[3]) + '}\nelse{ ' + codegen(ast[4]) + '}\n'; case 'comando-enquanto-node': return 'while(' + codegen(ast[2]) + ')' + codegen(ast[3]) + '\n'; case 'assignexpr-node': return codegen(ast[2]) + ' = ' + codegen(ast[3]); case 'assignexpr-vector-node': return codegen(ast[2]) + '[' + codegen(ast[3]) + '] = ' + codegen(ast[4]); case 'or-node': return codegen(ast[2]) + ' || ' + codegen(ast[3]); case 'and-node': return codegen(ast[2]) + ' && ' + codegen(ast[3]); case 'equals-node': return codegen(ast[2]) + ' == ' + codegen(ast[3]); case 'dif-node': return codegen(ast[2]) + ' != ' + codegen(ast[3]); case 'less-node': return codegen(ast[2]) + ' < ' + codegen(ast[3]); case 'greater-node': return codegen(ast[2]) + ' > ' + codegen(ast[3]); case 'greater-equals-node': return codegen(ast[2]) + ' >= ' + codegen(ast[3]); case 'less-equals-node': return codegen(ast[2]) + ' <= ' + codegen(ast[3]); case 'plus-node': return codegen(ast[2]) + ' + ' + codegen(ast[3]); case 'minus-node': return codegen(ast[2]) + ' - ' + codegen(ast[3]); case 'multiplication-node': return codegen(ast[2]) + ' * ' + codegen(ast[3]); case 'division-node': return codegen(ast[2]) + ' / ' + codegen(ast[3]); case 'modulus-node': return codegen(ast[2]) + ' % ' + codegen(ast[3]); case 'negation-node': return '-' + codegen(ast[2]); case 'no-node': return '!' + codegen(ast[2]); case 'access-vector-node': return ast[1].name + '[' + codegen(ast[1].position) + ']'; case 'function-node': return ast[1].name + '()'; case 'function-params-node': return ast[1].name + '(' + codegen(ast[2]) + ')'; case 'string-node': return ast[1].text; case 'listexpr-node': return codegen(ast[2]) + ' , ' + codegen(ast[3]); case 'null': return ''; case 'comando-expr-vector-node': return codegen(ast[2]); default: return 'Unknown statement/expression: ' + ast[0]; } } function codegenList(list) { return list.reduce(function(prev, curr) { return prev + codegen(curr); }, ''); } main(); });
2507ee1e49ad004246485379967ef74449d502ee
[ "Markdown", "JavaScript" ]
2
Markdown
deuslirio/3-3-Compiler
ac78e0ee73345d16ff0db0f1ffd4cbda70108e59
8cc5c7e446052758cb945c7988cf40f3041b5105
refs/heads/master
<repo_name>knut0815/ndsemu<file_sep>/raster3d/struct.go package raster3d import ( "ndsemu/emu" "ndsemu/emu/gfx" ) type RenderVertexFlags uint32 const ( RVFClipLeft RenderVertexFlags = 1 << iota RVFClipRight RVFClipTop RVFClipBottom RVFClipNear RVFClipFar RVFTransformed // vertex has been already transformed to screen space RVFClipMask = (RVFClipLeft | RVFClipRight | RVFClipTop | RVFClipBottom | RVFClipNear | RVFClipFar) ) type Vertex struct { // Coordinates in clip-space cx, cy, cz, cw emu.Fixed12 // Screen coordinates (fractional part is always zero) x, y, z emu.Fixed12 // Texture coordinates s, t emu.Fixed12 // Vertex color rgb color // Misc flags flags RenderVertexFlags } // NOTE: these flags match the polygon attribute word defined in the // geometry coprocessor. type PolygonFlags uint32 const ( PFRenderBack PolygonFlags = 1 << 6 PFRenderFront = 1 << 7 PFQuad = 1 << 31 ) func (f PolygonFlags) Alpha() int { return int(f>>16) & 0x1F } func (f PolygonFlags) ColorMode() uint { return uint(f>>4) & 3 } const ( LerpX = iota // coordinate on screen (X) LerpZ // depth on screen (Z or W) LerpT // texture X coordinate (T) LerpS // texture Y coordinate (S) LerpRGB // vertex color (RGB) NumLerps ) //go:generate go run gen/genfillers.go -filename polyfillers.go type Polygon struct { vtx [3]*Vertex flags PolygonFlags tex Texture // y coordinate of middle vertex hy int32 // linear interpolators for left and right edge of the polygon left [NumLerps]lerp right [NumLerps]lerp // polyfiller for this polygon filler func(*HwEngine3d, *Polygon, gfx.Line, gfx.Line, gfx.Line) // texture pointer texptr []byte } //go:generate stringer -type TexFormat type TexFormat int type TexFlags int const ( TexNone TexFormat = iota TexA3I5 Tex4 Tex16 Tex256 Tex4x4 TexA5I3 TexDirect ) const ( TexSFlip TexFlags = 1 << iota TexTFlip TexSRepeat TexTRepeat ) type Texture struct { VramTexOffset uint32 VramPalOffset uint32 Width, Height uint32 PitchShift uint // Masks to implement fast clamping in polyfillers. They're // set to ^(texturesize-1) if clamping is active, or 0 if not // so that clamp does not get triggered. SClampMask uint32 TClampMask uint32 // Masks to implement fast texture flipping in polyfillers. // They're set to the texture size (eg: 0x100) so that they // become a mask to check whether the coordinate is being // repeated an odd number of times. SFlipMask uint32 TFlipMask uint32 Transparency bool Format TexFormat Flags TexFlags } <file_sep>/emulator.go package main import ( "fmt" "io/ioutil" "ndsemu/e2d" "ndsemu/emu" "ndsemu/emu/debugger" "ndsemu/emu/gfx" log "ndsemu/emu/logger" "ndsemu/raster3d" "os" "path/filepath" "strconv" "github.com/BurntSushi/toml" ) type NDSMemory struct { Ram [4 * 1024 * 1024]byte // main RAM Vram [656 * 1024]byte // video RAM Wram [64 * 1024]byte // work RAM (nds7) PaletteRam [2048]byte // pallette RAM OamRam [2048]byte // object attribute RAM } type NDSRom struct { Bios9 []byte Bios7 []byte } type NDSHardware struct { E2d [2]*e2d.HwEngine2d E3d *raster3d.HwEngine3d Lcd9 *HwLcd Lcd7 *HwLcd Mc *HwMemoryController Ipc *HwIpc Div *HwDivisor Rtc *HwRtc Wifi *HwWifi Spi *HwSpiBus Gc *Gamecard Ff *HwFirmwareFlash Tsc *HwTouchScreen Key *HwKey Snd *HwSound Geom *HwGeometry Bkp *HwBackupRam Sl2 *HwSlot2 } type NDSEmulator struct { Mem *NDSMemory Rom *NDSRom Hw *NDSHardware Sync *emu.Sync dbg *debugger.Debugger screen gfx.Buffer audio []int16 framecount int powcnt uint32 } var Emu *NDSEmulator func NewNDSHardware(mem *NDSMemory, firmware string) *NDSHardware { hw := new(NDSHardware) bindir, _ := filepath.Abs(filepath.Dir(os.Args[0])) nds9 = NewNDS9() nds7 = NewNDS7() hw.Mc = NewMemoryController(nds9, nds7, mem.Vram[:]) hw.E3d = raster3d.NewHwEngine3d() hw.E2d[0] = e2d.NewHwEngine2d(0, hw.Mc, gfx.LayerFunc{Func: hw.E3d.Draw3D}) hw.E2d[1] = e2d.NewHwEngine2d(1, hw.Mc, nil) hw.Lcd9 = NewHwLcd(nds9.Irq) hw.Lcd7 = NewHwLcd(nds7.Irq) hw.Ipc = NewHwIpc(nds9.Irq, nds7.Irq) hw.Div = NewHwDivisor() hw.Rtc = NewHwRtc() hw.Wifi = NewHwWifi() hw.Bkp = NewHwBackupRam() hw.Gc = NewGamecard(filepath.Join(bindir, "bios/biosnds7.rom"), hw.Bkp) hw.Tsc = NewHwTouchScreen() hw.Key = NewHwKey() hw.Snd = NewHwSound(nds7.Bus) hw.Geom = NewHwGeometry(nds9.Irq, hw.E3d) hw.Sl2 = NewHwSlot2() hw.Spi = NewHwSpiBus() hw.Ff = NewHwFirmwareFlash() hw.Spi.AddDevice(0, NewHwPowerMan()) hw.Spi.AddDevice(1, hw.Ff) hw.Spi.AddDevice(2, hw.Tsc) return hw } func NewNDSRom() *NDSRom { rom := new(NDSRom) bindir, _ := filepath.Abs(filepath.Dir(os.Args[0])) bios9, err := ioutil.ReadFile(filepath.Join(bindir, "bios/biosnds9.rom")) if err != nil { log.ModEmu.Fatal("error loading rom:", err) } rom.Bios9 = bios9 bios7, err := ioutil.ReadFile(filepath.Join(bindir, "bios/biosnds7.rom")) if err != nil { log.ModEmu.Fatal("error loading rom:", err) } rom.Bios7 = bios7 return rom } func NewNDSEmulator(firmware string) *NDSEmulator { mem := new(NDSMemory) rom := NewNDSRom() hw := NewNDSHardware(mem, firmware) // Initialize syncing system sync, err := emu.NewSync(SyncConfig) if err != nil { panic(err) } sync.AddCpu(nds9, "arm9") sync.AddCpu(nds7, "arm7") sync.AddSubsystem(nds9.Timers, "timers9") sync.AddSubsystem(nds7.Timers, "timers7") sync.AddSubsystem(hw.Geom, "gx") e := &NDSEmulator{ Mem: mem, Hw: hw, Rom: rom, Sync: sync, } // Set the hsync callback to this instance's function e.Sync.SetHSyncCallback(e.hsync) // Register the syncer's logger as global logging function, // so that everything will also log the current subsystem // status (eg: CPU program counter) log.AddContext(e.Sync) emu.BreakFunc = e.DebugBreak // Initialize the memory map and reset the CPUs nds9.InitBus(e) nds7.InitBus(e) nds9.Reset() nds7.Reset() return e } func (emu *NDSEmulator) StartDebugger() { emu.dbg = debugger.New([]debugger.Cpu{nds7.Cpu, nds9.Cpu}, emu.Sync) type DebugConfig struct { Breakpoints []string Watchpoints []string } cfg := &DebugConfig{} if _, err := toml.DecodeFile("debug.ini", cfg); err != nil { log.ModEmu.WithField("error", err).Warnf("error loading debug.ini") } else { for _, bkp := range cfg.Breakpoints { if b, err := strconv.ParseUint(bkp, 0, 32); err != nil { log.ModEmu.WithField("error", err).Fatalf("invalid breakpoint %q", bkp) } else { emu.dbg.AddBreakpoint(uint32(b)) log.ModEmu.WithField("break", fmt.Sprintf("0x%08x", uint32(b))).Warnf("add breakpoint") } } for _, bkp := range cfg.Watchpoints { if b, err := strconv.ParseUint(bkp, 0, 32); err != nil { log.ModEmu.WithField("error", err).Fatalf("invalid watchpoint %q", bkp) } else { emu.dbg.AddWatchpoint(uint32(b)) log.ModEmu.WithField("watch", fmt.Sprintf("0x%08x", uint32(b))).Warnf("add watchpoint") } } } go emu.dbg.Run() } func (emu *NDSEmulator) DebugBreak(msg string) { if emu.dbg != nil { emu.dbg.Break(msg) } else { log.ModEmu.Error(msg) log.ModEmu.Fatal("debugging breakpoint, aborting") } } func (emu *NDSEmulator) eaOn() bool { return emu.powcnt&(1<<1) != 0 } func (emu *NDSEmulator) ebOn() bool { return emu.powcnt&(1<<9) != 0 } func (emu *NDSEmulator) lcdSwapped() bool { return emu.powcnt&(1<<15) != 0 } func (emu *NDSEmulator) hsync(x, y int) { emu.Hw.Lcd9.SyncEvent(x, y) emu.Hw.Lcd7.SyncEvent(x, y) if y == 0 && x == 0 { // NOTE: we must call BeginFrame on 3D before 2D, // so that the engine is then ready if the 2D BeginFrame // needs it. emu.Hw.E3d.BeginFrame() emu.Hw.E3d.SetVram(emu.Hw.Mc.VramTextureBank(), emu.Hw.Mc.VramTexturePaletteBank()) if emu.eaOn() { emu.Hw.E2d[0].BeginFrame() } if emu.ebOn() { emu.Hw.E2d[1].BeginFrame() } } if y < 192 { if x == 0 { emu.beginLine(y) } else if x == cHBlankFirstDot { emu.endLine(y) // Trigger the DMA hblank event (only in visible part of screen) for _, dmach := range nds9.Dma { dmach.TriggerEvent(DmaEventHBlank) } } } // Vblank if y == 192 && x == 0 { if emu.eaOn() { emu.Hw.E2d[0].EndFrame() } if emu.ebOn() { emu.Hw.E2d[1].EndFrame() } emu.Hw.E3d.EndFrame() } // Per-line audio emulation if x == 0 { nsamples := len(emu.audio) / 2 n0 := (nsamples * y) / 263 n1 := (nsamples * (y + 1)) / 263 emu.Hw.Snd.RunOneFrame(emu.audio[n0*2 : n1*2]) } } func (emu *NDSEmulator) RunOneFrame(screen gfx.Buffer, audio []int16) { up, down := "B", "A" if emu.lcdSwapped() { up, down = down, up } log.ModGfx.Infof("Begin frame: %d (up=%s, down=%s)", emu.framecount, up, down) emu.framecount++ // Save powcnt for this frame; letting it change within a frame isn't // really necessary and it's hard to handle with our parallel system emu.powcnt = nds9.misc.PowCnt.Value emu.screen = screen emu.audio = audio emu.Sync.RunOneFrame() emu.audio = nil } func (emu *NDSEmulator) beginLine(y int) { ya := y + 192 + 90 yb := y if emu.lcdSwapped() { ya, yb = yb, ya } if emu.eaOn() { emu.Hw.E2d[0].BeginLine(y, emu.screen.Line(ya)) } if emu.ebOn() { emu.Hw.E2d[1].BeginLine(y, emu.screen.Line(yb)) } } func (emu *NDSEmulator) endLine(y int) { if emu.eaOn() { emu.Hw.E2d[0].EndLine(y) } if emu.ebOn() { emu.Hw.E2d[1].EndLine(y) } } <file_sep>/raster3d/gen/genfillers.go package main import ( "bytes" "crypto/md5" "encoding/hex" "flag" "fmt" "io" "ndsemu/raster3d/fillerconfig" "os" "os/exec" "time" ) var filename = flag.String("filename", "-", "output filename") var maxlayers = flag.Int("layers", 8, "max number of layers to unroll") const ( TexNone uint = iota TexA3I5 Tex4 Tex16 Tex256 Tex4x4 TexA5I3 TexDirect ) type Generator struct { io.Writer out io.Writer } func (g *Generator) genFiller(cfg *fillerconfig.FillerConfig) { if cfg.FillMode == fillerconfig.FillModeSolid && cfg.TexWithAlpha() { cfg.FillMode = fillerconfig.FillModeAlpha } fmt.Fprintf(g, "x0, x1 := poly.left[LerpX].Cur().NearInt32(), poly.right[LerpX].Cur().NearInt32()\n") fmt.Fprintf(g, "nx := x1-x0; if nx==0 {return}\n") fmt.Fprintf(g, "z0, z1 := poly.left[LerpZ].Cur(), poly.right[LerpZ].Cur()\n") fmt.Fprintf(g, "dz := z1.SubFixed(z0).Div(nx)\n") fmt.Fprintf(g, "c0, c1 := color(poly.left[LerpRGB].CurAsInt()), color(poly.right[LerpRGB].CurAsInt())\n") fmt.Fprintf(g, "dc := c1.SubColor(c0).Div(nx)\n") if cfg.TexFormat > 0 { fmt.Fprintf(g, "texoff := poly.tex.VramTexOffset\n") fmt.Fprintf(g, "tshift := poly.tex.PitchShift\n") if cfg.Palettized() { fmt.Fprintf(g, "palette := e3d.palVram.Palette(int(poly.tex.VramPalOffset))\n") } fmt.Fprintf(g, "s0, s1 := poly.left[LerpS].Cur12(), poly.right[LerpS].Cur12()\n") fmt.Fprintf(g, "t0, t1 := poly.left[LerpT].Cur12(), poly.right[LerpT].Cur12()\n") fmt.Fprintf(g, "ds, dt := s1.SubFixed(s0).Div(nx), t1.SubFixed(t0).Div(nx)\n") switch cfg.TexCoords { case fillerconfig.TexCoordsFull: fmt.Fprintf(g, "sclamp, tclamp := poly.tex.SClampMask, poly.tex.TClampMask\n") fallthrough case fillerconfig.TexCoordsRepeatOrFlip: fmt.Fprintf(g, "sflip, tflip := poly.tex.SFlipMask, poly.tex.TFlipMask\n") fallthrough case fillerconfig.TexCoordsRepeatOnly: fmt.Fprintf(g, "smask, tmask := poly.tex.Width-1, poly.tex.Height-1\n") } } if cfg.FillMode == fillerconfig.FillModeAlpha { fmt.Fprintf(g, "polyalpha := uint8(poly.flags.Alpha())<<1\n") } // Pre pixel loop switch cfg.TexFormat { case Tex4: // 4 pixels per byte, decrease texture pitch fmt.Fprintf(g, "tshift -= 2\n") case Tex16: // 2 pixels per byte, decrease texture pitch fmt.Fprintf(g, "tshift -= 1\n") case TexDirect: // 2 bytes per pixel, increase texture pitch fmt.Fprintf(g, "tshift += 1\n") case Tex4x4: fmt.Fprintf(g, "decompTexBuf := e3d.texCache.Get(texoff)\n") fmt.Fprintf(g, "decompTex := gfx.NewLine(decompTexBuf)\n") } // Pixel loop var declarations fmt.Fprintf(g, "var px uint16\n") fmt.Fprintf(g, "var pxa uint8\n") fmt.Fprintf(g, "pxa = 63\n") fmt.Fprintf(g, "var px0 uint8\n") if cfg.TexFormat > 0 { fmt.Fprintf(g, "var s,t uint32\n") } // ************************** // PIXEL LOOP // ************************** fmt.Fprintf(g, "out.Add32(int(x0))\n") fmt.Fprintf(g, "zbuf.Add32(int(x0))\n") if cfg.FillMode == fillerconfig.FillModeAlpha { fmt.Fprintf(g, "abuf.Add8(int(x0))\n") } fmt.Fprintf(g, "for x:=x0; x<x1; x++ {\n") // z-buffer check fmt.Fprintf(g, "// zbuffer check\n") fmt.Fprintf(g, "if z0.V >= int32(zbuf.Get32(0)) { goto next }\n") if cfg.TexFormat > 0 { // texture coords fmt.Fprintf(g, "// texel coords\n") fmt.Fprintf(g, "s, t = uint32(s0.TruncInt32()), uint32(t0.TruncInt32())\n") if cfg.TexCoords == fillerconfig.TexCoordsRepeatOrFlip || cfg.TexCoords == fillerconfig.TexCoordsFull { fmt.Fprintf(g, "if s & sflip != 0 { s = ^s }\n") fmt.Fprintf(g, "if t & tflip != 0 { t = ^t }\n") } if cfg.TexCoords == fillerconfig.TexCoordsFull { // Use smart formula for doing min/max clamping with only one // comparison/branch. sclamp/tclamp have been initialized with // ^(texturesize-1), so if they're set it means that the coordinate // needs to clamped; at that point, the bit tweaking set the // coord to either 0 or 0xFFFFFFFF (which is then masked to the // texture size and thus become the first/last texel). fmt.Fprintf(g, "if s & sclamp != 0 { s = ^uint32(int32(s) >> 31) }\n") fmt.Fprintf(g, "if t & tclamp != 0 { t = ^uint32(int32(t) >> 31) }\n") } fmt.Fprintf(g, "s, t = s&smask, t&tmask\n") // texture fetch fmt.Fprintf(g, "// texel fetch\n") switch cfg.TexFormat { case Tex4: fmt.Fprintf(g, "px0 = e3d.texVram.Get8(texoff + t<<tshift + s/4)\n") fmt.Fprintf(g, "px0 = px0 >> (2 * uint(s&3))\n") fmt.Fprintf(g, "px0 &= 0x3\n") if cfg.ColorKey != 0 { fmt.Fprintf(g, "// color key check\n") fmt.Fprintf(g, "if px0 == 0 { goto next }\n") } fmt.Fprintf(g, "px = palette.Lookup(px0)\n") case Tex16: fmt.Fprintf(g, "px0 = e3d.texVram.Get8(texoff + t<<tshift + s/2)\n") fmt.Fprintf(g, "px0 = px0 >> (4 * uint(s&1))\n") fmt.Fprintf(g, "px0 &= 0xF\n") if cfg.ColorKey != 0 { fmt.Fprintf(g, "// color key check\n") fmt.Fprintf(g, "if px0 == 0 { goto next }\n") } fmt.Fprintf(g, "px = palette.Lookup(px0)\n") case Tex256: fmt.Fprintf(g, "px0 = e3d.texVram.Get8(texoff + t<<tshift + s)\n") if cfg.ColorKey != 0 { fmt.Fprintf(g, "if px0 == 0 { goto next }\n") } fmt.Fprintf(g, "px = palette.Lookup(px0)\n") case TexA3I5: fmt.Fprintf(g, "px0 = e3d.texVram.Get8(texoff + t<<tshift + s)\n") fmt.Fprintf(g, "pxa = (px0 >> 5)\n") fmt.Fprintf(g, "pxa = pxa | (pxa<<3)\n") fmt.Fprintf(g, "px0 &= 0x1F\n") if cfg.ColorKey != 0 { fmt.Fprintf(g, "// color key check\n") fmt.Fprintf(g, "if px0 == 0 { goto next }\n") } fmt.Fprintf(g, "px = uint16(px0)|uint16(px0)<<5|uint16(px0)<<10\n") case TexA5I3: fmt.Fprintf(g, "px0 = e3d.texVram.Get8(texoff + t<<tshift + s)\n") fmt.Fprintf(g, "pxa = px0 >> 3\n") fmt.Fprintf(g, "pxa = (pxa>>5) | (pxa<<1)\n") fmt.Fprintf(g, "px0 &= 0x7\n") fmt.Fprintf(g, "px0 <<= 2\n") if cfg.ColorKey != 0 { fmt.Fprintf(g, "// color key check\n") fmt.Fprintf(g, "if px0 == 0 { goto next }\n") } fmt.Fprintf(g, "px = uint16(px0)|uint16(px0)<<5|uint16(px0)<<10\n") case TexDirect: fmt.Fprintf(g, "px = e3d.texVram.Get16(texoff + t<<tshift + s*2)\n") fmt.Fprintf(g, "if px & 0x8000 != 0 { pxa = 63 }\n") fmt.Fprintf(g, "px &= 0x7FFF\n") case Tex4x4: fmt.Fprintf(g, "px = decompTex.Get16(int(t<<tshift + s))\n") // Tex4x4 is always color-keyed fmt.Fprintf(g, "// color key check\n") fmt.Fprintf(g, "if px == 0 { goto next }\n") default: panic("unsupported") } } // color mode: combine texture pixel and vertex color fmt.Fprintf(g, "// apply vertex color to texel\n") switch cfg.ColorMode { case fillerconfig.ColorModeModulation: fmt.Fprintf(g, "if true {\n") fmt.Fprintf(g, "pxc := newColorFrom555U(px)\n") fmt.Fprintf(g, "pxc = pxc.Modulate(c0)\n") fmt.Fprintf(g, "px = pxc.To555U()\n") if cfg.FillMode == fillerconfig.FillModeAlpha { fmt.Fprintf(g, "pxa = uint8((int32(pxa+1)*int32(polyalpha+1)-1)>>6)\n") } fmt.Fprintf(g, "}\n") case fillerconfig.ColorModeDecal: fmt.Fprintf(g, "if true {\n") fmt.Fprintf(g, "pxc := newColorFrom555U(px)\n") fmt.Fprintf(g, "pxc = pxc.Decal(c0, pxa)\n") fmt.Fprintf(g, "px = pxc.To555U()\n") if cfg.FillMode == fillerconfig.FillModeAlpha { fmt.Fprintf(g, "pxa = polyalpha\n") } fmt.Fprintf(g, "}\n") case fillerconfig.ColorModeToon, fillerconfig.ColorModeHighlight: fmt.Fprintf(g, "if true {\n") fmt.Fprintf(g, "tc0 := emu.Read16LE(e3d.ToonTable.Data[((c0.R()>>1)&0x1F)*2:])\n") fmt.Fprintf(g, "tc := newColorFrom555U(tc0)\n") fmt.Fprintf(g, "pxc := newColorFrom555U(px)\n") fmt.Fprintf(g, "pxc = pxc.Modulate(tc)\n") if cfg.ColorMode == fillerconfig.ColorModeHighlight { fmt.Fprintf(g, "pxc = pxc.AddSat(tc)\n") } fmt.Fprintf(g, "px = pxc.To555U()\n") if cfg.FillMode == fillerconfig.FillModeAlpha { fmt.Fprintf(g, "pxa = uint8((int32(pxa+1)*int32(polyalpha+1)-1)>>6)\n") } fmt.Fprintf(g, "}\n") case fillerconfig.ColorModeShadow: fmt.Fprintf(g, "px = 0\n") if cfg.FillMode == fillerconfig.FillModeAlpha { fmt.Fprintf(g, "pxa = polyalpha\n") } } fmt.Fprintf(g, "// alpha blending with background\n") if cfg.FillMode == fillerconfig.FillModeAlpha { fmt.Fprintf(g, "if pxa == 0 { goto next }\n") fmt.Fprintf(g, "if true {\n") fmt.Fprintf(g, "bkg := uint16(out.Get32(0))\n") fmt.Fprintf(g, "bkga := abuf.Get8(0)\n") fmt.Fprintf(g, "if bkga != 0 { px = rgbAlphaMix(px, bkg, pxa>>1) }\n") fmt.Fprintf(g, "if pxa > bkga { abuf.Set8(0, pxa) }\n") fmt.Fprintf(g, "}\n") } // draw pixel fmt.Fprintf(g, "// draw color and z\n") fmt.Fprintf(g, "out.Set32(0, uint32(px)|0x80000000)\n") fmt.Fprintf(g, "zbuf.Set32(0, uint32(z0.V))\n") // Pixel loop footer fmt.Fprintf(g, "next:\n") fmt.Fprintf(g, "out.Add32(1)\n") fmt.Fprintf(g, "zbuf.Add32(1)\n") if cfg.FillMode == fillerconfig.FillModeAlpha { fmt.Fprintf(g, "abuf.Add8(1)\n") } fmt.Fprintf(g, "z0 = z0.AddFixed(dz)\n") fmt.Fprintf(g, "c0 = c0.AddDelta(dc)\n") if cfg.TexFormat > 0 { fmt.Fprintf(g, "s0 = s0.AddFixed(ds)\n") fmt.Fprintf(g, "t0 = t0.AddFixed(dt)\n") } fmt.Fprintf(g, "}\n") fmt.Fprintf(g, "_=px0\n") fmt.Fprintf(g, "_=pxa\n") } func (g *Generator) Run() { g.Writer = g.out fmt.Fprintf(g, "// Generated on %v\n", time.Now()) fmt.Fprintf(g, "package raster3d\n") fmt.Fprintf(g, "import \"ndsemu/emu/gfx\"\n") fmt.Fprintf(g, "import \"ndsemu/emu\"\n") digests := make(map[string]uint, 1024) dups := make([]uint, fillerconfig.FillerKeyMax) var buf bytes.Buffer hash := md5.New() for i := uint(0); i < fillerconfig.FillerKeyMax; i++ { cfg := fillerconfig.FillerConfigFromKey(i) buf.Reset() hash.Reset() g.Writer = io.MultiWriter(&buf, hash) g.genFiller(&cfg) sum := hex.EncodeToString(hash.Sum(nil)) if idx, found := digests[sum]; found { dups[i] = idx fmt.Fprintf(g.out, "// filler_%03x skipped, because of identical polyfiller:\n", i) fmt.Fprintf(g.out, "// %03x -> %+v\n", i, cfg) fmt.Fprintf(g.out, "// %03x -> %+v\n", idx, fillerconfig.FillerConfigFromKey(idx)) fmt.Fprintf(g.out, "\n") } else { dups[i] = i digests[sum] = i fmt.Fprintf(g.out, "func (e3d *HwEngine3d) filler_%03x(poly *Polygon, out gfx.Line, zbuf gfx.Line, abuf gfx.Line) {\n", i) fmt.Fprintf(g.out, "// %+v\n", cfg) g.out.Write(buf.Bytes()) fmt.Fprintf(g.out, "}\n\n") } } g.Writer = g.out fmt.Fprintf(g, "var polygonFillerTable = [%d]func(*HwEngine3d,*Polygon,gfx.Line,gfx.Line,gfx.Line) {\n", fillerconfig.FillerKeyMax) for i := uint(0); i < fillerconfig.FillerKeyMax; i++ { fmt.Fprintf(g, "(*HwEngine3d).filler_%03x,\n", dups[i]) } fmt.Fprintf(g, "}\n") fmt.Fprintf(os.Stderr, "%d unique polyfillers generated (total combinations: %d)\n", len(digests), fillerconfig.FillerKeyMax) } func main() { flag.Parse() var f io.Writer if *filename == "-" { f = os.Stdout } else { ff, err := os.Create(*filename) if err != nil { fmt.Println(err) os.Exit(1) } defer func() { if r := recover(); r != nil { panic(r) } cmd := exec.Command("go", "fmt", *filename) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { os.Exit(1) } }() defer ff.Close() f = ff } g := Generator{out: f} g.Run() } <file_sep>/emu/fixed22.go package emu import "fmt" type Fixed22 struct { V int32 } func NewFixed22(val int32) Fixed22 { return Fixed22{val << 22} } func newFixed22FromInt64(val int64) Fixed22 { val32 := int32(val) if int64(val32) != val { fmt.Printf("%v %x\n", val, val) panic("fixed point overflow") } return Fixed22{val32} } func (f Fixed22) ToFloat64() float64 { return float64(f.V) / 4194304.0 } func (f Fixed22) NearInt32() int32 { return (f.V + (1 << 21)) >> 22 } func (f Fixed22) TruncInt32() int32 { return f.V >> 22 } func (f Fixed22) Add(add int32) Fixed22 { return Fixed22{f.V + add<<22} } func (f Fixed22) AddFixed(v Fixed22) Fixed22 { return Fixed22{f.V + v.V} } func (f Fixed22) SubFixed(v Fixed22) Fixed22 { return Fixed22{f.V - v.V} } func (f Fixed22) Mul(mul int32) Fixed22 { return Fixed22{f.V * mul} } func (f Fixed22) Div(den int32) Fixed22 { return Fixed22{f.V / den} } func (f Fixed22) Neg() Fixed22 { return Fixed22{-f.V} } func (f Fixed22) DivFixed(den Fixed22) Fixed22 { return newFixed22FromInt64((int64(f.V) << 22) / int64(den.V)) } func (f Fixed22) MulFixed(mul Fixed22) Fixed22 { return newFixed22FromInt64((int64(f.V) * int64(mul.V)) >> 22) } func (f Fixed22) Round() Fixed22 { return NewFixed22(f.NearInt32()) } func (f Fixed22) Clamp(min, max Fixed22) Fixed22 { if f.V < min.V { f.V = min.V } if f.V > max.V { f.V = max.V } return f } // func (f Fixed22) mulFixedNearest(mul Fixed22) Fixed22 { // res := int64(f.V) * int64(mul.V) // if res >= 0 { // res += 1 << 21 // } else { // res -= 1 << 21 // } // return newFromInt64(res >> 22) // } // Lerp computes a linear interpolation between f and f2. // Returns f + (f2-f)*ratio func (f Fixed22) Lerp(f2 Fixed22, ratio Fixed22) Fixed22 { return f2.SubFixed(f).MulFixed(ratio).AddFixed(f) } func (f Fixed22) String() string { return fmt.Sprintf("%.4f", f.ToFloat64()) } <file_sep>/e2d/mode1.go package e2d import ( "fmt" "ndsemu/emu/gfx" ) /************************************************ * Display Mode 1: BG & OBJ layers ************************************************/ type BgMode int //go:generate stringer -type BgMode const ( BgModeText BgMode = iota BgModeAffine BgModeAffineMap16 BgModeAffineBitmap BgModeAffineBitmapDirect BgModeLargeBitmap BgMode3D ) func (e2d *HwEngine2d) Mode1_BeginFrame() { // Set the 4 BG layer priorities for i := 0; i < 4; i++ { pri := uint(e2d.bgregs[i].priority()) e2d.lm.SetLayerPriority(i, pri) } e2d.lm.SetLayerPriority(4, 100) // put sprites always last in the mixer bgmode := e2d.DispCnt.Value & 7 bg3d := (e2d.DispCnt.Value>>3)&1 != 0 // Switch bg0 between text and 3d layer, depending on setting in DISPCNT // Notice also that in bgmode 6, layer 0 is always 3d if e2d.A() { if bg3d || bgmode == 6 { e2d.Mode1_setBgMode(0, BgMode3D) } else { e2d.Mode1_setBgMode(0, BgModeText) } } // Bg1 is always text e2d.Mode1_setBgMode(1, BgModeText) // Compute extended mode (only for bg2/bg3) var ext [4]BgMode for idx := 2; idx < 4; idx++ { if *e2d.bgregs[idx].Cnt&(1<<7) == 0 { ext[idx] = BgModeAffineMap16 } else if *e2d.bgregs[idx].Cnt&(1<<2) == 0 { ext[idx] = BgModeAffineBitmap } else { ext[idx] = BgModeAffineBitmapDirect } } // Change bg2/bg3 depending on mode switch bgmode { case 0: e2d.Mode1_setBgMode(2, BgModeText) e2d.Mode1_setBgMode(3, BgModeText) case 1: e2d.Mode1_setBgMode(2, BgModeText) e2d.Mode1_setBgMode(3, BgModeAffine) case 2: e2d.Mode1_setBgMode(2, BgModeAffine) e2d.Mode1_setBgMode(3, BgModeAffine) case 3: e2d.Mode1_setBgMode(2, BgModeText) e2d.Mode1_setBgMode(3, ext[3]) case 4: e2d.Mode1_setBgMode(2, BgModeAffine) e2d.Mode1_setBgMode(3, ext[3]) case 5: e2d.Mode1_setBgMode(2, ext[2]) e2d.Mode1_setBgMode(3, ext[3]) case 6: if e2d.A() { // Large bitmap mode only supported on engine A e2d.Mode1_setBgMode(2, BgModeLargeBitmap) } } e2d.lm.BeginFrame() bg0on := (e2d.DispCnt.Value >> 8) & 1 bg1on := (e2d.DispCnt.Value >> 9) & 1 bg2on := (e2d.DispCnt.Value >> 10) & 1 bg3on := (e2d.DispCnt.Value >> 11) & 1 objon := (e2d.DispCnt.Value >> 12) & 1 win0on := (e2d.DispCnt.Value >> 13) & 1 win1on := (e2d.DispCnt.Value >> 14) & 1 objwinon := (e2d.DispCnt.Value >> 15) & 1 modLcd.Infof("%s: modes=%v bg=[%d,%d,%d,%d] obj=%d win=[%d,%d,%d]", string('A'+e2d.Idx), e2d.bgmodes, bg0on, bg1on, bg2on, bg3on, objon, win0on, win1on, objwinon) // modLcd.Infof("%s: scroll0=[%d,%d] scroll1=[%d,%d] scroll2=[%d,%d] scroll3=[%d,%d] size0=%d size3=%d", // string('A'+e2d.Idx), // e2d.Bg0XOfs.Value, e2d.Bg0YOfs.Value, // e2d.Bg1XOfs.Value, e2d.Bg1YOfs.Value, // e2d.Bg2XOfs.Value, e2d.Bg2YOfs.Value, // e2d.Bg3XOfs.Value, e2d.Bg3YOfs.Value, // e2d.Bg0Cnt.Value>>14, e2d.Bg3Cnt.Value>>13) } func (e2d *HwEngine2d) Mode1_EndFrame() { e2d.lm.EndFrame() } func (e2d *HwEngine2d) Mode1_BeginLine(y int, screen gfx.Line) { pram := e2d.mc.VramPalette(e2d.Idx) e2d.bgPal = pram[:512] e2d.objPal = pram[512:] // Fetch direct pointers to extended palettes (both bg and obj). These // will be used by the mixer function to access the actual colors. // // Extended palettes are active if bit 30 (bg) and/or 31 (obj) in // DISPCNT are set, and of course the appropriate VRAM banks need to // be mapped. In any case, VramLinearBank() returnes an empty memory // area if the banks are unmapped, and we can even try to use it // (and display all black). This is possibly consistent with what NDS // does if the extended palettes are used without being properly // configured. bgextpal := e2d.mc.VramLinearBank(e2d.Idx, VramLinearBGExtPal, 0) for i := range e2d.bgExtPals { // When storing the pointer for each layer, we want to respect the // priority order; in fact, this array will be accessed by the mixer // function, so in that context bgExtPals[2] means the third layer in // priority order. lidx := e2d.lm.PriorityOrder[i] // Compute the BG Ext Palette slot used by each bg layer. Normally, // BG0 uses Slot 0, BG3 uses Slot 3, etc. but BG0 and BG1 can optionally // use a different slot (depending on bit 13 of BGxCNT register) slotnum := lidx if lidx == 0 && e2d.Bg0Cnt.Value&(1<<13) != 0 { slotnum = 2 } if lidx == 1 && e2d.Bg1Cnt.Value&(1<<13) != 0 { slotnum = 3 } e2d.bgExtPals[i] = bgextpal.FetchPointer(8 * 1024 * slotnum) } objextpal := e2d.mc.VramLinearBank(e2d.Idx, VramLinearOBJExtPal, 0) e2d.objExtPal = objextpal.FetchPointer(0) e2d.lm.BeginLine(screen) } func (e2d *HwEngine2d) Mode1_EndLine(y int) { e2d.lm.EndLine() } func (e2d *HwEngine2d) Mode1_setBgMode(lidx int, mode BgMode) { if e2d.bgmodes[lidx] == mode { return } e2d.bgmodes[lidx] = mode switch mode { case BgModeText: e2d.lm.ChangeLayer(lidx, gfx.LayerFunc{Func: e2d.DrawBG}) case BgMode3D: e2d.lm.ChangeLayer(lidx, e2d.l3d) case BgModeAffineMap16, BgModeAffineBitmapDirect, BgModeAffineBitmap, BgModeAffine: e2d.lm.ChangeLayer(lidx, gfx.LayerFunc{Func: e2d.DrawBGAffine}) default: panic(fmt.Errorf("bgmode %v not implemented", mode)) } } <file_sep>/emu/spi/spibus.go package spi import log "ndsemu/emu/logger" var modSpi = log.NewModule("spi") type Bus struct { SpiBusName string // Name of the bus (for logging) devs map[int]Device // registered devices tdev Device // current device that is transferring data req []byte // current request reply []byte // current reply } func (spi *Bus) log() log.Entry { return modSpi.WithField("name", spi.SpiBusName) } func (spi *Bus) AddDevice(addr int, dev Device) { if spi.devs == nil { spi.devs = make(map[int]Device) } if _, found := spi.devs[addr]; found { panic("spi: address already assigned") } spi.devs[addr] = dev } func (spi *Bus) BeginTransfer(addr int) { if spi.tdev != nil { if spi.tdev != spi.devs[addr] { spi.log().Warnf("wrong new device=%d", addr) // panic("SPI changed device during transfer") } else { return } } spi.tdev = spi.devs[addr] if spi.tdev == nil { spi.log().Fatalf("SPI device %d not implemented", addr) } if addr != 2 { spi.log().Infof("begin transfer device=%d (%T)", addr, spi.tdev) } spi.tdev.SpiBegin() if spi.req == nil { // first time, allocate a buffer, that we will reuse spi.req = make([]byte, 16) } spi.req = spi.req[:0] spi.reply = nil } func (spi *Bus) Transfer(val byte) (ret byte) { if spi.tdev == nil { spi.log().Warn("SPIDATA written but no transfer") return 0 } // First, compute the return value with any pending // reply. As described in the documentation, the return // value must already be computed at this time, because // the byte being written cannot affect the byte that // will be simultaneously read if len(spi.reply) == 0 { ret = 0 } else { ret = spi.reply[0] spi.reply = spi.reply[1:] } // If the current reply was fully sent-out, // send the request to the device, as it's // possibly a new request to be processed. if len(spi.reply) == 0 { var stat ReqStatus spi.req = append(spi.req, val) spi.reply, stat = spi.tdev.SpiTransfer(spi.req) if stat == ReqFinish { spi.req = spi.req[:0] } } return ret } func (spi *Bus) EndTransfer() { if spi.tdev == nil { spi.log().Warn("EndTransfer called but no transfer") return } spi.Reset() } func (spi *Bus) Reset() { if spi.tdev != nil { spi.tdev.SpiEnd() spi.log().Info("end of transfer") spi.tdev = nil } } <file_sep>/emu/fixed12.go package emu import "fmt" type Fixed12 struct { V int32 } func NewFixed12(val int32) Fixed12 { return Fixed12{val << 12} } func newFixed12FromInt64(val int64) Fixed12 { val32 := int32(val) if int64(val32) != val { fmt.Printf("%v %x\n", val, val) panic("fixed point overflow") } return Fixed12{val32} } func (f Fixed12) ToFloat64() float64 { return float64(f.V) / 4096.0 } func (f Fixed12) NearInt32() int32 { return (f.V + (1 << 11)) >> 12 } func (f Fixed12) TruncInt32() int32 { return f.V >> 12 } func (f Fixed12) Add(add int32) Fixed12 { return Fixed12{f.V + add<<12} } func (f Fixed12) AddFixed(v Fixed12) Fixed12 { return Fixed12{f.V + v.V} } func (f Fixed12) SubFixed(v Fixed12) Fixed12 { return Fixed12{f.V - v.V} } func (f Fixed12) Mul(mul int32) Fixed12 { return Fixed12{f.V * mul} } func (f Fixed12) Div(den int32) Fixed12 { return Fixed12{f.V / den} } func (f Fixed12) Neg() Fixed12 { return Fixed12{-f.V} } func (f Fixed12) DivFixed(den Fixed12) Fixed12 { return newFixed12FromInt64((int64(f.V) << 12) / int64(den.V)) } func (f Fixed12) MulFixed(mul Fixed12) Fixed12 { return newFixed12FromInt64((int64(f.V) * int64(mul.V)) >> 12) } func (f Fixed12) Round() Fixed12 { return NewFixed12(f.NearInt32()) } func (f Fixed12) Clamp(min, max Fixed12) Fixed12 { if f.V < min.V { f.V = min.V } if f.V > max.V { f.V = max.V } return f } // func (f Fixed12) mulFixedNearest(mul Fixed12) Fixed12 { // res := int64(f.V) * int64(mul.V) // if res >= 0 { // res += 1 << 11 // } else { // res -= 1 << 11 // } // return newFromInt64(res >> 12) // } // Lerp computes a linear interpolation between f and f2. // Returns f + (f2-f)*ratio func (f Fixed12) Lerp(f2 Fixed12, ratio Fixed12) Fixed12 { return f2.SubFixed(f).MulFixed(ratio).AddFixed(f) } func (f Fixed12) String() string { return fmt.Sprintf("%.4f", f.ToFloat64()) } func (f Fixed12) ToFixed22() (r Fixed22) { r.V = f.V << (22 - 12) if r.TruncInt32() != f.TruncInt32() { fmt.Printf("%v %v\n", f, r) panic("overflow in conversion") } return } <file_sep>/e2d/mode2.go package e2d import ( "ndsemu/emu" "ndsemu/emu/gfx" ) /************************************************ * Display Mode 2: VRAM display ************************************************/ func (e2d *HwEngine2d) Mode2_BeginFrame() { block := (e2d.DispCnt.Value >> 18) & 3 modLcd.Infof("%s: mode=VRAM-Display bank:%s", string('A'+e2d.Idx), string('A'+block)) } func (e2d *HwEngine2d) Mode2_EndFrame() {} func (e2d *HwEngine2d) Mode2_BeginLine(y int, screen gfx.Line) { block := (e2d.DispCnt.Value >> 18) & 3 vram := e2d.mc.VramRawBank(int(block))[y*cScreenWidth*2:] for x := 0; x < cScreenWidth; x++ { pix := emu.Read16LE(vram[x*2:]) screen.Set32(x, uint32(pix)) } } func (e2d *HwEngine2d) Mode2_EndLine(y int) {} <file_sep>/e2d/modes.go package e2d import ( "ndsemu/emu/gfx" "ndsemu/emu/hw" log "ndsemu/emu/logger" ) /************************************************ * Display Modes: basic dispatch ************************************************/ func (e2d *HwEngine2d) BeginFrame() { if gKeyState == nil { gKeyState = hw.GetKeyboardState() } // Check if display capture is activated if e2d.DispCapCnt.Value&(1<<31) != 0 { source := (e2d.DispCapCnt.Value >> 29) & 3 srca := (e2d.DispCapCnt.Value >> 24) & 1 srcb := (e2d.DispCapCnt.Value >> 25) & 1 if srca != 0 || srcb != 0 { modLcd.Fatalf("unimplemented display capture source=%d srca=%d srb=%d", source, srca, srcb) } // Begin capturing this frame e2d.dispcap.Enabled = true e2d.dispcap.Mode = int(source) e2d.dispcap.WBank = int((e2d.DispCapCnt.Value >> 16) & 3) e2d.dispcap.WOffset = ((e2d.DispCapCnt.Value >> 18) & 3) * 0x8000 e2d.dispcap.RBank = int((e2d.DispCnt.Value >> 18) & 3) e2d.dispcap.ROffset = ((e2d.DispCapCnt.Value >> 26) & 3) * 0x8000 e2d.dispcap.AlphaA = e2d.DispCapCnt.Value & 0x1F e2d.dispcap.AlphaB = (e2d.DispCapCnt.Value >> 8) & 0x1F if e2d.dispcap.AlphaA > 16 { e2d.dispcap.AlphaA = 16 } if e2d.dispcap.AlphaB > 16 { e2d.dispcap.AlphaB = 16 } switch (e2d.DispCapCnt.Value >> 20) & 3 { case 0: e2d.dispcap.Width = 128 e2d.dispcap.Height = 128 case 1: e2d.dispcap.Width = 256 e2d.dispcap.Height = 64 case 2: e2d.dispcap.Width = 256 e2d.dispcap.Height = 128 case 3: e2d.dispcap.Width = 256 e2d.dispcap.Height = 192 } modLcd.WithDelayedFields(func() log.Fields { return log.Fields{ "src": source, "sa": srca, "sb": srcb, "wbank": string(e2d.dispcap.WBank + 'A'), "woff": e2d.dispcap.WOffset, "w": e2d.dispcap.Width, "h": e2d.dispcap.Height, } }).Infof("Capture activated") } // Read current display mode once per frame (do not switch between // display modes within a frame) e2d.dispmode = int((e2d.DispCnt.Value >> 16) & 3) if e2d.B() { e2d.dispmode &= 1 } e2d.modeTable[e2d.dispmode].BeginFrame() } func (e2d *HwEngine2d) EndFrame() { e2d.modeTable[e2d.dispmode].EndFrame() // If we were capturing, stop it if e2d.dispcap.Enabled { e2d.dispcap.Enabled = false e2d.DispCapCnt.Value &^= 1 << 31 } } func (e2d *HwEngine2d) BeginLine(y int, screen gfx.Line) { if e2d.masterBrightChanged { e2d.updateMasterBrightTable() e2d.masterBrightChanged = false } e2d.curline = y e2d.curscreen = screen e2d.modeTable[e2d.dispmode].BeginLine(y, screen) } func (e2d *HwEngine2d) EndLine(y int) { e2d.modeTable[e2d.dispmode].EndLine(y) screen := e2d.curscreen // If capture is enabled, capture the screen output // and since we go through the pixels, also apply the // master brightness (which must be applied AFTER capturing) if e2d.dispcap.Enabled && e2d.curline < e2d.dispcap.Height { vram := e2d.mc.VramRawBank(e2d.dispcap.WBank) vram = vram[e2d.dispcap.WOffset:] capbuf := gfx.NewLine(vram) vram = e2d.mc.VramRawBank(e2d.dispcap.RBank) vram = vram[e2d.dispcap.ROffset:] readbuf := gfx.NewLine(vram) switch e2d.dispcap.Mode { case 0: for i := 0; i < e2d.dispcap.Width; i++ { pix := screen.Get32(i) capbuf.Set16(i, uint16(pix)|0x8000) } case 1: for i := 0; i < e2d.dispcap.Width; i++ { pix := readbuf.Get16(i) capbuf.Set16(i, uint16(pix)|0x8000) } case 2, 3: eva := e2d.dispcap.AlphaA evb := e2d.dispcap.AlphaB for i := 0; i < e2d.dispcap.Width; i++ { pix1 := uint16(screen.Get32(i)) pix2 := uint16(readbuf.Get16(i)) r1, g1, b1 := (pix1 & 0x1F), ((pix1 >> 5) & 0x1F), ((pix1 >> 10) & 0x1F) r2, g2, b2 := (pix2 & 0x1F), ((pix2 >> 5) & 0x1F), ((pix2 >> 10) & 0x1F) r := (uint32(r1)*eva + uint32(r2)*evb) >> 4 g := (uint32(g1)*eva + uint32(g2)*evb) >> 4 b := (uint32(b1)*eva + uint32(b2)*evb) >> 4 capbuf.Set16(i, 0x8000|uint16(r)|uint16(g)<<5|uint16(b)<<10) } } e2d.dispcap.ROffset += uint32(e2d.dispcap.Width * 2) if e2d.dispcap.ROffset == 128*1024 { e2d.dispcap.ROffset = 0 } e2d.dispcap.WOffset += uint32(e2d.dispcap.Width * 2) if e2d.dispcap.WOffset == 128*1024 { e2d.dispcap.WOffset = 0 } } // Apply master brightness and output to the screen for i := 0; i < 256; i++ { pix := screen.Get32(i) r := uint8(pix) & 0x1F g := uint8(pix>>5) & 0x1F b := uint8(pix>>10) & 0x1F screen.Set32(i, e2d.masterBrightR[r]|e2d.masterBrightG[g]|e2d.masterBrightB[b]) } } <file_sep>/e2d/mode1_mixer.go package e2d import "ndsemu/emu" // A pixel in a layer of the layer manager. It is composed as follows: // Bits 0-11: color index in the palette // Bit 12: set if the pixel uses the extended palette for its layer (either obj or bg) // Bit 29-30: priority // Bit 31: direct color type LayerPixel uint32 func (p LayerPixel) ColorIndex() uint16 { return uint16(p & 0xFFF) } func (p LayerPixel) ExtPal() bool { return (p & (1 << 12)) != 0 } func (p LayerPixel) Priority() uint32 { return uint32(p>>29) & 3 } func (p LayerPixel) Direct() bool { return int32(p) < 0 } func (p LayerPixel) DirectColor() uint16 { return uint16(p & 0x7FFF) } func (p LayerPixel) Transparent() bool { return p == 0 } func e2dMixer_Normal(layers []uint32, ctx interface{}) (res uint32) { var objpix, bgpix LayerPixel var pix uint16 var cram []uint8 var c16 uint16 e2d := ctx.(*HwEngine2d) // Extract the layers. They've been already sorted in priority order, // so the first layer with a non-transparent pixel is the one that gets // drawn. bgpix = LayerPixel(layers[0]) if !bgpix.Transparent() { if bgpix.ExtPal() { cram = e2d.bgExtPals[0] } else { cram = e2d.bgPal } goto checkobj } bgpix = LayerPixel(layers[1]) if !bgpix.Transparent() { if bgpix.ExtPal() { cram = e2d.bgExtPals[1] } else { cram = e2d.bgPal } goto checkobj } bgpix = LayerPixel(layers[2]) if !bgpix.Transparent() { if bgpix.ExtPal() { cram = e2d.bgExtPals[2] } else { cram = e2d.bgPal } goto checkobj } bgpix = LayerPixel(layers[3]) if !bgpix.Transparent() { if bgpix.ExtPal() { cram = e2d.bgExtPals[3] } else { cram = e2d.bgPal } goto checkobj } // No bglayer was drawn here, so see if there is at least an obj, in which // case we draw it directly objpix = LayerPixel(layers[4]) if !objpix.Transparent() { goto drawobj } // No objlayer, and no bglayer. Draw the backdrop. // pix = 0 cram = e2d.bgPal goto lookup checkobj: // We found a bg pixel; now check if there is an object pixel here: if so, // we need to check the priority to choose between bg and obj which pixel // to draw (if the priorities are equal, objects win) objpix = LayerPixel(layers[4]) if objpix.Transparent() || objpix.Priority() > bgpix.Priority() { if bgpix.Direct() { c16 = bgpix.DirectColor() goto draw } pix = bgpix.ColorIndex() goto lookup } drawobj: if objpix.Direct() { c16 = objpix.DirectColor() goto draw } pix = objpix.ColorIndex() if objpix.ExtPal() { cram = e2d.objExtPal } else { cram = e2d.objPal } lookup: c16 = emu.Read16LE(cram[pix*2:]) draw: // Just return the 16-bit value for now, the post-processing // function will take care of the last step return uint32(c16) } <file_sep>/emu/fixed8.go package emu import "fmt" type Fixed8 struct { v int64 } func NewFixed8(val int64) Fixed8 { return Fixed8{val << 8} } func (f Fixed8) ToFloat64() float64 { return float64(f.v) / 256.0 } func (f Fixed8) ToInt64() int64 { return (f.v + 0x80) >> 8 } func (f Fixed8) Mul(mul int64) Fixed8 { return Fixed8{f.v * mul} } func (f Fixed8) Div(den int64) Fixed8 { return Fixed8{f.v / den} } func (f Fixed8) DivFixed(den Fixed8) Fixed8 { return Fixed8{(f.v << 8) / den.v} } func (f Fixed8) MulFixed(mul Fixed8) Fixed8 { return Fixed8{(f.v * mul.v) >> 8} } func (f Fixed8) String() string { return fmt.Sprintf("%.3f", f.ToFloat64()) } <file_sep>/e2d/mode0.go package e2d import "ndsemu/emu/gfx" /************************************************ * Display Mode 0: display off ************************************************/ func (e2d *HwEngine2d) Mode0_BeginFrame() {} func (e2d *HwEngine2d) Mode0_EndFrame() {} func (e2d *HwEngine2d) Mode0_BeginLine(y int, screen gfx.Line) { for x := 0; x < cScreenWidth; x++ { // Display off -> draw white screen.Set32(x, 0xFFFFFF) } } func (e2d *HwEngine2d) Mode0_EndLine(y int) {} <file_sep>/raster3d/lerp.go package raster3d import ( "fmt" "ndsemu/emu" ) // Linear interpolator for a triangle. type lerp struct { cur int32 delta [2]int32 start int32 } func newLerp(start emu.Fixed22, d0 emu.Fixed22, d1 emu.Fixed22) lerp { return lerp{start: start.V, delta: [2]int32{d0.V, d1.V}} } func newLerp12(start emu.Fixed12, d0 emu.Fixed12, d1 emu.Fixed12) lerp { return lerp{start: start.V, delta: [2]int32{d0.V, d1.V}} } func newLerpFromInt(start int32, d0 int32, d1 int32) lerp { return lerp{start: start, delta: [2]int32{d0, d1}} } func (l *lerp) Reset() { l.cur = l.start } func (l *lerp) Cur() emu.Fixed22 { return emu.Fixed22{V: l.cur} } func (l *lerp) Cur12() emu.Fixed12 { return emu.Fixed12{V: l.cur} } func (l *lerp) CurAsInt() int32 { return l.cur } func (l *lerp) Next(didx int) { l.cur = l.cur + l.delta[didx] } func (l lerp) String() string { return fmt.Sprintf("lerp(%v (%v,%v) [%v])", emu.Fixed22{V: l.cur}, emu.Fixed22{V: l.delta[0]}, emu.Fixed22{V: l.delta[1]}, emu.Fixed22{V: l.start}) } <file_sep>/emu/hw/hw.go package hw import ( "fmt" "sync/atomic" "time" "unsafe" "ndsemu/emu/gfx" log "ndsemu/emu/logger" "github.com/veandco/go-sdl2/sdl" ) const ( kHwAudioBuffers = 3 ) type OutputConfig struct { Title string // Name of the window (displayed in titlebar) Width, Height int // Size of the window in pixels FramePerSecond int // Number of frames per second when running at full speed EnforceSpeed bool // True if we want to block to enforce the requested FramePerSecond / Audio.Frequency AudioFrequency int // Audio frequency in hertz AudioChannels int // Number of output channels (1 or 2) AudioSampleSigned bool // True if samples are signed, False if unsigned } type Output struct { cfg OutputConfig screen *sdl.Window renderer *sdl.Renderer frame *sdl.Texture framebuf [2][]byte framebufidx int videoEnabled bool audioEnabled bool framecounter int fpscounter int fpsclock uint32 audiocounter int32 // atomic aindexw int32 // atomic aindexr int32 // atomic audiobuf [kHwAudioBuffers]AudioBuffer } func NewOutput(cfg OutputConfig) *Output { if sdl.WasInit(sdl.INIT_VIDEO|sdl.INIT_AUDIO) == 0 { sdl.Init(sdl.INIT_VIDEO | sdl.INIT_AUDIO) } return &Output{ cfg: cfg, framebuf: [2][]byte{ make([]byte, cfg.Width*cfg.Height*4), make([]byte, cfg.Width*cfg.Height*4), }, } } func (out *Output) EnableVideo(enable bool) { if enable && !out.videoEnabled { var err error out.screen, err = sdl.CreateWindow(out.cfg.Title, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, out.cfg.Width*4/2, out.cfg.Height*4/2, sdl.WINDOW_RESIZABLE) if err != nil { panic(err) } // Create a renderer than never sync with vsync. // Syncing is always done with audio, not vsync, out.renderer, err = sdl.CreateRenderer(out.screen, -1, 0) if err != nil { panic(err) } out.renderer.SetLogicalSize(out.cfg.Width, out.cfg.Height) // make the scaled rendering look smoother. sdl.SetHint(sdl.HINT_RENDER_SCALE_QUALITY, "nearest") out.frame, err = out.renderer.CreateTexture( sdl.PIXELFORMAT_ABGR8888, sdl.TEXTUREACCESS_STREAMING, out.cfg.Width, out.cfg.Height) if err != nil { panic(err) } } else { out.frame.Destroy() out.frame = nil out.renderer.Destroy() out.renderer = nil out.screen.Destroy() out.screen = nil } out.videoEnabled = enable } func (out *Output) EnableAudio(enable bool) { if !enable { panic("unimplemented") } var format sdl.AudioFormat if out.cfg.AudioSampleSigned { format = sdl.AUDIO_S16 } else { format = sdl.AUDIO_U16 } if out.cfg.AudioFrequency%out.cfg.FramePerSecond != 0 { panic("audio frequency must be a multiple of frames-per-second") } samplesPerFrame := out.cfg.AudioFrequency / out.cfg.FramePerSecond for i := range out.audiobuf { out.audiobuf[i] = make(AudioBuffer, samplesPerFrame*out.cfg.AudioChannels) } spec := sdl.AudioSpec{ Freq: int32(out.cfg.AudioFrequency), Format: format, Channels: uint8(out.cfg.AudioChannels), Samples: uint16(samplesPerFrame), } out.audioSpecSetCallback(&spec) if dev, err := sdl.OpenAudioDevice("", false, &spec, nil, 0); err != nil { panic(err) } else { sdl.PauseAudioDevice(dev, false) } out.audioEnabled = enable } func (out *Output) BeginFrame() (gfx.Buffer, AudioBuffer) { out.framebufidx = 1 - out.framebufidx fbuf := gfx.NewBuffer(unsafe.Pointer(&out.framebuf[out.framebufidx][0]), out.cfg.Width, out.cfg.Height, out.cfg.Width*4) aindexw := atomic.LoadInt32(&out.aindexw) if aindexw >= atomic.LoadInt32(&out.aindexr)+kHwAudioBuffers { if out.cfg.EnforceSpeed { log.ModHw.WithFields(log.Fields{ "fc": fmt.Sprintf("%04d", out.framecounter), "ar": fmt.Sprintf("%04d", atomic.LoadInt32(&out.aindexr)), "aw": fmt.Sprintf("%04d", atomic.LoadInt32(&out.aindexw)), }).Warn("overflow audio buffer (producing too fast)") } } abuf := out.audiobuf[aindexw%kHwAudioBuffers] atomic.AddInt32(&out.aindexw, 1) return fbuf, abuf } func (out *Output) EndFrame(screen gfx.Buffer, audio AudioBuffer) { out.framecounter++ if out.videoEnabled { if int(atomic.LoadInt32(&out.audiocounter)) < out.framecounter { out.frame.Update(nil, screen.Pointer(), out.cfg.Width*4) out.renderer.Clear() out.renderer.Copy(out.frame, nil, nil) out.renderer.Present() out.fpscounter++ if out.cfg.EnforceSpeed { // Wait until audio catches up; this is where we slow down emulation // to match the desired framerate (but we do that syncing with audio // rathern than a timer). for int(atomic.LoadInt32(&out.audiocounter)) < out.framecounter { time.Sleep(1 * time.Millisecond) } } } if out.fpsclock+1000 < sdl.GetTicks() { out.screen.SetTitle(fmt.Sprintf("%s - %d FPS", out.cfg.Title, out.fpscounter)) out.fpscounter = 0 out.fpsclock += 1000 } } } func (out *Output) audioCallback(outbuf []int16) { aindexr := atomic.LoadInt32(&out.aindexr) if out.aindexr == atomic.LoadInt32(&out.aindexw) { // fmt.Println("audio underflow: no audio generated, silencing") for i := range outbuf { outbuf[i] = 0 } return } buf := out.audiobuf[aindexr%kHwAudioBuffers] if len(buf) != len(outbuf) { fmt.Println(len(buf), len(outbuf)) panic("invalid audio buffer size") } copy(outbuf, buf) atomic.AddInt32(&out.aindexr, 1) atomic.AddInt32(&out.audiocounter, 1) } type MouseButtons int const ( MouseButtonLeft MouseButtons = 1 << iota MouseButtonMiddle MouseButtonRight ) func (out *Output) GetMouseState() (x, y int, buttons MouseButtons) { x, y, state := sdl.GetMouseState() // Scale back to logical size w, h := out.screen.GetSize() x = x * out.cfg.Width / w y = y * out.cfg.Height / h if state&sdl.BUTTON_LEFT != 0 { buttons |= MouseButtonLeft } if state&sdl.BUTTON_RIGHT != 0 { buttons |= MouseButtonRight } if state&sdl.BUTTON_MIDDLE != 0 { buttons |= MouseButtonMiddle } return x, y, buttons } func GetKeyboardState() []uint8 { return sdl.GetKeyboardState() } func (out *Output) Poll() bool { for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch t := event.(type) { case *sdl.QuitEvent: return false case *sdl.KeyDownEvent: if t.Keysym.Sym == sdl.K_ESCAPE { return false } } } return true } func (out *Output) Screenshot(fn string) error { surf, err := sdl.CreateRGBSurfaceFrom( unsafe.Pointer(&out.framebuf[0]), out.cfg.Width, out.cfg.Height, 32, out.cfg.Width*4, 0x00000FF, 0x0000FF00, 0x00FF0000, 0) if err != nil { return err } surf.SaveBMP(fn) surf.Free() return nil } <file_sep>/e2d/mode1_obj.go package e2d import ( "ndsemu/emu" "ndsemu/emu/gfx" ) const ( objPixModeNormal = iota objPixModeAlpha objPixModeWindow objPixModeBitmap ) const ( objModeNormal = iota objModeAffine objModeHidden objModeAffineDouble ) var objWidth = []struct{ w, h int }{ // square {1, 1}, {2, 2}, {4, 4}, {8, 8}, // horizontal {2, 1}, {4, 1}, {4, 2}, {8, 4}, // vertical {1, 2}, {1, 4}, {2, 4}, {4, 8}, } func objBitmap_CalcAddress_2D128(tilenum int) int { return int((tilenum&0xF)*0x10 + (tilenum & ^0xF)*0x80) } func objBitmap_CalcAddress_2D256(tilenum int) int { return int((tilenum&0x1F)*0x10 + (tilenum & ^0x1F)*0x80) } func objBitmap_CalcAddress_1D128(tilenum int) int { return int(tilenum) * 128 } func objBitmap_CalcAddress_1D256(tilenum int) int { return int(tilenum) * 256 } func (e2d *HwEngine2d) DrawOBJ(ctx *gfx.LayerCtx, lidx int, sy int) { oam := e2d.mc.VramOAM(e2d.Idx) tiles := e2d.mc.VramLinearBank(e2d.Idx, VramLinearOAM, 0) mapping1d := (e2d.DispCnt.Value>>4)&1 != 0 boundary := 32 if mapping1d { boundary <<= (e2d.DispCnt.Value >> 20) & 3 } var vramBitmapCalcAddress func(int) int var objPitch int bitmapMapping1d := (e2d.DispCnt.Value>>6)&1 != 0 if !bitmapMapping1d { // OBJ Bitmap 2D mapping if (e2d.DispCnt.Value>>5)&1 == 0 { vramBitmapCalcAddress = objBitmap_CalcAddress_2D128 objPitch = 16 } else { vramBitmapCalcAddress = objBitmap_CalcAddress_2D256 objPitch = 32 } } else { // OBJ Bitmap 1D mapping if (e2d.DispCnt.Value>>22)&1 == 0 { vramBitmapCalcAddress = objBitmap_CalcAddress_1D128 } else { vramBitmapCalcAddress = objBitmap_CalcAddress_1D256 } } if e2d.A() && false { for i := 0; i < 128; i++ { a0, a1, _ := emu.Read16LE(oam[i*8:]), emu.Read16LE(oam[i*8+2:]), emu.Read16LE(oam[i*8+4:]) y := int(a0 & 0xff) x := int(a1 & 0x1ff) affine := (a0 >> 8) & 3 if affine == 2 { continue } if affine != 0 { aparms := ((a1 >> 9) & 0x1F) sz := objWidth[((a0>>14)<<2)|(a1>>14)] tw, th := sz.w, sz.h modLcd.Infof("oam=%d: pos=%d,%d sz=%d,%d aff=%d[%d]", i, x, y, tw, th, affine, aparms) } } for i := 0; i < 4; i++ { parms := i*0x20 + 0x6 dx := int(int16(emu.Read16LE(oam[parms:]))) dmx := int(int16(emu.Read16LE(oam[parms+8:]))) dy := int(int16(emu.Read16LE(oam[parms+16:]))) dmy := int(int16(emu.Read16LE(oam[parms+24:]))) modLcd.Infof("OBJ Parm %d: (%f,%f)-(%f,%f)", i, float32(dx)/256.0, float32(dy)/256.0, float32(dmx)/256.0, float32(dmy)/256.0) } } for { line := ctx.NextLine() if line.IsNil() { return } // If sprites are globally disabled, nothing to do if e2d.DispCnt.Value&(1<<12) == 0 { sy++ continue } useExtPal := (e2d.DispCnt.Value & (1 << 31)) != 0 // Go through the sprite list in reverse order, because an object with // lower index has HIGHER priority (so it gets drawn in front of all). // FIXME: This is actually a temporary hack because it will fail once we // emulate the sprite line limits; the correct solution would be // to go through in the correct order, but avoiding writing pixels // that have been already written to. for i := 127; i >= 0; i-- { a0, a1, a2 := emu.Read16LE(oam[i*8:]), emu.Read16LE(oam[i*8+2:]), emu.Read16LE(oam[i*8+4:]) // Sprite mode: 0=normal, 1=affine, 2=hidden, 3=affine double // We immediately skip hidden sprites, so from this point onward, // affine!=0 means affine mode. mode := (a0 >> 8) & 3 if mode == objModeHidden { continue } // Sprite pixel mode: 0=normal, 1=semi-transparent, 2=window, 3=bitmap pixmode := (a0 >> 10) & 3 const XMask = 0x1FF const YMask = 0xFF x := int(a1 & XMask) y := int(a0 & YMask) if x >= cScreenWidth { x -= XMask + 1 } if y >= cScreenHeight { y -= YMask + 1 } // Get the object size. The size is expressed in number of chars, // not pixels. sz := objWidth[((a0>>14)<<2)|(a1>>14)] tw, th := sz.w, sz.h tws, ths := tw, th if mode == objModeAffineDouble { tws *= 2 ths *= 2 } // If the sprite is visible // FIXME: this doesn't handle wrapping yet if sy >= y && sy < (y+ths*8) && (x < cScreenWidth && (x+tws*8) >= 0) { tilenum := int(a2 & 1023) depth256 := (a0>>13)&1 != 0 hflip := (a1>>12)&1 != 0 && mode == objModeNormal // hflip not available in affine mode vflip := (a1>>13)&1 != 0 && mode == objModeNormal // vflip not available in affine mode pri := (a2 >> 10) & 3 pal := (a2 >> 12) & 0xF // Size of a char (in byte), depending on the color setting charSize := 32 if depth256 { charSize = 64 } // Compute the offset within VRAM of the current object (for // now, its top-left pixel) var vramOffset int if pixmode == objPixModeBitmap { vramOffset = vramBitmapCalcAddress(tilenum) } else { vramOffset = tilenum * boundary } // Compute the line being drawn *within* the current object. // This must also handle vertical flip (in which the whole // object is flipped, not just the single chars) y0 := (sy - y) if vflip { y0 = ths*8 - y0 - 1 } // Calculate the pitch of a sprite, expressed in number of chars) // This depends on the 1D vs 2D tile mapping in VRAM; 1D // mapping means that tiles are arranged linearly in memory so the // pitch is just the size of the sprite (in tiles). // In 2D mapping, tiles are arranged in a 2D grid with a fixed size // depending on the BPP, and thus not pitch := tw if pixmode == objPixModeBitmap { if !bitmapMapping1d { pitch = objPitch } } else { if !mapping1d { if depth256 { pitch = 16 } else { pitch = 32 } } } // See if we need to draw in affine mode if mode != objModeNormal { if pixmode == objPixModeBitmap { panic("bitmap mode not supported in affine") } parms := ((a1>>9)&0x1F)*0x20 + 0x6 dx := int(int16(emu.Read16LE(oam[parms:]))) dmx := int(int16(emu.Read16LE(oam[parms+8:]))) dy := int(int16(emu.Read16LE(oam[parms+16:]))) dmy := int(int16(emu.Read16LE(oam[parms+24:]))) sx := (tw*8/2)<<8 - (tws*8/2)*dx - (ths*8/2)*dmx + y0*dmx sy := (th*8/2)<<8 - (tws*8/2)*dy - (ths*8/2)*dmy + y0*dmy src := tiles.FetchPointer(vramOffset) dst := line attrs := uint32(pri) << 29 if depth256 { if useExtPal { attrs |= uint32(pal<<8) | (1 << 12) } } else { attrs |= uint32(pal << 4) if useExtPal { attrs |= (1 << 12) } } for j := 0; j < tws*8; j++ { if x >= 0 && x < cScreenWidth { isx, isy := sx>>8, sy>>8 if isx >= 0 && isx < tw*8 && isy >= 0 && isy < th*8 { ty := isy / 8 off := (pitch * charSize) * ty isy &= 7 tx := isx / 8 off += charSize * tx isx &= 7 if depth256 { pix := uint32(src[off+isy*8+isx]) if pix != 0 { dst.Set32(x, pix|attrs) } } else { pix := uint32(src[off+isy*4+isx/2]) pix >>= 4 * uint(isx&1) pix &= 0xF if pix != 0 { dst.Set32(x, pix|attrs) } } } } sx += dx sy += dy x++ } } else { if pixmode == objPixModeBitmap { if hflip { modLcd.Fatal("horizontal flip in obj bitmap") } vramOffset += (pitch * 8 * y0) * 2 src := tiles.FetchPointer(vramOffset) dst := line attrs := (uint32(pri) << 29) | 0x80000000 for j := 0; j < tw*8; j++ { if x >= 0 && x < cScreenWidth { px := uint32(emu.Read16LE(src[j*2:])) dst.Set32(x, px|attrs) } x++ } } else { // Calculate the char row being drawn. ty := y0 / 8 // Adjust the offset to the beginning of the correct char row // within the object. vramOffset += (pitch * charSize) * ty // Now calculate the line being drawn within the current char row y0 &= 7 // Prepare initial src/dst pointer for drawing src := tiles.FetchPointer(vramOffset) dst := line dst.Add32(x) for j := 0; j < tw; j++ { tsrc := src[charSize*j:] if hflip { tsrc = src[charSize*(tw-j-1):] } if x > -8 && x < cScreenWidth { if depth256 { if !useExtPal { pal = 0 } e2d.drawChar256(y0, tsrc, dst, hflip, pri, pal, useExtPal) } else { e2d.drawChar16(y0, tsrc, dst, hflip, pri, pal, false) } } dst.Add32(8) x += 8 } } } } } sy++ } } <file_sep>/e2d/mode3.go package e2d import "ndsemu/emu/gfx" /************************************************ * Display Mode 3: Main memory display ************************************************/ func (e2d *HwEngine2d) Mode3_BeginFrame() { modLcd.Warn("mode 3 not implemented") } func (e2d *HwEngine2d) Mode3_EndFrame() {} func (e2d *HwEngine2d) Mode3_BeginLine(y int, screen gfx.Line) { for x := 0; x < cScreenWidth; x++ { screen.Set32(x, 0x0000FF) } } func (e2d *HwEngine2d) Mode3_EndLine(y int) {} <file_sep>/raster3d/engine3d.go package raster3d import ( "fmt" "ndsemu/emu" "ndsemu/emu/gfx" "ndsemu/emu/hwio" log "ndsemu/emu/logger" "ndsemu/raster3d/fillerconfig" "os" "sort" "sync" ) var mod3d = log.NewModule("e3d") const ( kFarClipping = 512 ) type buffer3d struct { Vram []Vertex Pram []Polygon } func (b *buffer3d) Reset() { b.Vram = b.Vram[:0] b.Pram = b.Pram[:0] } type HwEngine3d struct { Disp3dCnt hwio.Reg32 `hwio:"offset=0,rwmask=0x7FFF"` ToonTable hwio.Mem `hwio:"bank=1,offset=0x80,size=0x40,writeonly"` // Channel to receive new primitives (sent by GxFifo) CmdCh chan interface{} // Current viewport (last received viewport command) viewport Primitive_SetViewport pool sync.Pool // Current vram/pram (being drawn) cur buffer3d // Next vram/pram (being accumulated for next frame) next buffer3d nextCh chan buffer3d // Texture/palette VRAM texVram VramTextureBank palVram VramTexturePaletteBank // Cache for decompressed textures. This currently handles // Tex4x4 format as it's too hard to polyfill directly from // the compressed format. texCache texCache framecnt int } func NewHwEngine3d() *HwEngine3d { e3d := new(HwEngine3d) hwio.MustInitRegs(e3d) e3d.CmdCh = make(chan interface{}, 4096) e3d.pool.New = func() interface{} { return buffer3d{ Vram: make([]Vertex, 0, 8192), Pram: make([]Polygon, 0, 8192), } } e3d.next = e3d.pool.Get().(buffer3d) e3d.nextCh = make(chan buffer3d) // must be non buffered! go e3d.recvCmd() return e3d } func (e3d *HwEngine3d) recvCmd() { for { cmdi := <-e3d.CmdCh switch cmd := cmdi.(type) { case Primitive_SwapBuffers: e3d.cmdSwapBuffers(cmd) case Primitive_SetViewport: e3d.viewport = cmd case Primitive_Polygon: e3d.cmdPolygon(cmd) case Primitive_Vertex: e3d.cmdVertex(cmd) default: panic("invalid command received in HwEnginge3D") } } } func (vtx *Vertex) calcClippingFlags() { // Compute clipping flags (once per vertex) if vtx.cx.V < -vtx.cw.V { vtx.flags |= RVFClipLeft } if vtx.cx.V > vtx.cw.V { vtx.flags |= RVFClipRight } if vtx.cy.V < -vtx.cw.V { vtx.flags |= RVFClipBottom } if vtx.cy.V > vtx.cw.V { vtx.flags |= RVFClipTop } if vtx.cw.V < 0 { vtx.flags |= RVFClipNear } if vtx.cw.V > emu.NewFixed12(kFarClipping).V { vtx.flags |= RVFClipFar } // If w==0, we just flag the vertex as fully outside of the screen // FIXME: properly handle invalid inputs // if vtx.cw.V == 0 { // vtx.flags |= RVFClipAnything // } } func (e3d *HwEngine3d) cmdVertex(cmd Primitive_Vertex) { vtx := Vertex{ cx: cmd.X, cy: cmd.Y, cz: cmd.Z, cw: cmd.W, s: cmd.S, t: cmd.T, rgb: newColorFrom555(cmd.C[0], cmd.C[1], cmd.C[2]), } vtx.calcClippingFlags() e3d.next.Vram = append(e3d.next.Vram, vtx) } func (e3d *HwEngine3d) cmdPolygon(cmd Primitive_Polygon) { flags := PolygonFlags(cmd.Attr) var vinbuf [4]*Vertex vtxs := vinbuf[:0] // FIXME: for now, skip all polygons outside the screen count := 3 if flags&PFQuad != 0 { count = 4 flags &^= PFQuad } clipany := RenderVertexFlags(0) clipall := RVFClipMask for i := 0; i < count; i++ { if cmd.Vtx[i] >= len(e3d.next.Vram) || cmd.Vtx[i] < 0 { mod3d.Fatalf("wrong polygon index: %d (num vtx: %d)", cmd.Vtx[i], len(e3d.next.Vram)) } vtx := &e3d.next.Vram[cmd.Vtx[i]] clipany |= (vtx.flags & RVFClipMask) clipall &= (vtx.flags & RVFClipMask) vtxs = append(vtxs, vtx) } // If all vertices are out of the same plane (any of them), // the polygon is fully out, so clip it. if clipall != 0 { return } // Transform all vertices (that weren't transformed already) for _, vtx := range vtxs { e3d.vtxTransform(vtx) } // Do backface culling d0x := vtxs[0].x.SubFixed(vtxs[1].x) d0y := vtxs[0].y.SubFixed(vtxs[1].y) d1x := vtxs[2].x.SubFixed(vtxs[1].x) d1y := vtxs[2].y.SubFixed(vtxs[1].y) if int64(d0x.V)*int64(d1y.V) <= int64(d1x.V)*int64(d0y.V) { // Facing the back: see if we must render the back if flags&PFRenderBack == 0 { return } } else { // Facing the front: see if we must render the front if flags&PFRenderFront == 0 { return } } // Do clipping if clipany != 0 { vtxs = e3d.polyClip(vtxs) if vtxs == nil { return } } // Transform all vertices (that weren't transformed already) for _, vtx := range vtxs { // vtx.calcClippingFlags() // if vtx.flags != 0 { // fmt.Printf("vtx:(%v,%v,%v,%v) clip=%x clipany=%x\n", vtx.cx, vtx.cy, vtx.cz, vtx.cw, vtx.flags, clipany) // panic("clipping failed") // } e3d.vtxTransform(vtx) } // Split the clipped polygon into triangles and add them to pram for i := 1; i < len(vtxs)-1; i++ { poly := Polygon{ flags: flags, tex: cmd.Tex, vtx: [3]*Vertex{ vtxs[0], vtxs[i], vtxs[i+1], }, } e3d.next.Pram = append(e3d.next.Pram, poly) } } func (v0 *Vertex) Lerp(v1 *Vertex, ratio emu.Fixed12) *Vertex { vout := new(Vertex) vout.cx = v0.cx.Lerp(v1.cx, ratio) vout.cy = v0.cy.Lerp(v1.cy, ratio) vout.cz = v0.cz.Lerp(v1.cz, ratio) vout.cw = v0.cw.Lerp(v1.cw, ratio) vout.s = v0.s.Lerp(v1.s, ratio) vout.t = v0.t.Lerp(v1.t, ratio) vout.rgb = v0.rgb.Lerp(v1.rgb, ratio) return vout } var clipFormulas = [...]struct { Plane RenderVertexFlags PlaneCoord func(*Vertex) emu.Fixed12 PlaneSetCoord func(*Vertex, emu.Fixed12) }{ { RVFClipNear, func(v *Vertex) emu.Fixed12 { return emu.NewFixed12(0) }, func(v *Vertex, f emu.Fixed12) {}, }, { RVFClipFar, func(v *Vertex) emu.Fixed12 { return emu.NewFixed12(kFarClipping) }, func(v *Vertex, f emu.Fixed12) {}, }, { RVFClipTop, func(v *Vertex) emu.Fixed12 { return v.cy }, func(v *Vertex, f emu.Fixed12) { v.cy = f }, }, { RVFClipBottom, func(v *Vertex) emu.Fixed12 { return v.cy.Neg() }, func(v *Vertex, f emu.Fixed12) { v.cy = f.Neg() }, }, { RVFClipLeft, func(v *Vertex) emu.Fixed12 { return v.cx.Neg() }, func(v *Vertex, f emu.Fixed12) { v.cx = f.Neg() }, }, { RVFClipRight, func(v *Vertex) emu.Fixed12 { return v.cx }, func(v *Vertex, f emu.Fixed12) { v.cx = f }, }, } func (e3d *HwEngine3d) polyClip(poly []*Vertex) (clipped []*Vertex) { // fmt.Printf("begin clipping\n") // defer fmt.Printf("end clipping\n") for _, clipInfo := range clipFormulas { // fmt.Printf("begin clipping: plane %x\n", clipInfo.Plane) // for _, v := range poly { // fmt.Printf("vtx: %v,%v,%v,%v flags=%x\n", // v.cx, v.cy, v.cz, v.cw, // v.flags) // } last := poly[len(poly)-1] lastOut := last.flags&clipInfo.Plane != 0 for _, v := range poly { if (v.flags&clipInfo.Plane != 0 && !lastOut) || (v.flags&clipInfo.Plane == 0 && lastOut) { v0 := last dist1 := v0.cw.SubFixed(clipInfo.PlaneCoord(v0)) dist2 := v.cw.SubFixed(clipInfo.PlaneCoord(v)) if dist1.SubFixed(dist2).V == 0 { return nil } ratio := dist1.DivFixed(dist1.SubFixed(dist2)) vout := v0.Lerp(v, ratio) clipInfo.PlaneSetCoord(vout, vout.cw) // vout.cw = clipInfo.PlaneCoord(vout) // fix rounding errors vout.calcClippingFlags() // fmt.Printf("clip %d: %v,%v,%v,%v ratio:%v flags:%x\n", // idx, // vout.cx, vout.cy, vout.cz, vout.cw, // ratio, vout.flags) clipped = append(clipped, vout) } last = v if v.flags&clipInfo.Plane == 0 { lastOut = false clipped = append(clipped, v) } else { lastOut = true } } // for _, v := range clipped { // if v.flags&clipInfo.Plane != 0 { // panic("ahahah") // } // } // FIXME: check if it's really required if len(clipped) == 0 { return nil } poly = clipped clipped = nil } for _, v := range poly { v.cx = v.cx.Clamp(v.cw.Neg(), v.cw) v.cy = v.cy.Clamp(v.cw.Neg(), v.cw) v.cz = v.cz.Clamp(v.cw.Neg(), v.cw) // if v.flags&RVFClipMask != 0 { // fmt.Printf("vtx: %v,%v,%v,%v flags=%x\n", v.cx, v.cy, v.cz, v.cw, v.flags) // panic("ahahah2") // } } return poly } func (e3d *HwEngine3d) vtxTransform(vtx *Vertex) { if vtx.flags&RVFTransformed != 0 { return } viewwidth := emu.NewFixed12(int32(e3d.viewport.VX1 - e3d.viewport.VX0)) viewheight := emu.NewFixed12(int32(e3d.viewport.VY1 - e3d.viewport.VY0)) // Compute viewsize / (2*v.w) in two steps, to avoid overflows // (viewwidth could be 256<<12, which would overflow when further // shifted in preparation for division) dx := viewwidth.Div(2).DivFixed(vtx.cw) dy := viewheight.Div(2).DivFixed(vtx.cw) mirror := vtx.cw.Mul(2) // sx = (v.x + v.w) * viewwidth / (2*v.w) + viewx0 // sy = (v.y + v.w) * viewheight / (2*v.w) + viewy0 vtx.x = vtx.cx.AddFixed(vtx.cw).MulFixed(dx).Add(int32(e3d.viewport.VX0)).Round() vtx.y = mirror.SubFixed(vtx.cy.AddFixed(vtx.cw)).MulFixed(dy).Add(int32(e3d.viewport.VY0)).Round() vtx.z = vtx.cz.AddFixed(vtx.cw).Div(2).DivFixed(vtx.cw) // Clamp screen coord. This is only required because clipping in clip-space // cannot be accurate with fixed point coordinates (at least not with 12 bit), // and thus it can generate coordinates that are slightly out vtx.x = vtx.x.Clamp(emu.NewFixed12(int32(e3d.viewport.VX0)), emu.NewFixed12(int32(e3d.viewport.VX1))) vtx.y = vtx.y.Clamp(emu.NewFixed12(int32(e3d.viewport.VY0)), emu.NewFixed12(int32(e3d.viewport.VY1))) vtx.flags |= RVFTransformed } func (e3d *HwEngine3d) preparePolys() { for idx := range e3d.next.Pram { poly := &e3d.next.Pram[idx] v0, v1, v2 := poly.vtx[0], poly.vtx[1], poly.vtx[2] // Sort the three vertices by the Y coordinate (v0=top, v1=middle, 2=bottom) if v0.y.V > v1.y.V { v0, v1 = v1, v0 poly.vtx[0], poly.vtx[1] = poly.vtx[1], poly.vtx[0] } if v0.y.V > v2.y.V { v0, v2 = v2, v0 poly.vtx[0], poly.vtx[2] = poly.vtx[2], poly.vtx[0] } if v1.y.V > v2.y.V { v1, v2 = v2, v1 poly.vtx[1], poly.vtx[2] = poly.vtx[2], poly.vtx[1] } hy1 := v1.y.TruncInt32() - v0.y.TruncInt32() hy2 := v2.y.TruncInt32() - v1.y.TruncInt32() if hy1 < 0 || hy2 < 0 { panic("invalid y order") } // Calculate the four slopes for each coordinate. The coordinates // we need to interpolate are: position (X), depth (Z), texture (S & T). // // Assuming a triangle where: // * v0 is at top // * v1 is middle left // * v2 is bottom // we need two slopes for the left segments (from v0 to v1, and then from v1 to v2), and // one slope for the right segment (from v0 to v2). To make the line-based rasterizer // simpler, we consider the triangle virtually split in half at the v1 // level, so we calculate two slopes for each half-triangle; in our example, the right // slopes for the upper and lower part will obviously be the same (as it's just one // segment). var dxl0, dxl1, dxr0, dxr1 emu.Fixed22 var dzl0, dzl1, dzr0, dzr1 emu.Fixed22 var dsl0, dsl1, dsr0, dsr1 emu.Fixed12 var dtl0, dtl1, dtr0, dtr1 emu.Fixed12 var dcl0, dcl1, dcr0, dcr1 colorDelta dxl0 = v1.x.SubFixed(v0.x).ToFixed22() dzl0 = v1.z.SubFixed(v0.z).ToFixed22() dsl0 = v1.s.SubFixed(v0.s) dtl0 = v1.t.SubFixed(v0.t) dcl0 = v1.rgb.SubColor(v0.rgb) dxl1 = v2.x.SubFixed(v1.x).ToFixed22() dzl1 = v1.z.SubFixed(v1.z).ToFixed22() dsl1 = v2.s.SubFixed(v1.s) dtl1 = v2.t.SubFixed(v1.t) dcl1 = v2.rgb.SubColor(v1.rgb) if hy1 > 0 { dxl0 = dxl0.Div(hy1) dzl0 = dzl0.Div(hy1) dsl0 = dsl0.Div(hy1) dtl0 = dtl0.Div(hy1) dcl0 = dcl0.Div(hy1) } if hy2 > 0 { dxl1 = dxl1.Div(hy2) dzl1 = dzl1.Div(hy2) dsl1 = dsl1.Div(hy2) dtl1 = dtl1.Div(hy2) dcl1 = dcl1.Div(hy2) } if hy1+hy2 > 0 { dxr0 = v2.x.SubFixed(v0.x).ToFixed22().Div(hy1 + hy2) dzr0 = v2.z.SubFixed(v0.z).ToFixed22().Div(hy1 + hy2) dsr0 = v2.s.SubFixed(v0.s).Div(hy1 + hy2) dtr0 = v2.t.SubFixed(v0.t).Div(hy1 + hy2) dcr0 = v2.rgb.SubColor(v0.rgb).Div(hy1 + hy2) dxr1 = dxr0 dzr1 = dzr0 dsr1 = dsr0 dtr1 = dtr0 dcr1 = dcr0 } // Now create interpolator instances poly.left[LerpX] = newLerp(v0.x.ToFixed22(), dxl0, dxl1) poly.right[LerpX] = newLerp(v0.x.ToFixed22(), dxr0, dxr1) poly.left[LerpZ] = newLerp(v0.z.ToFixed22(), dzl0, dzl1) poly.right[LerpZ] = newLerp(v0.z.ToFixed22(), dzr0, dzr1) poly.left[LerpS] = newLerp12(v0.s, dsl0, dsl1) poly.right[LerpS] = newLerp12(v0.s, dsr0, dsr1) poly.left[LerpT] = newLerp12(v0.t, dtl0, dtl1) poly.right[LerpT] = newLerp12(v0.t, dtr0, dtr1) poly.left[LerpRGB] = newLerpFromInt(int32(v0.rgb), int32(dcl0), int32(dcl1)) poly.right[LerpRGB] = newLerpFromInt(int32(v0.rgb), int32(dcr0), int32(dcr1)) // If v0 and v1 lies on the same line (top segment), there is no upper // half of the triangle. In this case, we need the initial values of the lerp // to reflect this. Given that there was no divsion above, delta[0] is the // full different between v1 and v0, so we just need to add it to the start // coordinate (v0) to transform it into v1. if hy1 == 0 { if v0.x.V < v1.x.V { poly.left, poly.right = poly.right, poly.left for idx := range poly.left { rp := &poly.right[idx] rp.start += rp.delta[0] } } else { for idx := range poly.left { rp := &poly.left[idx] rp.start += rp.delta[0] } } } else { // We have assumed that the middle vertex is "on the left" (that is, // the segment between v0 and v1 is part of the left perimeter). // We check if that's the case, by simply comparing the calculated // slopes. If it's not true, we just swap all the calculated // interpolators. if dxl0.V > dxr0.V { poly.left, poly.right = poly.right, poly.left } } poly.hy = v1.y.TruncInt32() // if poly.flags.ColorMode() == fillerconfig.ColorModeToon { // left := poly.left[LerpRGB] // right := poly.right[LerpRGB] // left.Reset() // right.Reset() // log.Mod3d.Infof("toon polygon dump: %x,%x,%x", v0.rgb, v1.rgb, v2.rgb) // for i := 0; i < int(hy1); i++ { // log.Mod3d.Infof("step: %x,%x", left.cur, right.cur) // left.Next(0) // right.Next(0) // } // } } } type polySorter []Polygon func (p polySorter) Len() int { return len(p) } func (p polySorter) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p polySorter) Less(i, j int) bool { ai := p[i].flags.Alpha() aj := p[j].flags.Alpha() return aj > ai } func (e3d *HwEngine3d) sortPolys() { // Do a stable sort, so that we keep the existing order for all // solid polygons (alpha=0x1F). This should be consistent with the order // the NDS renderes the display list. sort.Stable(polySorter(e3d.next.Pram)) } func (e3d *HwEngine3d) polysSetWBuffer() { for idx := range e3d.next.Pram { poly := &e3d.next.Pram[idx] // Change screen Z coordinates with W (from clipping space, // which is obvioulsy the only one that exists). Polyfilers use // the screen Z for zbuffering, so this basically switches to // W-buffering. poly.vtx[0].z = poly.vtx[0].cw poly.vtx[1].z = poly.vtx[1].cw poly.vtx[2].z = poly.vtx[2].cw } } func (e3d *HwEngine3d) dumpNextScene() { if e3d.framecnt == 0 { os.Remove("dump3d.txt") } f, err := os.OpenFile("dump3d.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) if err != nil { panic(err) } defer f.Close() fmt.Fprintf(f, "begin scene\n") for idx, poly := range e3d.next.Pram { v0, v1, v2 := poly.vtx[0], poly.vtx[1], poly.vtx[2] fmt.Fprintf(f, "tri %d:\n", idx) fmt.Fprintf(f, " ccoord: (%v,%v,%v,%v)-(%v,%v,%v,%v)-(%v,%v,%v,%v)\n", v0.cx, v0.cy, v0.cz, v0.cw, v1.cx, v1.cy, v1.cz, v1.cw, v2.cx, v2.cy, v2.cz, v2.cw) fmt.Fprintf(f, " scoord: (%v,%v)-(%v,%v)-(%v,%v)\n", v0.x.TruncInt32(), v0.y.TruncInt32(), v1.x.TruncInt32(), v1.y.TruncInt32(), v2.x.TruncInt32(), v2.y.TruncInt32()) // fmt.Fprintf(f, " tex: (%v,%v)-(%v,%v)-(%v,%v)\n", // v0.s, v0.t, // v1.s, v1.t, // v2.s, v2.t) // fmt.Fprintf(f, " left lerps: %v\n", poly.left) // fmt.Fprintf(f, " right lerps: %v\n", poly.right) // fmt.Fprintf(f, " hy: %v\n", poly.hy) fmt.Fprintf(f, " flags: %08x\n", poly.flags) fmt.Fprintf(f, " tex: fmt=%d, flips=%v, flipt=%v, reps=%v, rept=%v\n", poly.tex.Format, poly.tex.Flags&TexSFlip != 0, poly.tex.Flags&TexTFlip != 0, poly.tex.Flags&TexSRepeat != 0, poly.tex.Flags&TexTRepeat != 0) } mod3d.Infof("end scene") } func (e3d *HwEngine3d) cmdSwapBuffers(cmd Primitive_SwapBuffers) { // The next frame primitives are complete; we can now do full-frame processing // in preparation for drawing next frame // Turn on wbuffering instead of zbuffering, if requested if cmd.WBuffering { e3d.polysSetWBuffer() } // Computer interpolators/slopes for all polygons e3d.preparePolys() // Sort polygons from back to front e3d.sortPolys() // Debug dump of scene // e3d.dumpNextScene() e3d.framecnt++ // Send the next buffer to the main rendering thread. Since the channel // is not buffered, this call will block until the other side reads, which is // at VBlank start. This is exactly what we expect from SwapBuffers: it blocks // until next VBlank. e3d.nextCh <- e3d.next // Get a new buffer from the pool, ready for next frame e3d.next = e3d.pool.Get().(buffer3d) } func (e3d *HwEngine3d) Draw3D(ctx *gfx.LayerCtx, lidx int, y int) { texMappingEnabled := e3d.Disp3dCnt.Value&1 != 0 // Initialize rasterizer. var polyPerLine [192][]uint16 for idx := range e3d.cur.Pram { poly := &e3d.cur.Pram[idx] // Set current segment to the initial one computed in preparePolys // This is required because we might need to redraw the exact // same 3D scene multiple times, so each time we want to start // from the beginning. for idx := range poly.left { poly.left[idx].Reset() poly.right[idx].Reset() } // If the polygon degrades to a segment, skip it for now (we don't support segments) v0, v1, v2 := poly.vtx[0], poly.vtx[1], poly.vtx[2] if (v0.x == v1.x && v0.y == v1.y) || (v1.x == v2.x && v1.y == v2.y) { // FIXME: implement segments continue } // Update the per-line polygon list, by adding this polygon's index // to the lines in which it is visible. for j := v0.y.TruncInt32(); j <= v2.y.TruncInt32(); j++ { polyPerLine[j] = append(polyPerLine[j], uint16(idx)) } // Setup the correct polyfiller for this fcfg := fillerconfig.FillerConfig{ TexFormat: uint(poly.tex.Format), ColorMode: poly.flags.ColorMode(), } if poly.tex.Flags&TexSRepeat == 0 || poly.tex.Flags&TexTRepeat == 0 { // If either S or T uses clamping, we need to use the full // calculation of texture coordinates. fcfg.TexCoords = fillerconfig.TexCoordsFull } else if poly.tex.Flags&TexSFlip != 0 || poly.tex.Flags&TexTFlip != 0 { // If either S or T uses flipping, we need to use the repeatorflip // calculation. fcfg.TexCoords = fillerconfig.TexCoordsRepeatOrFlip } else { // If both S and T uses repeat, we can use the repeatonly fast-path if poly.tex.Flags != TexSRepeat|TexTRepeat { panic("invalid tex flags") } fcfg.TexCoords = fillerconfig.TexCoordsRepeatOnly } // TexCoordsRepeatOnly is the fastest path. It can be selected // only if both S/T are configured in repeat mode, but we can also // force it if all vertices uses S/T within the texture size; // in that case, the repeat mode is basically ignored anyway, so // we can simply select the fastest path. if fcfg.TexCoords != fillerconfig.TexCoordsRepeatOnly { wrap := false for _, v := range poly.vtx { if v.s.V < 0 || v.t.V < 0 || v.s.TruncInt32() >= int32(poly.tex.Width) || v.t.TruncInt32() >= int32(poly.tex.Height) { wrap = true break } } if !wrap { fcfg.TexCoords = fillerconfig.TexCoordsRepeatOnly } } if poly.tex.Transparency { fcfg.ColorKey = 1 } if !texMappingEnabled { fcfg.TexFormat = 0 } switch poly.flags.Alpha() { case 31: fcfg.FillMode = fillerconfig.FillModeSolid case 0: fcfg.FillMode = fillerconfig.FillModeWireframe default: fcfg.FillMode = fillerconfig.FillModeAlpha } if fcfg.ColorMode == fillerconfig.ColorModeToon && e3d.Disp3dCnt.Value&(1<<1) != 0 { fcfg.ColorMode = fillerconfig.ColorModeHighlight } // log.Mod3d.Infof("polygon: %d - %+v (key:%x, alpha: %d)", idx, fcfg, fcfg.Key(), poly.flags.Alpha()) // if fcfg.ColorMode == fillerconfig.ColorModeToon { // log.Mod3d.Infof("toon: (%x,%x,%x)-(%x,%x,%x)\n", // poly.left[LerpRGB].cur, poly.left[LerpRGB].delta[0], poly.left[LerpRGB].delta[1], // poly.right[LerpRGB].cur, poly.right[LerpRGB].delta[0], poly.right[LerpRGB].delta[1]) // } poly.filler = polygonFillerTable[fcfg.Key()] } // FIXME: move elsewhere. Theoretically, 3d rendering begins // 19 lines before the first screen line, so it would be possible // to begin processing textures somewhere in the middle of vblank. // To be 100% sure, we can't do that when we receieve SwapBuffers // (that is, in the middle of previous frame) as the texture data // could not be ready. e3d.texCache.Update(e3d.cur.Pram, e3d) for { line := ctx.NextLine() if line.IsNil() { return } if e3d.Disp3dCnt.Value&(1<<14) != 0 { panic("bitmap") } var abuf [256]byte var zbuf [256 * 4]byte zbuffer := gfx.NewLine(zbuf[:]) abuffer := gfx.NewLine(abuf[:]) for i := 0; i < 256; i++ { zbuffer.Set32(i, 0x7FFFFFFF) abuffer.Set8(i, 0x1F) } for _, idx := range polyPerLine[y] { poly := &e3d.cur.Pram[idx] x0, x1 := poly.left[LerpX].Cur().NearInt32(), poly.right[LerpX].Cur().NearInt32() if x0 < 0 || x1 >= 256 || x1 < x0 { fmt.Printf("%v,%v\n", poly.vtx[0].x.TruncInt32(), poly.vtx[0].y.TruncInt32()) fmt.Printf("%v,%v\n", poly.vtx[1].x.TruncInt32(), poly.vtx[1].y.TruncInt32()) fmt.Printf("%v,%v\n", poly.vtx[2].x.TruncInt32(), poly.vtx[2].y.TruncInt32()) fmt.Printf("left lerps: %v\n", poly.left) fmt.Printf("right lerps: %v\n", poly.right) fmt.Printf("x0,x1=%v,%v y=%v, hy=%v\n", x0, x1, y, poly.hy) // panic("out of bounds") } else { poly.filler(e3d, poly, line, zbuffer, abuffer) } if int32(y) < poly.hy { for idx := 0; idx < NumLerps; idx++ { poly.left[idx].Next(0) poly.right[idx].Next(0) } } else { for idx := 0; idx < NumLerps; idx++ { poly.left[idx].Next(1) poly.right[idx].Next(1) } } } /* // TO BE TESTED for i := 0; i < 256; i++ { if abuffer.Get8(i) == 0 { line.Set16(i, 0) } } */ y++ } } func (e3d *HwEngine3d) SetVram(tex VramTextureBank, pal VramTexturePaletteBank) { e3d.texVram = tex e3d.palVram = pal } func (e3d *HwEngine3d) BeginFrame() { } func (e3d *HwEngine3d) EndFrame() { // We're now at vblank start. Read the pending buffer from SwapBuffers (if any). select { case next := <-e3d.nextCh: // OK got a new buffer. Recycle the current one into the pool e3d.cur.Reset() e3d.pool.Put(e3d.cur) e3d.cur = next default: // If there's no pending buffer, then it means that there was no new geometry // commands, or the commands are taking more than 1/60th of second to be elaborated; // in any case, it's too late; the same frame will be drawn again. } } func (e3d *HwEngine3d) NumVertices() int { return len(e3d.cur.Vram) } func (e3d *HwEngine3d) NumPolygons() int { return len(e3d.cur.Pram) } <file_sep>/arm/cp15.go package arm import ( "fmt" "ndsemu/emu" log "ndsemu/emu/logger" ) var modCp15 = log.NewModule("cp15") type Cp15 struct { cpu *Cpu regControl reg regControlRwMask uint32 regDtcmVsize reg regItcmVsize reg itcm []byte dtcm []byte itcmSizeMask uint32 dtcmSizeMask uint32 itcmBegin uint32 itcmEnd uint32 dtcmBegin uint32 dtcmEnd uint32 } // updateTcmConfig() recalculates the variables xtcmBegin/xtcmEnd, used by // CheckXTcm() to check whether an address lies withn the xTCM area. func (c *Cp15) updateTcmConfig() { if c.regControl.Bit(18) { // ITCM enable c.itcmBegin = uint32(c.regItcmVsize) & 0xFFFFF000 c.itcmEnd = c.itcmBegin + uint32(512<<uint((c.regItcmVsize>>1)&0x1F)) } else { // If the area is disabled, set these vars to a zero-sized area that // will never match the checks in CheckITcm. We use 0xFFFFFFFF instead // of 0x0 so that the first check in CheckITcm returns false (rather // than the second) c.itcmBegin = 0xFFFFFFFF c.itcmEnd = 0xFFFFFFFF } if c.regControl.Bit(16) { // DTCM enable c.dtcmBegin = uint32(c.regDtcmVsize) & 0xFFFFF000 c.dtcmEnd = c.dtcmBegin + uint32(512<<uint((c.regDtcmVsize>>1)&0x1F)) } else { c.dtcmBegin = 0xFFFFFFFF c.dtcmEnd = 0xFFFFFFFF } } // Check whether the specified address falls within the ITCM area, and returns // a slice to the referenced point. Returns nil if the address is outside, or // ITCM is disabled. func (c *Cp15) CheckITcm(addr uint32) []uint8 { if addr >= c.itcmBegin && addr < c.itcmEnd { addr = (addr - c.itcmBegin) & c.itcmSizeMask return c.itcm[addr:] } return nil } // Check whether the specified address falls within the DTCM area, and returns // a slice to the referenced point. Returns nil if the address is outside, or // DTCM is disabled. func (c *Cp15) CheckDTcm(addr uint32) []uint8 { if addr >= c.dtcmBegin && addr < c.dtcmEnd { addr = (addr - c.dtcmBegin) & c.dtcmSizeMask return c.dtcm[addr:] } return nil } func (c *Cp15) ExceptionVector() uint32 { if c.regControl.Bit(13) { return 0xFFFF0000 } else { return 0x00000000 } } func (c *Cp15) Read(op uint32, cn, cm, cp uint32) uint32 { if op != 0 { modCp15.WithField("op", op).Error("invalid op in read") return 0 } switch { case cn == 1 && cm == 0 && cp == 0: // modCp15.WithField("val", c.regControl).WithField("pc", c.cpu.GetPC()).Info("read control reg") return uint32(c.regControl) case cn == 9 && cm == 1 && cp == 0: // modCp15.WithField("val", c.regDtcmVsize).WithField("pc", c.cpu.GetPC()).Info("read DTCM size") return uint32(c.regDtcmVsize) case cn == 9 && cm == 1 && cp == 1: // modCp15.WithField("val", c.regItcmVsize).WithField("pc", c.cpu.GetPC()).Info("read ITCM size") return uint32(c.regItcmVsize) default: modCp15.WithField("pc", c.cpu.GetPC()).Warnf("unhandled read C%d,C%d,%d", cn, cm, cp) return 0 } } func (c *Cp15) Write(op uint32, cn, cm, cp uint32, value uint32) { if op != 0 { modCp15.WithField("op", op).Error("invalid op in write") return } switch { case cn == 1 && cm == 0 && cp == 0: c.regControl.SetWithMask(value, c.regControlRwMask) if c.regControl.Bit(17) || c.regControl.Bit(19) { modCp15.Fatal("DTCM/ITCM load mode") } modCp15.WithField("val", c.regControl).WithField("pc", c.cpu.GetPC()).Info("write control reg") if c.regControl.Bit(18) { base := uint32(c.regItcmVsize) & 0xFFFFF000 size := uint32(512 << uint((c.regItcmVsize>>1)&0x1F)) modCp15.WithFields(log.Fields{ "base": reg(base), "size": emu.Hex32(size), }).Info("Activated ITCM") } else { modCp15.Info("Disabled ITCM") } if c.regControl.Bit(16) { base := uint32(c.regDtcmVsize) & 0xFFFFF000 size := uint32(512 << uint((c.regDtcmVsize>>1)&0x1F)) modCp15.WithFields(log.Fields{ "base": reg(base), "size": emu.Hex32(size), }).Info("Activated DTCM") } else { modCp15.Info("Disabled DTCM") } c.updateTcmConfig() case cn == 9 && cm == 1 && cp == 0: c.regDtcmVsize = reg(value) c.updateTcmConfig() modCp15.WithField("val", c.regDtcmVsize).WithField("pc", c.cpu.GetPC()).Info("write DTCM size") case cn == 9 && cm == 1 && cp == 1: c.regItcmVsize = reg(value) c.updateTcmConfig() modCp15.WithField("val", c.regItcmVsize).WithField("pc", c.cpu.GetPC()).Info("write ITCM size") case cn == 6: modCp15.WithFields(log.Fields{ "pc": c.cpu.GetPC(), "region": cm, "enable": value & 1, "base": fmt.Sprintf("%08x", (value>>12)*4096), "size": fmt.Sprintf("%08x", 2<<((value>>1)&0x1F)), }).Info("PU region configuration") case cn == 7: if (cm == 0 && cp == 4) || (cm == 8 && cp == 2) { // Halt processor (wait for interrupt modCp15.WithField("pc", c.cpu.GetPC()).Info("halt cpu") c.cpu.SetLine(LineHalt, true) } // anything else is a cache command, ignore default: modCp15.WithField("pc", c.cpu.GetPC()).Warnf("unhandled write C%d,C%d,%d = %08x", cn, cm, cp, value) return } } func (c *Cp15) Exec(op uint32, cn, cm, cp, cd uint32) { modCp15.WithField("op", op).WithField("pc", c.cpu.GetPC()).Error("invalid op in exec") return } // ConfigureTcm activates emulation of TCM (tightly-coupled memory), which // is a level-1 memory with zero waitstates. ARM supports two different areas // (ITCM and DTCM), with possibly different sizes, and CP15 has specific // registers to map TCM in the virtual address space. func (c *Cp15) ConfigureTcm(itcmSize int, dtcmSize int) { if itcmSize > 0 { c.itcm = make([]byte, itcmSize) } else { c.itcm = nil } if dtcmSize > 0 { c.dtcm = make([]byte, dtcmSize) } else { c.dtcm = nil } // (assuming pow2) c.itcmSizeMask = uint32(itcmSize - 1) c.dtcmSizeMask = uint32(dtcmSize - 1) } // Configure the CP15 Control Register. Value is the initial value of the register, // while rwmask specifies which bits can be modified at runtime, and which bits // are fixed. func (c *Cp15) ConfigureControlReg(value uint32, rwmask uint32) { c.regControl = reg(value) c.regControlRwMask = rwmask } func newCp15(cpu *Cpu) *Cp15 { return &Cp15{ cpu: cpu, regControlRwMask: 0xFFFFFFFF, } } <file_sep>/memcnt.go package main import ( "ndsemu/e2d" "ndsemu/emu" "ndsemu/emu/hwio" log "ndsemu/emu/logger" "ndsemu/raster3d" ) var modMemCnt = log.NewModule("memcnt") type HwMemoryController struct { Nds9 *NDS9 Nds7 *NDS7 // Registers accessible by NDS9 VramCntA hwio.Reg8 `hwio:"bank=0,offset=0x0,rwmask=0x9f,writeonly,wcb"` VramCntB hwio.Reg8 `hwio:"bank=0,offset=0x1,rwmask=0x9f,writeonly,wcb"` VramCntC hwio.Reg8 `hwio:"bank=0,offset=0x2,rwmask=0x9f,writeonly,wcb"` VramCntD hwio.Reg8 `hwio:"bank=0,offset=0x3,rwmask=0x9f,writeonly,wcb"` VramCntE hwio.Reg8 `hwio:"bank=0,offset=0x4,rwmask=0x9f,writeonly,wcb"` VramCntF hwio.Reg8 `hwio:"bank=0,offset=0x5,rwmask=0x9f,writeonly,wcb"` VramCntG hwio.Reg8 `hwio:"bank=0,offset=0x6,rwmask=0x9f,writeonly,wcb"` WramCnt hwio.Reg8 `hwio:"bank=0,offset=0x7,rwmask=0x3,wcb"` VramCntH hwio.Reg8 `hwio:"bank=0,offset=0x8,rwmask=0x9f,writeonly,wcb"` VramCntI hwio.Reg8 `hwio:"bank=0,offset=0x9,rwmask=0x9f,writeonly,wcb"` // Read-only access by NDS7 WramStat hwio.Reg8 `hwio:"bank=1,offset=0x1,readonly,rcb"` ExMemCnt hwio.Reg16 `hwio:"wcb"` ExMemStat hwio.Reg16 `hwio:"rwmask=0x007F,wcb"` wram [32 * 1024]byte // Banks of VRAM that can be mapped to different addresses vram [9][]byte unmapVram [9]func() // Current mapping of BG Extended Palette. We keep the mapping for each // engine (A & B), and each slot (4 of them, 8KB each one). BgExtPalette [2][4][]byte // Current mapping of OBJ Extended Palette. We keep the mapping for each // engine (A & B), with a single palette (8 KB) ObjExtPalette [2][]byte // Current mapping of Texture memory (image and palette) Texture [4][]byte TexturePalette [6][]byte zero [16 * 1024]byte } func NewMemoryController(nds9 *NDS9, nds7 *NDS7, vram []byte) *HwMemoryController { mc := &HwMemoryController{ Nds9: nds9, Nds7: nds7, } hwio.MustInitRegs(mc) mc.vram[0] = vram[0 : 128*1024] vram = vram[128*1024:] mc.vram[1] = vram[0 : 128*1024] vram = vram[128*1024:] mc.vram[2] = vram[0 : 128*1024] vram = vram[128*1024:] mc.vram[3] = vram[0 : 128*1024] vram = vram[128*1024:] mc.vram[4] = vram[0 : 64*1024] vram = vram[64*1024:] mc.vram[5] = vram[0 : 16*1024] vram = vram[16*1024:] mc.vram[6] = vram[0 : 16*1024] vram = vram[16*1024:] mc.vram[7] = vram[0 : 32*1024] vram = vram[32*1024:] mc.vram[8] = vram[0 : 16*1024] vram = vram[16*1024:] if len(vram) != 0 { panic("invalid vram size") } return mc } func (mc *HwMemoryController) WriteWRAMCNT(_, val uint8) { mc.Nds9.Bus.Unmap(0x03000000, 0x03FFFFFF) mc.Nds7.Bus.Unmap(0x03000000, 0x037FFFFF) switch val { case 0: // NDS9 32K - NDS7 its own wram mc.Nds9.Bus.MapMemorySlice(0x03000000, 0x03FFFFFF, mc.wram[:], false) mc.Nds7.Bus.MapMemorySlice(0x03000000, 0x037FFFFF, Emu.Mem.Wram[:], false) case 1: // NDS9 16K (2nd) - NDS7 16K (1st) mc.Nds9.Bus.MapMemorySlice(0x03000000, 0x03FFFFFF, mc.wram[16*1024:], false) mc.Nds7.Bus.MapMemorySlice(0x03000000, 0x037FFFFF, mc.wram[:16*1024], false) case 2: // NDS9 16K (1st) - NDS7 16K (2nd) mc.Nds9.Bus.MapMemorySlice(0x03000000, 0x03FFFFFF, mc.wram[:16*1024], false) mc.Nds7.Bus.MapMemorySlice(0x03000000, 0x037FFFFF, mc.wram[16*1024:], false) case 3: // NDS9 unmapped - NDS7 32K mc.Nds7.Bus.MapMemorySlice(0x03000000, 0x037FFFFF, mc.wram[:], false) default: panic("unreachable") } } func (mc *HwMemoryController) ReadWRAMSTAT(_ uint8) uint8 { return mc.WramCnt.Value } func (mc *HwMemoryController) WriteEXMEMCNT(old, val uint16) { // Writable by NDS9. EXMEMSTAT reflects EXMEMCNT in higher bits mc.ExMemStat.Value |= val & 0xFF80 // Bit 11 changed: gamecard nds9/nds7 mapping if (old^val)&(1<<11) != 0 { if val&(1<<11) != 0 { nds9.Bus.UnmapBank(0x40001A0, Emu.Hw.Gc, 0) nds9.Bus.UnmapBank(0x4100010, Emu.Hw.Gc, 1) nds7.Bus.MapBank(0x40001A0, Emu.Hw.Gc, 0) nds7.Bus.MapBank(0x4100010, Emu.Hw.Gc, 1) Emu.Hw.Gc.Irq = nds7.Irq modMemCnt.Info("mapped gamecard to NDS7") } else { nds7.Bus.UnmapBank(0x40001A0, Emu.Hw.Gc, 0) nds7.Bus.UnmapBank(0x4100010, Emu.Hw.Gc, 1) nds9.Bus.MapBank(0x40001A0, Emu.Hw.Gc, 0) nds9.Bus.MapBank(0x4100010, Emu.Hw.Gc, 1) Emu.Hw.Gc.Irq = nds9.Irq modMemCnt.Info("mapped gamecard to NDS9") } } // Bit 7 changed: GBA slot nds9/nds7 mapping if (old^val)&(1<<7) != 0 { if val&(1<<7) != 0 { // GBA slot mapped to NDS7. Since we don't emulate it yet, when // there is no card in the slot, 0xFF is returned nds7.Bus.Unmap(0x8000000, 0xAFFFFFF) nds7.Bus.MapMemorySlice(0x8000000, 0x9FFFFFF, Emu.Hw.Sl2.Rom[:], true) nds7.Bus.MapMemorySlice(0xA000000, 0xAFFFFFF, Emu.Hw.Sl2.Ram[:], false) // NDS9 sees a zero-filled region nds9.Bus.Unmap(0x8000000, 0xAFFFFFF) nds9.Bus.MapMemorySlice(0x8000000, 0xAFFFFFF, mc.zero[:], true) } else { // GBA slot mapped to NDS9. Same as above, reversing roles nds9.Bus.Unmap(0x8000000, 0xAFFFFFF) nds9.Bus.MapMemorySlice(0x8000000, 0x9FFFFFF, Emu.Hw.Sl2.Rom[:], true) nds9.Bus.MapMemorySlice(0xA000000, 0xAFFFFFF, Emu.Hw.Sl2.Ram[:], false) nds7.Bus.Unmap(0x8000000, 0xAFFFFFF) nds7.Bus.MapMemorySlice(0x8000000, 0xAFFFFFF, mc.zero[:], true) } } } func (mc *HwMemoryController) WriteEXMEMSTAT(_, val uint16) { // Writable by NDS7. Low bits are also carried over to EXMEMCNT, and since // there is a rwmask here (preserving the higher bits), we can just copy it mc.ExMemCnt.Value = mc.ExMemStat.Value } func (mc *HwMemoryController) mapVram7(idx byte, start uint32, end uint32) { modMemCnt.WithFields(log.Fields{ "bank": string(idx), "addr": emu.Hex32(start), "end": emu.Hex32(end), }).Infof("mapping VRAM on NDS7") idx -= 'A' mc.Nds7.Bus.Unmap(start, end) mc.Nds7.Bus.MapMemorySlice(start, end, mc.vram[idx], false) mc.unmapVram[idx] = func() { modMemCnt.WithFields(log.Fields{ "bank": string(idx + 'A'), "start": emu.Hex32(start), "end": emu.Hex32(end), }).Info("unmap") mc.Nds7.Bus.Unmap(start, end) mc.Nds7.Bus.MapMemorySlice(start, end, mc.zero[:], true) } } func (mc *HwMemoryController) mapVram9(idx byte, start uint32, end uint32) { modMemCnt.WithFields(log.Fields{ "bank": string(idx), "addr": emu.Hex32(start), "end": emu.Hex32(end), }).Infof("mapping VRAM on NDS9") idx -= 'A' mc.Nds9.Bus.Unmap(start, end) mc.Nds9.Bus.MapMemorySlice(start, end, mc.vram[idx], false) mc.unmapVram[idx] = func() { modMemCnt.WithFields(log.Fields{ "bank": string(idx + 'A'), "start": emu.Hex32(start), "end": emu.Hex32(end), }).Info("unmap") mc.Nds9.Bus.Unmap(start, end) mc.Nds9.Bus.MapMemorySlice(start, end, mc.zero[:], true) } } func (mc *HwMemoryController) mapBgExtPalette(idx byte, engIdx int, firstslot int) { modMemCnt.WithFields(log.Fields{ "bank": string(idx), "slot": "bg-ext-palette", }).Infof("mapping VRAM on NDS9") idx -= 'A' var i int ptr := mc.vram[idx] for i := firstslot; i < 4 && len(ptr) > 0; i++ { mc.BgExtPalette[engIdx][i] = ptr[:8*1024] ptr = ptr[8*1024:] } lastslot := i mc.unmapVram[idx] = func() { for i := firstslot; i < lastslot; i++ { mc.BgExtPalette[engIdx][i] = nil } } } func (mc *HwMemoryController) mapObjExtPalette(idx byte, engIdx int) { modMemCnt.WithFields(log.Fields{ "bank": string(idx), "slot": "obj-ext-palette", }).Infof("mapping VRAM on NDS9") idx -= 'A' mc.ObjExtPalette[engIdx] = mc.vram[idx][:8*1024] mc.unmapVram[idx] = func() { mc.ObjExtPalette[engIdx] = nil } } func (mc *HwMemoryController) mapTexture(idx byte, slotnum int) { modMemCnt.WithFields(log.Fields{ "bank": string(idx), "slot": "texture", }).Infof("mapping VRAM on NDS9") idx -= 'A' mc.Texture[slotnum] = mc.vram[idx][:128*1024] mc.unmapVram[idx] = func() { mc.Texture[slotnum] = nil } } func (mc *HwMemoryController) mapTexturePalette(idx byte, slotnum int, offset int) { modMemCnt.WithFields(log.Fields{ "bank": string(idx), "slot": "texture-palette", }).Infof("mapping VRAM on NDS9") idx -= 'A' mc.TexturePalette[slotnum] = mc.vram[idx][offset : offset+16*1024] } func (mc *HwMemoryController) writeVramCnt(idx byte, val uint8) (int, int) { idx -= 'A' // FIXME: the VRAM unmapping logic is broken. The hwio.Table.Unmap() function // unmaps whatever happens to be present in that range, possibly a new mapping // of a different bank. Consider this: // // Bank A mapped to 6200000 // Bank B mapped to 6200000 (A is implicitly disabled) // Bank A mapped to 6400000 // // On the last line, if we run a blanket Unmap() of whatever is at 6200000, we // would unmap the B bank. hwio.Table currently doesn't expose an API like // "unmap this specific memory slice at this address, if present", so we // currently punt on unmapping. // // if mc.unmapVram[idx] != nil { // mc.unmapVram[idx]() // mc.unmapVram[idx] = nil // } if val&0x80 == 0 { return -1, -1 } return int(val & 7), int((val >> 3) & 3) } func (mc *HwMemoryController) WriteVRAMCNTA(_, val uint8) { mst, ofs := mc.writeVramCnt('A', val) switch mst { case -1: return case 0: mc.mapVram9('A', 0x6800000, 0x681FFFF) case 1: base := 0x6000000 + uint32(ofs)*0x20000 mc.mapVram9('A', base, base+0x1FFFF) case 2: base := 0x6400000 + uint32(ofs)*0x20000 mc.mapVram9('A', base, base+0x1FFFF) case 3: mc.mapTexture('A', ofs) default: modMemCnt.WithFields(log.Fields{ "bank": "A", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } func (mc *HwMemoryController) WriteVRAMCNTB(_, val uint8) { mst, ofs := mc.writeVramCnt('B', val) switch mst { case -1: return case 0: mc.mapVram9('B', 0x6820000, 0x683FFFF) case 1: base := 0x6000000 + uint32(ofs)*0x20000 mc.mapVram9('B', base, base+0x1FFFF) case 2: base := 0x6400000 + uint32(ofs)*0x20000 mc.mapVram9('B', base, base+0x1FFFF) case 3: mc.mapTexture('B', ofs) default: modMemCnt.WithFields(log.Fields{ "bank": "B", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } func (mc *HwMemoryController) WriteVRAMCNTC(_, val uint8) { mst, ofs := mc.writeVramCnt('C', val) switch mst { case -1: return case 0: mc.mapVram9('C', 0x6840000, 0x685FFFF) case 1: base := 0x6000000 + uint32(ofs)*0x20000 mc.mapVram9('C', base, base+0x1FFFF) case 3: mc.mapTexture('C', ofs) case 4: mc.mapVram9('C', 0x6200000, 0x621FFFF) default: modMemCnt.WithFields(log.Fields{ "bank": "C", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } func (mc *HwMemoryController) WriteVRAMCNTD(_, val uint8) { mst, ofs := mc.writeVramCnt('D', val) switch mst { case -1: return case 0: mc.mapVram9('D', 0x6860000, 0x687FFFF) case 1: base := 0x6000000 + uint32(ofs)*0x20000 mc.mapVram9('D', base, base+0x1FFFF) case 2: base := 0x6000000 + uint32(ofs)*0x20000 mc.mapVram7('D', base, base+0x1FFFF) case 3: mc.mapTexture('D', ofs) case 4: mc.mapVram9('D', 0x6600000, 0x661FFFF) default: modMemCnt.WithFields(log.Fields{ "bank": "D", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } func (mc *HwMemoryController) WriteVRAMCNTE(_, val uint8) { mst, ofs := mc.writeVramCnt('E', val) switch mst { case -1: return case 0: mc.mapVram9('E', 0x6880000, 0x688FFFF) case 1: mc.mapVram9('E', 0x6000000, 0x600FFFF) case 2: mc.mapVram9('E', 0x6400000, 0x640FFFF) case 3: mc.mapTexturePalette('E', 0, 0*1024) mc.mapTexturePalette('E', 1, 16*1024) mc.mapTexturePalette('E', 2, 32*1024) mc.mapTexturePalette('E', 3, 48*1024) case 4: mc.mapBgExtPalette('E', 0, 0) default: modMemCnt.WithFields(log.Fields{ "bank": "E", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } func (mc *HwMemoryController) WriteVRAMCNTF(_, val uint8) { mst, ofs := mc.writeVramCnt('F', val) switch mst { case -1: return case 0: mc.mapVram9('F', 0x6890000, 0x6893FFF) case 1: off := uint32(0x4000*(ofs&1) + 0x8000*(ofs&2)) mc.mapVram9('F', 0x6000000+off, 0x6003FFF+off) case 2: off := uint32((ofs&1)*0x4000 + (ofs&2)*0x8000) mc.mapVram9('F', 0x6400000+off, 0x6403FFF+off) case 3: slot := int((ofs&1)*1 + (ofs&2)*2) mc.mapTexturePalette('F', slot, 0) case 4: mc.mapBgExtPalette('F', 0, ofs*2) case 5: mc.mapObjExtPalette('F', 0) default: modMemCnt.WithFields(log.Fields{ "bank": "F", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } func (mc *HwMemoryController) WriteVRAMCNTG(_, val uint8) { mst, ofs := mc.writeVramCnt('G', val) switch mst { case -1: return case 0: mc.mapVram9('G', 0x6894000, 0x6897FFF) case 1: off := uint32(0x4000*(ofs&1) + 0x8000*(ofs&2)) mc.mapVram9('G', 0x6000000+off, 0x6003FFF+off) case 2: off := uint32(0x4000*(ofs&1) + 0x8000*(ofs&2)) mc.mapVram9('G', 0x6400000+off, 0x6403FFF+off) case 3: slot := int((ofs&1)*1 + (ofs&2)*2) mc.mapTexturePalette('G', slot, 0) case 4: mc.mapBgExtPalette('G', 0, ofs*2) case 5: mc.mapObjExtPalette('G', 0) default: modMemCnt.WithFields(log.Fields{ "bank": "G", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } func (mc *HwMemoryController) WriteVRAMCNTH(_, val uint8) { mst, ofs := mc.writeVramCnt('H', val) switch mst { case -1: return case 0: mc.mapVram9('H', 0x6898000, 0x689FFFF) case 1: mc.mapVram9('H', 0x6200000, 0x6207FFF) case 2: mc.mapBgExtPalette('H', 1, 0) default: modMemCnt.WithFields(log.Fields{ "bank": "H", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } func (mc *HwMemoryController) WriteVRAMCNTI(_, val uint8) { mst, ofs := mc.writeVramCnt('I', val) switch mst { case -1: return case 0: mc.mapVram9('I', 0x68A0000, 0x68A3FFF) case 1: mc.mapVram9('I', 0x6208000, 0x620BFFF) case 2: mc.mapVram9('I', 0x6600000, 0x6603FFF) case 3: mc.mapObjExtPalette('I', 1) default: modMemCnt.WithFields(log.Fields{ "bank": "I", "mst": mst, "ofs": ofs, }).Fatal("invalid vram configuration") } } /******************************************** * Engine2D VRAM ********************************************/ var empty [e2d.VramSmallestBankSize]byte // Return the VRAM linear bank that will be accessed by the specified engine. // The linear bank is 256k big, and can be accessed as 8-bit or 16-bit. // byteOffset is the offset within the VRAM from which the 256k bank starts. // // If the requested bank is unmapped, a zero-filled area is returned. If the // requested bank is mapped for less than 256K, the missing areas will be // zero-filled as well. func (mc *HwMemoryController) VramLinearBank(engine int, which e2d.VramLinearBankId, baseOffset int) (vb e2d.VramLinearBank) { for i := 0; i < 32; i++ { var ptr []byte switch which { case e2d.VramLinearBGExtPal: if i < len(mc.BgExtPalette[engine]) { ptr = mc.BgExtPalette[engine][i] } case e2d.VramLinearOBJExtPal: if i == 0 { ptr = mc.ObjExtPalette[engine] } case e2d.VramLinearBG: ptr = mc.Nds9.Bus.FetchPointer(uint32(0x6000000 + 0x200000*engine + baseOffset + i*e2d.VramSmallestBankSize)) case e2d.VramLinearOAM: ptr = mc.Nds9.Bus.FetchPointer(uint32(0x6400000 + 0x200000*engine + baseOffset + i*e2d.VramSmallestBankSize)) default: panic("unreachable") } vb.Ptr[i] = ptr if vb.Ptr[i] == nil { vb.Ptr[i] = empty[:] } } return } func (mc *HwMemoryController) VramPalette(engine int) []byte { return Emu.Mem.PaletteRam[engine*1024 : engine*1024+1024] } func (mc *HwMemoryController) VramOAM(engine int) []byte { return Emu.Mem.OamRam[0x400*engine : 0x400+0x400*engine] } func (mc *HwMemoryController) VramRawBank(bank int) []byte { return mc.vram[bank] } /******************************************** * Raster3D VRAM ********************************************/ func (mc *HwMemoryController) VramTextureBank() raster3d.VramTextureBank { return raster3d.VramTextureBank{Slots: mc.Texture} } func (mc *HwMemoryController) VramTexturePaletteBank() raster3d.VramTexturePaletteBank { return raster3d.VramTexturePaletteBank{Slots: mc.TexturePalette} } <file_sep>/raster3d/color.go package raster3d import "ndsemu/emu" // RGB color (6 bit precisions, spaced 8-bits each one). // This matches the internal precision used by the NDS hardware // when handling colors in rasterizer type color int32 type colorDelta int32 func newColorFrom666(r, g, b uint8) color { return color(r) | color(g)<<8 | color(b)<<16 } func newColorFrom555(r, g, b uint8) color { r = (r * 2) + (r+31)/32 g = (g * 2) + (g+31)/32 b = (b * 2) + (b+31)/32 return color(r) | color(g)<<8 | color(b)<<16 } func newColorFrom555U(rgb uint16) color { return newColorFrom555(uint8(rgb&0x1F), uint8(rgb>>5)&0x1F, uint8(rgb>>10)&0x1F) } func (c color) To555U() uint16 { r, g, b := c.R()>>1, c.G()>>1, c.B()>>1 return uint16(r) | uint16(g)<<5 | uint16(b)<<10 } func (c color) R() uint8 { return uint8(c >> 0) } func (c color) G() uint8 { return uint8(c >> 8) } func (c color) B() uint8 { return uint8(c >> 16) } // Compute a subtraction component-wise. // The result of this computation is not a real color, but can be used to computer // an interpolater between two colors. func (c1 color) SubColor(c2 color) colorDelta { r1, g1, b1 := int32(c1.R()), int32(c1.G()), int32(c1.B()) r2, g2, b2 := int32(c2.R()), int32(c2.G()), int32(c2.B()) rdiff := r1 - r2 gdiff := g1 - g2 bdiff := b1 - b2 return colorDelta(rdiff + (gdiff << 8) + (bdiff << 16)) } func (c1 color) AddDelta(d colorDelta) color { return c1 + color(d) } func (c colorDelta) Div(n int32) colorDelta { r := int32(int8(c & 0xFF)) c -= colorDelta(r) g := int32(int8(c >> 8)) c -= colorDelta(g << 8) b := int32(int8(c >> 16)) r /= n g /= n b /= n return colorDelta(r) + colorDelta(g<<8) + colorDelta(b<<16) } func (c1 color) Modulate(c2 color) color { r1, g1, b1 := int32(c1.R()), int32(c1.G()), int32(c1.B()) r2, g2, b2 := int32(c2.R()), int32(c2.G()), int32(c2.B()) r := ((r1+1)*(r2+1) - 1) >> 6 g := ((g1+1)*(g2+1) - 1) >> 6 b := ((b1+1)*(b2+1) - 1) >> 6 return newColorFrom666(uint8(r), uint8(g), uint8(b)) } func (c1 color) Decal(c2 color, alpha uint8) color { r1, g1, b1 := int32(c1.R()), int32(c1.G()), int32(c1.B()) r2, g2, b2 := int32(c2.R()), int32(c2.G()), int32(c2.B()) r := (r1*int32(alpha) + r2*(63-int32(alpha))) >> 6 g := (g1*int32(alpha) + g2*(63-int32(alpha))) >> 6 b := (b1*int32(alpha) + b2*(63-int32(alpha))) >> 6 return newColorFrom666(uint8(r), uint8(g), uint8(b)) } func (c1 color) AddSat(c2 color) color { r1, g1, b1 := int32(c1.R()), int32(c1.G()), int32(c1.B()) r2, g2, b2 := int32(c2.R()), int32(c2.G()), int32(c2.B()) r := r1 + r2 g := g1 + g2 b := b1 + b2 if r > 63 { r = 63 } if g > 63 { g = 63 } if b > 63 { b = 63 } return newColorFrom666(uint8(r), uint8(g), uint8(b)) } func (c1 color) Lerp(c2 color, ratio emu.Fixed12) color { r1, g1, b1 := int32(c1.R()), int32(c1.G()), int32(c1.B()) r2, g2, b2 := int32(c2.R()), int32(c2.G()), int32(c2.B()) r := r1 + emu.NewFixed12(r2-r1).MulFixed(ratio).NearInt32() g := g1 + emu.NewFixed12(g2-g1).MulFixed(ratio).NearInt32() b := b1 + emu.NewFixed12(b2-b1).MulFixed(ratio).NearInt32() return newColorFrom666(uint8(r), uint8(g), uint8(b)) } func rgbMix(c1 uint16, f1 int, c2 uint16, f2 int) uint16 { r1, g1, b1 := (c1 & 0x1F), ((c1 >> 5) & 0x1F), ((c1 >> 10) & 0x1F) r2, g2, b2 := (c2 & 0x1F), ((c2 >> 5) & 0x1F), ((c2 >> 10) & 0x1F) r := (int(r1)*f1 + int(r2)*f2) / (f1 + f2) g := (int(g1)*f1 + int(g2)*f2) / (f1 + f2) b := (int(b1)*f1 + int(b2)*f2) / (f1 + f2) return uint16(r) | uint16(g<<5) | uint16(b<<10) } func rgbAlphaMix(c1 uint16, c2 uint16, alpha uint8) uint16 { r1, g1, b1 := (c1 & 0x1F), ((c1 >> 5) & 0x1F), ((c1 >> 10) & 0x1F) r2, g2, b2 := (c2 & 0x1F), ((c2 >> 5) & 0x1F), ((c2 >> 10) & 0x1F) a1 := uint(alpha + 1) a2 := uint(31 - alpha) r := (uint(r1)*a1 + uint(r2)*a2) >> 5 g := (uint(g1)*a1 + uint(g2)*a2) >> 5 b := (uint(b1)*a1 + uint(b2)*a2) >> 5 return uint16(r) | uint16(g)<<5 | uint16(b)<<10 } <file_sep>/dma.go package main import ( "ndsemu/emu" "ndsemu/emu/hwio" log "ndsemu/emu/logger" ) type DmaEvent int const ( DmaEventInvalid DmaEvent = iota // invalid event (out-of-band value) DmaEventImmediate // immediate event (for immediate channels) DmaEventGamecard DmaEventHBlank DmaEventGxFifo ) type HwDmaFill struct { Dma0Fill hwio.Reg32 `hwio:"offset=0x00"` Dma1Fill hwio.Reg32 `hwio:"offset=0x04"` Dma2Fill hwio.Reg32 `hwio:"offset=0x08"` Dma3Fill hwio.Reg32 `hwio:"offset=0x0C"` } func NewHwDmaFill() *HwDmaFill { dma := new(HwDmaFill) hwio.MustInitRegs(dma) return dma } type HwDmaChannel struct { Cpu CpuNum Channel int Bus emu.Bus Irq *HwIrq DmaSad hwio.Reg32 `hwio:"offset=0x00"` DmaDad hwio.Reg32 `hwio:"offset=0x04"` DmaCount hwio.Reg16 `hwio:"offset=0x08"` DmaCntrl hwio.Reg16 `hwio:"offset=0x0A,wcb"` debugRepeat bool inProgress bool pendingEvent DmaEvent } func NewHwDmaChannel(cpu CpuNum, ch int, bus emu.Bus, irq *HwIrq) *HwDmaChannel { dma := &HwDmaChannel{ Cpu: cpu, Channel: ch, Bus: bus, Irq: irq, } hwio.MustInitRegs(dma) return dma } func (dma *HwDmaChannel) disable() { dma.DmaCntrl.Value &^= (1 << 15) } func (dma *HwDmaChannel) enabled() bool { return (dma.DmaCntrl.Value>>15)&1 != 0 } // Return the event that will trigger the start of this DMA channel. If the // channel is disabled, DmaEventInvalid is returned. func (dma *HwDmaChannel) startEvent() DmaEvent { if !dma.enabled() { return DmaEventInvalid } if dma.Cpu == CpuNds9 { start := (dma.DmaCntrl.Value >> 11) & 7 switch start { case 0: return DmaEventImmediate case 2: return DmaEventHBlank case 5: return DmaEventGamecard case 7: return DmaEventGxFifo default: log.ModDma.Fatalf("DMA start=%d not implemented", start) return DmaEventInvalid } } else { start := (dma.DmaCntrl.Value >> 12) & 3 switch start { case 0: return DmaEventImmediate case 2: return DmaEventGamecard default: log.ModDma.Fatalf("DMA start=%d not implemented", start) return DmaEventInvalid } } } func (dma *HwDmaChannel) WriteDMACNTRL(old, val uint16) { dma.debugRepeat = false // Check if this write activated a DMA channel. If it did, // we might to do something right away, depending on the start // event type. if ((old^val)>>15)&1 != 0 { evt := dma.startEvent() switch evt { case DmaEventImmediate: // DMA in immediate mode must be triggered immediately dma.TriggerEvent(DmaEventImmediate) case DmaEventGxFifo: // Sync up the geometry engine up to the current point // before making it see that the DMA is active; this // way, we get cycle-accurate emulation. Whenever the // geometry engine is then scheduled, it will trigger this // DMA (assuming the FIFO is empty enough). dma.DmaCntrl.Value = old Emu.Hw.Geom.Run(Emu.Sync.Cycles()) dma.DmaCntrl.Value = val } } } func (dma *HwDmaChannel) xfer() { ctrl := dma.DmaCntrl.Value sad := dma.DmaSad.Value dad := dma.DmaDad.Value irq := (ctrl>>14)&1 != 0 start := (ctrl >> 11) & 7 w32 := (ctrl>>10)&1 != 0 repeat := (ctrl>>9)&1 != 0 sinc := (ctrl >> 7) & 3 dinc := (ctrl >> 5) & 3 if sinc == 3 { log.ModDma.Fatal("sinc=3 should not happen") } cnt := uint32(dma.DmaCount.Value) if dma.Cpu == CpuNds9 { cnt |= (uint32(dma.DmaCntrl.Value) & 0x1F) << 16 if cnt == 0 { cnt = 0x200000 } } else { if cnt == 0 { if dma.Channel == 3 { cnt = 0x10000 } else { cnt = 0x4000 } } } wordsize := uint32(2) if w32 { wordsize = 4 } if !repeat || !dma.debugRepeat { if repeat { dma.debugRepeat = true } log.ModDma.WithFields(log.Fields{ "sad": emu.Hex32(sad), "dad": emu.Hex32(dad), "cnt": emu.Hex32(cnt), "sinc": sinc, "dinc": dinc, "irq": irq, "wsize": wordsize, }).Infof("transfer") } if dad == 0 { // nds9.Cpu.Exception(arm.ExceptionDataAbort) // Emu.DebugBreak("DMA to zero") dma.disable() return } if dma.Cpu == CpuNds9 && start == 7 { // GFXFIFO dma is different from others because it is technically // a single-transfer, while actually data is flushed in batches // of 112 words. So we need to trick this function into repeat mode // and avoid triggering irq, unless the transfer is really finished. if cnt > 112 { irq = false repeat = true dma.DmaCount.Value = uint16(cnt - 112) cnt = 112 } } dma.inProgress = true for ; cnt != 0; cnt-- { if w32 { dma.Bus.Write32(dad, dma.Bus.Read32(sad)) } else { dma.Bus.Write16(dad, dma.Bus.Read16(sad)) } if sinc == 0 || sinc == 3 { sad += wordsize } else if sinc == 1 { sad -= wordsize } if dinc == 0 || dinc == 3 { dad += wordsize } else if dinc == 1 { dad -= wordsize } } dma.inProgress = false if irq { dma.Irq.Raise(IrqDma0 << uint(dma.Channel)) } if !repeat { dma.disable() } else { // Update registers for next repeat. Notice that these should be // internal copies of registers, but the external visible registers // are writeonly anyway, so we can reuse those for our own goals. dma.DmaSad.Value = sad // dest-increment 3 is "reload each repetition" if dinc != 3 { dma.DmaDad.Value = dad } } } func (dma *HwDmaChannel) TriggerEvent(event DmaEvent) { if event == DmaEventInvalid { log.ModDma.Fatalf("invalid DMA event triggered (?)") } if dma.inProgress { // Event GxFifo is scheduled by the Geometry engine any time the // FIFO is less than half full. Since the engine can also run in // the middle of a DMA trasnfer, it might happen that there // are multiple calls pending (ex: super mario 64). Ignore it. if event == DmaEventGxFifo && dma.pendingEvent == DmaEventGxFifo { return } if dma.pendingEvent != DmaEventInvalid { log.ModDma.Fatalf("too many pending DMA events") } dma.pendingEvent = event } else { for event != DmaEventInvalid { if dma.startEvent() == event { dma.xfer() } // A new event might have been triggered while the DMA was in // progress (for instance, reading from gamecard triggers new // data to be ready and thus a new event to be scheduled). We // check here with a loop (instead of using recursion that would // grow the stack a lot, since tail recursion is not implemented // in the Go compiler) event = dma.pendingEvent dma.pendingEvent = DmaEventInvalid } } } <file_sep>/gamecard.go package main import ( "encoding/binary" "fmt" "io" "ndsemu/emu" "ndsemu/emu/hwio" log "ndsemu/emu/logger" "ndsemu/emu/spi" "os" ) var modGamecard = log.NewModule("gamecard") type gcStatus int const ( gcStatusRaw gcStatus = iota gcStatusKey1A gcStatusKey1B gcStatusKey2 ) type Gamecard struct { io.ReaderAt Irq *HwIrq closecb func() Size uint64 AuxSpiCnt hwio.Reg16 `hwio:"bank=0,offset=0x0,rwmask=0xF07F,wcb"` AuxSpiData hwio.Reg16 `hwio:"bank=0,offset=0x2,wcb"` RomCtrl hwio.Reg32 `hwio:"bank=0,offset=0x4,rwmask=0xFF7FFFFF,wcb"` GcCommand hwio.Reg64 `hwio:"bank=0,offset=0x8,wcb"` KeySeed0L hwio.Reg32 `hwio:"bank=0,offset=0x10,writeonly"` KeySeed1L hwio.Reg32 `hwio:"bank=0,offset=0x14,writeonly"` KeySeed0H hwio.Reg16 `hwio:"bank=0,offset=0x18,rwmask=0x7f,writeonly"` KeySeed1H hwio.Reg16 `hwio:"bank=0,offset=0x1A,rwmask=0x7f,writeonly"` CardData hwio.Reg32 `hwio:"bank=1,offset=0x0,readonly,rcb"` chipid [4]byte stat gcStatus buf []byte key1Tables [(18 + 1024) * 4]byte key2 Key2 secAreaOff int spi spi.Bus bkp *HwBackupRam } func NewGamecard(biosfn string, bkp *HwBackupRam) *Gamecard { gc := &Gamecard{ key2: NewKey2(), } hwio.MustInitRegs(gc) // Configure spi bus gc.spi.SpiBusName = "SpiAux" gc.spi.AddDevice(0, bkp) gc.bkp = bkp f, err := os.Open(biosfn) if err != nil { panic(err) } f.ReadAt(gc.key1Tables[:], 0x30) f.Close() return gc } func (gc *Gamecard) MapCart(data io.ReaderAt) { if gc.closecb != nil { gc.closecb() gc.closecb = nil } gc.ReaderAt = data } func (gc *Gamecard) MapCartFile(fn string) error { f, err := os.Open(fn) if err != nil { return err } size, err := f.Seek(0, 2) if err != nil { return err } f.Seek(0, 0) gc.Size = uint64(size) gc.MapCart(f) gc.closecb = func() { f.Close() } // Inititalize chip id gc.chipid[0] = 0xC2 // manufacturer (?) gc.chipid[1] = 0x7F // ROM size (Mbytes - 1) gc.chipid[2] = 0x00 // flags gc.chipid[3] = 0x80 // flags return nil } func (gc *Gamecard) WriteAUXSPICNT(old, value uint16) { modGamecard.Infof("Write AUXSPICNT %04x", value) if (old^value)&(1<<13) != 0 { if value&(1<<13) != 0 { modGamecard.Infof("change AUXSPI: SPI-backup") gc.spi.BeginTransfer(0) } else { modGamecard.Infof("change AUXSPI: ROM") } } gc.bkp.AuxSpiCntWritten(value) } func (gc *Gamecard) WriteAUXSPIDATA(_, value uint16) { modGamecard.Infof("Write AUXSPIDATA %04x", value) if gc.AuxSpiCnt.Value&(1<<13) == 0 { modGamecard.Warn("AUXSPIDATA written, but SPI not selected") return } if gc.AuxSpiCnt.Value&3 != 0 { modGamecard.Warn("AUXSPIDATA written, but wrong SPI frequency") return } // Do the SPI transfer. Send one byte, get one byte. read := gc.spi.Transfer(uint8(value)) gc.AuxSpiData.Value = uint16(read) // If chispselect is off, this is the last trasnfer byte, // so reset the write buffer to discard current command and restart // new one if gc.AuxSpiCnt.Value&(1<<6) == 0 { gc.spi.EndTransfer() } } func (gc *Gamecard) WriteROMCTRL(_, value uint32) { modGamecard.WithDelayedFields(func() log.Fields { return log.Fields{ "val": fmt.Sprintf("%08x", value), "lr": nds7.Cpu.Regs[14], "cmd": emu.Hex64(emu.Swap64(gc.GcCommand.Value)), "irq": gc.AuxSpiCnt.Value&(1<<14) != 0, } }).Info("Write ROMCTL") if gc.RomCtrl.Value&(1<<15) != 0 { s0 := uint64(gc.KeySeed0L.Value) | uint64(gc.KeySeed0H.Value)<<32 s1 := uint64(gc.KeySeed1L.Value) | uint64(gc.KeySeed1H.Value)<<32 gc.key2 = NewKey2WithSeed(s0, s1) modGamecard.WithFields(log.Fields{ "s0": emu.Hex64(s0), "s1": emu.Hex64(s1), }).Infof("Apply KEY2 encryption seeds") if true { var gamecode [4]byte gc.ReadAt(gamecode[:], 0x0C) var enccmd, cmd [8]byte binary.LittleEndian.PutUint64(enccmd[:], gc.GcCommand.Value) key1 := NewKey1(gc.key1Tables[:], gamecode[:], false) key1.DecryptBE(cmd[:], enccmd[:]) modGamecard.WithFields(log.Fields{ "enc": fmt.Sprintf("%x", enccmd), "dec": fmt.Sprintf("%x", cmd), }).Infof("key1 cmd decription TEST TEST") } } if gc.RomCtrl.Value&(1<<13) != 0 { modGamecard.Infof("Turn on KEY2 encryption for Data") } if gc.RomCtrl.Value&(1<<22) != 0 { modGamecard.Infof("Turn on KEY2 encryption for Cmd") } if gc.RomCtrl.Value&(1<<31) != 0 { size := (gc.RomCtrl.Value >> 24) & 7 if size == 7 { size = 4 } else if size > 0 { size = 0x100 << size } modGamecard.Infof("ROM block transfer: size: %d, command: %x", size, (gc.GcCommand.Value & 0xFF)) var buf []byte switch gc.stat { case gcStatusRaw: buf = gc.cmdRaw(size) case gcStatusKey1A: // we do nothing here and wait for the command to be reissued gc.stat = gcStatusKey1B case gcStatusKey1B: gc.stat = gcStatusKey1A buf = gc.cmdKey1(size) case gcStatusKey2: buf = gc.cmdKey2(size) default: modGamecard.Fatalf("status not implemented: %d", gc.stat) } gc.buf = buf gc.updateStatus() } } func (gc *Gamecard) cmdRaw(size uint32) []byte { buf := make([]byte, size) var cmd [8]byte binary.LittleEndian.PutUint64(cmd[:], gc.GcCommand.Value) switch cmd[0] { case 0x9F: // Dummy command: read 0xFF for i := range buf { buf[i] = 0xFF } case 0x00: // Read header gc.ReadAt(buf, 0) case 0x90: // Get ROM chip ID copy(buf[:], gc.chipid[:]) case 0x3C: // Activate KEY1 gc.stat = gcStatusKey1A for i := range buf { buf[i] = 0xFF } default: modGamecard.Fatalf("unknown raw command: %x", cmd[0]) } return buf } func (gc *Gamecard) cmdKey1(size uint32) []byte { var gamecode [4]byte gc.ReadAt(gamecode[:], 0x0C) var enccmd, cmd [8]byte binary.LittleEndian.PutUint64(enccmd[:], gc.GcCommand.Value) key1 := NewKey1(gc.key1Tables[:], gamecode[:], false) key1.DecryptBE(cmd[:], enccmd[:]) modGamecard.WithFields(log.Fields{ "enc": fmt.Sprintf("%x", enccmd), "dec": fmt.Sprintf("%x", cmd), }).Infof("key1 cmd decription") switch cmd[0] >> 4 { case 0x4: modGamecard.Infof("cmd: turn on KEY2") buf := make([]byte, 0x910) for i := 0; i < 0x910; i++ { buf[i] = 0xFF } return nil case 0x1: modGamecard.Infof("cmd: read ROM ID 2") buf := make([]byte, 4) copy(buf, gc.chipid[:]) return buf case 0x2: off := int(cmd[0]&0xF)<<12 | int(cmd[1])<<4 | int(cmd[2])>>4 off *= 0x1000 // This command is issued 8 times with the same offset, to load 8 // different secure area blocks. if gc.secAreaOff == 0 { gc.secAreaOff = off } else if !(gc.secAreaOff >= off && gc.secAreaOff < off+0x1000) { modGamecard.Errorf("invalid secure area loading: we didn't get 8 repetitions") emu.DebugBreak("invalid secure area loading") } buf := make([]byte, 512) gc.ReadAt(buf, int64(gc.secAreaOff)) modGamecard.Infof("cmd: get secure area block (offset: %x)", gc.secAreaOff) // Set encryption area ID, that is not present in unencrypted ROMs if gc.secAreaOff == 0x4000 { copy(buf[0:8], []byte("encryObj")) } // Apply encryption of secure area if gc.secAreaOff < 0x4800 { keyl3 := NewKey1(gc.key1Tables[:], gamecode[:], true) for i := 0; i < len(buf); i += 8 { keyl3.EncryptLE(buf[i:i+8], buf[i:i+8]) } } // Secure area ID (first 8 bytes) has two layers of encryption if gc.secAreaOff == 0x4000 { key1.EncryptLE(buf[0:8], buf[0:8]) } gc.secAreaOff += 0x200 if gc.secAreaOff == off+0x1000 { // This was the last repetition, switch back to normal key1 mode gc.stat = gcStatusKey1A gc.secAreaOff = 0 } else { // we still need to wait for reptitions, stay in key1b mode gc.stat = gcStatusKey1B } return buf case 0xA: modGamecard.Infof("cmd: switch to KEY2 status") gc.stat = gcStatusKey2 buf := make([]byte, 0x910) for i := 0; i < 0x910; i++ { buf[i] = 0xFF } return nil default: modGamecard.Fatalf("unknown key1 decrypted command: %x", cmd[0]) return nil } } func (gc *Gamecard) cmdKey2(size uint32) []byte { var cmd [8]byte binary.LittleEndian.PutUint64(cmd[:], gc.GcCommand.Value) buf := make([]byte, size) switch cmd[0] { case 0xB7: // Encrypted load off := int64(binary.BigEndian.Uint32(cmd[1:5])) & int64(gc.Size-1) gc.ReadAt(buf, off) // Apply key2 encryption // gc.key2.Encrypt(buf, buf) modGamecard.Infof("encrypted load from offset %x (enc:%x)", off, cmd) return buf case 0xB8: copy(buf, gc.chipid[:]) // Apply key2 encryption // gc.key2.Encrypt(buf, buf) return buf default: modGamecard.Fatalf("unknown key2 command: %x", cmd) return nil } } func (gc *Gamecard) updateStatus() { if len(gc.buf) == 0 { modGamecard.Info("end of transfer") gc.RomCtrl.Value &^= (1 << 31) gc.RomCtrl.Value &^= (1 << 23) if gc.AuxSpiCnt.Value&(1<<14) != 0 { gc.Irq.Raise(IrqGameCardData) } } else { // Signal data ready gc.RomCtrl.Value |= (1 << 23) nds9.TriggerDmaEvent(DmaEventGamecard) nds7.TriggerDmaEvent(DmaEventGamecard) } } func (gc *Gamecard) WriteGCCOMMAND(_, val uint64) { // emu.DebugBreak("write gccommand") // Emu.Log().Infof("Write COMMAND: %08x", val) } func (gc *Gamecard) ReadCARDDATA(_ uint32) uint32 { if len(gc.buf) == 0 { modGamecard.Warn("read DATA but not pending data") return 0 } data := binary.LittleEndian.Uint32(gc.buf[0:4]) gc.buf = gc.buf[4:] // log.Infof("read DATA: %08x", data) gc.updateStatus() return data } <file_sep>/e2d/const.go package e2d import ( log "ndsemu/emu/logger" ) const ( cScreenWidth = 256 cScreenHeight = 192 ) var modLcd = log.ModGfx var gKeyState []byte <file_sep>/emu/logger/modules.go package logger import ( "gopkg.in/Sirupsen/logrus.v0" ) type ModuleMask uint64 type Module uint const ( ModuleMaskAll ModuleMask = 0xFFFFFFFFFFFFFFFF ) // Predefine a few "common" module constants. The idea is to have a few // "standard" modules that can be used for easy logging, but it's always // possible for an emulator to define additional modules through NewModule() const ( ModEmu Module = iota + 1 ModCpu ModIrq ModMem ModSync ModHw ModHwIo ModGfx ModSerial ModCrypt ModDma ModTimer Mod3d ModInput ModSound endStandardMods ) var modCount = endStandardMods var modDebugMask ModuleMask = 0 var modNames = []string{ "<error>", "emu", "cpu", "irq", "mem", "sync", "hw", "hwio", "gfx", "serial", "crypt", "dma", "timer", "3d", "input", "sound", } func NewModule(name string) Module { mod := modCount modCount++ modNames = append(modNames, name) return mod } func ModuleByName(name string) (Module, bool) { for idx, s := range modNames { if s == name { return Module(idx), true } } return Module(0xFFFFFFFF), false } func EnableDebugModules(mask ModuleMask) { modDebugMask |= mask } func DisableDebugModules(mask ModuleMask) { modDebugMask &^= mask } func (mod Module) Mask() ModuleMask { return 1 << ModuleMask(mod) } func (mod Module) Enabled(level logrus.Level) bool { return level <= logrus.WarnLevel || modDebugMask&mod.Mask() != 0 } // Implement the whole logging interface directly on modules func (mod Module) WithFields(fields Fields) Entry { return Entry{mod: mod}.WithFields(fields) } func (mod Module) WithDelayedFields(getfields func() Fields) Entry { return Entry{mod: mod}.WithDelayedFields(getfields) } func (mod Module) WithField(key string, value interface{}) Entry { return Entry{mod: mod}.WithField(key, value) } func (mod Module) Debug(args ...interface{}) { Entry{mod: mod}.Debug(args...) } func (mod Module) Print(args ...interface{}) { Entry{mod: mod}.Print(args...) } func (mod Module) Info(args ...interface{}) { Entry{mod: mod}.Info(args...) } func (mod Module) Warn(args ...interface{}) { Entry{mod: mod}.Warn(args...) } func (mod Module) Warning(args ...interface{}) { Entry{mod: mod}.Warning(args...) } func (mod Module) Error(args ...interface{}) { Entry{mod: mod}.Error(args...) } func (mod Module) Fatal(args ...interface{}) { Entry{mod: mod}.Fatal(args...) } func (mod Module) Panic(args ...interface{}) { Entry{mod: mod}.Panic(args...) } // printf-like family func (mod Module) Debugf(format string, args ...interface{}) { Entry{mod: mod}.Debugf(format, args...) } func (mod Module) Printf(format string, args ...interface{}) { Entry{mod: mod}.Printf(format, args...) } func (mod Module) Infof(format string, args ...interface{}) { Entry{mod: mod}.Infof(format, args...) } func (mod Module) Warnf(format string, args ...interface{}) { Entry{mod: mod}.Warnf(format, args...) } func (mod Module) Warningf(format string, args ...interface{}) { Entry{mod: mod}.Warningf(format, args...) } func (mod Module) Errorf(format string, args ...interface{}) { Entry{mod: mod}.Errorf(format, args...) } func (mod Module) Fatalf(format string, args ...interface{}) { Entry{mod: mod}.Fatalf(format, args...) } func (mod Module) Panicf(format string, args ...interface{}) { Entry{mod: mod}.Panicf(format, args...) } // New-line style family func (mod Module) Debugln(args ...interface{}) { Entry{mod: mod}.Debugln(args...) } func (mod Module) Println(args ...interface{}) { Entry{mod: mod}.Println(args...) } func (mod Module) Infoln(args ...interface{}) { Entry{mod: mod}.Infoln(args...) } func (mod Module) Warnln(args ...interface{}) { Entry{mod: mod}.Warnln(args...) } func (mod Module) Warningln(args ...interface{}) { Entry{mod: mod}.Warningln(args...) } func (mod Module) Errorln(args ...interface{}) { Entry{mod: mod}.Errorln(args...) } func (mod Module) Fatalln(args ...interface{}) { Entry{mod: mod}.Fatalln(args...) } func (mod Module) Panicln(args ...interface{}) { Entry{mod: mod}.Panicln(args...) } <file_sep>/emu/gfx/screen.go package gfx import ( "reflect" "unsafe" ) type Line struct { ptr uintptr } func NewLine(mem []byte) Line { return Line{uintptr(unsafe.Pointer(&mem[0]))} } func (l Line) IsNil() bool { return l.ptr == 0 } func (l *Line) Add8(x int) { l.ptr += uintptr(x) } func (l *Line) Add16(x int) { l.ptr += uintptr(x * 2) } func (l *Line) Add32(x int) { l.ptr += uintptr(x * 4) } func (l Line) Get8(x int) uint8 { xx := uintptr(x) return *(*uint8)(unsafe.Pointer(l.ptr + xx)) } func (l Line) Get16(x int) uint16 { xx := uintptr(x * 2) return *(*uint16)(unsafe.Pointer(l.ptr + xx)) } func (l Line) Get32(x int) uint32 { xx := uintptr(x * 4) return *(*uint32)(unsafe.Pointer(l.ptr + xx)) } func (l Line) Set8(x int, val uint8) { xx := uintptr(x) *(*uint8)(unsafe.Pointer(l.ptr + xx)) = val } func (l Line) Set16(x int, val uint16) { xx := uintptr(x * 2) *(*uint16)(unsafe.Pointer(l.ptr + xx)) = val } func (l Line) Set32(x int, val uint32) { xx := uintptr(x * 4) *(*uint32)(unsafe.Pointer(l.ptr + xx)) = val } func (l Line) SetRGB(x int, r, g, b uint8) { xx := uintptr(x * 4) *(*uint8)(unsafe.Pointer(l.ptr + xx)) = r *(*uint8)(unsafe.Pointer(l.ptr + xx + 1)) = g *(*uint8)(unsafe.Pointer(l.ptr + xx + 2)) = b } type Buffer struct { ptr unsafe.Pointer Width, Height int pitch int } func NewBuffer(ptr unsafe.Pointer, w, h, pitch int) Buffer { return Buffer{ptr: ptr, Width: w, Height: h, pitch: pitch} } func NewBufferMem(w, h int) Buffer { mem := make([]byte, w*h*4) return NewBuffer(unsafe.Pointer(&mem[0]), w, h, w*4) } func (buf *Buffer) Pointer() unsafe.Pointer { return buf.ptr } func (buf *Buffer) Line(y int) Line { if y >= 0 && y < buf.Height { ptr := uintptr(buf.ptr) + uintptr(y*buf.pitch) return Line{ptr} } panic("invalid line") } func (buf *Buffer) LineAsSlice(y int) []uint8 { if y >= 0 && y < buf.Height { ptr := uintptr(buf.ptr) + uintptr(y*buf.pitch) slice := reflect.SliceHeader{Data: ptr, Len: buf.Width * 4, Cap: buf.Width * 4} return *(*[]uint8)(unsafe.Pointer(&slice)) } return nil } <file_sep>/powerman.go package main import ( "ndsemu/emu/spi" log "ndsemu/emu/logger" ) var modPower = log.NewModule("powerman") type HwPowerMan struct { cntrl uint8 } func NewHwPowerMan() *HwPowerMan { return &HwPowerMan{} } func (ff *HwPowerMan) SpiTransfer(data []byte) ([]byte, spi.ReqStatus) { index := data[0] if index&0x80 == 0 { // Write reg if len(data) < 2 { return nil, spi.ReqContinue } val := data[1] switch index & 0x7F { case 0: ff.cntrl = val modPower.Infof("write control: %02x", data) default: modPower.Infof("write reg %d: %02x", index&0x7F, val) } return nil, spi.ReqFinish } else { // Read reg switch index & 0x7F { case 0: return []byte{ff.cntrl}, spi.ReqFinish default: modPower.Infof("read reg %d", index&0x7F) return nil, spi.ReqFinish } } } func (ff *HwPowerMan) SpiBegin() {} func (ff *HwPowerMan) SpiEnd() {} <file_sep>/sync.go package main import ( "ndsemu/emu" ) const ( cBusClock = int64(0x1FF61FE) // 33.513982 Mhz cNds7Clock = cBusClock cNds9Clock = cBusClock * 2 cEmuClock = cBusClock cAudioFreq = 32760 // should be 32768, but we need a multiple of FPS ) var SyncConfig = emu.SyncConfig{ MainClock: cBusClock, DotClockDivider: 6, // Dot Clock = 5.585664 MHz HDots: 355, VDots: 263, // Sync at the beginning of each line, and at hblank HSyncs: []int{0, cHBlankFirstDot}, } <file_sep>/arm/regs.go package arm import ( "fmt" log "gopkg.in/Sirupsen/logrus.v0" ) type reg uint32 func boolToReg(f bool) reg { // Use a form that the compiler can optimize into a SETxx (https://github.com/golang/go/issues/6011) var i reg if f { i = 1 } return i } func (r reg) Bit(n uint) bool { return ((uint32(r) >> n) & 1) != 0 } func (r *reg) BitSet(n uint) { *r |= 1 << n } func (r *reg) BitClear(n uint) { *r &= ^(1 << n) } func (r *reg) BitChange(n uint, f bool) { i := boolToReg(f) *r = ((*r) &^ (1 << n)) | i<<n } func (r *reg) SetWithMask(val uint32, mask uint32) { *r = reg(((uint32)(*r) &^ mask) | (val & mask)) } func (r reg) String() string { return fmt.Sprintf("%08X", uint32(r)) } type regCpsr struct { r reg } func (r regCpsr) CB() uint32 { return (uint32(r.r) >> 29) & 1 } // We don't use Bit() here because of the Go compiler is too sucky at // optimizations and we don't want to create overhead on the hot paths func (r regCpsr) N() bool { return r.r&(1<<31) != 0 } func (r regCpsr) Z() bool { return r.r&(1<<30) != 0 } func (r regCpsr) C() bool { return r.r&(1<<29) != 0 } func (r regCpsr) V() bool { return r.r&(1<<28) != 0 } func (r regCpsr) Q() bool { return r.r&(1<<27) != 0 } func (r regCpsr) I() bool { return r.r&(1<<7) != 0 } func (r regCpsr) F() bool { return r.r&(1<<6) != 0 } func (r regCpsr) T() bool { return r.r&(1<<5) != 0 } func (r *regCpsr) SetNZ(val uint32) { r.r &= 0x3FFFFFFF r.r |= reg(val & 0x80000000) i := boolToReg(val == 0) r.r |= i << 30 } func (r *regCpsr) SetNZ64(val uint64) { r.r &= 0x3FFFFFFF r.r |= reg((val >> 32) & 0x80000000) i := boolToReg(val == 0) r.r |= i << 30 } func (r *regCpsr) SetC(val bool) { r.r.BitChange(29, val) } func (r *regCpsr) SetVAdd(s1, s2, res uint32) { v := ^(s1 ^ s2) & (s1 ^ res) & 0x80000000 r.r &^= 0x10000000 r.r |= reg(v >> 3) } func (r *regCpsr) SetVSub(s1, s2, res uint32) { v := ((s1 ^ s2) & (s1 ^ res) & 0x80000000) r.r &^= 0x10000000 r.r |= reg(v >> 3) } func (r *regCpsr) SetI(val bool) { r.r.BitChange(7, val) } func (r *regCpsr) SetF(val bool) { r.r.BitChange(6, val) } func (r *regCpsr) SetT(val bool) { r.r.BitChange(5, val) } func (r *regCpsr) GetMode() CpuMode { return CpuMode(r.r & 0x1F) } func (r *regCpsr) SetMode(mode CpuMode, cpu *Cpu) { r.SetWithMask(uint32(mode), 0x1F, cpu) } func (r *regCpsr) Set(val uint32, cpu *Cpu) { r.SetWithMask(val, 0xFFFFFFFF, cpu) } func (r *regCpsr) Uint32() uint32 { return uint32(r.r) } func (r *regCpsr) SetWithMask(val uint32, mask uint32, cpu *Cpu) { oldmode := CpuMode(r.r & 0x1F) r.r = (r.r &^ reg(mask)) | reg(val&mask) mode := CpuMode(r.r & 0x1F) // If the I/F bits are potentially changed, we must force // exit the tight loop, to check if the new bits will cause // an interrupt right away. if mask&0xC0 != 0 { cpu.tightExit = true } if mode == oldmode { return } // log.WithFields(log.Fields{ // "mode": mode, // "old": oldmode, // "pc": cpu.GetPC(), // }).Info("changing CPSR mode") switch oldmode { case CpuModeUser, CpuModeSystem: copy(cpu.UsrBank[:], cpu.Regs[13:15]) case CpuModeFiq: copy(cpu.FiqBank2[:], cpu.Regs[8:13]) copy(cpu.Regs[8:13], cpu.UsrBank2[:]) copy(cpu.FiqBank[:], cpu.Regs[13:15]) case CpuModeIrq: copy(cpu.IrqBank[:], cpu.Regs[13:15]) case CpuModeSupervisor: copy(cpu.SvcBank[:], cpu.Regs[13:15]) case CpuModeAbort: copy(cpu.AbtBank[:], cpu.Regs[13:15]) case CpuModeUndefined: copy(cpu.UndBank[:], cpu.Regs[13:15]) default: log.Fatalf("unknown CPU oldmode: %v", oldmode) } switch mode { case CpuModeUser, CpuModeSystem: copy(cpu.Regs[13:15], cpu.UsrBank[:]) case CpuModeFiq: copy(cpu.UsrBank2[:], cpu.Regs[8:13]) copy(cpu.Regs[8:13], cpu.FiqBank2[:]) copy(cpu.Regs[13:15], cpu.FiqBank[:]) case CpuModeIrq: copy(cpu.Regs[13:15], cpu.IrqBank[:]) case CpuModeSupervisor: copy(cpu.Regs[13:15], cpu.SvcBank[:]) case CpuModeAbort: copy(cpu.Regs[13:15], cpu.AbtBank[:]) case CpuModeUndefined: copy(cpu.Regs[13:15], cpu.UndBank[:]) default: log.Fatalf("unknown CPU newmode: %v", mode) } } func (r regCpsr) String() string { return r.r.String() } type CpuMode int const ( CpuModeUser CpuMode = 0x10 CpuModeFiq CpuMode = 0x11 CpuModeIrq CpuMode = 0x12 CpuModeSupervisor CpuMode = 0x13 CpuModeAbort CpuMode = 0x17 CpuModeUndefined CpuMode = 0x18 CpuModeSystem CpuMode = 0x1F ) func (m CpuMode) String() string { switch m { case CpuModeUser: return "CpuModeUser" case CpuModeFiq: return "CpuModeFiq" case CpuModeIrq: return "CpuModeIrq" case CpuModeSupervisor: return "CpuModeSupervisor" case CpuModeAbort: return "CpuModeAbort" case CpuModeUndefined: return "CpuModeUndefined" case CpuModeSystem: return "CpuModeSystem" default: return fmt.Sprintf("CpuMode(%02x)", int(m)) } } <file_sep>/backup.go package main import ( log "ndsemu/emu/logger" "ndsemu/emu/spi" ) var modBackup = log.NewModule("backup") // HwBackupRam implements the save ram presents in most cartridge. // It implements the spi.Device interface type HwBackupRam struct { sram [4 * 1024 * 1024]byte addrSize int addr int wbuf []byte writeEnabled bool autodetect bool auxCntrWritten bool } func NewHwBackupRam() *HwBackupRam { b := &HwBackupRam{ autodetect: true, } for idx := range b.sram { b.sram[idx] = 0xFF } return b } func (b *HwBackupRam) tryAutoDetect(data []byte) bool { if len(data) == 1 { b.auxCntrWritten = false return false } if b.auxCntrWritten { b.addrSize = len(data) - 2 modBackup.Warnf("autodetect addr size: %d", b.addrSize) b.autodetect = false return true } modBackup.Infof("autodetect failed, waiting") return false } func (b *HwBackupRam) SpiTransfer(data []byte) ([]byte, spi.ReqStatus) { switch data[0] { case 0x0: // Dummy command that is sometimes sent. Ignore it return nil, spi.ReqFinish case 0x5: // RDSR modBackup.Infof("cmd RDSR") return nil, spi.ReqFinish case 0x4: // WRDI modBackup.Infof("cmd WRDI") b.writeEnabled = false return nil, spi.ReqFinish case 0x6: // WREN modBackup.Infof("cmd WREN") b.writeEnabled = true return nil, spi.ReqFinish case 0x3: // RD if b.autodetect && !b.tryAutoDetect(data) { return nil, spi.ReqContinue } if len(data) < 1+b.addrSize { return nil, spi.ReqContinue } if len(data) == 1+b.addrSize { b.addr = 0 for _, v := range data[1:] { b.addr <<= 8 b.addr |= int(v) } } modBackup.WithField("addr", b.addr).Info("cmd RD") buf := make([]byte, 256) sz := len(b.sram) - b.addr if sz > 256 { sz = 256 } copy(buf[:sz], b.sram[b.addr:b.addr+sz]) return buf, spi.ReqContinue case 0x2, 0xA: // WR if !b.writeEnabled { modBackup.Fatal("writing with write disabled") } if b.autodetect { modBackup.Fatal("writing while autodetecting size") } if len(data) < 1+b.addrSize { return nil, spi.ReqContinue } if len(data) == 1+b.addrSize { b.addr = 0 for _, v := range data[1:] { b.addr <<= 8 b.addr |= int(v) } modBackup.WithField("addr", b.addr).Info("cmd WR") } // Copy the whole buffer every time; I know it's inefficient, // but never mind... copy(b.sram[b.addr:], data[1+b.addrSize:]) return nil, spi.ReqContinue // case 0x2: // WR // if len(gc.spiwbuf) >= 3 { // addr := int(gc.spiwbuf[1])<<8 + int(gc.spiwbuf[2]) // if len(gc.spiwbuf) == 3 { // modGamecard.WithField("addr", addr).Info("SPI write backup") // } // addr += len(gc.spiwbuf) - 3 // gc.backupSram[addr] = uint8(value) // } // case 0x2: // WRLO // if len(gc.spiwbuf) >= 2 { // addr := int(gc.spiwbuf[1]) // if len(gc.spiwbuf) == 2 { // modGamecard.WithField("addr", addr).Info("SPI write backup 0.5k LO") // } // addr += len(gc.spiwbuf) - 2 // gc.backupSram[addr] = uint8(value) // } // case 0xA: // WRHI // if len(gc.spiwbuf) >= 2 { // addr := int(gc.spiwbuf[1]) + 0x100 // if len(gc.spiwbuf) == 2 { // modGamecard.WithField("addr", addr).Info("SPI write backup 0.5k HI") // } // addr += len(gc.spiwbuf) - 2 // gc.backupSram[addr] = uint8(value) // } default: modBackup.Errorf("unimplemented command %x (len=%d)", data, len(data)) if len(data) == 16 { modBackup.Fatalf("ciao") } return nil, spi.ReqContinue } } // This is a callback to inform that the AUXSPI control register has been written. // It is normally not required on normal execution because it is already processed // by gamecard to control the spi bus (that eventually calls HwBackupRam as spi.Device); // but it's very useful when we are doing auto-detection of backup RAM size. func (b *HwBackupRam) AuxSpiCntWritten(value uint16) { b.auxCntrWritten = true } func (b *HwBackupRam) SpiBegin() { modBackup.Info("begin transfer") } func (b *HwBackupRam) SpiEnd() { modBackup.Info("end transfer") } <file_sep>/emu/logger/context.go package logger type LogContextAdder interface { // Given a log entry being formed, add some context it // (by called WithFields) AddLogContext(entry Entry) Entry } var contexts []LogContextAdder func AddContext(c LogContextAdder) { contexts = append(contexts, c) } <file_sep>/e2d/engine2d.go package e2d import ( "ndsemu/emu" "ndsemu/emu/gfx" "ndsemu/emu/hwio" log "ndsemu/emu/logger" ) type bgRegs struct { Cnt *uint16 XOfs, YOfs *uint16 PA, PB *uint16 PC, PD *uint16 PX, PY *uint32 } func (r *bgRegs) priority() uint16 { return (*r.Cnt & 3) } func (r *bgRegs) depth256() bool { return (*r.Cnt>>7)&1 != 0 } type HwEngine2d struct { Idx int DispCnt hwio.Reg32 `hwio:"offset=0x00,wcb"` Bg0Cnt hwio.Reg16 `hwio:"offset=0x08"` Bg1Cnt hwio.Reg16 `hwio:"offset=0x0A"` Bg2Cnt hwio.Reg16 `hwio:"offset=0x0C"` Bg3Cnt hwio.Reg16 `hwio:"offset=0x0E"` Bg0XOfs hwio.Reg16 `hwio:"offset=0x10,writeonly"` Bg0YOfs hwio.Reg16 `hwio:"offset=0x12,writeonly"` Bg1XOfs hwio.Reg16 `hwio:"offset=0x14,writeonly"` Bg1YOfs hwio.Reg16 `hwio:"offset=0x16,writeonly"` Bg2XOfs hwio.Reg16 `hwio:"offset=0x18,writeonly"` Bg2YOfs hwio.Reg16 `hwio:"offset=0x1A,writeonly"` Bg3XOfs hwio.Reg16 `hwio:"offset=0x1C,writeonly"` Bg3YOfs hwio.Reg16 `hwio:"offset=0x1E,writeonly"` Bg2PA hwio.Reg16 `hwio:"offset=0x20,writeonly"` Bg2PB hwio.Reg16 `hwio:"offset=0x22,writeonly"` Bg2PC hwio.Reg16 `hwio:"offset=0x24,writeonly"` Bg2PD hwio.Reg16 `hwio:"offset=0x26,writeonly"` Bg2PX hwio.Reg32 `hwio:"offset=0x28,writeonly"` Bg2PY hwio.Reg32 `hwio:"offset=0x2C,writeonly"` Bg3PA hwio.Reg16 `hwio:"offset=0x30,writeonly"` Bg3PB hwio.Reg16 `hwio:"offset=0x32,writeonly"` Bg3PC hwio.Reg16 `hwio:"offset=0x34,writeonly"` Bg3PD hwio.Reg16 `hwio:"offset=0x36,writeonly"` Bg3PX hwio.Reg32 `hwio:"offset=0x38,writeonly"` Bg3PY hwio.Reg32 `hwio:"offset=0x3C,writeonly"` Win0X hwio.Reg16 `hwio:"offset=0x40,writeonly"` Win1X hwio.Reg16 `hwio:"offset=0x42,writeonly"` Win0Y hwio.Reg16 `hwio:"offset=0x44,writeonly"` Win1Y hwio.Reg16 `hwio:"offset=0x46,writeonly"` WinIn hwio.Reg16 `hwio:"offset=0x48"` WinOut hwio.Reg16 `hwio:"offset=0x4A"` Mosaic hwio.Reg16 `hwio:"offset=0x4C,writeonly"` BldCnt hwio.Reg16 `hwio:"offset=0x50"` BldAlpha hwio.Reg16 `hwio:"offset=0x52"` BldY hwio.Reg32 `hwio:"offset=0x54"` MBright hwio.Reg32 `hwio:"offset=0x6C,rwmask=0xC01F,wcb"` // bank 1: registers available only on display A DispCapCnt hwio.Reg32 `hwio:"bank=1,offset=0x64"` DispMMemFifo hwio.Reg32 `hwio:"bank=1,offset=0x68,wcb"` bgregs [4]bgRegs bgmodes [4]BgMode mc MemoryController lineBuf [4 * (cScreenWidth + 16)]byte lm gfx.LayerManager l3d gfx.Layer dispmode int curline int curscreen gfx.Line modeTable [4]struct { BeginFrame func() EndFrame func() BeginLine func(y int, screen gfx.Line) EndLine func(y int) } dispcap struct { Enabled bool Mode int WBank int WOffset uint32 RBank int ROffset uint32 Width, Height int AlphaA, AlphaB uint32 } // Master brightness conversion. Depending on the master brightness // register, we precalculate highlighted/shadowed colors for the 32 // shades; moreover, to save time on the mixer, we also already shift // R,G,B of the correct amount, so that the mixer can just OR them // together. masterBrightChanged bool masterBrightR [32]uint32 masterBrightG [32]uint32 masterBrightB [32]uint32 bgPal []byte objPal []byte bgExtPals [4][]byte objExtPal []byte } func NewHwEngine2d(idx int, mc MemoryController, l3d gfx.Layer) *HwEngine2d { e2d := new(HwEngine2d) hwio.MustInitRegs(e2d) e2d.Idx = idx e2d.mc = mc e2d.l3d = l3d e2d.masterBrightChanged = true // force initial table calculation // Initialize bgregs data structure which is easier to index // compared to the raw registers e2d.bgregs[0].Cnt = &e2d.Bg0Cnt.Value e2d.bgregs[0].XOfs = &e2d.Bg0XOfs.Value e2d.bgregs[0].YOfs = &e2d.Bg0YOfs.Value e2d.bgregs[1].Cnt = &e2d.Bg1Cnt.Value e2d.bgregs[1].XOfs = &e2d.Bg1XOfs.Value e2d.bgregs[1].YOfs = &e2d.Bg1YOfs.Value e2d.bgregs[2].Cnt = &e2d.Bg2Cnt.Value e2d.bgregs[2].XOfs = &e2d.Bg2XOfs.Value e2d.bgregs[2].YOfs = &e2d.Bg2YOfs.Value e2d.bgregs[2].PA = &e2d.Bg2PA.Value e2d.bgregs[2].PB = &e2d.Bg2PB.Value e2d.bgregs[2].PC = &e2d.Bg2PC.Value e2d.bgregs[2].PD = &e2d.Bg2PD.Value e2d.bgregs[2].PX = &e2d.Bg2PX.Value e2d.bgregs[2].PY = &e2d.Bg2PY.Value e2d.bgregs[3].Cnt = &e2d.Bg3Cnt.Value e2d.bgregs[3].XOfs = &e2d.Bg3XOfs.Value e2d.bgregs[3].YOfs = &e2d.Bg3YOfs.Value e2d.bgregs[3].PA = &e2d.Bg3PA.Value e2d.bgregs[3].PB = &e2d.Bg3PB.Value e2d.bgregs[3].PC = &e2d.Bg3PC.Value e2d.bgregs[3].PD = &e2d.Bg3PD.Value e2d.bgregs[3].PX = &e2d.Bg3PX.Value e2d.bgregs[3].PY = &e2d.Bg3PY.Value // Initialize the mode table, used to implement the four different // display modes e2d.modeTable[0].BeginFrame = e2d.Mode0_BeginFrame e2d.modeTable[0].EndFrame = e2d.Mode0_EndFrame e2d.modeTable[0].BeginLine = e2d.Mode0_BeginLine e2d.modeTable[0].EndLine = e2d.Mode0_EndLine e2d.modeTable[1].BeginFrame = e2d.Mode1_BeginFrame e2d.modeTable[1].EndFrame = e2d.Mode1_EndFrame e2d.modeTable[1].BeginLine = e2d.Mode1_BeginLine e2d.modeTable[1].EndLine = e2d.Mode1_EndLine e2d.modeTable[2].BeginFrame = e2d.Mode2_BeginFrame e2d.modeTable[2].EndFrame = e2d.Mode2_EndFrame e2d.modeTable[2].BeginLine = e2d.Mode2_BeginLine e2d.modeTable[2].EndLine = e2d.Mode2_EndLine e2d.modeTable[3].BeginFrame = e2d.Mode3_BeginFrame e2d.modeTable[3].EndFrame = e2d.Mode3_EndFrame e2d.modeTable[3].BeginLine = e2d.Mode3_BeginLine e2d.modeTable[3].EndLine = e2d.Mode3_EndLine // Initialize layer manager (used in mode1) e2d.lm.Cfg = gfx.LayerManagerConfig{ Width: cScreenWidth, Height: cScreenHeight, ScreenBpp: 4, LayerBpp: 4, OverflowPixels: 8, Mixer: e2dMixer_Normal, MixerCtx: e2d, } // Background layers e2d.lm.AddLayer(gfx.LayerFunc{Func: e2d.DrawBG}) e2d.lm.AddLayer(gfx.LayerFunc{Func: e2d.DrawBG}) e2d.lm.AddLayer(gfx.LayerFunc{Func: e2d.DrawBG}) e2d.lm.AddLayer(gfx.LayerFunc{Func: e2d.DrawBG}) // Sprites layer e2d.lm.AddLayer(gfx.LayerFunc{Func: e2d.DrawOBJ}) return e2d } func (e2d *HwEngine2d) A() bool { return e2d.Idx == 0 } func (e2d *HwEngine2d) B() bool { return e2d.Idx != 0 } func (e2d *HwEngine2d) Name() byte { return 'A' + byte(e2d.Idx) } func (e2d *HwEngine2d) WriteDISPCNT(old, val uint32) { modLcd.WithFields(log.Fields{ "name": string('A' + e2d.Idx), "val": emu.Hex32(val), }).Info("write dispcnt") } func (e2d *HwEngine2d) WriteDISPMMEMFIFO(old, val uint32) { if val != 0 { modLcd.Fatalf("unimplemented DISP MMEM FIFO") } } func (e2d *HwEngine2d) WriteMBRIGHT(old, val uint32) { if old != val { e2d.masterBrightChanged = true } } func (e2d *HwEngine2d) updateMasterBrightTable() { // Setup master brightness lookup tables. Do this for every line just to be safe brightMode := (e2d.MBright.Value >> 14) & 3 brightFactor := int32(e2d.MBright.Value & 0x1F) if brightFactor > 16 { brightFactor = 16 } for i := int32(0); i < int32(32); i++ { // Expand to 6-bit color using the hardware formula. // It looks like internally the mixer handle 6-bit colors; // the 3D layer also outputs 6-bit colors, but we currently // drop the lower bit, so the mixer always receives 5-bit colors. c := i if c > 0 { c = c*2 + 1 } switch brightMode { case 1: // brightness up c += (63 - c) * brightFactor / 16 if c > 63 { c = 63 } case 2: // brightness down c -= c * brightFactor / 16 if c < 0 { c = 0 } } // Expand from 6-bits to 8-bits c = c<<2 | c>>4 // Fill up the table with the 3 masks e2d.masterBrightR[i] = uint32(c) e2d.masterBrightG[i] = uint32(c) << 8 e2d.masterBrightB[i] = uint32(c) << 16 } }
5b4b8d818b1760ced9983236ec4ac21a63eb6ac1
[ "Go" ]
31
Go
knut0815/ndsemu
4b7eff139499ffc856aa683972389f6b2f55fad2
a201103a6cc1ac2526ce109ebb455a2361992cb4
refs/heads/main
<file_sep># Nevezés #### Adottak a következő osztályok. ```java public class Alcoholic { public boolean isDrunk() { return true; } } ``` ```java public class Golya extends Alcoholic { private enum signature {signed, declined} private String neptun; private int felviPoint; private int mentalhealth; private int currentSemester; private short money; private signature signed = signature.declined; private Golya() { isDrunk(); } public boolean hasGirlfriend() { return false; } public boolean useFelviPoint() { return false; } public boolean uni() { while(mentalhealth >= 0) { mentalhealth--; currentSemester++; if(currentSemester >= 12) { money = 0; mentalhealth = 0; isDrunk(); } if(signed.equals(signature.declined)){ return isDrunk(); } } return isDrunk(); } } ``` ```java public class GolyaFutam { private Golya golyci; private boolean singedUp; public GolyaFutam(Golya golyo) { signUp(golyo); } public void signUp(Golya golyo){ golyci = golyo; singedUp = true; } } ``` ###### Sajnos, mikor elkezdtem programozni, még nem tudtam ilyen szofisztikált módon kódolni, sőt a java-t egyáltalán nem ismertem. Írtam is annak idején egy C kódot, amiben egy nagyon fontos üzenetet rejtettem el. De sajnos már nem tudom megfejteni, hogy mit is csinál a kódom. #### Ha át tudnám írni kicsit olvashatóbbra a kódot, rá tudnék jönni, hogy mi is az az üzenet: ```c #define BUT ; #define SO ; #define SEMMI (int)NULL #define SZAM 0xD #define kdGd_ return #define theEND ) #include <stdio.h> #define PONT '.' #define DONNO "%s" #define h6_d [ #define KISAUTO char int main( theEND { KISAUTO Hdu__d[0xF] BUT #define BLA [ Hdu__d BLA SZAM] = 'i' SO SO Hdu__d BLA 0xE - 0x0] = SEMMI; Hdu__d[2] = 't'; #include <stdbool.h> 3 h6_d Hdu__d] = PONT SO Hdu__d[5] = 121 BUT Hdu__d BLA 6] = '/' SO Hdu__d[1] = 'i' SO if(!(true) || ((true) && !(!(1))) && false); { Hdu__d[7] = 062 BUT Hdu__d BLA 010] = 'U'; } #define KILENC '0' Hdu__d BLA 2 * (7 - 2 theEND ] = 8 + KILENC BUT Hdu__d[0xB] = 'G' SO Hdu__d h6_d 014] = 'J'; SO Hdu__d h6_d 4 + 4 + 4 - 4 + 4 - 4 - 4] = 'l' SO #define $dolla ( Hdu__d[0x9] = '0';; ;;; ; Hdu__d[SEMMI] = 'b' BUT Hdu__d h6_d 0] = 0 BUT printf $dolla DONNO , Hdu__d) BUT kdGd_ SEMMI; } ``` <file_sep>public class GolyaFutam { private Golya golyci; private boolean singedUp; public GolyaFutam(Golya golyo) { signUp(golyo); } public void signUp(Golya golyo){ golyci = golyo; singedUp = true; } } <file_sep>#define BUT ; #define SO ; #define SEMMI (int)NULL #define SZAM 0xD #define kdGd_ return #define theEND ) #include <stdio.h> #define PONT '.' #define DONNO "%s" #define h6_d [ #define KISAUTO char int main( theEND { KISAUTO Hdu__d[0xF] BUT #define BLA [ Hdu__d BLA SZAM] = 'i' SO SO Hdu__d BLA 0xE - 0x0] = SEMMI; Hdu__d[2] = 't'; #include <stdbool.h> 3 h6_d Hdu__d] = PONT SO Hdu__d[5] = 121 BUT Hdu__d BLA 6] = '/' SO Hdu__d[1] = 'i' SO if(!(true) || ((true) && !(!(1))) && false); { Hdu__d[7] = 062 BUT Hdu__d BLA 010] = 'U'; } #define KILENC '0' Hdu__d BLA 2 * (7 - 2 theEND ] = 8 + KILENC BUT Hdu__d[0xB] = 'G' SO Hdu__d h6_d 014] = 'J'; SO Hdu__d h6_d 4 + 4 + 4 - 4 + 4 - 4 - 4] = 'l' SO #define $dolla ( Hdu__d[0x9] = '0';; ;;; ; Hdu__d[SEMMI] = 'b' BUT Hdu__d h6_d 0] = 0 BUT printf $dolla DONNO , Hdu__d) BUT kdGd_ SEMMI; }<file_sep>public class Golya extends Alcoholic { private enum signature {signed, declined} private String neptun; private int felviPoint; private int mentalhealth; private int currentSemester; private short money; private signature signed = signature.declined; private Golya() { isDrunk(); } public boolean hasGirlfriend() { return false; } public boolean useFelviPoint() { return false; } public boolean uni() { while(mentalhealth >= 0) { mentalhealth--; currentSemester++; if(currentSemester >= 12) { money = 0; mentalhealth = 0; isDrunk(); } if(signed.equals(signature.declined)){ return isDrunk(); } } return isDrunk(); } }
79a79d63b87aef258735b8799d17ad9346f19499
[ "Markdown", "Java", "C" ]
4
Markdown
GolyaFutam/Nevezes
2060af1244a0dc98a0524c958798cd1f47362535
172903abfa76c625b1f1e9b130f03a1298d419aa
refs/heads/master
<file_sep>/** * sails-model-builder.js * * @description :: utility class that allows you to build you sails models quickly and efficiently * @docs :: http://sailsjs.org/#!documentation/models */ /* jshint node:true */ 'use strict'; var _ = require('lodash'); var uuid = require('node-uuid'); // mayordomo event manager (https://github.com/kdelmonte/mayordomo) var mayordomo = require('mayordomo'); // List sails model lifecycles. We will use these later // to create subscribable events for each one var lifecycles = [ 'beforeValidate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy' ]; // Create a whitelist of properties to copy from mayordomo // This is a combination of the mayordomo event methods (on, off, trigger) // and the sails model lifecycles var mayordomoEvents = _.flatten(['on', 'off', 'trigger', lifecycles]); module.exports = function () { // Create new instance of event manager var eventManager = mayordomo.new(); // Sets up the lifecycle callbacks of Sails models as subscribable events // See more here: http://sailsjs.org/documentation/concepts/models-and-orm/lifecycle-callbacks function setupLifecycleEvents () { // Go through all Sails models lifecycles _.each(lifecycles, function (lifecycleName) { // Setup the lifecycle callabck as a function that will be // responsible for triggering the event handlers workingModel[lifecycleName] = function (instance, cb) { // If nobody has subscribed to this lifecycle, run callback immediately if (!eventManager.any(lifecycleName)) { cb(); return; } // `orphanCallback` will allow us to know if any of the handlers called the cb() callback // of the lifecycle var orphanCallback = true; // the `adopt` callback lets us know that the user assumed responsibility of running the callback var adopt = function () { orphanCallback = false; }; // Wrap sails callback in order to know if any handlers ran or plan to run the callback manually var wrappedCb = _.wrap(cb, function (fx, message) { // This callback is not an orphan anymore adopt(); // Run the sails lifecycle cb() fx(message); }); // Trigger all event handlers of this lifecycle eventManager.trigger(lifecycleName, [instance, wrappedCb, adopt]); // If the lifecycle cb() did not run, let's run it to get the response out of limbo if (orphanCallback) { cb(); } }; }); } // Declare the events (with shortcuts) in the event manager eventManager.declare(lifecycles, true); // Declare the working model var workingModel = { attributes: {} }; setupLifecycleEvents(); var modelBuilder = { // Sets or retrieves the working model model: function (model) { // If no arguments were passed, then this is just a getter if (!arguments.length) return workingModel; // Assign the model as the working model workingModel = model; // If the model that was passed does not contain attributes, // then set the attributes as an empty object if (!workingModel.attributes) { workingModel.attributes = {}; } // Setup the lifecycle events setupLifecycleEvents(); return this; }, // Adds the `id` attribute as an UUID to the working model uuidKey: function () { workingModel.attributes.id = { type: 'string', unique: true, primaryKey: true, defaultsTo: function () { return uuid.v4(); } }; return this; }, // Adds the `id` attribute as an integer to the working model intKey: function (autoIncrement) { workingModel.attributes.id = { type: 'integer', unique: true, primaryKey: true, autoIncrement: autoIncrement === undefined ? true : autoIncrement }; return this; }, // Sets a list of attributes as required. // If no list is provided, all attributes will be marked as required. require: function () { var attributeNames; if (!arguments.length) { // Since no arguments were passed, get all the current attribute names attributeNames = _.keys(workingModel.attributes); } else { // If the first argument is an array then use it. // Otherwise use the entire arguments object as the list if (_.isArray(arguments[0])) { attributeNames = arguments[0]; } else { attributeNames = _.toArray(arguments); } } // Make the specified attributes required modelBuilder.attr(attributeNames, { required: true }); return this; }, // Sets or extends attributes of the working model // This method supports three overloads: // 1) One that accepts an attributes object // Example: .attr({name: {type: 'string', maxLength: 45}}) // 2) One that accepts an attribute name, a property name, and a property value // Example: .attr('name', 'type', 'string') // 3) One that accepts a list of attribute names and an object that contains shared properties between those attributes // Example: .attr(['parentId','childId'],{type: 'string',minLength: 36, maxLength: 36}) attr: function (attributes, sharedProperties, value) { var currentAttribute; // If the first argument is an object, then we are dealing with overload #1 if (!_.isArray(attributes) && _.isObject(attributes)) { // Loop through all the attributes _.each(attributes, function (attribute, attributeName) { // Get the existing attribute from the working model // If none is found then set it as an empty object currentAttribute = workingModel.attributes[attributeName] || {}; // If current attribute is not a function, then extend it. // Otherwise, leave it alone if (!_.isFunction(attribute)) { _.extend(currentAttribute, attribute); } else { currentAttribute = attribute; } // Set the new extended attribute to the working model workingModel.attributes[attributeName] = currentAttribute; }); return this; } // If three arguments were passed, then we are dealing with overload #2 if (arguments.length === 3) { // The first argument is the attribute name var attributeName = arguments[0]; // The second attribute is the property name var propertyName = arguments[1]; // Get the existing attribute from the working model // If none is found then set it as an empty object currentAttribute = workingModel.attributes[attributeName] || {}; // Set the the value to the target property currentAttribute[propertyName] = value; // Set the updated attribute to the working model workingModel.attributes[attributeName] = currentAttribute; return this; } // If we are here, then we are dealing with overload #3 // If the user passed in a single attribute name in the first argument // then let's put it inside of an array to handle it the same way below if (!_.isArray(attributes)) { attributes = [attributes]; } // Go through all the attribute names that were passed _.each(attributes, function (attributeName) { // Get the existing attribute from the working model // If none is found then set it as an empty object currentAttribute = workingModel.attributes[attributeName] || {}; // Copy over all the shared properties _.extend(currentAttribute, sharedProperties); // Set the new extended attribute to the working model workingModel.attributes[attributeName] = currentAttribute; }); return this; }, // Sets the working model to the exports of the module that is passed in export: function (to) { to.exports = workingModel; return this; } }; // Extend model builder with certain members of the event manager _.extend(modelBuilder, _.pick(eventManager, function (value, key) { return _.contains(mayordomoEvents, key); })); // Setup chaining object to `modelBuilder` in `eventManager` so that // when users call on() or any other of the methods copied over from the // `eventManager` they will get the `modelBuilder` to continue chaining eventManager.chain(modelBuilder); // Finally, return the modelBuilder return modelBuilder; }; <file_sep># sails-model-builder sails-model-builder allows you to take the code over configuration approach when building your Sails models. It also sets up event handlers for all lifecycle callbacks of your models. ## Install `npm install sails-model-builder --save` ## Usage A sails model usually looks like this: var uuid = require('node-uuid'); var bcrypt = require('bcrypt'); module.exports = { id: { type: 'string', unique: true, primaryKey: true, defaultsTo: function () { return uuid.v4(); } }, firstName: { type: 'string', required: true }, lastName: { type: 'string', required: true }, email: { type: 'string', required: true }, phoneNumber: { type: 'string', required: true }, beforeCreate: function (values, cb) { bcrypt.hash(values.password, 10, function(err, hash) { if(err) return cb(err); values.password = <PASSWORD>; cb(); }); } }; Using the model builder you can rewrite it like this: var modelBuilder = require('sails-model-builder')(); var bcrypt = require('bcrypt'); modelBuilder .uuidKey() .attr(['firstName', 'lastName', 'email', 'phoneNumber'], { type: 'string', required: true` }) .beforeCreate(function(values, cb, adoptCb){ adoptCb(); bcrypt.hash(values.password, 10, function(err, hash) { if(err) return cb(err); values.password = <PASSWORD>; cb(); }); }) .export(module); ## API ### model([model]) Sets or retrieves the working model // Get the model var myModel = modelBuilder.model(); // Set the model modelBuilder.model({ attributes: { name: { type: 'string' } } }) ### uuidKey() Adds the `id` attribute as an UUID to the working model modelBuilder.uuidKey(); // Added the following attribute to the model id: { type: 'string', unique: true, primaryKey: true, defaultsTo: function () { return uuid.v4(); } } ### intKey([autoIncrement]) Adds the `id` attribute as an integer to the working model modelBuilder.uuidKey(true); // Added the following attribute to the model id: { type: 'integer', unique: true, primaryKey: true, autoIncrement: autoIncrement === undefined ? true : autoIncrement } ### require([attributeNameList]) Takes all the attributes passed in and marks them as required. If this method is called without arguments, then all attributes will be marked as required. // Pass the attributes as individual arguments modelBuilder.require('firstName', 'lastName'); // or as an array modelBuilder.require(['firstName', 'lastName']); // mark all attributes as required modelBuilder.require(); ### attr() Sets a new attribute or extends it if it already exists. This method supports three overloads: 1) One that accepts an attributes object modelBuilder.attr({ name: { type: 'string', maxLength: 45 } }); 2) One that accepts an attribute name, a property name, and a property value modelBuilder.attr('name', 'type', 'string'); modelBuilder.attr('name', 'maxLength', 45); 3) One that accepts a list of attribute names and an object that contains shared properties between those attributes modelBuilder.attr(['firstName','lastName'],{ type: 'string', required: true, maxLength: 50 } ) ### export(module) Sets the working model as the exports of the module that is passed in modelBuilder .attr({ name: { type: 'string', maxLength: 45 } }) .export(module); ## Event Handling & Lifecycles Read about the lifecycles of a sails model [here](http://sailsjs.org/documentation/concepts/models-and-orm/lifecycle-callbacks). sails-model-builder provides events for all lifecycles of a sails model. You can subscribe to these events like you would subscribe to a jQuery event. **Note**: Notice how you do not have to call `cb` in the example below. If you do not call it yourself, sails-model-builder will call it for you after all event handlers have been run. This is **NOT** the case if you are running an async operation; for that, see the next section. modelBuilder .attr({ username: { type: 'string', required: true }, password: { type: 'string', minLength: 6, required: true, columnName: '<PASSWORD>_<PASSWORD>' } }) // You could also do beforeCreate() .on('beforeCreate', function (values) { values.password = syncEncryptPassword(values.password); }); }) ### Asynchronous operations By default, if you don't call `cb` yourself, sails-model-builder will run it after all your event handlers have been triggered. If you wish to assume the responsibility of executing the callback yourself (maybe after some async operation completes), then you must execute the `assumeCb` callback that sails-model-builder passes to your event handler. This callback simply lets sails-model-builder know not to execute the `cb` for you. See the following example: var bcrypt = require('bcrypt'); modelBuilder .attr({ username: { type: 'string', required: true }, password: { type: 'string', minLength: 6, required: true, columnName: '<PASSWORD>' } }) .beforeCreate(function (values, cb, assumeCb) { // Let sails-model-builder know that you will execute // the cb callback sometime in the future assumeCb(); // Encrypt password bcrypt.hash(values.password, 10, function(err, hash) { if(err) return cb(err); values.password = hash; cb(); }); }) ## Contributing If you would like to contribute, please do so in the development branch.
2836d882b9bbb3b53ec7b54eb7aca558abe6be21
[ "JavaScript", "Markdown" ]
2
JavaScript
kdelmonte/sails-model-builder
fbd2a8ae847b0e39ac175a3bdaab61719db88108
e58e127fe90ff10080defd83f43653354cdcf5c5
refs/heads/master
<file_sep>class EmployeesController < ApplicationController before_filter :set_timezone, :only => [:sign_in, :show] layout 'employee' def new @employee = Employee.new render :layout => 'layouts/admin' end def show @employee = Employee.find_by_id(params[:id]) respond_to do |format| format.html do end format.js do foo = render_to_string(:partial => 'show_partial', :locals => {:employee => @employee}).to_json render :js => "$('#show_partial').html(#{foo});" end end end def search @employees = Employee.find(:all,:conditions => "name #{DATABASE_OPERATOR[:like_operator]} '#{params[:letter]}%'") end def create @employee = Employee.new(params[:employee]) @employee.enable_pin = params[:employee_enable_pin] # @pin = params[:pin_code].split(/,/).join('') # @employee.pin_code=@pin @employee.user_id=current_user.id if @employee.save redirect_to employee_path(@employee) else render :new end end def destroy @employee = Employee.find(params[:id]) @employee.destroy redirect_to employees_path end def index end def sign_in @employee = Employee.find_by_id(params[:id]) if @employee.is_sign_in @employee.update_attribute(:is_sign_in , false) @report= @employee.employee_reports.last @report.sign_out_at = DateTime.now.in_time_zone @report.save else @employee.update_attribute(:is_sign_in , true) @report = EmployeeReport.new @report.employee_id = @employee.id @report.sign_in_at = DateTime.now.in_time_zone @report.day = Time.now.utc.wday @report.save end redirect_to employee_path(@employee) end def sign_out_admin sign_out(current_user) respond_to do |format| format.js do foo = render_to_string(:partial => '/layouts/logout_partial').to_json poo = render_to_string(:partial => '/layouts/ajax_partial').to_json render :js => "$('#logout_div').html(#{foo});$('#ajax_div').html(#{poo});" end end end def set_timezone employee = Employee.find_by_id(params[:id]) # current_user.time_zone #=> 'Central Time (US & Canada)' Time.zone = employee.user.time_zone || 'Central Time (US & Canada)' end end <file_sep>class ApplicationController < ActionController::Base layout :get_layout protect_from_forgery def after_sign_in_path_for(resource) if current_user.user_type == 'superadmin' superadmin_users_path else root_path end end def get_layout if params[:controller]== "devise/registrations" && params[:action]=="edit" return 'admin' else return 'application' end end end <file_sep>class Superadmin::UsersController < ApplicationController layout 'superadmin' def index end def new @user = User.new end def create @user = User.new(params[:user]) @user.skip_confirmation! if @user.save redirect_to superadmin_users_path else render :new end end def update @user = User.find(params[:id]) @user.update_attributes(params[:user]) redirect_to superadmin_users_path end def modify_companies @users = User.where(:user_type => 'admin') end def edit @user = User.find(params[:id]) end def delete_companies unless params[:user_company_name].blank? params[:user_company_name].each do |user| @U = User.find_by_id(user) @U.destroy end end redirect_to '/users/companies' end def companies @users = User.where(:user_type => 'admin') end end <file_sep>class CreateVisitors < ActiveRecord::Migration def change create_table :visitors do |t| t.string :name t.integer :user_id t.datetime :sign_in_at t.datetime :sign_out_at t.string :company_name t.boolean :is_sign_in, :default => true t.timestamps end end end <file_sep>class UserMailer < ActionMailer::Base default :from => "<EMAIL>" def send_report(user) @user = user attachments.inline["Sign In Sheet Ending.#{Date.today}.pdf"] = File.read('Sign In Sheet Ending.pdf') mail(:to => @user.email, :body =>"Sign In Sheets of a week", :subject => "Sign In Sheets") end end <file_sep>require 'test_helper' class AdminssHelperTest < ActionView::TestCase end <file_sep>class User < ActiveRecord::Base has_many :employees has_many :visitors # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable def update_with_password(params={}) if params[:password].blank? params.delete(:password) params.delete(:password_confirmation) if params[:password_confirmation].blank? end update_attributes(params) end # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :admin_name, :user_type, :company_name, :company_domain, :avatar # attr_accessible :title, :body has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" } end <file_sep>class AdminsController < ApplicationController before_filter :authenticate_user! layout 'admin' def index end def gggg items = [] @employees_1 = Employee.all @visitors_1 = Visitor.all @employees_1.each_with_index do |emp,i| @reports = EmployeeReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND employee_id = ?' ,1.week.ago,'0', emp.id]) p "aaaaaaaaaaaaaaaaa", i @reports.map do |rep| if @reports.first == rep item = [] day = 'Sunday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.employee.name item<< nam compnam = rep.employee.user.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @visitors_1.each_with_index do |emp,i| @reports = VisitorReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND visitor_id = ?' ,1.week.ago,'0', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Sunday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.visitor.name item<< nam compnam = rep.visitor.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @employees_2 = Employee.all @employees_2.each_with_index do |emp,i| @reports = EmployeeReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND employee_id = ?' ,1.week.ago,'1', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Monday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.employee.name item<< nam compnam = rep.employee.user.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @visitors_2 = Visitor.all @visitors_2.each_with_index do |emp, i| @reports = VisitorReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND visitor_id = ?' ,1.week.ago,'1', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Monday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.visitor.name item<< nam compnam = rep.visitor.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @employees_3 = Employee.all @employees_3.each_with_index do |emp,i| @reports = EmployeeReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND employee_id = ?' ,1.week.ago,'2', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Tuesday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.employee.name item<< nam compnam = rep.employee.user.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @visitors_3 = Visitor.all @visitors_3.each_with_index do |emp,i| @reports = VisitorReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND visitor_id = ?' ,1.week.ago,'2', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Tuesday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.visitor.name item<< nam compnam = rep.visitor.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @employees_4 = Employee.all @employees_4.each_with_index do |emp,i| @reports = EmployeeReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND employee_id = ?' ,1.week.ago,'3', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Wednesday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.employee.name item<< nam compnam = rep.employee.user.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @visitors_4 = Visitor.all @visitors_4.each_with_index do |emp,i| @reports = VisitorReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND visitor_id = ?' ,1.week.ago,'3', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Wednesday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.visitor.name item<< nam compnam = rep.visitor.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @employees_5 = Employee.all @employees_5.each_with_index do |emp,i| @reports = EmployeeReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND employee_id = ?' ,1.week.ago,'4', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Thursday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.employee.name item<< nam compnam = rep.employee.user.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @visitors_5 = Visitor.all @visitors_5.each_with_index do |emp,i| @reports = VisitorReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND visitor_id = ?' ,1.week.ago,'4', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Thursday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.visitor.name item<< nam compnam = rep.visitor.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @employees_6 = Employee.all @employees_6.each_with_index do |emp,i| @reports = EmployeeReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND employee_id = ?' ,1.week.ago,'5', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Friday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.employee.name item<< nam compnam = rep.employee.user.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @visitors_6 = Visitor.all @visitors_6.each_with_index do |emp,i| @reports = VisitorReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND visitor_id = ?' ,1.week.ago,'5', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Friday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.visitor.name item<< nam compnam = rep.visitor.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @employees_7 = Employee.all @employees_7.each_with_index do |emp,i| @reports = EmployeeReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND employee_id = ?' ,1.week.ago,'6', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Saturday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.employee.name item<< nam compnam = rep.employee.user.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end @visitors_7 = Visitor.all @visitors_7.each_with_index do |emp,i| @reports = VisitorReport.find(:all, :conditions => ['created_at >= ? AND day = ? AND visitor_id = ?' ,1.week.ago,'6', emp.id]) @reports.map do |rep| if @reports.first == rep item = [] day = 'Saturday' item<< day crtdat = rep.created_at.strftime("%d/%m/%Y") item<< crtdat nam = rep.visitor.name item<< nam compnam = rep.visitor.company_name item<< compnam @reports.each do |rep_new| sigin = rep_new.sign_in_at.strftime(" %I:%M %P") item<< sigin sigout = rep_new.sign_out_at.strftime(" %I:%M %P") item<< sigout end items << item end end end cname = current_user.company_name logo = current_user.avatar.path endat = Time.now.end_of_week.strftime("%d-%m-%y") pdf = Prawn::Document.generate("Sign In Sheet Ending#{Date.today}.pdf",:page_layout => :landscape) do logopath = "#{logo}" image logopath , :width => 130, :height => 50, :style => :bold, :position => :left logopath = "#{Rails.root}/app/assets/images/logo-2-for-web.png" image logopath, :width => 197, :height => 91,:style => :bold,:at => [410,560] move_down 10 text "#{cname}", :size => 13, :style => :bold move_down 10 text "Sign In Sheet week ending:#{endat}", :size => 13 move_down 10 headers = [] headers << "Day" headers << "Date" headers << "Name" headers << "CompanyName" lngth = 0 items.each do|i| if i.length > lngth lngth = i.length end end max_lngth = lngth - 4 max_lngth = max_lngth/2 max_lngth.times { headers << "Time In" headers << "Time Out" } 4..lngth.times do|cnt| items.each do|i| if i[cnt].blank? i[cnt] = "--" end end end table(items,:cell_style => {:width => 95},:border_style => :grid,:row_colors => ["FFFFFF", "DDDDDD"],:column_widths => {0 => 75,1 =>80,2 =>80,3 =>94},:headers => true,:headers => headers) do cells.borders = [:bottom, :top, :left, :right] end move_down 15 text "This sign in sheet is powered by easysignin.com.au", :size => 13 end send_file pdf.path, :content_type => "application/pdf", :filename => "Sign In Sheet Ending#{Date.today}.pdf" UserMailer.send_report(current_user).deliver end def delete_employees unless params[:employee_name].blank? params[:employee_name].each do |emp| @e = Employee.find_by_id(emp) @e.employee_reports.each do |rep| rep.destroy end @e.destroy end end unless params[:visitor_name].blank? params[:visitor_name].each do |vis| @v = Visitor.find_by_id(vis) @v.destroy end end redirect_to "/admins/employee" end def employee @employees = Employee.all @visitors = Visitor.all end def reports # @user.user_id=current_user.id end def set_time end def set_user_time current_user.time_zone = params[:user][:time_zone] current_user.save redirect_to "/admins/reports" end end <file_sep>class CreateEmployeeReports < ActiveRecord::Migration def change create_table :employee_reports do |t| t.datetime :sign_in_at t.datetime :sign_out_at t.integer :employee_id t.string :day t.timestamps end end end <file_sep>class VisitorsController < ApplicationController before_filter :set_timezone, :only => :sign_in layout 'visitor' def new @visitor = Visitor.new end def show @visitor = Visitor.find_by_id(params[:id]) respond_to do |format| format.html do end format.js do foo = render_to_string(:partial => 'show_vis_partial', :locals => {:visitor => @visitor}).to_json render :js => "$('#show_vis_partial').html(#{foo});" end end end def search @visitors = Visitor.find(:all,:conditions => "name #{DATABASE_OPERATOR[:like_operator]} '#{params[:letter]}%'") end def create @visitor = Visitor.new(params[:visitor]) @visitor.user_id=current_user.id if @visitor.save redirect_to visitor_path(@visitor) else render :new end end def index @visitors = Visitor.all end def destroy @visitor = Visitor.find(params[:id]) @visitor.destroy redirect_to visitors_path end def sign_in @visitor = Visitor.find_by_id(params[:id]) if @visitor.is_sign_in @visitor.update_attribute(:is_sign_in , false) @report= @visitor.visitor_reports.last @report.sign_out_at = DateTime.now.in_time_zone @report.save else @visitor.update_attribute(:is_sign_in , true) @report = VisitorReport.new @report.visitor_id = @visitor.id @report.sign_in_at = DateTime.now.in_time_zone @report.day = Time.now.utc.wday @report.save end redirect_to visitor_path(@visitor) end def sign_out_admin sign_out(current_user) respond_to do |format| format.js do foo = render_to_string(:partial => '/layouts/logout_partial').to_json poo = render_to_string(:partial => '/layouts/vis_ajax_partial').to_json render :js => "$('#logout_div').html(#{foo});$('#vis_ajax_div').html(#{poo});" end end end def set_timezone visitor = Visitor.find_by_id(params[:id]) # current_user.time_zone #=> 'Central Time (US & Canada)' Time.zone = visitor.user.time_zone || 'Central Time (US & Canada)' end end <file_sep>class VisitorReport < ActiveRecord::Base # attr_accessible :title, :body belongs_to :visitor attr_accessible :sign_in_at, :sign_out_at,:visitor_id,:day end <file_sep>class CreateVisitorReports < ActiveRecord::Migration def change create_table :visitor_reports do |t| t.datetime :sign_in_at t.datetime :sign_out_at t.integer :visitor_id t.string :day t.timestamps end end end <file_sep># Load the rails application require File.expand_path('../application', __FILE__) #require "prawn" ActionMailer::Base.delivery_method = :smtp # Initialize the rails application EasySignin::Application.initialize! <file_sep>class EmployeeReport < ActiveRecord::Base belongs_to :employee attr_accessible :sign_in_at, :sign_out_at,:employee_id,:day end <file_sep>class Employee < ActiveRecord::Base belongs_to :user has_many :employee_reports attr_accessible :user_id, :name, :sign_in_at, :sign_out_at, :pin_code, :is_sign_in end <file_sep>class Visitor < ActiveRecord::Base attr_accessible :name, :company_name,:user_id, :sign_in_at, :sign_out_at, :is_sign_in has_many :visitor_reports belongs_to :user end
9ab290ebb0b8409fdf13d54858722fec25b3cfac
[ "Ruby" ]
16
Ruby
danielhollands/easysignin
74ba2ff71316e25ded9ba7c220b702359531bf67
a5839b9ed845abf5219c2d0e48d7a6be3ebbffc3
refs/heads/master
<repo_name>rtink/devcampportfolio<file_sep>/app/controllers/portfolios_controller.rb class PortfoliosController < ApplicationController def index @portfolio_items = Portfolio.all end def new @portfolio_item = Portfolio.new end def show @portfolio_item = Portfolio.find(params[:id]) end def create @portfolio_item = Portfolio.new(params.require(:portfolio).permit(:title, :subtitle, :body)) if @portfolio_item.save flash[:success] = "Your portfolio item is now live!" redirect_to portfolios_path(@portfolio_item) else render 'new' end end def edit @portfolio_item = Portfolio.find(params[:id]) end def update @portfolio_item = Portfolio.find(params[:id]) if @portfolio_item.update(params.require(:portfolio).permit(:title, :subtitle, :body)) flash[:warning] = "The record was updated" redirect_to portfolios_path(@portfolio_item) else render 'edit' end end def destroy @portfolio_item = Portfolio.find(params[:id]) @portfolio_item.destroy flash[:danger] = "Record was removed" redirect_to portfolios_url end end <file_sep>/db/seeds.rb 10.times do |blog| Blog.create!( title: "My Blog Post #{blog}", body: "Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead." ) end puts "10 blog posts created" 5.times do |skill| Skill.create!( title: "Rails #{skill}", percent_utilized: 75 ) end puts "5 skills created" 9.times do |portfolio_item| Portfolio.create!( title: "Portfolio title: #{portfolio_item}", subtitle: "My great service", body: "De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby.", main_image: "http://via.placeholder.com/600x400", thumb_image: "http://via.placeholder.com/350x200", ) end puts "9 portfolio items created"
32b129add67a6645040310c16fefc207f72f7065
[ "Ruby" ]
2
Ruby
rtink/devcampportfolio
01266119261b205d6faf9c6bbf9f8e4efb81d00f
b8c79c187064b0a6634f1a1e80273e8d4cbbf552
refs/heads/master
<file_sep>// // WorldPopulationModel.swift // MindX // // Created by <NAME> on 9/9/21. // import Foundation class WorldPopulationModel: RequestModel { // MARK: - Properties override var path: String { return "/worldpopulation" } } <file_sep>// // Configs.swift // MindX // // Created by <NAME> on 9/3/21. // import Foundation struct Configs { struct Network { public static let baseUrl = "https://world-population.p.rapidapi.com/" } struct Constant { public static let apiHost = "world-population.p.rapidapi.com" public static let apiKey = "ed74e2be46msha0be35e5f345febp17ac10jsn4262a33cbe07" } } <file_sep>// // ServiceManager.swift // MindX // // Created by <NAME> on 9/9/21. // import Foundation class ServiceManager { // MARK: - Properties static let shared: ServiceManager = ServiceManager() var baseURL: String = Configs.Network.baseUrl } // MARK: - Public Functions extension ServiceManager { func sendRequest<T: Codable>(requestModel: RequestModel, completion: @escaping (Swift.Result<T, ErrorModel>) -> Void) { let request = NSMutableURLRequest(url: NSURL(string: baseURL + requestModel.path)! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = requestModel.method.rawValue request.allHTTPHeaderFields = requestModel.headers let session = URLSession.shared let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, _, error) -> Void in if error != nil { completion(.failure(ErrorModel(error?.localizedDescription))) } else { let decoder = JSONDecoder() guard let data = data, let parsedResponse = try? decoder.decode(T.self, from: data) else { return } completion(.success(parsedResponse)) } }) dataTask.resume() } } <file_sep>// // AllCountryModel.swift // MindX // // Created by <NAME> on 9/9/21. // import Foundation class AllCountryModel: RequestModel { // MARK: - Properties override var path: String { return "/allcountriesname" } } <file_sep>// // ResponseModel.swift // MindX // // Created by <NAME> on 9/9/21. // import Foundation struct ResponseModel<T: Codable>: Codable { // MARK: - Properties var isSuccess: Bool var message: String? var error: ErrorModel { return ErrorModel(message) } // var rawData: Data? var data: T? // var request: RequestModel? init(isSuccess: Bool, message: String?) { self.isSuccess = isSuccess self.message = message } public init(from decoder: Decoder) throws { let keyedContainer = try decoder.container(keyedBy: CodingKeys.self) data = try? keyedContainer.decode(T.self, forKey: CodingKeys.data) isSuccess = (try? keyedContainer.decode(Bool.self, forKey: CodingKeys.isSuccess)) ?? false } } extension ResponseModel { private enum CodingKeys: String, CodingKey { case isSuccess case message case data } } class ErrorModel: Error { let message: String? init(_ message: String?) { self.message = message } } extension ErrorModel { class func generalError() -> ErrorModel { return ErrorModel("Error") } } <file_sep>// // AllCountryService.swift // MindX // // Created by <NAME> on 9/9/21. // import Foundation class AllCountryService { static func getAll(complete: @escaping ((Result<BaseModel<Country>, ErrorModel>) -> Void)) { ServiceManager.shared.sendRequest(requestModel: AllCountryModel(), completion: complete) } } class WorldPopulationService { static func getInfo(complete: @escaping ((Result<BaseModel<WorldPopulation>, ErrorModel>) -> Void)) { ServiceManager.shared.sendRequest(requestModel: WorldPopulationModel(), completion: complete) } } class BaseModel<T: Codable>: Codable { let body: T init(body: T) { self.body = body } } struct Country: Codable { var countries: [String] = [] } struct WorldPopulation: Codable { let world_population: Double let total_countries: Double } <file_sep>// // ViewController.swift // MindX // // Created by <NAME> on 9/3/21. // import UIKit class ViewController: UIViewController { @IBOutlet var searchBar: UISearchBar! @IBOutlet var tableView: UITableView! @IBOutlet var worldPopulationLabel: UILabel! @IBOutlet var totalCountrieslabel: UILabel! private var allCountry: Country = Country(countries: []) { didSet { searchName = allCountry.countries } } private var searchName: [String] = [] { didSet { DispatchQueue.main.async { self.tableView.reloadData() } } } private var worldPopulation: Double = 0 { didSet { DispatchQueue.main.async { self.worldPopulationLabel.text = "\(self.worldPopulation)" } } } private var numCountries: Double = 0 { didSet { DispatchQueue.main.async { self.totalCountrieslabel.text = "\(self.numCountries)" } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupTableView() searchBar.delegate = self AllCountryService.getAll { result in switch result { case let .success(data): self.allCountry = data.body case let .failure(error): print("error: \(error.message)") } } WorldPopulationService.getInfo { result in switch result { case let .success(data): self.worldPopulation = data.body.world_population self.numCountries = data.body.total_countries case let .failure(error): print("error: \(error.message)") } } } private func setupTableView() { tableView.delegate = self tableView.dataSource = self } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = DetailViewController() vc.countryDetail = CoutryDetail(name: allCountry.countries[indexPath.row]) navigationController?.pushViewController(vc, animated: true) } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchName.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = searchName[indexPath.row] return cell } } extension ViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text == "" { searchName = allCountry.countries return } searchName = allCountry.countries.filter { return $0.lowercased().contains("\(searchBar.text?.lowercased() ?? "")") } } } <file_sep>// // DetailViewController.swift // MindX // // Created by <NAME> on 9/9/21. // import UIKit class DetailViewController: UIViewController { @IBOutlet var countryName: UILabel! @IBOutlet var populationLlabel: UILabel! var countryDetail: CoutryDetail? { didSet { countryName.text = countryDetail?.name } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } struct CoutryDetail { let name: String }
545d667159372880ec07e68fc95c030db763ddde
[ "Swift" ]
8
Swift
HuongPlc/mindX-gen4
809b7743e5fa8257adfadfac26401a979f4ba19d
f9eb1c43042cef1150dfb60539117867019f9176
refs/heads/master
<repo_name>LiJinQ/book_manage<file_sep>/src/main/java/com/ambow/vo/ReaderBookVo.java package com.ambow.vo; import com.ambow.pojo.Reader; import com.ambow.pojo.ReaderBook; public class ReaderBookVo { private ReaderBook readerBook; private Reader reader; public ReaderBookVo() { super(); // TODO Auto-generated constructor stub } public ReaderBookVo(ReaderBook readerBook, Reader reader) { super(); this.readerBook = readerBook; this.reader = reader; } @Override public String toString() { return "ReaderBookVo [readerBook=" + readerBook + ", reader=" + reader + "]"; } public ReaderBook getReaderBook() { return readerBook; } public void setReaderBook(ReaderBook readerBook) { this.readerBook = readerBook; } public Reader getReader() { return reader; } public void setReader(Reader reader) { this.reader = reader; } } <file_sep>/src/main/java/com/ambow/sercice/EmpService.java package com.ambow.sercice; import java.util.List; import com.ambow.pojo.Emp; import com.ambow.vo.Pager; public interface EmpService { public boolean login(Emp emp); public int newEmp(Emp emp); public int updateEmp(Emp emp); public int deleteEmpById(int id); public Emp getEmpById(int id); public List<Emp> getAllEmp(); public Emp getEmpByUsername(String username); public Pager<Emp> getEmpPager(int pageNum); public Pager<Emp> getEmpFindPager(int pageNum,String sth); } <file_sep>/src/main/java/com/ambow/dao/EmpDao.java package com.ambow.dao; import java.util.Date; import java.util.List; import org.apache.ibatis.annotations.Param; import com.ambow.pojo.Emp; import com.ambow.vo.Pager; public interface EmpDao { public int newEmp(Emp emp); /** * �޸�Ա����Ϣ * @param emp */ public int updateEmp(Emp emp); /** * ɾ��Ա����Ϣ * @param id */ public int deleteEmpById(int id); /** * ����id�����û������в�ѯ * @param id * @param username * @return */ public Emp getEmpByIdOrUsername(@Param("id")int id,@Param("username")String username); /** * �鿴Ա����Ϣ������Ա��������Ա�����͡���ְʱ��ɸѡԱ����Ϣ * @param name * @param roleId * @param entryTime * @return */ public List<Emp> getEmp(@Param("name")String name,@Param("roleId")int roleId,@Param("entryTime")Date entryTime); public int getTotalRecord(); public int getFindTotalRecord(String sth); public List<Emp> getEmpPager(Pager<Emp> pager); public List<Emp> getEmpFind(@Param("pager")Pager<Emp> pager,@Param("sth")String sth); } <file_sep>/src/main/java/com/ambow/service/impl/ReaderBookServiceImpl.java package com.ambow.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ambow.dao.BookDao; import com.ambow.dao.ReaderBookDao; import com.ambow.dao.ReaderDao; import com.ambow.pojo.Book; import com.ambow.pojo.Reader; import com.ambow.pojo.ReaderBook; import com.ambow.sercice.ReaderBookService; import com.ambow.util.TimeFormat; import com.ambow.vo.Pager; import com.ambow.vo.ReaderBookVo; @Service public class ReaderBookServiceImpl implements ReaderBookService{ @Autowired private ReaderBookDao rbd; @Autowired private BookDao bd; @Autowired private ReaderDao rd; private boolean isPrice(int readerId) { List<ReaderBook> readerBooks = rbd.getReaderBookByReaderId(readerId); for(ReaderBook rb:readerBooks) { if(rb.getBackDate()==null) { return true; } } return false; } @Override public int borrowBook(ReaderBook readerBook) { // TODO Auto-generated method stub //传入的值有 读者id,书籍id // Book book = bd.getBookById(readerBook.getBookId()); if(book.getStock()-1<0) { return 1; } if(isPrice(readerBook.getReaderId())) { return 2; } book.setStock(book.getStock()-1); readerBook.setStartDate(rbd.getNow()); if(rbd.newReaderBook(readerBook)<=0) { return 3; } bd.updateBook(book); return 0; } @Override public int backBook(int readerBookId) { // TODO Auto-generated method stub ReaderBook readerBook = rbd.getReaderBookById(readerBookId); readerBook.setBackDate(new Date()); return rbd.updateReaderBook(readerBook); } @Override public ReaderBook getBackPrice(int id, int lost, int damaged) { // TODO Auto-generated method stub ReaderBook readerBook = rbd.getReaderBookById(id); Book book = bd.getBookById(readerBook.getBookId()); if(lost==1||damaged==1) { readerBook.setPrice(book.getPrice()); }else { int days = TimeFormat.getDays(new Date(), readerBook.getStartDate())-book.getBorrowTime(); float price = 0; if(days>0) { price = (float) (book.getPrice()*days*0.01); } readerBook.setPrice(price); } rbd.updateReaderBook(readerBook); return readerBook; } @Override public Pager<ReaderBook> getReaderBookByReaderId(int pageNum, int readerId) { // TODO Auto-generated method stub Pager<ReaderBook> pager = new Pager<ReaderBook>(pageNum, 10, rbd.getTotalRecord(readerId, 0)); List<ReaderBook> lists = rbd.getReaderBookPagerByReaderIdOrBookId(pager, readerId, 0); pager.setList(lists); return pager; } @Override public Pager<ReaderBook> getReaderBookByBookId(int pageNum, int bookId) { // TODO Auto-generated method stub Pager<ReaderBook> pager = new Pager<ReaderBook>(pageNum, 10, rbd.getTotalRecord(0, bookId)); List<ReaderBook> lists = rbd.getReaderBookPagerByReaderIdOrBookId(pager, 0, bookId); pager.setList(lists); return pager; } @Override public Pager<ReaderBook> getAllReaderBook(int pageNum) { // TODO Auto-generated method stub Pager<ReaderBook> pager = new Pager<ReaderBook>(pageNum, 10, rbd.getTotalRecord(0,0)); List<ReaderBook> lists = rbd.getReaderBookPagerByReaderIdOrBookId(pager, 0, 0); pager.setList(lists); return pager; } @Override public ReaderBook getReaderBookById(int id) { // TODO Auto-generated method stub return rbd.getReaderBookById(id); } @Override public List<ReaderBookVo> getReaderBookByBookId2(int bookId) { // TODO Auto-generated method stub List<ReaderBook> rbList = rbd.getReaderBookByBookId(bookId); List<ReaderBookVo> list = new ArrayList<ReaderBookVo>(); for(ReaderBook rb:rbList) { Reader r = rd.getReaderById(rb.getReaderId()); ReaderBookVo rbv = new ReaderBookVo(rb, r); list.add(rbv); } return list; } } <file_sep>/src/main/java/com/ambow/sercice/MenuService.java package com.ambow.sercice; import java.util.List; import com.ambow.pojo.Menu; public interface MenuService { public List<Menu> getMenuByRoleId(int roleId); } <file_sep>/src/main/java/com/ambow/dao/MenuDao.java package com.ambow.dao; import java.util.List; import com.ambow.pojo.Menu; public interface MenuDao { public List<Menu> getMenuByRoleId(int roleId); } <file_sep>/src/test/java/com/ambow/test/StatusTest.java package com.ambow.test; import java.util.Date; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.ambow.dao.StatusDao; import com.ambow.pojo.Status; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations= {"classpath:spring-db.xml","classpath:spring-mvc.xml","classpath:spring.xml"}) public class StatusTest { @Autowired StatusDao statusdao; @Test public void testupdateStatus() { statusdao.newStatus(new Status(2,2,2,2,2,new Date())); } @Test public void testgetStatusByEbbId() { System.out.println(statusdao.getStatusByEbbId(2)); } } <file_sep>/src/main/java/com/ambow/sercice/ReaderService.java package com.ambow.sercice; import java.util.List; import java.util.Map; import com.ambow.pojo.Reader; import com.ambow.vo.BookBeBorrow; import com.ambow.vo.Pager; public interface ReaderService { public int newReader(Reader reader); public int updateReader(Reader reader); public int deleteReaderById(int id); public Reader getReaderById(int id); public List<Reader> getAllReader(); public List<Reader> getReaderByName(String name); public List<Reader> getReaderSearch(String content); public List<Reader> getReaderConBorrow(); public Pager<Reader> getAllReader(int pageNum); public Pager<Reader> getReaderByName(int pageNum,String name); public Pager<Reader> getReaderSearch(int pageNum,String content); public Map<String,String> getSexProportion(); } <file_sep>/src/test/java/com/ambow/test/BookTestServiceTest.java package com.ambow.test; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.ambow.sercice.BookService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations= {"classpath:spring-db.xml","classpath:spring-mvc.xml","classpath:spring.xml"}) public class BookTestServiceTest { @Autowired BookService bs; @Test public void testNewBook() { fail("Not yet implemented"); } @Test public void testUpdateBook() { fail("Not yet implemented"); } @Test public void testDeleteBookById() { fail("Not yet implemented"); } @Test public void testGetBookById() { fail("Not yet implemented"); } @Test public void testGetAllBook() { fail("Not yet implemented"); } @Test public void testGetBookByTypeId() { fail("Not yet implemented"); } @Test public void testGetBookByName() { fail("Not yet implemented"); } @Test public void testGetBookBySearch() { System.out.println(bs.getBookBySearch("201")); } } <file_sep>/src/main/java/com/ambow/controller/ReaderBookController.java package com.ambow.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ambow.pojo.Reader; import com.ambow.pojo.ReaderBook; import com.ambow.sercice.ReaderBookService; import com.ambow.vo.Pager; import com.ambow.vo.PagerVo; import com.ambow.vo.ReaderBookVo; @Controller @RequestMapping("/readerBook") public class ReaderBookController { @Autowired private ReaderBookService rbs; /** * readerBook封装的值: * 1、reader_id * 2、book_id * @param readerBook * @return * 0:成功 * 1:库存不足 * 2:读者有欠款项 * 3:插入失败 */ @RequestMapping(value="/borrowBook.do",method = RequestMethod.POST) @ResponseBody public int borrowBook(@RequestBody ReaderBook readerBook) { return rbs.borrowBook(readerBook); } @RequestMapping(value = "/backBook.do",method = RequestMethod.POST) @ResponseBody public int backBook(@RequestBody int readerBookId) { return rbs.backBook(readerBookId); } /** * @param id 主键 * @param lost 丢失:1 * @param damaged 损坏:1 * @return 计算价格后的实体 */ @RequestMapping(value = "/getBackPrice.do",method = RequestMethod.POST) @ResponseBody public ReaderBook getBackPrice(@RequestBody PagerVo pv) { return rbs.getBackPrice(pv.getReaderBookId(), pv.getLost(), pv.getDamaged()); } @RequestMapping(value="getReaderBookByReaderId.do",method = RequestMethod.POST) @ResponseBody public Pager<ReaderBook> getReaderBookByReaderId(@RequestBody PagerVo pv){ return rbs.getReaderBookByReaderId(pv.getPageNum(), pv.getReaderId()); } @RequestMapping(value="getReaderBookByBookId.do",method = RequestMethod.POST) @ResponseBody public Pager<ReaderBook> getReaderBookByBookId(@RequestBody PagerVo pv){ return rbs.getReaderBookByBookId(pv.getPageNum(), pv.getBookId()); } @RequestMapping(value="getAllReaderBook.do",method = RequestMethod.POST) @ResponseBody public Pager<ReaderBook> getAllReaderBook(@RequestBody PagerVo pv){ return rbs.getAllReaderBook(pv.getPageNum()); } @RequestMapping(value="getReaderBookById.do",method = RequestMethod.POST) @ResponseBody public ReaderBook getReaderBookById(@RequestBody int id) { return rbs.getReaderBookById(id); } @RequestMapping(value="getReaderBookByBookId2.do",method = RequestMethod.POST) @ResponseBody public List<ReaderBookVo> getReaderBookByBookId2(@RequestBody int bookId) { return rbs.getReaderBookByBookId2(bookId); } } <file_sep>/src/main/java/com/ambow/sercice/ReaderBookService.java package com.ambow.sercice; import java.util.List; import com.ambow.pojo.Reader; import com.ambow.pojo.ReaderBook; import com.ambow.vo.Pager; import com.ambow.vo.ReaderBookVo; public interface ReaderBookService { /** * 0:成功 * 1:库存不足 * 2:读者有欠款项 * 3:插入失败 * @param readerBook * @return */ public int borrowBook(ReaderBook readerBook); public int backBook(int readerBookId); /** * @param id 主键 * @param lost 1:已丢失 * @param damaged 2:已损坏 * @return */ public ReaderBook getBackPrice(int id,int lost,int damaged); public Pager<ReaderBook> getReaderBookByReaderId(int pageNum,int readerId); public Pager<ReaderBook> getReaderBookByBookId(int pageNum,int bookId); public Pager<ReaderBook> getAllReaderBook(int pageNum); public ReaderBook getReaderBookById(int id); public List<ReaderBookVo> getReaderBookByBookId2(int bookId); } <file_sep>/src/main/java/com/ambow/pojo/ReaderBook.java package com.ambow.pojo; import java.util.Date; public class ReaderBook { private int id; private int readerId; private int bookId; private Date startDate; private Date backDate; private float price; public ReaderBook() { super(); // TODO Auto-generated constructor stub } public ReaderBook(int id, int readerId, int bookId, Date startDate, Date backDate, float price) { super(); this.id = id; this.readerId = readerId; this.bookId = bookId; this.startDate = startDate; this.backDate = backDate; this.price = price; } @Override public String toString() { return "ReaderBook [id=" + id + ", readerId=" + readerId + ", bookId=" + bookId + ", startDate=" + startDate + ", backDate=" + backDate + ", price=" + price + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getReaderId() { return readerId; } public void setReaderId(int readerId) { this.readerId = readerId; } public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getBackDate() { return backDate; } public void setBackDate(Date backDate) { this.backDate = backDate; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } }<file_sep>/src/main/java/com/ambow/pojo/Status.java package com.ambow.pojo; import java.util.Date; public class Status { private int id; private int ebbId; private int empId; private int status; private int empLevel; private Date updateDate; public Status() { super(); // TODO Auto-generated constructor stub } public Status(int id, int ebbId, int empId, int status, int empLevel, Date updateDate) { super(); this.id = id; this.ebbId = ebbId; this.empId = empId; this.status = status; this.empLevel = empLevel; this.updateDate = updateDate; } @Override public String toString() { return "Status [id=" + id + ", ebbId=" + ebbId + ", empId=" + empId + ", status=" + status + ", empLevel=" + empLevel + ", updateDate=" + updateDate + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getEbbId() { return ebbId; } public void setEbbId(int ebbId) { this.ebbId = ebbId; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getEmpLevel() { return empLevel; } public void setEmpLevel(int empLevel) { this.empLevel = empLevel; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } }<file_sep>/src/main/java/com/ambow/dao/EmpBuyBookDao.java package com.ambow.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.ambow.pojo.EmpBuyBook; import com.ambow.vo.Pager; public interface EmpBuyBookDao { public int newEmpBuyBook(EmpBuyBook empBuyBook); public EmpBuyBook getEmpBuyBookById(int id); public int getTotalRecord(); public List<EmpBuyBook> getEmpBuyBookPager(@Param("pager")Pager<EmpBuyBook> pager,@Param("bookId")int bookId); } <file_sep>/src/main/java/com/ambow/service/impl/BookTypeServiceImpl.java package com.ambow.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ambow.dao.BookDao; import com.ambow.dao.BookTypeDao; import com.ambow.pojo.Book; import com.ambow.pojo.BookType; import com.ambow.sercice.BookTypeService; import com.ambow.vo.Pager; @Service public class BookTypeServiceImpl implements BookTypeService { @Autowired private BookTypeDao btd; @Autowired private BookDao bd; @Override public int newBookType(BookType bookType) { return btd.newBookType(bookType); } @Override public int deleteBookTypeById(int id) { List<Book> list = bd.getBookByTypeIdOrName(id, null); if(!list.isEmpty()) { return 0; } return btd.deleteBookTypeById(id); } @Override public int updateBookType(BookType bookType) { return btd.updateBookType(bookType); } @Override public List<BookType> getAllBookType() { return btd.getAllBookType(); } @Override public BookType getBookTypeByName(String name) { return btd.getBookTypeByIdOrName(0, name); } @Override public Pager<BookType> getBookTypePager(int pageNum) { int totalRecord = btd.getTotalRecord(); Pager<BookType> pager = new Pager<BookType>(pageNum, 10, totalRecord); pager.setList(btd.getBookTypePager(pager)); return pager; } @Override public Pager<BookType> getBookTypeFindPager(int pageNum, String sth) { sth = "%" + sth + "%"; int totalRecord = btd.getFindTotalRecord(sth); Pager<BookType> pager = new Pager<BookType>(pageNum, 10, totalRecord); pager.setList(btd.getBookTypeFind(pager, sth)); return pager; } } <file_sep>/src/main/java/com/ambow/service/impl/EmpBuyBookServiceImpl.java package com.ambow.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ambow.dao.BookDao; import com.ambow.dao.EmpBuyBookDao; import com.ambow.dao.StatusDao; import com.ambow.pojo.Book; import com.ambow.pojo.EmpBuyBook; import com.ambow.pojo.Status; import com.ambow.sercice.EmpBuyBookService; import com.ambow.vo.Pager; import com.ambow.vo.PagerVo; import com.ambow.vo.StatusVo; @Service public class EmpBuyBookServiceImpl implements EmpBuyBookService{ @Autowired private EmpBuyBookDao ebbd; @Autowired private StatusDao sd; @Autowired private BookDao bd; @Override public int applyBuy(EmpBuyBook ebb) { // TODO Auto-generated method stub Date now = new Date(); ebb.setBuyDate(now); if(ebbd.newEmpBuyBook(ebb)<=0) { return 0; } Status status = new Status(0, ebb.getId(), ebb.getEmpId(), 1, 1, now); return sd.newStatus(status); } @Override public int examine(Status status) { // TODO Auto-generated method stub Status ss = sd.getStatusById(status.getId()); ss.setStatus(status.getStatus()); ss.setUpdateDate(new Date()); sd.updateStatus(ss); if(status.getStatus()==1) { Status s1 = new Status(0, ss.getEbbId(), ss.getEmpId(), 1, ss.getEmpLevel()+1, new Date()); return sd.newStatus(s1); } return 1; } @Override public Pager<StatusVo> getStatusNotPass(PagerVo pv) { // TODO Auto-generated method stub int empLevel = 1; if(pv.getRootId()==2) { empLevel = 3; }else if(pv.getRootId()==2) { empLevel = 2; } int totalRecord = sd.getTotalRecord(empLevel, 0); Pager<Status> pager = new Pager<Status>(pv.getPageNum(), 10,totalRecord); List<Status> list = sd.getStatusPager(pager, empLevel, 0); Pager<StatusVo> pager1 = new Pager<StatusVo>(pv.getPageNum(), 10, totalRecord); List<StatusVo> list1 = new ArrayList<StatusVo>(); for(Status s:list) { EmpBuyBook ebb = ebbd.getEmpBuyBookById(s.getEbbId()); Book book = bd.getBookById(ebb.getBookId()); StatusVo sv = new StatusVo(s, book); list1.add(sv); } pager1.setList(list1); return pager1; } @Override public Pager<StatusVo> getStatusPass(PagerVo pv) { // TODO Auto-generated method stub int empLevel = 1; if(pv.getRootId()==2) { empLevel = 3; }else if(pv.getRootId()==2) { empLevel = 2; } int totalRecord = sd.getTotalRecord(empLevel, 0); Pager<Status> pager = new Pager<Status>(pv.getPageNum(), 10,totalRecord); List<Status> list = sd.getStatusPager(pager, empLevel, 1); Pager<StatusVo> pager1 = new Pager<StatusVo>(pv.getPageNum(), 10, totalRecord); List<StatusVo> list1 = new ArrayList<StatusVo>(); for(Status s:list) { EmpBuyBook ebb = ebbd.getEmpBuyBookById(s.getEbbId()); Book book = bd.getBookById(ebb.getBookId()); StatusVo sv = new StatusVo(s, book); list1.add(sv); } pager1.setList(list1); return pager1; } @Override public Pager<EmpBuyBook> getEBB(PagerVo pv) { // TODO Auto-generated method stub int totalRecord = ebbd.getTotalRecord(); Pager<EmpBuyBook> pager = new Pager<EmpBuyBook>(pv.getPageNum(), 10, totalRecord); List<EmpBuyBook> list = ebbd.getEmpBuyBookPager(pager,pv.getBookId()); pager.setList(list); return pager; } } <file_sep>/src/test/java/com/ambow/test/UtilTest.java package com.ambow.test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.ambow.util.TimeFormat; public class UtilTest { @Test public void test() { System.out.println(TimeFormat.getRandomNumber()); } } <file_sep>/src/test/java/com/ambow/test/RoleTest.java package com.ambow.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.ambow.dao.RoleDao; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations= {"classpath:spring-db.xml","classpath:spring-mvc.xml","classpath:spring.xml"}) public class RoleTest { @Autowired private RoleDao roledao; @Test public void testgetRoleById() { System.out.println(roledao.getRoleById(2)); } } <file_sep>/src/main/java/com/ambow/sercice/BookService.java package com.ambow.sercice; import java.util.List; import com.ambow.pojo.Book; import com.ambow.vo.BookBeBorrow; import com.ambow.vo.Pager; public interface BookService { public int newBook(Book book); public int updateBook(Book book); public int deleteBookById(int id); public Book getBookById(int id); public List<Book> getAllBook(); public List<Book> getBookByTypeId(int typeId); public List<Book> getBookByName(String name); public List<Book> getBookBySearch(String content); public Pager<Book> getAllBookPager(int pageNum); public Pager<Book> getBookByName(int pageNum, String name); public Pager<Book> getBookByTypeId(int pageNum, int typeId); public Pager<Book> getBookBySearch(int pageNum, String content); public List<BookBeBorrow> getBookBeBorrow(); } <file_sep>/src/main/java/com/ambow/sercice/EmpBuyBookService.java package com.ambow.sercice; import com.ambow.pojo.EmpBuyBook; import com.ambow.pojo.Status; import com.ambow.vo.Pager; import com.ambow.vo.PagerVo; import com.ambow.vo.StatusVo; public interface EmpBuyBookService { /** * 传入empId * bookId * @param ebb * @return */ public int applyBuy(EmpBuyBook ebb); /** * id * status * @param status * @return */ public int examine(Status status); public Pager<StatusVo> getStatusNotPass(PagerVo pv); public Pager<StatusVo> getStatusPass(PagerVo pv); public Pager<EmpBuyBook> getEBB(PagerVo pv); } <file_sep>/target/m2e-wtp/web-resources/META-INF/maven/com.ambow/bookManage/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ambow</groupId> <artifactId>bookManage</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>bookManage Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- <spring.version>3.2.16.RELEASE</spring.version> --> <spring.version>4.1.4.RELEASE</spring.version> </properties> <dependencies> <!-- Spring相关 --> <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- 测试相关 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- mybatis相关 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- 其它 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.17</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.8</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.22</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency> </dependencies> <build> <finalName>bookManage</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> </dependencies> <configuration> <configurationFile>${basedir}/src/test/java/generatorCfg.xml</configurationFile> <overwrite>true</overwrite> </configuration> </plugin> <!-- define the project compile level --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> <file_sep>/src/main/java/com/ambow/service/impl/MenuServiceImpl.java package com.ambow.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ambow.dao.MenuDao; import com.ambow.pojo.Menu; import com.ambow.sercice.MenuService; @Service public class MenuServiceImpl implements MenuService { @Autowired private MenuDao md; @Override public List<Menu> getMenuByRoleId(int roleId) { // TODO Auto-generated method stub return md.getMenuByRoleId(roleId); } }
c9467672031b2a3a187ad6fec44b114499c29be0
[ "Java", "Maven POM" ]
22
Java
LiJinQ/book_manage
3666426b023d0aba1a900e8b8b1fd9ad2b2412f4
84a67e5ac4beafa354ea685bd465e6dc43a34862
refs/heads/master
<file_sep>#!/bin/zsh rgName="az-203-storage" location="UK South" accountName="domocdb" databaseName="domosql" ### RSG Create az group create -n $rgName -l $location ### Cosmos DB account #accepted values: BoundedStaleness, ConsistentPrefix, Eventual, Session, Strong az cosmosdb create -n $accountName -g $rgName --default-consistency-level Strong --kind GlobalDocumentDB --locations "East US=0" #--enable-multiple-write-locations to enable data sync globally, --enable-automatic-failover # List CosmosDB account Keys az cosmosdb list-keys -n $accountName -g $rgName # List CosmosDB Connection Strings az cosmosdb list-connection-strings -n $accountName -g $rgName # Show CosmosDB primary endpoint az cosmosdb show -n $accountName -g $rgName --query "documentEndpoint" ### Cosmod DB Database. az cosmosdb database create -n $accountName -g $rgName --db-name $databaseName ### Cosmos DB Collection az cosmosdb collection create -n $accountName -g $rgName --db-name $databaseName --collection-name "CollectionDOMO"<file_sep>#!/bin/zsh rgName="az-203-function" location="UK South" srtAccName="domofunc" qName="domoq" content=`cat /Users/donmorris/Documents/family.json` fName="domofunc" ### RSG Create az group create -n $rgName -l $location ### Azure function checks a storage Q and writes those messages to a storage table. ### Create storage account az storage account create -n $srtAccName -g $rgName -l $location --sku Standard_LRS --kind StorageV2 --access-tier Hot ### Get Connection String conString=`az storage account show-connection-string -n $srtAccName --query "connectionString"` ### Create Storage Queue az storage queue create --name $qName --account-name $srtAccName --connection-string $conString ### Add message to Queue az storage message put --account-name $srtAccName --connection-string $conString --queue-name $qName --content $content ### Create Function App az functionapp create -n $fName -g $rgName --storage-account=$srtAccName --disable-app-insights --os-type Linux --runtime python --runtime-version 3.7<file_sep>#!/bin/zsh ### Logic App to scan an Azure storage account for blobs that need to be archived and sends a message to Queue. rgName="az-203-logic" location="UK South" srtAccName="domologicsa" containerName="logicblob" qName="domoq" ### RSG Create az group create -n $rgName -l $location ### Storage Account Create az storage account create -n $srtAccName -g $rgName -l $location --sku Standard_LRS ### Get Connection String conString=`az storage account show-connection-string -n $srtAccName --query "connectionString"` ### Blob storage create container az storage container create --account-name $srtAccName -g $rgName -n $containerName --connection-string $conString ### Upload Blob to Container az storage blob upload --container-name $containerName --file /Users/donmorris/Documents/family.json --name family.json --connection-string $conString ### Create Storage Queue az storage queue create --name $qName --account-name $srtAccName --connection-string $conString ### Check messages in a storage queue az storage message peek --queue-name $qName --account-name $srtAccName --connection-string $conString --num-messages 10 <file_sep>#!/bin/zsh rgName="az-203-security" location="UK South" srtAccName="domoaz203sec" spName="DoMoAZSP" ### RSG Create az group create -n $rgName -l $location ### Storage Account Create az storage account create -n $srtAccName -g $rgName -l $location --sku Standard_LRS ### Create Service Principle. az ad sp create-for-rbac --name $spName ### Get App ID: appId=`az ad sp list --display-name $spName --query "[0].appId" --output tsv` ### Show SP az ad sp show --id $appId ### Show role assignments for the SP az role assignment list --assignee $appId ### Define the Roles. az role definition list ### Assign a role to a SP az role assignment create --role "Website Contributor" --assignee $appId # Use --scope to define specific scopes to resource IDs. ### az <resource> show --query id. ### Reset SP credential az ad sp credential reset --name $appId ### Create Key Vault. az webapp identity assign --name myApp --resource-group myResourceGroup - Note the Principle ID. az keyvault set-policy --name myKeyVault --object-id <PrincipalId> --secret-permissions get list <file_sep>#!/bin/zsh rgName="az-203-storage" location="UK South" srtAccName="domoaz203sa" tblName="domoaztbl" policyName="raud" containerName="domocontainer" ### RSG Create az group create -n $rgName -l $location ### Storage Account Create az storage account create -n $srtAccName -g $rgName -l $location --sku Standard_LRS ### Get Connection String conString=`az storage account show-connection-string -n $srtAccName --query "connectionString"` ### Get Account Key accKey=`az storage account keys list -n $srtAccName --query "[0].value"` ### Generate SAS Key on a blob az storage blob generate-sas --account-name $srtAccName -g $rgName --container-name $containerName --name family.json --permissions r ## use --start and --expiry Y-m-d'T'H:M'Z' ### Create a URL to access a blob with SAS token az storage blob url --sas ### Tables az storage table create -n $tblName --connection-string $conString az storage table create -n tblName --account-key $accKey --account-name $srtAccName ### Create Table Policy - Read, Add, Update, Delete. az storage table policy create -n $policyName --table-name $tblName --connection-string $conString --permissions raud --expiry 2020-04-24 ### Create a table entiry az storage entity insert --table-name $tblName --entity PartitionKey=001 RowKey=001 Content=DOMO --connection-string $conString ### Show storage table entity az storage entity show --partition-key 001 --row-key 001 --table-name $tblName --connection-string $conString ### Filter query using ODATA az storage entity query --table-name $tblName --filter "PartitionKey eq '001'" --connection-string $conString az storage entity query --table-name $tblName --filter "PartitionKey eq '001'and RowKey eq '003'" --connection-string $conString ### Blob storage create container az storage container create --account-name $srtAccName -g $rgName -n $containerName --connection-string $conString ### Upload Blob to Container az storage blob upload --container-name $containerName --file /Users/donmorris/Documents/family.json --name family.json --connection-string $conString az storage blob show --container-name $containerName --name family.json --connection-string $conString --query "etag" ### Copy between Blobs az storage blob copy start --destination-blob fam.json --destination-container cont2 --source-container domocontainer --source-blob family.json --connection-string $conString ### Update Blob or Container metadata using space-seperated k=v pairs. Overwites existing. az storage container metadata show --account-name $srtAccName --name $containerName --connection-string $conString az storage container metadata update --account-name $srtAccName --name $containerName --connection-string $conString --metadata name=don type=storage az storage blob service-properties show --account-name $srtAccName --connection-string $conString ### Acquire finite lease for writes. az storage blob lease acquire --container-name $containerName --blob-name family.json --connection-string $conString --lease-duration 15 az storage account management-policy create --policy (File in json) az storage account update --account-name $srtAccName -g $rgName -connection-string $conString --sku Standard_GZRS<file_sep>#!/bin/zsh rgName="az-203-search" location="UK South" sName="domo-search" ### RSG Create az group create -n $rgName -l $location ### Create Search Service az search service create -n $sName -g $rgName --sku free ### Retrieve the Admin key az search admin-key show --service-name $sName -g $rgName ### Service Bus Namespace az servicebus namespace create -n $nsName -g $rgName ### Get SBUS Connection String az servicebus namespace authorization-rule keys list -n $nsName -g $rgName ### Create SBUS Queue az servicebus queue create --namespace-name $nsName -g $rgName -n domoq ### Enable Disk Encryption on a VM on a ADE enabled key vault az keyvault create --name $vName --resource-group -g $rgName --enabled-for-disk-encryption az vm encryption enable --disk-encryption-keyvault $vName --volume-type {ALL, DATA, OS} az sql db create -g $r -s $sName -n $dName -e GeneralPurpose -f Gen5 -min-capacity 0.5 -c 2 --compute-model Serverless --auto-pause-delay 720<file_sep>#!/bin/zsh ### Use Event grid to alert a web app when a new blob is uploaded. rgName="az-203-event" location="UK South" sName="domo-event-hub" srtAccName="domoaz203ev" containerName="domocontainer" tURL="https://raw.githubusercontent.com/Azure-Samples/azure-event-grid-viewer/master/azuredeploy.json" sitename="domoazehub" ### RSG Create az group create -n $rgName -l $location ### Storage Account Create az storage account create -n $srtAccName -g $rgName -l $location --sku Standard_LRS ### Get Connection String conString=`az storage account show-connection-string -n $srtAccName --query "connectionString"` ### Get Account Key accKey=`az storage account keys list -n $srtAccName --query "[0].value"` ### Blob storage create container az storage container create --account-name $srtAccName $srtAccName -n $containerName --connection-string $conString ### Create Web App to act as Event Endpoint az group deployment create -g $rgName --template-uri $tURL --parameters siteName=$sitename hostingPlanName=viewerhost ### Register Event Grid provider on the subscription az provider register --namespace Microsoft.EventGrid az provider show --namespace Microsoft.EventGrid --query "registrationState" ### Subscribe to the storage account endpoint=https://$sitename.azurewebsites.net/api/updates storageid=$(az storage account show --n $srtAccName -g $rgName --query id --output tsv) az eventgrid event-subscription create --name domo-blob-ev --endpoint $endpoint --source-resource-id $storageid ### Trigger an Event from Blob Storage ### Upload Blob to Container az storage blob upload --container-name $containerName --file /Users/donmorris/Documents/family.json --name family.json --connection-string $conString az storage blob show --container-name $containerName --name family.json --connection-string $conString --query "etag" --included-event-types "Microsoft.Storage.BlobCreated" --subject-begins-with "/blobServices/default/containers/testcontainer/"<file_sep>Example: module "web_vms_cse" { source = "github.com/global-azure/terraform-azurerm-cse.git" vm_id = module.vm01.vm.*.id storage_account = var.cse_account storage_account_key = var.cse_key }<file_sep>package main import ( "fmt" "math/rand" "strconv" "time" ) func main() { fmt.Println("hello world") fmt.Println("String", randomString()) } func randomString() string { r := rand.New(rand.NewSource(time.Now().UnixNano())) return strconv.Itoa(r.Int()) }<file_sep>#!/bin/zsh # Tags date=`date` # Variables rgName="az-203-aks" location="UK South" aksName="domoazaks" clientID="" clientSecret="" subID="" tenantID="" #Resource Group az group create -n $rgName -l $location --tags date=$date #AKS Cluster az aks create -n $aksName -g $rgName -l $location --load-balancer-sku basic --vm-set-type AvailabilitySet --generate-ssh-keys --node-count 1 --node-vm-size Standard_A2_v2 --service-principal $clientID --client-secret $clientSecret # azureuser is default SSH user unless -u --admin-username is set. #AKS Credentials az aks get-credentials -n $aksName -g $rgName #Get cluster nodes kubectl get nodes #Apply Application kubectl apply -f azure-vote.yaml #Check deployment status kubectl get service azure-vote-front --watch ###https://github.com/Azure-Samples/azure-voting-app-redis<file_sep>#!/bin/zsh # Tags date=`date` # Variables rgName="az-203-batch" location="UK South" srtAccName="domoaz203batch" btcAccName="domoazbatch" btcPoolName="domoazpool" #Resource Group az group create -n $rgName -l $location --tags date=$date #Storage Account az storage account create -n $srtAccName -g $rgName -l $location --kind StorageV2 --sku Standard_LRS --tags date=$date #Batch Account az batch account create -n $btcAccName -g $rgName -l $location --storage-account $srtAccName #Batch Auth az batch account login -n $btcAccName -g $rgName #--shared-key-auth to use a key instead of AD or Service Principle. #Batch Pool az batch pool create --id $btcPoolName --node-agent-sku-id "batch.node.ubuntu 16.04" --vm-size Standard_A1_v2 --target-dedicated-nodes 2 --image canonical:ubuntuserver:16.04-LTS az batch pool show --pool-id $btcPoolName --query "allocationState" #Batch Job az batch job create --id myJob --pool-id $btcPoolName #Batch Task az batch task create --task-id myTask --job-id myJob --command-line "/bin/bash -c 'printenv | grep AZ_BATCH; sleep 90s'" #--resource-files can be used to download files to the nodes before running the --command-line. Public or read SAS. filename=httpurl az batch task show --job-id myJob --task-id myTask az batch task file list --job-id myJob --task-id myTask --output table az batch task file download --job-id myJob --task-id myTask --file-path stdout.txt --destination ./stdout-task-txt #DELETE az batch task stop --job-id myJob --task-id myTask az batch pool delete -id $btcPoolName az batch account delete -n $btcAccName -g $rgName az group delete -n $rgName<file_sep># WYEP Container Orchestration Platform The deployment templates and instructions in this repository can be used to deploy the following into an Azure Subscription: - Resource Groups - Azure Container Registry - Virtual Network and subnet. - Azure Kubernetes Service - Sample Nginx deployment and public service for testing. The AKS Cluster has been deployed with two node pools, one for critical system services and the other exclusively for user workloads. To ease any future integrations with other Azure resources the Azure network plugin (CNI) has been selected. System-managed identities are used to leverage platform management and credential rotation. A standard public load-balancer will provide ingress and egress for the AKS cluster. ## Requirements Besides access to an Azure Subscription, the following CLI tools should be installed to perform this deployment. - Terraform - AZ CLI - Kubectl ## Authenticate to an Azure Subscription The AZ CLi can be used to authenticate to an Azure account. The user should have sufficient privileges to perform a Role Assignment action later int he deployment. This can either be an "Owner" role or, alternatively, "User Access Administrator" role in addition to "Contributor". ``` az login az account set --subscription="[subId]" ``` A Service Principle can also be created for use during deployment. Note that an "Onwer" will need to execute these commands initially. ### Create a Service Principle and export using environment variables Create the Service Principle with a "Contributor" role and capture the output of the command. ``` az login az account set --subscription="[subId]" az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/[subId]" ``` Add the User Access Administrator role that will be used later in the deployment to attach the Container Registry with the AKS cluster. ``` az role assignment create --assignee [appId] --role "User Access Administrator" --scope "/subscriptions/[subId]" ``` Terraform can then use the Service Principle credentials for the deployment. Export ENV variables in the CLI, replacing the square brackets with the output from the previous commands. > **WARNING: Do not store these details in a file that may be checked into source control!** ``` export ARM_CLIENT_ID="[appId]" export ARM_CLIENT_SECRET="[password]" export ARM_SUBSCRIPTION_ID="[subId]" export ARM_TENANT_ID="[tenant]" ``` ## Deploy the templates using Terraform. Inside the repository directory (where this file is located): ``` terraform init terraform plan terraform apply ``` Once deployment is complete note the public IP address in the output labelled as public-svc-80-IP. ## Testing the AKS deployment. The Terraform templates will have created a sample Nginx deployment from a public registry along with a service exposed on port 80 using the Azure public load-balancer IP mentioned in the terraform output. You should be able to reach this in your browser or using the 'curl' command and get a 200 OK response. ``` curl -I [public-svc-80-IP] ``` ## Connecting to Kubernetes and the removing the test deployment. Connect to the newly deployed AKS cluster and remove the sample deployment and service. These commands assume that no names have been changed in the Terraform templates. ``` az account set --subscription [subId] az aks get-credentials --resource-group UKS-WYEP-PRD-AKS --name ukspwyepaks01 ``` The following commands can then be used to confirm and remove the sample deployment. ``` kubectl get deployment && kubectl get service kubectl delete service public-svc-80 kubectl delete deployment nginx kubectl get deployment && kubectl get service ``` ## Using the Managed Azure Container Registry The initial Nginx image was pulled directly from the public docker hub. To use the managed ACR we need to ensure that this is attached to the AKS cluster, push our own images, and then have the cluster create a new deployment from ACR. Start by ensuring that the AKS cluster can pull from ACR using the Managed identity. ``` az aks check-acr --resource-group UKS-WYEP-PRD-AKS --name ukspwyepaks01 --acr ukspwyepacr01.azurecr.io ``` If that command does not indicate that these resources have been successfully attached, use the following command: ``` az aks update --resource-group UKS-WYEP-PRD-AKS --name ukspwyepaks01 --attach-acr ukspwyepacr01 ``` Once attached, Your container can then be uploaded to ACR for later deployment. In this example we will simply import an existing public image into the managed Azure container registry that is referenced in the sample YAML template. ``` az acr login -n ukspwyepacr01 --expose-token az acr import -n ukspwyepacr01 --source docker.io/library/nginx:latest --image nginx:v1 kubectl apply -f k8s-nginx.yaml kubectl get deployment && kubectl get service curl -I [public-svc] ``` ## Clean up Use Terraform to remove all resources created during this deployment. ``` terraform destroy ``` ## Recommendations The deployment and infrastructure can be improved by incorporating some or all of the following ideas. - An Azure Firewall or other NVA can be deployed to filter ingress and egress traffic. - Azure FrontDoor or an Application Gateway (using the AGIC add-on in AKS) can be used to provide L7 routing, SSL and WAF functionality. - Azure Key Vault can be used for centralised and secure secret, certificate, and key management. - The AKS cluster can use Azure AD authentication in combination with the already-enabled RBAC feature for user access management. - Access to the public load-balancer IP should be restricted by source IP. AKS will use the NSG assigned to each node. - The terraform templates can be converted into a module if this deployment pattern will be repeated and requires additional interpolation. - The build can be performed in a centralised CI/CD pipeline, like Azure DevOPS, making it more accessible. <file_sep>#!/bin/zsh rgName="az-203-app" location="UK South" aspName="domo-asp" webName="domo-app" gitURL="https://github.com/banago/simple-php-website" dockURL="dockersamples/static-site" ### RSG Create az group create -n $rgName -l $location ### App Service Plan Create az appservice plan create -g $rgName -n $aspName --is-linux --sku B1 --number-of-workers 1 ### Web App Create ### List available runtimes: az webapp list-runtimes ###Create webapp and deploy local code: az webapp up #Github az webapp create -g $rgName --plan $aspName -n $webName --runtime "php|5.6" --deployment-source-url $gitURL #Container Image az webapp create -g $rgName --plan $aspName -n $webName --deployment-container-image-name $dockURL ### Manage Web App: az webapp /start/stop/restart -g $rgName -n $webName az webapp ssh -g $rgName -n $webName az webapp deployment source delete -g $rgName -n $webName az webapp deployment source config -g $rgName -n $webName --repo-url $gitURL --repository-type github --manual-integration ### Azure Functions <file_sep>docker build . -t web docker run -dt -p 80:80 web <file_sep>FROM alpine:latest RUN apk add nginx COPY default.conf /etc/nginx/conf.d/default.conf COPY index.html /var/www/ RUN echo "daemon off;" >> /etc/nginx/nginx.conf RUN echo "pid /tmp/nginx.pid;" >> /etc/nginx/nginx.conf EXPOSE 80 CMD ["/usr/sbin/nginx"] <file_sep># K8S Cluster with Kubeadm, ContainerD or Docker and Flannel/Weave # Disable SWAP sudo swapoff -a sudo sed -i '/ swap / s/^\(.*\)$/#\1/g' /etc/fstab # setup networking cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf overlay br_netfilter EOF sudo modprobe overlay sudo modprobe br_netfilter cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf net.bridge.bridge-nf-call-ip6tables = 1 net.bridge.bridge-nf-call-iptables = 1 net.ipv4.ip_forward = 1 EOF sudo sysctl --system # install containerD or docker sudo apt-get update && sudo apt-get install -y containerd apt-transport-https curl sudo mkdir -p /etc/containerd sudo containerd config default | sudo tee /etc/containerd/config.toml sudo systemctl enable containerd sudo systemctl restart containerd # // or // sudo apt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get update sudo apt-get install containerd.io # Change CGroup Driver to SystemD if using Docker sudo mkdir /etc/docker cat <<EOF | sudo tee /etc/docker/daemon.json { "exec-opts": ["native.cgroupdriver=systemd"], "log-driver": "json-file", "log-opts": { "max-size": "100m" }, "storage-driver": "overlay2" } EOF sudo systemctl enable docker sudo systemctl daemon-reload sudo systemctl restart docker sudo docker info | grep -i cgroup # install kubelet, kubeadm, kubectl v1.19.1 sudo apt-get update && sudo apt-get install -y apt-transport-https curl curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - cat <<EOF | sudo tee /etc/apt/sources.list.d/kubernetes.list deb https://apt.kubernetes.io/ kubernetes-xenial main EOF sudo apt-get update sudo apt-get install -y kubelet=1.20.1-00 kubeadm=1.20.1-00 kubectl=1.20.1-00 sudo apt-mark hold kubelet kubeadm kubectl # initialize cluster sudo kubeadm init --pod-network-cidr=10.244.0.0/16 # setup files to download from minion mkdir -p /home/azadmin/.kube cp -i /etc/kubernetes/admin.conf /home/azadmin/.kube/config chown -R $(id -u azadmin):$(id -g azadmin) /home/azadmin kubectl version # prepare configuration and provision flannel networking for linux kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml # OR Weave kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')" kubectl get pods -n kube-system # Join nodes to cluster -install steps above. kubeadm token create --print-join-command # Run this on worker nodes and verify. kubectl get nodes
c2ca103bec8a4bcf9f26aa13bfc958f00067c341
[ "Markdown", "Go", "Dockerfile", "Shell" ]
16
Shell
DonMorrisRak/Azure
a56491367d178fa808e460741e8e95461a02d3bb
f3a236481463b1bca103325041298ab15b730995
refs/heads/master
<repo_name>Roer1200/MilanovP3P<file_sep>/Website/Milanov/Milanov/pages/store/shoppingcart.aspx.cs using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Configuration; namespace Milanov.pages.store { public partial class shoppingcart : System.Web.UI.Page { decimal _TotalPrice = 0.00m; // decimal to count the total price protected void Page_Load(object sender, EventArgs e) { this.Title = "Winkelwagen - Milanov"; // Change the current title if (!Page.IsPostBack) { string delId = Request.QueryString["delId"]; if (!String.IsNullOrEmpty(delId)) // url containts a delId { // Deletes the item from the shoppingcart that has been deleted by user List<string> delList = (List<string>)Session["Cart"]; if (delList != null && delList.Contains(delId)) { delList.Remove(delId); Session["Cart"] = delList; } } GetProductsForCart(); } } #region GetProductsForCart /// <summary> /// Gets the products that are ordered and shows them in shoppingcart /// </summary> private void GetProductsForCart() { StringBuilder sb = new StringBuilder(); if (Session["Cart"] != null) // Session["Cart"] is NOT null { List<string> productList = (List<string>)Session["Cart"]; if (productList.Count > 0) // if the productList > 0 -> { ArrayList cartList = new ArrayList(); cartList = ConnectionClass.GetShopProducts(productList); foreach (Products product in cartList) { _TotalPrice += product.Price; sb.Append( string.Format( @"<tr> <td><a href='/pages/store/shoppingcart.aspx?delId={0}'><img src='/images/trash.png' alt='trash' /></a></td> <td><img src='/images/preview/{3}' alt='{1}' height='40px' width='40px' /></td> <td><a href='/pages/store/product.aspx?productId={0}'>{1}</td> <td>&euro; {2}</td> </tr>", product.Id, product.Name, product.Price, product.Image)); } lblOutput.Text = sb.ToString(); checkForDiscount(); } else // productList is NOT > 0 -> { sb.Append( string.Format(@" <tr> <td colspan='4'>Het winkelmandje is leeg.</td> </tr>")); lblOutput.Text = sb.ToString(); ltrPrice.Text = _TotalPrice.ToString(); } } else // Session["Cart"] is NULL { sb.Append( string.Format(@" <tr> <td colspan='4'>Het winkelmandje is leeg.</td> </tr>")); lblOutput.Text = sb.ToString(); ltrPrice.Text = _TotalPrice.ToString(); } } #endregion #region EmptyCart /// <summary> /// If Empty button is clicked, delete all products from shoppingcart /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void lbtnEmpty_Click(object sender, EventArgs e) { if (Session["Cart"] != null) { List<string> delList = (List<string>)Session["Cart"]; if (delList.Count > 0) { delList.Clear(); Session["Cart"] = delList; } } GetProductsForCart(); } /// <summary> /// Checks if user should get discount /// </summary> private void checkForDiscount() { if ((string)Session["role"] == "2" && _TotalPrice > 0) // If user is a regular customer -> calculate new price with 5% discount { decimal originalPrice = _TotalPrice; decimal discountPrice = ((_TotalPrice / 100) * 5); // 5% korting _TotalPrice = ((_TotalPrice / 100) * 95); // 5% korting voor vaste klanten discountPrice = Math.Round(discountPrice, 2); _TotalPrice = Math.Round(_TotalPrice, 2); ltrPrice.Text = originalPrice.ToString(); ltrDiscount.Visible = true; ltrDiscPrice.Visible = true; ltrDiscountN.Visible = true; ltrDiscPriceN.Visible = true; ltrDiscount.Text = discountPrice.ToString(); ltrDiscPrice.Text = _TotalPrice.ToString(); } else // User is not a regular custumor { ltrPrice.Text = _TotalPrice.ToString(); ltrDiscount.Visible = false; ltrDiscPrice.Visible = false; ltrDiscountN.Visible = false; ltrDiscPriceN.Visible = false; } } #endregion #region CheckOut /// <summary> /// If button CheckOout is clicked, go to paypal /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnCheckOut_Click(object sender, EventArgs e) { if (!lblOutput.Text.Contains("Het winkelmandje is leeg.")) // If shoppingcart contains items -> { string nPrice = ltrPrice.Text; string dPrice = ltrDiscPrice.Text; nPrice = nPrice.Replace(@",", @"."); // Changes the price that does not contain discount from xxx,xx to xxx.xx ( , -> . ) dPrice = dPrice.Replace(@",", @"."); // Changes the price that contains discount from xxx,xx to xxx.xx ( , -> . ) /* PayPal variables http://www.paypalobjects.com/IntegrationCenter/ic_std-variable-ref-buy-now.html */ string redirecturl = ""; //Mention URL to redirect content to paypal site redirecturl += "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" + ConfigurationManager.AppSettings["paypalemail"].ToString(); //First name we assign static, in live this name should be changed to the user his/her name redirecturl += "&first_name=milanovfirst"; //City we assign static, in live the city should be changed to the user his/her city redirecturl += "&city=milanovcity"; //State we assign static, in live this state should be changed to the user his/her state redirecturl += "&state=milanovstate"; //Product Name redirecturl += "&item_name=" + "Pictures"; if ((string)Session["role"] == "2") { //Product Amount redirecturl += "&amount=" + dPrice; } else { // Product Amount redirecturl += "&amount=" + nPrice; } //Business contact id //redirecturl += "&business=nameatgmail.com"; //Shipping charges if any redirecturl += "&shipping=0"; //Handling charges if any redirecturl += "&handling=0"; //Tax amount if any redirecturl += "&tax=0"; //Add quatity redirecturl += "&quantity=1"; //Currency code redirecturl += "&currency=EUR"; //Success return page url redirecturl += "&return=" + ConfigurationManager.AppSettings["SuccessURL"].ToString() + "?orderId=" + ((string)(Session["login"])); //Failed return page url redirecturl += "&cancel_return=" + ConfigurationManager.AppSettings["FailedURL"].ToString(); Response.Redirect(redirecturl); } else // Shoppingcart does not contain items, show error message { lblError.Visible = true; lblError.Text = "Er moet eerst een product worden toegevoegd."; } } #endregion } }<file_sep>/Website/Milanov/Milanov/pages/admin/Products_Add.aspx.cs using System; using System.Collections; using System.IO; using System.Drawing; using System.Collections.Specialized; using System.Linq; namespace Milanov.pages.admin { public partial class products_add : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string selectedValue = ddlImage.SelectedValue; // This is probably not necessary ... showImages(); // Execute showImages() ddlImage.SelectedValue = selectedValue; // This is probably not necessary ... } /// <summary> /// Adds and shows all the available images in the DropDownList /// </summary> private void showImages() { string[] images = Directory.GetFiles(Server.MapPath("~/images/products/")); ArrayList imagelist = new ArrayList(); foreach (string image in images) { string imageName = image.Substring(image.LastIndexOf(@"\") + 1); imagelist.Add(imageName); } ddlImage.DataSource = imagelist; ddlImage.DataBind(); } /// <summary> /// Clears all the textfields. /// </summary> private void ClearTextFields() { txtName.Text = ""; txtPrice.Text = ""; txtDescription.Text = ""; } /// <summary> /// If button upload is clicked, try to upload the file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnUploadImage_Click(object sender, EventArgs e) { try { NameValueCollection imageExtensions = new NameValueCollection(); imageExtensions.Add(".jpg", "image/jpeg"); imageExtensions.Add(".gif", "image/gif"); imageExtensions.Add(".png", "image/png"); string filename = Path.GetFileName(FileUpload1.FileName); string ext = "." + filename.Substring(filename.LastIndexOf(@".") + 1); if (imageExtensions.AllKeys.Contains(ext)) // check if extension is .jpg, .gif or .png { if (ddlImage.Items.FindByText(filename) != null) // check if filename is in use { lblResult.Text = "Foto " + filename + " is al in gebruik, kies een andere naam."; } else // extension is correct, name is not in use -> upload image and make preview image { FileUpload1.SaveAs(Server.MapPath("~/images/products/") + filename); Page_Load(sender, e); ddlImage.SelectedValue = filename.ToString(); // Add preview layer Bitmap bitmapImage = new Bitmap(Server.MapPath("~/images/products/") + filename); Graphics graphicImage = Graphics.FromImage(bitmapImage); Image preview = Image.FromFile(Server.MapPath("~/images/preview.png"), true); for (int i = 1; i < 4; i += 2) { for (int j = 1; j < 4; j += 2) { graphicImage.DrawImage(preview, new Rectangle(new Point((((bitmapImage.Width / 4) * j) - 52), ((bitmapImage.Height / 4) * i)), new Size(104, 19))); } } bitmapImage.Save(Server.MapPath("~/images/preview/") + filename); lblResult.Text = "Foto " + filename + " succesvol geupload!"; } } else // the chosen file has an extension that is not allowed { lblResult.Text = "Deze extensie wordt niet geaccepteerd, alleen bestanden met .jpg, .gif en .png mogen gebruikt worden."; } } catch (Exception) { lblResult.Text = "Upload foto mislukt!"; } } /// <summary> /// If button save is clicked, try to save the new product /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Click(object sender, EventArgs e) { try { string name = txtName.Text; int cat_id = Convert.ToInt32(ddlCategory.SelectedValue); decimal price = Convert.ToDecimal(txtPrice.Text); string image = ddlImage.SelectedValue; string description = txtDescription.Text; Products product = new Products(name, cat_id, price, image, description); ConnectionClass.AddProduct(product); lblResult.Text = "Upload nieuw product succesvol!"; ClearTextFields(); } catch (Exception) { lblResult.Text = "Upload new product mislukt!"; } } /// <summary> /// If button back is clicked, redirect to products_overview.aspx /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnBack_Click(object sender, EventArgs e) { Response.Redirect("/pages/admin/products_overview.aspx"); } } }<file_sep>/Website/Milanov/Milanov/pages/admin/Categories_Add.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Milanov.pages.admin { public partial class categories_add : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// Clears all the textfields. /// </summary> private void ClearTextFields() { txtName.Text = ""; } /// <summary> /// If button save is clicked, try to save the new category /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Click(object sender, EventArgs e) { // Create a new category Categories category = new Categories(txtName.Text); // Save the category and return a result message lblResult.Text = ConnectionClass.AddCategory(category); // If category is added -> ClearTextFields if (lblResult.Text == "Categorie toegevoegd!") { ClearTextFields(); } } /// <summary> /// If button back is clicked, redirect to categories_overview.aspx /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnBack_Click(object sender, EventArgs e) { Response.Redirect("/pages/admin/categories_overview.aspx"); } } }<file_sep>/Website/Milanov/Milanov/pages/admin/Users_Overview.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Milanov.pages.admin { public partial class users_overview : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// If button delete is clicked, here it will check what you are trying to delete /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { // If you are trying to delete the inbuilt admin account it will display a error message and disable you from deleting TableCell cell = GridView1.Rows[e.RowIndex].Cells[1]; if (cell.Text == "1") { lblError.Visible = true; lblError.Text = "Het ingebouwde admin account kan niet worden verwijderd."; } else { lblError.Visible = false; } } /// <summary> /// If button edit is clicked, here it will check what you are trying to edit /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { // If you are trying to edit the inbuilt admin account it will display a error message and disable you from editing TableCell cell = GridView1.Rows[e.NewEditIndex].Cells[1]; if (cell.Text == "1") { lblError.Visible = true; e.Cancel = true; lblError.Text = "Het ingebouwde admin account kan niet worden bewerkt."; } else { lblError.Visible = false; } } } }<file_sep>/Website/Milanov/Milanov/App_Code/Products.cs public class Products { public int Id { get; set; } public string Name { get; set; } public int Cat_id { get; set; } public string Cname { get; set; } // Voor het omzetten van het cat_id in een naam. public decimal Price { get; set; } public string Image { get; set; } public string Description { get; set; } public Products(int id, string name, int cat_id, decimal price, string image, string description) { this.Id = id; this.Name = name; this.Cat_id = cat_id; this.Price = price; this.Image = image; this.Description = description; } public Products(int id, string name, string cname, decimal price, string image, string description) { this.Id = id; this.Name = name; this.Cname = cname; this.Price = price; this.Image = image; this.Description = description; } public Products(string name, int cat_id, decimal price, string image, string description) { this.Name = name; this.Cat_id = cat_id; this.Price = price; this.Image = image; this.Description = description; } }<file_sep>/Website/Milanov/Milanov/pages/users/account.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Milanov.pages.users { public partial class account : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Check if a user is logged in if (Session["login"] != null) { this.Title = Session["login"] + " - Milanov"; lblCU.Text = "Welcome <b>" + Session["login"] + "</b>!"; // Check if user is admin if ((string)Session["role"] != "1") // If admin show 'administrator' button. { btnCMS.Visible = false; } else // If NOT admin don't show 'administrator' button. { btnCMS.Visible = true; } } else { Response.Redirect("/pages/users/login.aspx"); } } /// <summary> /// Clears all the e-mail textfields /// </summary> private void ClearEmailTextFields() { txtEcurrent.Text = ""; txtEnew.Text = ""; txtEconfirm.Text = ""; } #region ShowUserInfo /// <summary> /// If button info is clicked, open or close user info /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnInfo_Click(object sender, EventArgs e) { if (tblInfo.Visible != true) { string email = ConnectionClass.GetEmail(Session["login"].ToString()); string role = ConnectionClass.GetRole(Session["login"].ToString()); lblUsername.Text = "" + Session["login"]; lblEmail.Text = email; lblRole.Text = role; tblInfo.Visible = true; } else { tblInfo.Visible = false; } } #endregion #region ChangePassword /// <summary> /// If button ChangePassword is clicked, open or close fields to change password /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnChangePassword_Click(object sender, EventArgs e) { if (tblPassword.Visible != true) { lblPoutput.Text = ""; tblEmail.Visible = false; tblPassword.Visible = true; } else { tblPassword.Visible = false; } } /// <summary> /// If button Psubmit is clicked, try to change password /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnPsubmit_Click(object sender, EventArgs e) { lblPoutput.Text = ConnectionClass.ChangePassword(Session["Login"].ToString(), txtPcurrent.Text, txtPnew.Text); } #endregion #region ChangeEmail /// <summary> /// If button ChangeEmail is clicked, open or close fields to change e-mail /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnChangeEmail_Click(object sender, EventArgs e) { if (tblEmail.Visible != true) { lblEoutput.Text = ""; tblPassword.Visible = false; tblEmail.Visible = true; } else { tblEmail.Visible = false; } } /// <summary> /// If button Esubmit is clicked, try to change e-mail /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnEsubmit_Click(object sender, EventArgs e) { lblEoutput.Text = ConnectionClass.ChangeEmail(Session["Login"].ToString(), txtEcurrent.Text, txtEnew.Text); if (lblEoutput.Text == "Uw mail adres is aangepast!") { if (tblInfo.Visible == true) { tblInfo.Visible = false; } ClearEmailTextFields(); // If e-mail is changed -> ClearEmailTextFields(); } } #endregion protected void btnCMS_Click(object sender, EventArgs e) { Response.Redirect("/pages/admin/administrator.aspx"); } } }<file_sep>/Website/Milanov/Milanov/pages/users/register.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Milanov.pages.users { public partial class register : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Title = "Register - Milanov"; // Change the current title } /// <summary> /// Clears all the textfields. /// </summary> private void ClearTextFields() { txtUsername.Text = ""; txtPassword.Text = ""; txtConfirm.Text = ""; txtEmail.Text = ""; } /// <summary> /// If button register is clicked, try to register the new user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnRegister_Click(object sender, EventArgs e) { // Create a new user Users users = new Users(txtUsername.Text, txtPassword.Text, txtEmail.Text, 3); // Register the user and return a result message lblResult.Text = ConnectionClass.RegisterUser(users); // If category is added -> ClearTextFields if (lblResult.Text == "Uw account is aangemaakt!") { ClearTextFields(); } } /// <summary> /// If button back is clicked, redirect user to login.aspx /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnBack_Click(object sender, EventArgs e) { Response.Redirect("/pages/users/login.aspx"); } } }<file_sep>/Website/Milanov/Milanov/pages/contact.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net.Mail; namespace Milanov.pages { public partial class contact : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Title = "Contact - Milanov"; // Change the current title } /// <summary> /// // If send button is clicked, try to send the e-mail /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSend_Click(object sender, EventArgs e) { try { MailMessage eMailMessage = new MailMessage(); eMailMessage.From = new MailAddress(HttpUtility.HtmlEncode(txtEmail.Text)); eMailMessage.To.Add(new MailAddress("<EMAIL>")); eMailMessage.Subject = "Milanov: " + HttpUtility.HtmlEncode(txtSubject.Text); eMailMessage.Body = "<b>Naam:</b> " + HttpUtility.HtmlEncode(txtName.Text) + "<br />" + "<b>E-mail:</b> " + HttpUtility.HtmlEncode(txtEmail.Text) + "<br />" + "<b>Onderwerp:</b> " + HttpUtility.HtmlEncode(txtSubject.Text) + "<br />" + "<b>Bericht:</b> <br />" + HttpUtility.HtmlDecode(txtMessage.Content); eMailMessage.IsBodyHtml = true; eMailMessage.Priority = MailPriority.Normal; SmtpClient mSmtpClient = new SmtpClient(); mSmtpClient.Send(eMailMessage); lblSend.Text = "Uw bericht is verzonden, eventueel antwoord zal worden verstuurd naar: " + txtEmail.Text; } catch (Exception) { lblSend.Text = "De mail is niet verzonden, onze excuses voor het ongemak."; } } /// <summary> /// If reset button is clicked, go to ClearTextFields(); /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnReset_Click(object sender, EventArgs e) { ClearTextFields(); } /// <summary> /// Clears all the textfields. /// </summary> private void ClearTextFields() { txtName.Text = ""; txtEmail.Text = ""; txtSubject.Text = ""; txtMessage.Content = ""; } } }<file_sep>/Website/Milanov/Milanov/pages/store/succes.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net.Mail; using System.Text; using System.Collections; namespace Milanov.pages.store { public partial class succes : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Title = "Succes - Milanov"; // Change the current title if (!Page.IsPostBack) { string orderId = Request.QueryString["orderId"]; if (!String.IsNullOrEmpty(orderId)) // url contains a orderId { if (orderId == ((string)Session["login"])) // orderId equals to current user { if (Session["Cart"] != null) // session["Cart"] is NOT null -> ShowBoughtImages(); { List<string> boughtList = (List<string>)Session["Cart"]; ShowAndMailBoughtImages(boughtList); } else // session["Cart"] is null, redirect to error.aspx { Response.Redirect("~/error.aspx"); } } else // orderId does not equals to current user, redirect to error.aspx { Response.Redirect("~/error.aspx"); } } else // url does not contain a orderId { Response.Redirect("~/error.aspx"); } } } /// <summary> /// Shows and e-mails all the images that are bought by the user /// </summary> /// <param name="boughtList"></param> private void ShowAndMailBoughtImages(List<string> boughtList) { /* <- This code can be used for downloading the images. -> * NameValueCollection imageExtensions = new NameValueCollection(); * imageExtensions.Add(".jpg", "image/jpeg"); * imageExtensions.Add(".gif", "image/gif"); * imageExtensions.Add(".png", "image/png"); */ if (boughtList.Count > 0) // If the list of bought images is > 0 (this SHOULD always be true as we check this earlier) -> { StringBuilder sb = new StringBuilder(); ArrayList cartList = new ArrayList(); cartList = ConnectionClass.GetShopProducts(boughtList); string email = ConnectionClass.GetEmail((string)Session["login"]); List<string> images = new List<string>(); foreach (Products product in cartList) { sb.Append(string.Format(@"<img src='/images/products/{1}' alt='{0}' height='20%' width='20%' /><br /><br />", product.Name, product.Image)); images.Add(product.Image); /* <- This code can be used for downloading the images. -> * string ext = "." + product.Image.Substring(product.Image.LastIndexOf(@".") + 1); * if (imageExtensions.AllKeys.Contains(ext)) * { * Response.ContentType = imageExtensions.Get(ext); * Response.AppendHeader("Content-Disposition", "attachment; filename=" + product.Image); * Response.TransmitFile(Server.MapPath("~/images/products/" + product.Image)); * Response.End(); * } */ } lblImage.Text = sb.ToString(); // Shows the images // E-mail the images try { MailMessage eMailMessage = new MailMessage(); eMailMessage.From = new MailAddress(HttpUtility.HtmlEncode("<EMAIL>")); eMailMessage.To.Add(new MailAddress(email)); foreach(string img in images) { eMailMessage.Attachments.Add(new Attachment(Server.MapPath("/images/products/" + img))); } eMailMessage.Subject = "Uw bestelde foto's"; eMailMessage.Body = "Beste " + HttpUtility.HtmlEncode((string)(Session["login"])) + ",<br /><br />" + "Bedankt voor uw bestelling, in de bijlage vindt u de bestelde foto's.<br /><br />" + "Met vriendelijke groet," + "<br />" + "Milanov"; eMailMessage.IsBodyHtml = true; eMailMessage.Priority = MailPriority.Normal; SmtpClient mSmtpClient = new SmtpClient(); mSmtpClient.Send(eMailMessage); lblOutput.Text = "Uw bestelde foto('s) zijn verzonden naar " + email + "."; } catch (Exception) { lblOutput.Text = "Er is iets fout gegaan, neem contact op met de websitebeheerder."; } } else // The list of bought images is NOT > 0 (this SHOULD never happen) { Response.Redirect("~/error.aspx"); } } } }<file_sep>/Website/Milanov/Milanov/pages/users/login.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Milanov.pages.users { public partial class login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Title = "Login - Milanov"; // Change the current title } /// <summary> /// If button login is clicked, try to login /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnLogin_Click(object sender, EventArgs e) { // Check user credentials Users users = ConnectionClass.LoginUser(txtUsername.Text, txtPassword.Text); if (users != null) // If user credentials are correct -> login { // Store login variables in session Session["login"] = users.Username; Session["role"] = users.Rol_id.ToString(); if ((string)Session["role"] != "1") // If user is NOT admin -> redirect to home.aspx { Response.Redirect("/pages/home.aspx"); } else // If user is admin -> redirect to administrator.aspx { Response.Redirect("/pages/admin/administrator.aspx"); } } else // If user credentials are incorrect -> error message { lblError.Text = "Inloggen mislukt, wachtwoord vergeten? Klik <a href='/pages/users/forgotpassword.aspx'>hier</a>"; } } /// <summary> /// If button register is clicked, redirect to register.aspx /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnRegister_Click(object sender, EventArgs e) { Response.Redirect("/pages/users/register.aspx"); } } }<file_sep>/Website/Milanov/Milanov/pages/error.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Milanov.pages { public partial class error : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Title = "Error - Milanov"; // Change the current title if (!Page.IsPostBack) // Show error message { lblError.Text = String.Format(@"Er is iets foutgegaan, dit kan één of meerdere oorzaken hebben:<br /> <ul> <li>De pagina die u probeerde te bezoeken bestaat niet of is niet in gebruik.</li> <li>Wat u deed mag en/of kan niet.</li> </ul> Klik <a href='javascript:history.back()'>hier</a> om terug te gaan naar de vorige pagina."); lblError.Visible = true; } } } }<file_sep>/Website/Milanov/Milanov/pages/store/products.aspx.cs using System; using System.Collections; using System.Text; namespace Milanov.pages.store { public partial class products : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Title = "Winkel - Milanov"; // Change the current title if (!Page.IsPostBack) { string categoryId = Request.QueryString["categoryId"]; if (!String.IsNullOrEmpty(categoryId)) // url contains a categoryId -> show products in specified category { ArrayList productsList = new ArrayList(); productsList = ConnectionClass.GetProductByCategory(categoryId.ToString()); StringBuilder sb = new StringBuilder(); foreach (Products product in productsList) { sb.Append( string.Format( @"<table class='productsTable'> <tr> <th rowspan='6' width='150px'><a href='/pages/store//product.aspx?productId={0}'><img runat='server' src='/images/preview/{4}' alt='{1}'/></th> <th width='50px'>Naam:</th> <td>{1}</td> </tr> <tr> <th>Categorie:</th> <td>{2}</td> </tr> <tr> <th>Prijs:</th> <td>€ {3}</td> </tr> </table>", product.Id, product.Name, product.Cname, product.Price, product.Image)); lblOutput.Text = sb.ToString(); } } else // url does not contain a categoryId -> show all products { ArrayList productsList = new ArrayList(); productsList = ConnectionClass.GetProductByCategory("%"); StringBuilder sb = new StringBuilder(); foreach (Products product in productsList) { sb.Append( string.Format( @"<table class='productsTable'> <tr> <th rowspan='6' width='150px'><a href='/pages/store/product.aspx?productId={0}'><img runat='server' src='/images/preview/{4}' alt='{1}'/></th> <th width='50px'>Naam:</th> <td>{1}</td> </tr> <tr> <th>Categorie:</th> <td>{2}</td> </tr> <tr> <th>Prijs:</th> <td>€ {3}</td> </tr> </table>", product.Id, product.Name, product.Cname, product.Price, product.Image)); lblOutput.Text = sb.ToString(); } } } } } }<file_sep>/Website/Milanov/Milanov/App_Code/Users.cs public class Users { public int Id { get; set; } public string Username { get; set; } public string Password { get; set; } public string Email { get; set; } public int Rol_id { get; set; } public Users(int id, string username, string password, string email, int rol_id) { this.Id = id; this.Username = username; this.Password = <PASSWORD>; this.Email = email; this.Rol_id = rol_id; } public Users(string username, string password, string email, int rol_id) { this.Username = username; this.Password = <PASSWORD>; this.Email = email; this.Rol_id = rol_id; } }<file_sep>/Website/Milanov/Milanov/pages/admin/Products_Overview.aspx.cs using System; using System.Collections; using System.IO; using System.Web.UI.WebControls; namespace Milanov.pages.admin { public partial class products_overview : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }<file_sep>/Website/Milanov/Milanov/pages/store/product.aspx.cs using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Drawing; namespace Milanov.pages.store { public partial class product_details : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string productId = Request.QueryString["productId"]; if (!String.IsNullOrEmpty(productId)) // url containts a productId -> show specified product { ArrayList productList = new ArrayList(); productList = ConnectionClass.GetProductDetails(productId); StringBuilder sb = new StringBuilder(); foreach (Products product in productList) { sb.Append( string.Format( @"<table class='productTable'> <tr> <th rowspan='8' width='150px'><a href='/images/preview/{4}' rel='fancybox' title='{1}'><img runat='server' src='/images/preview/{4}' alt='{1}'/></a></th> <th width='50px'>Naam:</th> <td>{1}</td> </tr> <tr> <th>Categorie:</th> <td>{2}</td> </tr> <tr> <th>Prijs:</th> <td>€ {3}</td> </tr> <tr> <th valign='top'>Omschrijving:</th> <td>{5}</td> </tr> </table>", product.Id, product.Name, product.Cname, product.Price, product.Image, product.Description)); btnAddToCart.Visible = true; btnBack.Visible = true; lblOutput.Text = sb.ToString(); this.Title = product.Name + " - Milanov"; // Change the current title } } else // url does not contain a productId, redirect to error.aspx { Response.Redirect("~/pages/error.aspx"); } } } /// <summary> /// If button AddToCart is clicked, add the selected product to shoppingcart /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnAddToCart_Click(object sender, EventArgs e) { string productId = Request.QueryString["productId"]; List<string> ProductsInCart = (List<string>)Session["Cart"]; if (ProductsInCart == null) { ProductsInCart = new List<string>(); } if (!ProductsInCart.Contains(productId)) { ProductsInCart.Add(productId); Session["Cart"] = ProductsInCart; } Response.Redirect("~/pages/store/shoppingcart.aspx"); } } }<file_sep>/Website/Milanov/Milanov/pages/users/forgotpassword.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net.Mail; namespace Milanov.pages.users { public partial class forgotpassword : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Title = "Wachtwoord vergeten - Milanov"; // Change the current title } /// <summary> /// If button send is clicked, try send e-mail with password /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSend_Click(object sender, EventArgs e) { // Get the password string password = ConnectionClass.ForgotPassword(txtUsername.Text, txtEmail.Text); if (!password.Contains("<PASSWORD>")) // If password does not contain a error message, send e-mail with password. { try { MailMessage eMailMessage = new MailMessage(); eMailMessage.From = new MailAddress(HttpUtility.HtmlEncode("<EMAIL>")); eMailMessage.To.Add(new MailAddress(txtEmail.Text)); eMailMessage.Subject = "Uw wachtwoord"; eMailMessage.Body = "Beste " + HttpUtility.HtmlEncode(txtUsername.Text) + ",<br /><br />" + "Uw wachtwoord is: <b>" + password + "</b><br /><br />" + "Met vriendelijke groet," + "<br />" + "Milanov"; eMailMessage.IsBodyHtml = true; eMailMessage.Priority = MailPriority.Normal; SmtpClient mSmtpClient = new SmtpClient(); mSmtpClient.Send(eMailMessage); lblOutput.Text = "Uw wachtwoord is verzonden naar " + txtEmail.Text + "."; } catch (Exception) { lblOutput.Text = "Er is iets fout gegaan, neem contact op met de websitebeheerder."; } } else // If password contains a error message, display error message. { lblOutput.Text = password; } } } }<file_sep>/Website/Milanov/Milanov/pages/admin/Categories_Overview.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Milanov.pages.admin { public partial class categories_overview : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// If button delete is clicked, here it will check what you are trying to delete /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { // If you are trying to delete a category that is still in use by a product it will display a error message and disable you from deleting TableCell cell = GridView1.Rows[e.RowIndex].Cells[1]; bool error = ConnectionClass.GetInUseCategories(cell.Text); if (error == true) { lblError.Visible = true; lblError.Text = "Deze categorie is in gebruik door één of meerdere producten en kan hierdoor niet worden verwijderd."; } else { lblError.Visible = false; } } } }<file_sep>/Website/Milanov/Milanov/App_Code/ConnectionClass.cs using System; using System.Collections; using System.Configuration; using System.Data.SqlClient; using System.Collections.Generic; public static class ConnectionClass { private static SqlConnection conn; private static SqlCommand command; static ConnectionClass() { string connectionString = ConfigurationManager.ConnectionStrings["MilanovDBConnectionString"].ToString(); conn = new SqlConnection(connectionString); command = new SqlCommand("", conn); } #region GetProductByCategory /// <summary> /// Returns all the products in the specified category /// </summary> /// <param name="productCategory"></param> /// <returns></returns> public static ArrayList GetProductByCategory(string productCategory) { ArrayList list = new ArrayList(); string query = string.Format("SELECT p.id, p.name, c.name AS cname, p.price, p.image, p.description FROM products AS p INNER JOIN categories AS c ON p.cat_id = c.id WHERE p.cat_id LIKE '{0}'", productCategory); try { conn.Open(); command.CommandText = query; SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); string name = reader.GetString(1); string cname = reader.GetString(2); decimal price = reader.GetDecimal(3); string image = reader.GetString(4); string description = reader.GetString(5); Products product = new Products(id, name, cname, price, image, description); list.Add(product); } } finally { conn.Close(); command.Parameters.Clear(); } return list; } #endregion #region GetProductDetails /// <summary> /// Returns all the product details of the specified product /// </summary> /// <param name="productId"></param> /// <returns></returns> public static ArrayList GetProductDetails(string productId) { ArrayList list = new ArrayList(); string query = string.Format("SELECT p.id, p.name, c.name AS cname, p.price, p.image, p.description FROM products AS p INNER JOIN categories AS c ON p.cat_id = c.id WHERE p.id LIKE '{0}'", productId); try { conn.Open(); command.CommandText = query; SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); string name = reader.GetString(1); string cname = reader.GetString(2); decimal price = reader.GetDecimal(3); string image = reader.GetString(4); string description = reader.GetString(5); Products product = new Products(id, name, cname, price, image, description); list.Add(product); } } finally { conn.Close(); command.Parameters.Clear(); } return list; } #endregion #region GetShopProducts /// <summary> /// Returns all the products that are added to shoppingcart /// </summary> /// <param name="productId"></param> /// <returns></returns> public static ArrayList GetShopProducts(List<string> productId) { ArrayList list = new ArrayList(); foreach (string p in productId) { string query = string.Format("SELECT * FROM products WHERE id LIKE '{0}'", p); try { conn.Open(); command.CommandText = query; SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); string name = reader.GetString(1); int cat_id = reader.GetInt32(2); decimal price = reader.GetDecimal(3); string image = reader.GetString(4); string description = reader.GetString(5); Products product = new Products(id, name, cat_id, price, image, description); list.Add(product); } } finally { conn.Close(); command.Parameters.Clear(); } } return list; } #endregion #region GetInUseCategories /// <summary> /// Checks if a category is in use by a product and returns a bool (true or false) /// </summary> /// <param name="categoryId"></param> /// <returns></returns> public static bool GetInUseCategories(string categoryId) { string query = string.Format("SELECT COUNT(*) FROM products WHERE cat_id = '{0}'", categoryId); command.CommandText = query; try { conn.Open(); int amountOfCategorys = (int)command.ExecuteScalar(); if (amountOfCategorys > 0) // Check if category is in use { // Category in use return true; } else { // Category NOT in use return false; } } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region GetEmail /// <summary> /// Searches the e-mail in database that matches to the logged in user and returns this e-mail /// </summary> /// <param name="username"></param> /// <returns></returns> public static string GetEmail(string username) { string query = string.Format("SELECT email FROM users WHERE username = '{0}'", username); command.CommandText = query; try { conn.Open(); string dbEmail = command.ExecuteScalar().ToString(); return dbEmail; } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region GetRole /// <summary> /// Searches the role in database that matches to the logged in user and returns this role /// </summary> /// <param name="username"></param> /// <returns></returns> public static string GetRole(string username) { string query = string.Format("SELECT r.name FROM users AS u INNER JOIN roles AS r ON u.rol_id = r.id WHERE username = '{0}'", username); command.CommandText = query; try { conn.Open(); string dbRole = command.ExecuteScalar().ToString(); return dbRole; } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region AddCategory /// <summary> /// AddCategory checks if the category name is not in use, if not in use it adds a new category /// </summary> /// <param name="category"></param> /// <returns></returns> public static string AddCategory(Categories category) { string query = string.Format("SELECT COUNT(*) FROM categories WHERE name = '{0}'", category.Name); command.CommandText = query; try { conn.Open(); int amountOfCategorys = (int)command.ExecuteScalar(); if (amountOfCategorys < 1) // Check if category does NOT exist { // Category does NOT exists, create a new category query = string.Format(@"INSERT INTO categories VALUES ('{0}')", category.Name); command.CommandText = query; command.ExecuteNonQuery(); return "Categorie toegevoegd!"; } else // Category exists, return error message { return "Deze categorie bestaat al, categorie niet toegevoegd."; } } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region AddProduct /// <summary> /// AddProduct adds a new product /// </summary> /// <param name="product"></param> public static void AddProduct(Products product) { string query = string.Format( @"INSERT INTO products VALUES ('{0}', '{1}', @price, '{2}', '{3}')", product.Name, product.Cat_id, product.Image, product.Description); command.CommandText = query; command.Parameters.Add(new SqlParameter("@price", product.Price)); try { conn.Open(); command.ExecuteNonQuery(); } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region LoginUser /// <summary> /// LoginUser checks if the login credentials are correct /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public static Users LoginUser(string username, string password) { string query = string.Format("SELECT COUNT(*) FROM users WHERE username = '{0}'", username); command.CommandText = query; try { conn.Open(); int amountOfUsers = (int)command.ExecuteScalar(); if (amountOfUsers == 1) // Check if user exists { // User exists query = string.Format("SELECT password FROM users WHERE username = '{0}'", username); command.CommandText = query; string dbPassword = command.ExecuteScalar().ToString(); if (dbPassword == password) // Check if the passwords match { // Passwords match. Login and password data are known to us // Retrieve further user data from the database query = string.Format("SELECT email, rol_id FROM users WHERE username = '{0}'", username); command.CommandText = query; SqlDataReader reader = command.ExecuteReader(); Users users = null; while (reader.Read()) { string email = reader.GetString(0); int rol_id = reader.GetInt32(1); users = new Users(username, password, email, rol_id); } return users; } else { //Passwords do not match return null; } } else { //User does not exist return null; } } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region RegisterUser /// <summary> /// RegisterUser checks if the username and e-mail are unique, if so it adds the new user into database, otherwise it returns a error message /// </summary> /// <param name="users"></param> /// <returns></returns> public static string RegisterUser(Users users) { string query = string.Format("SELECT COUNT(*) FROM users WHERE username = '{0}'", users.Username); command.CommandText = query; try { conn.Open(); int amountOfUsers = (int)command.ExecuteScalar(); if (amountOfUsers < 1) // Check if user exists { // User does NOT exist query = string.Format("SELECT COUNT(*) FROM users WHERE email = '{0}'", users.Email); command.CommandText = query; int amountOfEmail = (int)command.ExecuteScalar(); if (amountOfEmail < 1) // Check if e-mail exists { // E-mail does NOT exist query = string.Format("INSERT INTO users VALUES ('{0}', '{1}', '{2}', '{3}')", users.Username, users.Password, users.Email, users.Rol_id); command.CommandText = query; command.ExecuteNonQuery(); return "Uw account (" + users.Username + ") is aangemaakt!"; } else { // E-mail exists return "Een gebruiker met dit e-mail adres bestaat al, het account is niet aangemaakt."; } } else { // User exists return "Een gebruiker met deze gebruikersnaam bestaat al, het account is niet aangemaakt."; } } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region ForgotPassword /// <summary> /// Checks if the username and e-mail match, if so it returns the password, otherwise it returns a error message /// </summary> /// <param name="username"></param> /// <param name="email"></param> /// <returns></returns> public static string ForgotPassword(string username, string email) { string query = string.Format("SELECT COUNT(*) FROM users WHERE username = '{0}'", username); command.CommandText = query; try { conn.Open(); int amountOfUsers = (int)command.ExecuteScalar(); if (amountOfUsers == 1) // Check if user exists { //User exists query = string.Format("SELECT email FROM users WHERE username = '{0}'", username); command.CommandText = query; string dbEmail = command.ExecuteScalar().ToString(); if (dbEmail == email) // Check if the e-mails match { // Username and e-mail matches query = string.Format("SELECT password FROM users WHERE username = '{0}'", username); command.CommandText = query; string password = command.ExecuteScalar().ToString(); return password; } else { // Email does not match username return "Wachtwoord is niet verzonden, e-mail komt niet overeen met de gebruikersnaam."; } } else { // User does not exist return "Wachtwoord is niet verzonden, gebruiker bestaat niet."; } } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region ChangePassword /// <summary> /// Checks if current password (by user input) matches the password that is known in database, /// if so it changes the password and returns a succes message, otherwise it returns a error message /// </summary> /// <param name="username"></param> /// <param name="Pcurrent"></param> /// <param name="Pnew"></param> /// <returns></returns> public static string ChangePassword(string username, string Pcurrent, string Pnew) { string query = string.Format("SELECT password FROM users WHERE username = '{0}'", username); command.CommandText = query; try { conn.Open(); string dbPassword = command.ExecuteScalar().ToString(); if (dbPassword == Pcurrent) // Check if passwords match { // Passwords match query = string.Format("UPDATE users SET password = '{0}' WHERE username = '{1}'", Pnew, username); command.CommandText = query; command.ExecuteNonQuery(); return "Het wachtwoord is aangepast, de volgende keer dat u inlogt moet u gebruik maken van dit nieuwe wachtwoord."; } else { // Passwords do not match return "Het huidige wachtwoord komt niet overeen."; } } finally { conn.Close(); command.Parameters.Clear(); } } #endregion #region ChangeEmail /// <summary> /// Checks if current e-mail (by user input) matches the e-mail that is known in database, /// if so it changes the e-mail and returns a succes message, otherwise it returns a error message /// </summary> /// <param name="username"></param> /// <param name="Ecurrent"></param> /// <param name="Enew"></param> /// <returns></returns> public static string ChangeEmail(string username, string Ecurrent, string Enew) { string query = string.Format("SELECT email FROM users WHERE username = '{0}'", username); command.CommandText = query; try { conn.Open(); string dbEmail = command.ExecuteScalar().ToString(); if (dbEmail == Ecurrent) // Check if e-mails match { // E- mails match query = string.Format("SELECT COUNT(*) FROM users WHERE email = '{0}'", Enew); command.CommandText = query; int amountOfEmail = (int)command.ExecuteScalar(); if (amountOfEmail < 1) // Check if new e-mail is in use { // E-mail NOT in use query = string.Format("UPDATE users SET email = '{0}' WHERE username = '{1}'", Enew, username); command.CommandText = query; command.ExecuteNonQuery(); return "Uw mail adres is aangepast!"; } else { // E-mail in use return "Het nieuwe e-mail adres is al in gebruik!"; } } else { // Emails do NOT match return "De huidige e-mail komt niet overeen!"; } } finally { conn.Close(); command.Parameters.Clear(); } } #endregion }
ee116bf9d0cadd1b6f3f383185bc42e5cba55be2
[ "C#" ]
18
C#
Roer1200/MilanovP3P
b6eb1cb7986de1091dd9fd3f85bda553b98bb4ab
cc748d908a1b6d174fd9f4ccf9b208352971ea3c
refs/heads/master
<file_sep>/* * 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 springmvc.controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import springmvc.entity.Genre; import springmvc.entity.Utilisateur; import springmvc.service.GenreCrudService; import springmvc.service.InscriptionService; import springmvc.service.UtilisateurCrudService; /** * * @author admin */ @Controller @RequestMapping(value = "/genre") public class GenreController { @Autowired GenreCrudService genreCrudService; @Autowired UtilisateurCrudService utilisateurCrudService; @Autowired InscriptionService inscriptionService; @RequestMapping(value = "home", method = RequestMethod.GET) public String home() { return "indexInit"; } @RequestMapping(value = "non_logger", method = RequestMethod.GET) public String non_logger(Model m) { m.addAttribute("monUtilisateur", new Utilisateur()); return "_non_logger"; } @RequestMapping(value = "inscription", method = RequestMethod.GET) public String inscription(Model m) { m.addAttribute("monUtilisateur", new Utilisateur()); return "inscription"; } @RequestMapping(value = "inscriptionPOST", method = RequestMethod.POST) public String inscriptionPOST(@ModelAttribute(value = "monUtilisateur") Utilisateur utilisateur) { Boolean etatInscription = inscriptionService.inscription(utilisateur); // if (etatInscription == false) { // return "inscription"; // } else { return "indexInit"; // } } @RequestMapping(value = "loginPOST", method = RequestMethod.POST) public String loginPOST(@ModelAttribute(value = "monUtilisateur") Utilisateur utilisateur, Model model) { List<Utilisateur> listeUtilisateurs = new ArrayList<>(); listeUtilisateurs = (List<Utilisateur>) utilisateurCrudService.findAll(); Boolean estLogger = false; if (!listeUtilisateurs.isEmpty()) { for (Utilisateur j : listeUtilisateurs) { if (j.getLogin().equals(utilisateur.getLogin())) { if (j.getMdp().equals(utilisateur.getMdp())) { estLogger = true; } } } } model.addAttribute("monLogin", utilisateur.getLogin()); System.out.println("11111111111111111111111111111111111111111111"+utilisateur.getLogin()); return "index"; } @RequestMapping(value = "logger", method = RequestMethod.GET) public String logger(@ModelAttribute(value = "monUtilisateur") Utilisateur utilisateur, Model model) { System.out.println("222222222222222222222222222222222222222222222"+utilisateur.getLogin()); model.addAttribute("monLogin", utilisateur.getLogin()); return "_logger"; } @RequestMapping(value = "lister", method = RequestMethod.GET) public String lister(Model model) { Iterable<Genre> listeGenre = genreCrudService.findAll(); model.addAttribute("maListe", listeGenre); return "genre_lister"; } @RequestMapping(value = "genre_ajouter", method = RequestMethod.GET) public String ajouter(Model model) { model.addAttribute("monGenre", new Genre()); return "genre_ajouter"; } @RequestMapping(value = "ajouterPOST", method = RequestMethod.POST) public String ajouter(@ModelAttribute(value = "monGenre") Genre g) { genreCrudService.save(g); return "redirect:/genre/lister"; } @RequestMapping(value = "genre_modifier/{idGenre}", method = RequestMethod.GET) public String modifier(@PathVariable(value = "idGenre") long id, Model model) { Genre g = genreCrudService.findOne(id); model.addAttribute("monGenre", g); return "genre_modifier"; } @RequestMapping(value = "genre_modifier/{idGenre}", method = RequestMethod.POST) public String modifierPOST(@ModelAttribute(value = "monGenre") Genre g) { genreCrudService.save(g); return "redirect:/genre/lister"; } @RequestMapping(value = "genre_supprimer/{idGenre}", method = RequestMethod.GET) public String supprimer(@PathVariable(value = "idGenre") long id) { Genre g = genreCrudService.findOne(id); genreCrudService.delete(g); return "redirect:/genre/lister"; } } <file_sep>/* * 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 springmvc.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; /** * Entité gérant les films * Je suis passé par la ! Arthur * @author admin */ @Entity public class Film implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToMany(mappedBy = "quel_film") private List<Lien> liens = new ArrayList<>(); @ManyToOne @JoinColumn(name = "ID_GENRE") private Genre genre; @ManyToOne @JoinColumn(name = "ID_PAYS") private Pays pays; @ManyToMany @JoinTable(name = "film_realisateur") private List<Realisateur> createurs = new ArrayList<>(); private String titre; private String sinopsis; private Long anneeProd; public Film() { } public Film(Genre genre, Pays pays, String titre, String sinopsis, Long anneeProd) { this.genre = genre; this.pays = pays; this.titre = titre; this.sinopsis = sinopsis; this.anneeProd = anneeProd; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<Lien> getLiens() { return liens; } public void setLiens(List<Lien> liens) { this.liens = liens; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } public Pays getPays() { return pays; } public void setPays(Pays pays) { this.pays = pays; } public List<Realisateur> getCreateurs() { return createurs; } public void setCreateurs(List<Realisateur> createurs) { this.createurs = createurs; } public String getTitre() { return titre; } public void setTitre(String titre) { this.titre = titre; } public String getSinopsis() { return sinopsis; } public void setSinopsis(String sinopsis) { this.sinopsis = sinopsis; } public Long getAnneeProd() { return anneeProd; } public void setAnneeProd(Long anneeProd) { this.anneeProd = anneeProd; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Film)) { return false; } Film other = (Film) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "streaming.entity.Film[ id=" + id +" nom="+titre+" ]"; } } <file_sep>//function afficheSablier(){ // $('img').show(); //} // //function clicSurBouton(){ // afficheSablier(); // $('#contenu').load('_contenu.html') // cacheSablier(); //} // //function cacheSablier(){ // $('img').hide(); //} // //function sablier(){ // $('img').fadeToggle(); //} // function init(){ $('#logger').load('non_logger'); } // function inscription(){ $('#non_logger').load('inscription'); // $('#logger').load('inscription'); } // function logger(){ $('#logger').load('logger'); } // //function logout(){ // $('#logger').load('LogoutServlet'); // $('#logger').load('_non_logger.jsp'); //} // // //function nouvellePartie(){ // $('#contenu').load('lister'); //} // //function partiesEnCours(){ // $('#contenu').load('_partiesEnCours.jsp'); //}
f0350932cd8d56d28b2ac0c09a8642a4858ed763
[ "JavaScript", "Java" ]
3
Java
tbaudrey/springmvc
8051cf68fb8cd83d2da0908e49abdd9d1bb54711
6fb4c129bfa2958788fe9cfbd6b21f928220cb33
refs/heads/master
<file_sep># Python program to illustrate the concept # of threading import threading, os, copy from pprint import pprint from pgm import pgmread, pgmwrite import numpy as np def __extrair_imax(imagem): return int(imagem[0].astype(np.float).max()) def __extrair_imin(imagem): return int(imagem[0].astype(np.float).min()) def alargamento_contraste(imagem): print("Executando a thread: {}".format(threading.current_thread().name)) nova_imagem = np.zeros((480, 640)) imax = __extrair_imax(imagem) imin = __extrair_imin(imagem) for x in range(len(imagem[0])): for y in range(len(imagem[0][x])): processamento = (255/(imax - imin)) * (imagem[0][x][y].astype(np.int) - imin) nova_imagem[x][y] = round(processamento) pgmwrite(nova_imagem, 'alargamento_final.pgm') def __calcular_histograma(imagem): h = np.zeros(256) for x in range(len(imagem[0])): for y in range(len(imagem[0][x])): h[imagem[0][x][y].astype(np.int)] += 1 return h def __calcular_probabilidade_ocorrencia(h): p = np.zeros(256) for i in range(256): p[i] = h[i] / (480 * 640) return p def __calcular_probabilidade_acumulada(p): q = np.zeros(256) for i in range(256): cont = 0 for j in range(i): cont = cont + p[j] q[i] = cont return q def equalizacao_histograma(imagem): print("Executando a thread: {}".format(threading.current_thread().name)) h = __calcular_histograma(imagem) p = __calcular_probabilidade_ocorrencia(h) q = __calcular_probabilidade_acumulada(p) nova_imagem = np.zeros((480, 640)) for x in range(len(imagem[0])): for y in range(len(imagem[0][x])): nova_imagem[x][y] = round(255* q[imagem[0][x][y].astype(np.int)]) pgmwrite(nova_imagem, 'equalizacao_histograma.pgm') if __name__ == "__main__": img_original = pgmread('balloons.ascii.pgm') # deepcopy para evitar condição de corrida img_tratamento_1 = copy.deepcopy(img_original) img_tratamento_2 = copy.deepcopy(img_original) # criando threads t1 = threading.Thread(target=alargamento_contraste, name='alargamento', args=(img_tratamento_1,)) t2 = threading.Thread(target=equalizacao_histograma, name='equalização', args=(img_tratamento_2,)) # inicio das execuções t1.start() t2.start() # esperando até o final da execução t1.join() t2.join() <file_sep> from numpy import array, int32 def pgmread(filename): """ This function reads Portable GrayMap (PGM) image files and returns a numpy array. Image needs to have P2 or P5 header number. Line1 : MagicNum Line2 : Width Height Line3 : Max Gray level Lines starting with # are ignored """ f = open(filename, 'r') # Read header information count = 0 while count < 3: line = f.readline() if line[0] == '#': # Ignore comments continue count = count + 1 if count == 1: # Magic num info magicNum = line.strip() if magicNum != 'P2' and magicNum != 'P5': f.close() print('Not a valid PGM file') exit() elif count == 2: # Width and Height [width, height] = (line.strip()).split() width = int(width) height = int(height) elif count == 3: # Max gray level maxVal = int(line.strip()) # Read pixels information img = [] buf = f.read() elem = buf.split() if len(elem) != width*height: print('Error in number of pixels') exit() for i in range(height): tmpList = [] for j in range(width): tmpList.append(elem[i*width+j]) img.append(tmpList) return (array(img), width, height) def pgmwrite(img, filename, maxVal=255, magicNum='P2'): """ This function writes a numpy array to a Portable GrayMap (PGM) image file. By default, header number P2 and max gray level 255 are written. Width and height are same as the size of the given list. Line1 : MagicNum Line2 : Width Height Line3 : Max Gray level Image Row 1 Image Row 2 etc. """ img = int32(img).tolist() f = open(filename, 'w') width = 0 height = 0 for row in img: height = height + 1 width = len(row) f.write(magicNum + '\n') f.write(str(width) + ' ' + str(height) + '\n') f.write(str(maxVal) + '\n') for i in range(height): count = 1 for j in range(width): f.write(str(img[i][j]) + ' ') if count >= 17: # No line should contain gt 70 chars (17*4=68) # Max three chars for pixel plus one space count = 1 f.write('\n') else: count = count + 1 f.write('\n') f.close()
c48fb5d6db70b37f9edb9fc6aef859152b1be9d6
[ "Python" ]
2
Python
Trunkol/DCA0108-threads
c9a728c34edc27f5b00667b92549466531b0fa83
99bac067631ef124deea63e5df7f4de0610ce2b7
refs/heads/master
<repo_name>anlapier91/Project1<file_sep>/our-js/beersearch.js $(document).ready(function() { $(".modal").modal(); $(document).ready(function() { $(".parallax").parallax(); }); $("#find-beer").on("click", function(event) { event.preventDefault(); var beer = $("#beer-input").val(); // var food = $("#food-input").val(); console.log("beer = " + beer); if (beer === "") { var queryURL = "https://api.punkapi.com/v2/beers/?page=2&per_page=60&" + beer; console.log("no beer entered but here's a random beer " + beer); } else { var queryURL = "https://api.punkapi.com/v2/beers/?beer_name=" + beer; console.log("user chosen beer " + beer); $("#beer-input").empty(); } $.ajax({ url: queryURL, method: "GET" }).done(function(response) { console.log(response); for (var i = 0; i < response.length; i++) { var beerName = response[i].name; var beerTagline = response[i].tagline; var beerDescription = response[i].description; var beerImage = response[i].image_url; var beerAbv = response[i].abv; var beerFood = response[i].food_pairing; console.log("Foods are in an array " + beerFood); beerFood = beerFood.toString(); beerFood = beerFood.split(",").join(", "); //if we remove index, beerFood is now an array. //This means to diplay all foods we need a separate loop and some separate Jquery insode that loop //then we need to also get that into the modal, and we have packed it as a value in the data-food attribute //however, again, since it's an array, when you deal with it in the new modal, you may have to loop again var malt = response[i].ingredients.malt; var hops = response[i].ingredients.hops; var yeast = response[i].ingredients.yeast; var beerBrewed = response[i].first_brewed; var beerBrewery = response[i].withBreweries; var beerOrganic = response[i].isOrganic; var convertSearchterm = JSON.stringify(response); // for (var j = 0; j < malt.length; j++) { // console.log( "ingredient " + malt[i].name + "value: " + malt[i].amount.value + "unit: " + malt[i].amount.unit) // } // for (var k = 0; k < hops.length; k++) { // console.log( "ingredient " + hops[i].name + "value: " + hops[i].amount.value + "unit: " + hops[i].amount.unit) // } // for (var m = 0; m < yeast.length; m++) { // console.log( "ingredient " + yeast) // } var beerCard = $("<li>").css("display", "inline-flex", "float", "relative"); var beerContent = $("<div>").css("width", "250px", "height", "250px"); beerCard.addClass("collection-item").css("margin", "auto"); beerContent .addClass("card-content gray-text") .css("padding", "10px", "overflow", "hidden"); beerContent.attr("data-name", beerName); beerContent.attr("data-describe", beerDescription); beerContent.attr("data-abv", beerAbv); beerContent.attr("data-year", beerBrewed); beerContent.attr("data-food", beerFood); var cardSpan = $("<span>"); cardSpan.addClass("card-title"); cardSpan.append("<i>" + beerTagline) .css({ color: "#1C1C1C", margin: "auto", padding: "5px" }); var cardText = $("<p>"); cardText.addClass("card-text"); cardSpan.html(beer); var cardImage = $("<img>"); cardImage.addClass("card-image"); cardImage.css({ height: "250px", display: "block", margin: "auto", padding: "8px" }); cardImage.attr("src", beerImage); cardText.append(cardImage); cardSpan.addClass("card-title").text(beerName); beerContent .prepend(cardSpan) .append("<i>" + beerTagline) .css({ color: "#a8a4b0", margin: "auto", padding: "5px" }); // var foodIcon = $("<i>").addClass("material-icons").text("add"); // cardText.append(foodIcon + "Great with: " + beerFood + "<br>").attr("material-icons", "local_dining"); beerContent.append(cardText); beerCard.append(beerContent); var dynamicCard = $("#list-stuff"); $("#list-stuff").append(beerCard); beerCard.addClass("card").css("margin", "5px", "float", "relative"); // var beerRow = $("<div>"); // beerRow.addClass("row").append(dynamicCard); //module trigger and adding the card classes var trigger = $("<button>"); trigger.addClass("waves-effect waves-light btn"); trigger.attr("id", "trigger"); trigger.attr("data-target", "modal1"); trigger .text("More Info") .css({ display: "block", margin: "auto" }); beerContent.append(trigger); $(".card").on("click", "button", function(event) { var dataName = $(this) .parent() .attr("data-name"); var dataDescribe = $(this) .parent() .attr("data-describe"); var dataAbv = $(this) .parent() .attr("data-abv"); var dataYear = $(this) .parent() .attr("data-year"); var dataFood = $(this) .parent() .attr("data-food"); console.log("back of card beer " + dataName); $("#modal1").modal("open"); $("#modal-header").html(dataName); $("#modal-body").html( dataDescribe + " " + "<hr>" + dataAbv + "%" + "<hr>" + "First Brewed on " + dataYear + "<hr>" + "Goes best with " + dataFood + "<hr>" ); $("#food-input").val(dataFood); // NEED TO APPEND THIS to the Container before the beer div <div id="modal1" class="modal modal-fixed-footer"> // <div class="modal-content"> // <h4>Modal Header</h4> // <p>A bunch of text</p> // </div> // <div class="modal-footer"> // <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat "><i class="material-icons">close</i>Close</a> // </div> // </div> }); $("#find-food").on("click", function(event) { event.preventDefault(); //now we've packed food array into value var food = $("#food-input").val(); //loop through array to make dropdown food = food.toString(); food = food.split(/[ ,]+/); console.log("Food carried over: " + food); var proxy = "https://cors-anywhere.herokuapp.com/"; var queryURL = "https://food2fork.com/api/search?key=f18f20279482aabaea4a0d26c8810819&q=" + food; $.ajax({ url: proxy + queryURL, method: "GET" }).done(function(response) { console.log(response); console.log("hi"); var res = JSON.parse(response); var recipes = res.recipes; var count = res.count; console.log(count); if (count === 0) { //alert("try again") console.log("inside count === 0"); var noResults = $("<div>"); noResults.text("Try Again"); $("#food-view").append(noResults); } else { for (var i = 0; i < recipes.length; i++) { var foodPublisher = recipes[i].publisher; var foodTitle = recipes[i].title; var foodSourceURL = recipes[i].source_url; var foodImage = recipes[i].image_url; // var foodDiv = $("#food-view"); var listItem = $("<li>"); listItem.addClass("food-item"); listItem.append( "<h3>" + foodTitle + "</h3>" + "<hr>" + "PUBLISHER: " + foodPublisher + "<hr>" // + "DESCRIPTION: " + foodSourceURL + "<hr>" ); var source = $("<a>"); source.addClass("source"); source.text( "Click here to get recipes for: " + foodTitle ); source.attr("href", foodSourceURL); var image = $("<img>"); image.addClass("food-image"); image.attr("src", foodImage); listItem.append(image); listItem.append(source); $("#food-view").append(listItem); } } }); }); } }); }); });
4d5b8f73b66a49588e8377c385f51847df93d16d
[ "JavaScript" ]
1
JavaScript
anlapier91/Project1
9b117187dd9cba26e82cfafa90bbbf95c191335a
3f8435d026c2ae5dfae8932fcbf76071fca11bbe
refs/heads/master
<file_sep>namespace t { let node = new Node(); node.children = [new Node(), new Node()]; node.alpha = 0.5; node.children[0].alpha = 0.5; console.assert(node.children[0].worldAlpha === 0.25); console.assert(node.children[1].worldAlpha === 0.5); node.visible = false; console.assert(node.children[0].worldVisible === false); console.assert(node.children[1].worldVisible === false); }<file_sep>namespace t { export class Container { get parent() { return this._parent; } set parent(v) { if (this._parent === v) { return; } this._parent = v; this._parentChanged(); } protected _parent?: Container; protected _parentChanged() { } get children() { return this._children; } set children(v) { if (this._children) { for (let i = 0; i < this._children.length; i++) { this._children[i].parent = undefined; } } this._children = v; if (this._children) { for (let i = 0; i < this._children.length; i++) { this._children[i].parent = this; } } this._childrenChanged(); } protected _children?: Container[]; protected _childrenChanged() { } } } <file_sep>namespace t { export class Node { constructor() { this._children = []; this._alpha = 1; this._worldAlpha = 1; this._visible = true; this._worldVisible = true; } } export interface Node extends NodeAlpha, NodeVisible, Container { parent: Node; children: Node[]; } applyMixins(Node, [NodeAlpha, NodeVisible, Container]); } <file_sep>namespace t { export class NodeVisible { parent?: NodeVisible; children: NodeVisible[] = []; get visible() { return this._visible; } set visible(v) { if (this._visible === v) { return; } this._visible = v; this._updateVisibleChanged(); } protected _visible: boolean = true; protected _updateVisibleChanged() { this._updateWorldVisible(); } get worldVisible() { return this._worldVisible; } protected _worldVisible: boolean = true; protected _updateWorldVisible(updateChildren = true) { this._worldVisible = this._visible && (this.parent ? this.parent._worldVisible : true); if (updateChildren && this.children) { for (let i = 0; i < this.children.length; i++) { this.children[i]._updateWorldVisible(); } } } } }<file_sep>{ "compilerOptions": { "target": "es5", "sourceMap": true, "strict": true, "outFile": "./dist/index.js" }, "files": [ "./src/applyMixins.ts", "./src/Container.ts", "./src/NodeAlpha.ts", "./src/NodeVisible.ts", "./src/Node.ts", "./src/index.ts", ] }<file_sep>namespace t { export class NodeAlpha { parent?: NodeAlpha; children: NodeAlpha[] = []; get alpha() { return this._alpha; } set alpha(v) { if (this._alpha === v) { return; } this._alpha = v; this._updateAlphaChanged(); } protected _alpha: number = 1; protected _updateAlphaChanged() { this._updateWorldAlpha(); } get worldAlpha() { return this._worldAlpha; } protected _worldAlpha: number = 1; protected _updateWorldAlpha(updateChildren = true) { this._worldAlpha = this._alpha * (this.parent ? this.parent._worldAlpha : 1); if (updateChildren && this.children) { for (let i = 0; i < this.children.length; i++) { this.children[i]._updateWorldAlpha(); } } } } }
37c27fe12023a0c47258ea6ebb5841cc8a4a6ef2
[ "TypeScript", "JSON with Comments" ]
6
TypeScript
wardenfeng/test-node-alpha-transform
8ec770c6c06051718fd431be078b7f7722e54447
9709dafb112f0874c9380986398c62161054a8c6
refs/heads/master
<repo_name>mzegarras/AMA<file_sep>/LabLista/src/net/msonic/lablista/ClienteTO.java package net.msonic.lablista; public class ClienteTO { public String Nombres; public String Apellidos; public int Edad; public String FechaNacimiento; } <file_sep>/README.md Android Mobile Application - Laboratorio de Clases <NAME> referencia: http://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder
234e2f8586936178b15e455c417d306ab75d83d1
[ "Markdown", "Java" ]
2
Java
mzegarras/AMA
278ea1c7313828e1e250388763d9e7c253c92b30
277983ab70fd0c2a2ced666e0b1e1cdf81e9abe7
refs/heads/master
<repo_name>benmc17/web-server<file_sep>/src/main/java/uk/co/bpm/webserver/http/HttpGeneralHeader.java package uk.co.bpm.webserver.http; public class HttpGeneralHeader { } <file_sep>/src/main/java/uk/co/bpm/webserver/logging/Logger.java package uk.co.bpm.webserver.logging; public interface Logger { public void info(String message); public void error(String message); public void error(String message, Exception ex); public void trace(String message); public void debug(String message); public void out(String message); } <file_sep>/src/main/java/uk/co/bpm/webserver/http/HttpProtocol.java package uk.co.bpm.webserver.http; import uk.co.bpm.webserver.http.request.HttpRequest; import uk.co.bpm.webserver.protocol.Protocol; import uk.co.bpm.webserver.protocol.ProtocolException; public class HttpProtocol implements Protocol { private HttpMessageParser requestParser; public HttpProtocol(HttpMessageParser requestParser) { this.requestParser = requestParser; } @Override public byte[] processEvent(byte[] data) throws ProtocolException { try { HttpRequest request = (HttpRequest) requestParser.parse(data); HttpContext context = new HttpContext(); } catch(HttpException e) { } return null; } } <file_sep>/src/main/java/uk/co/bpm/webserver/http/HttpMessageParser.java package uk.co.bpm.webserver.http; public interface HttpMessageParser { public HttpMessage parse(byte[] httpPacket) throws HttpException; } <file_sep>/src/main/java/uk/co/bpm/webserver/protocol/Protocol.java package uk.co.bpm.webserver.protocol; public interface Protocol { byte[] processEvent(byte[] data) throws ProtocolException; } <file_sep>/src/main/java/uk/co/bpm/webserver/protocol/ProtocolFactory.java package uk.co.bpm.webserver.protocol; import uk.co.bpm.webserver.WebServerException; import uk.co.bpm.webserver.http.HttpMessageParser; import uk.co.bpm.webserver.http.HttpProtocol; import uk.co.bpm.webserver.https.HttpsProtocol; public class ProtocolFactory { public ProtocolFactory() {} public Protocol createProtocol(ProtocolType type, HttpMessageParser requestParser) throws WebServerException { switch(type) { case HTTP: return new HttpProtocol(requestParser); case HTTPS: return new HttpsProtocol(); default: throw new WebServerException("Unrecognised Protocol: "); } } } <file_sep>/src/main/java/uk/co/bpm/webserver/http/HttpMessage.java package uk.co.bpm.webserver.http; import java.util.Map; public abstract class HttpMessage { private final Map<String, String> headers; private final long contentLength; private final String messageBody; public HttpMessage(Map<String, String> headers) { this(headers, -1, null); } public HttpMessage(Map<String, String> headers, long contentLength, String messageBody) { this.headers = headers; this.contentLength = contentLength; this.messageBody = messageBody; } public String getMessageBody() { return messageBody; } public long getContentLength() { return contentLength; } public String getHeaderValue(String headerKey) { return headers.get(headerKey); } } <file_sep>/src/main/java/uk/co/bpm/webserver/http/request/impl/HttpRequestParserImpl.java package uk.co.bpm.webserver.http.request.impl; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.Map; import uk.co.bpm.webserver.http.HttpConstants; import uk.co.bpm.webserver.http.HttpException; import uk.co.bpm.webserver.http.HttpGeneralHeader; import uk.co.bpm.webserver.http.HttpMethod; import uk.co.bpm.webserver.http.impl.AbstractHttpMessageParser; import uk.co.bpm.webserver.http.request.HttpRequest; import uk.co.bpm.webserver.logging.Logger; public class HttpRequestParserImpl extends AbstractHttpMessageParser { private final Logger logger; public HttpRequestParserImpl(Logger logger) { this.logger = logger; } @Override public HttpRequest parse(byte[] httpPacket) throws HttpException { // Section 5 - Request try(ByteArrayInputStream bais = new ByteArrayInputStream(httpPacket); BufferedReader in = new BufferedReader(new InputStreamReader(bais))) { // Section 5.1 - Parse Request Line HttpMethod method = getMethod(parseSection(in)); String requestURIStr = parseSection(in); URI requestURI = null; if(!requestURIStr.equals("*")) { requestURI = getRequestURI(requestURIStr); } String httpVersion = parseSection(in); // skip last LF (Line Feed) in.skip(1); // Section 4.5, Section 5.3, Section 7.1 Map<String, String> headers = this.parseHeaders(in); // CRLF - CRLF in.skip(4); String contentLength = headers.get(HttpConstants.HTTP_HEADER_CONTENT_LENGTH); String transferEncoding = headers.get(HttpConstants.HTTP_HEADER_TRANSFER_ENCODING); String content = null; long contentBytes = -1; if(transferEncoding != null && !transferEncoding.equals("identity")) { //TODO: ignore content length } else if(contentLength != null) { // Section 4.3 - Parse Message Body contentBytes = Long.parseLong(contentLength); content = parseMessageBody(in, contentBytes); } HttpGeneralHeader generalHeader = new HttpGeneralHeader(); return new HttpRequest(headers, contentBytes, content, method, requestURI, requestURIStr, httpVersion, generalHeader); } catch(IOException e) { throw new HttpException("Error parsing HTTP request, it could be an invalid message.", e); } } private HttpMethod getMethod(String method) throws HttpException { try { return Enum.valueOf(HttpMethod.class, method); } catch(Exception e) { throw new HttpException("Invalid HTTP 1.1 Method Specified", e); } } private URI getRequestURI(String requestURI) throws HttpException { try { return URI.create(requestURI); } catch(Exception e) { throw new HttpException("Invalid HTTP 1.1 Request URI Specified", e); } } private String parseSection(BufferedReader in) throws IOException { char c; StringBuilder builder = new StringBuilder(); while((c = (char) in.read()) != -1) { if(c == 32 || c == 13) break; builder.append(c); } return builder.toString(); } private String parseMessageBody(BufferedReader in, long contentLength) throws IOException { char c; StringBuilder builder = new StringBuilder(); for(int i = 0; i < contentLength; i++) { builder.append((char) in.read()); } return builder.toString(); } } <file_sep>/src/main/java/uk/co/bpm/webserver/http/HttpConstants.java package uk.co.bpm.webserver.http; public class HttpConstants { public static final String HTTP_HEADER_CONTENT_LENGTH = "Content-Length"; public static final String HTTP_HEADER_TRANSFER_ENCODING = "Transfer-Encoding"; } <file_sep>/src/main/java/uk/co/bpm/webserver/impl/WebServerProcessImpl.java package uk.co.bpm.webserver.impl; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.spi.SelectorProvider; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import uk.co.bpm.webserver.WebServerException; import uk.co.bpm.webserver.WebServerProcess; import uk.co.bpm.webserver.logging.Logger; import uk.co.bpm.webserver.workers.WebServerWorkerPool; public class WebServerProcessImpl implements WebServerProcess { private final InetAddress hostAddress; private final int port; private final Logger logger; private final Selector selector; private final ServerSocketChannel serverChannel; private final ByteBuffer readBuffer; private final WebServerWorkerPool workerPool; private final Queue<WebServerChangeRequest> changeRequests = new LinkedList<WebServerChangeRequest>(); private final Map<SocketChannel, Queue<ByteBuffer>> pendingData = new HashMap<SocketChannel, Queue<ByteBuffer>>(); private boolean running = true; public WebServerProcessImpl(WebServerWorkerPool workerPool, int port, Logger logger) throws WebServerException { this(workerPool, null, port, logger, -1); } public WebServerProcessImpl(WebServerWorkerPool workerPool, InetAddress hostAddress, int port, Logger logger) throws WebServerException { this(workerPool, hostAddress, port, logger, -1); } public WebServerProcessImpl(WebServerWorkerPool workerPool, InetAddress hostAddress, int port, Logger logger, int readBufferSize) throws WebServerException { this.hostAddress = hostAddress; this.port = port; this.logger = logger; this.workerPool = workerPool; if(readBufferSize <= 0) { readBufferSize = 8192; } this.readBuffer = ByteBuffer.allocate(readBufferSize); try { this.serverChannel = ServerSocketChannel.open(); this.selector = createSelector(); } catch(IOException e) { throw new WebServerException("Error creating WebServer", e); } } @Override public void run() { logger.out("Starting server.."); if(!this.workerPool.isRunning()) { logger.error("Could not start server, worker pool has not been started."); return; } while(running) { try { logger.trace("Waiting..."); synchronized(this.changeRequests) { Iterator<WebServerChangeRequest> requests = this.changeRequests.iterator(); while(requests.hasNext()) { WebServerChangeRequest change = requests.next(); if(change.type == WebServerChangeRequest.CHANGEOPS) { SelectionKey key = change.socket.keyFor(this.selector); key.interestOps(change.ops); } } this.changeRequests.clear(); } this.selector.select(); logger.trace("Attempted Connection"); Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator(); while(selectedKeys.hasNext()) { SelectionKey key = selectedKeys.next(); selectedKeys.remove(); if (!key.isValid()) { continue; } if(key.isAcceptable()) { this.accept(key); } else if(key.isReadable()) { this.read(key); } else if(key.isWritable()) { this.write(key); } } } catch(Exception e) { logger.error("An unexpected error has occurred.", e); } } } @Override public void send(SocketChannel socket, byte[] data) { logger.debug("Sending data..."); synchronized(this.changeRequests) { this.changeRequests.add(new WebServerChangeRequest(socket, WebServerChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE)); synchronized(this.pendingData) { Queue<ByteBuffer> dataQueue = this.pendingData.get(socket); if(dataQueue == null) { dataQueue = new LinkedList<ByteBuffer>(); this.pendingData.put(socket, dataQueue); } dataQueue.add(ByteBuffer.wrap(data)); } } this.selector.wakeup(); } @Override public synchronized void stop() { running = false; } private void write(SelectionKey key) throws IOException { SocketChannel sc = (SocketChannel) key.channel(); synchronized(this.pendingData) { Queue<ByteBuffer> dataQueue = this.pendingData.get(sc); while(!dataQueue.isEmpty()) { ByteBuffer buf = dataQueue.peek(); sc.write(buf); if(buf.remaining() > 0) { break; } dataQueue.remove(); } if(dataQueue.isEmpty()) { key.interestOps(SelectionKey.OP_READ); } } } private void accept(SelectionKey key) throws IOException { logger.debug("Accepting connection..."); ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); //Socket socket = socketChannel.socket(); sc.configureBlocking(false); sc.register(this.selector, SelectionKey.OP_READ); } private void read(SelectionKey key) throws WebServerException { SocketChannel sc = (SocketChannel) key.channel(); this.readBuffer.clear(); //TODO: chunking packets of over buffer size!! int readCount; try { try { readCount = sc.read(this.readBuffer); logger.trace("Reading"); } catch(IOException e) { key.cancel(); sc.close(); return; } if(readCount == -1) { key.channel().close(); key.cancel(); return; } this.workerPool.handOffToWorker(sc, this.readBuffer.array(), readCount); } catch(IOException e) { throw new WebServerException("An error has occurred processing OP_READ key", e); } } private Selector createSelector() throws IOException { Selector selector = SelectorProvider.provider().openSelector(); this.serverChannel.configureBlocking(false); InetSocketAddress isa = null; if(this.hostAddress == null) { isa = new InetSocketAddress("localhost", this.port); } else { isa = new InetSocketAddress(this.hostAddress, this.port); } this.serverChannel.socket().bind(isa); this.serverChannel.register(selector, SelectionKey.OP_ACCEPT); return selector; } } <file_sep>/src/main/java/uk/co/bpm/webserver/WebServerProcess.java package uk.co.bpm.webserver; import java.nio.channels.SocketChannel; public interface WebServerProcess extends Runnable { public void stop(); public void send(SocketChannel socket, byte[] data); }
92d6fd244360a94679a477957916566b1ba61291
[ "Java" ]
11
Java
benmc17/web-server
561583970a1118a018b8be697c1faf977e5cabb7
68911e22592961254a077ec011e4d8a61de77e60
refs/heads/master
<file_sep># Blanks A mobile application game. This is an old project, I intend to update this with best practices as it's a bit hacky. <file_sep>// JavaScript Document /* word types */ var male = ['a male name', '<NAME>, <NAME>']; var female = ['a female name', '<NAME>, <NAME>']; var activity = ['an activity', 'fishing, sailing, golf']; var adjective = ['a describing word', 'giant, flexible, annoying']; var animal = ['an animal', 'cat, ant, human']; var animals = ['animals', 'cats, ants, humans']; var attribute = ['a personal attribute', 'pretty, old, intelligent']; var bodyfluid = ['a bodily fluid', 'blood, sweat, tears']; var bodypart = ['a body part', 'arm, heart, nose'] var bodyparts = ['body parts (plural)', 'arms, hearts, noses']; var clothing = ['an item of clothing', 'socks, jeans, t-shirt']; var container = ['a container', 'box, case, chest']; var destination = ['a destination', 'chip shop, beach, supermarket']; var emotion = ['an emotion', 'happy, sad, heartbroken']; var events = ['an event', 'charity ball, concert, pub crawl']; var fate = ['a fate', 'die, burn, thrive']; var job = ['a job', 'nurse, postman, receptionist']; var label = ['a persons label', 'chav, hero, idiot']; var liquid = ['a liquid', 'water, coke, oil']; var movementPast = ['movement (past tense)', 'walked, flew, drifted']; var movementPresent = ['movement (present tense)', 'walking, flying, floating']; var noun = ['a noun', 'dog, man, coffee, chair']; var nouns = ['plural noun', 'dogs, women, chairs']; var number = ['a number', '5, 21, 594']; var object = ['an object', 'pencil, cabbage, rock']; var objects = ['objects (plural)', 'tables, eggs, pebbles']; var rand = ['wildcard (anything goes)', '?']; var rands = ['plural wildcard (anything goes)', '?']; var reactionPast = ['a reaction (past tense)', 'cried, cheered, booed']; var shop = ['a type of shop', 'chip, bike, retail']; var speechPast = ['speech (past tense)', 'said, yelled, roared']; var town = ['a village, town or city name', 'London, Paris, Farmville']; var transport = ['mode of transport', 'flying, canoeing, driving']; var vehicle = ['a vehicle', 'car, bus, rowing boat']; var verb = ['an action', 'scare, punch, kiss']; var verbPast = ['an action (past tense)', 'scared, smashed, kissed']; var verbPresent = ['an action (present tense)', 'scares, smashes, kisses']; /* categories */ const categories = [{ title: 'Starter Pack', owned: 1 }, { title: 'Pack One', owned: 0 }]; /* stories */ const stories = [{ title: 'A bad day', text: `NAME realised he had run out of XXX, so decided to walk to the shop before going to his job as a XXX. Unfortunately, he had forgotten his XXX, and didn\'t realise until he had trod in a XXX pile of XXX XXX whilst XXX down the road. He had no choice but to carry on to the local XXX shop, where the XXX shopkeeper handed him a XXX to clean his XXX.`, words: [objects, job, object, adjective, animal, bodyfluid, movementPresent, shop, adjective, object, clothing], names: [male], category: 0 },{ title: 'The Delivery', text: `On a bright, XXX morning, NAME opened his front door to find someone had left a XXX on his doorstep during the night. He frantically opened it to find that inside was a XXX and attached was a note reading \"this used to be your fathers, use it to clean your XXX\". The boy felt very XXX, and decided to ignore the note, choosing instead to use the object as a case for his XXX.`, words: [adjective, object, container, object, object, emotion, object], names: [male], category: 0 },{ title: 'Short stories', text: `Every day, NAME uses her XXX mind to create short stories for her local XXX. She drinks lots of XXX so that she can think of the XXX stories to tell the local children who sadly do not have XXX. Unfortunately for them, she isn\'t a very XXX person, as she also likes to try and XXX the children by showing them her XXX.`, words: [adjective, events, liquid, adjective, nouns, attribute, verb, noun], names: [female], category: 0 },{ title: 'Pensioners Secret', text: `In a small, XXX town called XXX, an XXX lady lives in a creepy cottage covered in XXX. She can often be seen standing at her bedroom window, looking out at the locals whilst wearing her dirty XXX and holding her XXX. Unbeknownst to the locals, this old and XXX lady does take some pride in her appearance, and once a year takes a holiday via XXX to the XXX where she takes part in a competition for best dressed XXX.`, words: [adjective, town, attribute, objects, clothing, object, attribute, vehicle, destination, noun], names: [], category: 0 },{ title: 'Muggers!', text: `On his way home late at night, NAME encountered some scary looking XXX. He cowered at the size of their XXX which looked like XXX against the backdrop. As he XXX past, the XXX one of them squared up to him and XXX, “Give me all your XXX”. The boy yelped in terror as he frantically reached into his pocket and clasped the one thing he knew would protect him - his trusty XXX.`, words: [animals, bodyparts, objects, movementPast, adjective, speechPast, objects, object], names: [male], category: 0 },{ title: 'Not all heroes wear capes', text: `It was a day like any other on the 50th floor of the office until a XXX noticed that one of the window cleaners was dangling by his fingertips from his platform without a safety harness. No one knew what had happened but one thing was for sure, he sure was XXX. <br><br>There was much commotion in the building at this point as people frantically tried to figure a way to save the XXX man, but then they saw it. Was it a bird? Was it a plane? No it was NAME the XXX superhero coming to save the day. <br><br>He XXX in and XXX the window cleaner from the platform and they floated gracefully to the ground below, the man XXX his XXX onto the sidewalk as the onlooking crowd XXX, what a XXX.`, words: [job, adjective, adjective, adjective, movementPast, verbPast, verbPast, bodypart, reactionPast, label], names: [male], category: 0 },{ title: 'A day in the sun', text: `It was the perfect day for XXX, the sun was shining - not a cloud in the sky. NAME and NAME had just started when they realised that neither of them had brought any XXX, they were surely going to XXX! Because of this they spent the rest of the day hiding under a friend's XXX which was just big enough to shelter them from the intense midday heat, whilst taking sips of XXX from Barry’s XXX to stay hydrated.`, words: [activity, noun, fate, noun, liquid, container], names: [male, female], category: 0 },{ title: 'Life\'s a beach', text: `The beach was XXX on a XXX bank holiday monday, this didn’t bother NAME who was more concerned about the XXX inflatable XXX that someone had placed right in the way of his perfect view of the vast XXX sea. “That’s it” he XXX as he XXX to his feet, before strolling over and proceeding to strangle the lifeless bit of plastic until every last bit of air had been removed. The owner, a XXX XXX, burst into XXX which didn’t seem to phase the man who simply returned to his spot, cracked open a XXX and beamed at the much improved view ahead of him.`, words: [adjective, adjective, adjective, noun, adjective, speechPast, movementPast, adjective, animal, liquid, noun], names: [male], category: 0 },{ title: 'TEST', text: 'TEST XXX NAME', words: [noun], names: [male], category: 1 }]; /* how to play */ var tutorial = '<h2 class="title">How to play</h2>'+ '<strong>Gather your friends</strong>'+ '<p>This game is best played in groups.</p>'+ '<strong>Pick the story</strong>'+ '<p>Select a story you want to play.</p>'+ '<strong>Use words</strong>'+ '<p>Read the word type and enter a word of your choice without letting anyone know. Once entered, click the next button and then pass your device to the next player, continue until a player gets to the generate button.</p>'+ '<strong>Generate your story</strong>'+ '<p>The next player clicks the generate button and reads the story out loud.</p>'; /* Achievements */ const achs = [{ title: 'We <3 you', description: 'Launch the BLANKS app for the first time', kudos: 25 }];
2bcbe69d9ea5a8c75e5cc222901be16f8b10fe4c
[ "Markdown", "JavaScript" ]
2
Markdown
jackcranston/blanks-app
a338449cc3c0241a07220099cd2ee16e3f43e17d
754505e7fbf3c4e0fafe0454dd0d0cf82a228aa5
refs/heads/master
<file_sep>#! /bin/bash webpack && rsync -avzr ./client/ mmmurphy:play/plates/ <file_sep>const React = require('react'); const component = require('omniscient'); const Immstruct = require('immstruct'); const mainStyle = require('./style.styl'); const DraggableNumber = require('./draggable-number'); const PlateCalc = require('./plate-calc'); const struct = Immstruct({ bar: 45, total: 100, }) const Main = component('Main', ({cursor}) => { const up = function(key) { return function(e) { cursor.set(key, e.target.value); } } return <div className="container"> <div className="row"> <div className="col-xs-12"> <h1 style={{textAlign:'center'}}>Plate-o-matic!</h1> </div> <hr/> <div className="col-xs-6"> <label>Bar Weight</label> <DraggableNumber value={cursor.get('bar')} style={{ fontSize:'3em', padding:'1em', background: '#e74c3c', color: '#ecf0f1', }} onDoneDragging={up('bar')}/> </div> <div className="col-xs-6"> <label>Total Weight</label> <DraggableNumber value={cursor.get('total')} style={{ fontSize:'3em', padding:'1em', background: '#e74c3c', color: '#ecf0f1', }} onDoneDragging={up('total')}/> </div> <hr/> <PlateCalc bar={cursor.get('bar')} total={cursor.get('total')}/> </div> </div> }).jsx const render = function() { React.render(<Main cursor={struct.cursor()}/>, document.getElementById('main')) } struct.on('swap', render) render() <file_sep># Plate-o-matic This is a little offline-ready app for figuring out how to load up the bar at the gym. It's easy! <file_sep>const component = require('omniscient'); const React = require('react'); const {merge, identity} = require('lodash'); React.initializeTouchEvents(true) export default component('DraggableNumber', { getInitialState: function() { return { delta: 0 } }, propTypes: { value: React.PropTypes.number, onDoneDragging: React.PropTypes.func, style: React.PropTypes.object, }, getDefaultProps: function() { return { value: 0, onDoneDragging: identity, style: {}, } } }, function({value, onDoneDragging}) { const onDragStart = (e) => { console.log(e); } const onTouchMove = (e) => { console.log(e); } const onDragEnd = (e) => { console.log(e); } const modifiedStyle = merge({cursor:'pointer', userSelect: 'none'}, this.props.style) // return <div // ref='num' // style={modifiedStyle} // onTouchStart={onDragStart} // onTouchEnd={onDragEnd} // onTouchMove={onTouchMove} // > // {value + this.state.delta} // </div> return <input className="form-control" type="number" value={this.props.value} onChange={this.props.onDoneDragging}/> }).jsx <file_sep>var webpack = require('webpack'); var os = require('os') var autoprefixer = require('autoprefixer-core'); module.exports = { entry: [ 'webpack-dev-server/client?http://' + os.hostname() + ':3007', 'webpack/hot/dev-server', './src/index.jsx', ], output: { path: __dirname + '/static/', filename: 'bundle.js', }, resolve: { extensions: ['', '.js', '.json', '.jsx', 'index.jsx', 'index.js', '.styl', '.es6.js'] }, plugins: [ new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.jsx?$/, loader: 'react-hot!6to5' }, { test: /\.es6.js?$/, loader: '6to5' }, { test: /\.styl$/, loader: 'style-loader!css-loader!postcss-loader!stylus-loader' }, { test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=8192' }, { test: /\.json$/, loader: 'json' } ], }, postcss: [ autoprefixer({ browsers: ['last 2 version'] }) ] }; <file_sep>var AppCachePlugin = require('appcache-webpack-plugin') var webpack = require('webpack'); var autoprefixer = require('autoprefixer-core'); module.exports = { plugins: [ new webpack.NormalModuleReplacementPlugin(/^react$/, 'react/addons'), new AppCachePlugin({ cache: [ 'index.html', 'bundle.js', 'vendor/bootstrap.min.css', 'vendor/ionicons.css', 'fonts/ionicons.svg', 'fonts/ionicons.eot', 'fonts/ionicons.ttf', 'fonts/ionicons.woff', ] }), ], entry: './src/index.jsx', output: { path: __dirname + '/static', filename: 'bundle.js' }, resolve: { extensions: ['', '.js', '.jsx', '.es6.js', 'index.js', 'index.jsx', 'index.es6.js', '.styl'], modulesDirectories: ['node_modules', 'src'] }, module: { loaders: [ { test: /\.jsx$/, loader: '6to5' }, { test: /\.es6\.js$/, loader: '6to5' }, { test: /\.styl$/, loader: 'style!css!postcss!stylus' }, { test: /\.css$/, loader: 'style!css!postcss' }, { test: /\.(png|jpg|gif)$/, loader: 'url?limit=8192' } ], noParse: /lie.js/ }, postcss: [ autoprefixer({ browsers: ['last 2 version'] }) ], externals: { APIHOST: '""' }, devtool: "#eval" }; <file_sep>var koa = require('koa'); var serve = require('koa-static'); var PORT = process.env.NODE_PORT || 3008; var app = koa(); app.use(serve('./static')); app.listen(PORT); console.log('server listening on port ' + PORT);
f758176167951cb85b45c899aa01a5a17d2580d3
[ "JavaScript", "Markdown", "Shell" ]
7
Shell
mrmurphy/plateomatic
4a2719bf23a08e5c6a070d9e327ed1e220218500
8e1ecb6db1f2d8eca19aaa51b83e007d48fbcd4e
refs/heads/master
<repo_name>Metalmastery/todo-react-redux-saga<file_sep>/source/containers/addItem.jsx import React, { PropTypes } from "react" import { connect } from 'react-redux' import { ActionCreators } from '../actions' import Form from '../components/form/form' const mapDispatchToProps = (dispatch) => { return { addItem : (value) => { dispatch(ActionCreators.addTodo(value)); }, displayError : (text) => { dispatch(ActionCreators.displayError(text)); } } }; const AddItemForm = connect( null, mapDispatchToProps )(Form); export default AddItemForm;<file_sep>/source/stores/todoStore.js import { createStore, applyMiddleware, compose } from 'redux' import createSagaMiddleware from 'redux-saga' import todoApp from '../reducers/reducers' import { todoSaga } from '../sagas/sagas' import {persistStore, autoRehydrate} from 'redux-persist' const sagaMiddleware = createSagaMiddleware() const store = createStore(todoApp, applyMiddleware(sagaMiddleware), autoRehydrate()) persistStore(store) sagaMiddleware.run(todoSaga); export default store<file_sep>/source/components/statusBar/statusBar.jsx import React from "react"; import handlersConnections from '../../libs/handlers-connections-bundle' const defaultURL = 'https://project-3173980971439450621.firebaseapp.com/favicon-server.ico'; export default class StatusBar extends React.Component { constructor (props) { super(props); this.updateStatusManually = this.updateStatusManually.bind(this); this.networkCallback = this.networkCallback.bind(this); this.internetCallback = this.internetCallback.bind(this); this.servicesCallback = this.servicesCallback.bind(this); this.handleChange = this.handleChange.bind(this); this.resetDefaultURL = this.resetDefaultURL.bind(this); this.state = { networkAvailable : false, internetAvailable : false, serviceAvailable : false, url : defaultURL }; this.handlersConnections = new handlersConnections({ network: { onChangeStatus: this.networkCallback }, internet: { onChangeStatus: this.internetCallback }, services: [ { url: this.state.url, onChangeStatus: this.servicesCallback, repeat: 3000, priority: 0 } ] }) } componentDidUpdate () { this.changeURL(this.state.url) } handleChange (event) { this.setState({url : event.target.value}) } networkCallback (status) { this.setState({networkAvailable : status}) }; internetCallback (status) { this.setState({internetAvailable : status}) }; servicesCallback (status) { this.setState({serviceAvailable : status}) }; resetDefaultURL () { this.setState({url : defaultURL}) } changeURL (url) { // todo change hardcode after API finalization this.handlersConnections.services[0].url = url } updateStatusManually () { this.handlersConnections.checkNetwork() .then(this.networkCallback); this.handlersConnections.checkInternet() .then(this.internetCallback); this.handlersConnections.checkServices() .then(this.servicesCallback); } componentDidMount () { this.updateStatusManually() } render () { return <div onClick={this.updateStatusManually} className="status-bar"> <div className={'indicator-' + this.state.networkAvailable}> network </div> <div className="description"> Network status depends on hardware and changes when you turn physical connection (wifi or cable) on or off. </div> <div className={'indicator-' + this.state.internetAvailable}> internet </div> <div className="description"> Internet status depends on reachability of services with high uptime percent. Currently we use services listed below: <ul> <li>www.google.com</li> <li>aws.amazon.com</li> <li>www.cloudflare.com</li> <li>www.baidu.com</li> <li>www.yahoo.com</li> </ul> </div> <div className={'indicator-' + this.state.serviceAvailable}> service </div> <div className="description"> Service status depends on reachability of services specified in configuration. Currently we check URL given below every 3 seconds. <ul> <li>{this.state.url}</li> </ul> You can modify URL here and we'll use it instead (we do not validate this field). CORS policy may disallow your browser to make request from different domain. <input type="text" value={this.state.url} onChange={this.handleChange} /> <button onClick={this.resetDefaultURL}>reset to default</button> </div> </div> } }<file_sep>/karma.conf.js var webpackConfig = require('./webpack.config.js'); // todo magic fix - to add or not to add this line? // webpackConfig.entry = {}; module.exports = function(config) { config.set({ browsers: ['PhantomJS'], files: [ { pattern: './spec/test.entry.js', watched: false } ], frameworks: ['jasmine'], preprocessors: { './spec/test.entry.js': ['webpack'] }, reporters: ['spec'], singleRun: true, webpack : webpackConfig, webpackServer: { noInfo: true }, plugins: [ 'karma-webpack', 'karma-phantomjs-launcher', // 'karma-chrome-launcher', 'karma-jasmine', 'karma-spec-reporter' ] }); };<file_sep>/gulpfile.js var gulp = require('gulp'); var clean = require('gulp-clean'); var webpack = require('webpack-stream'); var cordova = require("cordova-lib").cordova; var KarmaServer = require('karma').Server; var runSequence = require('run-sequence'); var webpackConfig = require('./webpack.config.js'); var electronInstaller = require('electron-winstaller'); var pathDir = { webpackEntry : webpackConfig.entry, webpackOutput : webpackConfig.output.path, cordova : 'cordova-test', cordovaWWW : 'cordova-test/www', electron : 'electron-test', firebase : 'public' }; gulp.task('buildSource', function() { return gulp.src(pathDir.webpackEntry) .pipe(webpack( webpackConfig )) .pipe(gulp.dest(pathDir.webpackOutput)) }); gulp.task('sourcecopy', function () { return gulp.src([ 'index.html', 'assets/**/*', 'build/**/*' ], { base : '.'}) .pipe(gulp.dest(pathDir.cordovaWWW)) .pipe(gulp.dest(pathDir.firebase)) .pipe(gulp.dest(pathDir.electron)); }); gulp.task('clean', function() { return gulp.src([ pathDir.webpackOutput, pathDir.cordovaWWW ], {read: false}) .pipe(clean()) }); gulp.task('cordova', function (cb) { process.chdir(pathDir.cordova); cordova.build({ "platforms": ["android"], "options": { argv: ["--release","--gradleArg=--no-daemon"] } }, cb); }); // gulp.task('electron', function (cb) { // process.chdir('electron-test'); // // ' electron-packager ./electron-test --all --out electron-test/platforms --overwrite' // // ' electron-packager ./electron-test --platform=darwin --arch=x64 --out electron-test/platforms --overwrite' // // }); gulp.task('test', function (done) { new KarmaServer({ configFile: __dirname + '/karma.conf.js', singleRun: true, // reporters: [] }, done).start(); }); gulp.task('winstaller', function () { var resultPromise = electronInstaller.createWindowsInstaller({ appDirectory: 'electron-test/platforms/electron-test-win32-x64', outputDirectory: 'electron-test/platforms/win', authors: 'My App Inc.', exe: 'myapp.exe' }); resultPromise.then( () => console.log('It worked!'), (e) => console.log(`No dice: ${e.message}`) ); }); // todo apply karma tests before build gulp.task('default', function () { runSequence(['clean', 'buildSource'], 'sourcecopy') }); gulp.task('build', function () { runSequence(['test', 'clean', 'buildSource'], 'sourcecopy', 'cordova') }); <file_sep>/source/actions.js const Actions = { Items : { ADD : 'ADD_ITEM', REMOVE : 'REMOVE_ITEM', REMOVE_CONFIRMED : 'REMOVE_ITEM_CONFIRMED', COMPLETE : 'COMPLETE_ITEM' }, Filters : { SET : 'SET_FILTER', ALL : 'FILTER_ALL', ACTIVE : 'FILTER_ACTIVE', COMPLETED : 'FILTER_COMPLETED' }, Errors : { GENERAL_ERROR : 'GENERAL_ERROR', EMPTY_VALUE_ERROR : 'EMPTY_VALUE_ERROR' } }; const Texts = { errors : { CONFIRMATION_FAILS : 'can\'t confirm item removing' }, confirmation : { SURE_TO_REMOVE : 'are you sure?' } } const ActionCreators = { addTodo : (value = '') => ({ type: Actions.Items.ADD, value }), removeTodo : (id) => ({ type: Actions.Items.REMOVE, id }), removeTodoConfirmed : (id) => ({ type: Actions.Items.REMOVE_CONFIRMED, id }), completeTodo : (id) => ({ type: Actions.Items.COMPLETE, id }), setFilter : (filter) => ({ type: Actions.Filters.SET, filter }), displayError : (text) => ({ type: Actions.Errors.GENERAL_ERROR, text }), }; export { ActionCreators, Actions, Texts }<file_sep>/source/components/form/form.jsx import React, { PropTypes } from "react"; export default class Form extends React.Component { constructor (props) { super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); this.buttonClick = this.buttonClick.bind(this); this.keyUp = this.keyUp.bind(this); this.addItem = props.addItem; this.displayError = props.displayError; } buttonClick () { if (this.state.value.length) { this.addItem(this.state.value); this.setState({value : ''}) } else { // todo show error message this.displayError('field is empty'); } } keyUp (event) { // todo remove hardcode if (event.keyCode === 13) { this.buttonClick(); } } handleChange (event) { // todo change wrapping element to form and prevent submit // event.preventDefault(); this.setState({value: event.target.value}); } render() { return <div> <input type="text" value={this.state.value} onChange={this.handleChange} onKeyUp={this.keyUp} /> <button onClick={this.buttonClick}>add</button> </div> } } Form.propTypes = { addItem: PropTypes.func.isRequired };<file_sep>/spec/components.spec.js import { Actions, ActionCreators} from '../source/actions' import { ItemReducer, FilterReducer } from '../source/reducers/reducers' describe("Components work well", () => { describe("Form works well", () => { }) }) <file_sep>/spec/reducers.spec.js import { Actions, ActionCreators} from '../source/actions' import { ItemReducer, FilterReducer } from '../source/reducers/reducers' describe("Reducers work well", () => { // todo check mocking and avoid hardcoded objects describe("Item reducer", () => { it('ItemReducer returns default state on empty action', () => { expect(ItemReducer([], {})).toEqual([]); }) it('ItemReducer returns default state on incorrect action', () => { expect(ItemReducer([], { type: 'INCORRECT_TYPE', value: null })).toEqual([]); }) beforeEach(() => { // todo move mock objects & actions here }) it('ItemReducer handles ADD action', () => { var action = ActionCreators.addTodo(), fakeObject = { value : '', completed : false }, oldState = [], newState = ItemReducer(oldState, action); expect(newState).toEqual(jasmine.any(Array)); expect(newState.length).toEqual(1); expect(newState[0]).toEqual(jasmine.objectContaining(fakeObject)); }) it('ItemReducer handles REMOVE action', () => { // todo rewrite with more details expect(ItemReducer([{ value: null, completed: false, id: 0 }], { type: Actions.Items.REMOVE_CONFIRMED, id: 0 })).toEqual([]); }) it('ItemReducer handles COMPLETE action', () => { expect(ItemReducer([{ value: null, completed: false, id: 0 }], { type: Actions.Items.COMPLETE, id: 0 })).toEqual([{ value: null, completed: true, id: 0 }]); }) }) });<file_sep>/source/components/list/list.jsx import React, { PropTypes } from "react" import TodoItem from './item' export default class List extends React.Component { render() { var toggleComplete = this.props.toggleCompleted, removeItem = this.props.removeItem, rows = this.props.dataList.map( item => <TodoItem toggleCompleted={toggleComplete} removeItem={removeItem} key={item.uid} item={item}> </TodoItem> ); return <ul> {rows} </ul> } } List.propTypes = { dataList: PropTypes.array.isRequired, toggleCompleted : PropTypes.func.isRequired };<file_sep>/source/containers/visibleList.js import { connect } from 'react-redux' import { Actions, ActionCreators } from '../actions' import List from '../components/list/list' var { Items, Filters } = Actions; const getVisibleTodos = (items, filter) => { switch (filter) { case Filters.ALL: return items; case Filters.COMPLETED: return items.filter(t => t.completed); case Filters.ACTIVE: return items.filter(t => !t.completed) } }; const mapStateToProps = (state) => { return { dataList: getVisibleTodos(state.items, state.filter) } }; const mapDispatchToProps = (dispatch) => { return { toggleCompleted: (id) => { dispatch(ActionCreators.completeTodo(id)) }, removeItem: (id) => { dispatch(ActionCreators.removeTodo(id)) } } }; const VisibleTodoList = connect( mapStateToProps, mapDispatchToProps )(List); export default VisibleTodoList<file_sep>/spec/sagas.spec.js import { delay } from 'redux-saga' import { put, call } from 'redux-saga/effects' import { Actions, ActionCreators, Texts } from '../source/actions' import { logItem, confirmRemove, asyncConfirm } from '../source/sagas/sagas' describe("Sagas work properly", () => { describe('logItem works well', () => { const logItemGenerator = logItem(); it("logItem posts log after 100ms", () => { expect(logItemGenerator.next().value).toEqual(call(delay, 100)); }); it("logItem finished", () => { expect(logItemGenerator.next()).toEqual({ done: true, value: undefined }); }); }) describe('asyncConfirm works well', () => { it('asyncConfirm returs promise', () => { expect(asyncConfirm() instanceof Promise).toBeTruthy() }) it('asyncConfirm\'s promise resolves if param is correct', (done) => { var confirmationPromise = asyncConfirm(true), successSpy = jasmine.createSpy('success'), failureSpy = jasmine.createSpy('failure'); confirmationPromise.then(successSpy, failureSpy).catch(t=>t).then(()=>{ expect(failureSpy).not.toHaveBeenCalled(); expect(successSpy).toHaveBeenCalled(); done() }); }) it('asyncConfirm\'s promise rejects if param is incorrect', (done) => { var confirmationPromise = asyncConfirm(false), successSpy = jasmine.createSpy('success'), failureSpy = jasmine.createSpy('failure'); confirmationPromise.then(successSpy, failureSpy).catch(t=>t).then(()=>{ expect(failureSpy).toHaveBeenCalled(); expect(successSpy).not.toHaveBeenCalled(); done() }); }) }) describe('confirmRemove works well', () => { const mockItem = {id : 0}, removeActionMock = ActionCreators.removeTodo(mockItem.id), removeConfirmedActionMock = ActionCreators.removeTodoConfirmed(mockItem.id), errorActionMock = ActionCreators.displayError(Texts.errors.CONFIRMATION_FAILS); // todo read about mocking stores it("confirmRemove puts REMOVE_CONFIRMED on promise success", () => { var confirmSuccessful = true, confirmRemoveGenerator = confirmRemove(removeActionMock, confirmSuccessful); expect(confirmRemoveGenerator.next().value).toEqual(call(asyncConfirm, confirmSuccessful)); expect(confirmRemoveGenerator.next().value).toEqual(put(removeConfirmedActionMock)); expect(confirmRemoveGenerator.next().done).toEqual(true); }); it("confirmRemove puts GENERAL_ERROR on promise reject", () => { var confirmSuccessful = false, confirmRemoveGenerator = confirmRemove(removeActionMock, confirmSuccessful); expect(confirmRemoveGenerator.next().value).toEqual(call(asyncConfirm, confirmSuccessful)); expect(confirmRemoveGenerator.throw().value).toEqual(put(errorActionMock)); expect(confirmRemoveGenerator.next().done).toEqual(true); }); }) });<file_sep>/spec/actions.spec.js import { Actions, ActionCreators } from '../source/actions' describe("Action creators actually create actions", () => { describe("addTodo action creator works correctly", () => { it('addTodo returns an object', () => { expect(ActionCreators.addTodo('test')).toEqual({ type: Actions.Items.ADD, value : 'test' }); }); it('addTodo works without param', () => { expect(ActionCreators.addTodo()).toEqual({ type: Actions.Items.ADD, value : '' }); }) }); });<file_sep>/index.jsx import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import store from './source/stores/todoStore' import Test from './source/main' render( <Provider store={store}> <Test /> </Provider>, document.getElementById('test') );
2a961c212318215ff5e8bda6625846a677458d0d
[ "JavaScript" ]
14
JavaScript
Metalmastery/todo-react-redux-saga
68d2990964617da17f4ef7d2302c14fab6887981
c4f76ca6fbeea1c8a65f9cb0417de0da24a3c8c5
refs/heads/master
<repo_name>bsleys/hobo-jasper-reports<file_sep>/lib/generators/hobo_jasper_reports/install_generator.rb module HoboJasperReports module Generators class InstallGenerator < ::Rails::Generators::Base source_root File.expand_path('../../../..', __FILE__) desc "Installs Hobo Models and controlers to work with Jasper Reports" def install base_pathname = Pathname.new(File.expand_path('../../../../hobo-jasper-reports', __FILE__)) Dir[File.expand_path('../../../../hobo-jasper-reports/**/*.*', __FILE__)].each do |fn| rfn=Pathname.new(fn).relative_path_from(base_pathname) copy_file "hobo-jasper-reports/#{rfn}", "app/#{rfn}" end end end end end<file_sep>/README.markdown # Hobo JasperReports * http://github.com/bsleys/hobo-jasper-reports ## DESCRIPTION: Add JasperReports (http://jasperforge.org/) reporting to a Hobo app iReport Designer is required to generate the report templates. Gem developed with iReport 4.1.3 The gem is heavly based on the work here http://oldwiki.rubyonrails.org/rails/pages/HowtoIntegrateJasperReports ## FEATURES/PROBLEMS: * Report model to store info about reports * Report admin controler to setup and upload iReport report designs * Report controler to show report via hobo_show action * Document model to generate report * send_doc_helper used in report controler to aid in generating report ## REQUIREMENTS: * Java is require to run the reports * paperlip ~> 2.3 * paperclip_with_hobo is required see (http://cookbook.hobocentral.net/plugins/paperclip_with_hobo) ## INSTALL: Add the following line to your gemfile gem 'hobo-jasper-reports', :git => 'git://github.com/bsleys/hobo-jasper-reports.git' And then run bundle install rails generate hobo_jasper_reports:install bundle exec hobo g migration Add to admin_site.dryml <include gem="hobo-jasper-reports"/> The following file will be overwritten with hobo_jasper_reports:install /app/controllers/reports_controller.rb /app/controllers/admin/reports_controller.rb /app/helpers/send_doc_helper.rb /app/models/document.rb /app/models/report.rb The migration will add a reports table to the database ## USAGE: Edit REPORT_TYPES in /app/models/report.rb to setup new XML datasources for your reports. There are two parts to each report type <model>/<xmlview> (described below). This is hard coded to a enum field because each model you wish to report on will need one or more xml datasources created and since this has to be done manualy anyway adding the appropriate string here seems to make sense. The model can be specified in either plural or sigular form. This is useful if say on the index view of a model you want to be able to generate reports for all the models records you could use the plural form of the model name. Then on the show view of a specific record you should use the singular form of the model. The xmlview portion is the filename of an .rxml file stored in view/reports. The report model has the following fields name - Name of the report this is used in views etc. report_action - hold the REPORT_TYPES described above report_query_string - XML query string used in generating the report include - advanced optional option to include needed sub tables if specifying a filter filter - filter or where clause for database query output_file_name - file name the report will be download to output_file_type - file type the report will be exported to (:pdf, :xml, :rtf, :xls, :csv) ## LICENSE: Copyright (c) 2012 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.<file_sep>/hobo-jasper-reports/models/document.rb class Document include Config def self.generate_report(xml_data, report_design, output_type, select_criteria) report_design << '.jasper' if !report_design.match(/\.jasper$/) interface_classpath="#{HoboJasperReports.root}/jasper_reports/bin" case CONFIG['host'] when /mswin32/ mode = "w+b" #windows requires binary mode Dir.foreach("#{HoboJasperReports.root}/jasper_reports/lib") do |file| interface_classpath << ";#{HoboJasperReports.root}/jasper_reports/lib/" + file if (file != '.' and file != '..' and file.match(/.jar/)) end else mode = "w+b" Dir.foreach("#{HoboJasperReports.root}/jasper_reports/lib") do |file| interface_classpath << ":#{HoboJasperReports.root}/jasper_reports/lib/" + file if (file != '.' and file != '..' and file.match(/.jar/)) end end result=nil IO.popen "java -Djava.awt.headless=true -cp \"#{interface_classpath}\" XmlJasperInterface -o#{output_type} -f#{report_design} -x#{select_criteria}", mode do |pipe| pipe.write xml_data pipe.close_write result = pipe.read pipe.close end return result end end<file_sep>/hobo-jasper-reports.gemspec name = File.basename( __FILE__, '.gemspec' ) version = File.read(File.expand_path('../VERSION', __FILE__)).strip spec = Gem::Specification.new do |s| s.name = name s.version = version s.summary = "Jasper Reports support for Hobo" s.description = "Jasper Reports support for Hobo" s.author = "<NAME>" s.email = "<EMAIL>" s.files = `git ls-files -x #{name}/* -z`.split("\0") s.add_runtime_dependency('paperclip', [">= 2.3"]) end<file_sep>/hobo-jasper-reports/controllers/reports_controller.rb class ReportsController < ApplicationController hobo_model_controller auto_actions :index, :show include SendDocHelper def show hobo_show do action = @report.report_action.split('/') cid = params[:cid] || "" @robj = Kernel.const_get(action[0].singularize.titleize).scoped @robj = @robj.where(:id => cid) if !cid.blank? @robj = @robj.includes(Report::REPORT_INCLUDES[action[1]]) if Report::REPORT_INCLUDES[action[1]] @robj = @robj.where(@report.filter) if !@report.filter.blank? if @report.jasperreport_file_name? send_doc( render_to_string(action[1], :layout=>false), @report.report_query_string, @report.jasperreport.path, @report.output_file_name, @report.output_file_type ) else render(action[1], :layout=>false) end end end end <file_sep>/jasper_reports/bin/XmlJasperInterface.java /* * An XML Jasper interface; Takes XML data from the standard input * and uses JRXmlDataSource to generate Jasper reports in the * specified output format using the specified compiled Jasper design. * * Inspired by the xmldatasource sample application provided with * jasperreports-1.1.0 */ import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRXmlDataSource; import net.sf.jasperreports.engine.export.JRCsvExporter; import net.sf.jasperreports.engine.export.JRRtfExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; /** * @author <NAME> (jonas at schwertfeger dot ch) * @version $Id: XmlJasperInterface.java 97 2005-11-23 14:48:15Z js $ */ public class XmlJasperInterface { private static final String TYPE_PDF = "pdf"; private static final String TYPE_XML = "xml"; private static final String TYPE_RTF = "rtf"; private static final String TYPE_XLS = "xls"; private static final String TYPE_CSV = "csv"; private String outputType; private String compiledDesign; private String selectCriteria; public static void main(String[] args) { String outputType = null; String compiledDesign = null; String selectCriteria = null; if (args.length != 3) { printUsage(); return; } for (int k = 0; k < args.length; ++k) { if (args[k].startsWith("-o")) outputType = args[k].substring(2); else if (args[k].startsWith("-f")) compiledDesign = args[k].substring(2); else if (args[k].startsWith("-x")) selectCriteria = args[k].substring(2); } XmlJasperInterface jasperInterface = new XmlJasperInterface(outputType, compiledDesign, selectCriteria); if (!jasperInterface.report()) { System.exit(1); } } public XmlJasperInterface( String outputType, String compiledDesign, String selectCriteria) { this.outputType = outputType; this.compiledDesign = compiledDesign; this.selectCriteria = selectCriteria; } public boolean report() { try { JasperPrint jasperPrint = JasperFillManager.fillReport(compiledDesign, null, new JRXmlDataSource(System.in, selectCriteria)); if (TYPE_PDF.equals(outputType)) { JasperExportManager.exportReportToPdfStream(jasperPrint, System.out); } else if (TYPE_XML.equals(outputType)) { JasperExportManager.exportReportToXmlStream(jasperPrint, System.out); } else if (TYPE_RTF.equals(outputType)) { JRRtfExporter rtfExporter = new JRRtfExporter(); rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, System.out); rtfExporter.exportReport(); } else if (TYPE_XLS.equals(outputType)) { JRXlsExporter xlsExporter = new JRXlsExporter(); xlsExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); xlsExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, System.out); xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE); xlsExporter.exportReport(); } else if (TYPE_CSV.equals(outputType)) { JRCsvExporter csvExporter = new JRCsvExporter(); csvExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); csvExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, System.out); csvExporter.exportReport(); } else { printUsage(); } } catch (JRException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } return true; } private static void printUsage() { System.out.println("XmlJasperInterface usage:"); System.out.println("\tjava XmlJasperInterface -oOutputType -fCompiledDesign -xSelectExpression < input.xml > report\n"); System.out.println("\tOutput types:\t\tpdf | xml | rtf | xls | csv"); System.out.println("\tCompiled design:\tFilename of the compiled Jasper design"); System.out.println("\tSelect expression:\tXPath expression that specifies the select criteria"); System.out.println("\t\t\t\t(See net.sf.jasperreports.engine.data.JRXmlDataSource for further information)"); System.out.println("\tStandard input:\t\tXML input data"); System.out.println("\tStandard output:\tReport generated by Jasper"); } } <file_sep>/hobo-jasper-reports/models/report.rb class Report < ActiveRecord::Base hobo_model # Don't put anything above this # private static final String TYPE_PDF = "pdf"; # private static final String TYPE_XML = "xml"; # private static final String TYPE_RTF = "rtf"; # private static final String TYPE_XLS = "xls"; # private static final String TYPE_CSV = "csv"; FILE_TYPES = HoboFields::Types::EnumString.for(:pdf, :xml, :rtf, :xls, :csv) # REPORT_TYPES = HoboFields::Types::EnumString.for('project/BulkSampleLog', # 'organization/OrganizationMaterials') REPORT_TYPES = HoboFields::Types::EnumString.for() # Use of REPORT_INCLUDES is optional but advised # first it activates eager loading so lest number of sql queries will be run when generating the report # second it enables the end user to filter on sub tables that are listed in the includes # REPORT_INCLUDES = {'BulkSampleLog' => [{:samples=>{:location=>:location_name}} , # {:samples=>{:field_tech=>:licences, :material=>:building}}, # :organization], # 'OrganizationMaterials' => [:buildings => # {:floors => # { :spaces => # {:locations => # [{ :location_materials => :material}, :location_name] # } # } # } # ] # } REPORT_INCLUDES = {} fields do name :string, :required report_action Report::REPORT_TYPES, :required report_query_string :string filter :string output_file_name :string output_file_type Report::FILE_TYPES timestamps end has_attached_file :jasperreport, :path => ":rails_root/jasper_reports/:attachment/:id/:style/:filename" # validates_attachment_presence :jasperreport validates_attachment_content_type :jasperreport, :content_type => ['application/octet-stream'] scope :for_model, lambda { |m, admin| if admin hidexml = "" else hidexml = "jasperreport_file_name is not NULL and " end where("#{hidexml}report_action like ?", "#{m}/%"). order(:name) } # --- Permissions --- # def create_permitted? acting_user.administrator? end def update_permitted? acting_user.administrator? end def destroy_permitted? acting_user.administrator? end def view_permitted?(field) true end end <file_sep>/lib/hobo-jasper-reports.rb $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) module HoboJasperReports VERSION = File.read(File.expand_path('../../VERSION', __FILE__)).strip @@root = Pathname.new File.expand_path('../..', __FILE__) def self.root; @@root; end end<file_sep>/hobo-jasper-reports/helpers/send_doc_helper.rb module SendDocHelper protected def cache_hack if request.env['HTTP_USER_AGENT'] =~ /msie/i headers['Pragma'] = '' headers['Cache-Control'] = '' else headers['Pragma'] = 'no-cache' headers['Cache-Control'] = 'no-cache, must-revalidate' end end def send_doc(xml, xml_start_path, report, filename, output_type = 'pdf') # output types from XmlJasperInterface # private static final String TYPE_PDF = "pdf"; # private static final String TYPE_XML = "xml"; # private static final String TYPE_RTF = "rtf"; # private static final String TYPE_XLS = "xls"; # private static final String TYPE_CSV = "csv"; case output_type when 'xml' extension = 'xml' mime_type = 'text/xlm' jasper_type = 'xml' when 'rtf' extension = 'rtf' mime_type = 'application/rtf' jasper_type = 'rtf' when 'xls' extension = 'xls' mime_type = 'application/excel' jasper_type = 'xls' when 'csv' extension = 'csv' mime_type = 'text/csv' jasper_type = 'csv' else # pdf extension = 'pdf' mime_type = 'application/pdf' jasper_type = 'pdf' end cache_hack send_data Document.generate_report(xml, report, jasper_type, xml_start_path), :filename => "#{filename}.#{extension}", :type => mime_type, :disposition => 'inline' end end
95ba9b032c32dc63d86515acfae112d1efb1494b
[ "Markdown", "Java", "Ruby" ]
9
Ruby
bsleys/hobo-jasper-reports
32dd1aefba7e4449e9a537861ea5fe1a71515cd2
bb11ac200749b2d0d62a0eaf2928dd94613e2b3b
refs/heads/main
<file_sep>#!/bin/bash # TESTING ENV VARS # NOKEYREAD - set this to 1 to prevent the key from being read in. # NOLOCKDOWN - prevents the pi from hardening and locking down. For testing. # NOREBOOT - prevents reboot at end of bootstrap.sh # # Usage: # NOKEYREAD=1 NOLOCKDOWN=1 bash <(curl -s ...) # We assume this script will be curl'd in. # We assume it will be curl'd in and sudo will prompt for a password. # It is for configuring a Raspberry Pi to be part of a pilot data collection effort. # That pilot is being run in partnership between 10x/18F/IMLS. # If you are not one of the people taking part in that pilot, then this # software will *not* be useful to you. # It will do things to your Raspberry Pi. # Things you might not want. # You have been warned. # Here be krackens. # CRITICAL GLOBALS REPOS_ROOT="https://github.com/jadudm" PLAYBOOK_REPOS="imls-client-pi-playbook" PLAYBOOK_URL="${REPOS_ROOT}/${PLAYBOOK_REPOS}" PLAYBOOK_WORKING_DIR="/opt/imls" INITIAL_CONFIGURATION_BINARY_URL="https://github.com/jadudm/input-initial-configuration/releases/download/v0.0.9/input-initial-configuration" RALINK_DIR="/tmp/ralink" RALNK_BINARY="https://github.com/jadudm/find-ralink/releases/download/v0.0.9/find-ralink" # A GLOBAL CATCH # If something goes wrong, set this to 1. # If the _err function is ever used, it sets this automatically. SOMETHING_WENT_WRONG=0 # PURPOSE # Creates a temporary logfile in a way that lets the OS # decide where it should go. create_logfile () { export SETUP_LOGFILE=$(mktemp -t "setup-log-XXX") } mangle_console () { # https://serverfault.com/questions/103501/how-can-i-fully-log-all-bash-scripts-actions # Save all the pipes. # 3 is Stdout. 4 is stderr. exec 3>&1 4>&2 # Restore some. trap 'exec 2>&4 1>&3' 0 1 2 3 exec 1>> /dev/null 2>&1 } # PURPOSE # Sets up redirects so that STDOUT and STDERR make their way to # a temporary logfile. setup_logging () { mangle_console # Redirect stdout/stderr to a logfile. exec 1>> "${SETUP_LOGFILE}" 2>&1 _status "Logfile started. It can be accessed for debugging purposes." _variable "SETUP_LOGFILE" } # COLORS! RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' PURPLE='\033[0;35m' # No color NC='\033[0m' _msg () { TAG="$1" COLOR="$2" MSG="$3" printf "[${TAG}] ${MSG}\n" >&1 printf "[${COLOR}${TAG}${NC}] ${MSG}\n" >&3 } _status () { MSG="$1" _msg "STATUS" "${GREEN}" "${MSG}" } _debug () { MSG="$1" _msg "DEBUG" "${YELLOW}" "${MSG}" } _err () { SOMETHING_WENT_WRONG=1 MSG="$1" _msg "ERROR" "${RED}" "${MSG}" } _variable () { VAR="$1" _msg "$VAR" "${PURPLE}" "${!VAR}" } #################################### # CHECKS # These are helper functions for checking if things exist, # etc. Used a lot, clarifies the code. # https://stackoverflow.com/questions/592620/how-can-i-check-if-a-program-exists-from-a-bash-script command_exists () { type "$1" &> /dev/null ; } command_does_not_exist () { if command_exists "$1"; then return 1 else return 0 fi } # PURPOSE # Restores the file descriptors after capturing/redirecting. restore_console () { # https://stackoverflow.com/questions/21106465/restoring-stdout-and-stderr-to-default-value # Reconnect stdout and close the third filedescriptor. exec 1>&4 4>&- # Reconnect stderr exec 1>&3 3>&- } initial_update () { # This will need lshw echo "Doing an initial software update." mangle_console sudo apt update restore_console } fix_the_time () { echo "Setting the time." mangle_console sudo apt install -y ntp ntpdate sudo service ntp stop sudo ntpdate 0.us.pool.ntp.org sudo service ntp start restore_console } check_for_usb_wifi () { echo "Checking for wifi..." mangle_console sudo apt install -y lshw # We need better time. rm -rf ${RALINK_DIR} mkdir -p ${RALINK_DIR} pushd ${RALINK_DIR} rm -f find-ralink curl -L -s -o find-ralink ${RALNK_BINARY} chmod 755 find-ralink if [[ "$(./find-ralink --exists)" =~ "false" ]]; then restore_console echo "********************* PANIC OH NOES! *********************" echo "We think you did not plug in the USB wifi adapter!" echo "Please do the following:" echo "" echo " 1. Plug in the USB wifi adapter." echo " 2. Push the up arrow. (This brings back the bash command.)" echo " 3. Press enter." echo "" echo "This will start the setup process again." echo "********************* PANIC OH NOES! *********************" echo "" exit fi popd restore_console } read_initial_configuration () { # Fetch the binary. pushd /tmp # 20210427 MCJ Again, in dev/testing conditions, wipe things out. rm -f iic curl -L -s -o iic ${INITIAL_CONFIGURATION_BINARY_URL} chmod 755 iic sudo ./iic --path ${PLAYBOOK_WORKING_DIR}/auth.yaml --fcfs-seq --tag --word-pairs --write popd } bootstrap_ansible () { _status "Bootstrapping Ansible" _status "Updating sources." echo "deb http://ppa.launchpad.net/ansible/ansible/ubuntu trusty main" | sudo tee -a /etc/apt/sources.list _status "Installing dirmngr." sudo apt-get install dirmngr -y _status "Adding local keys." sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys <KEY> _status "Doing an update. This may take a moment. Be patient." sudo apt-get update _status "Installing the most recent ansible." sudo apt-get install -y ansible } install_prerequisites () { sudo apt-get install -y git } setup_playbook_dir () { sudo rm -rf $PLAYBOOK_WORKING_DIR sudo mkdir -p $PLAYBOOK_WORKING_DIR sudo chown -R pi:pi $PLAYBOOK_WORKING_DIR } # PURPOSE # This clones and runs the playbook for configuring the # RPi for the IMLS/10x/18F data collection pilot. ansible_pull_playbook () { _status "Installing hardening playbook." ansible-galaxy collection install devsec.hardening pushd $PLAYBOOK_WORKING_DIR _status "Cloning the playbook: ${PLAYBOOK_URL}" # 20210427 MCJ Adding a shallow clone. git clone --depth=1 $PLAYBOOK_URL pushd $PLAYBOOK_REPOS _status "Running the playbook. This will take a while." # For testing/dev purposes, we might not want to lock things down # when we're done. The lockdown flag is required to run the # hardening and lockdown roles. # -z checks if the var is UNSET. if [[ -z "${NOLOCKDOWN}" ]]; then ansible-playbook -i inventory.yaml playbook.yaml --extra-vars "lockdown=yes" else _status "Running playbook WITHOUT lockdown" ansible-playbook -i inventory.yaml playbook.yaml fi ANSIBLE_EXIT_STATUS=$? popd popd _status "Done running playbook." if [ $ANSIBLE_EXIT_STATUS -ne 0 ]; then _err "Ansible playbook failed." _err "Exit code: ${ANSIBLE_EXIT_STATUS}" _err "Check the log: ${SETUP_LOGFILE}" fi } disable_interactive_login () { # https://www.raspberrypi.org/forums/viewtopic.php?t=21632 # Disables console and desktop login using the builtin script. # This tells the pi to boot to the console login, but not to auto-login `pi` # https://github.com/RPi-Distro/raspi-config/blob/master/raspi-config#L1308 sudo /usr/bin/raspi-config nonint do_boot_behaviour B1 } main () { echo "*****************************************************************" echo "* Thank you for participating in the IMLS pilot project. *" echo "* We are going to configure this Raspberry Pi as a wifi sensor. *" echo "* Expect this process to take about 20 to 30 minutes. *" echo "*****************************************************************" initial_update fix_the_time check_for_usb_wifi setup_playbook_dir if [[ -z "${NOKEYREAD}" ]]; then # If NOREAD is undefined, we should read in the config. read_initial_configuration else echo " -- SKIPPING CONFIG ENTRY FOR TESTING PURPOSES --" fi create_logfile setup_logging bootstrap_ansible install_prerequisites ansible_pull_playbook disable_interactive_login if [ $SOMETHING_WENT_WRONG -ne 0 ]; then _err "Things finished with errors." _err "We may need to see the logs: ${SETUP_LOGFILE}" else _status "All done!" _status "We're rebooting in one minute!" # If the NOREBOOT flag is NOT set, then reboot. if [[ -z "${NOREBOOT}" ]]; then sleep 60 sudo reboot else _status "Reboot prevented by env flag." fi fi } main <file_sep>.PHONY: test test: ansible-playbook -i inventory.yaml playbook.yaml --extra-vars "lockdown=yes, preserve_ssh=yes, preserve_users=yes"
cfcd028bb0250978316afe097e78c698101a7b1e
[ "Makefile", "Shell" ]
2
Shell
jadudm/imls-client-pi-playbook
f6a0f9c442f4cb0a661b96af74b9e17d95b529e8
746d429c13aeb70649bfd0878af7cb5ba0397f46
refs/heads/main
<file_sep>int variable = 0; void setup() { Serial.begin(9600); } void loop() { variable = random(1, 360 + 1); Serial.println(variable); delay(20); } <file_sep>#include <Servo.h> Servo servo_5; void setup() { servo_5.attach(5, 500, 2500); } void loop() { servo_5.write(0); servo_5.write(180); delay(10); }
ee8f2e2627d5156dc55a91172b763af6aed0d62c
[ "C++" ]
2
C++
selechevenet/ejercicios-sele
47d51c7aff9278bbae97a97124e6f39beb5199ca
9b5cd6850ddbee8777556bc838e225915bf3a523
refs/heads/master
<repo_name>Anndon766/knowi<file_sep>/cannibal.cpp #include<iostream> #include<iomanip> using std::cout; //intially 3 cannibals and 3 missionaries were assumed to be on one side. /*here the issue is the cannibals and missionaries on the same side should be equal in number or missionaries more in number. iF the cannibals count is more, they'll eat the missionaries. The goal is to make the 6 members cross the river in a boat of capacity 2 , alive to the other side. */ int intial_mis = 3, intial_cani = 3, i; int final_mis = 0, final_cani = 0; int position = 0, pts = 0, pick = 0; void print(char cm1, char cm2) { cout << "\n\n\n"; for (int i = 0; i < final_mis; i++) cout << " $ "; /*here $ represent missionaries on other bank*/ for (int i = 0; i < final_cani; i++) cout << " @ ";/*here @ represent cannibals on other bank*/ if (pts == 0) cout << " <----------(" << cm1 << "," << cm2 << ") "; else cout << " (" << cm1 << "," << cm2 << ")----------> "; for (int i = 0; i < intial_mis; i++) cout << " $ "; for (int i = 0; i < intial_cani; i++) cout << " @ "; } int safe() { return (final_cani == 3 && final_mis == 3) ? 0 : 1; } //solution is printed to the console void ans() { while (safe()) { if (!pts) { switch (pick) { case 1: print('@', ' '); intial_cani++; break; case 2: print('@', '$'); intial_cani++; intial_mis++; break; } if (((intial_mis - 2) >= intial_cani && (final_mis + 2) >= final_cani) || (intial_mis - 2) == 0) { intial_mis = intial_mis - 2; pick = 1; print('$', '$'); pts = 1; } else if ((intial_cani - 2) < intial_mis && (final_mis == 0 || (final_cani + 2) <= final_mis) || intial_mis == 0) { intial_cani = intial_cani - 2; pick = 2; print('@', '@'); pts = 1; } else if ((intial_cani--) <= (intial_mis--) && (final_mis++) >= (final_cani++)) { intial_cani = intial_cani - 1; intial_mis = intial_mis - 1; pick = 3; print('$', '@'); pts = 1; } } else { switch (pick) { case 1: print('$', '$'); final_mis = final_mis + 2; break; case 2: print('@', '@'); final_cani = final_cani + 2; break; case 3: print('$', '@'); final_cani = final_cani + 1; final_mis = final_mis + 1; break; } if (safe()) { if (((final_cani > 1 && final_mis == 0) || intial_mis == 0)) { final_cani--; pick = 1; print('@', ' '); pts = 0; } else if ((intial_cani + 2) > intial_mis) { final_cani--; final_mis--; pick = 2; print('@', '$'); pts = 0; } } } } } int main() { cout << "MISSIONARIES AND CANNIBAL ANSWER"<<"\n@-CANNIBLAS \n$-MISSIONARIES"; print(' ', ' '); ans(); print(' ', ' '); return 0; } /* HERE I HAVE PASTED THE OUTPUT I GOT IN MY COMPLIER SCREEN;- MISSIONARIES AND CANNIBAL ANS @-CANNIBLAS $-MISSIONARIES <----------( , ) $ $ $ @ @ @ <----------(@,@) $ $ $ @ (@,@)----------> $ $ $ @ @ (@, )----------> $ $ $ @ @ <----------(@, ) $ $ $ @ @ <----------(@,@) $ $ $ @ (@,@)----------> $ $ $ @ @ (@, )----------> $ $ $ @ @ <----------(@, ) $ $ $ @ @ <----------($,$) $ @ @ @ ($,$)----------> $ @ $ @ (@,$)----------> $ @ $ @ <----------(@,$) $ @ $ @ <----------($,$) @ @ $ @ ($,$)----------> @ @ $ $ $ (@, )----------> @ @ $ $ $ <----------(@, ) @ @ $ $ $ <----------(@,@) @ $ $ $ (@,@)----------> @ $ $ $ @ (@, )----------> @ $ $ $ @ <----------(@, ) @ $ $ $ @ <----------(@,@) $ $ $ @ (@,@)----------> $ $ $ @ @ @ ( , )----------> Process returned 0 (0x0) execution time : 0.437 s Press any key to continue. */ <file_sep>/README.md # knowi cannibal problem for know i project implemented using c
35a2ac943e7689ba2faf88102b13a499be355ebf
[ "Markdown", "C++" ]
2
C++
Anndon766/knowi
8af2b3d68a789c48159f3f7c42034718ec66ea30
667863ccc49428b0eec8ebad866673ee4e169444
refs/heads/master
<repo_name>guyht/ReviewScraper<file_sep>/scraper.js /* * Setup input and button */ $(function() { $('#gobtn').click(function() { new SCRAPER($('#app-id').val()).start(); }); }); /* * Setup Scraper object */ /* * Init scraper */ function SCRAPER(appId) { this.appId = appId; }; /* * Actually start the scraping... also loads the list of app stores */ SCRAPER.prototype.start = function() { var codes = [], fn = this; // Load list of app stores $.get('AppStores.txt', function(data) { var lines = data.split('\n'), i, len = lines.length - 1, code, c, reviews = []; for(i=0;i<len;i++) { c = lines[i].split('\t'); code = { 'country' : c[0], 'code' : c[1], 'storeid' : c[2] }; codes.push(code); } console.log('Loaded ' + codes.length + ' app stores'); // Load framework for(i=0;i<codes.length;i++) { var h = [ '<div id="rpt-', codes[i].code, '" ', 'class="report span-20 last">', '<div class="large country span-20 last">', codes[i].country, '</div></div>']; $('#report-container').append(h.join('')); } fn.go(0, codes); }); }; /* * Self loop for scraping through the app stores */ SCRAPER.prototype.go = function(i, codes) { var fn = this; // Loop through app stores if(i < codes.length) { fn.do_scrape(codes[i].code, codes[i].storeid, function(review) { var j=0; len = review.length; for(k=0;j<len;j++) { var h = [ '<div class="review span-20 last">', '<div class="user span-4">', review[j].user, '</div>', '<div class="title span-16 last">', review[j].title, '</div>', '<div class="stars span-16 last">', review[j].stars, '</div>', '<div class="rev-content span-20 last">', review[j].review, '</div>', '</div>']; $(['#rpt-', review[j].storeCode].join('')).append(h.join('')); } i++; fn.go(i, codes); } ); } }; /* * This is where the actual request is made and the data is extracted */ SCRAPER.prototype.do_scrape = function(storeCode, storeId, cb) { var //path = 'http://itunes.apple.com/' + storeCode + '/app/split-screen/id453757310?mt=12', path = 'http://itunes.apple.com/WebObjects/MZStore.woa/wa/customerReviews?displayable-kind=30&id=' + this.appId, data = [], s1, s2; console.log('Lets scrape, store id ' + storeId); s1 = new Date().getTime(); $.ajax( { type : 'GET', url : path, headers : { 'User-Agent' : 'MacAppStore/1.1.1 (Macintosh; U; Intel Mac OS X 10.7.1; en) AppleWebKit/534.48.3', 'X-Apple-Connection-Type' : 'WiFi', 'X-Apple-Partner' : 'origin.0', 'X-Apple-Store-Front' : storeId + '-1,13' }, success : function(data) { var reviews = []; $(data).find('.customer-review').each( function(idx) { var ret = {}; ret.title = $(this).find('.customerReviewTitle').text(); ret.user = $(this).find('.user-info').text(); ret.review = $(this).find('p.content').text(); ret.stars = $(this).find('div.rating').attr('aria-label'); ret.storeCode = storeCode; reviews.push(ret); } ); s2 = new Date().getTime(); console.log('Processing finished for store ' + storeCode + ' . Total time taken - ' + (s2 - s1)/1000 + 's'); // Send callback cb(reviews); } } ) .error(function(err) { console.error('Error for store ' + storeCode); cb([]); }); };
03506169a32a041866ec90036e8dd1e0b8a7f110
[ "JavaScript" ]
1
JavaScript
guyht/ReviewScraper
2888b0ffebdeb7008a31e773f840185903a490ea
c9d1f488072af9fa2e9a7017671f221084b40773
refs/heads/master
<repo_name>lilixuelian/C-exercise<file_sep>/50 practice/20.c #include<stdio.h> int sum_n(int a[ ]){ int j; int sum = 0; if(a[n]) if(a[n] % 2 == 0){ sum += 0.1 / a[n - 1]; } else sum -= 0.1 / a[n - 1]; } int main (void){ int m, i; int a[100]; scanf("%d", &m); for(i = 0; i < m; i++){ scanf("%d", &a[i]); } return 0; } <file_sep>/50 practice/37.c #include<stdio.h> int main (void){ int i, j, k, n, m; int a[1000][3]; int b[1000]; int c[1000]; scanf("%d", &n); for(i = 0; i < n; i++){ for(j = 0; j < 3; j++){ scanf("%s", &a[i][j]); } } scanf("%d", &m); for(k = 0; k < 2; k++){ scanf("%d", b[k]); for(i = 0; i < n; i++){ if(a[i][1] == b[k]){ printf("%d %d", a[i][0], a[i][2]); } } } return 0; } <file_sep>/PAT/1015.c #include<stdio.h> //这种写法非常蠢: //1、分别四类人都建立四个二维数组 //2、交换的时候还要把三个内容(学号、德分、才分)都要交换 //3、答案还错了一部分。。。提交不通过 // //这是一个典型的用结构体来写的题啊!!! void print (int a[][8],int m){ int i, j, temp; for(i = 0; i < m - 1; i++){ for(j = 0; j < m - 1 - i; j++){ if(a[m + 1][3] > a[m][3]){ temp = a[m][0]; a[m][0] = a[m+1][0]; a[m+1][0] = temp; temp = a[m][1]; a[m][1] = a[m+1][1]; a[m+1][1] = temp; temp = a[m][2]; a[m][2] = a[m+1][2]; a[m+1][2] = temp; } } } for(i = 0; i < m; i++){ printf("%d %d %d\n", a[m][0], a[m][1], a[m][2]); } } int main (void){ int sum, l, h, cnt = 0, a[100000][4], b[100000][4], c[100000][4], d[100000][4], num, mor, tal; int m = 0, n = 0, p = 0, q = 0, i; scanf("%d %d %d", &sum, &l, &h); for(i = 0; i < sum; i++){ scanf("%d %d %d", &num, &mor, &tal); if(mor >= l && tal >= l){ cnt++; if(mor >= h){ if(tal >= h){ a[m][0] = num; a[m][1] = mor; a[m][2] = tal; a[m][3] = mor + tal; m++; } else{ b[n][0] = num; b[n][1] = mor; b[n][2] = tal; b[n][3] = mor + tal; n++; } } else{ if(mor >= tal){ c[p][0] = num; c[p][1] = mor; c[p][2] = tal; c[p][3] = mor + tal; p++; } else{ d[q][0] = num; d[q][1] = mor; d[q][2] = tal; d[q][3] = mor + tal; q++; } } } } printf("%d\n", cnt); print(a, m); print(b, n); print(c, p); print(d, q); return 0; } <file_sep>/50 practice/01.cpp /* (if判断)输入三个实数,判断组成三角形形状。若为正三角形则输出1,位等腰三角形则输出2,为任意三角形则输出3,不能构成三角形则输出0. */ #include<stdio.h> int main (void) { int a, b, c; puts("请输入三个实数:"); printf("实数1:",a); scanf("%d",&a); printf("实数2:",b); scanf("%d",&b); printf("实数3:",c); scanf("%d",&c); if(a+b<c || a+c<b|| b+c<a) puts("0"); else if( a==b && a==c) puts("1"); else if ( a==b || a==c || b==c) puts("2"); else if ( (a + b) > c || (a + c) > b || (b + c) > a) puts("3"); else puts("0"); return 0; } <file_sep>/PAT/1028.c #include<stdio.h> #include <string.h> int main (void){ int n, max = 20140906, min = 18140906, sum, cnt = 0, i, year, month, day; char name[6], old_name[6], young_name[6]; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%s %d/%d/%d", name, &year, &month, &day); sum = year * 10000 + month * 100 + day; if(sum >= 18140906 && sum <= 20140906){ cnt++; if(sum < max){ max = sum; strcpy(old_name, name); } if(sum > min){ min = sum; strcpy(young_name, name); } } } if(cnt != 0){ printf("%d %s %s\n", cnt, old_name, young_name); } else{ printf("0"); } return 0; } // //int year(int a){ // if(a % 400 == 0 || ( a % 4 == 0 && a % 100 != 0)){ // return 1; // } // else return 0; //} // //int date(int a, int b, int c){ // if(b > 0 && b < 13){ // if((b == 4 || b == 6 || b == 9 || b == 11) && c <= 30){ // return 1; // } // else if((b == 1 || b == 3 || b == 5 || b == 7 || b == 8 || b == 10 || b == 12) && c <= 31){ // return 1; // } // else if(b == 2){ // if(year(a) && c <= 29){ // return 1; // } // else if(!year(a) && c <= 28){ // return 1; // } // else{ // return 0; // } // } // else return 0; // } // else return 0; //} <file_sep>/50 practice/36.c #include<stdio.h> int main (void){ int i, n, year, month, day; char name[100000][6]; int yearmin = 1814; int monthmin = 9; int daymin = 6; int yearmax = 2014; int monthmax = 9; int daymax = 6; char min, max; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%s", name[i]); scanf("%d/%d/%d", &year, &month, &day); if((year < 1814) || ((year = 1814) && (month < 9)) || ((year = 1814) && (month = 9) && (day < 6))){ n--; if(year < yearmin){ min = name[i]; } else if((year = yearmin) && (month < monthmin)){ min = name[i]; } else if((year = yearmin) && (month = monthmin) && (day < daymin)){ min = name[i]; } else{ min = 'nobody'; } if(year > yearmax){ max = name[i]; } else if((year = yearmax) && (month > monthmax)){ max = name[i]; } else if((year = yearmax) && (month = monthmax) && (day > daymax)){ max = name[i]; } else{ max = 'nobody'; } } } printf("%d %s %s", n, max, min); return 0; } <file_sep>/PAT/1015(2).c #include<stdio.h> typedef struct{ int number; int morality; int talent; int type; int sum; } Student; void swap(Student *x, Student *y){ Student temp = *x; *x = *y; *y = temp; } // //int classify(Student x, int l, int h){ // int cnt = 0; // // if(x.morality >= l && x.talent >= l){ // cnt++; // x.sum = x.morality + x.talent; // if(x.morality >= h){ // if(x.talent >= h){ // x.type = 1; // } // else{ // x.type = 2; // } // } // else{ // if(x.morality >= x.talent){ // x.type = 3; // } // else{ // x.type = 4; // } // } // } // else{ // x.type = 5; // x.sum = 0; // } // // return cnt; //} int main (void){ int num = 0, n, l, h, i, j; Student x[1000]; scanf("%d %d %d", &n, &l, &h); for(i = 0; i < n; i++){ scanf("%d %d %d", &x[i].number, &x[i].morality, &x[i].talent); if(x[i].morality >= l && x[i].talent >= l){ num++; x[i].sum = x[i].morality + x[i].talent; if(x[i].morality >= h){ if(x[i].talent >= h){ x[i].type = 1; } else{ x[i].type = 2; } } else{ if(x[i].morality >= x[i].talent){ x[i].type = 3; } else{ x[i].type = 4; } } } else{ x[i].type = 5; x[i].sum = 0; } } for(i = 0; i < num - 1; i++){ for(j = 0; j < num - 1 - i; j++){ if(x[j].type > x[j + 1].type){ swap(&x[j], &x[j + 1]); } else if(x[j].type == x[j + 1].type && x[j].sum < x[j + 1].sum){ swap(&x[j], &x[j + 1]); } else if(x[j].type == x[j + 1].type && x[j].sum == x[j + 1].sum && x[j].morality < x[j + 1].morality){ swap(&x[j], &x[j + 1]); } else if(x[j].type == x[j + 1].type && x[j].sum == x[j + 1].sum && x[j].morality == x[j + 1].morality && x[j].number > x[j + 1].number){ swap(&x[j], &x[j + 1]); } } } printf("%d\n", num); for(i = 0; i <= num; i++){ if(x[i].sum > 0){ printf("%d %d %d\n", x[i].number, x[i].morality, x[i].talent); } } return 0; } <file_sep>/PAT/1026(2).c #include<stdio.h> int main (void){ int c1, c2, t; scanf("%d %d", &c1, &c2); t = (c2 - c1 + 50) / 100; printf("%02d:%02d:%02d\n", t/3600, t%3600/60, t%60); return 0; } <file_sep>/PAT/1032.c #include<stdio.h> int main (void){ int n, i, j, flag = 1, max = 0; int a[100000][2], b[100000][2] = {0}; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%d %d", &a[i][0], &a[i][1]); } for(j = 1; j <= n; j++){ for(i = 0; i < n; i++){ if(a[i][0] == j){ b[j][1] += a[i][1]; } if(b[j][1] > max){ max = b[j][1]; flag = j; } } } printf("%d %d", flag, max); return 0; } <file_sep>/PAT/1013.c #include<stdio.h> #include<math.h> int is_prime(int i){ int j, cnt = 1; for(j = 2; j <= sqrt(i); j++){ if(i % j == 0){ cnt = 0; } } return cnt; } int main (void){ int i = 0, m, n, num = 1, a[10000], cnt = 0; scanf("%d %d", &m, &n); while(i <= n){ if(is_prime(num)) a[i++] = num; num++; } for(i = m; i < n; i++){ cnt++; if(cnt % 10) printf("%d ", a[i]); else printf("%d\n", a[i]); } printf("%d", a[n]); return 0; } <file_sep>/PAT/1008.c #include<stdio.h> int main (void){ int i, m, n, a[102]; scanf("%d %d", &m, &n); for(i = 0; i < m; i++){ scanf("%d", &a[i]); } if(n > m){ n %= m; } for(i = m - n; i <= m - 1; i++){ printf("%d ", a[i]); } for(i = 0; i <= m - n - 1; i++){ printf("%d", a[i]); if(i < m - n - 1){ printf(" "); } } return 0; } <file_sep>/50 practice/33.c #include<stdio.h> #include<stdlib.h> void put_char(int n, char a){ while(n-- > 0) putchar(a); } void put_block(int n, char a){ n -= 2; while(n-- > 0) putchar(' '); } int main (void){ int n, i, n1, n2; char a; scanf("%d ", &n); a = getchar(); put_char(n, a); printf("\n"); if(n % 2 == 1){ n1 = n + 1; n2 = n; } for( i = 0; i < (n1/2 - 2); i++){ putchar(a); put_block( n2, a); putchar(a); printf("\n"); } put_char( n2, a); return 0; } <file_sep>/50 practice/30(error).c #include<stdio.h> int str_dcount(const char a[], int n){ int i = 0; int cnt = 0; while(a[i]){ if(a[i] == 'n'){ cnt++; } } return cnt; } int sum(int cnt, int n){ int sum = n; while(--cnt){ sum *= 10; sum += n; } return sum; } int main (void){ int n1, n2, cnt1, cnt2; char a[100000000], b[1000000000]; scanf("%s %d %s %d", a, &n1, b, &n2); cnt1 = str_count(a, n1); cnt2 = str_count(b, n2); printf("%d", sum(cnt1, n1) + sum(cnt2, n2)); return 0; } <file_sep>/50 practice/25.c #include<stdio.h> #include<math.h> int main (void){ int n; double r1, r2, p1, p2; scanf("%f %f %f %f", &r1, &p1, &r2, &p2); a1 = r1 * cos(p1); a2 = r2 * cos(p2); b1 = r1 * return 0; } <file_sep>/50 practice/03.cpp #include<stdio.h> #define NUMBER 3 void put_chars(int n) { while(n++ > 0) putchar(' '); } int main (void) { int i, a, j; int n = NUMBER; for(i = 1; i <= n; i++){ put_chars(n); for(a = 0; a < (2*n-1); a++){ printf("*"); } printf("\n"); } return 0; } <file_sep>/50 practice/13.cpp #include<stdio.h> int main (void){ int n, i; int a[10][3]; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%d %d %d", &a[i][0], &a[i][1], &a[i][2]); } for(i = 0; i < n; i++){ if((a[i][0] + a[i][1]) > a[i][2]) printf("Case #%d: ture\n", i); else printf("Case #%d: false\n", i); } return 0; } <file_sep>/50 practice/17.cpp #include<stdio.h> int main (void){ int m, n, i, j; int num = 0; int a[10000]; int k = 0; scanf("%d %d", &m, &n); for(i = 0; i < 10000; i++){ int isprime = 1; for(j = 2; j < i - 1; j++){ if( i % j == 0){ isprime = 0; break; } } if( isprime ){ a[k] = i; k++; } } for(k = m; k <= n; k++){ printf("%d ", a[k + 1]); num++; if(num % 10 == 0){ printf("\n"); } } return 0; } <file_sep>/50 practice/08.c #include<stdio.h> int main (void){ int n, i, x, min, max, sum; while(scanf("%d", &n) != EOF){ scanf("%d", &x); min = max = sum = x; for(i = 1; i < n; i++){ scanf("%d", &x); sum += x; max = (x > max) ? x : max; min = (x < min) ? x : min; } printf("%.2f\n", (double)(sum - max - min) / (n - 2)); } return 0; } <file_sep>/PAT/1020.c #include<stdio.h> int main (void){ float money, x, y; int type, quality, a[1000], b[1000], i, j, sum, temp; scanf("%d %d", &type, &quality); for(i = 0; i < type; i++){ scanf("%d", &a[i]); } for(i = 0; i < type; i++){ scanf("%d", &b[i]); } for(i = 0; i < type - 1; i++){ for(j = 0; j < i - type - 1; j++){ x = b[j] / a[j]; y = b[j + 1] / a[j + 1]; printf("j = %d, x = %d, y = %d\n", j, x, y); if(a[j] < b[j]){ temp = b[j]; b[j] = b[j + 1]; b[j + 1] = temp; // temp = a[j]; // a[j] = a[j + 1]; // a[j + 1] = temp; } } } printf("%d %d %d\n", a[0], a[1], a[2]); printf("%d %d %d\n", b[0], b[1], b[2]); sum = a[0]; ; while(1){ if(quality > sum){ sum += a[i + 1]; money += a[i] * b[i]; } else{ money += (quality - sum) * b[i]; } } printf("%0.2f", money); return 0; } <file_sep>/PAT/1032(2).c #include <stdio.h> int school[100000]={0};//题目要求把数组的声明放在第1行 int main(){ int n,id,score; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d%d",&id,&score); school[id]+=score;//将id相同的score累加起来,统计总成绩 } int k=-1,max=-1; for(int i=1;i<=n;i++){//遍历 if(school[i]>max){//遍历比较 max=school[i];//将最大值赋给max k=i; //记录下标 } } printf("%d %d",k,max); return 0; } <file_sep>/50 practice/06.c #include<stdio.h> #include<math.h> int main(void){ int n, i, j, a[100]; while(scanf("%d", &n) && n!= 0){ for(i = 0; i < n; i++){ scanf("%d", &a[i]); } for(i = 0; i < n - 1; i++){ for(j = 0; j < n - 1 - i; j++){ if(abs(a[j]) < abs(a[j + 1])){ int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } for(i = 0; i < n; i++){ if(i < n - 1){ printf("%d ", a[i]); } else printf("%d", a[i]); } printf("\n"); } return 0; } <file_sep>/50 practice/39(error).c #include<stdio.h> int main (void){ int i, n, end; int a[100]; int sum = 0; int cnt = 0; do{ scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%d", &a[i]); } }while(scanf("%d", &end) == 0); for(i = 0; i < n; i++){ if(a[i] >= 100){ cnt += a[i] / 100; a[i] -= 100 * cnt; } else if(a[i] >= 50 && a[i] != 0){ cnt += a[i] / 50; a[i] -= 50 * cnt; } else if(a[i] >= 10 && a[i] != 0){ cnt += a[i] / 10; a[i] -= 10 * cnt; } else if(a[i] >= 5 && a[i] != 0){ cnt += a[i] / 5; a[i] -= 5 * cnt; } else if(a[i] >= 2 && a[i] != 0){ cnt += a[i] / 2; a[i] -= cnt * 2; } else if(a[i] >= 1 && a[i] != 0){ cnt += a[i]; } printf("%d\n", cnt); sum += cnt; } printf("%d", sum); return 0; } <file_sep>/PAT/1063.c #include<stdio.h> #include<math.h> int main (void){ int n, a, b, i; float sum, max = 0; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%d %d", &a, &b); sum = sqrt(a * a + b * b); if(sum > max){ max = sum; } } printf("%.2f", max); return 0; } <file_sep>/PAT/1038(3).c #include <stdio.h> //这一版改进的地方在于最后一个不输出空格的方式,好好看哦 int main() { int n, grade[101] = {0}, x; scanf("%d", &n); while(n--){ scanf("%d", &x); grade[x]++; } scanf("%d", &n); while(n){ scanf("%d", &x); printf("%d%c", grade[x], n > 1 ? ' ' : '\n'); n--; } return 0; } <file_sep>/PAT/10171.c #include<stdio.h> #include<string.h> int main (void){ int b, q, r, a, i; char str[1001]; scanf("%s %d", str, &b); if(strlen(str) == 1){ printf("%d %d", (str[0] - '0') / b, (str[0] - '0') % b); } else{ if(str[0] - '0' > b || strlen(str) == 1){ printf("%d", (str[0] - '0') / b); a = ((str[0] - '0') % b) * 10 + (str[1] - '0'); } else{ a = (str[0] - '0') * 10 + (str[1] - '0'); } r = a % b; q = a / b; printf("%d", q); for(i = 1; i < strlen(str) - 1; i++){ a = r * 10 + (str[i + 1] - '0'); q = a / b; printf("%d", q); r = a % b; } printf(" %d", r); } return 0; } <file_sep>/50 practice/05.cpp #include <stdio.h> int main (void){ int m, n, t; scanf("%d %d", &m, &n); if(m < n){ int temp = n; n = m; m = temp; } do{ t = m % n; m = n; n = t; }while(t != 0); printf("%d", m); return 0; } <file_sep>/50 practice/16.cpp #include<stdio.h> int main (void){ int n, i, j, k; char str[100]; int cnt[][5] = {0}; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%s", str); for(j = 0; str[j] != '\0'; j++){ if(str[j] == 'a') cnt[i][0]++; else if(str[j] == 'e') cnt[i][1]++; else if(str[j] == 'i') cnt[i][2]++; else if(str[j] == 'o') cnt[i][3]++; else if(str[j] == 'u') cnt[i][4]++; } } for(k = 0; k < n; k++){ printf("a:%d\n", cnt[k][0]); printf("e:%d\n", cnt[k][1]); printf("i:%d\n", cnt[k][2]); printf("o:%d\n", cnt[k][3]); printf("u:%d\n", cnt[k][4]); if(k != n) printf("\n"); } return 0; } <file_sep>/50 practice/38.c #include<stdio.h> int main(void){ int a[100][100]; int sum[100]; int i, j, n, m; scanf("%d %d", &n, &m); for(i = 0; i < n + 2; i++){ for(j = 0; j < m; j++){ scanf("%d", &a[i][j]); } } for(i = 2; i < n + 2; i++){ for(j = 0; j < m; j++){ if(a[i][j] == a[1][j]){ sum[i] += a[0][j]; } } printf("%d\n", sum[i]); } return 0; } <file_sep>/50 practice/11.cpp #include<stdio.h> int main (void){ int a[100000]; int n, m, i, j, k; //输入n和m while(scanf("%d %d", &n, &m)!=EOF){ //输入n个数字 for(i = 0; i < n; i++){ scanf("%d", a[i]); } //n个数字排序 for(j = 0; j < n; j++){ for(k = n - 1; k > j; k--){ if(a[k - 1] < a[k]){ int temp = a[k]; a[k] = a[k - 1]; a[k - 1] = temp; } } } //n个数字中挑m个输出 for(i = 0; i < m; i++){ printf("%d", a[i]); } } return 0; } <file_sep>/PAT/1040.c #include<stdio.h> #include<string.h> int main (void){ char str[100000]; int cnt = 0, flag, i, j, k; scanf("%s", str); for(i = 0; i < strlen(str); i++){ flag = 0; if(str[i] == 'P'){ for(j = i; j < strlen(str); j++){ if(str[j] == 'A'){ for(k = j; k < strlen(str); k++){ if(str[k] == 'T'){ cnt++; if(cnt == 1000000007){ cnt = 0; } flag = 1; break; } } } if(flag == 1) break; } } } printf("%d", cnt); return 0; } <file_sep>/PAT/1038(2).c #include<stdio.h> //这一版比上一版改进的地方在于,把分数储存起来做一个数组,这样的话只要输入一个数字就可以存放到相应的数组里面。 //一定要注意,分数的这个数组声明时要声明101,而不是100,别忘了还有一个0 int main (void){ int n1, n2, i, j; int score, num[101] = {0}, tag; scanf("%d", &n1); for(i = 0; i < n1; i++){ scanf("%d", &score); num[score]++; } scanf("%d", &n2); for(i = 0; i < n2; i++){ scanf("%d", &tag); printf("%d", num[tag]); if(i < n2 - 1){ printf(" "); } } return 0; } <file_sep>/PAT/1009.c #include<stdio.h> #include <string.h> int main (void){ char str[81]; int n, j = 0, i; int b[80]; gets(str); n = strlen(str); for(i = 0; i < n; i++){ if(str[i] == ' '){ b[j++] = i; } } for(i = str[b[j] + 1]; i < str[n]; i++){ printf("%s", str[i]); } printf(" "); while(j >= 0){ for(i = str[b[j] + 1]; i < str[b[j + 1] - 1]; i++){ printf("%s", str[i]); } printf(" "); j--; } return 0; } <file_sep>/PAT/1037.c #include<stdio.h> int main (void){ int pa, pb, pc, aa, ab, ac, p, a, b, c, diff; scanf("%d.%d.%d %d.%d.%d", &pa, &pb, &pc, &aa, &ab, &ac); p = pa * 17 * 29 + pb * 29 + pc; a = aa * 17 * 29 + ab * 29 + ac; if(p > a){ printf("-"); diff = p - a; } else{ diff = a - p; } a = diff / (17 * 29); b = (diff - a * 17 * 29) / 29; c = diff - a * 17 * 29 - b * 29; printf("%d.%d.%d", a, b, c); return 0; } <file_sep>/PAT/1038.c #include<stdio.h> int main (void){ int n1, n2, i, j; int score[100000], tag[100000], num[100000] = {0}; scanf("%d", &n1); for(i = 0; i < n1; i++){ scanf("%d", &score[i]); } scanf("%d", &n2); for(i = 0; i < n2; i++){ scanf("%d", &tag[i]); } for(i = 0; i < n1; i++){ for(j = 0; j < n2; j++){ if(score[i] == tag[j]){ num[j]++; break; } } } for(j = 0; j < n2 - 1; j++){ printf("%d ", num[j]); } printf("%d", num[n2 - 1]); return 0; } <file_sep>/PAT/1041.c #include<stdio.h> int main (void){ char str[1001][20], x, ch; int m, n, i, j, k, s; scanf("%d", &n); fflush(stdin); for(i = 0; i < n; i++){ s = 0; while((ch = getchar()) != '\n'){ str[i][s] = ch; s++; } } scanf("%d", &m); fflush(stdin); for(i = 0; i <= m; i++){ scanf("%c", &x); for(j = 0; j < n; j++){ if(x == str[j][17]){ for(k = 0; k < 17; k++){ printf("%c", str[j][k]); } printf("%c\n", str[j][19]); } } } return 0; } <file_sep>/50 practice/21.c #include<stdio.h> int main (void){ int n; int a[1001]; int i; a[1] = 0; a[2] = 2; a[3] = 2; for(i = 4; i < 1001; i++){ a[i] = (a[i - 1] + a[i - 2] * 2) % 10000; } while(scanf("%d", &n), n){ printf("%d\n", a[n]); } return 0; } <file_sep>/PAT/1019.c #include<stdio.h> #include<stdlib.h> int cmp1(const void *a, const void *b){ return *(int *)a - *(int *)b; } int cmp2(const void *a, const void *b){ return *(int *)b - *(int *)a; } int upper(int n){ int i, j, temp, a[4], x; for(i = 0; i < 4; i++){ a[i] = n % 10; n /= 10; } qsort(a, 4, sizeof(a[0]), cmp1); x = a[0]; for(i = 0; i < 3; i++){ x = x * 10 + a[i + 1]; } return x; } int lower(int n){ int i, j, temp, a[4], x; for(i = 0; i < 4; i++){ a[i] = n % 10; n /= 10; } qsort(a, 4, sizeof(a[0]), cmp2); x = a[0]; for(i = 0; i < 3; i++){ x = x * 10 + a[i + 1]; } return x; } int main(void){ int n, diff, up, low; scanf("%d", &n); up = upper(n); low = lower(n); diff = low - up; if(diff == 0){ printf("%04d - %04d = %04d\n", low, up, diff); } else{ while(1){ if(diff == 0){ printf("%04d - %04d = %04d\n", low, up, diff); break; } else if(diff == 6174){ printf("%04d - %04d = %04d\n", low, up, diff); break; } else{ printf("%04d - %04d = %04d\n", low, up, diff); up = upper(diff); low = lower(diff); diff = low - up; if(diff == 6174){ printf("%04d - %04d = %04d\n", low, up, diff); break; } } } } return 0; } <file_sep>/50 practice/14.cpp #include<stdio.h> int main (void){ int a[100]; int i, j, k, n; int min = 1000000; while((scanf("%d", &n)) != 0){ for(i = 0; i < n; i++){ scanf("%d", &a[i]); if(a[i] < min){ min = a[i]; k = i; } } a[k] = n; a[0] = min; for(j = 0; j < n; j++){ printf("%d ", a[j]); } } return 0; } <file_sep>/PAT/1010.c #include<stdio.h> int main (void){ int a[100],b[100]; int i = 0; int j; int a,b; int flag = 0; while(scanf("%d %d",&a,&b)==2){ if(b!=0){ if(flag == 0)printf("%d",a*b); else printf(" %d",a*b); printf(" %d",b-1); flag = 1; } } if(flag==0)printf("0 0"); return 0; } <file_sep>/PAT/1015(3).c #include<stdio.h> #include<stdlib.h> int L, H; // 录取最低分数线和优先录取线 typedef struct Student { int id; // 准考证号 short de, cai, all; // 德分,才分,总分 char level; // 等级,A圣人,B君子,C愚人,D小人,E淘汰 }Stu; // 考生 Stu stu[100001]; // 考生 char getLevel(short de, short cai) { if (de >= H) { if (cai >= H) { return 'A'; // 圣人 } else if (cai >= L) { return 'B'; // 君子 } else { return 'E'; // 淘汰 } } else if (de >= L) { if (cai >= H) { return 'D'; // 小人 } else if (cai >= L) { if (de >= cai) { return 'C'; // 愚人 } else { return 'D'; // 小人 } } else { return 'E'; // 淘汰 } } else { return 'E'; // 淘汰 } } int compare(const Stu* stu1, const Stu* stu2) { if (stu1->level != stu2->level) { // 等级不同 return stu1->level - stu2->level; // 按照等级升序排列 } if (stu1->all != stu2->all) { // 等级相同,总分不同 return stu2->all - stu1->all; // 按照总分降序排列 } if (stu1->de != stu2->de) { // 等级和总分都相同,德分不同 return stu2->de - stu1->de; // 按照德分降序排列 } return stu1->id - stu2->id; // 若等级,总分,德分都相同,按照准考证号升序排列 } int main() { int N, enter; // enter录取的人数 scanf("%d%d%d", &N, &L, &H); // 输入人数,最低录取分数线和优先录取线 enter = N; // 初始全部录取 for (int i = 0; i < N; i++) { scanf("%d%d%d", &stu[i].id, &stu[i].de, &stu[i].cai); // 考生信息 stu[i].all = stu[i].de + stu[i].cai; // 计算总分 stu[i].level = getLevel(stu[i].de, stu[i].cai); // 分级 if ('E' == stu[i].level) { enter--; // 若考生被淘汰,录取人数减1 } } qsort(stu, N, sizeof(Stu), compare); // 排序,头文件stdlib.h printf("%d\n", enter); for (int i = 0; i < enter; i++) { printf("%d %d %d\n", stu[i].id, stu[i].de, stu[i].cai); } } <file_sep>/50 practice/43(error).c #include<stdio.h> int main (void){ int m, n, a, b, x, i, j; int s[100][500]; scanf("%d %d %d %d %d", &m, &n, &a, &b, &x); for(i = 0; i < m; i++){ for(j = 0; j < n; j++){ scanf("%d", &s[i][j]); } } for(i = 0; i < m; i++){ for(j = 0; j < n; j++){ if((s[i][j] >= a) && (s[i][j] <= b)){ s[i][j] = x; } printf("%.3d", s[i][j]); if(j < n){ printf(" "); } } printf("\n"); } return 0; } <file_sep>/PAT/1019(2).c #include<stdio.h> #include<stdlib.h> int cmp(const void *a, const void *b){ return *(int *)a - *(int *)b; } int main(void){ int n, diff, up, low, x, i, a[4] = {0}; scanf("%d", &n); while(n != 0){ x = n; for(i = 0; i < 4; i++){ a[i] = x % 10; x /= 10; } qsort(a, 4, sizeof(a[0]), cmp); up = a[0] * 1000 + a[1] * 100 + a[2] * 10 + a[3]; low = a[3] * 1000 + a[2] * 100 + a[1] * 10 + a[0]; n = low - up; if(n == 0){ printf("%04d - %04d = %04d\n", low, up, n); } else{ printf("%04d - %04d = %04d\n", low, up, n); if(n == 6174){ break; } } } return 0; } <file_sep>/PAT/1027.c #include<stdio.h> #include<math.h> int between(int i, int n){ int small = 2 * i * i - 1; int big = 2 * (i + 1) * (i + 1) - 1; if(n >= small && n < big){ return 1; } else{ return 0; } } void print(int i, char str){ int k, j = 0; while(i > 1){ for(k = 0; k < j; k++){ printf(" "); } j++; for(k = 0; k < (2 * i - 1); k++){ printf("%c", str); } i--; printf("\n"); } while(j >= 0){ for(k = 0; k < j; k++){ printf(" "); } j--; for(k = 0; k < (2 * i - 1); k++){ printf("%c", str); } i++; printf("\n"); } } int main (void){ int n, i, remain; char str; scanf("%d %ch", &n, &str); for(i = 0; i <= sqrt(n) + 1; i++){ if(between(i, n)){ print(i, str); remain = n - (2 * i * i - 1); printf("%d", remain); break; } } return 0; } <file_sep>/50 practice/35.c #include<stdio.h> int main (void){ int n, i, j, k, t; double h; double max[100] = {0}; scanf("%d", &t); for(k = 0; k < t; k++){ scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%lf", &h); if(h > max[k]){ max[k] = h; } } } for(j = 0; j < t; j++){ printf("%.2f\n", max[j]); } return 0; } <file_sep>/50 practice/46(error).c #include<stdio.h> int sum_count(x){ int sum = 0; int d; do{ d = x % 10; x /= 10; sum += d; }while(x > 0); return sum; } int main (void){ int n, i, j, k; int sum[100]; int b[100], a[100], c[100]; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%d", &a[i]); sum[i] = sum_count(a[i]); } for(i = 0; i < n - 1; i++){ for(j = n - 1; j > i; j--){ if(sum[j - 1] >= sum[j]){ int temp = sum[j]; sum[j] = sum[j - 1]; sum[j - 1] = temp; } } } k = 0; for(i = 1; i < n; i++){ if(sum[i] != sum[i - 1]){ k++; c[k] = i; } } printf("%d\n", k + 1); printf("%d ", sum[0]); for(i = 1; i < k; i++){ printf("%d ", sum[c[i]]); } printf("%d", sum[c[k]]); return 0; } <file_sep>/PAT/1007.c #include<stdio.h> int main(void){ int n, k, i; int j = 0; int a[10000]; int cnt = 0; scanf("%d", &n); for(i = 1; i < 10000; i++){ int isPrime = 1; for(k = 2; k < i - 1; k++){ if(i % k == 0){ isPrime = 0; break; } } if(isPrime == 1){ a[j] = i; j++; } } for( k = 1; k <= n; k++){ if(a[k + 1] - a[k] == 2){ cnt++; } } printf("%d", cnt / 2); return 0; } <file_sep>/PAT/1003.c #include<stdio.h> int main (void){ char str[100]; int a = 0, z = 0, p = 0, t = 0, i = 0; scanf("%s", str); while(str[i] != '\0'){ if(str[i] == 'A'){ a++; } if (str[i] == ' '){ z++; } if(str[i] == 'P'){ p++; } if(str[i] == 'T'){ t++; } i++; } printf("i = %d, a = %d, z = %d, p = %d, t = %d", i, a, z, p, t); } <file_sep>/50 practice/34.c #include<stdio.h> int main (void){ int x = 0; int y = 0; int i, j, n; int a[100][4]; scanf("%d", &n); for(i = 0; i < n; i++){ for(j = 0; j < 4; j++){ scanf("%d", &a[i][j]); } if((a[i][1] == a[i][0] + a[i][2]) && (a[i][3] != a[i][0] + a[i][2])){ y++; } else if((a[i][1] != a[i][0] + a[i][2]) && (a[i][3] == a[i][0] + a[i][2])){ x++; } } printf("%d %d", x, y); return 0; } <file_sep>/PAT/1011.c #include<stdio.h> int main (void){ // int n, i; // double a, b, c; // // scanf("%d", &n); // // for(i = 0; i < n; i++){ // scanf("%lf%lf%lf", &a, &b, &c); // if(a + b > c){ // printf("Case #%d: true\n", i + 1); // } // else{ // printf("Case #%d: false\n", i + 1); // } // } double a, b, c; scanf("%f%f%f", &a, &b, &c); printf("%f %f %f\n", a, b, c); scanf("%f %f %f", &a, &b, &c); printf("%f %f %f\n", a, b, c); scanf("%lf%lf%lf", &a, &b, &c); printf("%f %f %f\n", a, b, c); scanf("%lf %lf %lf", &a, &b, &c); printf("%f %f %f\n", a, b, c); return 0; } <file_sep>/PAT/1012.c #include<stdio.h> int main (void){ int i, n, x, t = 0, m, cnt[6] = {0}; float a[6] = {0}; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%d", &x); m = x % 5; switch( m ){ case 0: if(x % 2 == 0) { a[1] += x; cnt[1]++;} break; case 1: if(cnt[2] % 2){ x = -x; } a[2] += x; cnt[2]++; break; case 2: a[3]++; cnt[3]++; break; case 3: cnt[4]++; a[4] += x; break; case 4: if(x > a[5]) a[5] = x; cnt[5]++; break; } } if(a[4] != 0) a[4] /= cnt[4]; for(i = 1; i <= 5; i++){ if(a[i] == 0 && cnt[i] == 0){ printf("N"); } else{ if(i == 4){ printf("%.1f", a[i]); } else{ printf("%.0f", a[i]); } } if(i <= 4){ printf(" "); } } return 0; } <file_sep>/50 practice/12.cpp #include<stdio.h> int main (void){ int n; int m = 0; scanf("%d", &n); while(n != 1){ if( n % 2 == 0) n /= 2; else n = (3*n+1) / 2; m++; } printf("%d", m); return 0; } <file_sep>/PAT/1039.c #include<stdio.h> #include<string.h> int main (void){ int cnt = 0, lack = 0, flag = 1, i; char str[10000], ch; scanf("%s", str); fflush(stdin); while((ch = getchar()) != '\n'){ i = 0; cnt++; while(ch != str[i]){ i++; if(i == strlen(str)){ flag = 0; lack++; } } if(ch == str[i]){ str[i] = '*'; } } if(flag){ printf("Yes %d", (strlen(str) - cnt)); } else{ printf("No %d", lack); } return 0; } <file_sep>/PAT/1014.c #include<stdio.h> #include<string.h> void week(char str){ char weekname[][4] = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}; char week[8] = "ABCDEFG"; int i; for(i = 0; i < 7; i++){ if(str == week[i]){ printf("%s ", weekname[i]); } } } void hour(char str){ int hour[24], i; char hourname[24] = "0123456789ABCDEFGHIJKLMN"; for(i = 0; i < 24; i++){ hour[i] = i; if(str == hourname[i]){ printf("%02d:", hour[i]); } } } int main(void){ char a[61], b[61], c[61], d[61]; int i; scanf("%s %s %s %s", a, b, c, d); for(i = 0; i < strlen(a); i++){ if(a[i] == b[i] && a[i] >= 'A' && a[i] <= 'Z'){ week(a[i]); i++; break; } } while(i < strlen(a)){ if((a[i] >= 'A' && a[i] <= 'Z') || (a[i] >= '0' && a[i] <= '9')){ if(a[i] == b[i]){ hour(a[i]); break; } } i++; } for(i = 0; i < strlen(c); i++){ if( c[i] >= 'a' && c[i] <= 'z' && c[i] == d[i]){ printf("%02d", i); break; } } return 0; } <file_sep>/50 practice/42(error).c #include<stdio.h> #include<string.h> int main (void){ int n; int a, b, c, d, i, j, len; char str[50]; scanf("%d", &n); while(n--){ for(i = 0; i < n; i++){ a = b = c = d = 0; scanf("%s", str); len = strlen(str); if(len >= 8 && len <= 16){ for(j = 0; j < len; j++){ if('A' <= str[j] && str[j] <= 'Z'){ a = 1; } else if('a' <= str[j] && str[j] <= 'z'){ b = 1; } else if('0' <= str[j] && str[j] <= '9'){ c = 1; } else if(str[j] == '~' || str[j] == '@' || str[j] == '%' || str[j] == '!'){ d = 1; } } int count = a + b + c + d; if(count >= 3){ printf("YES\n"); } else{ printf("NO\n"); } break; } printf("NO\n"); } } return 0; } <file_sep>/PAT/1036.c #include<stdio.h> int main (void){ int n, i, col, k; char ch; scanf("%d %c", &n, &ch); if(n == 1){ printf("%c", ch); } else if(n == 2){ printf("%c%c", ch, ch); } else{ if(n % 2){ col = n / 2 + 1; } else{ col = n / 2; } for(k = 0; k < n; k++){ printf("%c", ch); } printf("\n"); for(i = 2; i < col; i++){ printf("%c", ch); for(k = 0; k < n - 2; k++){ printf(" "); } printf("%c\n", ch); } for(k = 0; k < n; k++){ printf("%c", ch); } } return 0; } <file_sep>/50 practice/44(error).c #include<stdio.h> int main (void){ int i, sum, pass, n; char str[17]; int a[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; char b[] = { '1','0','X','9','8','7','6','5','4','3','2' }; scanf("%d", &n); while(n--){ scanf("%s", str); sum = 0; for(i = 0; i < 17; i++){ if(str[i] >= '0' && str[i] <= '9'){ sum += (str[i] - '0') * a[i]; if(i == 16){ if(str[17] == b[sum % 11]){ pass = 0; } else{ pass = 1; puts(str); break; } } } else{ pass = 1; puts(str); break; } } } if(pass == 0){ printf("All passed"); } return 0; } <file_sep>/PAT/1043.c #include<stdio.h> int main (void){ char ch; int a[6] = {0}; while((ch = getchar()) != '\n'){ if(ch == 'P'){ a[0]++; } else if(ch == 'A'){ a[1]++; } else if(ch == 'T'){ a[2]++; } else if(ch == 'e'){ a[3]++; } else if(ch == 's'){ a[4]++; } else if(ch == 't'){ a[5]++; } } while(a[0] > 0 || a[1] > 0 || a[2] > 0 || a[3] > 0 || a[4] > 0 || a[5] > 0){ if(a[0] > 0){ printf("P"); a[0]--; } if(a[1] > 0){ printf("A"); a[1]--; } if(a[2] > 0){ printf("T"); a[2]--; } if(a[3] > 0){ printf("e"); a[3]--; } if(a[4] > 0){ printf("s"); a[4]--; } if(a[5] > 0){ printf("t"); a[5]--; } } return 0; } <file_sep>/50 practice/45(error).c #include<stdio.h> #include<string.h> int main (void){ int a1, a2, a3; char str[100]; int i, len; while(scanf("%s", str) != EOF){ if(str == 'E') break; a1 = a2 = a3 = 0; len = strlen(str); for(i = 0; i < len; i++){ if(str[i] == 'Z'){ a1++; } if(str[i] == 'O'){ a2++; } if(str[i] == 'J'){ a3++; } } while (a1 != 0 || a2 != 0 || a3 != 0){ if (a1 != 0){ a1--; printf("Z"); } if (a2 != 0){ a2--; printf("O"); } if (a3 != 0){ a3--; printf("J"); } } return 0; } <file_sep>/50 practice/04.cpp #include<stdio.h> int main (void){ int i, j; int m = 0; for(i = 0; i < 100; i++){ for(j = 2; j < i-1; j++){ if(i % j != 0){ printf("%2d ", i); m++; } if(m % 5 == 0) printf("\n"); break; } } return 0; } <file_sep>/50 practice/09(error).c #include<stdio.h> int main (void){ int num[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int sum, year, month, day, i; while(scanf("%d/%d/%d", &year, &month, &day) != EOF){ sum = 0; for(i = 0; i < month - 1; i++){ sum += num[i]; } if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){ sum += 1; } printf("%d\n", sum + day); } } <file_sep>/50 practice/10(error).c #include<stdio.h> int main (void){ int a[51][6]; int n, m, i, j; int sum = 0; scanf("%d %d", &n, &m); for(i = 0; i < n; i++){ for(j = 0; j < m; j++){ scanf("%d ", a[i][j]); a[i][6] += a[i][j]; a[51][j] += a[i][j]; } } for(i = 0; i < n; i++){ printf("%.2d ", a[i][6] / m); } for(j = 0; j < m; j++){ printf("%.2d", a[51][j] / n); } for(i = 0; i < n; i++){ for(j = 0; j < m; j++){ if(a[i][j] < a[i][6] / m) break; else sum = 1; } sum += sum; } return 0; } <file_sep>/PAT/1002.c #include<stdio.h> int main (void){ int n, x, t, i; int sum = 0; int mask = 1; char str[100]; scanf("%s", str); i = 0; while(str[i] != '\0'){ sum += str[i] - '0'; i++; } t = sum; while(t > 9){ t /= 10; mask *= 10; } while(mask > 0){ x = sum / mask; sum %= mask; mask /= 10; switch(x){ case 0: printf("ling"); break; case 1: printf("yi"); break; case 2: printf("er"); break; case 3: printf("san"); break; case 4: printf("si"); break; case 5: printf("wu"); break; case 6: printf("liu"); break; case 7: printf("qi"); break; case 8: printf("ba"); break; case 9: printf("jiu"); break; } if(mask > 0){ printf(" "); } } return 0; } <file_sep>/50 practice/23.c #include<stdio.h> int main (void){ int i; char n; int a[10] = {0}; while((n = getchar()) != '\n'){ switch(n - '0'){ case 0 : a[0]++; break; case 1 : a[1]++; break; case 2 : a[2]++; break; case 3 : a[3]++; break; case 4 : a[4]++; break; case 5 : a[5]++; break; case 6 : a[6]++; break; case 7 : a[7]++; break; case 8 : a[8]++; break; case 9 : a[9]++; break; } } for(i = 0; i < 10; i++){ if(a[i] > 0){ printf("%d:%d\n", i, a[i]); } } return 0; } <file_sep>/PAT/1016.c #include<stdio.h> int sum(int da, int a_num){ int sum = 0, i; for(i = 1; i <= a_num; i++){ sum = sum*10 + da; } return sum; } int main (void){ int a, da, b, db, a_num[10] = {0}, b_num[10] = {0}; scanf("%d %d %d %d", &a, &da, &b, &db); while(a > 0){ a_num[a % 10]++; a /= 10; } while(b > 0){ b_num[b % 10]++; b /= 10; } printf("%d", sum(da, a_num[da]) + sum(db, b_num[db])); } <file_sep>/50 practice/28.c #include<stdio.h> int main (void){ int n, i, j, k; char str[1000][1000]; int cnt[1000]; scanf("%d", n); for(i = 0; i < n; i++){ scanf("%s", str[i]); } for(j = 0; j < n; j++){ while(str[j][k]){ if((str[j][k] >= '0') && (str[j][k] <= '9')){ cnt[i]++; } k++; } } return 0; } <file_sep>/PAT/1005.c #include<stdio.h> void bsort(int c[], int j){ int p, q; for(p = 0; p < j - 1; p++){ for(q = j - 1; q > p; q--){ if(c[q - 1] < c[q]){ int temp = c[q]; c[q] = c[q - 1]; c[q - 1] = temp; } } } } int main (void){ int n, i, j, p, q, k; int a[100], b[100], c[100]; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%d", &a[i]); b[i] = a[i]; } for(i = 0; i < n; i++){ while(a[i] != 1){ if(a[i] % 2 == 0){ a[i] /= 2; for(k = 0; k < n; k++){ if(b[k] == a[i]){ b[k] = 0; } } } else{ a[i] = (3*a[i] + 1) / 2; for(k = 0; k < n; k++){ if(b[k] == a[i]){ b[k] = 0; } } } } } j = 0; for(k = 0; k < n; k++){ if(b[k] != 0){ c[j] = b[k]; j++; } } bsort(c, j); for(k = 0; k < j; k++){ printf("%d", c[k]); if(k < j - 1){ printf(" "); } } return 0; } <file_sep>/50 practice/31.c #include<stdio.h> int main (void){ int i, j, t; int a[100], b[100]; scanf("%d", &t); for(i = 0; i < t; i++){ scanf("%d %d", &a[i], &b[i]); } for(j = 0; j < t; j++){ if((a[j] % b[j]) != 0){ printf("NO\n"); } else{ printf("YES\n"); } } return 0; } <file_sep>/50 practice/27.c #include<stdio.h> int main (void){ scanf("%lf %d", sum, m); for(i = 0; i < m; i++){ scanf("%d", n); for(j = 0; j < n; j++){ n = getchar(); scanf("%f", &count) printf("%s:%f", n, count); } } return 0; } <file_sep>/PAT/1006.c #include<stdio.h> int main (void){ int n, a, b, c; int i = 1; scanf("%d", &n); a = n / 100; b = (n - 100 * a) / 10; c = n % 10; while(a > 0){ printf("B"); a--; } while(b > 0){ printf("S"); b--; } while(i <= c){ printf("%d", i); i++; } return 0; } <file_sep>/50 practice/02.cpp #include<stdio.h> int main (void) { int a, b; puts("请输入两门课的成绩。"); printf("第一门课:"); scanf("%d", &a); printf("第二门课:"); scanf("%d", &b); if ( 0 < a && a < 100 && 0 < b && b < 100){ switch(a > 60 && b > 60 ){ case 0: printf("it is not pass."); break; case 1: printf("it is pass."); break; } } else printf("it is error."); return 0; } <file_sep>/PAT/1004.c #include<stdio.h> int main (void){ int n, i; char name[100][11], number[100][11]; int score[100]; int max = 0, min = 100, tempmax = 0, tempmin = 0; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%s %s %d", name[i], number[i], &score[i]); if(score[i] > max){ max = score[i]; tempmax = i; } if(score[i] < min){ min = score[i]; tempmin = i; } } printf("%s %s", name[tempmax], number[tempmax]); printf("\n"); printf("%s %s", name[tempmin], number[tempmin]); return 0; } <file_sep>/50 practice/22.c #include<stdio.h> int main (void){ int c1, c2, hh, mm, x, y, s; double diff, ss; scanf("%d %d", &c1, &c2); diff = (c2 - c1) / 100.00; hh = diff / 3600; mm = (diff - hh * 3600) / 60; ss = diff - hh * 3600 - mm * 60.0; x = ss * 10; y = x % 10; if(y >= 5){ s = (x + 10) / 10; } printf("%d:%d:%d", hh, mm, s); return 0; } <file_sep>/PAT/1026.c #include<stdio.h> int main (void){ int before, after, diff, hour, minute, second; scanf("%d %d", &before, &after); diff = after - before; if(diff % 100 >= 50){ diff += 100; } diff /= 100; hour = diff / 3600; minute = (diff - hour * 3600) / 60; second = diff - hour * 3600 - minute * 60; printf("%02d:%02d:%02d", hour, minute, second); return 0; } <file_sep>/PAT/1022.c #include<stdio.h> int main (void){ int a, b, c, i = 0, sum, n[32] = {0}; scanf("%d %d %d", &a, &b, &c); sum = a + b; while(1){ n[i] = sum % c; if(sum / c == 0){ break; } i++; sum /= c; } while(i >= 0){ printf("%d", n[i]); i--; } return 0; } <file_sep>/50 practice/24.c #include<stdio.h> int main (void){ int n, x, m, t1, t2; int sum = 0; int mask = 1; scanf("%d", &n); t1 = n; do{ x = t1 % 10; t1 /= 10; sum += x; }while(x > 0); t2 = sum; while( t2 > 9){ t2 /= 10; mask *= 10; } while(mask > 0){ m = sum / mask; sum %= mask; mask /= 10; switch(m / 1){ case 0 : printf("ling"); break; case 1 : printf("yi"); break; case 2 : printf("er"); break; case 3 : printf("san"); break; case 4 : printf("si"); break; case 5 : printf("wu"); break; case 6 : printf("liu"); break; case 7 : printf("qi"); break; case 8 : printf("ba"); break; case 9 : printf("jiu"); break; } if(mask > 0){ printf(" "); } } return 0; }
df2b7cdf59e15946f5baa9e833d6a0d9b01812a9
[ "C", "C++" ]
75
C
lilixuelian/C-exercise
ea79d7ba1fb39f6a2c82cfe90ff02c62a608df0a
2a58df9b1ade91d95e0fc67782194a648ea57228
refs/heads/master
<repo_name>sajadkhosravi/FerdowsiMechanismDesignApp<file_sep>/src/algorithms/assignment/schoolChoice/Student.java package algorithms.assignment.schoolChoice; class Student { private String name; private School[] preference; private School school; private int lastProposed; Student(String name, School[] preference) { this.name = name; this.preference = preference; this.lastProposed = -1; } public String getName() { return name; } public void setName(String name) { this.name = name; } public School[] getPreference() { return preference; } public void setPreference(School[] preference) { this.preference = preference; } public School getSchool() { return school; } public void setSchool(School school) { this.school = school; } public boolean initialPropose() { this.lastProposed++; if(this.lastProposed >= this.preference.length) return false; return this.preference[this.lastProposed].addToProposeList(this); } @Override public String toString() { return this.name; } }<file_sep>/src/algorithms/assignment/serialDictatorship/SerialDictatorship.java package algorithms.assignment.serialDictatorship; import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class SerialDictatorship { private List<Agent> agents; private List<Obj> objs; public SerialDictatorship(String[] agents, Obj[] objs, Obj[][] agentPreferences) { this.agents = new ArrayList<Agent>(); this.objs = new ArrayList<Obj>(); for(int i = 0; i < objs.length; i++){ this.objs.add(new Obj(objs[i].getName())); } for(int i = 0; i < agents.length; i++){ this.agents.add(new Agent(agents[i], agentPreferences[i])); } } public List<List<Integer>> SD() { boolean foundPreference = false; List<List<Integer>> result = new ArrayList<List<Integer>>(); for(Agent agent: this.agents) { int[] currentAgentList = new int[objs.size()]; int currentAgentListIndex = 0; foundPreference = false; for(Obj preference: agent.getPreference()) { currentAgentListIndex = 0; if(!foundPreference) { for(Obj realObject: objs) { if(realObject.getName() == preference.getName() && !realObject.getAssigned()) { realObject.setAssigned(true); currentAgentList[currentAgentListIndex] = 1; foundPreference = true; break; } else if(realObject.getName() == preference.getName()) { break; } currentAgentListIndex++; } } } ArrayList<Integer> currentAgentArrayList = new ArrayList<Integer>(); for(int cell: currentAgentList) { currentAgentArrayList.add(cell); } result.add(currentAgentArrayList); } return result; } // public static void main(String[] args) { // Obj obj1 = new Obj("obj1"); // Obj obj2 = new Obj("obj2"); // Obj obj3 = new Obj("obj3"); // Obj obj4 = new Obj("obj4"); // String[] agents = {"agentB", "agentA"}; // Obj[] objs = {obj1, obj2, obj3, obj4}; // Obj[][] agentPreferences = { // {obj2, obj3, obj4, obj1}, // {obj1, obj3, obj4, obj2} // }; // SerialDictatorship sd = new SerialDictatorship(agents, objs, agentPreferences); // System.out.println(sd.SD()); // } }<file_sep>/src/algorithms/assignment/envyFree/Envy.java package algorithms.assignment.envyFree; import java.util.ArrayList; import java.util.List; public class Envy { /** * کلاسی برای ذخیریه نتیجه مقایسه هر دو سطر یک ماتریس یا هر دو عامل می باشد * این کلاس دارای متغیرهای agent و virvalAgent‌ می باشد که به ترتیب نشان دهنده عامل اصلی و عامل مقایسه شده می باشد * نتیجه مقایسه در متغیر Ressult ذخیره می شود که متغیر Result‌ از نوع Status‌ می باشد که در کلاس Status ‌بیشتر مورد بررسی قرار می گیرد */ private class Result { int Agent; int virvalAgent; Status Ressult; Result(int agent, int virvalAgent, Status ressult) { Agent = agent; this.virvalAgent = virvalAgent; Ressult = ressult; } } /** * نوع داده ای برای نگه داری ۳ وضعیت Envy ، Weakly_envy_free ، Envy_free می باشد. * وضعیت Envy که با کد صفر مشخص می شود برای زمانی است که عامل نسبت به عامل‌ های دیگر مغلوب شده باشد. * وضعیت Weakly_envy_free که با کد ۱ مشخص می شود برای زمانی است که عامل حداقل با یک عامل دیگر برابر باشد و نبست به دیگر عامل ها غالب باشد. * وضعیت Envy_free که با کد ۲ مشخص می شود برای زمانی است که عامل نسبت به دیگر عامل ها غالب باشد. */ private enum Status { Envy(0), Envy_free(2), Weakly_envy_free(1); private int Value; Status(int value) { this.Value = value; } public int getValue() { return Value; } // به منظور برگرداندن وضعیت با استفاده از کد وضعیت public static Status getStatus(int code) { Status status = null; for (Status item : values()) { if (item.Value == code) { status = item; } } return status; } } /** * تنها تابع کلاس Envy می باشد که از خارج کلاس در دسترس می باشد و در واقع تابعی است که مدیریت روال برنامه را بر عهدا دارد. * @param assigmentMatrix ماتریس تخصیص * @param preferMatrix ماتریس ترجیحات * در مرحله اول تعدادی ماتریس تخصیص مرتب شده براساس ماتریس ترجیحات ایجاد می کند و در sortedMatrixs نگه می دارد. * در مرحله دوم سطر های هر ماتریس را با سطر عامل مقایسه کرده و نتایج را در لیستی به نام resultForRows ذخیره می کند. * در مرحله سوم بررسی می کنیم ماتریس تخصیص ارایه شده کدام یک از ۳ وضعیت یاد شده در بالا را داراست. و در متغیر statusForMatrix ذخیره می کند. * * در نهایت آماده رشته ای با ترتیب خاص برای بر گرداندن ایجاد می کند. * @return * برگرداندن رشته ای با فرمت خاص */ public String Execute(double[][] assigmentMatrix, int[][] preferMatrix) { StringBuilder outPut = new StringBuilder(); //مرحله اول List<double[][]> sortedMatrixs = Sort(assigmentMatrix, preferMatrix); //مرحله دوم List<Result> resultForRows = Compare(sortedMatrixs); // مرحله سوم Status statusForMatrix = CompareMatrix(resultForRows); // ایجاد رشته برای خروجی outPut.append(Print.PrepareForPrint(assigmentMatrix,preferMatrix,sortedMatrixs,resultForRows,statusForMatrix)); return outPut.toString(); } //region Sort /** * * @param assigmentMatrix ماتریس تخصیص * @param preferMatrix ماتریس ترجیحات * * @return * * به تعداد سطر های ماتریس ترجیحات تعدادی ماتریس تخصیص مرتب شده براساس ماتریس ترجیحات را بر می گرداند * */ private List<double[][]> Sort(double[][] assigmentMatrix, int[][] preferMatrix) { List<double[][]> sortedMatrixs = new ArrayList<>(); for (int[] row : preferMatrix) { int j = 0; double[][] newNatrix = CreateMatrix(assigmentMatrix.length,assigmentMatrix[0].length); for (int index : row) { for (int i = 0; i < assigmentMatrix.length; i++) { newNatrix[i][j] = assigmentMatrix[i][index]; } j++; } sortedMatrixs.add(newNatrix); } return sortedMatrixs; } /** * * @param rowNumber تعداد سطر ها ماتریس مورد نظر * @param columnNumber تعداد ستون های ماتریس مورد نظر * @return * ماتریسی با ابعاد مورد نظر و مقدار اولیه صفر ایجاد می کند */ private double[][] CreateMatrix(int rowNumber , int columnNumber) { double[][] tempMatrix = new double[rowNumber][]; for (int i=0;i<rowNumber;i++) { tempMatrix[i] =new double[columnNumber]; } return tempMatrix; } //endregion //region Compare /** * در این تابع سطرهای هر ماتریس را جدا نموده و به همراه سطر عامل مورد نظر ( که همان سطر با شماره ماتریس می باشد) را برای مشخص شدن وضعیت سطر عامل نسبت به دیگر سطرها را به تابع ()CompareAgents می فرستد و نتیجه را در لیستی از Result به نام result اضافه می کند. * @param sortedMatrixs لیستی از ماتریس مرتب شده * @return *لیت result را برمی گرداند */ private List<Result> Compare(List<double[][]> sortedMatrixs) { List<Result> results = new ArrayList<>(); for (int agent = 0; agent < sortedMatrixs.size(); agent++) { double[][] matrix = sortedMatrixs.get(agent); for (int virval = 0; virval < matrix.length; virval++) { double[] ComparativeRow = matrix[virval]; if (virval != agent) { double[] MainRow = matrix[agent]; Status status = CompareAgents(MainRow, ComparativeRow); results.add(new Result(agent, virval, status)); } } } return results; } /** * ابتدا مورد اول هر دو تخصیص را مقایسه می کند : * اگر تخصیص عامل مورد نظر ار تخصیص دیگر بزرگتر بود آنگاه عامل مورد نظر نسبت به عامل دیگر Envy_free‌ می باشد و نتیجه را بر می گردانیم. * اگر تخصیص عامل مورد نظر از تخصیص دیگر کوچکتر بود آنگاه عامل مورد نظر نسبت به عامل دیگر Envy می باشد و نتیجه را بر می گردانیم. * اگر دو تخصیص برابر بود مجموع دو مورد اول را طبق الگوریتم بالا مقایسه می کنیم تا زمانی که در یکی از حالات بالا متوقف شویم یا تا انتهای تخصیص را بررسی کنیم که در حات دوم نتیجه می گیریم دو تخصیص نسبت به هم Weakly_envy_free می باشند و نتیجه را بر کی گردانیم. * @param MainRow تخصیص عامل مورد نظر * @param ComparativeRow عاملی که قرار است با عامل مورد نظر مقایسه شود * * @return * برگرداندن وضعیت دو عامل */ private Status CompareAgents(double[] MainRow, double[] ComparativeRow) { double mainAgent = 0; double comparativeAgent = 0; Status status = null; for (int i = 0; i < MainRow.length - 1; i++) { mainAgent += MainRow[i]; comparativeAgent += ComparativeRow[i]; int compareResult = Double.compare(mainAgent, comparativeAgent); if (compareResult > 0) { status = Status.Envy_free; break; } else if (compareResult < 0) { status = Status.Envy; break; } else // if == 0 { continue; } } if (status == null) { status = Status.Weakly_envy_free; } return status; } //endregion //region CompareMatrix /** * در این تابع وضعیت عامل ها را بررسی کرده و وضیعیت با کمترین کد را به عنوان وضعیت ماتریس انتخاب می کنیم که در نوع داده ای Status‌ کد ها را بررسی کردیم * @param resultForRows نتیجه مقایسه سطر ها * @return * وضعیت ماتریس */ private Status CompareMatrix(List<Result> resultForRows) { int minimumState = 10; for (Result row : resultForRows) { if (row.Ressult.getValue() < minimumState) { minimumState = row.Ressult.Value; } } return Status.getStatus(minimumState); } //endregion /** * در این کلاس صرفا نتیجه نهایی را برای چا آماده می کنیم که به ترتیتب زیر موارد را چاپ می کند * ابتدا ماتریس تخصیص را چا می کند * سپس ماتریس ترجیحات چاپ می شود * سپس به ازای هر ماتریس مرتب شده * ابتدا ماتریس مرتب شده آن چاپ می شود * سپس وضعیت عامل آن ماتریس نسبت به دیگر عامل ها * در ادامه وضعیت کلی آن عامل چاپ می شود * در انتها وضعیت کلی ماتریس چاپ می شود */ private static class Print { static StringBuilder PrepareForPrint(double[][] assigmentMatrix, int[][] preferMatrix, List<double[][]> sortedMatrixs, List<Result> resultForRows, Status statusForMatrix) { StringBuilder outPut = new StringBuilder(); outPut.append("assigmentMatrix : \n"); outPut.append(printMatrix(assigmentMatrix)); outPut.append("\n"); outPut.append("preferMatrix : \n"); outPut.append(printMatrix(preferMatrix)); outPut.append("********************************************************\n"); for (int matrixNumber=0;matrixNumber<sortedMatrixs.size();matrixNumber++) { double[][] matrix = sortedMatrixs.get(matrixNumber); outPut.append("P(").append(matrixNumber).append(") = \n"); outPut.append(printMatrix(matrix)); outPut.append(printResults(resultForRows,matrixNumber)); outPut.append("----------------------------------------------------\n"); } outPut.append("********************************************************\n"); outPut.append("The Assignment of P is : ").append(statusForMatrix).append("\n"); return outPut; } private static StringBuilder printResults(List<Result> resultForRows , int agent ) { StringBuilder print = new StringBuilder(); print.append("\n"); int minimumStatus = 10; for (Result result : resultForRows) { if (result.Agent == agent) { print.append("Agent").append(agent).append(" to ").append("Agent").append(result.virvalAgent) .append(" = ").append(result.Ressult).append("\n"); if (minimumStatus > result.Ressult.getValue()) { minimumStatus = result.Ressult.getValue(); } } } print.append("\n"); print.append("General State of Agent").append(agent).append(" ").append(Status.getStatus(minimumStatus)).append("\n"); return print; } private static StringBuilder printMatrix(double[][] matrix) { StringBuilder print = new StringBuilder(); for (double[] row : matrix) { for (double index : row) { print.append(index).append(" "); } print.append("\n"); } return print; } private static StringBuilder printMatrix(int[][] matrix) { StringBuilder print = new StringBuilder(); for (int[] row : matrix) { for (int index : row) { print.append(index).append(" "); } print.append("\n"); } return print; } } } <file_sep>/README.md # FerdowsiMechanismDesignApp this is a application contain some of mechanism desing algorithem implementation ## INSTALL ``` git clone https://github.com/sajadkh/FerdowsiMechanismDesignApp.git ``` RUN /src/ui/Main.java ## INPUTS for enter input please enter arrays element between {} and separate them with , for example ``` [1,2,3] = {1,2,3} ``` and for 2D Arrays please enter each row between {} for example ``` [[1,2,3],[4,5,6]] = {{1,2,3},{4,5,6}} ``` <file_sep>/src/algorithms/assignment/randomSerialDictatorship/AgentPreferencesStructure.java package algorithms.assignment.randomSerialDictatorship; import java.util.*; final class AgentPreferencesStructure { private int Index; public int getIndex() { return Index; } public void setIndex(int value) { Index = value; } private String Agent; public String getAgent() { return Agent; } public void setAgent(String value) { Agent = value; } private ArrayList<Integer> Objects; public ArrayList<Integer> getObjects() { return Objects; } public void setObjects(ArrayList<Integer> value) { Objects = value; } }<file_sep>/src/algorithms/assignment/randomSerialDictatorship/RSD.java package algorithms.assignment.randomSerialDictatorship; import java.util.*; import java.lang.*; public class RSD { private int countOfObjects; private int countOfAgents; private ArrayList<boolean[]> AssignedMatrixes; private void permutation(AgentPreferencesStructure[] arr, int k) { if (k >= arr.length) { RefObject<AgentPreferencesStructure[]> tempRef_arr = new RefObject<AgentPreferencesStructure[]>(arr); assign(tempRef_arr); arr = tempRef_arr.argValue; } else { permutation(arr, k + 1); for (int i = k + 1; i < arr.length; i++) { RefObject<AgentPreferencesStructure> tempRef_Object = new RefObject<AgentPreferencesStructure>(arr[k]); RefObject<AgentPreferencesStructure> tempRef_Object2 = new RefObject<AgentPreferencesStructure>(arr[i]); swap(tempRef_Object, tempRef_Object2); arr[i] = tempRef_Object2.argValue; arr[k] = tempRef_Object.argValue; permutation(arr, k + 1); RefObject<AgentPreferencesStructure> tempRef_Object3 = new RefObject<AgentPreferencesStructure>(arr[k]); RefObject<AgentPreferencesStructure> tempRef_Object4 = new RefObject<AgentPreferencesStructure>(arr[i]); swap(tempRef_Object3, tempRef_Object4); arr[i] = tempRef_Object4.argValue; arr[k] = tempRef_Object3.argValue; } } } private <AgentPreferencesStructure> void swap(RefObject<AgentPreferencesStructure> item1, RefObject<AgentPreferencesStructure> item2) { AgentPreferencesStructure temp = item1.argValue; item1.argValue = item2.argValue; item2.argValue = temp; } private void assign(RefObject<AgentPreferencesStructure[]> arr) { ArrayList<Integer> servedObjects = new ArrayList<Integer>(); boolean[] tempAssign = new boolean[countOfObjects * arr.argValue.length]; for (int i = 0; i < arr.argValue.length; i++) for (int j = 0; j < countOfObjects; j++) { if (j >= arr.argValue[i].getObjects().size()) break; if (servedObjects.contains(arr.argValue[i].getObjects().get(j))) continue; servedObjects.add(arr.argValue[i].getObjects().get(j)); tempAssign[arr.argValue[i].getIndex() * arr.argValue.length + arr.argValue[i].getObjects().get(j)] = true; break; } AssignedMatrixes.add(tempAssign); } public String DoRSD(String[] objects, String[] agentPreferences) { try { this.countOfObjects = objects.length; this.countOfAgents = agentPreferences.length; System.out.println(this.countOfAgents); ArrayList<AgentPreferencesStructure> agents = new ArrayList<AgentPreferencesStructure>(this.countOfObjects); for (int i = 0; i < this.countOfObjects; i++) { String objectsOrderSplitRegex = "\\s*,[,\\s]*"; String[] temp = agentPreferences[i].split(":"); AgentPreferencesStructure tempAgentPreferencesStructure = new AgentPreferencesStructure(); tempAgentPreferencesStructure.setObjects(new ArrayList<Integer>()); tempAgentPreferencesStructure.setAgent(temp[0]); tempAgentPreferencesStructure.setIndex(i); String[] tempAgentPreferencesArray = temp[1].replace("[", "").replace("]", "").split(objectsOrderSplitRegex); for(int j=0;j<tempAgentPreferencesArray.length;j++){ int selectedObjectIndex = Integer.parseInt(tempAgentPreferencesArray[j]) - 1; if (selectedObjectIndex < 0 || selectedObjectIndex >= this.countOfObjects) throw new Exception("Its not correct, please try again!"); if (tempAgentPreferencesStructure.getObjects().contains(selectedObjectIndex)) throw new Exception("The choosen preference was selected that, please try another one!"); tempAgentPreferencesStructure.getObjects().add(selectedObjectIndex); } agents.add(tempAgentPreferencesStructure); } AssignedMatrixes = new ArrayList<boolean[]>(); permutation(agents.toArray(new AgentPreferencesStructure[0]), 0); int[] tempFinalMatrix = new int[this.countOfObjects * this.countOfAgents]; String[] finalMatrix = new String[this.countOfObjects * this.countOfAgents]; for (int i = 0; i < AssignedMatrixes.size(); i++) for (int j = 0; j < tempFinalMatrix.length; j++) tempFinalMatrix[j] += (AssignedMatrixes.get(i)[j] ? 1 : 0); String result = "<table><tr><td></td>"; for (int i = 0; i < this.countOfObjects; i++) result += String.format("<td>%1$s</td>", objects[i]); result += "</tr>"; for (int i = 0; i < tempFinalMatrix.length; i++) { if (i % this.countOfObjects == 0) { result += "</tr><tr>"; result += String.format("<td>%1$s</td>", agents.get(i / countOfObjects).getAgent()); } finalMatrix[i] = String.format("%1$s/%2$s", tempFinalMatrix[i], AssignedMatrixes.size()); result += String.format("<td>%1$s</td>", finalMatrix[i]); } result += "</tr></table>"; return result; } catch (Exception ex) { return ex.getMessage(); } } }
8426e17f64f392abb4e908603dc251abf566e985
[ "Markdown", "Java" ]
6
Java
sajadkhosravi/FerdowsiMechanismDesignApp
c03ea736abc2e76f38ace802e7bef54da4589503
325ba45b875643cebd45682cc8cef9468f846253
refs/heads/master
<repo_name>hwei/ScorePlugin<file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/ScoreDynmap.java package me.hwei.bukkit.scoreplugin; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import me.hwei.bukkit.scoreplugin.data.Storage; import me.hwei.bukkit.scoreplugin.data.Work; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.plugin.Plugin; import org.dynmap.DynmapCommonAPI; import org.dynmap.markers.MarkerAPI; import org.dynmap.markers.MarkerIcon; import org.dynmap.markers.MarkerSet; import org.dynmap.markers.Marker; public class ScoreDynmap implements Listener { static protected ScoreDynmap Instance = null; static void Update() { if(Instance == null) return; Instance.update(); } static Listener getSetupListerner() { return new Listener() { @SuppressWarnings("unused") @EventHandler(priority=EventPriority.MONITOR) public void onPluginEnable(PluginEnableEvent event) { Plugin p = event.getPlugin(); String name = p.getDescription().getName(); if(name.equals("dynmap")) { Setup(p); } } }; } public static void Setup(Plugin dynmap) { DynmapCommonAPI dynmapCoreAPI = (DynmapCommonAPI)dynmap; Instance = new ScoreDynmap(dynmapCoreAPI.getMarkerAPI()); Instance.update(); } protected ScoreDynmap(MarkerAPI markerAPI) { this.layers = new ArrayList<Layer>(); if(ScoreConfig.getDynmapDisplayOpen()) this.layers.add(new OpenScoreLayer(markerAPI)); if(ScoreConfig.getDynmapDisplayClosed()) this.layers.add(new ClosedScoreLayer(markerAPI)); } protected List<Layer> layers; protected void update() { for(Layer layer : this.layers) { layer.update(); } } private class OpenScoreLayer extends Layer { public OpenScoreLayer(MarkerAPI markerAPI) { MarkerSet markerSet = markerAPI.getMarkerSet("score.open"); if(markerSet == null) { markerSet = markerAPI.createMarkerSet( "score.open", "Score-open", null, false); } else { markerSet.setMarkerSetLabel("Score-open"); } MarkerIcon markerIcon = markerAPI.getMarkerIcon("star"); this.Init(markerSet, markerIcon); } @Override protected List<MarkerData> getMarkers() { List<Work> works = Storage.GetInstance().loadOpenWorkList(1000); ArrayList<MarkerData> markers = new ArrayList<MarkerData>(works.size()); for(int i=0; i<works.size(); ++i) { Work work = works.get(i); MarkerData markerData = new MarkerData(); markerData.id = work.getWork_id(); markerData.worldName = work.getWorld(); markerData.locX = work.getPos_x(); markerData.locY = work.getPos_y(); markerData.locZ = work.getPos_z(); markerData.label = work.getName(); markerData.description = String.format( "<table><caption>Score</caption><tbody><tr><td>Name</td><td><strong>%s</strong></td></tr><tr><td>Author</td><td><strong>%s</strong><img src=\"tiles/faces/16x16/%s.png\"></td></tr><tr><td>TP</td><td><strong>%d</strong></td></tr></tbody></table>", work.getName(), work.getAuthor(), work.getAuthor(), i); markers.add(markerData); } return markers; } } private class ClosedScoreLayer extends Layer { public ClosedScoreLayer(MarkerAPI markerAPI) { MarkerSet markerSet = markerAPI.getMarkerSet("score.closed"); if(markerSet == null) { markerSet = markerAPI.createMarkerSet( "score.closed", "Score-closed", null, false); } else { markerSet.setMarkerSetLabel("Score-closed"); } MarkerIcon markerIcon = markerAPI.getMarkerIcon("goldstar"); this.Init(markerSet, markerIcon); } @Override protected List<MarkerData> getMarkers() { List<Work> works = Storage.GetInstance().loadClosedWorkList(1000); ArrayList<MarkerData> markers = new ArrayList<MarkerData>(works.size()); for(int i=0; i<works.size(); ++i) { Work work = works.get(i); MarkerData markerData = new MarkerData(); markerData.id = work.getWork_id(); markerData.worldName = work.getWorld(); markerData.locX = work.getPos_x(); markerData.locY = work.getPos_y(); markerData.locZ = work.getPos_z(); markerData.label = work.getName(); markerData.description = String.format( "<table><caption>Score</caption><tbody><tr><td>Name</td><td><strong>%s</strong></td></tr><tr><td>Author</td><td><strong>%s</strong><img src=\"tiles/faces/16x16/%s.png\"></td></tr><tr><td>Score</td><td><strong>%.2f</strong></td></tr></tbody></table>", work.getName(), work.getAuthor(), work.getAuthor(), work.getScore()); markers.add(markerData); } return markers; } } private abstract class Layer { protected Layer() { } protected void Init(MarkerSet markerSet, MarkerIcon markerIcon) { this.markerSet = markerSet; this.markerIcon = markerIcon; this.oldMarkers = new TreeMap<Integer, Marker>(); } private MarkerSet markerSet; private MarkerIcon markerIcon; private Map<Integer, Marker> oldMarkers; protected abstract List<MarkerData> getMarkers(); public void update() { List<MarkerData> markers = this.getMarkers(); Map<Integer, Marker> newMarkers = new TreeMap<Integer, Marker>(); for(MarkerData markerData : markers) { Marker marker = this.oldMarkers.remove(markerData.id); if(marker == null) { marker = this.markerSet.createMarker( Integer.toString(markerData.id), markerData.label, markerData.worldName, markerData.locX, markerData.locY, markerData.locZ, this.markerIcon, false); marker.setDescription(markerData.description); } else { marker.setLocation( markerData.worldName, markerData.locX, markerData.locY, markerData.locZ); marker.setLabel(markerData.label); marker.setMarkerIcon(this.markerIcon); marker.setDescription(markerData.description); } newMarkers.put(markerData.id, marker); } for(Marker marker : this.oldMarkers.values()) { marker.deleteMarker(); } this.oldMarkers.clear(); this.oldMarkers = newMarkers; } } private class MarkerData { public String label; public String description; public int id; public String worldName; public int locX; public int locY; public int locZ; } } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/commands/ReloadCommand.java package me.hwei.bukkit.scoreplugin.commands; import org.bukkit.command.CommandSender; import me.hwei.bukkit.scoreplugin.ScoreConfig; import me.hwei.bukkit.scoreplugin.util.AbstractCommand; import me.hwei.bukkit.scoreplugin.util.LanguageManager; import me.hwei.bukkit.scoreplugin.util.OutputManager; import me.hwei.bukkit.scoreplugin.util.UsageException; public class ReloadCommand extends AbstractCommand { public ReloadCommand(String usage, String perm, AbstractCommand[] children) throws Exception { super(usage, perm, children); } @Override protected boolean execute(CommandSender sender, MatchResult[] data) throws UsageException { ScoreConfig.Reload(); LanguageManager.Reload(); OutputManager.GetInstance().toSender(sender).output("Reloaded."); return true; } } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/listeners/ScoreBlockListener.java package me.hwei.bukkit.scoreplugin.listeners; import me.hwei.bukkit.scoreplugin.ScoreSignHandle; import me.hwei.bukkit.scoreplugin.ScoreSignUtil; import me.hwei.bukkit.scoreplugin.util.IOutput; import me.hwei.bukkit.scoreplugin.util.OutputManager; import me.hwei.bukkit.scoreplugin.util.PermissionManager; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.SignChangeEvent; public class ScoreBlockListener implements Listener { @EventHandler public void onBlockDamage(BlockDamageEvent event) { if (event.isCancelled()) return; Block block = event.getBlock(); if (block.getType() != Material.SIGN_POST && block.getType() != Material.WALL_SIGN) { return; } if(PermissionManager.GetInstance().hasPermission(event.getPlayer(), "score.break")) return; Sign sign = (Sign)block.getState(); if(ScoreSignHandle.IsProtected(sign)) { event.setCancelled(true); } } @EventHandler public void onBlockBreak(BlockBreakEvent event) { if (event.isCancelled()) return; Block block = event.getBlock(); if (block.getType() != Material.SIGN_POST && block.getType() != Material.WALL_SIGN) { return; } Sign sign = (Sign)block.getState(); Player player = event.getPlayer(); IOutput toPlayer = OutputManager.GetInstance().toSender(player); boolean removed = ScoreSignHandle.Remove(toPlayer, sign, PermissionManager.GetInstance().hasPermission(player, "score.break")); if(!removed) { event.setCancelled(true); } } @EventHandler public void onBlockPhysics(BlockPhysicsEvent event) { if (event.isCancelled()) return; Block block = event.getBlock(); if (block.getType() != Material.SIGN_POST && block.getType() != Material.WALL_SIGN) { return; } Sign sign = (Sign)block.getState(); if(ScoreSignHandle.IsProtected(sign)) { event.setCancelled(true); } } @EventHandler public void onSignChange(SignChangeEvent event) { if (event.isCancelled()) return; if(! PermissionManager.GetInstance().hasPermission(event.getPlayer(), "score.create")) return; ScoreSignUtil.GetInstance().create(event); } } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/ScoreSignUtil.java package me.hwei.bukkit.scoreplugin; import me.hwei.bukkit.scoreplugin.data.Work; import org.bukkit.ChatColor; import org.bukkit.block.Sign; import org.bukkit.event.block.SignChangeEvent; public class ScoreSignUtil { protected ScoreSignUtil(String signHeader) { this.signHeader = signHeader; } public Work read(Sign sign) { if(sign == null) return null; String signHeader = sign.getLine(0); if(!signHeader.equalsIgnoreCase(this.signHeader) && !signHeader.equalsIgnoreCase(ChatColor.DARK_BLUE.toString() + this.signHeader)) { return null; } Work work = new Work(); work.setName(sign.getLine(1)); String authorLine = sign.getLine(3); if(authorLine.startsWith(ChatColor.DARK_GRAY.toString())) { work.setAuthor(authorLine.substring(2)); } else { work.setAuthor(authorLine); } work.setWorld(sign.getWorld().getName()); work.setPos_x(sign.getX()); work.setPos_y(sign.getY()); work.setPos_z(sign.getZ()); return work; } public void write(Sign sign, Work work) { if(sign == null) return; sign.setLine(0, ChatColor.DARK_BLUE.toString() + this.signHeader); sign.setLine(1, work.getName()); if(work.getWork_id() == null) { sign.setLine(2, ""); } else { sign.setLine(2, work.getReward() == null ? ChatColor.DARK_RED.toString() + "open" : ChatColor.YELLOW.toString() + String.format("%.2f", work.getScore())); } sign.setLine(3, ChatColor.DARK_GRAY.toString() + work.getAuthor()); sign.update(); } public void create(SignChangeEvent event) { if(!event.getLine(0).equalsIgnoreCase(this.signHeader)) { return; } event.setLine(2, ""); event.setLine(3, ChatColor.DARK_GRAY.toString() + event.getPlayer().getName()); } public double calcAuthorReward(double score, double maxReward) { double score_threshold = ScoreConfig.getAutherScoreThreshold(); if(score > score_threshold) { return maxReward * (score - score_threshold) / (10.0 - score_threshold); } else if(score_threshold == 10.0) { return score == 10.0 ? maxReward : 0.0; } else { return 0.0; } } public double calcViewerReward(double score, double viewer_score) { double diff = Math.abs(score - viewer_score); double max_reword = ScoreConfig.getViewerMaxReward(); double score_threshold = ScoreConfig.getViewerScoreThreshold(); if(diff > score_threshold) { return 0.0; } else if(score_threshold <= 0.0) { return diff == 0.0 ? max_reword : 0.0; } else { return max_reword * (score_threshold - diff) / score_threshold; } } protected String signHeader; protected static ScoreSignUtil instance = null; public static ScoreSignUtil GetInstance() { return instance; } public static void Setup(String signHeader) { instance = new ScoreSignUtil(signHeader); } } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/util/CommandOnlyForPlayerException.java package me.hwei.bukkit.scoreplugin.util; public class CommandOnlyForPlayerException extends UsageException { public CommandOnlyForPlayerException(String usage) { super(usage, "This command is only for players."); } private static final long serialVersionUID = 1L; } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/ScorePlugin.java package me.hwei.bukkit.scoreplugin; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.persistence.PersistenceException; import me.hwei.bukkit.scoreplugin.ScoreConfig.IConfigDataSource; import me.hwei.bukkit.scoreplugin.commands.*; import me.hwei.bukkit.scoreplugin.data.Score; import me.hwei.bukkit.scoreplugin.data.ScoreAggregate; import me.hwei.bukkit.scoreplugin.data.Storage; import me.hwei.bukkit.scoreplugin.data.Work; import me.hwei.bukkit.scoreplugin.listeners.ScoreBlockListener; import me.hwei.bukkit.scoreplugin.listeners.ScoreEntityListener; import me.hwei.bukkit.scoreplugin.listeners.ScorePlayerListener; import me.hwei.bukkit.scoreplugin.util.AbstractCommand; import me.hwei.bukkit.scoreplugin.util.IOutput; import me.hwei.bukkit.scoreplugin.util.LanguageManager; import me.hwei.bukkit.scoreplugin.util.MoneyManager; import me.hwei.bukkit.scoreplugin.util.OutputManager; import me.hwei.bukkit.scoreplugin.util.PermissionManager; import me.hwei.bukkit.scoreplugin.util.PermissionsException; import me.hwei.bukkit.scoreplugin.util.UsageException; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.Configuration; import org.bukkit.entity.Player; public class ScorePlugin extends JavaPlugin { protected IOutput toConsole = null; protected boolean enable = false; protected Map<String, AbstractCommand> topCommands = null; @Override public void onDisable() { if(this.enable) { this.enable = false; this.toConsole.output("Disabled."); } this.toConsole = null; this.topCommands = null; } @Override public void onEnable() { IOutput toConsole = new IOutput() { @Override public void output(String message) { getServer().getConsoleSender().sendMessage(message); } }; IOutput toAll = new IOutput() { @Override public void output(String message) { getServer().broadcastMessage(message); } }; OutputManager.IPlayerGetter playerGetter = new OutputManager.IPlayerGetter() { @Override public Player get(String name) { return getServer().getPlayer(name); } }; OutputManager.Setup( "[" + ChatColor.YELLOW + this.getDescription().getName() + ChatColor.WHITE + "] ", toConsole, toAll, playerGetter); this.toConsole = OutputManager.GetInstance().prefix(toConsole); LanguageManager.Setup(new File( this.getDataFolder(), "language" + this.getDescription().getVersion() + ".yml")); ScoreSignUtil.Setup("[" + this.getDescription().getName() + "]"); ScoreConfig.Setup(new IConfigDataSource(){ @Override public Configuration getConfig() { Configuration config = ScorePlugin.this.getConfig(); config.options().copyDefaults(true); return config; } @Override public void saveConfig() { ScorePlugin.this.saveConfig(); } }); ScoreConfig.Reload(); this.saveConfig(); this.setupDatabase(); Storage.SetUp(this.getDatabase()); if(!this.setupCommands()) { this.toConsole.output(this.getDescription().getVersion() + ChatColor.RED + " is just broken. :'("); return; } PluginManager pluginManager = this.getServer().getPluginManager(); pluginManager.registerEvents(new ScorePlayerListener(), this); pluginManager.registerEvents(new ScoreBlockListener(), this); pluginManager.registerEvents(new ScoreEntityListener(), this); MoneyManager.Setup(getServer().getServicesManager()); PermissionManager.Setup(getServer().getServicesManager()); Plugin dynmap = pluginManager.getPlugin("dynmap"); if(dynmap != null && dynmap.isEnabled()) { ScoreDynmap.Setup(dynmap); } else { pluginManager.registerEvents(ScoreDynmap.getSetupListerner(), this); } this.enable = true; this.toConsole.output(this.getDescription().getVersion() + " Enabled. Developed by " + this.getDescription().getAuthors().get(0) + "."); } protected void setupDatabase() { try { this.getDatabase().find(Work.class).findRowCount(); this.getDatabase().find(Score.class).findRowCount(); } catch (PersistenceException ex) { this.toConsole.output("Installing database for " + this.getDescription().getName() + " due to first time usage"); this.installDDL(); } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { AbstractCommand topCommand = this.topCommands.get(command.getName()); if(topCommand == null) { return false; } try { if(!topCommand.execute(sender, args)) { topCommand.showUsage(sender, command.getName()); } } catch (PermissionsException e) { sender.sendMessage(String.format(ChatColor.RED.toString() + "You do not have permission of %s", e.getPerms())); } catch (UsageException e) { sender.sendMessage("Usage: " + ChatColor.YELLOW + command.getName() + " " + e.getUsage()); sender.sendMessage(String.format(ChatColor.RED.toString() + e.getMessage())); } catch (Exception e) { e.printStackTrace(); } return true; } @Override public List<Class<?>> getDatabaseClasses() { List<Class<?>> list = new ArrayList<Class<?>>(); list.add(Work.class); list.add(Score.class); list.add(ScoreAggregate.class); return list; } protected boolean setupCommands() { try { AbstractCommand[] childCommands = new AbstractCommand[] { new OpenCommand( "open Open a score sign.", "score.open", null), new ScoreCommand( "<score> Give a score. (Range: 0.0~10.0)", "score.score", null), new ForcedScoreCommand( "set <score> Set a forced score. (Range: 0.0~10.0)", "score.forcedscore", null), new UnsetForcedScoreCommand( "unset Unset a forced score.", "score.forcedscore", null), new ClearCommand( "clear Clear all scores given by viewers.", "score.clear", null), new CloseCommand( "close Close a score sign and distrubute rewards", "score.close", null), new MaxRewardCommand( "maxreward <reward> Set max reward of a score sign.", "score.maxreward", null), new ListCommand( "list [pagesize] List recent open score signs.", "score.list", null), new TeleportCommand( "tp <num> Teleport to a score sign in list.", "score.tp", null, new TeleportCommand.IWorldGetter() { @Override public World get(String name) { return getServer().getWorld(name); } }), new ReloadCommand( "reload Reload configuration.", "score.reload", null) }; String pluginInfo = String.format( ChatColor.YELLOW.toString() + "%s " + ChatColor.GOLD + "%s" + ChatColor.WHITE + ". Type /scr ? to get help.", this.getDescription().getName(), this.getDescription().getVersion()); MessageCommand scoreCommand = new MessageCommand( " Get plugin info.", "score", childCommands, pluginInfo); this.topCommands = new TreeMap<String, AbstractCommand>(); this.topCommands.put("score", scoreCommand); } catch (Exception e) { this.toConsole.output("Can not setup commands!"); e.printStackTrace(); return false; } return true; } } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/ScoreSignHandle.java package me.hwei.bukkit.scoreplugin; import java.util.List; import me.hwei.bukkit.scoreplugin.data.Score; import me.hwei.bukkit.scoreplugin.data.ScoreAggregate; import me.hwei.bukkit.scoreplugin.data.Storage; import me.hwei.bukkit.scoreplugin.data.Work; import me.hwei.bukkit.scoreplugin.util.IOutput; import me.hwei.bukkit.scoreplugin.util.LanguageManager; import me.hwei.bukkit.scoreplugin.util.MoneyManager; import me.hwei.bukkit.scoreplugin.util.OutputManager; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerInteractEvent; public class ScoreSignHandle { public static ScoreSignHandle GetFromSight(Player player) { Block block = player.getTargetBlock(null, 3); IOutput toPlayer = OutputManager.GetInstance().toSender(player); String s_no_sign = LanguageManager.GetInstance().getPhrase("no_sign"); if(block == null || (block.getType() != Material.SIGN_POST && block.getType() != Material.WALL_SIGN)) { toPlayer.output(s_no_sign); return null; } Sign sign = (Sign)block.getState(); Work infoFromSign = ScoreSignUtil.GetInstance().read(sign); if(infoFromSign == null) { toPlayer.output(s_no_sign); return null; } Work work = Storage.GetInstance().load(infoFromSign); return new ScoreSignHandle(player, sign, work == null ? infoFromSign : work); } public static ScoreSignHandle GetFromInteract(PlayerInteractEvent event) { if (event.isCancelled()) return null; Block block = event.getClickedBlock(); if (block == null) return null; Sign sign = null; if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) { sign = (Sign)block.getState(); } else { return null; } ScoreSignUtil signUtil = ScoreSignUtil.GetInstance(); Work infoFromSign = signUtil.read(sign); if(infoFromSign == null) { return null; } Work work = Storage.GetInstance().load(infoFromSign); return new ScoreSignHandle(event.getPlayer(), sign, work == null ? infoFromSign : work); } public static boolean IsProtected(Sign sign) { Work infoFromSign = ScoreSignUtil.GetInstance().read(sign); if(infoFromSign == null) { return false; } Work work = Storage.GetInstance().load(infoFromSign); if(work == null) { return false; } return true; } public static boolean Remove(IOutput toSender, Sign sign, boolean admin) { Work infoFromSign = ScoreSignUtil.GetInstance().read(sign); if(infoFromSign == null) { return true; } Work work = Storage.GetInstance().load(infoFromSign); if(work == null) { return true; } if(!admin) { return false; } Storage.GetInstance().delete(work); toSender.output(LanguageManager.GetInstance().getPhrase("removed")); ScoreDynmap.Update(); return true; } protected Player player; protected Sign sign; protected Work work; protected ScoreSignHandle(Player player, Sign sign, Work work) { this.player = player; this.sign = sign; this.work = work; } public void showInfo(boolean advanced) { IOutput toPlayer = OutputManager.GetInstance().toSender(player); LanguageManager lm = LanguageManager.GetInstance(); if(this.work.getWork_id() == null) { toPlayer.output(lm.getPhrase("not_open")); return; } ScoreSignUtil signUtil = ScoreSignUtil.GetInstance(); signUtil.write(sign, work); Storage storage = Storage.GetInstance(); Score score = storage.load(work.getWork_id(), player.getName()); if(this.work.getReward() == null) { int viewerNumber = storage.scoreCount(work.getWork_id()); toPlayer.output(String.format(lm.getPhrase("is_open"), viewerNumber)); if(advanced) { ScoreAggregate scoreAgg = storage.scoreAggregate(this.work.getWork_id()); if(scoreAgg != null) { double authorWillWin = this.work.getScore() == null ? signUtil.calcAuthorReward(scoreAgg.getAverage(), this.work.getMax_reward()) : signUtil.calcAuthorReward(this.work.getScore(), this.work.getMax_reward()); toPlayer.output( String.format(lm.getPhrase("advanced_info"), scoreAgg.getAverage(), scoreAgg.getMin(), scoreAgg.getMax(), scoreAgg.getSum(), this.work.getScore() == null ? "none" : String.format("%.2f", this.work.getScore()), this.work.getMax_reward(), authorWillWin)); } else if(this.work.getScore() != null) { double authorWillWin = signUtil.calcAuthorReward(this.work.getScore(), this.work.getMax_reward()); toPlayer.output( String.format(lm.getPhrase("advanced_info2"), this.work.getScore(), this.work.getMax_reward(), authorWillWin)); } } if(score == null) { toPlayer.output(lm.getPhrase("how_to_score")); return; } else { toPlayer.output(String.format(lm.getPhrase("give_score"), score.getScore())); return; } } else { MoneyManager moneyManager = MoneyManager.GetInstance(); toPlayer.output(String.format(lm.getPhrase("already_close"), moneyManager.format(work.getReward()))); if(score != null) { toPlayer.output(String.format(lm.getPhrase("already_close_and_score"), score.getScore(), moneyManager.format(score.getReward()))); return; } return; } } public void open() { IOutput toPlayer = OutputManager.GetInstance().toSender(player); LanguageManager lm = LanguageManager.GetInstance(); if(this.work.getWork_id() != null) { toPlayer.output(lm.getPhrase("already_open")); return; } this.work.setMax_reward(ScoreConfig.getAutherMaxReward()); Storage.GetInstance().save(this.work); ScoreSignUtil.GetInstance().write(this.sign, this.work); IOutput toAll = OutputManager.GetInstance().prefix(OutputManager.GetInstance().toAll()); toAll.output(String.format(lm.getPhrase("new_open"), work.getName(), work.getAuthor())); ScoreDynmap.Update(); } public void giveScore(double score) { IOutput toPlayer = OutputManager.GetInstance().toSender(player); LanguageManager lm = LanguageManager.GetInstance(); if(!this.requireOpenScore(toPlayer)) { return; } if(this.work.getAuthor() == player.getName()) { toPlayer.output(lm.getPhrase("dont_score_self")); return; } Storage storage = Storage.GetInstance(); Score scoreItem = storage.load(this.work.getWork_id(), this.player.getName()); if(scoreItem == null) { double price = ScoreConfig.getPrice(); MoneyManager moneyManager = MoneyManager.GetInstance(); if(moneyManager.takeMoney(player.getName(), price)) { scoreItem = new Score(); scoreItem.setScore(score); scoreItem.setWork_id(this.work.getWork_id()); scoreItem.setViewer(this.player.getName()); storage.save(scoreItem); toPlayer.output(String.format(lm.getPhrase("you_give_score"), score, moneyManager.format(price) )); IOutput toAll = OutputManager.GetInstance().prefix(OutputManager.GetInstance().toAll()); toAll.output(String.format(lm.getPhrase("someone_give_score"), this.player.getName(), work.getName(), work.getAuthor() )); } else { toPlayer.output(lm.getPhrase("no_money")); } return; } else { double oldScoreNumber = scoreItem.getScore(); scoreItem.setScore(score); storage.save(scoreItem); toPlayer.output(String.format(lm.getPhrase("change_score"), oldScoreNumber, score)); return; } } public void setForcedScore(Double forcedScore) { IOutput toPlayer = OutputManager.GetInstance().toSender(player); LanguageManager lm = LanguageManager.GetInstance(); if(!this.requireOpenScore(toPlayer)) { return; } Double oldForcedScore = work.getScore(); work.setScore(forcedScore); Storage storage = Storage.GetInstance(); storage.save(work); toPlayer.output(String.format(lm.getPhrase("change_force_score"), oldForcedScore == null ? "null" : String.format("%.2f", oldForcedScore), forcedScore == null ? "null" : String.format("%.2f", forcedScore) )); } public void clearScore() { IOutput toPlayer = OutputManager.GetInstance().toSender(player); LanguageManager lm = LanguageManager.GetInstance(); if(!this.requireOpenScore(toPlayer)) { return; } Storage storage = Storage.GetInstance(); storage.clearScore(this.work.getWork_id()); toPlayer.output(lm.getPhrase("clear_score")); } public void close() { IOutput toPlayer = OutputManager.GetInstance().toSender(player); LanguageManager lm = LanguageManager.GetInstance(); if(!this.requireOpenScore(toPlayer)) { return; } Storage storage = Storage.GetInstance(); Double score = this.work.getScore(); if(score == null) { ScoreAggregate scoreAgg = storage.scoreAggregate(this.work.getWork_id()); if(scoreAgg == null) { toPlayer.output(lm.getPhrase("no_score_close")); return; } score = scoreAgg.getAverage(); } ScoreSignUtil signutil = ScoreSignUtil.GetInstance(); double autherReward = signutil.calcAuthorReward(score, this.work.getMax_reward()); MoneyManager moneyManager = MoneyManager.GetInstance(); this.work.setScore(score); this.work.setReward(autherReward); storage.save(this.work); signutil.write(this.sign, this.work); IOutput toAll = OutputManager.GetInstance().prefix(OutputManager.GetInstance().toAll()); if(moneyManager.giveMoney(this.work.getAuthor(), autherReward)) { toAll.output(String.format(lm.getPhrase("announce_close"), this.work.getName(), score, this.work.getAuthor(), moneyManager.format(autherReward) )); } List<Score> scoreList = storage.loadScoreList(this.work.getWork_id()); Score bestViewerScore = null; for(Score viewerScore : scoreList) { double viewerReward = signutil.calcViewerReward(score, viewerScore.getScore()); viewerScore.setReward(viewerReward); if(moneyManager.giveMoney(viewerScore.getViewer(), viewerReward)) { IOutput toThePlayer = OutputManager.GetInstance().prefix(OutputManager.GetInstance().toSender((viewerScore.getViewer()))); toThePlayer.output(String.format(lm.getPhrase("reward_viewer"), work.getName(), score, viewerScore.getScore(), moneyManager.format(viewerReward) )); if(bestViewerScore == null || viewerScore.getReward() > bestViewerScore.getReward()) { bestViewerScore = viewerScore; } } } if(bestViewerScore != null) { toAll.output(String.format(lm.getPhrase("best_viewer"), bestViewerScore.getViewer(), bestViewerScore.getScore(), moneyManager.format(bestViewerScore.getReward()) )); } storage.saveScoreList(scoreList); ScoreDynmap.Update(); } public void setMaxReward(double maxReward) { IOutput toPlayer = OutputManager.GetInstance().toSender(player); LanguageManager lm = LanguageManager.GetInstance(); if(!this.requireOpenScore(toPlayer)) { return; } Storage storage = Storage.GetInstance(); double oldMaxReward = this.work.getMax_reward(); this.work.setMax_reward(maxReward); storage.save(work); MoneyManager moneyManager = MoneyManager.GetInstance(); toPlayer.output(String.format(lm.getPhrase("set_max_reward"), moneyManager.format(oldMaxReward), moneyManager.format(maxReward) )); } protected boolean requireOpenScore(IOutput toPlayer) { LanguageManager lm = LanguageManager.GetInstance(); if(this.work.getWork_id() == null) { toPlayer.output(lm.getPhrase("not_open")); return false; } if(this.work.getReward() != null) { toPlayer.output(String.format(lm.getPhrase("already_close"), MoneyManager.GetInstance().format(this.work.getReward()))); return false; } return true; } } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/listeners/ScoreEntityListener.java package me.hwei.bukkit.scoreplugin.listeners; import me.hwei.bukkit.scoreplugin.ScoreSignHandle; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityExplodeEvent; public class ScoreEntityListener implements Listener { @EventHandler public void onEntityExplode(EntityExplodeEvent event) { if (event.isCancelled()) return; for (Block block : event.blockList()) { if (block.getType() != Material.WALL_SIGN && block.getType() != Material.SIGN_POST) continue; Sign sign = (Sign)block.getState(); if(ScoreSignHandle.IsProtected(sign)) { event.setCancelled(true); break; } } } } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/ScoreConfig.java package me.hwei.bukkit.scoreplugin; import org.bukkit.configuration.Configuration; public class ScoreConfig { public static void Setup(IConfigDataSource configDataSource) { ScoreConfig.configDataSource = configDataSource; } public interface IConfigDataSource { public Configuration getConfig(); public void saveConfig(); } public static void Reload() { Configuration config = configDataSource.getConfig(); price = config.getDouble("price"); tpPrice = config.getDouble("tp_price"); viewerMaxReward = config.getDouble("viewer_max_reward"); autherMaxReward = config.getDouble("auther_max_reward"); viewerScoreThreshold = config.getDouble("viewer_score_threshold"); autherScoreThreshold = config.getDouble("auther_score_threshold"); dynmapDisplayOpen = config.getBoolean("dynmap_display_open"); dynmapDisplayClosed = config.getBoolean("dynmap_display_close"); configDataSource.saveConfig(); } private static IConfigDataSource configDataSource = null; private static double price = 0.0; private static double viewerMaxReward = 0.0; private static double autherMaxReward = 0.0; private static double viewerScoreThreshold = 0.0; private static double autherScoreThreshold = 0.0; private static boolean dynmapDisplayOpen = true; private static boolean dynmapDisplayClosed = true; private static double tpPrice = 0.0; public static double getPrice() { return price; } public static double getViewerMaxReward() { return viewerMaxReward; } public static double getAutherMaxReward() { return autherMaxReward; } public static double getViewerScoreThreshold() { return viewerScoreThreshold; } public static double getAutherScoreThreshold() { return autherScoreThreshold; } public static double getTpPrice() { return tpPrice; } public static boolean getDynmapDisplayOpen() { return dynmapDisplayOpen; } public static boolean getDynmapDisplayClosed() { return dynmapDisplayClosed; } } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/commands/MessageCommand.java package me.hwei.bukkit.scoreplugin.commands; import org.bukkit.command.CommandSender; import me.hwei.bukkit.scoreplugin.util.AbstractCommand; import me.hwei.bukkit.scoreplugin.util.OutputManager; import me.hwei.bukkit.scoreplugin.util.UsageException; public class MessageCommand extends AbstractCommand { public MessageCommand(String usage, String perm, AbstractCommand[] children, String message) throws Exception { super(usage, perm, children); this.message = message; } @Override protected boolean execute(CommandSender sender, MatchResult[] data) throws UsageException { OutputManager.GetInstance().toSender(sender).output(this.message); return true; } protected String message; } <file_sep>/src/main/java/me/hwei/bukkit/scoreplugin/util/PermissionManager.java package me.hwei.bukkit.scoreplugin.util; import net.milkbowl.vault.permission.Permission; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.ServicesManager; public class PermissionManager { protected static PermissionManager instance = null; public static PermissionManager GetInstance() { return instance; } public static void Setup(ServicesManager servicesManager) { RegisteredServiceProvider<Permission> permissionProvider = servicesManager.getRegistration(Permission.class); Permission permission = null; if(permissionProvider != null) { permission = permissionProvider.getProvider(); } instance = new PermissionManager(permission); } protected Permission permission; protected PermissionManager(Permission permission) { this.permission = permission; } public boolean hasPermission(CommandSender sender, String permission) { if(this.permission == null || !(sender instanceof Player)) { return sender.hasPermission(permission); } else { return this.permission.has((Player)sender, permission); } } } <file_sep>/README.md ScorePlugin =========== Score plugin for bukkit. Features -------- * Viewers can give a score to a work. The range of score is 0.0 - 10.0. * Author will receive reward according to the final score. * Give score will cost viewer money but he will win reward if the score is near to the final score. * Final score is average score of viewers generally. But admin can also set it to a forced score. * Display score sign position on dynmap. Requirements ------------ Required: * Minecraft server that runs CraftBukkit * Any economy plugin supported by Vault, for example iConomy Optional: * Any permissions plugin supporting Vault, for example PermissionBukkit or PermissionEx Usage ----- 1. Create a sign near your work: 1st line is `[Score]`, 2ed line is the name of your work. 2. Punch this sign, your name will display in 4th line. 3. Ask admin to use `\scr open` to open this score sign for you. 4. Inform other players of your work, and let them to give it a score. 5. Ask admin to use `\scr close` to close this score sign to get a final score and distribute rewards. Commands -------- ### For users /scr info View score info. /scr <score> Give a score. /scr list List recent open score signs. /scr tp <num> Teleport to a score sign in list. ### For Admins /scr open Open a score sign. /scr admin View info for admins. /scr set <score> Set a forced score. /scr unset Unset forced score. /scr clear Clear all scores from viewers. /scr maxreward <amount> Set max reward for author. /scr close Close a score sign and distribute rewards. /scr reload Reload config.yml. Permissions ----------- permissions: score.*: description: Gives access to all Score commands children: score.admin: true score.admin: description: Allows you to manage Score. default: op children: score.use: true score.use: description: Allows you to view info and give score. default: true Configuation ----------- config.yml example # How much money to take from viewer when give a score. price: 25.0 # How much money the viewer will win if he has given the exact score to the final score. viewer_max_reward: 500.0 # How much money the author will win if he has got score of 10.0. auther_max_reward: 5000.0 # If the difference form viewer's score to final score is greater than this, he will win no money. viewer_score_threshold: 1.0 # If the score of auther is less than this, he will win no money. auther_score_threshold: 6.0 # The price of teleporting to score sign. tp_price: 100.0 # Whether display open score signs on dynmap dynmap_display_open: true # Whether display closed score sings on dynmap dynmap_display_close: true
f365230b49f88c257b5a3770cf3409811e601920
[ "Markdown", "Java" ]
12
Java
hwei/ScorePlugin
8c41e78aea56542637b9b6eb8af01a17bfe98be9
c0cad259309c93c11cf076a63f37a97f81857b66
refs/heads/master
<repo_name>StarsiegePlayers/memstar<file_sep>/zlib/ioapi.c /* ioapi.c -- IO base function header for compress/uncompress .zip files using zlib + zip or unzip API Version 1.01e, February 12th, 2005 Copyright (C) 1998-2005 <NAME> */ #include "zlib.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "ioapi.h" /* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */ #ifndef SEEK_CUR #define SEEK_CUR 1 #endif #ifndef SEEK_END #define SEEK_END 2 #endif #ifndef SEEK_SET #define SEEK_SET 0 #endif void fill_fopen_filefunc (pzlib_filefunc_def) zlib_filefunc_def* pzlib_filefunc_def; { } <file_sep>/PlayGui.cpp #include "Callback.h" #include "Patch.h" #include "Fear.h" #include "OpenGL.h" #include "Console.h" namespace VersionSnoop { extern DWORD* versionPtr; }; namespace GUI { MultiPointer(ptr_SIMCANVASSET_ONRENDER_VFT, 0, 0, 0x00704670, 0x00714AE0); MultiPointer(ptr_SIMCANVAS_RENDER, 0, 0, 0x005c9a50, 0x005CD2F4); MultiPointer(ptr_SIMCANVAS_RENDERGUI_CALL, 0, 0, 0x005d5db4, 0x005D9658); CodePatch cpDrawGUI = { ptr_SIMCANVAS_RENDERGUI_CALL, "\xe8\x97\x3c\xff\xff", "\xe8rgui", 5, false }; u32 fnOnRender, fnRenderGui = ptr_SIMCANVAS_RENDER; Fear::GraphicsAdapter* gfxAdapter; void GatherInformation() { } void OnPlayGUIPreDraw(Fear::GraphicsAdapter* gfx) { if (OpenGL::IsActive()) { OpenGL::ShutdownTex1ARB(); glDisable(GL_CULL_FACE); Callback::trigger(Callback::OnGuiDraw, true); } } void OnPlayGUIPostDraw(Fear::GraphicsAdapter* gfx) { if (OpenGL::IsActive()) Callback::trigger(Callback::OnGuiDraw, false); } NAKED void OnRender() { __asm { pushad call GatherInformation popad jmp[fnOnRender] } } NAKED void OnPlayGUI() { __asm { mov[gfxAdapter], edx pushad push[gfxAdapter] call OnPlayGUIPreDraw pop[gfxAdapter] popad push[esp + 8] push[esp + 8] call[fnRenderGui] pushad push[gfxAdapter] call OnPlayGUIPostDraw pop[gfxAdapter] popad retn 8 } } struct Init { Init() { if (VersionSnoop::GetVersion() == VERSION::vNotGame) { return; } if (VersionSnoop::GetVersion() != VERSION::v001004) { return; } cpDrawGUI.DoctorRelative((u32)OnPlayGUI, 1).Apply(true); fnOnRender = Patch::ReplaceHook((void*)ptr_SIMCANVASSET_ONRENDER_VFT, OnRender); } } Init; }; // namespace GUI<file_sep>/Originals.h #ifndef __ORIGINALS_H__ #define __ORIGINALS_H__ Original mOriginalsTable[] = { { 0x00142d13, "MOON.RD_P_TEE.TGA" }, { 0x0059a77f, "CYENGINEM1_SD.TGA" }, { 0x005eab1e, "FX_SHK06.TGA" }, { 0x00663cae, "TEMPERATE.RD_D_TEE.TGA" }, { 0x006893fb, "EUROPA.N.PANEL0.TGA" }, { 0x006ab596, "PLUTO.PAVED_PPPP.TGA" }, { 0x0087f0e7, "VENUS.SSSS.TGA" }, { 0x009fa7f9, "ICE.DDDD.TGA" }, { 0x00a1cc14, "@FX_BSMK07.TGA" }, { 0x00f654ba, "EUROPA.DDDD.TGA" }, { 0x01127d78, "@FX_SMK12.TGA" }, { 0x0116bc8e, "HSLAT3L.TGA" }, { 0x012b01eb, "HWINDOW.TGA" }, { 0x0150f002, "CY_COMPUTERM_S.TGA" }, { 0x01597609, "FX_DUSTWH05.TGA" }, { 0x017823f7, "TEMPERATE.T.PANEL4.TGA" }, { 0x0181fe80, "HMAR02.TGA" }, { 0x01ab356a, "XENGINE.TGA" }, { 0x01f7db1d, "FX_DIS06.TGA" }, { 0x02038fb2, "CIN_CRYO2.TGA" }, { 0x0204542c, "@FX_CLAS.TGA" }, { 0x02051abe, "FX_BSMK16.TGA" }, { 0x0225ed96, "XWINDOW3.TGA" }, { 0x02358215, "MARS.PAVED1.TGA" }, { 0x0271a904, "@FX_FL102.TGA" }, { 0x02940212, "PLUTO.GRRG.TGA" }, { 0x02979fd4, "HMAR05.TGA" }, { 0x029da4c5, "ICE.FFFF3.TGA" }, { 0x02b9960e, "@FX_FL14.TGA" }, { 0x02ccd55f, "GUI.TGA" }, { 0x0309b903, "MERCURY.SSSS.TGA" }, { 0x030a1a03, "@FX_ESP00.TGA" }, { 0x031fd7ef, "MARS.LGGG3.TGA" }, { 0x03218511, "CSLAT3.TGA" }, { 0x034ca0b0, "@FX_G_GLOW.TGA" }, { 0x035ea3c4, "HUSENSORM1_SD.TGA" }, { 0x03884141, "DESERT.DSDD.TGA" }, { 0x0391fe9a, "FX_LXP11.TGA" }, { 0x03b63878, "MERCURY.SSSS2.TGA" }, { 0x03b6791e, "CY_COMPUTERS_SD.TGA" }, { 0x03bc5cd4, "TEAM_4.TGA" }, { 0x03cd69c7, "EUROPA.DDDD.TGA" }, { 0x03cdff61, "ICE.RD_BEGIN.TGA" }, { 0x03d5c195, "@FX_EXS07.TGA" }, { 0x03e0cc91, "ROCKETBOOST_S.TGA" }, { 0x03f54d9a, "EUROPA.DGGG2.TGA" }, { 0x03f5c527, "DESERT.PAVED1.TGA" }, { 0x042e521a, "ARMOR2_SD.TGA" }, { 0x0434360d, "HBRICKD.TGA" }, { 0x0471b1f6, "TITAN.HHHH4.TGA" }, { 0x048e2147, "EUROPA.RD_D_CROS.TGA" }, { 0x0491e4dc, "VENUS.GDSS2.TGA" }, { 0x04aa7981, "EUROPA.FGRR.TGA" }, { 0x04c0aa02, "FX_DUSTBL05.TGA" }, { 0x04c57be2, "HUSHIELDGENM2_S.TGA" }, { 0x04cc5dcc, "@FX_BLAST1.TGA" }, { 0x04dcf32d, "MOON.T.MOON.TGA" }, { 0x052e67e2, "FX_NCAN.TGA" }, { 0x053b98dc, "DESERT.SDDS.TGA" }, { 0x05523abb, "PLUTO.GGGG3.TGA" }, { 0x055b60d3, "DESERT.NB_PANEL0.TGA" }, { 0x055d5c90, "FX_DUSTDO05.TGA" }, { 0x056da398, "PRX_S.TGA" }, { 0x057853ea, "HMAR01.TGA" }, { 0x05888816, "MERCURY.SDDD2.TGA" }, { 0x05bec325, "FX_BSMK04.TGA" }, { 0x05bf918a, "ARMOR4_SD.TGA" }, { 0x05d423bc, "VIP_SD.TGA" }, { 0x061566f6, "HTROOPDOORS.TGA" }, { 0x0643a727, "PLUTO.GSSS.TGA" }, { 0x064cf236, "ICE.DB_MOON0.TGA" }, { 0x06891c8e, "SORT_ARROW.TGA" }, { 0x0697876b, "FX_FOG.TGA" }, { 0x06acbd71, "EUROPA.CFFC2.TGA" }, { 0x06b0090e, "MOON.DSSS2.TGA" }, { 0x06cce8e2, "FX_FLA14.TGA" }, { 0x06f1c345, "FX_DUSTDB10.TGA" }, { 0x070210eb, "FX_PR101.TGA" }, { 0x07131d71, "MARS.RD_BEGIN.TGA" }, { 0x07184314, "TEMPERATE.T.PANEL0.TGA" }, { 0x0726b882, "DESERT.PAVED_LANDG.TGA" }, { 0x0732374f, "ICE.DFFF.TGA" }, { 0x07475690, "MIN_SD.TGA" }, { 0x074ca948, "FX_DUSTWH10.TGA" }, { 0x07521748, "PLUTO.MMMM4.TGA" }, { 0x075d0d38, "XBROWNSTRP.TGA" }, { 0x079ef26c, "HU_COMPUTERM_S.TGA" }, { 0x07c0f8dc, "PLUTO.N.MOON.TGA" }, { 0x082459d2, "FX_ELE01.TGA" }, { 0x08248c22, "DESERT.PAVEDSCORCH.TGA" }, { 0x0857a5e0, "CY_ENGINE1_S.TGA" }, { 0x088f2f22, "MARS.LLGG3.TGA" }, { 0x08c7323f, "MOON.N.MOON.TGA" }, { 0x08ecb114, "@FX_FL105.TGA" }, { 0x08f4d481, "HA_CPIT.TGA" }, { 0x0918cfb8, "FX_SPK11.TGA" }, { 0x0920d4b9, "MTECH1.TGA" }, { 0x0947be9f, "TITAN.T_PANEL1.TGA" }, { 0x094b2232, "EUROPA.GGGG6.TGA" }, { 0x095f10ec, "TEMPERATE.RD_P_CROS.TGA" }, { 0x097aee4c, "FX_DUSTWH13.TGA" }, { 0x09ade129, "XHEADLAMP2.TGA" }, { 0x09ba247e, "FX_FLA07.TGA" }, { 0x09ba5fa5, "@FX_SMK14.TGA" }, { 0x09df4306, "MERCURY.SDDD.TGA" }, { 0x09dfcddb, "TITAN.GGGG4.TGA" }, { 0x09ebb24a, "PLUTO.RRRR.TGA" }, { 0x09f217ea, "FX_SPK15.TGA" }, { 0x0a1a6eb6, "RESET.TGA" }, { 0x0a1bad07, "VENUS.RD_P_TEE.TGA" }, { 0x0a25e7d9, "VENUS.GGGG.TGA" }, { 0x0a66b8bf, "SETCLOSED.TGA" }, { 0x0ac81d3f, "FX_DUSTDO14.TGA" }, { 0x0b66a9b6, "OPEN_HAND.TGA" }, { 0x0b720a9b, "MERCURY.TRANS_PDDD.TGA" }, { 0x0b95f8bb, "MOON.RD_D_TEE.TGA" }, { 0x0b9c5a25, "SPR_S.TGA" }, { 0x0be04d54, "DESERT.DB_PANEL1.TGA" }, { 0x0be1ac85, "TEMPERATE.NB_PANEL2.TGA" }, { 0x0c3393d6, "FX_GAS13.TGA" }, { 0x0c4e3b8e, "AMMO2.TGA" }, { 0x0c55d623, "FX_PBW.TGA" }, { 0x0c58660e, "TEMPERATE.GGRR.TGA" }, { 0x0ca65ed6, "XMISSLE.TGA" }, { 0x0caa595f, "PSTHEIGT.TGA" }, { 0x0cb32200, "CYSHIELDGENM1_S.TGA" }, { 0x0cde5e91, "TEMPERATE.DB_PANEL2.TGA" }, { 0x0ce9d695, "TITAN.GGGG3.TGA" }, { 0x0cee33eb, "MOON.GDDD2.TGA" }, { 0x0d135741, "FLIPVERT.TGA" }, { 0x0d177e20, "CTECH6.TGA" }, { 0x0d234ac3, "HMARMS.TGA" }, { 0x0d382a2c, "DESERT.RD_PAVE_TEE.TGA" }, { 0x0d7614b6, "EUROPA.GDDD.TGA" }, { 0x0d7761ff, "FX_DUST03.TGA" }, { 0x0dbe9174, "TITAN.GHOO.TGA" }, { 0x0dbf5f5f, "EUROPA.GGGG3.TGA" }, { 0x0dce351d, "@FX_PR104.TGA" }, { 0x0df1f7ad, "FX_DUSTBL07.TGA" }, { 0x0e000dc8, "FX_TLAS.TGA" }, { 0x0e02dac2, "FX_SPK06.TGA" }, { 0x0e07bd09, "VENUS.TB_PANEL2.TGA" }, { 0x0e1303ae, "MARS.GSSS.TGA" }, { 0x0e148105, "SCANNEX_CANN_SML.TGA" }, { 0x0e29f6ad, "CIN_HELMET.TGA" }, { 0x0e653d70, "HUSHIELDGENS2_S.TGA" }, { 0x0e7c9471, "MOON.RD_TRANS.TGA" }, { 0x0e8c672f, "CY_PROT1.TGA" }, { 0x0e9cf996, "CYENGINEL2_S.TGA" }, { 0x0ec89966, "SETHEIGT.TGA" }, { 0x0f24127a, "@FX_QGUN.TGA" }, { 0x0f24d4e2, "EUROPA.DDDD5.TGA" }, { 0x0f28118b, "DESERT.RD_PAVE_CRNR.TGA" }, { 0x0f37339c, "TEMPERATE.TRANS_DPPP.TGA" }, { 0x0f54b733, "@FX_EX04.TGA" }, { 0x0f635a6c, "VENUS.DDDD7.TGA" }, { 0x0f781dc5, "MARS.RD_PAVE_CRNR.TGA" }, { 0x0f84e0a6, "VENUS.SGGG2.TGA" }, { 0x0faec53a, "PLUTO.MMMM5.TGA" }, { 0x0fc14845, "TITAN.HGGG2.TGA" }, { 0x0fc96242, "EUROPA.DDDD3.TGA" }, { 0x1000d8f5, "MOON.GGGG3.TGA" }, { 0x10167c67, "TEMPERATE.TRANS_PDDD.TGA" }, { 0x10183ce3, "FX_DUSTGR14.TGA" }, { 0x10297da4, "CY_PROT2.TGA" }, { 0x10421ddb, "ICE.RFFF3.TGA" }, { 0x104b245e, "EHUL_S.TGA" }, { 0x10641a18, "VENUS.DDDD7.TGA" }, { 0x1065c86c, "EUROPA.FRGG.TGA" }, { 0x10ce445a, "DESERT.DDDD4.TGA" }, { 0x10dd1a2b, "HKONGFLOOR.TGA" }, { 0x111a61d7, "FX_DUSTDY02.TGA" }, { 0x113197b0, "XTOWER.TGA" }, { 0x115dc8f9, "LGB_SD.TGA" }, { 0x1169565a, "MOON.DDDD3.TGA" }, { 0x1171efac, "EMAN_PIRATE.TGA" }, { 0x1172fcaf, "FX_DUSTLB09.TGA" }, { 0x117a6a0a, "MOON.GDDD.TGA" }, { 0x118c099d, "LASERMISSILE_SD.TGA" }, { 0x11a13ca8, "PLUTO.MMMM5.TGA" }, { 0x11a69212, "CYSHIELDGEN4_S.TGA" }, { 0x11d2547e, "TITAN.TB_MOON0.TGA" }, { 0x11ecfad0, "TR_GEN1.TGA" }, { 0x120172de, "ICE.D.MOON.TGA" }, { 0x12267d98, "FX_DUSTWH04.TGA" }, { 0x123d7848, "@FX_FL02.TGA" }, { 0x1246a6ae, "HU_ENGINE3_SD.TGA" }, { 0x1247d5ad, "TEMPERATE.T.PANEL3.TGA" }, { 0x1262071b, "TR_OVER2.TGA" }, { 0x1280081d, "@FX_BLK03.TGA" }, { 0x129c371d, "PLUTO.GGGG5.TGA" }, { 0x12b49ad9, "PREV_DM_HEAVENS_PEAK.TGA" }, { 0x12c48bf4, "EUROPA.FRRR.TGA" }, { 0x12cf74c0, "@FX_B_GLOW.TGA" }, { 0x12ef80cd, "ARROW.TGA" }, { 0x12fadf24, "PLUTO.RRRR5.TGA" }, { 0x1314f82c, "SHIELDS_SOLID.TGA" }, { 0x13322afd, "VENUS.D.PANEL3.TGA" }, { 0x13333f78, "VENUS.RD_P_CROS.TGA" }, { 0x1354743b, "XTECH1.TGA" }, { 0x136e02d3, "EUROPA.RRGG2.TGA" }, { 0x137159e6, "VENUS.SGDD2.TGA" }, { 0x139cd0b1, "MERCURY.RD_PP_CRNR.TGA" }, { 0x13a367f6, "@FX_BLUEEXH.TGA" }, { 0x13b3717a, "@FX_EXS04.TGA" }, { 0x13cc3316, "ICE.RD_P_CRNR.TGA" }, { 0x13d39373, "EUROPA.GDDD.TGA" }, { 0x13e7a023, "DESERT.PAVED_LANDG.TGA" }, { 0x141729f7, "EUROPA.FFFF4.TGA" }, { 0x1449e3fd, "MOON.SSSS3.TGA" }, { 0x147511b4, "ICE.DEV_PLAIN1.TGA" }, { 0x148cfbda, "PLUTO.GGGG3.TGA" }, { 0x14adb1f8, "EUROPA.GRFF.TGA" }, { 0x14cccba4, "TITAN.OHHH.TGA" }, { 0x14d4a6a8, "DESERT.PAVED_TRANS_PSSS.TGA" }, { 0x14e411b8, "IRC_ICON_SPKR_L.TGA" }, { 0x14ec7eda, "STATIC.TGA" }, { 0x15180ac7, "CYSENSORM1_SD.TGA" }, { 0x151eec87, "HA_TRAN.TGA" }, { 0x152c33b1, "EUROPA.DDGG.TGA" }, { 0x15321833, "FX_SMK11.TGA" }, { 0x159900ba, "FX_PR102.TGA" }, { 0x159d011e, "MOON.PAVE_PLAIN1.TGA" }, { 0x15a17a20, "EUROPA.T.PANEL3.TGA" }, { 0x15b9d7e5, "FX_PR103.TGA" }, { 0x15e073b9, "@FX_MFAC.TGA" }, { 0x15fcecf1, "HUREACTORM1_S.TGA" }, { 0x160bbf30, "FX_ELE06.TGA" }, { 0x16460dfd, "FX_DUSTLG06.TGA" }, { 0x16594e2a, "PLUTO.RMMM.TGA" }, { 0x167b49df, "NO_COMPONENT_S.TGA" }, { 0x16ab4a96, "PLUTO.T.PANEL3.TGA" }, { 0x16b5976d, "FX_RAL00.TGA" }, { 0x16b7eafa, "XWINDOW6.TGA" }, { 0x16bcedc7, "EUROPA.CFFF3.TGA" }, { 0x16f6820a, "MARS.RD_DIRT_STRT.TGA" }, { 0x172c646f, "DESERT.T.PANEL1.TGA" }, { 0x1771bd9c, "HDESERTTROOPDOORS.TGA" }, { 0x178a72e9, "CYREACTORM2_S.TGA" }, { 0x17b3a85f, "TEMPERATE.GDDD.TGA" }, { 0x17d1d5c1, "FX_FLA11.TGA" }, { 0x17ded396, "TEMPERATE.RD_D_END.TGA" }, { 0x180177b6, "EUROPA.FRRR2.TGA" }, { 0x1802f2a8, "VENUS.DDDD3.TGA" }, { 0x1810c1cc, "HUSENSORL2_S.TGA" }, { 0x182640f1, "EUROPA.RD_D_CRNR.TGA" }, { 0x1850ac33, "@FX_BSMK13.TGA" }, { 0x18a66dab, "ELEVATE.TGA" }, { 0x18c19b69, "DESERT.GGGG6.TGA" }, { 0x18c9ef9c, "XPERSONNEL_ONE.TGA" }, { 0x18cc0bbb, "PREV_DM_TWIN_SIEGE.TGA" }, { 0x190636f1, "EUROPA.CFCF3.TGA" }, { 0x1935b567, "DESERT.DGDD.TGA" }, { 0x19409e2a, "FX_BSMK14.TGA" }, { 0x19644fc7, "FX_BLAST.TGA" }, { 0x19861379, "XHEAL_VENUS.TGA" }, { 0x19950c43, "TITAN.DB_PANEL3.TGA" }, { 0x199a4336, "TEMPERATE.GGGG5.TGA" }, { 0x199b847e, "VENUS.GGGG2.TGA" }, { 0x19c26287, "BURNT_HULK_SML.TGA" }, { 0x19ea96c2, "MERCURY.TRANS_PPDD.TGA" }, { 0x19ed72ef, "XHERCMOVIE17.TGA" }, { 0x19f0b573, "TITAN.ROAD_END.TGA" }, { 0x1a083ed3, "DESERT.DSSD.TGA" }, { 0x1a0ccc5a, "TEMPERATE.ROCK.TGA" }, { 0x1a1307d7, "VENUS.TB_PANEL1.TGA" }, { 0x1a3e6a7e, "TEMPERATE.GGGG4.TGA" }, { 0x1a45b0ec, "TLAS_SD.TGA" }, { 0x1a66c77f, "@FX_SPK07.TGA" }, { 0x1a6a42b8, "PLUTO.RD_D_TEE.TGA" }, { 0x1a7005c2, "@FX_FL12.TGA" }, { 0x1a7587e7, "@FX_BSMK16.TGA" }, { 0x1a7d4f84, "DESERT.SDSS.TGA" }, { 0x1ad6da4a, "FX_RAL09.TGA" }, { 0x1b4798c4, "@FX_LXP07.TGA" }, { 0x1b67bd40, "FX_RAL04.TGA" }, { 0x1b69b720, "CPYHEIGT.TGA" }, { 0x1b854639, "CYENGINEM3_S.TGA" }, { 0x1bba3692, "TEMPERATE.T.MOON1.TGA" }, { 0x1bc5fcf9, "CYSENSOR3_SD.TGA" }, { 0x1be191bb, "@FX_PR105.TGA" }, { 0x1be1d449, "FX_BLAST1.TGA" }, { 0x1c5dd165, "SIZEFILE.TGA" }, { 0x1c8c4aee, "DESERT.RD_DIRT_TEE.TGA" }, { 0x1c8c5fca, "FX_BLUEEXH.TGA" }, { 0x1c912ad6, "VENUS.T.MOON0.TGA" }, { 0x1ce8eccf, "ICE.RRRR3.TGA" }, { 0x1cf45fbd, "FX_BLS01.TGA" }, { 0x1cf4ad26, "ICON_NAV_BLUE.TGA" }, { 0x1d0af3ee, "MERCURY.LDDL.TGA" }, { 0x1d183062, "VENUS.RD_TRANS.TGA" }, { 0x1d1acc5e, "HEAL2.TGA" }, { 0x1d20563d, "DESERT.DGGG.TGA" }, { 0x1d34357a, "MERCURY.SSSS4.TGA" }, { 0x1d4c35fc, "CYECM2_S.TGA" }, { 0x1d54b027, "TITAN.OOOO.TGA" }, { 0x1d6e38f8, "TR_SUPR.TGA" }, { 0x1d88ed68, "FX_DUSTBR07.TGA" }, { 0x1d8b241b, "TEMPERATE.GGGG.TGA" }, { 0x1d8c746a, "MOON.DSSS.TGA" }, { 0x1d9916f9, "ARMOR5_S.TGA" }, { 0x1db0abcf, "MARS.RD_DIRT_TEE.TGA" }, { 0x1db2c2e9, "CLOGO2.TGA" }, { 0x1db37298, "MERCURY.DDDD3.TGA" }, { 0x1db3a8ba, "MARS.SSSS6.TGA" }, { 0x1ded1b4d, "PLUTO.SGGS.TGA" }, { 0x1e16c33f, "MARS.GGGG5.TGA" }, { 0x1e1e53c0, "HBC_S.TGA" }, { 0x1e376c5e, "XMETAL.TGA" }, { 0x1e7fe501, "PLUTO.RD_D_STRT.TGA" }, { 0x1e825934, "TITAN.HHOO.TGA" }, { 0x1e954209, "HTROOPSTRIPE.TGA" }, { 0x1e9c5106, "ICE.FRRR.TGA" }, { 0x1ea77527, "CUR_ARROW.TGA" }, { 0x1ec92c05, "INTERIOROPEN.TGA" }, { 0x1ee23432, "VENUS.GSSS2.TGA" }, { 0x1ee696fd, "@FX_SHK01.TGA" }, { 0x1eecdfb1, "FX_DUSTYL07.TGA" }, { 0x1f378aef, "XAMMO_VENUS.TGA" }, { 0x1f45fd37, "EUROPA.CFFF2.TGA" }, { 0x1f4c3b8e, "WP_MAST.TGA" }, { 0x1f640b1d, "NCAN_SD.TGA" }, { 0x1f7b3b69, "FX_DUSTYL10.TGA" }, { 0x1f863136, "MOON.D.PANEL1.TGA" }, { 0x1f9be153, "NAMSELEC.TGA" }, { 0x1fa274cc, "TITAN.CCGG.TGA" }, { 0x1fc07b1f, "EUROPA.DDGG2.TGA" }, { 0x1fc5a833, "PING_RED.TGA" }, { 0x1ff4bf60, "PALA_TR.TGA" }, { 0x1ff7a09b, "MERCURY.D.PANEL4.TGA" }, { 0x2014f6a9, "TEMPERATE.RD_D_STRT.TGA" }, { 0x2060c150, "XLAND1.TGA" }, { 0x206d9fed, "MERCURY.PAVE_LANDG.TGA" }, { 0x207701a4, "CYTHERMSENSOR_SD.TGA" }, { 0x20dbf43c, "FX_DUSTLG14.TGA" }, { 0x20ec98a7, "FX_DUSTLB11.TGA" }, { 0x2103566d, "THUM_RB.TGA" }, { 0x210a3689, "EUROPA.FFGG.TGA" }, { 0x210ba8fd, "SWARM_SD.TGA" }, { 0x210e5d09, "SCANNEX_MELAN_LG.TGA" }, { 0x21181d63, "FX_DUST12.TGA" }, { 0x211e3c3f, "CYREACTORL1_S.TGA" }, { 0x21336c1a, "DAM_TAR.TGA" }, { 0x216832ca, "TEMPERATE.DB_PANEL0.TGA" }, { 0x21793729, "EUROPA.DDDD6.TGA" }, { 0x2182027d, "HUSHIELDGEN3_SD.TGA" }, { 0x21dd865e, "CYGAP.TGA" }, { 0x21e7a9c9, "XSLATS7.TGA" }, { 0x2221c9ab, "TITAN.GHHH.TGA" }, { 0x224b05cb, "ICON_NAV_YELO.TGA" }, { 0x224d4ff6, "EUROPA.GGGG3.TGA" }, { 0x22614e86, "@FX_EX11.TGA" }, { 0x229770fc, "EUROPA.FFRR2.TGA" }, { 0x22a3c0b7, "TR_SOVE.TGA" }, { 0x22bad60d, "FX_DROP01.TGA" }, { 0x22ce96f7, "PLUTO.TECH_TTTT2.TGA" }, { 0x22e1de0f, "EUROPA.FFFF2.TGA" }, { 0x22fc205f, "CYENGINEL3_S.TGA" }, { 0x2303e93f, "VENUS.RD_P_CRNR.TGA" }, { 0x23053e9e, "MOON.DDDD.TGA" }, { 0x2327c7b1, "TITAN.CCCC4.TGA" }, { 0x23315940, "CIN_SATURNRINGS.TGA" }, { 0x2347ca15, "TEMPERATE.RD_D_END.TGA" }, { 0x234c2555, "HUENGINES3_SD.TGA" }, { 0x2361563f, "TEMPERATE.PAVE_LANDG.TGA" }, { 0x239a3ae4, "HUREACTORM2_SD.TGA" }, { 0x23b0d87f, "SCANNEX_POLICE_LG.TGA" }, { 0x23cdff26, "VENUS.DB_PANEL2.TGA" }, { 0x23d0451d, "EUROPA.FGGG.TGA" }, { 0x23f6396c, "MARS.PAVED_SCORCH.TGA" }, { 0x23f950b0, "@FX_SPK04.TGA" }, { 0x2423f376, "EUROPA.DDDD6.TGA" }, { 0x2423fda2, "EMC_SD.TGA" }, { 0x2425885a, "HGARSONLOGO.TGA" }, { 0x242d61df, "LOADPAL.TGA" }, { 0x243a03a8, "PLUTO.D.MOON.TGA" }, { 0x24427d3e, "VENUS.GDDD.TGA" }, { 0x245a6d0c, "TEAM_3.TGA" }, { 0x24665f48, "FX_LXP09.TGA" }, { 0x249a3df2, "FX_BSMK17.TGA" }, { 0x249e59cb, "XMONUMENT2.TGA" }, { 0x24aaac44, "PLUTO.RD_D_END.TGA" }, { 0x24d0fdc2, "HBLA_S.TGA" }, { 0x24db928d, "MARS.D.MOON.TGA" }, { 0x24e34cc9, "@FX_EX07.TGA" }, { 0x24ecac5f, "DESERT.RD_PAVE_CROS.TGA" }, { 0x24f84020, "VENUS.N.PANEL0.TGA" }, { 0x2538f2f0, "VENUS.GGGG4.TGA" }, { 0x254267e9, "DESERT.RD_DIRT_END.TGA" }, { 0x254fdfec, "TITAN.OHHH.TGA" }, { 0x256e2cbe, "MOON.RRGG.TGA" }, { 0x2570df07, "FX_DUSTLG10.TGA" }, { 0x2576d890, "FX_SHD04.TGA" }, { 0x25aee769, "EUROPA.GDDD2.TGA" }, { 0x25c8b3f0, "HUREACTORM2_S.TGA" }, { 0x25c9f2c5, "XHERCMOVIE6.TGA" }, { 0x25caed06, "TEMPERATE.NB_PANEL0.TGA" }, { 0x25f51d68, "HMOONDOORLOGO.TGA" }, { 0x25f78317, "DESERT.T.MOON.TGA" }, { 0x26125d0d, "AVEN_RB.TGA" }, { 0x262cdb6b, "CSLAT4.TGA" }, { 0x263a2f7c, "DESERT.PAVED2.TGA" }, { 0x2641dce9, "@FX_DIS04.TGA" }, { 0x264c841b, "CIN_EARTH.TGA" }, { 0x264f21dd, "HUSHIELDGENS2_SD.TGA" }, { 0x265b072f, "FX_DUSTWH11.TGA" }, { 0x2673be07, "EMC_S.TGA" }, { 0x267ac81e, "SCANNEX_RBL_LG.TGA" }, { 0x2697dadf, "@FX_ELC03.TGA" }, { 0x26b267c0, "PLUTO.TECH_TSSS.TGA" }, { 0x26bed6a0, "@FX_ESP02.TGA" }, { 0x26cdee07, "@FX_SMK11.TGA" }, { 0x2723406e, "@FX_GAS10.TGA" }, { 0x2725761d, "ARA_SD.TGA" }, { 0x273434e5, "@FX_EB01.TGA" }, { 0x273da947, "FX_DUST05.TGA" }, { 0x2765f15a, "CFLORICON.TGA" }, { 0x276d8989, "@FX_SPK03.TGA" }, { 0x2771f7a5, "SETOPEN.TGA" }, { 0x278b37bf, "CYSHIELDGENS2_S.TGA" }, { 0x27be621d, "EUROPA.CFFC2.TGA" }, { 0x27fd167e, "LASERMISSILE2_S.TGA" }, { 0x28029313, "HROOF.TGA" }, { 0x280d1459, "CHECK_N_OFF.TGA" }, { 0x281b8bec, "FX_DUSTLG05.TGA" }, { 0x28428074, "MARS.SSSS3.TGA" }, { 0x284f4307, "@FX_LXP13.TGA" }, { 0x285b2890, "XWARNING.TGA" }, { 0x2877df72, "VENUS.DB_PANEL0.TGA" }, { 0x288457c8, "TEMPERATE.T.MOON2.TGA" }, { 0x28b2ded7, "HPIPE3L.TGA" }, { 0x28b3d1f9, "HAD_SD.TGA" }, { 0x295afae7, "RB_MISC_LIGHT.TGA" }, { 0x2965d08c, "CUTTLEFISHCLOAK_S.TGA" }, { 0x29897393, "CYSENSOR4_S.TGA" }, { 0x29956c16, "MARS.LLGG.TGA" }, { 0x29a8d23c, "TITAN.OOOO3.TGA" }, { 0x29ad75d1, "EUROPA.D.PANEL2.TGA" }, { 0x29b30fa2, "TEMPERATE.T.PANEL2.TGA" }, { 0x29b5e963, "TITAN.TB_PANEL1.TGA" }, { 0x2a263ac7, "EUROPA.GFFF.TGA" }, { 0x2a5ee8eb, "@FX_DIS01.TGA" }, { 0x2a68d76f, "VENUS.SGGG2.TGA" }, { 0x2a9547bb, "FX_CLAS.TGA" }, { 0x2aa6fe74, "TEMPERATE.RD_P_STRT.TGA" }, { 0x2ab6486c, "ARWLIST.TGA" }, { 0x2add9d60, "AGRAVGEN_SD.TGA" }, { 0x2ae5eea4, "MARS.RD_PAVE_TEE.TGA" }, { 0x2ae6b416, "SCANNEX_MACH_LG.TGA" }, { 0x2aede137, "TITAN.CGGG.TGA" }, { 0x2b1141cd, "@FX_SMK08.TGA" }, { 0x2b209915, "ICE.RD_P_CROS.TGA" }, { 0x2b387953, "MARS.D.PANEL2.TGA" }, { 0x2b66431b, "FX_DUSTDB07.TGA" }, { 0x2b678b82, "@FX_SHK04.TGA" }, { 0x2b8447fe, "FX_LAS.TGA" }, { 0x2bc6fbf1, "HMAR07.TGA" }, { 0x2bcd7af2, "XVENTS.TGA" }, { 0x2bd3b4d1, "FIELDSTABILIZER_SD.TGA" }, { 0x2bd7ef8c, "@FX_GAS06.TGA" }, { 0x2beb8409, "MINO_KN.TGA" }, { 0x2bf2fa87, "EXEC_CY.TGA" }, { 0x2c02e82b, "PLUTO.T.PANEL4.TGA" }, { 0x2c094772, "TITAN.D_PANEL2.TGA" }, { 0x2c167cb1, "ICE.RD_P_END.TGA" }, { 0x2c388a3a, "MERCURY.RD_D_CRNR.TGA" }, { 0x2c4a8649, "MARS.SSSS3.TGA" }, { 0x2c54d171, "HKONGWINDOWS.TGA" }, { 0x2c60ecf2, "EUROPA.RD_D_CROS.TGA" }, { 0x2c69377a, "FX_DROP08.TGA" }, { 0x2c7dcd29, "FX_DUSTLG09.TGA" }, { 0x2c7f9587, "TITAN.GCCC2.TGA" }, { 0x2c821834, "TITAN.D_PANEL3.TGA" }, { 0x2c9a894d, "MARS.NB_PANEL1.TGA" }, { 0x2ca6ef28, "PLUTO.GRRR.TGA" }, { 0x2caa5788, "HDESERTTROOPPANEL.TGA" }, { 0x2cb30af4, "CIRC_S.TGA" }, { 0x2cb46d8f, "HBLA_SD.TGA" }, { 0x2d088b94, "FX_GAS08.TGA" }, { 0x2d1bc431, "ICE.FFFF2.TGA" }, { 0x2d1f3b08, "FX_ESP08.TGA" }, { 0x2d307a91, "HSLAT1L.TGA" }, { 0x2d38ef05, "MARS.LLGG2.TGA" }, { 0x2d3f65f8, "ICE.DEV_LANDG.TGA" }, { 0x2d572709, "TITAN.T_PANEL2.TGA" }, { 0x2d6ec4f9, "FX_SMK05.TGA" }, { 0x2d737f85, "TEMPERATE.GGGG4.TGA" }, { 0x2d9584c6, "PLUTO.GRRR.TGA" }, { 0x2d9f6657, "SCANNEX_CYB_SML.TGA" }, { 0x2daeaf6b, "EUROPA.PAVE_PLAIN2.TGA" }, { 0x2dd8c435, "TEMPERATE.TRANS_DPPP.TGA" }, { 0x2dd97efa, "TEMPERATE.GRRR2.TGA" }, { 0x2de367d6, "VENUS.SSSS8.TGA" }, { 0x2deb3e4d, "HDESERTGNRC.TGA" }, { 0x2df63dc6, "@FX_ELC02.TGA" }, { 0x2e2a3f0d, "VENUS.SDDD2.TGA" }, { 0x2e380f26, "NANOREPAIR_S.TGA" }, { 0x2e57819f, "TEMPERATE.GGGG2.TGA" }, { 0x2e723471, "CYSHIELDGENS1_SD.TGA" }, { 0x2e7eff0d, "RUINS1.TGA" }, { 0x2e9baa4e, "DESERT.DB_MOON0.TGA" }, { 0x2ea04ea8, "SCANNEX_DS_SML.TGA" }, { 0x2ec03858, "TITAN.GHHH2.TGA" }, { 0x2ec9f501, "HUSHIELDGENL2_S.TGA" }, { 0x2eddc8f6, "FLARES_SD.TGA" }, { 0x2edfb625, "XTURRET.TGA" }, { 0x2ee3bc8d, "VENUS.DGGG.TGA" }, { 0x2ee4e087, "CY_FOOTPRINT.TGA" }, { 0x2ee5bf2d, "HVENUSCRYSTAL.TGA" }, { 0x2efe1c5e, "SGUN_S.TGA" }, { 0x2f083d06, "FX_DUSTLB04.TGA" }, { 0x2f63b2c4, "PLUTO.RMMR.TGA" }, { 0x2f6b419f, "FX_ELC01.TGA" }, { 0x2fefe526, "TITAN.GGOO.TGA" }, { 0x30544ee1, "SEEK_MG.TGA" }, { 0x3059a86d, "ICE.FFFF4.TGA" }, { 0x307ba387, "ICE.PAVED_SCORCH.TGA" }, { 0x309fb0b6, "MERCURY.PAVE_PLAIN2.TGA" }, { 0x30cd900a, "MERCURY.DDDD5.TGA" }, { 0x30de1288, "XSLATS2.TGA" }, { 0x30f4ab1e, "VENUS.GGDD2.TGA" }, { 0x30fcbb54, "MERCURY.TRANS_DPPP.TGA" }, { 0x3110a2b9, "HU_ENGINE4_S.TGA" }, { 0x312ec6ab, "LGB_S.TGA" }, { 0x31410095, "PREV_DM_AVALANCHE.TGA" }, { 0x31556a1e, "MARS.GGGG5.TGA" }, { 0x31cc6157, "MOON.RD_D_STRT.TGA" }, { 0x31db1589, "PLUTO.GSSS.TGA" }, { 0x31f218f6, "@FX_LENSFLARE_2.TGA" }, { 0x32047fc3, "@FX_LXP05.TGA" }, { 0x3206af64, "XGRUNGE2.TGA" }, { 0x32296613, "XGRATE4.TGA" }, { 0x322c630b, "TEMPERATE.D.PANEL2.TGA" }, { 0x32333618, "TEAM_2.TGA" }, { 0x323e1b6e, "XTECH4.TGA" }, { 0x3245e38e, "BATTERY_S.TGA" }, { 0x32887f0c, "PLUTO.RRRR2.TGA" }, { 0x328f41af, "DELSTATE.TGA" }, { 0x32aabc94, "TITAN.N_PANEL0.TGA" }, { 0x32ad0771, "MARS.LGGG3.TGA" }, { 0x32ad6853, "QUIT.TGA" }, { 0x32aff392, "HUENGINEM2_SD.TGA" }, { 0x32bfe512, "@FX_SPK09.TGA" }, { 0x331a552f, "VENUS.D.PANEL2.TGA" }, { 0x336ac741, "FX_DROP05.TGA" }, { 0x338db993, "VENUS.PAVED_PPPP.TGA" }, { 0x33944aa5, "PLUTO.T.PANEL1.TGA" }, { 0x339de251, "PLUTO.GGGG4.TGA" }, { 0x33d0d172, "FLOATSEL.TGA" }, { 0x33dd1623, "PLUTO.MMRR2.TGA" }, { 0x33e4eb19, "MERCURY.RD_PP_CRNR.TGA" }, { 0x343d7af8, "EUROPA.RFFF.TGA" }, { 0x346feed0, "HUREACTORS1_SD.TGA" }, { 0x3474a3ce, "BANS_KN.TGA" }, { 0x3488c273, "EUROPA.TRANS_PDDD.TGA" }, { 0x34964a6b, "PLUTO.GGGG.TGA" }, { 0x34a382dd, "ICE.RRRR2.TGA" }, { 0x34aaa1f6, "DESERT.T.PANEL7.TGA" }, { 0x34ab2af1, "CY_ENGINE4_S.TGA" }, { 0x34b317c9, "SETPLAYINGGAME.TGA" }, { 0x34ca24d6, "EUROPA.RRRR4.TGA" }, { 0x34ef2ad7, "HMOONWINDOW.TGA" }, { 0x34efdddb, "HU_ENGINE4_SD.TGA" }, { 0x34f43e98, "TITAN.ROAD_BEGIN.TGA" }, { 0x350ffe88, "SCANNEX_CANN_LG.TGA" }, { 0x35213df0, "XSLATS6.TGA" }, { 0x3530c5ae, "FX_DUSTYL14.TGA" }, { 0x35403cbb, "VENUS.DDDD.TGA" }, { 0x3548b7eb, "MOON.SSSS6.TGA" }, { 0x35668dde, "DESERT.SDDS.TGA" }, { 0x35824aac, "ANGELLIFE_S.TGA" }, { 0x35a08719, "HTITANDOOR.TGA" }, { 0x35a14fe4, "TITAN.PAVED_SCORCH.TGA" }, { 0x35a4afeb, "TEMPERATE.GGRR.TGA" }, { 0x35a8c825, "@FX_EXS02.TGA" }, { 0x35bf9239, "MFAC_SD.TGA" }, { 0x35ccfa72, "MARS.TRANS_PPDD.TGA" }, { 0x35ddd3d6, "AGRAVGEN_S.TGA" }, { 0x35f0da66, "FX_LXP13.TGA" }, { 0x35f2fcb6, "ANGELLIFE_SD.TGA" }, { 0x35f81334, "DESERT.DDDD.TGA" }, { 0x36021d6a, "CB_POPUP.TGA" }, { 0x36087e5f, "FX_SPK14.TGA" }, { 0x3618d9c8, "MERCURY.RD_D_CROS.TGA" }, { 0x365d1b7a, "MARS.SSAA.TGA" }, { 0x36628fae, "MOON.DDDD3.TGA" }, { 0x36797172, "HMARH.TGA" }, { 0x368ae711, "PLUTO.T.PANEL0.TGA" }, { 0x369247d5, "EUROPA.CFCF.TGA" }, { 0x369c0c08, "SHEP_MG.TGA" }, { 0x36a7220f, "MARS.D.PANEL4.TGA" }, { 0x36bfc659, "@FX_SHK03.TGA" }, { 0x36cab9cd, "EUROPA.RRRR.TGA" }, { 0x36cad83e, "HU_ENGINE2_SD.TGA" }, { 0x36e5ef90, "VENUS.GDDD.TGA" }, { 0x36eefc2d, "XZEN_LITE.TGA" }, { 0x36fc9d2e, "MARS.DB_PANEL0.TGA" }, { 0x37005622, "HVENUSTROOPLOGO.TGA" }, { 0x3706c049, "FX_GAS12.TGA" }, { 0x3715d93b, "MERCURY.SSDD.TGA" }, { 0x372427c4, "XSAFETY2.TGA" }, { 0x3746acfb, "CLOSE.TGA" }, { 0x37499370, "HU_ENGINE1_S.TGA" }, { 0x375036aa, "HVENUSROOF.TGA" }, { 0x376e4ef3, "PLUTO.SGGG.TGA" }, { 0x379c3915, "XDROPPOD.TGA" }, { 0x37ba588f, "TITAN.OOOO2.TGA" }, { 0x37c309bc, "MARS.RD_PAVE_TEE.TGA" }, { 0x37d1ae2c, "PLUTO.SSSS.TGA" }, { 0x37d85abe, "PLUTO.GRRG2.TGA" }, { 0x37ddf208, "MP3.TGA" }, { 0x3806b283, "FX_GAS11.TGA" }, { 0x3813c587, "PING_GREEN.TGA" }, { 0x381ecbb4, "@FX_EB04.TGA" }, { 0x3823210a, "@FX_GFLARE.TGA" }, { 0x385429d2, "VENUS.SDDD2.TGA" }, { 0x387fdae7, "FX_DUSTLG12.TGA" }, { 0x38875f5f, "XHEAL_DARK.TGA" }, { 0x389be827, "MARS.RD_DIRT_STRT.TGA" }, { 0x38a54279, "TITAN.GGHH.TGA" }, { 0x38b50a0a, "PLUTO.TECH_TTSS.TGA" }, { 0x392278d0, "CIN_CAFACE.TGA" }, { 0x393af036, "FX_PLAS.TGA" }, { 0x395677f8, "HBRICK4T.TGA" }, { 0x3989748f, "CSLAT1.TGA" }, { 0x3993b3a3, "PREV_DM_STATE_OF_CONFUSION.TGA" }, { 0x3993bab2, "MFAC_S.TGA" }, { 0x39a64e9f, "MERCURY.RD_TRANS.TGA" }, { 0x39a9c248, "SHIELDMODULATER_SD.TGA" }, { 0x39ba49b2, "ICE.RRFF3.TGA" }, { 0x39bd9066, "FB1.TGA" }, { 0x39d32fd1, "XPAD.TGA" }, { 0x39dc4a0b, "XPULSE.TGA" }, { 0x3a2e4807, "DEBUG.TGA" }, { 0x3a681207, "FX_GAS03.TGA" }, { 0x3a79da8b, "ICE.TRANS_DPPP.TGA" }, { 0x3aa3a168, "FX_FLA01.TGA" }, { 0x3aba9587, "DESERT.RD_PAVE_CRNR.TGA" }, { 0x3ad85c48, "SHIELDCAPACITOR_S.TGA" }, { 0x3b0cf5c7, "FX_MFAC.TGA" }, { 0x3b336f97, "FX_DUSTLB06.TGA" }, { 0x3b399537, "TITAN.HHHH2.TGA" }, { 0x3b441056, "DESERT.SSSS.TGA" }, { 0x3b54af9c, "TITAN.PAVED_PPPP2.TGA" }, { 0x3b5a60f5, "@FX_DIS03.TGA" }, { 0x3b639e2d, "SHIELDAMPLIFIER_S.TGA" }, { 0x3b6a1f44, "PLUTO.RD_D_CRNR.TGA" }, { 0x3b7d091c, "EUROPA.DDDD4.TGA" }, { 0x3b82b0e5, "INTERIOR.TGA" }, { 0x3b8d1e2b, "SCISSORS.TGA" }, { 0x3ba355d5, "MARS.GLLL.TGA" }, { 0x3bba21e4, "FX_SHK03.TGA" }, { 0x3bc41061, "TEMPERATE.GGGG2.TGA" }, { 0x3bc78482, "FX_BSMK06.TGA" }, { 0x3bd06073, "VENUS.RD_P_CROS.TGA" }, { 0x3be733f4, "DESERT.RD_DIRT_CROS.TGA" }, { 0x3be97b25, "MERCURY.LLLL3.TGA" }, { 0x3bed46f8, "VENUS.SSSS4.TGA" }, { 0x3c070810, "HDOORL.TGA" }, { 0x3c11e170, "HUSENSORL1_S.TGA" }, { 0x3c177401, "ICON_WON.TGA" }, { 0x3cbf610a, "MOON.RD_TRANS.TGA" }, { 0x3cc5e469, "TITAN.GGGG4.TGA" }, { 0x3cfa6bff, "FX_SMK15.TGA" }, { 0x3d118dd8, "UNDO.TGA" }, { 0x3d158858, "TITAN.N_PANEL2.TGA" }, { 0x3d241595, "XAMMO_LITE.TGA" }, { 0x3d3e3fd0, "CY_ENGINE2_SD.TGA" }, { 0x3d547b66, "MARS.T.PANEL1.TGA" }, { 0x3d6332c0, "GOAD_CY.TGA" }, { 0x3d679982, "FX_SPK13.TGA" }, { 0x3d6a68b7, "TITAN.ROAD_BEGIN.TGA" }, { 0x3d99ebd0, "PLUTO.MMMM2.TGA" }, { 0x3ddad789, "MOON.RD_P_STRT.TGA" }, { 0x3ddb660a, "MERCURY.DDDD4.TGA" }, { 0x3df22ca1, "DECHEIGT.TGA" }, { 0x3df439f2, "TEMPERATE.DDDD5.TGA" }, { 0x3e1b7631, "ICE.DDDD2.TGA" }, { 0x3e27efd3, "MERCURY.SSDD2.TGA" }, { 0x3e332e47, "MERCURY.LDDL2.TGA" }, { 0x3e7eb721, "HUENGINEM1_S.TGA" }, { 0x3e807ebd, "ICE.DFFD.TGA" }, { 0x3e814d46, "XGRID.TGA" }, { 0x3eae965b, "EUROPA.RFFF2.TGA" }, { 0x3ebefe15, "FX_DUSTYL08.TGA" }, { 0x3ec7a508, "HTITAN_PHASOR_B.TGA" }, { 0x3edfacba, "TITAN.GGGG2.TGA" }, { 0x3ee18c91, "DESERT.T.PANEL2.TGA" }, { 0x3f00877f, "FX_DUSTBL02.TGA" }, { 0x3f111c9c, "ICE.RRRR5.TGA" }, { 0x3f14cf22, "CY_ENGINE1_SD.TGA" }, { 0x3f39be2a, "ARMOR6_SD.TGA" }, { 0x3f44c886, "GUIOPEN.TGA" }, { 0x3f4d33ba, "SETMAT.TGA" }, { 0x3f5638eb, "TITAN.HOOO2.TGA" }, { 0x3f639bb6, "MARS.AAAA2.TGA" }, { 0x3f682cae, "CY_FLYENGINEL_SD.TGA" }, { 0x3f854472, "VENUS.DB_PANEL1.TGA" }, { 0x3f885194, "FX_DUSTBL10.TGA" }, { 0x3f888fcb, "FX_LENSFLARE_1.TGA" }, { 0x3fb934c7, "@FX_LENSFLARE_3.TGA" }, { 0x3fceace7, "MARS.SSGG.TGA" }, { 0x3fdce972, "TITAN.ROAD_CRNR.TGA" }, { 0x3ff055d0, "VENUS.GDSS2.TGA" }, { 0x3ff59570, "DESERT.RD_TRANS.TGA" }, { 0x403d8fff, "FOLDEROPEN.TGA" }, { 0x406f3858, "MARS.SSSS5.TGA" }, { 0x407214b6, "EUROPA.RRRR3.TGA" }, { 0x4075257f, "FX_QGUN.TGA" }, { 0x407557fd, "VENUS.NB_PANEL0.TGA" }, { 0x408e61de, "@FX_FOG.TGA" }, { 0x40a06044, "TEMPERATE.TB_PANEL0.TGA" }, { 0x40afc84a, "XHERCMOVIE8.TGA" }, { 0x40b0bbf0, "PLUTO.GGGG5.TGA" }, { 0x40ebfc11, "LIGHTNING_LOW.TGA" }, { 0x40ed06ba, "HTITAN_PHASOR_A.TGA" }, { 0x40f6f37a, "EUROPA.CFCF.TGA" }, { 0x40fc76a2, "FX_DUSTLB14.TGA" }, { 0x410729c6, "FX_LXP05.TGA" }, { 0x411f71e1, "EUROPA.FFFF3.TGA" }, { 0x4131ca73, "HUENGINEL1_S.TGA" }, { 0x4183ae09, "FX_LXP08.TGA" }, { 0x418ff3b0, "MERCURY.LDDD2.TGA" }, { 0x419d88d0, "EUROPA.RD_D_STRT.TGA" }, { 0x41b2f3c7, "VENUS.SSSS5.TGA" }, { 0x41ba6a1d, "@FX_ELC01.TGA" }, { 0x41c6c421, "TEMPERATE.NB_PANEL1.TGA" }, { 0x41f2f1b9, "MOON.SSSS4.TGA" }, { 0x41fd50a8, "HUSENSOR3_SD.TGA" }, { 0x42241449, "DAM_SELF_LOW.TGA" }, { 0x425563b6, "FX_SMK08.TGA" }, { 0x426c47c0, "CY_ARTL.TGA" }, { 0x42a2a6e4, "EUROPA.FGRR2.TGA" }, { 0x42c20a2f, "FX_HLAS.TGA" }, { 0x42c41601, "FX_FLA03.TGA" }, { 0x42dfe8c7, "TITAN.OOOO2.TGA" }, { 0x42eb5328, "FX_ELC03.TGA" }, { 0x4300033f, "TITAN.OHHH2.TGA" }, { 0x430a0625, "HUSHIELDGENL1_S.TGA" }, { 0x43278f33, "XRADARS.TGA" }, { 0x435bd1e7, "CYTHERMSENSOR_S.TGA" }, { 0x438d4017, "FX_DUST06.TGA" }, { 0x43919cf0, "HVENUSDOORS.TGA" }, { 0x43925898, "MERCURY.LLLL.TGA" }, { 0x439d468c, "DESERT.GGGG3.TGA" }, { 0x43a59c2e, "DESERT.PAVEDSCORCH.TGA" }, { 0x43bcc125, "MERCURY.SSSS2.TGA" }, { 0x44060627, "TEMPERATE.DGGG2.TGA" }, { 0x44082ebf, "TITAN.ROAD_STRT.TGA" }, { 0x440f1adb, "SHIELDS_LOW.TGA" }, { 0x44afb138, "PLUTO.PAVED_PPPP.TGA" }, { 0x44b7491a, "HTITANCEMENT.TGA" }, { 0x44d5d2de, "FX_DUSTDB12.TGA" }, { 0x44d843e8, "EUROPA.FFRR.TGA" }, { 0x45077ae5, "ICE.DEV_PLAIN2.TGA" }, { 0x451799c7, "TITAN.GCCC.TGA" }, { 0x451bd05b, "EUROPA.D.PANEL0.TGA" }, { 0x454767aa, "HDESERTTROOPSTRIPE.TGA" }, { 0x456b9f8b, "EVALUATE.TGA" }, { 0x4570075f, "MARS.T.PANEL7.TGA" }, { 0x4571a237, "ICE.RD_P_STRT.TGA" }, { 0x4574bb3b, "EMP_SD.TGA" }, { 0x45911d3f, "FX_EMP04.TGA" }, { 0x45a13aa3, "MERCURY.PAVE_PLAIN1.TGA" }, { 0x45a82052, "HLOGO1L.TGA" }, { 0x45aa649c, "PREV_DM_REQUIEM_FOR_GEN_LANZ.TGA" }, { 0x45d5e26b, "MERCURY.DSSS.TGA" }, { 0x45d62a28, "VENUS.RD_P_TEE.TGA" }, { 0x45f7642a, "FX_SHD05.TGA" }, { 0x460679f5, "@FX_SHD04.TGA" }, { 0x461bf1dd, "VENUS.SGDD.TGA" }, { 0x461c2cfd, "XTECH3.TGA" }, { 0x4625c49a, "HUENGINEM3_S.TGA" }, { 0x462b5385, "FX_ELC05.TGA" }, { 0x462f5cca, "CUR_GRAB.TGA" }, { 0x464e1cf7, "HTROOPWINDOWS.TGA" }, { 0x46546f30, "MOON.GDDD.TGA" }, { 0x465937d0, "FX_DUSTDY08.TGA" }, { 0x465fd37f, "DESERT.GDGG.TGA" }, { 0x468045b2, "EUROPA.RD_P_TEE.TGA" }, { 0x468ecc26, "XFLATBED.TGA" }, { 0x46a4021c, "FX_RAD.TGA" }, { 0x46adf964, "HMARSMASSDRIVER_A.TGA" }, { 0x46b3612d, "CY_CPIT.TGA" }, { 0x46e1d4fa, "PLUTO.PAVED_SSSS.TGA" }, { 0x46ea0f06, "CY_ENGINE4_SD.TGA" }, { 0x46ef3181, "PLAS_S.TGA" }, { 0x4702edc1, "FX_DUSTBR12.TGA" }, { 0x472d4dad, "FX_DUSTDY09.TGA" }, { 0x47332a30, "MERCURY.DDLL.TGA" }, { 0x47379934, "TEMPERATE.GGGG5.TGA" }, { 0x473d3a21, "HDOORSWINDOWSMP.TGA" }, { 0x47773353, "CYENGINETURBO_SD.TGA" }, { 0x47ac3343, "EUROPA.RD_P_CRNR.TGA" }, { 0x47b15070, "MOON.RD_D_TEE.TGA" }, { 0x47d17a3d, "MERCURY.RD_D_TEE.TGA" }, { 0x47d9ca8f, "TITAN.CCGG2.TGA" }, { 0x47f9d2cf, "IRC_ICON_OPER_L.TGA" }, { 0x4839e125, "MOON.PAVE_PLAIN1.TGA" }, { 0x48421343, "@FX_EXS08.TGA" }, { 0x4850525c, "PLUTO.GGRR.TGA" }, { 0x486b7477, "EMAN_RB.TGA" }, { 0x486cd693, "PLUTO.RD_D_END.TGA" }, { 0x4871be76, "ICE.NB_PANEL1.TGA" }, { 0x48767df0, "MP2.TGA" }, { 0x487c1b33, "MERCURY.RD_PP_TEE.TGA" }, { 0x4880515d, "XNAVPOINT.TGA" }, { 0x4899b028, "XHERCMOVIE12.TGA" }, { 0x48aaa1fd, "FX_EXS06.TGA" }, { 0x48ea8d35, "MARS.RD_PAVE_CROS.TGA" }, { 0x48f00b22, "TITAN.CGGG2.TGA" }, { 0x492853b1, "CTECH7.TGA" }, { 0x492ce7d7, "NO_ARMOR_S.TGA" }, { 0x4944f5bb, "FX_RAL02.TGA" }, { 0x49474aba, "XAMMO_DARK.TGA" }, { 0x496083e2, "XHERCMOVIE3.TGA" }, { 0x49615d85, "TEMPERATE.GRRR2.TGA" }, { 0x496a074f, "MARS.T.PANEL2.TGA" }, { 0x4982c7a1, "FX_DUSTDY05.TGA" }, { 0x498b7418, "TITAN.GGGG.TGA" }, { 0x49a17a10, "MOON.RGGG2.TGA" }, { 0x49cdefc5, "FX_DROP06.TGA" }, { 0x49ff5250, "TITAN.OGGG.TGA" }, { 0x4a24625a, "SELBYNAM.TGA" }, { 0x4a47a1ef, "APOC_PIRATE.TGA" }, { 0x4a5c0937, "QGUN_SD.TGA" }, { 0x4a875ab9, "XWINDOW2.TGA" }, { 0x4a9d916f, "TEMPERATE.TB_PANEL1.TGA" }, { 0x4aa49fb1, "XHERCMOVIE1.TGA" }, { 0x4acad0ed, "ICE.T.PANEL3.TGA" }, { 0x4acc046d, "PLUTO.SSSS3.TGA" }, { 0x4acc1644, "SETPAUSEGAME.TGA" }, { 0x4aeb4754, "RECALCULATE.TGA" }, { 0x4afa7e7a, "FX_CHN01.TGA" }, { 0x4b1156f3, "CIRC_D.TGA" }, { 0x4b42966b, "FX_DUSTDB08.TGA" }, { 0x4b57956e, "VENUS.SSSS.TGA" }, { 0x4b58c476, "TITAN.GGHH2.TGA" }, { 0x4b803786, "VENUS.T.PANEL0.TGA" }, { 0x4b8b7b57, "MOON.RD_P_CROS.TGA" }, { 0x4b9e332e, "KN_DROP.TGA" }, { 0x4bb14ca1, "EUROPA.RD_D_CRNR.TGA" }, { 0x4bc181a4, "PLUTO.MRRR.TGA" }, { 0x4bc55eb6, "TITAN.ROAD_CROS.TGA" }, { 0x4be96b1b, "CYSHIELDGENS2_SD.TGA" }, { 0x4c2a503c, "FX_SPK07.TGA" }, { 0x4c2b339c, "TITAN.DB_MOON0.TGA" }, { 0x4c37a1bc, "EUROPA.RD_P_STRT.TGA" }, { 0x4c3b94fb, "VENUS.SSGG2.TGA" }, { 0x4c69aac2, "THERMALDIFFUSER_S.TGA" }, { 0x4c704c38, "CYENGINEL3_SD.TGA" }, { 0x4c8092d3, "XSLATS4.TGA" }, { 0x4c892bbe, "CYSENSORM2_S.TGA" }, { 0x4c8e9ec4, "@FX_ESP06.TGA" }, { 0x4ca174fc, "MOON.SSSS.TGA" }, { 0x4cc35ef1, "MARS.PAVED2.TGA" }, { 0x4cc4f678, "MARS.SSGG2.TGA" }, { 0x4cf41d60, "DESERT.GDDG.TGA" }, { 0x4d12afa6, "CHECK_N_ON.TGA" }, { 0x4d18e6cd, "TITAN.OOOO4.TGA" }, { 0x4d426533, "FX_DUSTDO04.TGA" }, { 0x4d44c326, "MARS.LGGG.TGA" }, { 0x4d5774f2, "XSAFETY.TGA" }, { 0x4d5a475a, "HUSENSORL1_SD.TGA" }, { 0x4d746246, "TITAN.TB_PANEL0.TGA" }, { 0x4d7d1983, "DESERT.TB_PANEL0.TGA" }, { 0x4d91d37e, "MARS.SSGG.TGA" }, { 0x4d9aa70b, "DOPPLEGANGER_SD.TGA" }, { 0x4da71765, "SCANNEX_ORBIT_LG.TGA" }, { 0x4dabe8a8, "DESERT.DDDD3.TGA" }, { 0x4dbd3698, "LAS_SD.TGA" }, { 0x4df308ea, "MOON.PAVE_LANDG.TGA" }, { 0x4e02b2f9, "FX_ELE03.TGA" }, { 0x4e0bd668, "TITAN.HHHH.TGA" }, { 0x4e2cb05c, "HBRICK2T.TGA" }, { 0x4e415cdb, "FX_CHN03.TGA" }, { 0x4e4cc2a2, "MOON.DDSS2.TGA" }, { 0x4e5e3353, "TEMPERATE.RD_P_TEE.TGA" }, { 0x4e9dd2ea, "UNIPACK_S.TGA" }, { 0x4ea6c243, "@FX_SPK08.TGA" }, { 0x4eb12cd4, "XSNOWTECH.TGA" }, { 0x4edeeffb, "MERCURY.LLLL4.TGA" }, { 0x4ef4605c, "VENUS.GSSS.TGA" }, { 0x4efa22b2, "FX_DUSTDO02.TGA" }, { 0x4f0d6733, "TEMPERATE.RRRR.TGA" }, { 0x4f77327d, "@FX_FL01.TGA" }, { 0x4fddad0d, "MOON.DSSS.TGA" }, { 0x4fe1e28b, "MARS.LLLL.TGA" }, { 0x500ced23, "VENUS.SSSS2.TGA" }, { 0x50630985, "@FX_DIS05.TGA" }, { 0x507414ed, "CYSHIELDGENL1_S.TGA" }, { 0x50747e82, "FX_DUSTLB13.TGA" }, { 0x50c78f3f, "MERCURY.RD_D_CRNR.TGA" }, { 0x50d12f07, "MOON.PAVE_LANDG.TGA" }, { 0x5103f0b4, "DESERT.DSSD.TGA" }, { 0x510f7d0c, "EUROPA.GGGG4.TGA" }, { 0x5117f44e, "FX_ESP05.TGA" }, { 0x5119f283, "CTF2.TGA" }, { 0x5149d7d9, "MOON.GRRR2.TGA" }, { 0x51574e94, "@FX_RAL02.TGA" }, { 0x515c6027, "CYSENSORM2_SD.TGA" }, { 0x51733b26, "FX_DUSTDO08.TGA" }, { 0x51c16044, "ICE.TRANS_DDPP.TGA" }, { 0x51c3ed26, "DISR_KN.TGA" }, { 0x51c6c72d, "FX_DUSTBL08.TGA" }, { 0x51c7ba27, "HMARSKUL.TGA" }, { 0x51cbe1f8, "CIN_AGIRL.TGA" }, { 0x51dd7e3d, "LTADS_SD.TGA" }, { 0x51ec7770, "FX_DUSTLB08.TGA" }, { 0x51ed124e, "@FX_LXP15.TGA" }, { 0x51f218c8, "BULLET.TGA" }, { 0x52249467, "TITAN.PAVED_GPPP.TGA" }, { 0x522cd1b4, "TITAN.GGGG3.TGA" }, { 0x524fc52c, "EUROPA.RGGG2.TGA" }, { 0x526e51bd, "VENUS.NB_PANEL2.TGA" }, { 0x527c8050, "DISR_TR.TGA" }, { 0x528ffcda, "MERCURY.LLLL2.TGA" }, { 0x529420a2, "MERCURY.SSSS5.TGA" }, { 0x52ad36aa, "CYSENSORM1_S.TGA" }, { 0x52d49808, "FX_EB02.TGA" }, { 0x52e191be, "FX_EXS05.TGA" }, { 0x52e89f1e, "CIN_TITAN.TGA" }, { 0x530d6f04, "HUENGINES3_S.TGA" }, { 0x532bad9a, "FX_SMK14.TGA" }, { 0x53385a77, "EUROPA.GRRR2.TGA" }, { 0x5349c53c, "DESERT.RD_PAVE_TEE.TGA" }, { 0x534d3d19, "CIN_MOON.TGA" }, { 0x535422e1, "EUROPA.FFRR2.TGA" }, { 0x5355c58e, "XRUST1.TGA" }, { 0x535c87ef, "SCANNEX_ORBIT_SML.TGA" }, { 0x53754098, "MERCURY.PAVE_SCORCH.TGA" }, { 0x537ab252, "@FX_SHD02.TGA" }, { 0x537b7732, "FX_SPK09.TGA" }, { 0x53bd290d, "DESERT.RD_TRANS.TGA" }, { 0x53c51c4e, "@FX_ESP10.TGA" }, { 0x53cd98ba, "HSTRIPLOGOMP.TGA" }, { 0x53d14af7, "RECL_CY.TGA" }, { 0x541cb372, "OPEN.TGA" }, { 0x54420a93, "DESERT.D.PANEL3.TGA" }, { 0x544df7f9, "TEMPERATE.D.PANEL1.TGA" }, { 0x5451a82a, "PREV_DM_TERRAN_CONQUEST.TGA" }, { 0x5482c225, "FX_DUSTDO01.TGA" }, { 0x5483c1a7, "TEMPERATE.D.MOON1.TGA" }, { 0x54abd797, "DESERT.RD_DIRT_STRT.TGA" }, { 0x54ee9305, "@FX_ELE05.TGA" }, { 0x54f5cd5a, "FIELDSTABILIZER_S.TGA" }, { 0x5500d374, "CYSHIELDGENL2_SD.TGA" }, { 0x552739d6, "TR_POD1.TGA" }, { 0x5538e64d, "VENUS.RD_P_END.TGA" }, { 0x55426b62, "MARS.TRANS_PPDD.TGA" }, { 0x555170e2, "EUROPA.FGRR2.TGA" }, { 0x555bed1f, "MERCURY.SSSS3.TGA" }, { 0x55616a32, "PLUTO.D.PANEL0.TGA" }, { 0x556bd145, "DESERT.GGGG5.TGA" }, { 0x55912e7f, "@FX_SMK18.TGA" }, { 0x55efb5cc, "LAS_S.TGA" }, { 0x55f50b92, "CYSENSORS1_SD.TGA" }, { 0x55fb9db8, "TITAN.HGGG2.TGA" }, { 0x5617f26f, "FX_FLARE1.TGA" }, { 0x564d599d, "SCANNEX_BECK_LG.TGA" }, { 0x5669531d, "HERC.TGA" }, { 0x56897a7f, "HKONGBUDDA.TGA" }, { 0x568ef38a, "PLUTO.GGGG2.TGA" }, { 0x569080c6, "MG_MISC_FINS.TGA" }, { 0x5697af84, "@FX_EX02.TGA" }, { 0x569da06c, "PL_MISC_FINS.TGA" }, { 0x56a146d5, "NODEOPEN.TGA" }, { 0x56a1ad67, "XMOONROCK.TGA" }, { 0x57135a99, "VENUS.SSGG.TGA" }, { 0x57140234, "HMARG.TGA" }, { 0x5765c95d, "TITAN.GGHH2.TGA" }, { 0x579de8e2, "TUBINEBOOST_SD.TGA" }, { 0x57abe55d, "MERCURY.PAVE_SCORCH.TGA" }, { 0x58010382, "HWINDOWS.TGA" }, { 0x5813e22e, "@FX_DISR_02.TGA" }, { 0x5815a88d, "FX_GAS10.TGA" }, { 0x582083aa, "FX_G_GLOW.TGA" }, { 0x583451fb, "EUROPA.CFFF3.TGA" }, { 0x5884d8c4, "MOON.RD_P_CROS.TGA" }, { 0x588792da, "TEMPERATE.RD_P_CROS.TGA" }, { 0x58b90a7b, "TB_FRONT.TGA" }, { 0x58c90578, "@FX_FL11.TGA" }, { 0x58de376e, "@FX_LXP16.TGA" }, { 0x58e0d810, "PLUTO.MMMM3.TGA" }, { 0x58e298ec, "CY_PROM.TGA" }, { 0x58ef6bba, "DARKTGA.TGA" }, { 0x58ffaedf, "MOON.RD_D_CRNR.TGA" }, { 0x5909562d, "CYSENSORS1_S.TGA" }, { 0x59187f58, "TITAN.T_PANEL5.TGA" }, { 0x59262205, "FX_BLAST2.TGA" }, { 0x5930afd4, "TITAN.PAVED_PPPP.TGA" }, { 0x5965900e, "XCARGOSHIP.TGA" }, { 0x596c7e11, "HUSHIELDGENL2_SD.TGA" }, { 0x597b334c, "DESERT.GGGG.TGA" }, { 0x59801c11, "@FX_CHN06.TGA" }, { 0x598532b6, "VENUS.T.PANEL1.TGA" }, { 0x598b2dd1, "HUSHIELDGEN4_S.TGA" }, { 0x5994b3b8, "FX_PR105.TGA" }, { 0x59bafdd6, "@FX_ELE09.TGA" }, { 0x59c10896, "EUROPA.FFRR.TGA" }, { 0x59df1441, "LOAD_CAP.TGA" }, { 0x59e5d7dd, "MARS.AAAA.TGA" }, { 0x59e7eeaf, "TB_BACK.TGA" }, { 0x59f99dfd, "CLAS_SD.TGA" }, { 0x5a0bd261, "VENUS.RD_P_END.TGA" }, { 0x5a49ceab, "ICE.RD_P_TEE.TGA" }, { 0x5a4c3f21, "EUROPA.DGGG2.TGA" }, { 0x5a67c50d, "DESERT.SSDD.TGA" }, { 0x5a734773, "MERCURY.RD_PP_STRT.TGA" }, { 0x5a87b270, "TITAN.GCCC.TGA" }, { 0x5a8bbb0a, "MOON.RGGG.TGA" }, { 0x5a8e3abb, "MOON.TRANS_PPDD.TGA" }, { 0x5aa5b360, "FX_DIS05.TGA" }, { 0x5ac0b600, "HUSHIELDGEN4_SD.TGA" }, { 0x5acbfa0e, "MARS.TRANS_PDDD.TGA" }, { 0x5aed90e0, "@FX_BSMK18.TGA" }, { 0x5b039712, "TEMPERATE.GDDD.TGA" }, { 0x5b1b22f4, "EUROPA.CFFF2.TGA" }, { 0x5b1dde6a, "MARS.SSSA.TGA" }, { 0x5b20f00c, "@FX_GAS02.TGA" }, { 0x5b39ad3b, "MARS.NB_PANEL0.TGA" }, { 0x5b50ac01, "PLUTO.T.PANEL2.TGA" }, { 0x5b95a9c5, "VENUS.PAVED_SCORCH.TGA" }, { 0x5b99118a, "CYSENSORS2_SD.TGA" }, { 0x5bbca7b4, "FX_DROP09.TGA" }, { 0x5bc21a6c, "PLUTO.RGGG.TGA" }, { 0x5bf9e493, "FX_BLK03.TGA" }, { 0x5c1498e6, "CYECM1_SD.TGA" }, { 0x5c27ee07, "MERCURY.TRANS_PDDD.TGA" }, { 0x5c2d1630, "TITAN.GOHH.TGA" }, { 0x5c51f114, "TITAN.DB_PANEL0.TGA" }, { 0x5c658649, "CIN_HAFACE.TGA" }, { 0x5c69bf96, "FX_GAS04.TGA" }, { 0x5c9ae919, "PR_PRX.TGA" }, { 0x5cb136a5, "CY_COMPUTERM_SD.TGA" }, { 0x5ce44037, "TB_RIGHTJUSTIFY.TGA" }, { 0x5d145a57, "EUROPA.RRRR2.TGA" }, { 0x5d1e2145, "ICE.T.PANEL2.TGA" }, { 0x5d41b3e0, "MARS.AAAS.TGA" }, { 0x5d4aed54, "FX_DUSTGR09.TGA" }, { 0x5d5b1d69, "ELF_SD.TGA" }, { 0x5d74b2b6, "MARS.T.PANEL4.TGA" }, { 0x5d77e160, "VENUS.DDDD6.TGA" }, { 0x5d955599, "MERCURY.RD_PP_CROS.TGA" }, { 0x5da735e0, "MOON.RD_P_CRNR.TGA" }, { 0x5daf880d, "ICE.FRRR2.TGA" }, { 0x5db53b9b, "VENUS.NB_PANEL1.TGA" }, { 0x5dbd1aa0, "@FX_LXP02.TGA" }, { 0x5dcb69aa, "EUROPA.GRFF2.TGA" }, { 0x5de67dfe, "MARS.GSSS2.TGA" }, { 0x5ded8f8c, "VENUS.DSSS2.TGA" }, { 0x5dfce5c4, "SCANNEX_MELAN_SML.TGA" }, { 0x5e0fac68, "EUROPA.RRRR3.TGA" }, { 0x5e17841f, "APOC_HA.TGA" }, { 0x5e3978ea, "EUROPA.RRRR2.TGA" }, { 0x5e43cddd, "HUSHIELDGENM1_SD.TGA" }, { 0x5e579699, "CYSENSOR3_S.TGA" }, { 0x5e7c7794, "EUROPA.PAVE_PLAIN2.TGA" }, { 0x5e98635e, "PLUTO.GGGG2.TGA" }, { 0x5eab0fc9, "MOON.DDDD4.TGA" }, { 0x5eb6e6d6, "EUROPA.GFFF2.TGA" }, { 0x5ec32cdb, "XSLATS3.TGA" }, { 0x5ed9db86, "MERCURY.LDDL2.TGA" }, { 0x5edf1c04, "EUROPA.PAVE_LANDG.TGA" }, { 0x5ee1ddcf, "XREDSTRP.TGA" }, { 0x5ee48e6e, "TEMPERATE.GDDD2.TGA" }, { 0x5f07408d, "@FX_DISR_01.TGA" }, { 0x5f09468b, "EUROPA.RD_TRANS.TGA" }, { 0x5f1c7617, "@FX_RAL06.TGA" }, { 0x5f2f6d50, "MERCURY.RD_PP_TEE.TGA" }, { 0x5f32e3af, "MOON.GDDD2.TGA" }, { 0x5f377071, "CYENGINEM3_SD.TGA" }, { 0x5f3e9853, "MARS.LLGG3.TGA" }, { 0x5f639588, "TEMPERATE.RD_TRANS.TGA" }, { 0x5f6bbce0, "HUENGINEM1_SD.TGA" }, { 0x5f731f4c, "FX_DUST02.TGA" }, { 0x5f7ebf38, "@FX_DROP07.TGA" }, { 0x5f8b299a, "ICE.DDDD.TGA" }, { 0x5f949369, "PREV_CTF_STAB_N_GRAB.TGA" }, { 0x5fac00fe, "HUTHERMSENSOR_S.TGA" }, { 0x5fb56ba9, "@FX_FL13.TGA" }, { 0x5fbf6fa9, "QGUN_S.TGA" }, { 0x5fcf7f38, "FX_DUSTYL13.TGA" }, { 0x5fd221ce, "EUROPA.GGGG5.TGA" }, { 0x6030dfd2, "EUROPA.DGGG.TGA" }, { 0x6055ff92, "DESERT.GGGG3.TGA" }, { 0x606d8547, "PLUTO.GGRR2.TGA" }, { 0x60763e70, "EUROPA.RD_D_TEE.TGA" }, { 0x60a4685d, "TR_FOOTPRINT.TGA" }, { 0x60ca3cd9, "HTITANTECH.TGA" }, { 0x60f2b09c, "TEMPERATE.RD_P_CRNR.TGA" }, { 0x6105a71d, "XCROSSBEAM1.TGA" }, { 0x611dee89, "ICE.DB_PANEL0.TGA" }, { 0x6125bb52, "TEMPERATE.DDGG.TGA" }, { 0x61449507, "MARS.TB_PANEL0.TGA" }, { 0x6156184e, "FX_DUSTBR02.TGA" }, { 0x61b52469, "HUENGINETURBO_SD.TGA" }, { 0x61caaa2c, "FX_DISR_04.TGA" }, { 0x61e17ded, "FX_FLA04.TGA" }, { 0x61ea6141, "VENUS.T.PANEL3.TGA" }, { 0x61fb71a6, "@FX_SHD03.TGA" }, { 0x61fbf005, "DESERT.SDDD.TGA" }, { 0x62284e3b, "EUROPA.GDDD2.TGA" }, { 0x62609138, "FX_ESP04.TGA" }, { 0x626a93fc, "@FX_SMK03.TGA" }, { 0x62b5eca4, "HUENGINES2_S.TGA" }, { 0x62d60199, "MOON.DDDD2.TGA" }, { 0x62d85ce2, "DESERT.SSSS3.TGA" }, { 0x62f293de, "TEMPERATE.GGGG3.TGA" }, { 0x62fe3942, "@FX_SHOCK.TGA" }, { 0x6305b8e3, "MARS.GLLL.TGA" }, { 0x6306bddf, "TITAN.CCCC3.TGA" }, { 0x6321f82a, "TEMPERATE.D.MOON0.TGA" }, { 0x632662fe, "CY_TEMPLEWALL_1.TGA" }, { 0x6326cefa, "FX_DISR_02.TGA" }, { 0x6359daa1, "FX_ESP10.TGA" }, { 0x636e87a8, "TITAN.OOOO4.TGA" }, { 0x638bde7f, "XHEADLAMP.TGA" }, { 0x639ed4eb, "TITAN.T_PANEL4.TGA" }, { 0x63a68170, "APOC_KN.TGA" }, { 0x63e1dc2b, "XRUIN3.TGA" }, { 0x63ebef0d, "HUREACTORM1_SD.TGA" }, { 0x6402e120, "NCAN_S.TGA" }, { 0x641d4acd, "TEMPERATE.DGGG.TGA" }, { 0x64337795, "CMDMINE_SD.TGA" }, { 0x643b81c9, "FX_FLA13.TGA" }, { 0x64a244a9, "PREV_DM_THE_GUARDIAN.TGA" }, { 0x64b4e124, "FX_SHD01.TGA" }, { 0x64b736d7, "TR_CPIT.TGA" }, { 0x64c53cda, "@FX_SPK12.TGA" }, { 0x64d96bd1, "MERCURY.LDDL.TGA" }, { 0x64e06626, "@FX_LXP09.TGA" }, { 0x64ed02b3, "MARS.PAVED_CRATER.TGA" }, { 0x650ac058, "XRUIN2.TGA" }, { 0x652a3247, "CIN_MERCURY.TGA" }, { 0x6531b6eb, "XPYLON.TGA" }, { 0x6541795d, "TITAN.TB_PANEL3.TGA" }, { 0x654818e4, "XGRATE.TGA" }, { 0x655ebb54, "TEMPERATE.T.PANEL5.TGA" }, { 0x6584ab3d, "CAPACITOR_S.TGA" }, { 0x658d68a2, "@FX_SMK13.TGA" }, { 0x65925769, "FX_DUSTDY11.TGA" }, { 0x659ddee6, "CFLOR.TGA" }, { 0x65aad3fe, "HGABLE.TGA" }, { 0x65d48dc5, "HFERT1M.TGA" }, { 0x660f4771, "EUROPA.TRANS_PPDD.TGA" }, { 0x6610d882, "TEMPERATE.PAVEDSCORCH.TGA" }, { 0x661482cd, "XCHECKER.TGA" }, { 0x6641f26c, "RAIL_S.TGA" }, { 0x6658b37d, "TR_FOOTPRINT3.TGA" }, { 0x665ab3ff, "DESERT.DDGG.TGA" }, { 0x665d8d70, "PINAREA.TGA" }, { 0x6693b353, "FX_RAL03.TGA" }, { 0x66dbad71, "HUENGINEL3_SD.TGA" }, { 0x66f5c15e, "FX_BSMK01.TGA" }, { 0x67140624, "UNIPACK_SD.TGA" }, { 0x672e33af, "@ARCTIC_TREE.TGA" }, { 0x6732a62a, "TEMPERATE.RGGG.TGA" }, { 0x673aa988, "FX_SHD02.TGA" }, { 0x6740da1a, "ICE.TRANS_PDDD.TGA" }, { 0x6793c04f, "DESERT.DDDD2.TGA" }, { 0x67a064ef, "RELIGHT.TGA" }, { 0x67c3d8e5, "DESERT.DDDD2.TGA" }, { 0x67cf22cc, "DESERT.SSSS3.TGA" }, { 0x67f18504, "@FX_SMK09.TGA" }, { 0x6800bf6f, "HLAS_S.TGA" }, { 0x680d3331, "XGRATE3.TGA" }, { 0x6815a18c, "EUROPA.GRRR.TGA" }, { 0x6827b693, "HDESERTTRIM.TGA" }, { 0x685bd427, "HFACADE.TGA" }, { 0x685e7217, "FX_DUSTDO13.TGA" }, { 0x6869637f, "FX_DUSTBL12.TGA" }, { 0x68847a8c, "FX_BSMK05.TGA" }, { 0x689c9b02, "TUBINEBOOST_S.TGA" }, { 0x68a2ae6d, "PLUTO.SSSS2.TGA" }, { 0x68a97508, "TITAN.D_MOON0.TGA" }, { 0x68cf95ff, "HUD_CIRCLE_F.TGA" }, { 0x68df7292, "VENUS.D.PANEL1.TGA" }, { 0x68e917ab, "REDO.TGA" }, { 0x691726e5, "CTECH8.TGA" }, { 0x692380f7, "ZEN1.TGA" }, { 0x692aca77, "EUROPA.GGGG2.TGA" }, { 0x692b36f3, "CYENGINES3_SD.TGA" }, { 0x6931b22a, "VENUS.RD_P_STRT.TGA" }, { 0x6946b90e, "ROCKETBOOST_SD.TGA" }, { 0x69598297, "ELF_S.TGA" }, { 0x697595be, "FX_DUSTBL13.TGA" }, { 0x697ad7aa, "GUARDIANECM_S.TGA" }, { 0x6988812d, "FX_DUSTLG08.TGA" }, { 0x69bd5520, "FX_DUST08.TGA" }, { 0x69c2d411, "MOON.DDSS.TGA" }, { 0x69c6cad2, "VENUS.GGGG3.TGA" }, { 0x69d0de1c, "XDRIPS1.TGA" }, { 0x69e57e08, "TITAN.HHOO2.TGA" }, { 0x6a047b52, "TEMPERATE.TB_MOON0.TGA" }, { 0x6a17769e, "PLUTO.TECH_TTTT.TGA" }, { 0x6a1ea092, "DESERT.SSSS4.TGA" }, { 0x6a2fff0c, "PING_YELLOW.TGA" }, { 0x6a38972c, "MARS.GGGG3.TGA" }, { 0x6a75f21a, "CYSHIELDGENL2_S.TGA" }, { 0x6a9bcf96, "VENUS.DB_PANEL3.TGA" }, { 0x6aa7cd94, "DESERT.DSSS.TGA" }, { 0x6aabaa93, "MOON.DDDD.TGA" }, { 0x6ab35b3b, "FX_BSMK02.TGA" }, { 0x6b0d1f13, "@FX_PR101.TGA" }, { 0x6b28fdc6, "@FX_DROP06.TGA" }, { 0x6b51baa6, "MERCURY.PAVE_PLAIN2.TGA" }, { 0x6b56492f, "FLARES_S.TGA" }, { 0x6b865945, "ATC_S.TGA" }, { 0x6b868206, "HUSENSORM2_SD.TGA" }, { 0x6b906a24, "CYSHIELDGENL1_SD.TGA" }, { 0x6b9fc4fe, "TITAN.GOOO.TGA" }, { 0x6ba320a9, "ARMOR3_S.TGA" }, { 0x6bae84c0, "CY_ENGINE2_S.TGA" }, { 0x6bc1c490, "FX_DUSTGR11.TGA" }, { 0x6bc6e862, "EUROPA.PAVEDCRATER.TGA" }, { 0x6be1b559, "PLASMABOLT.TGA" }, { 0x6bf96500, "ICE.RRRR.TGA" }, { 0x6c29931a, "SCANNEX_NAVY_SML.TGA" }, { 0x6c43cdc4, "@FX_SPK06.TGA" }, { 0x6c4dbb15, "HUREACTORS2_SD.TGA" }, { 0x6c61d4ef, "HUSENSORL2_SD.TGA" }, { 0x6c7dcdad, "MOON.GGGG3.TGA" }, { 0x6c8d8333, "FX_DUSTDY06.TGA" }, { 0x6ca5746a, "TB_LEFTJUSTIFY.TGA" }, { 0x6cac82ba, "EUROPA.FFFF5.TGA" }, { 0x6ccb7a7f, "TEMPERATE.DGGG2.TGA" }, { 0x6d007acf, "XWINDOW4.TGA" }, { 0x6d0284e9, "FX_DUSTYL01.TGA" }, { 0x6d0976b6, "FX_FLARE.TGA" }, { 0x6d0fe3e0, "@FX_ELE10.TGA" }, { 0x6d46373d, "MARS.PAVED1.TGA" }, { 0x6d730be4, "MARS.PAVED_LANDG.TGA" }, { 0x6db0096f, "@FX_BSMK14.TGA" }, { 0x6dcd45e1, "@FX_BSMK12.TGA" }, { 0x6dd14784, "MERCURY.RD_PP_STRT.TGA" }, { 0x6e054c7a, "MOON.SSSS5.TGA" }, { 0x6e33aa3f, "PLUTO.GGGG4.TGA" }, { 0x6eacd5d4, "MERCURY.SSSS3.TGA" }, { 0x6ebb1ddb, "MERCURY.LDDD.TGA" }, { 0x6ed89659, "SCANNEX_PROV_SML.TGA" }, { 0x6f0a1dde, "VENUS.TB_PANEL3.TGA" }, { 0x6f0f58c7, "@FX_FL09.TGA" }, { 0x6f19cc2f, "ICE.RD_P_STRT.TGA" }, { 0x6f244f97, "HU_COMPUTERM_SD.TGA" }, { 0x6f3e6182, "FX_DIS04.TGA" }, { 0x6f5e0fce, "MARS.SSGG2.TGA" }, { 0x6f9728dc, "FX_DISR_03.TGA" }, { 0x6f98523d, "FX_ELC04.TGA" }, { 0x6f9d965a, "TEMPERATE.PAVE_PLAIN2.TGA" }, { 0x6fae3c23, "VENUS.T.PANEL2.TGA" }, { 0x6fdf8aa5, "TR_SURV.TGA" }, { 0x6ffec6a0, "RAD_S.TGA" }, { 0x7001e8d5, "MERCURY.LLLL2.TGA" }, { 0x7029653b, "MOON.RRRR.TGA" }, { 0x703cfb9f, "FX_CHN00.TGA" }, { 0x7041644c, "COLUMN.TGA" }, { 0x704becf0, "BATTERY_SD.TGA" }, { 0x704f47c4, "VENUS.DGGG.TGA" }, { 0x706d3515, "ICE.FFFF.TGA" }, { 0x709e4453, "MARS.T.PANEL5.TGA" }, { 0x70c2a3d0, "FX_GAS07.TGA" }, { 0x70c6c963, "MARS.RD_DIRT_CROS.TGA" }, { 0x70c7e759, "DESERT.PAVED_TRANS_SPPP.TGA" }, { 0x70caf339, "TEMPERATE.N.MOON0.TGA" }, { 0x70d36ca9, "CTF1.TGA" }, { 0x70da56f8, "CIN_WFEMAL.TGA" }, { 0x71020c36, "TRIANGLE.TGA" }, { 0x712a6fda, "FX_SHD06.TGA" }, { 0x71324ad8, "TR_STAR.TGA" }, { 0x7147cdf1, "TR_DROP.TGA" }, { 0x715382ae, "MERCURY.DSSS2.TGA" }, { 0x715aa20f, "MINO_TR.TGA" }, { 0x7163e292, "ICE.FFFF2.TGA" }, { 0x7165a6d0, "MERCURY.T.MOON.TGA" }, { 0x7180dc2f, "FX_SMK09.TGA" }, { 0x718a1039, "EUROPA.FRGG.TGA" }, { 0x71937ff1, "TLAS_S.TGA" }, { 0x71a8bba8, "VENUS.SSSS4.TGA" }, { 0x71c42396, "EUROPA.RD_D_TEE.TGA" }, { 0x71d9cde9, "FX_DUSTDB06.TGA" }, { 0x71dda69a, "TITAN.HHOO2.TGA" }, { 0x71fd97f9, "@FX_GAS11.TGA" }, { 0x72076f48, "PLUTO.TECH_STTT.TGA" }, { 0x720f0806, "HUSHIELDGENS1_S.TGA" }, { 0x7211d9ef, "HUREACTORL1_SD.TGA" }, { 0x721967e9, "TITAN.PAVED_PPPP2.TGA" }, { 0x72318db8, "@FX_BLS04.TGA" }, { 0x723c5639, "TEMPERATE.DDDD.TGA" }, { 0x7259c904, "CYENGINES2_SD.TGA" }, { 0x72674b6e, "TITAN.NB_PANEL3.TGA" }, { 0x7274ae61, "TITAN.HHHH5.TGA" }, { 0x72803417, "EUROPA.RD_TRANS.TGA" }, { 0x72a0d5ce, "@FX_EXS03.TGA" }, { 0x72ab3c5c, "HMAR03.TGA" }, { 0x72c6b9c4, "FX_LXP06.TGA" }, { 0x72d713bb, "TEMPERATE.D.PANEL3.TGA" }, { 0x72e0142e, "CSLAT5.TGA" }, { 0x72e1949e, "FX_ESP03.TGA" }, { 0x7328bc93, "VENUS.PAVED_PGGG.TGA" }, { 0x7338c063, "EUROPA.DDDD4.TGA" }, { 0x73642b4b, "ICE.RD_P_TEE.TGA" }, { 0x7381816f, "FLATN2HT.TGA" }, { 0x73839094, "ANTIGROW.TGA" }, { 0x73b3dfab, "@FX_EX05.TGA" }, { 0x73c7c10e, "XHERCMOVIE5.TGA" }, { 0x746910c7, "XSLATS8.TGA" }, { 0x7472c0da, "ICE.RRFF3.TGA" }, { 0x7480974c, "HBRICK2D.TGA" }, { 0x7481ebcb, "HDOGMAND.TGA" }, { 0x74b73fed, "ICON_SCANNEX_S.TGA" }, { 0x74d5a0c8, "MOON.SSSS2.TGA" }, { 0x74d9f3e0, "EUROPA.N.PANEL4.TGA" }, { 0x74e2fed8, "CYENGINES3_S.TGA" }, { 0x7527ef9d, "PREV_WAR_MARTIAN_STANDOFF.TGA" }, { 0x752ba98a, "TITAN.HHHH5.TGA" }, { 0x75347c13, "DESERT.T.PANEL6.TGA" }, { 0x754bb9eb, "VENUS.GGGG4.TGA" }, { 0x75891527, "EUROPA.D.PANEL1.TGA" }, { 0x759327b1, "MARS.T.MOON0.TGA" }, { 0x75af957e, "TITAN.ROAD_CROS.TGA" }, { 0x75c46cb2, "SCANNEX_CS_LG.TGA" }, { 0x75c94ac9, "TR_OVER1.TGA" }, { 0x7601b9b9, "HVENUSGIRDER.TGA" }, { 0x7618d6a3, "CYSENSORL2_S.TGA" }, { 0x763b4465, "DESERT.D.PANEL4.TGA" }, { 0x764d5e40, "HTECHWALLMP.TGA" }, { 0x7654fce8, "FX_DUSTDO07.TGA" }, { 0x76aebc07, "PLUTO.RD_D_STRT.TGA" }, { 0x76aefb78, "CYREACTORL2_SD.TGA" }, { 0x76c942ae, "@FX_SPK13.TGA" }, { 0x76ee29ef, "XWINDOW.TGA" }, { 0x76fd347e, "XHERCMOVIE7.TGA" }, { 0x77064524, "XSLUDGE.TGA" }, { 0x772ea341, "FERT_TEX.TGA" }, { 0x77371dda, "EUROPA.RRGG2.TGA" }, { 0x7738b597, "FX_SHK05.TGA" }, { 0x77492b55, "PLUTO.SSSS5.TGA" }, { 0x7797fafd, "TITAN.CCGG.TGA" }, { 0x77a066c9, "SCANNEX_INQU_LG.TGA" }, { 0x77ad58f0, "VENUS.PAVED_GGGG.TGA" }, { 0x77dd7f87, "@FX_BLK04.TGA" }, { 0x77fe4039, "EUROPA.T.PANEL1.TGA" }, { 0x7808ce24, "EUROPA.N.MOON.TGA" }, { 0x7865444c, "@FX_GAS01.TGA" }, { 0x7879f692, "FX_DUSTGR02.TGA" }, { 0x788e5a5c, "FX_ESP09.TGA" }, { 0x789b270c, "MOON.SDDD.TGA" }, { 0x790983be, "TITAN.CGGG2.TGA" }, { 0x79187d5f, "SHIELDAMPLIFIER_SD.TGA" }, { 0x7922e741, "MARS.SGGG2.TGA" }, { 0x792e250a, "MARS.RD_DIRT_CRNR.TGA" }, { 0x7933942d, "EUROPA.RD_D_END.TGA" }, { 0x79752fa1, "VENUS.GGGG7.TGA" }, { 0x79797130, "MOON.TRANS_PDDD.TGA" }, { 0x797fbdae, "VENUS.GGGG6.TGA" }, { 0x79854f38, "TEMPERATE.RRRR3.TGA" }, { 0x79b252b2, "EUROPA.RD_P_CROS.TGA" }, { 0x79d81d35, "HU_FLYENGINES_S.TGA" }, { 0x79f28413, "@FX_EX03.TGA" }, { 0x7a22e802, "FX_FLA06.TGA" }, { 0x7a369f3b, "FX_ELF.TGA" }, { 0x7a5c7e54, "PLUTO.PAVED_SSSS.TGA" }, { 0x7a791d50, "MOON.D.PANEL2.TGA" }, { 0x7a8242ac, "TALO_KN.TGA" }, { 0x7ad6a7ea, "CYREACTORM1_SD.TGA" }, { 0x7addb8a1, "HTITANWINDOW.TGA" }, { 0x7b2d96a5, "TEMPERATE.DB_PANEL3.TGA" }, { 0x7b3fdbfe, "CY_CONS.TGA" }, { 0x7b4aeffe, "FX_DUSTBR04.TGA" }, { 0x7b4e8eef, "FX_DUSTDB03.TGA" }, { 0x7b73c3b2, "@FX_LXP14.TGA" }, { 0x7b7ebd8c, "HSLAT2E.TGA" }, { 0x7b8337c5, "ARA_S.TGA" }, { 0x7b8df724, "TITAN.ROAD_STRT.TGA" }, { 0x7b93944c, "ICE.TB_PANEL2.TGA" }, { 0x7b9a19a0, "FX_ELE04.TGA" }, { 0x7bd56ed7, "MOON.SSSS2.TGA" }, { 0x7bf66ced, "FX_DUSTLG03.TGA" }, { 0x7bfc5b8d, "@FX_BLAST.TGA" }, { 0x7bfcc43d, "EUROPA.CFFC.TGA" }, { 0x7c0a5a4c, "CYREACTORS2_S.TGA" }, { 0x7c1d67c8, "CYENGINEL1_SD.TGA" }, { 0x7c2d47ab, "FX_BSMK12.TGA" }, { 0x7c4e0182, "TEMPERATE.GGRR2.TGA" }, { 0x7c61081a, "XTREAD.TGA" }, { 0x7c61903b, "HMAR06.TGA" }, { 0x7c8158f6, "HDOOR.TGA" }, { 0x7c9319d6, "FX_BLS04.TGA" }, { 0x7cd03ef0, "PLUTO.SGGS2.TGA" }, { 0x7cdfdf85, "CIN_ARMOR.TGA" }, { 0x7d2a6542, "PLUTO.RRRR5.TGA" }, { 0x7d3f1612, "ICE.RFFF3.TGA" }, { 0x7d446421, "@FX_CHN00.TGA" }, { 0x7d451a03, "@FX_SMK02.TGA" }, { 0x7d4c0072, "XMONUMENT.TGA" }, { 0x7da4b667, "ARMOR6_S.TGA" }, { 0x7dbb3388, "MOON.D.PANEL4.TGA" }, { 0x7dd23254, "CYPANEL.TGA" }, { 0x7dd54015, "@FX_CHN05.TGA" }, { 0x7e0309a2, "HU_ENGINE1_SD.TGA" }, { 0x7e5d6793, "SEEK_CY.TGA" }, { 0x7e8ba41c, "TEMPERATE.DDDD.TGA" }, { 0x7eb5ba35, "FX_DUSTYL09.TGA" }, { 0x7ebb6228, "MERCURY.RD_D_END.TGA" }, { 0x7ed14a72, "MARS.SSSS4.TGA" }, { 0x7ee20a3d, "PLUTO.RGGG.TGA" }, { 0x7f12f4d7, "XOBSTACLE.TGA" }, { 0x7f2f0d44, "MOON.RD_D_END.TGA" }, { 0x7f338494, "@FX_LXP03.TGA" }, { 0x7f5dec39, "JUDG_MG.TGA" }, { 0x7f87b01b, "HMARCOP1.TGA" }, { 0x7fa5e1be, "CDISH.TGA" }, { 0x7fb3e34c, "FX_DUSTYL03.TGA" }, { 0x7ffcdc55, "HUENGINEM2_S.TGA" }, { 0x8015b6fa, "MERCURY.N.MOON.TGA" }, { 0x804cd5e1, "TEMPERATE.RD_D_CRNR.TGA" }, { 0x8077a3fc, "FX_EXHAUST.TGA" }, { 0x80843ed8, "FX_CHN04.TGA" }, { 0x8094da91, "HU_FLYENGINES_SD.TGA" }, { 0x80a1c4f2, "MARS.GGGG6.TGA" }, { 0x80d6e028, "@FX_FL07.TGA" }, { 0x80e2a005, "FX_CHN02.TGA" }, { 0x80ed6b50, "TITAN.GHHH.TGA" }, { 0x80f28abb, "BLNK_SD.TGA" }, { 0x80ffe7c0, "SCANNEX_RBL_SML.TGA" }, { 0x810a75d9, "EUROPA.ICECRATER.TGA" }, { 0x8129f9fd, "TITAN.T_PANEL0.TGA" }, { 0x812a4ca8, "@FX_CHN01.TGA" }, { 0x81453d9b, "HKONGCIVIL.TGA" }, { 0x814ad8f8, "FX_DUSTDY13.TGA" }, { 0x81a71101, "ROAD.TGA" }, { 0x81a785e1, "HBRICK4M.TGA" }, { 0x81b77178, "VENUS.N.PANEL1.TGA" }, { 0x81fd9964, "DESERT.RD_DIRT_TEE.TGA" }, { 0x8214d988, "MP1.TGA" }, { 0x8215f870, "@FX_ELE08.TGA" }, { 0x821bd489, "VENUS.SSSS2.TGA" }, { 0x8234d752, "PLUTO.TECH_TTTT.TGA" }, { 0x8236a748, "@FX_SPK14.TGA" }, { 0x82451bee, "VENUS.GGGG.TGA" }, { 0x825cfd5a, "EUROPA.DDGG.TGA" }, { 0x827c5213, "PLUTO.RD_D_CROS.TGA" }, { 0x827d6e5a, "PLUTO.MMMM4.TGA" }, { 0x828ecca4, "TEMPERATE.DDDD3.TGA" }, { 0x829af60a, "SS_BUS.TGA" }, { 0x82b144f6, "SCANNEX_MACH_SML.TGA" }, { 0x82bdb45c, "FX_DISR_01.TGA" }, { 0x82cc38a1, "TEMPERATE.RRRR3.TGA" }, { 0x82e5d210, "CHANCE.TGA" }, { 0x8307db06, "XPIPE.TGA" }, { 0x83277aa3, "MARS.SSSS2.TGA" }, { 0x837227a4, "FX_SHK01.TGA" }, { 0x8394a169, "HCOLONYDOOR2.TGA" }, { 0x839bb0fb, "FX_DUSTGR12.TGA" }, { 0x83a51660, "SCANNEX_IMP_SML.TGA" }, { 0x83b3033c, "EUROPA.PAVEDSCORCH.TGA" }, { 0x83f9f004, "TEMPERATE.RD_P_TEE.TGA" }, { 0x84002317, "PLUTO.RGGG2.TGA" }, { 0x8409a557, "HMARS_POLICE_FLAG.TGA" }, { 0x84156d91, "CYSHIELDGENS1_S.TGA" }, { 0x845d89e2, "DESERT.RD_DIRT_END.TGA" }, { 0x848027f4, "HDESERTPYRAMID.TGA" }, { 0x8491043f, "PLUTO.SSSS5.TGA" }, { 0x84a0d323, "DESERT.DB_PANEL0.TGA" }, { 0x84b4566e, "PLUTO.T.PANEL6.TGA" }, { 0x84c7bea6, "MERCURY.DDLL2.TGA" }, { 0x84f0508c, "TEMP.TGA" }, { 0x84fb1ecb, "FX_DUSTLG01.TGA" }, { 0x85006442, "FX_FLA02.TGA" }, { 0x85087c3f, "@FX_LAS.TGA" }, { 0x850f02d3, "FX_REDEXH.TGA" }, { 0x852876f4, "MERCURY.DDDD6.TGA" }, { 0x85431e8a, "MERCURY.D.MOON.TGA" }, { 0x85462ec6, "MOON.D.MOON.TGA" }, { 0x85490ce1, "FX_DIS02.TGA" }, { 0x855c5e1f, "CYSENSORS2_S.TGA" }, { 0x855c852d, "ICE.PAVED_SCORCH.TGA" }, { 0x85633494, "VENUS.GGDD.TGA" }, { 0x8580f598, "SCANNEX_BECK_SML.TGA" }, { 0x858f76df, "FX_DUSTGR07.TGA" }, { 0x858ff995, "XZEN_DARK.TGA" }, { 0x85951c85, "CIN_SATURN.TGA" }, { 0x85b230ca, "FX_EXS02.TGA" }, { 0x85ba92d3, "MARS.GGGG3.TGA" }, { 0x85e4580e, "TEMPERATE.PAVE_PLAIN1.TGA" }, { 0x85fb4b59, "DESERT.D.PANEL5.TGA" }, { 0x860a16ed, "VENUS.DDDD.TGA" }, { 0x860fcdb6, "DESERT.PAVED1.TGA" }, { 0x861d0260, "MARS.SSSS6.TGA" }, { 0x862669ef, "@FX_SPK10.TGA" }, { 0x862e47dc, "6MISSILEPACK_SD.TGA" }, { 0x868017c7, "WAR1.TGA" }, { 0x8698400a, "@FX_FL08.TGA" }, { 0x86a20656, "@FX_SHK05.TGA" }, { 0x86aca8e5, "@FX_REDEXH.TGA" }, { 0x86b369ca, "@FX_ELC04.TGA" }, { 0x86ce799e, "FX_DUSTDY14.TGA" }, { 0x86d3d7fd, "MOON.DSSS2.TGA" }, { 0x86e87c9b, "CYENGINEM2_S.TGA" }, { 0x86ff938d, "XSLATS5.TGA" }, { 0x87182bee, "EUROPA.D.MOON2.TGA" }, { 0x872203e0, "PLUTO.SGGG2.TGA" }, { 0x8738e17f, "CY_FOOTPRINT3.TGA" }, { 0x8740c3d2, "@FX_PR102.TGA" }, { 0x87415454, "DESERT.DGGD.TGA" }, { 0x8757579d, "MOON.DGGG2.TGA" }, { 0x87769436, "ARMOR5_SD.TGA" }, { 0x879438fb, "MOON.TRANS_PDDD.TGA" }, { 0x87b10955, "CYSPIN.TGA" }, { 0x87b3e8f1, "FX_DUSTLB03.TGA" }, { 0x87d2aaef, "PREV_CTF_BALANCE_OF_POWER.TGA" }, { 0x87e2deb9, "HBRICK3D.TGA" }, { 0x8806d7b9, "@FX_DROP05.TGA" }, { 0x88340812, "TEMPERATE.DDGG.TGA" }, { 0x88434d0f, "@FX_FLARE.TGA" }, { 0x8847972e, "ICE.D.PANEL1.TGA" }, { 0x884cf0f1, "ICE.T.PANEL0.TGA" }, { 0x88550954, "XRUIN1.TGA" }, { 0x8870ee88, "HUSENSOR3_S.TGA" }, { 0x88729218, "FB4.TGA" }, { 0x887d7ad0, "@FX_SPK02.TGA" }, { 0x88fee0bb, "PLUTO.PAVED_PTTT.TGA" }, { 0x890424d2, "HMAR04.TGA" }, { 0x890f9a8b, "MARS.TRANS_PDDD.TGA" }, { 0x891c2785, "FX_DUSTLB10.TGA" }, { 0x89547dcf, "FX_SHK04.TGA" }, { 0x89752751, "@FX_GAS09.TGA" }, { 0x897bc2fb, "PALA_KN.TGA" }, { 0x897d4617, "XVENT2.TGA" }, { 0x89a028ed, "TEMPERATE.RD_D_CROS.TGA" }, { 0x89b804e5, "MERCURY.DDDD.TGA" }, { 0x89b96019, "TITAN.HHHH3.TGA" }, { 0x89bc8a77, "@FX_CHN02.TGA" }, { 0x89e24cf5, "FX_LASE.TGA" }, { 0x89e2733b, "TITAN.GOOO.TGA" }, { 0x89edfd76, "6MINEPACK_S.TGA" }, { 0x8a0dade7, "VENUS.SSGG.TGA" }, { 0x8a147652, "MARS.D.PANEL1.TGA" }, { 0x8a168560, "MARS.RD_DIRT_TEE.TGA" }, { 0x8a27b323, "DESERT.T.PANEL3.TGA" }, { 0x8a2cac34, "SCANNEX_VENUS_LG.TGA" }, { 0x8a35b714, "EUROPA.T.PANEL6.TGA" }, { 0x8a36b7f4, "FX_DUSTBL06.TGA" }, { 0x8a770f97, "GOAD_MG.TGA" }, { 0x8ab55c72, "DESERT.PAVED_TRANS_PSSS.TGA" }, { 0x8ace9bfe, "FX_BSMK18.TGA" }, { 0x8aec003b, "10MINEPACK_SD.TGA" }, { 0x8aee2e05, "ZEN.TGA" }, { 0x8b0ec0c9, "PLUTO.GRRR2.TGA" }, { 0x8b373b8b, "TITAN.GGOO.TGA" }, { 0x8b421e15, "PLUTO.GGRR2.TGA" }, { 0x8b5b163a, "IRC_ICON_SPEC_L.TGA" }, { 0x8b5e74c3, "VENUS.DDDD2.TGA" }, { 0x8b7b3c22, "MERCURY.DDDD5.TGA" }, { 0x8ba1c9df, "SCANNEX_DS_LG.TGA" }, { 0x8bc95ae4, "PLUTO.N.PANEL.TGA" }, { 0x8bf4a0b0, "XCROSSBEAM2.TGA" }, { 0x8bf9310e, "FX_DROP02.TGA" }, { 0x8bfd3df6, "DESERT.SSSS4.TGA" }, { 0x8c01743c, "FX_DUSTWH09.TGA" }, { 0x8c153865, "FX_FLA08.TGA" }, { 0x8c272f62, "MARS.LLLL2.TGA" }, { 0x8c2f0ba7, "NO_SPECIAL_S.TGA" }, { 0x8c4ea392, "HMOONFOIL2.TGA" }, { 0x8c854b52, "FX_DUSTWH01.TGA" }, { 0x8c86f2ef, "TEMPERATE.N.PANEL0.TGA" }, { 0x8c880255, "SETEDITINGMISSION.TGA" }, { 0x8c973873, "CUR_HAND.TGA" }, { 0x8cab3782, "VENUS.DDDD4.TGA" }, { 0x8cabc48c, "FX_DUST11.TGA" }, { 0x8cb23c9b, "FX_SMK04.TGA" }, { 0x8cb5e62e, "CYREACTORL2_S.TGA" }, { 0x8cea4852, "@FX_DROP09.TGA" }, { 0x8d0a314e, "STRCIRCLE.TGA" }, { 0x8d11934a, "WP_GENRC.TGA" }, { 0x8d16b92a, "ICE.RFFF2.TGA" }, { 0x8d19ca30, "PLUTO.TECH_TSSS.TGA" }, { 0x8d22275b, "FX_ESP02.TGA" }, { 0x8d33f1f8, "HFLOOR.TGA" }, { 0x8d34449c, "@FX_SHK02.TGA" }, { 0x8d49d153, "DESERT.GDDD.TGA" }, { 0x8d6ade5a, "LIGHTNING_HIGH.TGA" }, { 0x8d6dad4d, "TEMPERATE.GGGG.TGA" }, { 0x8d7bbfef, "@FX_DROP10.TGA" }, { 0x8d845c59, "XHERCMOVIE11.TGA" }, { 0x8d976ccd, "NO_COMPUTER_S.TGA" }, { 0x8d99b8d9, "HKANGI2.TGA" }, { 0x8dd4703e, "PLUTO.SSSS4.TGA" }, { 0x8dd9e6d1, "PLUTO.RRRR2.TGA" }, { 0x8ddca9a2, "FX_DUSTDO09.TGA" }, { 0x8de09944, "VENUS.GGGG5.TGA" }, { 0x8dec590d, "TITAN.T_PANEL3.TGA" }, { 0x8e1b0257, "EUROPA.GFFF2.TGA" }, { 0x8e22a769, "DESERT.DGGG.TGA" }, { 0x8e22e69e, "TITAN.ROAD_TEE.TGA" }, { 0x8e4a0e3d, "EUROPA.RD_P_TEE.TGA" }, { 0x8e70b3fe, "TB_HSPACE.TGA" }, { 0x8e892c4d, "TITAN.GHOO.TGA" }, { 0x8e9f5084, "TEMPERATE.GRRR.TGA" }, { 0x8ec75f05, "HUENGINEL1_SD.TGA" }, { 0x8ecf8708, "BASL_TR.TGA" }, { 0x8f1dea12, "CYENGINES1_S.TGA" }, { 0x8f1f9b4f, "TEMPERATE.DDDD4.TGA" }, { 0x8f60516b, "VENUS.GDDD2.TGA" }, { 0x8f62bad2, "TITAN.OHHH2.TGA" }, { 0x8f78922a, "@FX_GAS14.TGA" }, { 0x8f84dd1e, "EUROPA.FGRR.TGA" }, { 0x8f8eeef3, "XGLASS.TGA" }, { 0x8f959eb8, "ICE.N.MOON.TGA" }, { 0x90053b1d, "ICE.RRFF2.TGA" }, { 0x90256960, "CIN_WMALE.TGA" }, { 0x9035fed2, "FX_DUST04.TGA" }, { 0x90519646, "TITAN.HOGG.TGA" }, { 0x90b99455, "BLNK_S.TGA" }, { 0x90bae206, "MOON.DDDD2.TGA" }, { 0x91411b08, "FX_SPK04.TGA" }, { 0x91486680, "HUREACTORL2_SD.TGA" }, { 0x914fdd7f, "MARS.RD_TRANS.TGA" }, { 0x9153979c, "EUROPA.DGGG.TGA" }, { 0x91659d6c, "FX_DUSTBR06.TGA" }, { 0x91669dd5, "TITAN.GGHH.TGA" }, { 0x91b3e3bc, "HMARSMASSDRIVER_B.TGA" }, { 0x91b50c22, "@FX_RAL05.TGA" }, { 0x91d46c0b, "@FX_ESP03.TGA" }, { 0x91d7f2d3, "MOON.SSSS5.TGA" }, { 0x91e5d90d, "CYSHIELDGENM2_S.TGA" }, { 0x91f2fe4b, "@FX_ESP05.TGA" }, { 0x91f39619, "SHRK_SD.TGA" }, { 0x91f99996, "XTUBEVENT2.TGA" }, { 0x920b62ad, "MERCURY.RD_D_END.TGA" }, { 0x9210c2af, "@FX_RAL01.TGA" }, { 0x922f810d, "@FX_GAS05.TGA" }, { 0x92479793, "EUROPA.T.PANEL7.TGA" }, { 0x926a0d41, "FLIPHORZ.TGA" }, { 0x926bc89d, "HKONGPIPES.TGA" }, { 0x929fd2f6, "ICE.BLUESCREEN.TGA" }, { 0x92bc4c16, "LINK.TGA" }, { 0x92d72cac, "MERCURY.SDDD2.TGA" }, { 0x92e92edf, "MOON.SSSS6.TGA" }, { 0x92ea7e36, "ICE.DDDD3.TGA" }, { 0x92f59528, "GORG_KN.TGA" }, { 0x92f64c4e, "DESERT.GGGG2.TGA" }, { 0x9308e206, "MERCURY.DLLL2.TGA" }, { 0x93149ac9, "SCANNEX_IMP_LG.TGA" }, { 0x931cd6a3, "DROPPT.TGA" }, { 0x93550c0e, "MARS.GGGG2.TGA" }, { 0x935b4743, "@FX_RAL04.TGA" }, { 0x935c0e4a, "FX_EXS08.TGA" }, { 0x93648aa6, "SHEP_CY.TGA" }, { 0x93a2ca0a, "TITAN.OGGG.TGA" }, { 0x93a3dfeb, "TEMPERATE.GGGG3.TGA" }, { 0x93a70424, "PLUTO.SSGG2.TGA" }, { 0x93b72594, "TITAN.GGGG2.TGA" }, { 0x93d392b7, "XWINDOW8.TGA" }, { 0x93f46874, "@FX_DISR_03.TGA" }, { 0x941628c4, "CIN_MARS.TGA" }, { 0x94174a40, "FX_ELE09.TGA" }, { 0x941db9f7, "@FX_LENSFLARE_5.TGA" }, { 0x942a36b9, "GUARDIANECM_SD.TGA" }, { 0x945d2742, "EHUL_SD.TGA" }, { 0x9463ba01, "MOON.SSSS4.TGA" }, { 0x9466a284, "@FX_CHN04.TGA" }, { 0x94768e6c, "HUENGINES1_S.TGA" }, { 0x94e56dfe, "@FX_RAL09.TGA" }, { 0x9512117a, "VENUS.DGGG2.TGA" }, { 0x951f887c, "TEMPERATE.DB_MOON0.TGA" }, { 0x952300e1, "HKONGROOF.TGA" }, { 0x95504950, "@FX_SPK15.TGA" }, { 0x95553f96, "DIS_S.TGA" }, { 0x9568256d, "TITAN.HOOO.TGA" }, { 0x95a81c56, "EUROPA.CFCF3.TGA" }, { 0x95d2c184, "HUSHIELDGENS1_SD.TGA" }, { 0x95d7b22a, "VENUS.GGGG5.TGA" }, { 0x95e65666, "@FX_DROP08.TGA" }, { 0x95e9b2de, "EUROPA.PAVE_LANDG.TGA" }, { 0x95f15a41, "BLAS_SD.TGA" }, { 0x95f3fd63, "VENUS.RD_P_STRT.TGA" }, { 0x95fe2398, "EUROPA.N.PANEL2.TGA" }, { 0x960212d4, "VENUS.D.PANEL0.TGA" }, { 0x9627c9ee, "LASERMISSILE2_SD.TGA" }, { 0x963d6695, "VENUS.SSSS7.TGA" }, { 0x96476bab, "CURSOR.TGA" }, { 0x964da369, "VENUS.DDDD5.TGA" }, { 0x96507833, "XHERCMOVIE14.TGA" }, { 0x9654e3da, "PREV_CTF_CIRCULAR_LOGIC.TGA" }, { 0x9666fbd4, "TR_CONV.TGA" }, { 0x966f4a49, "@FX_EXS00.TGA" }, { 0x967dd2fd, "FX_EB00.TGA" }, { 0x96b4be35, "TEMPERATE.DDDD4.TGA" }, { 0x96bae3d5, "FX_SPK02.TGA" }, { 0x96d3f824, "SHIELDS_LOW_SOLID.TGA" }, { 0x97081a00, "MARS.RD_PAVE_STRT.TGA" }, { 0x970eeab5, "@FX_FL10.TGA" }, { 0x97161bca, "CYSENSOR4_SD.TGA" }, { 0x971dda46, "@FX_TLAS.TGA" }, { 0x9728b28a, "MOON.DDDD4.TGA" }, { 0x97508d5b, "FX_ELE02.TGA" }, { 0x976f531a, "MARS.RD_DIRT_END.TGA" }, { 0x977e8969, "ICE.T.MOON.TGA" }, { 0x9795e237, "ADVO_CY.TGA" }, { 0x97aea9c4, "SCANNEX_ALLI_LG.TGA" }, { 0x97d13e64, "CLOGO1.TGA" }, { 0x97dab7b7, "VENUS.TB_MOON0.TGA" }, { 0x97df83cd, "DESERT.SSSS2.TGA" }, { 0x97e25644, "MARS.SSSA.TGA" }, { 0x97f65e23, "MARS.AAAA2.TGA" }, { 0x98833c65, "@FX_LXP04.TGA" }, { 0x989769a1, "FX_DUSTBL03.TGA" }, { 0x98c0897d, "MARS.GLLL2.TGA" }, { 0x98c9a8d1, "ICE.FDDD.TGA" }, { 0x98cb72a7, "HUENGINES2_SD.TGA" }, { 0x98e74fc0, "PLUTO.TECH_TTSS.TGA" }, { 0x98ebbd6d, "PLUTO.MMRR.TGA" }, { 0x99163d66, "TITAN.N_MOON0.TGA" }, { 0x99200106, "ICE.FFFF4.TGA" }, { 0x9954698a, "XHUBTECH.TGA" }, { 0x995eb31d, "FX_DUSTWH08.TGA" }, { 0x9984c446, "PLAS_SD.TGA" }, { 0x9999c59e, "@FX_RAL08.TGA" }, { 0x99a5b9ab, "VENUS.GGDD.TGA" }, { 0x99a86a2c, "@FX_FL103.TGA" }, { 0x99a8b66f, "PLUTO.MMRR2.TGA" }, { 0x99b499f3, "TITAN.N_PANEL1.TGA" }, { 0x99b8aefc, "MOON.RD_D_STRT.TGA" }, { 0x99dac3ee, "TITAN.ROAD_CRNR.TGA" }, { 0x99df418a, "CYREACTORL1_SD.TGA" }, { 0x99e07a33, "MARS.N.PANEL2.TGA" }, { 0x99e246ea, "FX_DUSTDB01.TGA" }, { 0x99e28571, "FX_DROP03.TGA" }, { 0x99e42cf0, "TEMPERATE.RD_P_CRNR.TGA" }, { 0x99e554b3, "MARS.AAAA.TGA" }, { 0x99fc9f19, "ICE.TB_PANEL1.TGA" }, { 0x9a16333f, "SETEDITINGTERRAIN.TGA" }, { 0x9a1f6ed2, "FX_RAL07.TGA" }, { 0x9a2cca45, "TEMPERATE.DGGG.TGA" }, { 0x9a2edecf, "VENUS.SSSS6.TGA" }, { 0x9a90b583, "RAIL_SD.TGA" }, { 0x9a9ac8fe, "PREV_DM_COLD_TITAN_NIGHT.TGA" }, { 0x9ab412b3, "TITAN.PAVED_PPGG.TGA" }, { 0x9ad368e9, "XTUBEVENT1.TGA" }, { 0x9afa6748, "PLUTO.PAVED_PPPP2.TGA" }, { 0x9b09a924, "FX_LXP12.TGA" }, { 0x9b6226ce, "ICE.DEV_PLAIN2.TGA" }, { 0x9b75b2d1, "EUROPA.GRFF2.TGA" }, { 0x9b7c2adc, "NANO_S.TGA" }, { 0x9b855820, "CTECH5.TGA" }, { 0x9b9a7c95, "TEMPERATE.PAVE_PLAIN1.TGA" }, { 0x9bb43724, "MARS.GGGG4.TGA" }, { 0x9be78bd9, "FB2.TGA" }, { 0x9bf0abfe, "TEMPERATE.RGGG.TGA" }, { 0x9c10072a, "CY_FLYENGINES_S.TGA" }, { 0x9c2dab6c, "MERCURY.LLLL3.TGA" }, { 0x9c2db975, "@FX_BSMK02.TGA" }, { 0x9c3cd534, "FX_B_GLOW.TGA" }, { 0x9c452d49, "PLUTO.D.PANEL1.TGA" }, { 0x9c543d07, "PLUTO.T.MOON.TGA" }, { 0x9c7fd264, "PLUTO.TECH_TTTT2.TGA" }, { 0x9c8077d4, "CREPOS_H.TGA" }, { 0x9c832965, "ICE.DDDD3.TGA" }, { 0x9c836f50, "ICE.TB_PANEL0.TGA" }, { 0x9ca9737e, "EUROPA.RRRR5.TGA" }, { 0x9ceb3d73, "TEMPERATE.RD_D_CROS.TGA" }, { 0x9ced2830, "DESERT.SSSS2.TGA" }, { 0x9cf70a81, "PLUTO.RRRR4.TGA" }, { 0x9cfb910f, "FX_ESP06.TGA" }, { 0x9d28f653, "PLUTO.GSSS2.TGA" }, { 0x9d3a9a0d, "EUROPA.T.PANEL2.TGA" }, { 0x9d3d85c4, "@FX_ELE02.TGA" }, { 0x9d54aa8a, "MOON.RD_P_TEE.TGA" }, { 0x9d5f0163, "ICE.DEV_LANDG.TGA" }, { 0x9d63a5b5, "SNOWLOGO.TGA" }, { 0x9d68523c, "VENUS.SSDD.TGA" }, { 0x9d88aeeb, "ICE.FRRR.TGA" }, { 0x9d8f77ff, "EUROPA.RGGG2.TGA" }, { 0x9da13faa, "FX_ELE10.TGA" }, { 0x9df6f193, "MOON.GGDD2.TGA" }, { 0x9e21964b, "CUR_ROTATE.TGA" }, { 0x9e2ada99, "DESERT.RD_DIRT_CRNR.TGA" }, { 0x9e310a7b, "IMPHTMAP.TGA" }, { 0x9e78aa7a, "PLUTO.RRRR3.TGA" }, { 0x9e800617, "WP_TERRN.TGA" }, { 0x9eb2a5f0, "MOON.RD_D_END.TGA" }, { 0x9f0b9e7c, "@FX_GAS08.TGA" }, { 0x9f138cd7, "TEMPERATE.T.MOON0.TGA" }, { 0x9f3cc984, "@FX_GAS13.TGA" }, { 0x9f4f3b51, "MERCURY.SSSS6.TGA" }, { 0x9f64d2a3, "TITAN.CCCC2.TGA" }, { 0x9f7a3ae5, "ICE.RRFF.TGA" }, { 0x9fba581a, "DESERT.GGGG4.TGA" }, { 0x9fcee878, "MOON.SDDD2.TGA" }, { 0x9fd47322, "FX_GAS09.TGA" }, { 0x9fdde210, "FX_DUSTBR11.TGA" }, { 0x9fe868dd, "EUROPA.GGGG.TGA" }, { 0xa048843e, "KN_POD2.TGA" }, { 0xa058af42, "FX_XGLASS.TGA" }, { 0xa06a9f88, "HPIPE2L.TGA" }, { 0xa071e791, "HUREACTORS1_S.TGA" }, { 0xa0b1aa45, "HUSENSORS2_SD.TGA" }, { 0xa0b7c853, "PLUTO.GGGG.TGA" }, { 0xa0bbe42b, "EUROPA.FRGG2.TGA" }, { 0xa0bbeb45, "HBRICK2M.TGA" }, { 0xa0bef348, "HUSENSORS1_SD.TGA" }, { 0xa0c2b40a, "DIS_SD.TGA" }, { 0xa0cc59e0, "FX_LXP07.TGA" }, { 0xa0ceb310, "CSLAT2.TGA" }, { 0xa0cf38d3, "FX_DUSTBL04.TGA" }, { 0xa0ec03e7, "EUROPA.FRGG2.TGA" }, { 0xa0f14e72, "TITAN.PAVED_SCORCH.TGA" }, { 0xa0f29b5a, "MOON.PAVE_SCORCH.TGA" }, { 0xa0fd07b8, "MARS.GGGG6.TGA" }, { 0xa11e3199, "FX_DUST13.TGA" }, { 0xa1648136, "ICON_NAV_RED.TGA" }, { 0xa16732c0, "DESERT.GGGG4.TGA" }, { 0xa16fa3a9, "SHIELDMODULATER_S.TGA" }, { 0xa18ce87a, "20MINEPACK_S.TGA" }, { 0xa1bb7857, "MOON.GRRR.TGA" }, { 0xa1ccc68a, "XMARS_DAMAGE.TGA" }, { 0xa1d0740d, "FX_EMP01.TGA" }, { 0xa1e22825, "HTITANLOGO.TGA" }, { 0xa1e4e101, "PREV_DM_MOONSTRIKE.TGA" }, { 0xa1e8dfab, "ICE.RRFF.TGA" }, { 0xa2081647, "PLUTO.MMRR.TGA" }, { 0xa216574a, "SCANNEX_ALLI_SML.TGA" }, { 0xa21f1e31, "ADDBLOCK.TGA" }, { 0xa2427c4e, "HUREACTORL1_S.TGA" }, { 0xa273dcf7, "FX_CHN05.TGA" }, { 0xa277d0bd, "MARS.PAVED_CRATER.TGA" }, { 0xa27f45d4, "SAVE.TGA" }, { 0xa2ca89e7, "PASSLOCK.TGA" }, { 0xa2cfa31e, "FX_FLA15.TGA" }, { 0xa2d004e3, "FX_DUSTDO12.TGA" }, { 0xa2d8b6e9, "FX_DUSTGR10.TGA" }, { 0xa2ef8fa0, "HKANGI.TGA" }, { 0xa2f1e11e, "MERCURY.D.PANEL3.TGA" }, { 0xa2fa69e9, "FX_SPK08.TGA" }, { 0xa30c8dd8, "CY_ENGINE3_S.TGA" }, { 0xa3216741, "KN_POD1.TGA" }, { 0xa3268951, "FX_BLS02.TGA" }, { 0xa32b86ff, "@FX_HLAS.TGA" }, { 0xa35e5392, "EUROPA.GGGG5.TGA" }, { 0xa35e7f91, "VENUS.SDGG2.TGA" }, { 0xa386d6f8, "XHERCMOVIE13.TGA" }, { 0xa4088ed0, "DREA_RB.TGA" }, { 0xa41ea4b0, "TEMPERATE.PAVE_LANDG.TGA" }, { 0xa44ce592, "ICE.RRRR4.TGA" }, { 0xa492f973, "ICE.D.PANEL0.TGA" }, { 0xa49feb74, "FX_DUSTGR08.TGA" }, { 0xa4c7fd27, "TITAN.CCCC.TGA" }, { 0xa507fc89, "EMP_S.TGA" }, { 0xa5654e48, "MOON.SDDD.TGA" }, { 0xa56dc7b5, "HMOONDOOR.TGA" }, { 0xa5abdfa8, "@FX_BSMK01.TGA" }, { 0xa5d6f70e, "@FX_SHD06.TGA" }, { 0xa5d9c7c2, "CY_FLYENGINEL_S.TGA" }, { 0xa6149038, "EXEC_PL.TGA" }, { 0xa640593a, "FX_DUSTWH02.TGA" }, { 0xa6506bca, "MOON.RGGG.TGA" }, { 0xa656d444, "EUROPA.N.PANEL1.TGA" }, { 0xa664e8c9, "TITAN.HHOO.TGA" }, { 0xa6736347, "@FX_SMK07.TGA" }, { 0xa68ac06d, "DESERT.DDGG.TGA" }, { 0xa69a99cd, "ICE.RRRR.TGA" }, { 0xa69e6547, "@FX_EX06.TGA" }, { 0xa6adc341, "HUSENSOR4_S.TGA" }, { 0xa6f1478c, "@FX_NANNO.TGA" }, { 0xa6f4a886, "HSLAT3E.TGA" }, { 0xa6fab17f, "@FX_FL101.TGA" }, { 0xa70ee4f3, "TEMPERATE.DDGG2.TGA" }, { 0xa71af144, "HBRICK3M.TGA" }, { 0xa7323b64, "CREPOS.TGA" }, { 0xa74df796, "FX_EB01.TGA" }, { 0xa7819f1e, "VENUS.GGGG2.TGA" }, { 0xa793ba74, "SCANNEX_CS_SML.TGA" }, { 0xa7a989e7, "@FX_BSMK09.TGA" }, { 0xa7e05ec0, "@FX_EX12.TGA" }, { 0xa80ab4a5, "XHERCMOVIE16.TGA" }, { 0xa80b35cb, "MERCURY.RD_D_CROS.TGA" }, { 0xa817dcd6, "@FX_LXP01.TGA" }, { 0xa834cb73, "UNDO.TGA" }, { 0xa865cf3b, "@FX_DROP03.TGA" }, { 0xa8669052, "PREV_DM_CITY_ON_THE_EDGE.TGA" }, { 0xa8699f67, "FX_LXP01.TGA" }, { 0xa8796da2, "VENUS.DDDD6.TGA" }, { 0xa885ca91, "TITAN.CCCC2.TGA" }, { 0xa8deec1c, "VENUS.DSSS.TGA" }, { 0xa920578c, "MOON.DDDD5.TGA" }, { 0xa9363238, "TITAN.NB_PANEL1.TGA" }, { 0xa9624074, "VENUS.PAVED_PPGG.TGA" }, { 0xa96d2a4e, "DESERT.DDDD3.TGA" }, { 0xa9b1ae0f, "HDESERTROOF.TGA" }, { 0xa9b23aa3, "FX_DUSTYL11.TGA" }, { 0xa9b3eb9e, "TITAN.HGGG.TGA" }, { 0xa9c00517, "ARMOR4_S.TGA" }, { 0xa9c38e5e, "CYSENSORL1_SD.TGA" }, { 0xa9df0d67, "PLUTO.TECH_STTT.TGA" }, { 0xa9eb471d, "EUROPA.CFFC3.TGA" }, { 0xa9ee75aa, "HUTHERMSENSOR_SD.TGA" }, { 0xaa19c8d6, "ICON_DYN.TGA" }, { 0xaa2eccf1, "MOON.DDDD5.TGA" }, { 0xaa3db71c, "TITAN.OOOO.TGA" }, { 0xaa472905, "PLUTO.PAVED_SCORCH.TGA" }, { 0xaa6cd0c7, "TEMPERATE.ROCK.TGA" }, { 0xaa8e0c53, "FX_DUSTWH07.TGA" }, { 0xaa923c73, "EUROPA.GRRR.TGA" }, { 0xaaa60281, "CY_OMNI.TGA" }, { 0xaab80a58, "DESERT.DGDD.TGA" }, { 0xab02a456, "@FX_FL104.TGA" }, { 0xab5297ba, "FX_BSMK13.TGA" }, { 0xab6f561f, "FX_LXP10.TGA" }, { 0xaba9bdda, "NO_ENGINE_S.TGA" }, { 0xabd17022, "MARS.LGGG2.TGA" }, { 0xabf25bbc, "DESERT.DDDD.TGA" }, { 0xac0f073e, "FX_DUSTGR13.TGA" }, { 0xac2a0a0d, "HU_COMPUTERL_SD.TGA" }, { 0xac2bdb98, "TEMPERATE.GRRR.TGA" }, { 0xac3d0406, "FX_DUSTDB14.TGA" }, { 0xac4f96d0, "TITAN.OOOO3.TGA" }, { 0xac6af6f0, "XRUSTTRIM.TGA" }, { 0xac76ee0a, "MOON.GGDD.TGA" }, { 0xac807d46, "@FX_BSMK03.TGA" }, { 0xac8e7054, "TEMPERATE.NB_PANEL3.TGA" }, { 0xaca2dc5e, "HSLAT3T.TGA" }, { 0xaca5c96d, "MOON.DGGG.TGA" }, { 0xaca991ff, "@FX_LENSFLARE_0.TGA" }, { 0xacfc838f, "MOON.PAVE_SCORCH.TGA" }, { 0xad35c6bb, "TEMPERATE.GGRR2.TGA" }, { 0xad5d2768, "APOC_TR.TGA" }, { 0xad700a7a, "TEMPERATE.RRRR2.TGA" }, { 0xadb4e113, "EUROPA.T.PANEL5.TGA" }, { 0xadce6e51, "HU_FLYENGINEL_S.TGA" }, { 0xade36616, "MARS.GGGG.TGA" }, { 0xadedf1f2, "VENUS.SSDD2.TGA" }, { 0xae2dc0af, "EUROPA.DDDD5.TGA" }, { 0xae53ecfd, "FX_DROP07.TGA" }, { 0xae57bf5a, "MOON.TRANS_PPDD.TGA" }, { 0xae82aa7c, "FX_DUSTBR08.TGA" }, { 0xaeafc341, "TITAN.LANDING_GGGG.TGA" }, { 0xaec06db2, "TR_POD2.TGA" }, { 0xaec3a986, "@FX_RAL03.TGA" }, { 0xaec7949f, "FX_DUSTDB05.TGA" }, { 0xaec94606, "@FX_BLK02.TGA" }, { 0xaeca6ae7, "EUROPA.FGGG2.TGA" }, { 0xaecfe71a, "EUROPA.GGGG2.TGA" }, { 0xaedac61a, "FX_DUSTGR04.TGA" }, { 0xaede3cb8, "MARS.LLLL2.TGA" }, { 0xaef03ad9, "VENUS.PAVED_GPPP.TGA" }, { 0xaef1904e, "VENUS.PAVED_PGGG.TGA" }, { 0xaf39384b, "@FX_EX09.TGA" }, { 0xaf3ff588, "MOON.RRRR.TGA" }, { 0xaf49c394, "TITAN.HOOO2.TGA" }, { 0xaf4aeb8b, "MOON.RRGG2.TGA" }, { 0xaf5755b5, "MARS.DB_PANEL1.TGA" }, { 0xafc8b951, "DESERT.T.PANEL5.TGA" }, { 0xafcbd088, "TRANSMIT.TGA" }, { 0xafd6b852, "EUROPA.DDGG2.TGA" }, { 0xafda4dd7, "CUR_CENTERING.TGA" }, { 0xafed182e, "TEMPERATE.RGGG2.TGA" }, { 0xb021356c, "TITAN.GGGG.TGA" }, { 0xb02d674f, "@FX_GAS12.TGA" }, { 0xb04bddc9, "HMOVIE.TGA" }, { 0xb0765c1c, "FX_BSMK09.TGA" }, { 0xb09eae79, "TITAN.PAVED_PPGG.TGA" }, { 0xb0bc5670, "@FX_ESP04.TGA" }, { 0xb0dde66b, "FX_SPK12.TGA" }, { 0xb0eb3526, "@FX_SHK06.TGA" }, { 0xb1023356, "MOON.RD_P_CRNR.TGA" }, { 0xb16d16b0, "TITAN.ROAD_END.TGA" }, { 0xb172ae3f, "EUROPA.FFFF2.TGA" }, { 0xb190effb, "ICON_NAV_PRPL.TGA" }, { 0xb198010d, "FX_EB04.TGA" }, { 0xb1d04f97, "VENUS.SSSS5.TGA" }, { 0xb1d5b81b, "TITAN.NB_PANEL2.TGA" }, { 0xb1f5f204, "TEMPERATE.TRANS_PDDD.TGA" }, { 0xb2047cc0, "MARS.RD_DIRT_END.TGA" }, { 0xb22d922d, "BIKE_RB.TGA" }, { 0xb233ac37, "BANS_TR.TGA" }, { 0xb26079ae, "@FX_EMP03.TGA" }, { 0xb2838776, "FX_DIS01.TGA" }, { 0xb2840f2a, "@FX_SMK16.TGA" }, { 0xb28a0c96, "CIRC_N.TGA" }, { 0xb2c71c54, "HVENUSLOGO.TGA" }, { 0xb2d6b7ad, "XCRYODOOR.TGA" }, { 0xb34a7c58, "EUROPA.DDDD2.TGA" }, { 0xb354acad, "FX_DUSTDY01.TGA" }, { 0xb357bee0, "FX_FLA12.TGA" }, { 0xb38197aa, "HTROOPPANEL.TGA" }, { 0xb3ad293f, "TEAM_1.TGA" }, { 0xb3af384c, "PLUTO.SSSS3.TGA" }, { 0xb3ded26f, "ICE.DDDD2.TGA" }, { 0xb3e47308, "ATC_SD.TGA" }, { 0xb3fe4d55, "TEMPERATE.RRRR4.TGA" }, { 0xb41583ed, "GORG_TR.TGA" }, { 0xb419b038, "FX_ELC02.TGA" }, { 0xb41ac3e2, "EUROPA.RD_P_CROS.TGA" }, { 0xb41baf66, "FX_GAS16.TGA" }, { 0xb43e2b63, "FX_SHD03.TGA" }, { 0xb455811e, "MISSIONOPEN.TGA" }, { 0xb469b2cc, "EMPTY.TGA" }, { 0xb479dd0f, "PLUTO.RRRR4.TGA" }, { 0xb48766f5, "XHEAL_LITE.TGA" }, { 0xb489cc6f, "MOON.PAVE_PLAIN2.TGA" }, { 0xb4c7e9b4, "MERCURY.TRANS_DPPP.TGA" }, { 0xb4e63ae1, "FX_SMK02.TGA" }, { 0xb4e7f891, "FX_GFLARE.TGA" }, { 0xb4e8f174, "PLUTO.RD_D_CRNR.TGA" }, { 0xb4f1652f, "HUSENSOR4_SD.TGA" }, { 0xb5032ad7, "VENUS.DGGG2.TGA" }, { 0xb5287d12, "PLUTO.MMMM3.TGA" }, { 0xb52e1982, "VENUS.SSSS8.TGA" }, { 0xb53db1f1, "DESERT.GGGG5.TGA" }, { 0xb55a501d, "HCONSTRUCTION.TGA" }, { 0xb55da2f3, "FX_DIS03.TGA" }, { 0xb55f353a, "@FX_GAS16.TGA" }, { 0xb56c422b, "@FX_BLAST2.TGA" }, { 0xb57e28a4, "MERCURY.TRANS_PPDD.TGA" }, { 0xb5a12ebe, "CYENGINEM1_S.TGA" }, { 0xb5a91ddb, "CYREACTORM1_S.TGA" }, { 0xb5ce4545, "FX_MUZE.TGA" }, { 0xb5f06c5e, "SHIELDS.TGA" }, { 0xb5fbca45, "DELBLOCK.TGA" }, { 0xb604c1f5, "MOON.D.PANEL3.TGA" }, { 0xb6068e4a, "VENUS.SDGG2.TGA" }, { 0xb628686c, "TITAN.CCGG2.TGA" }, { 0xb63515a2, "FX_DROP00.TGA" }, { 0xb658746a, "FX_DUSTLB05.TGA" }, { 0xb663d5a0, "CUR_WAYPOINT.TGA" }, { 0xb66ad9cd, "HU_ENGINE3_S.TGA" }, { 0xb66dae36, "10MINEPACK_S.TGA" }, { 0xb6d9680c, "MISSION.TGA" }, { 0xb6db123b, "MOON.GGGG2.TGA" }, { 0xb6e4212b, "HUENGINEM3_SD.TGA" }, { 0xb6eb29eb, "TITAN.PAVED_GGGG.TGA" }, { 0xb6ec71a7, "PLUTO.SSSS4.TGA" }, { 0xb6ee876a, "MARS.T.MOON1.TGA" }, { 0xb6f4a39b, "PINBLOCK.TGA" }, { 0xb7215700, "@FX_DIS06.TGA" }, { 0xb73b4dd3, "@FX_SMK17.TGA" }, { 0xb74ad979, "PLUTO.SGGS.TGA" }, { 0xb753b200, "FX_BLK01.TGA" }, { 0xb764eebd, "@FX_EX10.TGA" }, { 0xb77e0307, "@FX_RAL10.TGA" }, { 0xb780f1d3, "TB_BOTTOMALIGN.TGA" }, { 0xb789ffcd, "PLUTO.PAVED_PTTT.TGA" }, { 0xb7a87b36, "VENUS.DSSS2.TGA" }, { 0xb7b13365, "XBOX.TGA" }, { 0xb7b8c7fe, "EUROPA.CFFF.TGA" }, { 0xb7cbdb2c, "DESERT.TB_PANEL2.TGA" }, { 0xb7d49d51, "MARS.D.PANEL3.TGA" }, { 0xb7dac181, "TEMPERATE.PAVEDSCORCH.TGA" }, { 0xb7e34122, "FX_GAS14.TGA" }, { 0xb7e8d0e8, "TB_CENTERJUSTIFY.TGA" }, { 0xb7f052a0, "MSSHADOW.TGA" }, { 0xb7f39e4e, "MERCURY.DDLL2.TGA" }, { 0xb7f51f44, "MARS.GGGG2.TGA" }, { 0xb80a2741, "FX_PR104.TGA" }, { 0xb833b195, "TR_NIKE.TGA" }, { 0xb84ac34e, "MARS.SGGG.TGA" }, { 0xb857d730, "FX_SMK13.TGA" }, { 0xb8a24ecb, "VENUS.NB_MOON0.TGA" }, { 0xb8cb6fce, "MOON.GGDD.TGA" }, { 0xb8fd88fb, "@FX_ELE03.TGA" }, { 0xb9060e89, "PLUTO.GRRG.TGA" }, { 0xb911ca2b, "FX_SHK02.TGA" }, { 0xb924abb0, "PREV_DM_MERCURY_RISING.TGA" }, { 0xb936a8b7, "MOON.TRANS_DPPP.TGA" }, { 0xb94545d8, "FX_GAS15.TGA" }, { 0xb96a5ad6, "FX_LXP15.TGA" }, { 0xb9861ea1, "12MISSILEPACK_S.TGA" }, { 0xb997a165, "VENUS.SSSS6.TGA" }, { 0xb9bb235c, "BC_SD.TGA" }, { 0xb9c4692a, "RAD_SD.TGA" }, { 0xb9f68765, "FX_DUSTYL06.TGA" }, { 0xb9fbeb42, "FX_DUST14.TGA" }, { 0xba0275b5, "@FX_BSMK10.TGA" }, { 0xba090b52, "VENUS.PAVED_SCORCH.TGA" }, { 0xba2970c6, "@FX_RAD.TGA" }, { 0xba2b13f8, "@FX_BLS03.TGA" }, { 0xba30b70a, "XVENT3.TGA" }, { 0xba44d4d3, "ARMOR1_SD.TGA" }, { 0xba68d4a2, "TEMPERATE.RGGG2.TGA" }, { 0xba6cd754, "XHERCMOVIE15.TGA" }, { 0xba88d02f, "12MISSILEPACK_SD.TGA" }, { 0xba900877, "CTECH3.TGA" }, { 0xba9191a7, "@FX_EMP04.TGA" }, { 0xba935cb2, "TITAN.PAVED_GGGG.TGA" }, { 0xbaa72a60, "FX_DUSTWH03.TGA" }, { 0xbac2bb29, "ICE.BLUESCREEN.TGA" }, { 0xbb24892e, "VIP_S.TGA" }, { 0xbb2ac29b, "TB_TOPALIGN.TGA" }, { 0xbb319b7b, "CYECM1_S.TGA" }, { 0xbb3762e9, "MYRM_TR.TGA" }, { 0xbb469478, "MOON.RRRR2.TGA" }, { 0xbb6b3399, "CYREACTORS1_SD.TGA" }, { 0xbb705fe5, "VENUS.RD_TRANS.TGA" }, { 0xbb74ecf3, "FX_DUSTWH12.TGA" }, { 0xbb956de3, "FX_DUSTYL04.TGA" }, { 0xbb9ade22, "@FX_LXP08.TGA" }, { 0xbbc9bd67, "MOON.DDSS.TGA" }, { 0xbbc9d706, "@FX_ELC05.TGA" }, { 0xbbcd6003, "XGRATE2.TGA" }, { 0xbbe9343f, "MARS.SSSS5.TGA" }, { 0xbbefcc7e, "@FX_EX13.TGA" }, { 0xbbf74b37, "ICE.RD_BEGIN.TGA" }, { 0xbc2ab0e3, "XLIGHT.TGA" }, { 0xbc93a40c, "MARS.RD_PAVE_CROS.TGA" }, { 0xbcd93eff, "TB_KILLTB.TGA" }, { 0xbcfe7d03, "PREV_CTF_CITY_ON_THE_EDGE.TGA" }, { 0xbcff20c8, "DESERT.N.MOON.TGA" }, { 0xbd26a7c9, "MOON.SDDD2.TGA" }, { 0xbd37092e, "@FX_BSMK05.TGA" }, { 0xbd85d2b3, "ICE.FFFF3.TGA" }, { 0xbd86ddbd, "PLUTO.RMMR.TGA" }, { 0xbdad332b, "FX_SPLASH.TGA" }, { 0xbdbbd919, "TITAN.CCCC4.TGA" }, { 0xbdc98e66, "MERCURY.SSDD2.TGA" }, { 0xbdf8bb22, "VENUS.DDDD4.TGA" }, { 0xbe025918, "PLUTO.PAVED_PPPP2.TGA" }, { 0xbe28a3c5, "VENUS.SGDD2.TGA" }, { 0xbe37f307, "PREV_DM_IMPACT.TGA" }, { 0xbe65af26, "DESERT.T.PANEL4.TGA" }, { 0xbe7c3772, "HBRICKM.TGA" }, { 0xbe91a325, "TITAN.HHHH.TGA" }, { 0xbe952e50, "PLUTO.RGGG2.TGA" }, { 0xbea1a77e, "HMOONFOIL.TGA" }, { 0xbebcbaee, "EUROPA.FFFF.TGA" }, { 0xbf0f2751, "DESERT.RD_PAVE_CROS.TGA" }, { 0xbf1a944f, "MARS.SSSS.TGA" }, { 0xbf1b6268, "DESERT.RD_DIRT_CROS.TGA" }, { 0xbf1f4a1a, "CTECH2.TGA" }, { 0xbf5addee, "PBW_SD.TGA" }, { 0xbf7199ca, "@FX_EXS05.TGA" }, { 0xbf80fa44, "VENUS.DDDD3.TGA" }, { 0xbf8a5228, "CYENGINEL2_SD.TGA" }, { 0xbf9383ab, "MARS.TRANS_DPPP.TGA" }, { 0xbf950a02, "FX_DUST10.TGA" }, { 0xbf99b03d, "MERCURY.DDLL.TGA" }, { 0xbfb03b47, "@FX_BLK01.TGA" }, { 0xbfb305d3, "@FX_SMK06.TGA" }, { 0xbfb572af, "CYENGINEM2_SD.TGA" }, { 0xbfc8cd19, "EUROPA.FFFF5.TGA" }, { 0xbfc90baf, "VENUS.SDDD.TGA" }, { 0xbff88c33, "FX_BLS03.TGA" }, { 0xc017db7e, "@FX_BSMK06.TGA" }, { 0xc01d59e2, "XHERCMOVIE4.TGA" }, { 0xc04b21ea, "HMARSWATERTTOP.TGA" }, { 0xc05be98f, "FX_CHN06.TGA" }, { 0xc078e31f, "CVENT2.TGA" }, { 0xc0817287, "DAM_TAR_LOW.TGA" }, { 0xc0924210, "HUD_CIRCLE_O.TGA" }, { 0xc0bfdb9f, "HMAR08.TGA" }, { 0xc0ccca6a, "@FX_SMK04.TGA" }, { 0xc0e692bb, "MERCURY.DDDD6.TGA" }, { 0xc0f3dbf5, "FX_DUSTDO10.TGA" }, { 0xc0f80098, "THERMALDIFFUSER_SD.TGA" }, { 0xc10aae81, "HLAS_SD.TGA" }, { 0xc1188e78, "FX_DUSTLB12.TGA" }, { 0xc11bdc18, "INCHEIGT.TGA" }, { 0xc11fe3d6, "EUROPA.FFGG2.TGA" }, { 0xc127c202, "@FX_SMK10.TGA" }, { 0xc1479942, "HUSHIELDGENM2_SD.TGA" }, { 0xc14ede3f, "FX_DUSTBL14.TGA" }, { 0xc154ca4c, "CIN_PLUTO.TGA" }, { 0xc174e194, "HVENTPLATE.TGA" }, { 0xc183c427, "FX_DUSTWH14.TGA" }, { 0xc1858c65, "TEMPERATE.RD_TRANS.TGA" }, { 0xc187eb8f, "FX_SPK10.TGA" }, { 0xc1919e99, "MOON.RRGG2.TGA" }, { 0xc1d7534e, "SGUN_SD.TGA" }, { 0xc1dd1df5, "DESERT.SSDD.TGA" }, { 0xc25b4b1b, "PLUTO.GRRG2.TGA" }, { 0xc2698d4a, "FX_DUST09.TGA" }, { 0xc2731b67, "TITAN.HOOO.TGA" }, { 0xc2763b92, "SCANNEX_NAVY_LG.TGA" }, { 0xc281321d, "FX_DUSTGR01.TGA" }, { 0xc282fdaf, "PLUTO.SGGS2.TGA" }, { 0xc286fde3, "MARS.PAVED_SCORCH.TGA" }, { 0xc2b9d951, "PLUTO.SSSS2.TGA" }, { 0xc2beef84, "DESERT.GGGG.TGA" }, { 0xc2dc0b8e, "MARS.RD_PAVE_CRNR.TGA" }, { 0xc2dd3cb7, "FX_EXS03.TGA" }, { 0xc2e51f7b, "MERCURY.DDDD2.TGA" }, { 0xc306cc0f, "VENUS.GSSS2.TGA" }, { 0xc31488d8, "HDESERTMOTIF.TGA" }, { 0xc3240f04, "@FX_PBW.TGA" }, { 0xc3563262, "MERCURY.SSSS5.TGA" }, { 0xc36a4778, "INVERT.TGA" }, { 0xc39a6ff9, "HAND.TGA" }, { 0xc3b77123, "ICE.RRFF2.TGA" }, { 0xc3ba9d2e, "@FX_GAS07.TGA" }, { 0xc3bd87e1, "@FX_GAS03.TGA" }, { 0xc3f590b4, "@FX_EB02.TGA" }, { 0xc3f68814, "VENUS.SSDD2.TGA" }, { 0xc4198a96, "MERCURY.RD_D_STRT.TGA" }, { 0xc42f5a37, "CYSHIELDGENM2_SD.TGA" }, { 0xc48be3f9, "MOON.GRRR.TGA" }, { 0xc48d212b, "VENUS.GDDD2.TGA" }, { 0xc4943547, "@FX_FL04.TGA" }, { 0xc4972c49, "TEMPERATE.RRRR2.TGA" }, { 0xc4bf862d, "FX_EXS07.TGA" }, { 0xc4d32baa, "TITAN.CGGG.TGA" }, { 0xc4db5066, "XWINDOW5.TGA" }, { 0xc4e4d573, "SCANNEX_PROV_LG.TGA" }, { 0xc4f1a9d9, "MARS.N.MOON.TGA" }, { 0xc52bf0d0, "TEMPERATE.PAVE_PLAIN2.TGA" }, { 0xc532b2df, "AMMO.TGA" }, { 0xc56d1f39, "EUROPA.DDDD2.TGA" }, { 0xc57f3e8c, "EUROPA.D.PANEL3.TGA" }, { 0xc5942aa8, "VENUS.GGGG6.TGA" }, { 0xc5e02645, "CVENT1.TGA" }, { 0xc5feb27f, "DESERT.SDDD.TGA" }, { 0xc5ff0d92, "FX_DUSTBR13.TGA" }, { 0xc63f66bf, "FX_RAL08.TGA" }, { 0xc65c9439, "ICE.NB_PANEL0.TGA" }, { 0xc676ebdd, "ICE.RD_P_CROS.TGA" }, { 0xc69c14fb, "MARS.PAVED_LANDG.TGA" }, { 0xc6abda71, "CY_FLYENGINES_SD.TGA" }, { 0xc6c91a62, "VENUS.DSSS.TGA" }, { 0xc6d3bff5, "FX_DUSTLG02.TGA" }, { 0xc6eac45d, "CYENGINEL1_S.TGA" }, { 0xc6ead1b2, "FX_DUSTLB07.TGA" }, { 0xc71876b6, "FX_SMK06.TGA" }, { 0xc74738db, "@FX_ELE07.TGA" }, { 0xc79fe09c, "MERCURY.RD_D_STRT.TGA" }, { 0xc7b9a62b, "FX_DUSTGR05.TGA" }, { 0xc7be3bf3, "@FX_BSMK08.TGA" }, { 0xc7d1ed1c, "PLUTO.RMMM.TGA" }, { 0xc7e776fe, "FX_DUSTBL11.TGA" }, { 0xc7ef7740, "EUROPA.GRRR2.TGA" }, { 0xc7efdc3d, "XHERCMOVIE10.TGA" }, { 0xc8037e7b, "MARS.D.PANEL5.TGA" }, { 0xc80e3d10, "CYSHIELDGEN3_S.TGA" }, { 0xc82e1c33, "@FX_EXS01.TGA" }, { 0xc838a614, "FX_SPK01.TGA" }, { 0xc8513f66, "15MINEPACK_SD.TGA" }, { 0xc8518071, "XGRUNGE1.TGA" }, { 0xc8696246, "FX_DUSTDY03.TGA" }, { 0xc8a8c87d, "FX_ESP01.TGA" }, { 0xc8b7380e, "PREV_CTF_WINTER_WASTELAND.TGA" }, { 0xc8b81c4e, "@FX_BLS01.TGA" }, { 0xc8f35574, "ARMOR1_S.TGA" }, { 0xc8fa13c1, "ICE.T.PANEL1.TGA" }, { 0xc8fa7367, "CMDMINE_S.TGA" }, { 0xc900df64, "DESERT.DSDD.TGA" }, { 0xc914e5ea, "MERCURY.DDDD4.TGA" }, { 0xc91b4ef1, "MERCURY.DLLL2.TGA" }, { 0xc94ad016, "DESERT.DSSS.TGA" }, { 0xc94d8cf7, "ICE.ROCK.TGA" }, { 0xc9892167, "@FX_BLS02.TGA" }, { 0xc9a24f18, "ICE.D.PANEL3.TGA" }, { 0xc9a425cf, "MYRM_KN.TGA" }, { 0xc9c00c68, "SCANNEX_POLICE_SML.TGA" }, { 0xc9f4140d, "CSLAT6.TGA" }, { 0xc9fa0741, "MOON.SSSS.TGA" }, { 0xca11799f, "TEMPERATE.RD_D_STRT.TGA" }, { 0xca1f54ff, "CIN_CRYO4.TGA" }, { 0xca3a1565, "TITAN.TB_PANEL2.TGA" }, { 0xca67eaca, "VENUS.PAVED_PPGG.TGA" }, { 0xca78322f, "@FX_ELE01.TGA" }, { 0xca7ddd9f, "DESERT.T.PANEL0.TGA" }, { 0xcac4eecb, "EUROPA.PAVEDCRATER.TGA" }, { 0xcacdf03c, "HU_COMPUTERS_SD.TGA" }, { 0xcad00f95, "FX_DUSTDB13.TGA" }, { 0xcb077bea, "PRED_HA.TGA" }, { 0xcb0f3cf7, "DESERT.PAVED_TRANS_SPPP.TGA" }, { 0xcb38da6d, "HUENGINEL2_S.TGA" }, { 0xcb6bfa8f, "FX_SHOCK.TGA" }, { 0xcb6d0845, "DAM_SELF.TGA" }, { 0xcb70b1c3, "TR_UTIL.TGA" }, { 0xcb764f7e, "CY_COMPUTERL_SD.TGA" }, { 0xcb818bf8, "FX_LENSFLARE_4.TGA" }, { 0xcba6144f, "ICE.RD_P_CRNR.TGA" }, { 0xcbb81485, "DESERT.D.PANEL1.TGA" }, { 0xcbd1cf65, "EUROPA.RRGG.TGA" }, { 0xcbfbd1be, "CYREACTORM2_SD.TGA" }, { 0xcc1ade45, "MARS.N.PANEL4.TGA" }, { 0xcc1ebc46, "FX_BSMK11.TGA" }, { 0xcc2d4b24, "FX_LENSFLARE_5.TGA" }, { 0xcc312035, "MERCURY.D.PANEL1.TGA" }, { 0xcc50d9c8, "MARS.SGGG2.TGA" }, { 0xcc5edf4d, "MARS.GGGG4.TGA" }, { 0xcc841fcc, "XVENUSRADAR.TGA" }, { 0xcc8d5a72, "CTECH1.TGA" }, { 0xccd604f1, "VENUS.GGDD2.TGA" }, { 0xcd2169fe, "TALO_TR.TGA" }, { 0xcd48c8ec, "MOON.SSSS3.TGA" }, { 0xcd505c84, "@FX_GAS15.TGA" }, { 0xcd781eb8, "CY_MISC_FINS.TGA" }, { 0xcd9abfdc, "HMOONRADAR.TGA" }, { 0xcdd6f90e, "FX_DUSTBL09.TGA" }, { 0xcdf588e1, "@FX_FLARE1.TGA" }, { 0xce03d9db, "EUROPA.RRRR4.TGA" }, { 0xce25cb5f, "FX_SPK05.TGA" }, { 0xce5f7379, "CYREACTORS1_S.TGA" }, { 0xce6729fa, "EUROPA.RRGG.TGA" }, { 0xce78ca7f, "HOST.TGA" }, { 0xce81d4da, "DESERT.NB_PANEL1.TGA" }, { 0xce9ae761, "SWRM_SD.TGA" }, { 0xce9e2881, "FX_DUSTDB02.TGA" }, { 0xceb0d28a, "HKANGI3.TGA" }, { 0xceb540cc, "CHKHEIGT.TGA" }, { 0xceb54577, "@FX_DROP02.TGA" }, { 0xcef31208, "ARMOR2_S.TGA" }, { 0xcf001132, "MARS.GSSS2.TGA" }, { 0xcf0c0748, "DESERT.SSSS.TGA" }, { 0xcf0deee0, "SCANNEX_INQU_SML.TGA" }, { 0xcf10daa9, "HTITANDOORLOGO.TGA" }, { 0xcf2e1993, "PREV_DM_BLOODY_BRUNCH.TGA" }, { 0xcf5c5997, "MOON.DGGG2.TGA" }, { 0xcf727dad, "@FX_EX08.TGA" }, { 0xcf9401f1, "FX_EB03.TGA" }, { 0xcfbe4aeb, "EUROPA.TRANS_DPPP.TGA" }, { 0xcfe0d136, "EUROPA.RRRR.TGA" }, { 0xcff304fc, "ICE.D.PANEL2.TGA" }, { 0xd003bb0b, "ICE.RFFF.TGA" }, { 0xd0156629, "HU_FLYENGINEL_SD.TGA" }, { 0xd0261921, "EUROPA.N.PANEL3.TGA" }, { 0xd02d1496, "MARS.LLLL.TGA" }, { 0xd0356793, "VENUS.SDDD.TGA" }, { 0xd04dd4db, "@FX_LENSFLARE_4.TGA" }, { 0xd051f413, "MOON.DGGG.TGA" }, { 0xd0735ac9, "@FX_FL03.TGA" }, { 0xd079929f, "VENUS.PAVED_GGGG.TGA" }, { 0xd0b03936, "FX_RAL05.TGA" }, { 0xd0ce25db, "DESERT.GGGG6.TGA" }, { 0xd0e68303, "MERCURY.SSSS6.TGA" }, { 0xd108d908, "CYSENSORL2_SD.TGA" }, { 0xd10de324, "DROPPTOPEN.TGA" }, { 0xd11032f8, "ICE.DDFF.TGA" }, { 0xd1139582, "VENUS.SSSS3.TGA" }, { 0xd118d7af, "@FX_FL05.TGA" }, { 0xd127eefe, "VENUS.GGGG7.TGA" }, { 0xd12ff6a5, "MARS.GSSS.TGA" }, { 0xd1334361, "IRC_ICON_LOCK.TGA" }, { 0xd1343dd2, "CLAS_S.TGA" }, { 0xd1381983, "FX_BSMK10.TGA" }, { 0xd1402141, "MARS.SSSS.TGA" }, { 0xd141fec5, "CY_ENGINE3_SD.TGA" }, { 0xd169c2d7, "TITAN.CCCC.TGA" }, { 0xd19014e0, "VENUS.SDGG.TGA" }, { 0xd1931897, "ICE.DFFF.TGA" }, { 0xd1e5fd8c, "TITAN.DB_PANEL2.TGA" }, { 0xd20238ec, "VENUS.GGGG3.TGA" }, { 0xd234786a, "TEMPERATE.TB_PANEL2.TGA" }, { 0xd2475fc1, "MERCURY.PAVE_LANDG.TGA" }, { 0xd24f1bb5, "FX_BLK05.TGA" }, { 0xd253d8bd, "HLUNA.TGA" }, { 0xd270ab2c, "TITAN.PAVED_PGGG.TGA" }, { 0xd27c96d0, "SWRM_S.TGA" }, { 0xd285a10f, "MARS.SSSS4.TGA" }, { 0xd2ad32db, "XTEMPLEFRONT.TGA" }, { 0xd2b4e322, "MARS.RD_PAVE_STRT.TGA" }, { 0xd2d6016a, "FX_ESP00.TGA" }, { 0xd2d7a400, "@FX_SPK05.TGA" }, { 0xd2df8fed, "VENUS.GSSS.TGA" }, { 0xd2ffe053, "EUROPA.CFFC3.TGA" }, { 0xd347651b, "DESERT.D.PANEL7.TGA" }, { 0xd3725172, "MERCURY.LDDD.TGA" }, { 0xd39d2540, "XGUN.TGA" }, { 0xd3bcf9d2, "MERCURY.SDDD.TGA" }, { 0xd3c54a33, "CYSHIELDGEN3_SD.TGA" }, { 0xd3ca4737, "MARS.RD_BEGIN.TGA" }, { 0xd3da7830, "HSLAT1E.TGA" }, { 0xd41c9058, "FX_DUSTLG11.TGA" }, { 0xd4265078, "FX_LXP04.TGA" }, { 0xd43d3647, "HUSHIELDGENL1_SD.TGA" }, { 0xd454e181, "TEMPERATE.GDDD2.TGA" }, { 0xd4728a6f, "6MISSILEPACK_S.TGA" }, { 0xd49b22b5, "HVENUSVENTS.TGA" }, { 0xd4a83f4d, "PLUTO.GSSS2.TGA" }, { 0xd4df75c5, "TITAN.NB_PANEL0.TGA" }, { 0xd4dfb351, "HERCOPEN.TGA" }, { 0xd4f513af, "MOON.GGGG2.TGA" }, { 0xd4feaf21, "FX_DUSTLB02.TGA" }, { 0xd5132e5d, "ICE.FDDD.TGA" }, { 0xd51cf98e, "HDOORS.TGA" }, { 0xd54c6756, "EUROPA.FRRR2.TGA" }, { 0xd56079a6, "ICE.FRRR2.TGA" }, { 0xd562ff72, "MARS.SGGG.TGA" }, { 0xd568c96f, "FX_ESP07.TGA" }, { 0xd56fcc61, "EUROPA.FRRR.TGA" }, { 0xd5a90759, "@FX_EMP02.TGA" }, { 0xd5b345f7, "FX_DUSTDY10.TGA" }, { 0xd5c94d04, "FX_SMK12.TGA" }, { 0xd5ea79e0, "EUROPA.RD_D_STRT.TGA" }, { 0xd5f6f957, "HCOLONYDOOR.TGA" }, { 0xd611d152, "MARS.LGGG.TGA" }, { 0xd61938bd, "HDESERTTROOPWINDOWS.TGA" }, { 0xd6539c23, "@FX_ESP09.TGA" }, { 0xd66346d2, "TITAN.HOGG.TGA" }, { 0xd668b3ea, "ICE.RFFF2.TGA" }, { 0xd66fc037, "FX_LXP00.TGA" }, { 0xd684d326, "VENUS.SSDD.TGA" }, { 0xd699b0b3, "EUROPA.GGGG4.TGA" }, { 0xd69d286f, "VENUS.SDGG.TGA" }, { 0xd6c01a23, "MOON.RD_P_STRT.TGA" }, { 0xd71176da, "RUINS2.TGA" }, { 0xd7120274, "FX_BSMK15.TGA" }, { 0xd71796f9, "HUENGINETURBO_S.TGA" }, { 0xd71ae234, "VENUS.SGGG.TGA" }, { 0xd7300db8, "MOON.GGGG.TGA" }, { 0xd7370c69, "XTROOPFTATBED.TGA" }, { 0xd7556599, "TEMPERATE.DDDD2.TGA" }, { 0xd78d0644, "@FX_FL15.TGA" }, { 0xd7a04540, "BOLO_CY.TGA" }, { 0xd7c1048f, "MIN_S.TGA" }, { 0xd7c2e58c, "HATC_SD.TGA" }, { 0xd7ec1622, "FX_EXS04.TGA" }, { 0xd820d007, "EUROPA.FFGG2.TGA" }, { 0xd838f69d, "MARS.RD_DIRT_CROS.TGA" }, { 0xd87981b1, "ICE.TRANS_DPPP.TGA" }, { 0xd8895cdf, "MOON.RD_D_CROS.TGA" }, { 0xd889a79b, "@FX_BSMK17.TGA" }, { 0xd8a92cb9, "EUROPA.RRRR5.TGA" }, { 0xd8ad07e5, "HUSENSORM2_S.TGA" }, { 0xd8ad8fdb, "ICE.DDFF.TGA" }, { 0xd8be1bf4, "EUROPA.RGGG.TGA" }, { 0xd8fce071, "FX_DUSTBR10.TGA" }, { 0xd9344c78, "FX_SMK03.TGA" }, { 0xd94906dc, "@FX_DROP04.TGA" }, { 0xd95b9443, "MARS.GLLL2.TGA" }, { 0xd97f7b0d, "VENUS.DB_MOON0.TGA" }, { 0xd98cfbdc, "ICE.RFFF.TGA" }, { 0xd99b9051, "VENUS.SGDD.TGA" }, { 0xd9b42269, "SHIELDCAPACITOR_SD.TGA" }, { 0xd9cf865c, "FX_SMK18.TGA" }, { 0xd9fb9899, "COPYMATS.TGA" }, { 0xda22d014, "FX_DUSTDO11.TGA" }, { 0xda24e9cb, "CURSORPLUS.TGA" }, { 0xda405020, "MARS.PAVED3.TGA" }, { 0xda53e4f0, "ARMOR3_SD.TGA" }, { 0xda6be17f, "PRX_SD.TGA" }, { 0xda855beb, "ICE.TRANS_PDDD.TGA" }, { 0xdaadff37, "MOON.GRRR2.TGA" }, { 0xdb16a8da, "FX_DUSTLB01.TGA" }, { 0xdb2916f7, "CSLAT7.TGA" }, { 0xdb3c901d, "@FX_NCAN.TGA" }, { 0xdb56854b, "@FX_EB03.TGA" }, { 0xdb5a4755, "@FX_BSMK04.TGA" }, { 0xdb636dc0, "PBW_S.TGA" }, { 0xdb7647c2, "@FX_LXP11.TGA" }, { 0xdb7ab84c, "VENUS.GDSS.TGA" }, { 0xdb81e47f, "FX_NANNO.TGA" }, { 0xdbaa7965, "TEMPERATE.RD_D_CRNR.TGA" }, { 0xdbe492de, "XPLUGS.TGA" }, { 0xdbe4e37b, "PREV_DM_LUNACY.TGA" }, { 0xdbe9ffed, "PLUTO.SGGG.TGA" }, { 0xdbfa77c0, "NANO_SD.TGA" }, { 0xdc103558, "20MINEPACK_SD.TGA" }, { 0xdc182d40, "VENUS.PAVED_PPPP.TGA" }, { 0xdc1b67c5, "FX_GAS06.TGA" }, { 0xdc4ae0a1, "FX_BLK04.TGA" }, { 0xdc4b4511, "FX_DUSTLG07.TGA" }, { 0xdc5c4638, "TITAN.HHHH3.TGA" }, { 0xdc5d98bc, "@XDEBRIS1.TGA" }, { 0xdc5f394d, "HVENUSTECH.TGA" }, { 0xdc6b34fa, "PLUTO.PAVED_PPTT.TGA" }, { 0xdcc77cd4, "MERCURY.DSSS2.TGA" }, { 0xdcc8d294, "XHUMANSEED.TGA" }, { 0xdcf2fa30, "FX_LENSFLARE_0.TGA" }, { 0xdd0d20e1, "JUDG_CY.TGA" }, { 0xdd0d533a, "MOON.RGGG2.TGA" }, { 0xdd1b23c1, "DESERT.DDDD4.TGA" }, { 0xdd20859f, "DESERT.PAVED_TRANS_PPSS.TGA" }, { 0xdd3ad765, "HDESERTDOORS.TGA" }, { 0xdd4a9b7a, "MOON.D.MOON1.TGA" }, { 0xddb412f7, "CYREACTORS2_SD.TGA" }, { 0xddcf3421, "FX_DUSTGR03.TGA" }, { 0xddd4189a, "TEMPERATE.TB_PANEL3.TGA" }, { 0xdde190b3, "MOON.RRGG.TGA" }, { 0xdde1a70d, "@FX_DISR_04.TGA" }, { 0xddee4bab, "RESIZE_TITLEBAR.TGA" }, { 0xddeffa71, "ICE.RRRR4.TGA" }, { 0xddf1b40e, "MARS.GGGG.TGA" }, { 0xddf552a7, "BLACK.TGA" }, { 0xde0312f9, "EUROPA.CFCF2.TGA" }, { 0xde1fb00d, "FX_DUSTBR01.TGA" }, { 0xde3fb843, "MARS.RD_TRANS.TGA" }, { 0xde8493de, "TB_EDIT.TGA" }, { 0xde85283b, "MARS.LLGG2.TGA" }, { 0xde8edd4c, "NEW.TGA" }, { 0xdeabb156, "PLUTO.GGRR.TGA" }, { 0xdeb27d5b, "@FX_ELE04.TGA" }, { 0xdef518a0, "TITAN.HHHH4.TGA" }, { 0xdefc4f5b, "FX_ELE08.TGA" }, { 0xdf0441f5, "EUROPA.ICECRATER.TGA" }, { 0xdf1286fa, "@FX_EX01.TGA" }, { 0xdf1be146, "FX_DUSTBR03.TGA" }, { 0xdf1fbf4d, "MOON.GGGG.TGA" }, { 0xdf270e14, "DELNMSEL.TGA" }, { 0xdf28aed5, "FX_SPK03.TGA" }, { 0xdf4b5241, "CA_TRAN.TGA" }, { 0xdf4f27f3, "COLONY.TGA" }, { 0xdf512799, "DESERT.D.PANEL0.TGA" }, { 0xdf5f99a2, "FX_ELE05.TGA" }, { 0xdf7d1911, "SHRK_S.TGA" }, { 0xdf81979c, "LTADS_S.TGA" }, { 0xdfa627d2, "MERCURY.RD_TRANS.TGA" }, { 0xdfb0d9e6, "EUROPA.FFFF.TGA" }, { 0xdfeae0a0, "CAPACITOR_SD.TGA" }, { 0xe00da957, "@FX_RAL07.TGA" }, { 0xe026727e, "@FX_ESP08.TGA" }, { 0xe037a0c4, "CONFIGUR.TGA" }, { 0xe08969c0, "FX_EMP02.TGA" }, { 0xe0a44b08, "HCB_POPUP.TGA" }, { 0xe0d32a3a, "VENUS.SSGG2.TGA" }, { 0xe0f35cf7, "FX_EXS00.TGA" }, { 0xe14750ed, "MERCURY.DSSS.TGA" }, { 0xe147674b, "@FX_BLK05.TGA" }, { 0xe1479964, "PLUTO.GRRR2.TGA" }, { 0xe162411f, "FX_SMK07.TGA" }, { 0xe1a8b240, "MERCURY.SSSS4.TGA" }, { 0xe1be1ecc, "DESERT.GDGG.TGA" }, { 0xe1dfb100, "HMARSRUIN1.TGA" }, { 0xe1ed8e8e, "TEMPERATE.DDDD5.TGA" }, { 0xe1f88a67, "@FX_EB00.TGA" }, { 0xe21ca42d, "PLUTO.SSGG.TGA" }, { 0xe24945f2, "MOON.GGDD2.TGA" }, { 0xe2569b19, "FX_BSMK08.TGA" }, { 0xe29aa592, "TELE1.TGA" }, { 0xe2a1674e, "XHERCMOVIE9.TGA" }, { 0xe2a7d27f, "HUSHIELDGENM1_S.TGA" }, { 0xe2aabb1e, "TITAN.LANDING_GGGG.TGA" }, { 0xe2b1c6e9, "PREV_DM_FEAR_IN_ISOLATION.TGA" }, { 0xe2c290d3, "FX_DUSTGR06.TGA" }, { 0xe2c9a701, "FX_ELE07.TGA" }, { 0xe31a6ed2, "XSENSOR.TGA" }, { 0xe350b8ee, "FX_DUSTLG04.TGA" }, { 0xe35111b1, "BASL_KN.TGA" }, { 0xe366dd10, "MARS.LLGG.TGA" }, { 0xe369aaa1, "FX_DUSTDY12.TGA" }, { 0xe37d5e21, "NANOREPAIR_SD.TGA" }, { 0xe3960c2c, "CYSENSORL1_S.TGA" }, { 0xe3a34c4f, "FX_DUSTYL02.TGA" }, { 0xe3bd35c6, "FX_DUST07.TGA" }, { 0xe3e6d6ad, "PLUTO.SGGG2.TGA" }, { 0xe410efe2, "ICE.TRANS_DDPP.TGA" }, { 0xe4253ced, "EUROPA.TRANS_PDDD.TGA" }, { 0xe42db0d7, "ICE.DEV_PLAIN1.TGA" }, { 0xe431a14d, "EUROPA.TRANS_PPDD.TGA" }, { 0xe440cc7b, "MERCURY.LLLL4.TGA" }, { 0xe4670029, "MERCURY.DDDD2.TGA" }, { 0xe4728e25, "TEMPERATE.DDGG2.TGA" }, { 0xe4768a69, "TITAN.HHHH2.TGA" }, { 0xe47d149d, "EUROPA.D.MOON.TGA" }, { 0xe48c1072, "FX_DUSTDB11.TGA" }, { 0xe4c572f6, "FX_DUSTBR14.TGA" }, { 0xe4d672a6, "MARS.RD_DIRT_CRNR.TGA" }, { 0xe5271ac5, "@FX_SMK05.TGA" }, { 0xe5286082, "MOON.RD_D_CRNR.TGA" }, { 0xe5618c1e, "HROOFTOPSMP.TGA" }, { 0xe56d76d6, "TEMPERATE.DB_PANEL1.TGA" }, { 0xe57edea8, "PLUTO.MMMM1.TGA" }, { 0xe581c896, "VENUS.DDDD2.TGA" }, { 0xe58cf444, "TEMPERATE.DDDD3.TGA" }, { 0xe59e7503, "DESERT.RD_PAVE_STRT.TGA" }, { 0xe5a0367b, "CYLOGO.TGA" }, { 0xe5ac3a53, "FX_DUSTDY07.TGA" }, { 0xe5aca070, "CRYSTAL_BALL.TGA" }, { 0xe5e143bf, "VENUS.RD_P_CRNR.TGA" }, { 0xe61ff4a2, "MOON.RD_D_CROS.TGA" }, { 0xe621b969, "XSTEEL.TGA" }, { 0xe65b0650, "ICE.RRRR3.TGA" }, { 0xe65e3b82, "FX_LENSFLARE_2.TGA" }, { 0xe672f7ef, "ICE.ROCK.TGA" }, { 0xe6738eb0, "HKONGSIDE.TGA" }, { 0xe6959689, "FX_DUSTDO06.TGA" }, { 0xe6b70d69, "FX_DUSTDB09.TGA" }, { 0xe6b8413f, "FX_DUSTBR09.TGA" }, { 0xe6bb3172, "MERCURY.RD_D_TEE.TGA" }, { 0xe6c05f69, "@FX_SMK01.TGA" }, { 0xe6e14366, "@FX_LXP00.TGA" }, { 0xe70956ec, "MERCURY.PAVE_PLAIN1.TGA" }, { 0xe70bf0d6, "TITAN.D_PANEL1.TGA" }, { 0xe711b73b, "VENUS.NB_PANEL3.TGA" }, { 0xe7171342, "TITAN.GCCC2.TGA" }, { 0xe732000c, "EUROPA.FFFF3.TGA" }, { 0xe7332a94, "HU_COMPUTERL_S.TGA" }, { 0xe736a08d, "TEMPERATE.TRANS_PPDD.TGA" }, { 0xe73a40e1, "RB_ARTL.TGA" }, { 0xe7467926, "EUROPA.DDDD3.TGA" }, { 0xe7468645, "WAR2.TGA" }, { 0xe74adec8, "@FX_ESP07.TGA" }, { 0xe74c27c7, "@FX_LXP10.TGA" }, { 0xe74f3db4, "EUROPA.GGGG6.TGA" }, { 0xe75b3484, "CYECM2_SD.TGA" }, { 0xe76a30b8, "XHERCMOVIE2.TGA" }, { 0xe76c7802, "@FX_GAS04.TGA" }, { 0xe77ba3d7, "EUROPA.RD_P_CRNR.TGA" }, { 0xe7abd679, "DESERT.N.PANEL0.TGA" }, { 0xe7b0a1fc, "TITAN.DB_PANEL1.TGA" }, { 0xe7b0b948, "@FX_LASE.TGA" }, { 0xe7bcbd06, "@FX_SPK01.TGA" }, { 0xe7d63c7b, "HU_COMPUTERS_S.TGA" }, { 0xe7e0adac, "HEAL.TGA" }, { 0xe807c540, "EUROPA.T.PANEL0.TGA" }, { 0xe80ab3ca, "@FX_EXHAUST.TGA" }, { 0xe8161d8c, "MERCURY.D.PANEL2.TGA" }, { 0xe82c709a, "HILITE_CRNR.TGA" }, { 0xe83289fe, "XTECH2.TGA" }, { 0xe839db47, "SORT_ARROW_HUD.TGA" }, { 0xe869ea62, "EUROPA.FFGG.TGA" }, { 0xe86c2b56, "HBC_SD.TGA" }, { 0xe8751a41, "OLYP_RB.TGA" }, { 0xe879785a, "MERCURY.DDDD3.TGA" }, { 0xe87c8e07, "FX_DUSTDO03.TGA" }, { 0xe8907133, "FX_DUSTBR05.TGA" }, { 0xe8b6232c, "VENUS.TB_PANEL0.TGA" }, { 0xe8b771ff, "VENUS.GDSS.TGA" }, { 0xe8c0237a, "FX_SMK17.TGA" }, { 0xe8c69d67, "EUROPA.RFFF2.TGA" }, { 0xe8daa128, "@FX_SHD05.TGA" }, { 0xe8f9a4a1, "PLUTO.PAVED_PPTT.TGA" }, { 0xe8fe57ed, "DESERT.TB_PANEL3.TGA" }, { 0xe90d3245, "PLUTO.MMMM2.TGA" }, { 0xe9362fe8, "XSHOCK.TGA" }, { 0xe93e27ea, "MARS.AAAS.TGA" }, { 0xe95e2b79, "CYENGINES2_S.TGA" }, { 0xe9728603, "NO_WEAPON_S.TGA" }, { 0xe980176b, "FX_DUSTDY04.TGA" }, { 0xe996c0bc, "MARS.SSSS2.TGA" }, { 0xe99fb92d, "HUSENSORM1_S.TGA" }, { 0xe9d1011b, "TABLE_HEAD8.TGA" }, { 0xe9ea7e9d, "TEMPERATE.D.MOON2.TGA" }, { 0xe9f50c0e, "TEMPERATE.RD_P_STRT.TGA" }, { 0xea067ebe, "BASL_CA.TGA" }, { 0xea2feb4f, "FX_LXP02.TGA" }, { 0xea4858ea, "HMARCOP2.TGA" }, { 0xea588d3a, "PREV_STARSIEGE_FOOTBALL.TGA" }, { 0xea663f85, "HUREACTORS2_S.TGA" }, { 0xea962668, "RB_CPIT.TGA" }, { 0xea9a0853, "EUROPA.RFFF.TGA" }, { 0xeae2ea6f, "MARS.PAVED2.TGA" }, { 0xeaec4aa6, "TITAN.PAVED_PPPP.TGA" }, { 0xeaf010ea, "VENUS.DB_MOON1.TGA" }, { 0xeb4135f7, "EXEC_MG.TGA" }, { 0xeb638b67, "XPERSONNEL_TWO.TGA" }, { 0xebfb9cd6, "FX_LENSFLARE_3.TGA" }, { 0xec740099, "VENUS.SGGG.TGA" }, { 0xec79ab4f, "TOGLSEL.TGA" }, { 0xec84b9dc, "EUROPA.PAVE_PLAIN1.TGA" }, { 0xec8929c7, "VENUS.D.MOON.TGA" }, { 0xec99079d, "EUROPA.FFFF4.TGA" }, { 0xeccc885c, "PLUTO.SSGG2.TGA" }, { 0xed02ec37, "MARS.TB_PANEL1.TGA" }, { 0xed075c35, "TITAN.GOHH.TGA" }, { 0xed115446, "MOON.TRANS_DPPP.TGA" }, { 0xed30c42d, "ICE.TB_PANEL3.TGA" }, { 0xed4b98a0, "MARS.PAVED3.TGA" }, { 0xed4c785c, "FX_DUSTWH06.TGA" }, { 0xed533482, "CYENGINETURBO_S.TGA" }, { 0xed5d9960, "MARS.TRANS_DPPP.TGA" }, { 0xed5d9bea, "TEMPERATE.DDDD2.TGA" }, { 0xed8341be, "@FX_PR103.TGA" }, { 0xeda6a41c, "HPLATE.TGA" }, { 0xedaf4a57, "ADDSTATE.TGA" }, { 0xedb3496f, "@FX_EMP01.TGA" }, { 0xedbfd613, "HVENTS.TGA" }, { 0xedf4bcef, "TB_VSPACE.TGA" }, { 0xee029012, "TITAN.CCCC3.TGA" }, { 0xee0d43af, "PLUTO.SSGG.TGA" }, { 0xee0f0aba, "CY_SPAC.TGA" }, { 0xee25c3e1, "MARS.D.PANEL0.TGA" }, { 0xee3b7923, "DESERT.D.MOON.TGA" }, { 0xee476ecd, "TEMPERATE.RRRR.TGA" }, { 0xee62b772, "MERCURY.SSDD.TGA" }, { 0xee83707d, "MERCURY.N.PANEL0.TGA" }, { 0xee9bce4d, "MARS.DB_MOON0.TGA" }, { 0xeed9aeef, "ICE.FFFF.TGA" }, { 0xeedaab46, "FX_DUSTYL12.TGA" }, { 0xeef28db9, "TITAN.PAVED_PGGG.TGA" }, { 0xeef557e6, "MARS.N.PANEL3.TGA" }, { 0xef1a8666, "CYDISH.TGA" }, { 0xef3d50e5, "FB3.TGA" }, { 0xef3ff2c1, "MOON.PAVE_PLAIN2.TGA" }, { 0xef5355ff, "XSLATB1.TGA" }, { 0xef7a57d3, "@FX_ESP01.TGA" }, { 0xef8d63fa, "MARS.T.PANEL6.TGA" }, { 0xef92651e, "MARS.T.PANEL3.TGA" }, { 0xefcc961d, "EUROPA.TRANS_DPPP.TGA" }, { 0xefd1b150, "VENUS.DDDD5.TGA" }, { 0xefd52a7a, "FX_SMK10.TGA" }, { 0xefdc2cb6, "JUDG_PL.TGA" }, { 0xefe85118, "@FX_FL06.TGA" }, { 0xefef6763, "EUROPA.GRFF.TGA" }, { 0xeff3ee2f, "HUENGINES1_SD.TGA" }, { 0xeff6a591, "PLUTO.RD_D_CROS.TGA" }, { 0xf00233c9, "@FX_DROP00.TGA" }, { 0xf02ebb7b, "ICE.RRRR2.TGA" }, { 0xf04dce9a, "15MINEPACK_S.TGA" }, { 0xf0797b4e, "CY_EMIS.TGA" }, { 0xf0a47170, "FX_GAS01.TGA" }, { 0xf0be7771, "CY_COMPUTERS_S.TGA" }, { 0xf0ccd675, "FX_SMK01.TGA" }, { 0xf0d10e9c, "SCANNEX_CYB_LG.TGA" }, { 0xf1003126, "EUROPA.CFFF.TGA" }, { 0xf13e7751, "HUREACTORL2_S.TGA" }, { 0xf155da4c, "ICE.N.PANEL0.TGA" }, { 0xf1985fad, "@FX_MUZE.TGA" }, { 0xf19bcc36, "HPIPE1L.TGA" }, { 0xf1a78207, "EUROPA.FGGG.TGA" }, { 0xf1b7471f, "VENUS.SSSS3.TGA" }, { 0xf1de3f6c, "HATC_S.TGA" }, { 0xf1f2b969, "DESERT.RD_PAVE_STRT.TGA" }, { 0xf2174aac, "PLUTO.T.PANEL5.TGA" }, { 0xf2413256, "LASERMISSILE_S.TGA" }, { 0xf2441d70, "DESERT.GGGG2.TGA" }, { 0xf2bf29ae, "DESERT.GDDD.TGA" }, { 0xf2cde30e, "FX_BSMK07.TGA" }, { 0xf324c368, "MERCURY.SSSS.TGA" }, { 0xf35d3737, "PLUTO.SSSS.TGA" }, { 0xf37267f1, "EUROPA.T.PANEL4.TGA" }, { 0xf375780a, "@FX_LENSFLARE_1.TGA" }, { 0xf37cd668, "FX_DUSTDB04.TGA" }, { 0xf3801023, "ASNBLOCK.TGA" }, { 0xf39bfd3b, "FX_DROP04.TGA" }, { 0xf3c01590, "FOLDERCLOSED.TGA" }, { 0xf3c8dea2, "TEMPERATE.D.PANEL0.TGA" }, { 0xf3deab46, "CY_TEMPLEWALL_2.TGA" }, { 0xf3e9c454, "BC_S.TGA" }, { 0xf4112301, "CHAMELEONCLOAK_SD.TGA" }, { 0xf43451b4, "MERCURY.DLLL.TGA" }, { 0xf471a9d6, "DESERT.GDDG.TGA" }, { 0xf4be94ab, "@FX_DROP01.TGA" }, { 0xf4c3cb51, "PLUTO.MRRR.TGA" }, { 0xf4c875d3, "@FX_BSMK15.TGA" }, { 0xf53d9a9e, "EUROPA.GGGG.TGA" }, { 0xf547c22d, "CYENGINES1_SD.TGA" }, { 0xf565e04d, "BLAS_S.TGA" }, { 0xf572d1a1, "TEMPERATE.N.PANEL1.TGA" }, { 0xf58c18f3, "FX_DUSTBL01.TGA" }, { 0xf590cc67, "MARS.N.PANEL1.TGA" }, { 0xf5a30794, "MERCURY.LLLL.TGA" }, { 0xf5cabe0d, "6MINEPACK_SD.TGA" }, { 0xf5e64d14, "@FX_SMK15.TGA" }, { 0xf5fba1b3, "MARS.SSAA.TGA" }, { 0xf601d1da, "ICE.RD_P_END.TGA" }, { 0xf630016e, "HSLAT4L.TGA" }, { 0xf6484cc1, "MERCURY.DDDD.TGA" }, { 0xf656206b, "ICE.RRRR5.TGA" }, { 0xf656b566, "DESERT.SDSS.TGA" }, { 0xf6829648, "CHAMELEONCLOAK_S.TGA" }, { 0xf698562d, "CYSHIELDGENM1_SD.TGA" }, { 0xf6cc042b, "CY_DROPPOD.TGA" }, { 0xf6d307c5, "XLANDING.TGA" }, { 0xf6e05db6, "TITAN.HGGG.TGA" }, { 0xf7229c0f, "I_BEAM.TGA" }, { 0xf73b3115, "@FX_LXP06.TGA" }, { 0xf768b01e, "HSNOWROOF.TGA" }, { 0xf78406d5, "TEMPERATE.T.PANEL6.TGA" }, { 0xf7c036aa, "MERCURY.DLLL.TGA" }, { 0xf7c37841, "DESERT.DGGD.TGA" }, { 0xf7ca70f5, "FX_DUST01.TGA" }, { 0xf7cc4b1e, "PLUTO.PAVED_SCORCH.TGA" }, { 0xf7d5ece3, "FX_EXS01.TGA" }, { 0xf7e12100, "MERCURY.RD_PP_CROS.TGA" }, { 0xf7e7d747, "@FX_CHN03.TGA" }, { 0xf80115a4, "FX_BLK02.TGA" }, { 0xf80a69bd, "FX_FLA10.TGA" }, { 0xf816c253, "TITAN.ROAD_TEE.TGA" }, { 0xf82b79d4, "VENUS.PAVED_GPPP.TGA" }, { 0xf8303ec6, "DESERT.RD_DIRT_CRNR.TGA" }, { 0xf83b5116, "FX_SMK16.TGA" }, { 0xf8613911, "ICON_SCANNEX_N.TGA" }, { 0xf889fb89, "XSOLAR.TGA" }, { 0xf88dd14e, "ICE.DFFD.TGA" }, { 0xf88efdf4, "DREA_PIRATE.TGA" }, { 0xf89325d4, "EUROPA.RGGG.TGA" }, { 0xf8bc00d6, "CUTTLEFISHCLOAK_SD.TGA" }, { 0xf8d546eb, "FX_DUSTLG13.TGA" }, { 0xf8d74b0a, "MARS.LGGG2.TGA" }, { 0xf8e7e2e1, "HUSHIELDGEN3_S.TGA" }, { 0xf902e973, "CY_COMPUTERL_S.TGA" }, { 0xf9133d33, "@FX_SPK11.TGA" }, { 0xf924f80f, "@FX_ELE06.TGA" }, { 0xf94a11ca, "FX_DUSTYL05.TGA" }, { 0xf94b0f46, "SPR_SD.TGA" }, { 0xf94de3ab, "XSLATS1.TGA" }, { 0xf9773aa6, "DESERT.N.PANEL1.TGA" }, { 0xf9809e47, "@FX_EXS06.TGA" }, { 0xf984ba8d, "STRCIRCLE_LOW.TGA" }, { 0xf99532b5, "PREV_DM_SACRIFICE_TO_BAST.TGA" }, { 0xf9b057b4, "HDOORE.TGA" }, { 0xf9bce151, "DESERT.D.PANEL2.TGA" }, { 0xfa02014c, "GRAB.TGA" }, { 0xfa13a31b, "TEMPERATE.T.PANEL7.TGA" }, { 0xfa399346, "EUROPA.PAVEDSCORCH.TGA" }, { 0xfa748a90, "FX_FLA09.TGA" }, { 0xfa8a5d6c, "DESERT.PAVED2.TGA" }, { 0xfaa6362b, "FX_GAS02.TGA" }, { 0xfabe1b9d, "TITAN.D_PANEL0.TGA" }, { 0xfad2a5f5, "EUROPA.RD_D_END.TGA" }, { 0xfad37f18, "HU_ENGINE2_S.TGA" }, { 0xfada69fe, "@FX_PLAS.TGA" }, { 0xfb085d95, "TEMPERATE.T.PANEL1.TGA" }, { 0xfb311180, "HUENGINEL2_SD.TGA" }, { 0xfb347779, "PREV_CTF_TITANIC_ASSAULT.TGA" }, { 0xfb53c387, "HMARS_REBEL_FLAG.TGA" }, { 0xfb7225d0, "DESELECT.TGA" }, { 0xfb800bbe, "@FX_SHD01.TGA" }, { 0xfb8cc9b7, "FX_LXP03.TGA" }, { 0xfb943ad3, "MOON.DDSS2.TGA" }, { 0xfba6c267, "MOON.RRRR2.TGA" }, { 0xfbc5bf22, "EUROPA.GFFF.TGA" }, { 0xfbd4578e, "TEMPERATE.RRRR4.TGA" }, { 0xfbe4c73d, "CYSHIELDGEN4_SD.TGA" }, { 0xfbe9b8c0, "EUROPA.PAVE_PLAIN1.TGA" }, { 0xfc00aa54, "TEMPERATE.TRANS_PPDD.TGA" }, { 0xfc0edb20, "FX_FLA05.TGA" }, { 0xfc28ffa4, "DESERT.TB_PANEL1.TGA" }, { 0xfc41390c, "HDESERTBRCK.TGA" }, { 0xfc5cf83c, "HAD_S.TGA" }, { 0xfcae75d1, "VENUS.SSSS7.TGA" }, { 0xfcb4565e, "MERCURY.LDDD2.TGA" }, { 0xfcb7f641, "STATICOPEN.TGA" }, { 0xfcdda69d, "EUROPA.FGGG2.TGA" }, { 0xfce0ed60, "FX_DROP10.TGA" }, { 0xfcea2c61, "HSLAT2L.TGA" }, { 0xfceae1d8, "FX_EMP03.TGA" }, { 0xfd0aa9f0, "FX_GAS05.TGA" }, { 0xfd1371af, "@FX_LXP12.TGA" }, { 0xfd699ea9, "CTECH4.TGA" }, { 0xfd74eb21, "SMOOTH.TGA" }, { 0xfd7ddb5e, "EUROPA.CFFC.TGA" }, { 0xfdae403a, "PLUTO.MMMM1.TGA" }, { 0xfdbad8d1, "@FX_DIS02.TGA" }, { 0xfdd5be0e, "TITAN.PAVED_GPPP.TGA" }, { 0xfe01b5d3, "TITAN.GHHH2.TGA" }, { 0xfe0a5f1d, "DESERT.D.PANEL6.TGA" }, { 0xfe1288b4, "DESERT.PAVED_TRANS_PPSS.TGA" }, { 0xfe2b0efe, "FX_LXP14.TGA" }, { 0xfe2c9553, "SCANNEX_VENUS_SML.TGA" }, { 0xfe2dfc63, "EUROPA.CFCF2.TGA" }, { 0xfe6db82e, "TITAN.N_PANEL3.TGA" }, { 0xfe78b05d, "XTREETEST.TGA" }, { 0xfeb08f60, "FX_RAL06.TGA" }, { 0xfeb3d013, "@FX_RAL00.TGA" }, { 0xfebbb515, "DESERT.RD_DIRT_STRT.TGA" }, { 0xfecb333b, "HUSENSORS2_S.TGA" }, { 0xfedf41b3, "TR_HTRA.TGA" }, { 0xfee5b538, "MARS.T.PANEL0.TGA" }, { 0xff1ab7b7, "DOPPLEGANGER_S.TGA" }, { 0xff1e3d15, "@FX_ELF.TGA" }, { 0xff5d0db3, "PLUTO.RRRR.TGA" }, { 0xff64b555, "CHECK_D_ON.TGA" }, { 0xff844f40, "HMOONTECH.TGA" }, { 0xff850ed3, "HUENGINEL3_S.TGA" }, { 0xff87b1b4, "NO_REACTOR_S.TGA" }, { 0xff952c0c, "PLUTO.RRRR3.TGA" }, { 0xffae6a4d, "EUROPA.RD_P_STRT.TGA" }, { 0xffd9281e, "HSLAT4E.TGA" }, { 0xffe7024f, "TEMPERATE.RD_D_TEE.TGA" }, { 0xffe99425, "FX_BSMK03.TGA" }, { 0xffee35f5, "PLUTO.RD_D_TEE.TGA" }, { 0xffeec6ce, "NODE.TGA" }, { 0xfffe2653, "HUSENSORS1_S.TGA" }, }; #define __ORIGINAL_COUNT__ ( sizeof( Replacer::mOriginalsTable ) / sizeof( Original ) ) #endif // __ORIGINALS_H__<file_sep>/Lib/HashTable.h #ifndef __HASHTABLE_H__ #define __HASHTABLE_H__ #include "Hash.h" #include "Strings.h" #include "Comparisons.h" /* Supports common types */ class HashKey { public: unsigned int operator() ( unsigned int i ) { return ( i ); } // uint key assumed to be a hash unsigned int operator() ( const char *str ) { return ( HashString(str) ); } unsigned int operator() ( const String &str ) { return ( HashString(str.c_str()) ); } }; class KeyCmp { public: bool operator() ( int a, int b ) const { return ( a == b ); } bool operator() ( const char *a, const char *b ) const { return ( strcmp( a, b ) == 0 ); } bool operator() ( const String &a, const String &b ) const { return ( a == b ); } }; class IKeyCmp { public: bool operator() ( int a, int b ) const { return ( a == b ); } bool operator() ( const char *a, const char *b ) const { return ( _stricmp( a, b ) == 0 ); } bool operator() ( const String &a, const String &b ) const { return ( a.IEquals( b ) ); } }; /* Use ValueDeleter<key_type,value_type> if your hash node value is a pointer and you need it deleted when the node is deleted */ template< class key_type, class value_type > class NoDeleter { public: void operator() ( key_type &key, value_type &value ) { } }; template< class key_type, class value_type > class ValueDeleter { public: void operator() ( key_type &key, value_type &value ) { delete value; } }; template< class key_type, class value_type > class KeyValueDeleter { public: void operator() ( key_type &key, value_type &value ) { delete key; delete value; } }; /* HashTable< key_type, value_type, compare object => KeyCmp, value deleter => Blank<value_type>, key hasher => HashKey > */ template < class key_type, class value_type, class equals = KeyCmp, class deleter = NoDeleter<key_type,value_type>, class hash_key = HashKey > class HashTable { public: /* Node */ class Node { public: Node( const key_type &key, const value_type &value, Node *next ) : mNext(next) { mValue = ( value ); mKey = ( key ); } ~Node( ) { deleter()( mKey, mValue ); } Node *mNext; key_type mKey; value_type mValue; }; /* Iterator */ class Iterator { public: friend class HashTable; Iterator( ): mNode(NULL) {} Iterator( HashTable *hash ) : mHash(hash), mBucketOn(-1), mNode(NULL) { SkipToNext(); } key_type &key() const { return ( mNode->mKey ); } value_type &value() const { return ( mNode->mValue ); } // ++ on End() will always exit Iterator &operator++ ( ) { if ( mNode ) { mNode = ( mNode->mNext ); SkipToNext( ); } return ( *this ); } bool operator!= ( Iterator &b ) { return ( mNode != b.mNode ); } bool operator== ( Iterator &b ) { return ( mNode == b.mNode ); } protected: void SkipToNext( ) { while ( !mNode ) { if ( mBucketOn >= ( mHash->mBucketCount - 1 ) ) break; mNode = ( mHash->mBuckets[ ++mBucketOn ] ); } } Node *mNode; HashTable *mHash; int mBucketOn; }; /* Hash Table */ HashTable( int num_buckets ) : mItemCount(0) { mBucketCount = ( SmallestPow2( num_buckets ) ); mBucketMask = ( mBucketCount - 1 ); mBuckets = new Node*[ mBucketCount ]; memset( mBuckets, 0, sizeof( Node* ) * mBucketCount ); } ~HashTable( ) { Clear( ); delete[] mBuckets; mBuckets = ( NULL ); } Iterator Begin( ) { if ( !mItemCount ) return ( End( ) ); return ( Iterator( this ) ); } size_t Bucket( const key_type &key, int mask ) const { return ( hash_key()( key ) & mask ); } size_t Bucket( const key_type &key ) const { return ( Bucket( key, mBucketMask ) ); } void Clear( ) { if ( !mItemCount ) return; for ( int i = 0; i < mBucketCount; i++ ) { Node *node = ( mBuckets[ i ] ); while ( node ) { Node *next = ( node->mNext ); delete node; node = next; } mBuckets[ i ] = NULL; } mItemCount = 0; } void Compact( ) { Resize( SmallestPow2( mItemCount ) ); } int Count( ) const { return ( mItemCount ); } void Delete( const key_type &key ) { if ( !mItemCount ) return; Node **head = ( &mBuckets[ Bucket( key ) ] ); Node *node = ( *head ), *prev = ( NULL ); while ( node ) { Node *next = ( node->mNext ); if ( mCompare( node->mKey, key ) ) { Unlink( head, prev, node ); return; } else { prev = ( node ); } node = ( next ); } } void Delete( Iterator &iter ) { if ( !iter.mNode ) return; if ( iter.mBucketOn >= mBucketCount ) return; Node **head = ( &mBuckets[ iter.mBucketOn ] ), *node = ( *head ), *prev = ( NULL ); for ( ; node && ( node != iter.mNode ); prev = node, node = node->mNext ) {} if ( node != iter.mNode ) return; iter.mNode = Unlink( head, prev, node ); if ( !iter.mNode ) iter.SkipToNext(); } Iterator End( ) { return ( Iterator( ) ); } value_type *Find( const key_type &key ) const { Node **head = ( &mBuckets[ Bucket( key ) ] ); Node *node = ( *head ); for ( node = *head; node; node = node->mNext ) { if ( mCompare( node->mKey, key ) ) return ( &node->mValue ); } return ( NULL ); } value_type *Insert( const key_type &key, const value_type &value ) { CheckIncrease(); Node **head = ( &mBuckets[ Bucket( key ) ] ); value_type *ret = ( Link( head, key, value ) ); return ( ret ); } value_type *InsertUnique( const key_type &key, const value_type &value ) { CheckIncrease(); Node **head = ( &mBuckets[ Bucket( key ) ] ); Node *node = ( *head ); for ( node = *head; node; node = node->mNext ) { if ( mCompare( node->mKey, key ) ) { return ( &node->mValue ); } } value_type *ret = ( Link( head, key, value ) ); return ( ret ); } int Size( ) { return ( mItemCount ); } int SmallestPow2( int cap ) const { int count = ( 1 ); while ( count < cap ) count <<= 1; return ( count ); } value_type &operator[] ( const key_type &key ) { return ( *InsertUnique( key, value_type() ) ); } private: value_type *Link( Node **bucket, const key_type &key, const value_type &value ) { Node *node = new Node( key, value, *bucket ); if ( node ) { *bucket = node; mItemCount++; return ( &node->mValue ); } else { return ( NULL ); } } Node *Unlink( Node **bucket, Node *prev, Node *node ) { Node *next = ( node->mNext ); if ( prev ) prev->mNext = ( next ); else *bucket = ( next ); delete node; mItemCount--; return ( next ); } void CheckIncrease( ) { if ( mBucketCount <= mItemCount ) Resize( mBucketCount << 1 ); } void Resize( int bucket_count ) { if ( mBucketCount == bucket_count ) return; Node **new_buckets = new Node*[ bucket_count ]; if ( !new_buckets ) return; memset( new_buckets, 0, sizeof( Node** ) * bucket_count ); for ( int i = 0; i < mBucketCount; i++ ) { Node *node = ( mBuckets[ i ] ); while ( node ) { Node *next = ( node->mNext ); Node **head = &new_buckets[ Bucket( node->mKey, ( bucket_count - 1 ) ) ]; node->mNext = ( *head ); *head = node; node = ( next ); } } delete[] mBuckets; mBuckets = ( new_buckets ); mBucketCount = ( bucket_count ); mBucketMask = ( bucket_count - 1 ); } Node **mBuckets; int mBucketCount, mBucketMask, mItemCount; equals mCompare; }; #endif // __HASHTABLE_H__<file_sep>/README.md Source code of floodyberry's mem.dll <file_sep>/DLLMain.cpp #include "Memstar.h" BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { } break; case DLL_PROCESS_DETACH: { } break; } return TRUE; }<file_sep>/Memstar.h #ifndef __MEMSTAR_H__ #define __MEMSTAR_H__ #define _CRT_SECURE_NO_WARNINGS #define DLLAPI __declspec(dllexport) #define NAKED __declspec(naked) #define INLINE __forceinline #include <windows.h> #include <Psapi.h> #include <stdio.h> #include <stdarg.h> #include "BaseTypes.h" #include "version.h" #endif // __MEMSTAR_H__ <file_sep>/Texture.h #ifndef __TEXTURE_H__ #define __TEXTURE_H__ #include "Fear.h" #include "HashTable.h" #define TGA_INDEXED ( 1 ) #define TGA_RGB ( 2 ) #define TGA_GRAY ( 3 ) #define TGA_INDEXED_RLE ( 9 ) #define TGA_RGB_RLE ( 10 ) #pragma pack(push) #pragma pack(1) class TargaHeader { public: void LoadPalette(unsigned char*& input, RGBA* pal); void LoadIndexed(unsigned char* input, RGBA* pixels, RGBA* pal); void LoadRGB(unsigned char* input, RGBA* pixels); unsigned char id_length, colormap_type, image_type; unsigned short colormap_index, colormap_length; unsigned char colormap_size; unsigned short x_origin, y_origin, width, height; unsigned char pixel_size, attributes; }; #pragma pack(pop) #define TEXTURE_WIDTH ( 1 << 0 ) #define TEXTURE_HEIGHT ( 1 << 1 ) #define TEXTURE_INVERSE ( 1 << 2 ) class Texture { public: /* FUNCTIONS */ Texture() : mData(NULL), mHandle(0), mWidth(0), mHeight(0) { } ~Texture() { Free(); } void AlphaBloom(int blur_radius, int actual_width, int actual_height); static int CeilPow2(int x) { int y = 1; while (y < x) y <<= 1; return (y); } void Clear(int r, int g, int b, int a) { if (!mData) return; RGBA color = RGBA(r, g, b, a); for (int i = 0; i < mWidth * mHeight; i++) mData[i] = color; } void Draw(float x, float y); void DrawScaled(float x, float y, float scale_x, float scale_y); void DrawCentered(float x, float y); void DrawTo(float x, float y, float width, float height); void DrawPartial(float x, float y, float percent, int flags); void DrawRotated(float x, float y, float scale_x, float scale_y, float rotation); Texture* Duplicate(); bool Duplicate(Texture& b) const; bool Loaded() const { return (mData != NULL); } bool LoadTGA(unsigned char* input); bool New(int width, int height); // Virtuals virtual void Free(); virtual bool BindToGraphicsCard(); virtual void UnloadFromGraphicsCard(); // Operators RGBA& operator()(int x, int y) { return (mData[y * mWidth + x]); } /* VARIABLES */ unsigned int mHandle; int mWidth, mHeight; RGBA* mData; /* STATICS */ typedef HashTable< unsigned int, Texture* > Hash; static void BuildMulTab(); static void HalveTexture(RGBA* src, int srcX, int srcY, RGBA* dst, int dstX, int dstY); static void UnloadAllFromGraphicsCard(); static unsigned int mMulTab[256 * 256]; static bool mMulTabCalculated; static Hash mTexturesLoadedToOpenGL; }; class TextureWithMips : public Texture { public: TextureWithMips() : Texture() { memset(mMipMaps, 0, sizeof(mMipMaps)); } ~TextureWithMips() { FreeMipMaps(); } virtual void Free(); void GenerateMipMaps(); void FreeMipMaps(); virtual bool BindToGraphicsCard(); //private: Texture* mMipMaps[12]; }; #endif // __TEXTURE_H__<file_sep>/Font.h #ifndef __FONT_H__ #define __FONT_H__ #include "Texture.h" #include "OpenGL.h" class LetterWidth { public: LetterWidth() {} LetterWidth(int a, int b, int c) : mA(a), mB(b), mC(c) {} int mA, mB, mC; }; class Letter { public: Letter() { } // letter loads itself to opengl on demand void Draw(int x, int y, int font_height, int glow_radius) { if (!mTexture.Loaded() || !mTexture.BindToGraphicsCard()) return; x -= (glow_radius); y -= (glow_radius); int glow = (glow_radius * 2); int width = (mWidth.mB + glow); int height = (font_height + glow); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2i(x, y); glTexCoord2f(mExtent.x, 0); glVertex2i(x + width, y); glTexCoord2f(mExtent.x, mExtent.y); glVertex2i(x + width, y + height); glTexCoord2f(0, mExtent.y); glVertex2i(x, y + height); glEnd(); /* glDisable( GL_TEXTURE_2D ); glBegin( GL_LINE_STRIP ); glVertex2f( x, y ); glVertex2f( x + width, y ); glVertex2f( x + width, y + height ); glVertex2f( x, y + height ); glVertex2f( x, y ); glEnd( ); glEnable( GL_TEXTURE_2D ); */ } // size of actual character, not trailing/leading rendering space int GlyphWidth() const { return (mWidth.mB); } bool CreateTexture(int font_height, int glow_radius) { int width = (GlyphWidth() + glow_radius * 2); int height = (font_height + glow_radius * 2); mTexture.New(Texture::CeilPow2(width), Texture::CeilPow2(height)); if (!mTexture.Loaded()) return (false); // clear to pure white, no alpha mTexture.Clear(255, 255, 255, 0); mExtent.x = ((float)width / (float)mTexture.mWidth); mExtent.y = ((float)height / (float)mTexture.mHeight); return (true); } Texture mTexture; Vector2f mExtent; LetterWidth mWidth; }; class Font { public: enum Rendering { Pixel, Smooth, }; Font() : mLoaded(false), mLastUsed(GetTickCount()), mCreatedDC(false) { } ~Font() { Close(); } void Close(); bool Create(const char* name, int pixel_height, Rendering mode, int glow_radius); void Draw(const char* str, int x, int y); int LastUsed() { return (mLastUsed); } Vector2i StringDimensions(const char* str); void UpdateLastUsed() { mLastUsed = (GetTickCount()); } private: bool CreateLetter(Letter& l, char ch); void RenderCharacter(Letter& l, char ch); void RenderCharacterSmooth(Letter& l, char ch); // font info Letter mLetters[256]; int mHeight; bool mLoaded; int mLastUsed; // only for rendering int mGlowAdd, mBlurRadius; Rendering mMode; bool mCreatedDC; RGBA* mDibPixels; HDC mDC; HFONT mFont; HBITMAP mDib; int mDibSize, mAscent, mMaxWidth; bool mTrueType; }; #endif // __FONT_H__ <file_sep>/Loader.cpp #include "Console.h" #include "Patch.h" #include "Fear.h" #include "Callback.h" #include "MultiPointer.h" namespace Loader { namespace Test { BuiltInFunction("Sky::setRotation", skySetRot) { Fear::Sky* sky = Fear::findSky(); if (sky) { sky->rotation = (f32)atof(argv[0]); sky->calcPoints(); } return "true"; } }; // namespace Test u32 fnFearInstanceInit, fnUEHandler, fnEndFrame; u32 Crashed = 0; MultiPointer(ptrFearInstanceUEHandler, 0, 0, 0x0085e084, 0x0087F16C); NAKED void UEHandler() { __asm { mov dword ptr[Crashed], 1 jmp[fnUEHandler] } } MultiPointer(ptrFearInstanceInitVFT, 0, 0, 0x006c8000, 0x006D802C); void Startup() { Callback::trigger(Callback::OnStarted, true); } NAKED void StartupStub() { __asm { push dword ptr[fnFearInstanceInit] mov esi, ptrFearInstanceInitVFT pop dword ptr ds:[esi] call[fnFearInstanceInit] call Startup retn } } MultiPointer(ptrEndFrameVFT, 0, 0, 0x006c7f74, 0x006D7FA0); void OnEndFrameManaged() { Callback::trigger(Callback::OnEndframe, true); } NAKED void OnEndFrame() { __asm { push eax call OnEndFrameManaged pop eax jmp[fnEndFrame] } } struct Init { Init() { if (VersionSnoop::GetVersion() == VERSION::vNotGame) { return; } if (VersionSnoop::GetVersion() < VERSION::v001003) { return; } fnUEHandler = Patch::ReplaceHook((void*)ptrFearInstanceUEHandler, &UEHandler); fnFearInstanceInit = Patch::ReplaceHook((void*)ptrFearInstanceInitVFT, &StartupStub); fnEndFrame = Patch::ReplaceHook((void*)ptrEndFrameVFT, &OnEndFrame); } } Init; }; // namespace Loader<file_sep>/Lib/Comparisons.h #ifndef __COMPARISONS_H__ #define __COMPARISONS_H__ template < class type > class Comparison { public: bool operator()( const type &x, const type &y ) const { return ( false ); } }; template < class type > class Less : public Comparison<type> { public: bool operator()( const type &x, const type &y ) const { return ( x < y ); } }; template < class type > class Greater : public Comparison<type> { public: bool operator()( const type &x, const type &y ) const { return ( x > y ); } }; template < class type > class Equals : public Comparison<type> { public: bool operator()( const type &x, const type &y ) const { return ( x == y ); } }; #endif // __COMPARISONS_H__ <file_sep>/Fear.cpp #include "Fear.h" #include "Strings.h" #include "MultiPointer.h" namespace Fear { MultiPointer(ptr_SIM_PTR, 0, 0, 0x0070caec, 0x0071CF5C); MultiPointer(ptr_SIMSKY_VFT, 0, 0, 0x007021ec, 0x0071265C); MultiPointer(ptr_SIMSET_VFT, 0, 0, 0x0070452c, 0x0071492C); MultiPointer(ptr_SIMCANVAS_PTR, 0, 0, 0x0076f4d0, 0x0077FAE8); Sim* Sim::Client() { return *(Sim**)(ptr_SIM_PTR); } template<class T> T* Sim::findObject(const char* nameOrId) { if (!this) return NULL; __asm { mov eax, this push eax mov edx, [nameOrId] mov ecx, [eax] call[ecx + 0x6c] pop this } } Sky* findSky() { SimSet* render_set = Sim::Client()->findObject<SimSet>(13); if (render_set->vft == ptr_SIMSET_VFT) { for (SimSet::Iterator iter = render_set->Begin(); iter != render_set->End(); ++iter) if ((*iter)->vft == ptr_SIMSKY_VFT) return (Sky*)*iter; } return NULL; } PlayerPSC* findPSC() { return Sim::Client()->findObject<PlayerPSC>(636); } f32 Sim::getTime() { return (this) ? Time : 0; } static const u32 fnSkyCalcPoints = 0x005855E0; void Sky::calcPoints() { __asm { mov eax, this push eax call[fnSkyCalcPoints] pop this } } bool getScreenDimensions(Vector2i* dim) { __asm { // SimGui::Canvas mov esi, ptr_SIMCANVAS_PTR mov eax, ds:[esi] and eax, eax jz done // GFXDevice::? mov ebx, [eax + 0x144] xor eax, eax and ebx, ebx jz done // GFX::Surface mov eax, [ebx + 0x3c] mov edx, [dim] mov ecx, [eax + 0x3c] mov[edx + 0], ecx mov ecx, [eax + 0x40] mov[edx + 4], ecx mov eax, 1 done: } } }; // namespace Fear<file_sep>/Lib/Patch.h #ifndef __PATCH_H__ #define __PATCH_H__ #include "Memstar.h" namespace Patch { INLINE u32 Protect(void *base, u32 size, u32 protection) { if ((int)base <= 0) { return 0; } DWORD old_protect; VirtualProtect(base, size, protection, &old_protect); return (u32)old_protect; } INLINE void Write(void *base, void *bytes, u32 size) { if ((int)base <= 0) { return; } Protect(base, size, PAGE_EXECUTE_READWRITE); memcpy(base, bytes, size); } INLINE u32 ReplaceHook(void *address, void *new_hook) { if ((int)address <= 0) { return 0; } u32 tmp = *(u32 *)address; *(u32 *)address = (u32)new_hook; return tmp; } }; // namespace Patch struct CodePatch { void Apply(bool state) { if ((int)location <= 0) { return; } Patch::Write((void *)location, (state) ? patched_bytes : unpatched_bytes, size); } // alter an int at patched_byttes[ patch_offset ] CodePatch &DoctorInt(u32 value, u32 patch_offset) { Patch::Protect(patched_bytes, size, PAGE_EXECUTE_READWRITE); memcpy(patched_bytes + patch_offset, &value, 4); return *this; } // alter a value relative to location CodePatch &DoctorRelative(u32 value, s32 patch_offset) { return DoctorInt(value + -(location + patch_offset + 4), patch_offset); } public: s32 location; char *unpatched_bytes; char *patched_bytes; u32 size; bool patched; }; #endif // __PATCH_H__<file_sep>/FontManager.h #ifndef __FONTMANAGER_H__ #define __FONTMANAGER_H__ #include "Font.h" namespace FontManager { Font* LoadFont(const char* name, int pixel_height, Font::Rendering mode, int glow_radius); }; #endif // __FONTMANAGER_H__<file_sep>/Replacer.cpp #include "Replacer.h" #include "HashTable.h" #include "FileSystem.h" #include "Console.h" #include "OpenGL.h" #include "Patch.h" #include "Callback.h" #include "Terrain.h" #include "OpenGL_Pointers.h" namespace Replacer { #include "Originals.h" MultiPointer(ptr_OPENGL_FLUSH_TEXTURE_VFT, 0, 0, 0x0071a15c, 0x0072A748); BuiltInVariable("pref::ShowMatchedTextures", bool, prefShowMatchedTextures, false); typedef HashTable< String, TextureWithMips*, IKeyCmp, ValueDeleter<String, TextureWithMips*> > ReplacementHash; typedef HashTable< u32, String > OriginalHash; bool lastScanMatched = false; bool foundLastCRC = false; bool ignoreTexImageMips = false; bool ignoreTexSubImageMips = false; bool lastNonMipMatched = false; u32 lastFoundCRC = 0; TextureWithMips* lastMatchedTexture = NULL, * lastUsedTexture = NULL; FileSystem mFiles(128); ReplacementHash mTextures(128); OriginalHash mOriginals(4096); void Forget() { lastScanMatched = false; lastMatchedTexture = NULL; foundLastCRC = false; } TextureWithMips* LastMatchedTexture() { return (lastScanMatched) ? lastMatchedTexture : NULL; } bool LastScanWasReplaceable() { return foundLastCRC; } TextureWithMips* FindReplacement(const String* name) { // allowed to pass null if (!name) return (NULL); TextureWithMips** find = mTextures.Find(*name); if (find) return *find; TextureWithMips* texture = new TextureWithMips(); if (!texture || !mFiles.ReadTGA(*name, *texture) || !mTextures.Insert(*name, texture)) { delete texture; texture = NULL; } return texture; } const String* FindOriginalName(u32 texture_crc) { return mOriginals.Find(texture_crc); } void Open() { mFiles.Clear(); mTextures.Clear(); mFiles.Grok("Memstar/Replacements"); } void Scan(Fear::GFXBitmap* bmp) { if (Terrain::TexImageCheck(bmp->bitmapData)) return; lastFoundCRC = HashBytes(bmp->bitmapData, bmp->width * bmp->height); const String* file = FindOriginalName(lastFoundCRC); if (prefShowMatchedTextures != true) { Console::echo("Matched texture %s", file->c_str()); } foundLastCRC = (file != NULL); lastMatchedTexture = FindReplacement(file); lastScanMatched = (lastMatchedTexture != NULL); } BuiltInFunction("Memstar::AddReplacement", AddReplacement) { if (argc != 2) { Console::echo("%s( <texture crc>, <texture name> );", self); } else { u32 crc; if (atohhl(argv[0], &crc)) { const String* find = FindOriginalName(crc); if (find) { Console::echo("Replacer: Duplicate CRC! Already bound to %s", find->c_str()); } else { Console::echo("Replacer: Adding %s(hash:%x)", argv[1], crc); mOriginals.Insert(crc, String2(argv[1])); } } } return "true"; } u32 fnglTexImage2D, fnglTexSubImage2D, fnFlushTexture; MultiPointer(fnResumeCacheBitmap, 0, 0, 0x0063e71a, 0x0064D822); MultiPointer(fnIsFromCurrentRound, 0, 0, 0x0063dedc, 0x0064CFAC); MultiPointer(ptr_cacheBitmapPatch, 0, 0, 0x0063e714, 0x0064D81C); CodePatch cacheBitmapPatch = { ptr_cacheBitmapPatch, "", "\xE9tccb", 5, false }; NAKED void OnCacheBitmap() { __asm { pushad mov edi, ecx mov esi, edx mov ebx, eax mov edx, edi mov eax, ebx call[fnIsFromCurrentRound] test al, al jnz __ignore push esi call Scan add esp, 4 __ignore: popad push ebp mov ebp, esp add esp, -0x18 jmp[fnResumeCacheBitmap] } } NAKED void OnFlushTexture() { __asm { pushad mov edi, edx mov ebx, eax mov edx, edi mov eax, [ebx + 0x158] call[fnIsFromCurrentRound] test al, al jz __ignore push dword ptr[edi + 0x38] call Terrain::TexSubImageCheck add esp, 4 __ignore: popad jmp[fnFlushTexture] } } void GLAPIENTRY OnGlTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLvoid* pixels) { typedef void (GLAPIENTRY* fn)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels); bool isMip = (level != 0), needDefault = true; if (ignoreTexImageMips && isMip) return; lastNonMipMatched &= isMip; ignoreTexImageMips = false; if (!isMip) { if (prefShowMatchedTextures && foundLastCRC) { static const RGBA colors[16] = { RGBA(204,204,204,64),RGBA(255,102, 0,64),RGBA(255, 51, 0,64),RGBA(153,204, 0,64), RGBA(255,204,102,64),RGBA(153,153, 0,64),RGBA(255, 0, 0,64),RGBA(153,153, 51,64), RGBA(255, 51, 51,64),RGBA(102,153, 0,64),RGBA(153, 0, 51,64),RGBA(102,255, 51,64), RGBA(204,153,102,64),RGBA(153,204,102,64),RGBA(102,204,102,64),RGBA(255,153,255,64), }; ((fn)fnglTexImage2D)(target, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &colors[lastFoundCRC & 0x0f]); ignoreTexImageMips = true; needDefault = false; } else if (lastMatchedTexture) { ((fn)fnglTexImage2D)(target, level, GL_RGBA8, lastMatchedTexture->mWidth, lastMatchedTexture->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, lastMatchedTexture->mData); lastUsedTexture = lastMatchedTexture; lastNonMipMatched = true; needDefault = false; } else { RGBA** terrain = Terrain::CheckForTerrainTile(); if (terrain) { u32 mipWidth = width, mipLevel = 0; while (mipWidth > 0) { if (!*terrain) break; ((fn)fnglTexImage2D)(target, mipLevel, GL_RGBA8, mipWidth, mipWidth, 0, GL_RGBA, GL_UNSIGNED_BYTE, *terrain++); mipLevel++; mipWidth >>= 1; } ignoreTexImageMips = true; needDefault = false; } } } else if (lastNonMipMatched && (level == 1)) { lastUsedTexture->GenerateMipMaps(); for (u32 i = 0; lastUsedTexture->mMipMaps[i]; i++) { Texture* mip = lastUsedTexture->mMipMaps[i]; ((fn)fnglTexImage2D)(target, i + 1, GL_RGBA8, mip->mWidth, mip->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mip->mData); } ignoreTexImageMips = true; needDefault = false; } if (needDefault) ((fn)fnglTexImage2D)(target, level, internalformat, width, height, border, format, type, pixels); Forget(); } void GLAPIENTRY OnGlTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels) { typedef void (GLAPIENTRY* fn)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels); if (ignoreTexSubImageMips) { if (level != 0) return; ignoreTexSubImageMips = false; } bool needDefault = true; RGBA** terrain = Terrain::CheckForTerrainTile(); if (terrain) { u32 mipWidth = width, mipLevel = 0; while (mipWidth > 0) { if (!*terrain) break; ((fn)fnglTexSubImage2D)(target, mipLevel, xoffset, yoffset, mipWidth, mipWidth, GL_RGBA, GL_UNSIGNED_BYTE, *terrain++); mipLevel++; mipWidth >>= 1; } ignoreTexSubImageMips = true; needDefault = false; } if (needDefault) ((fn)fnglTexSubImage2D)(target, level, xoffset, yoffset, width, height, format, type, pixels); } void OnStarted(bool state) { Open(); for (int i = 0; i < __ORIGINAL_COUNT__; i++) { mOriginals.Insert(mOriginalsTable[i].mCrc, String2(mOriginalsTable[i].mName)); } fnglTexImage2D = Patch::ReplaceHook((void*)OpenGLPtrs::ptr_OPENGL32_GLTEXIMAGE2D, OnGlTexImage2D); fnglTexSubImage2D = Patch::ReplaceHook((void*)OpenGLPtrs::ptr_OPENGL32_GLTEXSUBIMAGE2D, OnGlTexSubImage2D); fnFlushTexture = Patch::ReplaceHook((void*)ptr_OPENGL_FLUSH_TEXTURE_VFT, OnFlushTexture); cacheBitmapPatch.DoctorRelative((u32)&OnCacheBitmap, 1).Apply(true); } struct Init { Init() { if (VersionSnoop::GetVersion() == VERSION::vNotGame) { return; } if (VersionSnoop::GetVersion() < VERSION::v001003) { return; } Callback::attach(Callback::OnStarted, OnStarted); } } init; }; // namespace Replacer<file_sep>/Console.cpp #include "Console.h" #include "Callback.h" #include "Strings.h" #include "VersionSnoop.h" namespace Console { u32 dummy, dummy2; VariableConstructor* VariableConstructor::mFirst = NULL; ConsoleConstructor* ConsoleConstructor::mFirst = NULL; typedef List<const char*> StringList; typedef StringList::Iterator StringIter; StringList variables, functions; MultiPointer(ptrConsole, 0, 0, 0x00712b34, 0x00722FA4); MultiPointer(fnAddFunction, 0, 0, 0x005e34dc, 0x005E6D80); void addFunction(const char* name, void* cb) { __asm { push[cb] push 0 mov ecx, [name] xor edx, edx mov eax, ptrConsole mov eax, ds:[eax] call[fnAddFunction] } } MultiPointer(fnAddVariable, 0, 0, 0x005e3474, 0x005E6D18); void addVariable(const char* name, const void* address, const VariableType var_type) { __asm { push[var_type] push[address] mov ecx, [name] xor edx, edx mov eax, ptrConsole mov eax, ds:[eax] call[fnAddVariable] } } MultiPointer(fnDBEcho, 0x005d3a44, 0x005d4b1c, 0x005e2900, 0x005e61a4); NAKED void dbecho(u32 level, const char* fmt, ...) { u32 ptrHold; __asm { pop[dummy] mov ptrHold, esi mov esi, ptrConsole push dword ptr ds:[esi] mov esi, ptrHold call[fnDBEcho] add esp, 4 jmp[dummy] } } MultiPointer(fnEcho, 0, 0, 0x005e3178, 0x005E6A1C); NAKED void echo(const char* fmt, ...) { u32 ptrHold; __asm { pop[dummy] mov ptrHold, esi mov esi, ptrConsole push dword ptr ds:[esi] mov esi, ptrHold call[fnEcho] add esp, 4 jmp[dummy] } } MultiPointer(fnExecFunction, 0, 0, 0x005e362c, 0x005E6ED0); NAKED const char* execFunction(u32 argc, char* function, ...) { u32 ptrHold; __asm { pop[dummy2] mov ptrHold, esi mov esi, ptrConsole push dword ptr ds:[esi] mov esi, ptrHold inc dword ptr[esp + 0x4] // argc call[fnExecFunction] add esp, 4 jmp[dummy2] } } MultiPointer(fnEval, 0, 0, 0x005e354c, 0x005E6DF0); void eval(const char* cmd) { __asm { push 0 push 0 mov eax, ptrConsole mov eax, ds:[eax] xor ecx, ecx mov edx, [cmd] call[fnEval] } } MultiPointer(fnFunctionExists, 0, 0, 0x005e387c, 0x005E7120); bool functionExists(const char* name) { __asm { mov eax, ptrConsole mov eax, ds:[eax] mov edx, [name] call[fnFunctionExists] } } MultiPointer(fnGetVariable, 0, 0, 0x005e3394, 0x005E6C38); const char* getVariable(const char* name) { __asm { mov eax, ptrConsole mov eax, ds:[eax] mov edx, [name] call[fnGetVariable] } } MultiPointer(fnSetVariable, 0, 0, 0x005e32ac, 0x005E6B50); void setVariable(const char* name, const char* value) { __asm { mov eax, ptrConsole mov eax, ds:[eax] mov ecx, [value] mov edx, [name] call[fnSetVariable] } } void OnStarted(bool active) { VariableConstructor::Process(); ConsoleConstructor::Process(); Console::echo("[mem.dll] Initalized Successfully"); Console::echo("---------------------------------"); Console::execFunction(0, "Memstar::version"); Console::echo("---------------------------------"); const char* pref = Console::getVariable("$pref::OpenGL::NoPackedTextures"); if (VersionSnoop::GetVersion() == VERSION::v001004 && _stricmp(pref, "false") != 0) { Console::echo("[mem.dll] v4 Warning: initalizing $pref::OpenGL::NoPackedTextures to 'false'", pref); Console::setVariable("$pref::OpenGL::NoPackedTextures", "false"); } } struct Init { Init() { Callback::attach(Callback::OnStarted, OnStarted); } } init; struct StringSorter { bool operator() (const char*& a, const char*& b) const { return _stricmp(a, b) < 0; } }; struct FunctionPrinter { void operator() (const char*& in) const { Console::echo(" %s()", in); } }; struct VariablePrinter { void operator() (const char*& in) const { Console::echo(" $%s = \"%s\";", in, Console::getVariable(in)); } }; template <typename Printer> void DumpStrings(StringList& strings) { Printer p; strings.Sort(StringSorter()); for (StringIter iter = strings.Begin(); iter != strings.End(); ++iter) p(iter.value()); } BuiltInFunction("Memstar::dumpAddons", dumpAddons) { Console::echo("------------------"); Console::echo("Memstar Functions"); DumpStrings<FunctionPrinter>(functions); Console::echo("------------------"); Console::echo("Memstar Variables"); DumpStrings<VariablePrinter>(variables); return "true"; } }; // namespace Console<file_sep>/Lib/StringConversions.cpp #include "Strings.h" #include "StringConversions.h" namespace StringConversions { static const int conversionBufferCount = 32; static const int conversionBufferSize = 1024; static char conversionBuffers[conversionBufferCount][ conversionBufferSize + 1 ]; static int conversionBufferOn = 0; char *getConversionBuffer() { return ( conversionBuffers[ (conversionBufferOn++) & (conversionBufferCount-1) ] ); } int getConversionBufferSize() { return ( conversionBufferSize ); } /* Specialized strcpy, returns end of copied string (doesn't add null) */ char *strcpywalk( char *dst, const char *src ) { while ( *src ) *dst++ = *src++; return ( dst ); } char *strcatspace( char *dst ) { *dst++ = ' '; return ( dst ); } /* Converting TO a string */ template<> const char *tostring( const bool &value ) { return ( value ) ? "true" : "false"; } template<> const char *tostring( const s32 &value ) { char *buffer = getConversionBuffer(); return _itoa( value, buffer, 10 ); } template<> const char *tostring( const u32 &value ) { char *buffer = getConversionBuffer(); return _itoa( value, buffer, 10 ); } template<> const char *tostring( const char &value ) { char *buffer = getConversionBuffer(); return _itoa( value, buffer, 10 ); } template<> const char *tostring( const s8 &value ) { char *buffer = getConversionBuffer(); return _itoa( value, buffer, 10 ); } template<> const char *tostring( const u8 &value ) { char *buffer = getConversionBuffer(); return _itoa( value, buffer, 10 ); } template<> const char *tostring( const unsigned long &value ) { char *buffer = getConversionBuffer(); return _itoa( value, buffer, 10 ); } template<> const char *tostring( const f64 &value, char *buffer, int buffersize ) { int size = Snprintf( buffer, buffersize, "%f", value ); buffer[ size ] = NULL; char *tail = ( buffer + size - 1 ); while ( tail > buffer ) { if ( *tail != '0' ) break; tail--; } if ( *tail == '.' ) tail[0] = '\x0'; else tail[1] = '\x0'; return ( buffer ); } template<> const char *tostring( const f32 &value, char *buffer, int buffersize ) { return ( tostring<double>( value, buffer, buffersize ) ); } template<> const char *tostring( const f32 &value ) { return ( tostring<double>( value, getConversionBuffer(), conversionBufferSize ) ); } template<> const char *tostring( const f64 &value ) { return ( tostring( value, getConversionBuffer(), conversionBufferSize ) ); } template<> const char *tostring( const Vector3f &value ) { char format[ 128 ]; char *buffer = getConversionBuffer(), *out = buffer; out = strcpywalk( out, tostring( value.x, format, 127 ) ); out = strcatspace( out ); out = strcpywalk( out, tostring( value.y, format, 127 ) ); out = strcatspace( out ); out = strcpywalk( out, tostring( value.z, format, 127 ) ); *out = NULL; return ( buffer ); } template<> const char *tostring( const Vector2f &value ) { char format[ 128 ]; char *buffer = getConversionBuffer(), *out = buffer; out = strcpywalk( out, tostring( value.x, format, 127 ) ); out = strcatspace( out ); out = strcpywalk( out, tostring( value.y, format, 127 ) ); *out = NULL; return ( buffer ); } template<> const char *tostring( const Vector2i &value ) { char *buffer = getConversionBuffer(), *out = buffer; out = strcpywalk( out, tostring( value.x ) ); out = strcatspace( out ); out = strcpywalk( out, tostring( value.y ) ); *out = NULL; return ( buffer ); } /* Converting FROM a string */ template<> void fromstring( const char *string, f32 &value ) { value = (f32)atof( string ); } template<> void fromstring( const char *string, f64 &value ) { value = (f64)atof( string ); } template<> void fromstring( const char *string, s32 &value ) { value = atoi( string ); } template<> void fromstring( const char *string, Vector3f &value ) { sscanf( string, "%f %f %f", &value.x, &value.y, &value.z ); } template<> void fromstring( const char *string, Vector2f &value ) { sscanf( string, "%f %f", &value.x, &value.y ); } template<> void fromstring( const char *string, Vector2i &point ) { sscanf( string, "%d %d", &point.x, &point.y ); } template<> bool fromstring( const char *string ) { return (!_stricmp(string, "true") || atof(string)); } template<> f32 fromstring( const char *string ) { return (f32)atof( string ); } template<> f64 fromstring( const char *string ) { return atof( string ); } template<> s32 fromstring( const char *string ) { return atoi( string ); } template<> u32 fromstring( const char *string ) { return atoi( string ); } template<> Vector3f fromstring( const char *string ) { Vector3f v; fromstring( string, v ); return ( v ); } template<> Vector2f fromstring( const char *string ) { Vector2f v; fromstring( string, v ); return ( v ); } /* Round an ascii string */ // breaks on scientific retardation format! const char *roundascii( const char *value, int digits ) { const char *in = value; digits = ( digits > 32 ) ? 32 : digits; char *buffer = getConversionBuffer(), *out = buffer; while ( *in && ( *in != '.' ) ) *out++ = *in++; if ( digits <= 0 ) { *out = NULL; return ( buffer ); } if ( *in == '.' ) { const char *end = in + digits; while ( *in && ( in <= end ) ) *out++ = *in++; while ( in++ <= end ) *out++ = '0'; } else { *out++ = '.'; while ( digits-- ) *out++ = '0'; } *out = NULL; return ( buffer ); } /* A short lived formatted string which won't require any allocating */ const char *format( const char *fmt, ... ) { char *buffer = getConversionBuffer(); va_list args; va_start( args, fmt ); Snprintf( buffer, conversionBufferSize, fmt, args ); va_end( args ); return( buffer ); } const char *format( int buffersize, char *buffer, const char *fmt, ... ) { va_list args; va_start( args, fmt ); Snprintf( buffer, buffersize, fmt, args ); va_end( args ); return( buffer ); } const char *format( int buffersize, char *buffer, va_list &args, const char *fmt ) { Snprintf( buffer, buffersize, fmt, args ); return( buffer ); } char *escapestring( const char *src, u32 dstlen, char *dst ) { char *out = dst, *end = out + dstlen - 1; for ( ; *src && out < end; src++ ) { u8 c = *src; if ( c == '\"' || c == '\\' || c == '\r' || c == '\n' || c == '\t' ) { if ( out + 2 >= end ) break; *out++ = '\\'; switch ( c ) { case '\"': *out++ = '"'; break; case '\\': *out++ = '\\'; break; case '\r': *out++ = 'r'; break; case '\n': *out++ = 'n'; break; case '\t': *out++ = 't'; break; } } else if ( ( c < 32 ) || ( c > 127 ) ) { if ( out + 4 >= end ) break; *out++ = '\\'; *out++ = 'x'; u8 dig1 = c >> 4, dig2 = c & 0xf; dig1 += ( dig1 < 10 ) ? '0' : 'A' - 10; dig2 += ( dig2 < 10 ) ? '0' : 'A' - 10; *out++ = dig1; *out++ = dig2; } else { *out++ = c; } } *out = NULL; return dst; } char *escapestring( const char *src ) { char *buffer = getConversionBuffer(); return escapestring( src, conversionBufferSize, buffer ); } }; // namespace StringConversions <file_sep>/OpenGL_Pointers.h #pragma once #ifndef __OPENGLPTRS__ #define __OPENGLPTRS__ #include "MultiPointer.h" namespace OpenGLPtrs { MultiPointer_Ext(ptr_OPENGL_BOUND_TEXTURE); MultiPointer_Ext(ptr_OPENGL_SET_ALPHA_SOURCE); MultiPointer_Ext(ptr_OPENGL32_GLACCUM); MultiPointer_Ext(ptr_OPENGL32_GLALPHAFUNC); MultiPointer_Ext(ptr_OPENGL32_GLARETEXTURESRESIDENT); MultiPointer_Ext(ptr_OPENGL32_GLARRAYELEMENT); MultiPointer_Ext(ptr_OPENGL32_GLBEGIN); MultiPointer_Ext(ptr_OPENGL32_GLBINDTEXTURE); MultiPointer_Ext(ptr_OPENGL32_GLBITMAP); MultiPointer_Ext(ptr_OPENGL32_GLBLENDFUNC); MultiPointer_Ext(ptr_OPENGL32_GLCALLLIST); MultiPointer_Ext(ptr_OPENGL32_GLCALLLISTS); MultiPointer_Ext(ptr_OPENGL32_GLCLEAR); MultiPointer_Ext(ptr_OPENGL32_GLCLEARACCUM); MultiPointer_Ext(ptr_OPENGL32_GLCLEARCOLOR); MultiPointer_Ext(ptr_OPENGL32_GLCLEARDEPTH); MultiPointer_Ext(ptr_OPENGL32_GLCLEARINDEX); MultiPointer_Ext(ptr_OPENGL32_GLCLEARSTENCIL); MultiPointer_Ext(ptr_OPENGL32_GLCLIPPLANE); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3B); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3BV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3D); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3DV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3F); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3FV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3I); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3IV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3S); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3SV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3UB); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3UBV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3UI); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3UIV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3US); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR3USV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4B); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4BV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4D); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4DV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4F); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4FV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4I); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4IV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4S); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4SV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4UB); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4UBV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4UI); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4UIV); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4US); MultiPointer_Ext(ptr_OPENGL32_GLCOLOR4USV); MultiPointer_Ext(ptr_OPENGL32_GLCOLORMASK); MultiPointer_Ext(ptr_OPENGL32_GLCOLORMATERIAL); MultiPointer_Ext(ptr_OPENGL32_GLCOLORPOINTER); MultiPointer_Ext(ptr_OPENGL32_GLCOPYPIXELS); MultiPointer_Ext(ptr_OPENGL32_GLCOPYTEXIMAGE1D); MultiPointer_Ext(ptr_OPENGL32_GLCOPYTEXIMAGE2D); MultiPointer_Ext(ptr_OPENGL32_GLCOPYTEXSUBIMAGE1D); MultiPointer_Ext(ptr_OPENGL32_GLCOPYTEXSUBIMAGE2D); MultiPointer_Ext(ptr_OPENGL32_GLCULLFACE); MultiPointer_Ext(ptr_OPENGL32_GLDELETELISTS); MultiPointer_Ext(ptr_OPENGL32_GLDELETETEXTURES); MultiPointer_Ext(ptr_OPENGL32_GLDEPTHFUNC); MultiPointer_Ext(ptr_OPENGL32_GLDEPTHMASK); MultiPointer_Ext(ptr_OPENGL32_GLDEPTHRANGE); MultiPointer_Ext(ptr_OPENGL32_GLDISABLE); MultiPointer_Ext(ptr_OPENGL32_GLDISABLECLIENTSTATE); MultiPointer_Ext(ptr_OPENGL32_GLDRAWARRAYS); MultiPointer_Ext(ptr_OPENGL32_GLDRAWBUFFER); MultiPointer_Ext(ptr_OPENGL32_GLDRAWELEMENTS); MultiPointer_Ext(ptr_OPENGL32_GLDRAWPIXELS); MultiPointer_Ext(ptr_OPENGL32_GLEDGEFLAG); MultiPointer_Ext(ptr_OPENGL32_GLEDGEFLAGPOINTER); MultiPointer_Ext(ptr_OPENGL32_GLEDGEFLAGV); MultiPointer_Ext(ptr_OPENGL32_GLENABLE); MultiPointer_Ext(ptr_OPENGL32_GLENABLECLIENTSTATE); MultiPointer_Ext(ptr_OPENGL32_GLEND); MultiPointer_Ext(ptr_OPENGL32_GLENDLIST); MultiPointer_Ext(ptr_OPENGL32_GLEVALCOORD1D); MultiPointer_Ext(ptr_OPENGL32_GLEVALCOORD1DV); MultiPointer_Ext(ptr_OPENGL32_GLEVALCOORD1F); MultiPointer_Ext(ptr_OPENGL32_GLEVALCOORD1FV); MultiPointer_Ext(ptr_OPENGL32_GLEVALCOORD2D); MultiPointer_Ext(ptr_OPENGL32_GLEVALCOORD2DV); MultiPointer_Ext(ptr_OPENGL32_GLEVALCOORD2F); MultiPointer_Ext(ptr_OPENGL32_GLEVALCOORD2FV); MultiPointer_Ext(ptr_OPENGL32_GLEVALMESH1); MultiPointer_Ext(ptr_OPENGL32_GLEVALMESH2); MultiPointer_Ext(ptr_OPENGL32_GLEVALPOINT1); MultiPointer_Ext(ptr_OPENGL32_GLEVALPOINT2); MultiPointer_Ext(ptr_OPENGL32_GLFEEDBACKBUFFER); MultiPointer_Ext(ptr_OPENGL32_GLFINISH); MultiPointer_Ext(ptr_OPENGL32_GLFLUSH); MultiPointer_Ext(ptr_OPENGL32_GLFOGF); MultiPointer_Ext(ptr_OPENGL32_GLFOGFV); MultiPointer_Ext(ptr_OPENGL32_GLFOGI); MultiPointer_Ext(ptr_OPENGL32_GLFOGIV); MultiPointer_Ext(ptr_OPENGL32_GLFRONTFACE); MultiPointer_Ext(ptr_OPENGL32_GLFRUSTUM); MultiPointer_Ext(ptr_OPENGL32_GLGENLISTS); MultiPointer_Ext(ptr_OPENGL32_GLGENTEXTURES); MultiPointer_Ext(ptr_OPENGL32_GLGETBOOLEANV); MultiPointer_Ext(ptr_OPENGL32_GLGETCLIPPLANE); MultiPointer_Ext(ptr_OPENGL32_GLGETDOUBLEV); MultiPointer_Ext(ptr_OPENGL32_GLGETERROR); MultiPointer_Ext(ptr_OPENGL32_GLGETFLOATV); MultiPointer_Ext(ptr_OPENGL32_GLGETINTEGERV); MultiPointer_Ext(ptr_OPENGL32_GLGETLIGHTFV); MultiPointer_Ext(ptr_OPENGL32_GLGETLIGHTIV); MultiPointer_Ext(ptr_OPENGL32_GLGETMAPDV); MultiPointer_Ext(ptr_OPENGL32_GLGETMAPFV); MultiPointer_Ext(ptr_OPENGL32_GLGETMAPIV); MultiPointer_Ext(ptr_OPENGL32_GLGETMATERIALFV); MultiPointer_Ext(ptr_OPENGL32_GLGETMATERIALIV); MultiPointer_Ext(ptr_OPENGL32_GLGETPIXELMAPFV); MultiPointer_Ext(ptr_OPENGL32_GLGETPIXELMAPUIV); MultiPointer_Ext(ptr_OPENGL32_GLGETPIXELMAPUSV); MultiPointer_Ext(ptr_OPENGL32_GLGETPOINTERV); MultiPointer_Ext(ptr_OPENGL32_GLGETPOLYGONSTIPPLE); MultiPointer_Ext(ptr_OPENGL32_GLGETSTRING); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXENVFV); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXENVIV); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXGENDV); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXGENFV); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXGENIV); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXIMAGE); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXLEVELPARAMETERFV); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXLEVELPARAMETERIV); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXPARAMETERFV); MultiPointer_Ext(ptr_OPENGL32_GLGETTEXPARAMETERIV); MultiPointer_Ext(ptr_OPENGL32_GLHINT); MultiPointer_Ext(ptr_OPENGL32_GLINDEXMASK); MultiPointer_Ext(ptr_OPENGL32_GLINDEXPOINTER); MultiPointer_Ext(ptr_OPENGL32_GLINDEXD); MultiPointer_Ext(ptr_OPENGL32_GLINDEXDV); MultiPointer_Ext(ptr_OPENGL32_GLINDEXF); MultiPointer_Ext(ptr_OPENGL32_GLINDEXFV); MultiPointer_Ext(ptr_OPENGL32_GLINDEXI); MultiPointer_Ext(ptr_OPENGL32_GLINDEXIV); MultiPointer_Ext(ptr_OPENGL32_GLINDEXS); MultiPointer_Ext(ptr_OPENGL32_GLINDEXSV); MultiPointer_Ext(ptr_OPENGL32_GLINDEXUB); MultiPointer_Ext(ptr_OPENGL32_GLINDEXUBV); MultiPointer_Ext(ptr_OPENGL32_GLINITNAMES); MultiPointer_Ext(ptr_OPENGL32_GLINTERLEAVEDARRAYS); MultiPointer_Ext(ptr_OPENGL32_GLISENABLED); MultiPointer_Ext(ptr_OPENGL32_GLISLIST); MultiPointer_Ext(ptr_OPENGL32_GLISTEXTURE); MultiPointer_Ext(ptr_OPENGL32_GLLIGHTMODELF); MultiPointer_Ext(ptr_OPENGL32_GLLIGHTMODELFV); MultiPointer_Ext(ptr_OPENGL32_GLLIGHTMODELI); MultiPointer_Ext(ptr_OPENGL32_GLLIGHTMODELIV); MultiPointer_Ext(ptr_OPENGL32_GLLIGHTF); MultiPointer_Ext(ptr_OPENGL32_GLLIGHTFV); MultiPointer_Ext(ptr_OPENGL32_GLLIGHTI); MultiPointer_Ext(ptr_OPENGL32_GLLIGHTIV); MultiPointer_Ext(ptr_OPENGL32_GLLINESTIPPLE); MultiPointer_Ext(ptr_OPENGL32_GLLINEWIDTH); MultiPointer_Ext(ptr_OPENGL32_GLLISTBASE); MultiPointer_Ext(ptr_OPENGL32_GLLOADIDENTITY); MultiPointer_Ext(ptr_OPENGL32_GLLOADMATRIXD); MultiPointer_Ext(ptr_OPENGL32_GLLOADMATRIXF); MultiPointer_Ext(ptr_OPENGL32_GLLOADNAME); MultiPointer_Ext(ptr_OPENGL32_GLLOGICOP); MultiPointer_Ext(ptr_OPENGL32_GLMAP1D); MultiPointer_Ext(ptr_OPENGL32_GLMAP1F); MultiPointer_Ext(ptr_OPENGL32_GLMAP2D); MultiPointer_Ext(ptr_OPENGL32_GLMAP2F); MultiPointer_Ext(ptr_OPENGL32_GLMAPGRID1D); MultiPointer_Ext(ptr_OPENGL32_GLMAPGRID1F); MultiPointer_Ext(ptr_OPENGL32_GLMAPGRID2D); MultiPointer_Ext(ptr_OPENGL32_GLMAPGRID2F); MultiPointer_Ext(ptr_OPENGL32_GLMATERIALF); MultiPointer_Ext(ptr_OPENGL32_GLMATERIALFV); MultiPointer_Ext(ptr_OPENGL32_GLMATERIALI); MultiPointer_Ext(ptr_OPENGL32_GLMATERIALIV); MultiPointer_Ext(ptr_OPENGL32_GLMATRIXMODE); MultiPointer_Ext(ptr_OPENGL32_GLMULTMATRIXD); MultiPointer_Ext(ptr_OPENGL32_GLMULTMATRIXF); MultiPointer_Ext(ptr_OPENGL32_GLNEWLIST); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3B); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3BV); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3D); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3DV); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3F); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3FV); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3I); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3IV); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3S); MultiPointer_Ext(ptr_OPENGL32_GLNORMAL3SV); MultiPointer_Ext(ptr_OPENGL32_GLNORMALPOINTER); MultiPointer_Ext(ptr_OPENGL32_GLORTHO); MultiPointer_Ext(ptr_OPENGL32_GLPASSTHROUGH); MultiPointer_Ext(ptr_OPENGL32_GLPIXELMAPFV); MultiPointer_Ext(ptr_OPENGL32_GLPIXELMAPUIV); MultiPointer_Ext(ptr_OPENGL32_GLPIXELMAPUSV); MultiPointer_Ext(ptr_OPENGL32_GLPIXELSTOREF); MultiPointer_Ext(ptr_OPENGL32_GLPIXELSTOREI); MultiPointer_Ext(ptr_OPENGL32_GLPIXELTRANSFERF); MultiPointer_Ext(ptr_OPENGL32_GLPIXELTRANSFERI); MultiPointer_Ext(ptr_OPENGL32_GLPIXELZOOM); MultiPointer_Ext(ptr_OPENGL32_GLPOINTSIZE); MultiPointer_Ext(ptr_OPENGL32_GLPOLYGONMODE); MultiPointer_Ext(ptr_OPENGL32_GLPOLYGONOFFSET); MultiPointer_Ext(ptr_OPENGL32_GLPOLYGONSTIPPLE); MultiPointer_Ext(ptr_OPENGL32_GLPOPATTRIB); MultiPointer_Ext(ptr_OPENGL32_GLPOPCLIENTATTRIB); MultiPointer_Ext(ptr_OPENGL32_GLPOPMATRIX); MultiPointer_Ext(ptr_OPENGL32_GLPOPNAME); MultiPointer_Ext(ptr_OPENGL32_GLPRIORITIZETEXTURES); MultiPointer_Ext(ptr_OPENGL32_GLPUSHATTRIB); MultiPointer_Ext(ptr_OPENGL32_GLPUSHCLIENTATTRIB); MultiPointer_Ext(ptr_OPENGL32_GLPUSHMATRIX); MultiPointer_Ext(ptr_OPENGL32_GLPUSHNAME); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS2D); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS2DV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS2F); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS2FV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS2I); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS2IV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS2S); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS2SV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS3D); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS3DV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS3F); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS3FV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS3I); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS3IV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS3S); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS3SV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS4D); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS4DV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS4F); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS4FV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS4I); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS4IV); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS4S); MultiPointer_Ext(ptr_OPENGL32_GLRASTERPOS4SV); MultiPointer_Ext(ptr_OPENGL32_GLREADBUFFER); MultiPointer_Ext(ptr_OPENGL32_GLREADPIXELS); MultiPointer_Ext(ptr_OPENGL32_GLRECTD); MultiPointer_Ext(ptr_OPENGL32_GLRECTDV); MultiPointer_Ext(ptr_OPENGL32_GLRECTF); MultiPointer_Ext(ptr_OPENGL32_GLRECTFV); MultiPointer_Ext(ptr_OPENGL32_GLRECTI); MultiPointer_Ext(ptr_OPENGL32_GLRECTIV); MultiPointer_Ext(ptr_OPENGL32_GLRECTS); MultiPointer_Ext(ptr_OPENGL32_GLRECTSV); MultiPointer_Ext(ptr_OPENGL32_GLRENDERMODE); MultiPointer_Ext(ptr_OPENGL32_GLROTATED); MultiPointer_Ext(ptr_OPENGL32_GLROTATEF); MultiPointer_Ext(ptr_OPENGL32_GLSCALED); MultiPointer_Ext(ptr_OPENGL32_GLSCALEF); MultiPointer_Ext(ptr_OPENGL32_GLSCISSOR); MultiPointer_Ext(ptr_OPENGL32_GLSELECTBUFFER); MultiPointer_Ext(ptr_OPENGL32_GLSHADEMODEL); MultiPointer_Ext(ptr_OPENGL32_GLSTENCILFUNC); MultiPointer_Ext(ptr_OPENGL32_GLSTENCILMASK); MultiPointer_Ext(ptr_OPENGL32_GLSTENCILOP); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD1D); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD1DV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD1F); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD1FV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD1I); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD1IV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD1S); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD1SV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD2D); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD2DV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD2F); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD2FV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD2I); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD2IV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD2S); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD2SV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD3D); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD3DV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD3F); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD3FV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD3I); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD3IV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD3S); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD3SV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD4D); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD4DV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD4F); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD4FV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD4I); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD4IV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD4S); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORD4SV); MultiPointer_Ext(ptr_OPENGL32_GLTEXCOORDPOINTER); MultiPointer_Ext(ptr_OPENGL32_GLTEXENVF); MultiPointer_Ext(ptr_OPENGL32_GLTEXENVFV); MultiPointer_Ext(ptr_OPENGL32_GLTEXENVI); MultiPointer_Ext(ptr_OPENGL32_GLTEXENVIV); MultiPointer_Ext(ptr_OPENGL32_GLTEXGEND); MultiPointer_Ext(ptr_OPENGL32_GLTEXGENDV); MultiPointer_Ext(ptr_OPENGL32_GLTEXGENF); MultiPointer_Ext(ptr_OPENGL32_GLTEXGENFV); MultiPointer_Ext(ptr_OPENGL32_GLTEXGENI); MultiPointer_Ext(ptr_OPENGL32_GLTEXGENIV); MultiPointer_Ext(ptr_OPENGL32_GLTEXIMAGE1D); MultiPointer_Ext(ptr_OPENGL32_GLTEXIMAGE2D); MultiPointer_Ext(ptr_OPENGL32_GLTEXPARAMETERF); MultiPointer_Ext(ptr_OPENGL32_GLTEXPARAMETERFV); MultiPointer_Ext(ptr_OPENGL32_GLTEXPARAMETERI); MultiPointer_Ext(ptr_OPENGL32_GLTEXPARAMETERIV); MultiPointer_Ext(ptr_OPENGL32_GLTEXSUBIMAGE1D); MultiPointer_Ext(ptr_OPENGL32_GLTEXSUBIMAGE2D); MultiPointer_Ext(ptr_OPENGL32_GLTRANSLATED); MultiPointer_Ext(ptr_OPENGL32_GLTRANSLATEF); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX2D); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX2DV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX2F); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX2FV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX2I); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX2IV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX2S); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX2SV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX3D); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX3DV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX3F); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX3FV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX3I); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX3IV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX3S); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX3SV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX4D); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX4DV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX4F); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX4FV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX4I); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX4IV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX4S); MultiPointer_Ext(ptr_OPENGL32_GLVERTEX4SV); MultiPointer_Ext(ptr_OPENGL32_GLVERTEXPOINTER); MultiPointer_Ext(ptr_OPENGL32_GLVIEWPORT); MultiPointer_Ext(ptr_OPENGL32_WGLCHOOSEPIXELFORMAT); MultiPointer_Ext(ptr_OPENGL32_WGLCOPYCONTEXT); MultiPointer_Ext(ptr_OPENGL32_WGLCREATECONTEXT); MultiPointer_Ext(ptr_OPENGL32_WGLCREATELAYERCONTEXT); MultiPointer_Ext(ptr_OPENGL32_WGLDELETECONTEXT); MultiPointer_Ext(ptr_OPENGL32_WGLDESCRIBELAYERPLANE); MultiPointer_Ext(ptr_OPENGL32_WGLDESCRIBEPIXELFORMAT); MultiPointer_Ext(ptr_OPENGL32_WGLGETCURRENTCONTEXT); MultiPointer_Ext(ptr_OPENGL32_WGLGETCURRENTDC); MultiPointer_Ext(ptr_OPENGL32_WGLGETDEFAULTPROCADDRESS); MultiPointer_Ext(ptr_OPENGL32_WGLGETLAYERPALETTEENTRIES); MultiPointer_Ext(ptr_OPENGL32_WGLGETPIXELFORMAT); MultiPointer_Ext(ptr_OPENGL32_WGLGETPROCADDRESS); MultiPointer_Ext(ptr_OPENGL32_WGLMAKECURRENT); MultiPointer_Ext(ptr_OPENGL32_WGLREALIZELAYERPALETTE); MultiPointer_Ext(ptr_OPENGL32_WGLSETLAYERPALETTEENTRIES); MultiPointer_Ext(ptr_OPENGL32_WGLSETPIXELFORMAT); MultiPointer_Ext(ptr_OPENGL32_WGLSHARELISTS); MultiPointer_Ext(ptr_OPENGL32_WGLSWAPBUFFERS); MultiPointer_Ext(ptr_OPENGL32_WGLSWAPLAYERBUFFERS); MultiPointer_Ext(ptr_OPENGL32_WGLUSEFONTBITMAPSA); MultiPointer_Ext(ptr_OPENGL32_WGLUSEFONTBITMAPSW); MultiPointer_Ext(ptr_OPENGL32_WGLUSEFONTOUTLINESA); MultiPointer_Ext(ptr_OPENGL32_WGLUSEFONTOUTLINESW); } #endif //__OPENGLPTRS_ <file_sep>/Font.cpp #include "Fear.h" #include "Font.h" #include "OpenGL.h" #pragma warning( disable : 4244 ) // conversion from 'double' to 'float', possible loss of data void Font::Close() { if (!mCreatedDC) return; DeleteObject(mFont); DeleteObject(mDib); DeleteDC(mDC); mDC = (NULL); mFont = (NULL); mDib = (NULL); mLoaded = (false); } // get the font information and create windows handles bool Font::Create(const char* name, int pixel_height, Rendering mode, int glow_radius) { Close(); // rendering mMode = (mode); mGlowAdd = (glow_radius > 16) ? 16 : glow_radius; mBlurRadius = (glow_radius); mDC = (CreateCompatibleDC(NULL)); if (!mDC) return (false); SetMapMode(mDC, MM_TEXT); mFont = CreateFont( -pixel_height, 0, /* width */ 0, /* escapement */ 0, /* orientation */ FW_NORMAL, /* weight */ 0, /* italic */ 0, /* underline */ 0, /* strikeout */ ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, name); if (!mFont) { DeleteDC(mDC); mDC = (NULL); return (false); } else { SelectObject(mDC, mFont); } // Font height TEXTMETRIC metric; GetTextMetrics(mDC, &metric); mHeight = (metric.tmHeight); mAscent = (metric.tmAscent); mMaxWidth = (metric.tmMaxCharWidth); mTrueType = ((metric.tmPitchAndFamily & TMPF_TRUETYPE) != 0); // Char widths ABC widths[256]; if (!mTrueType || !GetCharABCWidths(mDC, 0, 255, widths)) { int widths2[256]; GetCharWidth(mDC, 0, 255, widths2); for (int i = 0; i < 256; i++) { widths[i].abcA = (0); widths[i].abcB = (widths2[i]); widths[i].abcC = (0); } } // DibSection mDibSize = Texture::CeilPow2(max(mMaxWidth, mHeight)); BITMAPINFO header; memset(&header, 0, sizeof(header)); header.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); header.bmiHeader.biWidth = (mDibSize); header.bmiHeader.biHeight = -(mDibSize); // negative means top down header.bmiHeader.biPlanes = (1); header.bmiHeader.biBitCount = (32); header.bmiHeader.biCompression = (BI_RGB); mDib = CreateDIBSection(mDC, &header, DIB_RGB_COLORS, (void**)&mDibPixels, 0, 0); SelectObject(mDC, mDib); // Color SetTextColor(mDC, (COLORREF)0x00FFFFFF); SetBkColor(mDC, (COLORREF)0x00000000); SetBkMode(mDC, TRANSPARENT); // Init character widths for (int i = 0, x = 0, y = 0; i < 256; i++) { Letter& l = (mLetters[i]); ABC& abc = (widths[i]); l.mWidth = LetterWidth(abc.abcA, abc.abcB, abc.abcC); } mCreatedDC = (true); mLoaded = (true); return (true); } // render a letter for use bool Font::CreateLetter(Letter& l, char ch) { if (l.mTexture.Loaded()) return (true); // dont draw these if (ch < 31 || ch > 126 || (l.GlyphWidth() <= 0)) return (false); if (mMode == Smooth) RenderCharacterSmooth(l, ch); else RenderCharacter(l, ch); if (mGlowAdd) l.mTexture.AlphaBloom(mBlurRadius, l.mWidth.mB, mHeight); return (true); } void Font::Draw(const char* str, int x, int y) { if (!mLoaded) return; glDisable(GL_ALPHA_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); Vector2i start(x, y); RGBA color(255, 255, 255, 255); while (*str) { unsigned char ch = (*str++); if (ch == '\n') { x = (start.x); y += (mHeight); continue; } else if (ch == '<') { if (atoh(str, (char*)&color, 4) == 4) { str += (8); if (*str) str++; glColor4ub(color.r, color.g, color.b, color.a); continue; } } Letter& l = (mLetters[ch]); if (CreateLetter(l, ch)) { x += (l.mWidth.mA); l.Draw(x, y, mHeight, mGlowAdd); x += (l.mWidth.mB + l.mWidth.mC); } } } /* Renders a character with no smoothing */ void Font::RenderCharacter(Letter& l, char ch) { if (!l.CreateTexture(mHeight, mGlowAdd)) return; memset(mDibPixels, 0, mDibSize * mDibSize * 4); TextOut(mDC, -l.mWidth.mA, 0, (char*)&ch, 1); for (int y = 0; y < mHeight; y++) { for (int x = 0; x < l.GlyphWidth(); x++) { RGBA& quad = (mDibPixels[x + y * mDibSize]); if (quad.r) quad.a = 255; else quad = (RGBA(255, 255, 255, 0)); l.mTexture(x + mGlowAdd, y + mGlowAdd) = (quad); } } } /* Attempts to create an AA character with GetGlyphOutline */ void Font::RenderCharacterSmooth(Letter& l, char ch) { GLYPHMETRICS metrics; MAT2 mat2 = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } }; int bytes = (GetGlyphOutline(mDC, ch, GGO_GRAY8_BITMAP, &metrics, 0, NULL, &mat2)); if (bytes == 0) { // fallback to non-aa RenderCharacter(l, ch); return; } unsigned char* gray = new unsigned char[bytes]; GetGlyphOutline(mDC, ch, GGO_GRAY8_BITMAP, &metrics, bytes, gray, &mat2); // character dimensions may change with anti-aliasing int pad = (metrics.gmBlackBoxX - l.mWidth.mB), half = (pad >> 1); l.mWidth.mA -= (pad - half); l.mWidth.mB = (metrics.gmBlackBoxX); l.mWidth.mC -= (half); // resize the texture, it wont fail! l.CreateTexture(mHeight, mGlowAdd); int width = (metrics.gmBlackBoxX + 3) & ~3; // dword aligned int start_y = (mAscent - metrics.gmptGlyphOrigin.y); int start_x = 0; for (unsigned int j = 0; j < metrics.gmBlackBoxY; j++) { for (unsigned int i = start_x; i < metrics.gmBlackBoxX; i++) { int x = (i - start_x) + mGlowAdd; int y = (j + start_y) + mGlowAdd; if ((x >= l.mTexture.mWidth) || (y >= l.mTexture.mHeight)) continue; // format is 64 shades of gray l.mTexture(x, y) = RGBA(255, 255, 255, gray[(j * width) + i] * 255 / 64); } } delete[] gray; } Vector2i Font::StringDimensions(const char* str) { Vector2i dimensions(0, mHeight); if (!mLoaded) return (dimensions); int x = 0; while (*str) { unsigned char ch = (*str++); if (ch == '\n') { dimensions.y += (mHeight); continue; } else if (ch == '<') { RGBA color; if (atoh(str, (char*)&color, 4) == 4) { str += (8); if (*str) str++; continue; } } Letter& l = (mLetters[ch]); x += (l.mWidth.mA + l.mWidth.mB + l.mWidth.mC); dimensions.x = (max(dimensions.x, x)); } return (dimensions); } <file_sep>/ExeFixes.cpp #include "Console.h" #include "Patch.h" #include "VersionSnoop.h" #include "MultiPointer.h" namespace ExeFixes { MultiPointer(ptrWideScreen, 0, 0, 0x0063c807, 0x0064B747); CodePatch widescreen = { ptrWideScreen, "", "\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90", 58, false }; MultiPointer(ptrDoSFix, 0, 0, 0x0067c7e6, 0x0068C6B2); // |. 8DBD 38FFFFFF LEA EDI,DWORD PTR SS:[EBP-C8] CodePatch dosfix = { ptrDoSFix, "", "\xE9OSFX", 5, false }; MultiPointer(fnBitStreamReadInt, 0, 0, 0, 0x0056D4A0); MultiPointer(fnReadPacketAcksResume, 0, 0, 0, 0x0068C6E9); static const char* crashAttempt = "DoSFiX: Crash Attempt by %s"; NAKED void DosFix() { __asm { push ebx lea edi, [ebp - 0xc8] lea ebx, [edi + (0x1a * 0x8)] jmp __primed_jump __read_ack_loop : lea eax, [ebp - 0xf0] mov edx, 0x5 call[fnBitStreamReadInt] mov[edi - 0x4], eax inc dword ptr[ebp - 0x28] add edi, 0x8 __primed_jump: lea eax, [ebp - 0xf0] mov edx, 0x3 call[fnBitStreamReadInt] mov[edi], eax cmp edi, ebx jae __crash_attempt test eax, eax jnz __read_ack_loop __leave_loop : pop ebx jmp[fnReadPacketAcksResume] __crash_attempt : lea eax, [ebp + 0x28] push eax mov eax, [crashAttempt] push eax call Console::echo add esp, 0x8 jmp __leave_loop } } struct Init { Init() { if (VersionSnoop::GetVersion() == VERSION::vNotGame) { return; } if (VersionSnoop::GetVersion() != VERSION::v001004) { return; } widescreen.Apply(true); dosfix.DoctorRelative((u32)DosFix, 1).Apply(true); } } init; }; // namespace ExeFixes<file_sep>/Lib/Callback.cpp #include "Callback.h" #include "List.h" namespace Callback { typedef List<Listener> CallbackList; typedef CallbackList::Iterator ListIter; CallbackList *root = NULL; CallbackList &get_cb(const Type t) { if (!root) root = new CallbackList[NumCallbacks]; return root[t]; } void attach(const Type t, Listener cb) { get_cb(t).Push(cb); } void trigger(const Type t, bool state) { CallbackList &list = get_cb(t); for (ListIter iter = list.Begin(); iter != list.End(); ++iter) iter.value()(state); } }; // namespace Callback<file_sep>/Terrain.h #ifndef __TERRAIN_H__ #define __TERRAIN_H__ namespace Terrain { RGBA** CheckForTerrainTile(); bool TexImageCheck(void* bmp); bool TexSubImageCheck(void* bmp); }; // namespace Terrain #endif // __TERRAIN_H__<file_sep>/FileSystem.h #ifndef __FILESYSTEM_H__ #define __FILESYSTEM_H__ #include "Fear.h" #include "HashTable.h" #include "List.h" #include "Strings.h" #include "Texture.h" #include "zlib/unzip.h" class FileInfo { public: virtual const char* Path() const = 0; virtual bool Read(char*& buffer, int& size) = 0; }; class DiskFile : public FileInfo { public: DiskFile(const String& path) { mPath = path; } virtual const char* Path() const { return (mPath.c_str()); } virtual bool Read(char*& buffer, int& size) { if (!mPath.Strlen()) return (false); HANDLE f = CreateFile(mPath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); DWORD r; if (f == INVALID_HANDLE_VALUE) return (false); size = (GetFileSize(f, NULL)); buffer = new char[size]; if (buffer && ReadFile(f, buffer, size, &r, NULL)) { if (r != size) { delete[] buffer; buffer = (NULL); } } CloseHandle(f); return (buffer != NULL); } private: String mPath; }; class ZipFile : public FileInfo { public: ZipFile(unzFile zip, int zip_size, int zip_offset) : mZip(zip), mZipSize(zip_size), mZipOffset(zip_offset) { } virtual const char* Path() const { return (""); } virtual bool Read(char*& buffer, int& size) { size = (mZipSize); buffer = new char[mZipSize]; unzSetOffset(mZip, mZipOffset); if (buffer && (unzOpenCurrentFile(mZip) == UNZ_OK)) { if (unzReadCurrentFile(mZip, buffer, mZipSize) != mZipSize) { delete[] buffer; buffer = (NULL); } unzCloseCurrentFile(mZip); } return (buffer != NULL); } private: int mZipSize; unzFile mZip; int mZipOffset; }; class FileSystem { public: typedef HashTable< String, FileInfo*, IKeyCmp, ValueDeleter<String, FileInfo*> > FileHash; typedef FileHash::Iterator Iterator; typedef List< unzFile > ZipList; typedef ZipList::Iterator ZipIterator; FileSystem(int hash_size) : mFiles(hash_size) { } FileSystem() : mFiles(256) { } ~FileSystem() { Clear(); } Iterator Begin() { return (mFiles.Begin()); } void Clear() { mFiles.Clear(); ZipIterator iter = mZipHandles.Begin(); while (iter != mZipHandles.End()) { unzClose(iter.value()); ++iter; } mZipHandles.Clear(); } Iterator End() { return (mFiles.End()); } void Grok(const char* path) { Clear(); Scan(path, false); // read in non-zips first Scan(path, true); } void GrokNonZips(const char* path) { Clear(); Scan(path, false); } bool Read(const String& name, char*& buffer, int& size) { FileInfo** info = (mFiles.Find(name)); if (!info) return (false); return ((*info)->Read(buffer, size)); } bool ReadTGA(const String& name, Texture& texture) { char* buffer; int size; if (!Read(name, buffer, size)) return (NULL); bool ok = (texture.LoadTGA((unsigned char*)buffer)); delete[] buffer; return (ok); } private: void ProcessZip(const char* path); void Scan(const char* path, bool zip_scan); FileHash mFiles; ZipList mZipHandles; }; #endif // __FILESYSTEM_H__ <file_sep>/VistaFix.cpp #include "Memstar.h" #include "Patch.h" #include "MultiPointer.h" namespace VistaFix { MultiPointer(ptrWindowsHookExA, 0x0084ca28, 0x0084ea30, 0x00864a48, 0x00885a48); NAKED void SetWindowsHookExAStub() { __asm { call ds : [GetCurrentThreadId] push eax push[esp + 0x10] push[esp + 0x10] push[esp + 0x10] call ds : [SetWindowsHookExA] retn 0x10 } } struct Init { Init() { if (VersionSnoop::GetVersion() == VERSION::vNotGame) { return; } Patch::Protect((u32*)ptrWindowsHookExA, 256, PAGE_READWRITE); Patch::ReplaceHook((u32*)ptrWindowsHookExA, &SetWindowsHookExAStub); } } VistaFixInit; }; // namespace VistaFix <file_sep>/GLOpcodes.h #ifndef __GLOPCODES_H__ #define __GLOPCODES_H__ #include "Fear.h" #include "FontManager.h" #include "Strings.h" #include "ScriptGL.h" #include "List.h" /* Construct in place: type *item = new( from ) type; */ INLINE void* __cdecl operator new(size_t size, void* in_place) { size; return (in_place); } INLINE void __cdecl operator delete(void* block, void* in_place) { block; in_place; } #define GLEX_DRAW ( 0 ) #define GLEX_CENTERED ( 1 ) #define GLEX_SCALED ( 2 ) #define GLEX_ROTATED ( 3 ) #define GLEX_FONT_PIXEL ( Font::Pixel ) #define GLEX_FONT_SMOOTH ( Font::Smooth ) /* Base opcode */ class GLOp { public: virtual void Execute() {}; virtual void Free() {}; }; /* More an op-stack than a compiler.. */ class GLCompiler { public: typedef List< char > OpcodeCache; typedef List< size_t > OpsIndex; GLCompiler::~GLCompiler() { Clear(); } void Clear() { OpsIndex::Iterator iter = (mOpsIndex.Begin()), end = (mOpsIndex.End()); while (iter != end) { ((GLOp*)&mCache[iter.value()])->Free(); ++iter; } // clear resets the item count without freeing memory mCache.Clear(); mOpsIndex.Clear(); } void Execute() { ScriptGL::mBeginCount = (0); OpsIndex::Iterator iter = (mOpsIndex.Begin()), end = (mOpsIndex.End()); while (iter != end) { ((GLOp*)&mCache[iter.value()])->Execute(); ++iter; } // an un-closed glBegin will royally screw things up if (ScriptGL::mBeginCount > 0) glEnd(); } template< class type > void Push(const type& op) { // abuse the vector of bytes for variable object size storage type* item = (type*)(mCache.Allocate(sizeof(op))); if (!item) { return; } new(item) type; // construct in place *item = (op); // need to use offsets instead of pointers because List reallocs can move // base pointer around. this means we need to re-align string2's as well mOpsIndex.Push(((char*)item - &mCache[0])); } private: OpcodeCache mCache; OpsIndex mOpsIndex; }; /* Opcodes */ class GLBegin : public GLOp { public: GLBegin() {} GLBegin(GLenum cap) : mCap(cap) {} virtual void Execute() { glBegin(mCap); ScriptGL::mBeginCount++; } private: GLenum mCap; }; class GLBindTexture : public GLOp { public: GLBindTexture() {} GLBindTexture(const char* tex) : mTexture(tex) {} virtual void Execute() { Texture* find = ScriptGL::FindTexture(mTexture.Realign().c_str()); if (find) find->BindToGraphicsCard(); } virtual void Free() { mTexture.Free(); } private: String2 mTexture; }; class GLBlendFunc : public GLOp { public: GLBlendFunc() {} GLBlendFunc(GLenum sfactor, GLenum dfactor) : mSource(sfactor), mDest(dfactor) {} virtual void Execute() { glBlendFunc(mSource, mDest); } private: GLenum mSource, mDest; }; class GLColor4ub : public GLOp { public: GLColor4ub() {} GLColor4ub(GLubyte r, GLubyte g, GLubyte b, GLubyte a) : mRGBA(RGBA(r, g, b, a)) {} virtual void Execute() { glColor4ub(mRGBA.r, mRGBA.g, mRGBA.b, mRGBA.a); } private: RGBA mRGBA; }; class GLDisable : public GLOp { public: GLDisable() {} GLDisable(GLenum cap) : mCap(cap) {} virtual void Execute() { glDisable(mCap); } private: GLenum mCap; }; class GLEnable : public GLOp { public: GLEnable() {} GLEnable(GLenum cap) : mCap(cap) {} virtual void Execute() { glEnable(mCap); } private: GLenum mCap; }; class GLEnd : public GLOp { public: GLEnd() {} virtual void Execute() { glEnd(); ScriptGL::mBeginCount--; } }; class GLTexCoord2f : public GLOp { public: GLTexCoord2f() {} GLTexCoord2f(GLfloat u, GLfloat v) : mU(u), mV(v) {} virtual void Execute() { glTexCoord2f(mU, mV); } private: float mU, mV; }; class GLTexEnvi : public GLOp { public: GLTexEnvi() {} GLTexEnvi(GLint param) : mParam(param) {} virtual void Execute() { glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, mParam); } private: int mParam; }; class GLVertex2i : public GLOp { public: GLVertex2i() {} GLVertex2i(GLint x, GLint y) : mX(x), mY(y) {} virtual void Execute() { glVertex2i(mX, mY); } private: GLint mX, mY; }; class GLDrawString : public GLOp { public: GLDrawString() {} GLDrawString(int x, int y, const char* str) : mX(x), mY(y) { mStr = str; } virtual void Execute() { if (!ScriptGL::mFont) return; ScriptGL::mFont->Draw(mStr.Realign().c_str(), mX, mY); } virtual void Free() { mStr.Free(); } private: int mX, mY; String2 mStr; }; class GLDrawTexture : public GLOp { public: GLDrawTexture() { } GLDrawTexture(const char* file, int mode, float x, float y, float sx, float sy, float r) : mMode(mode), mX(x), mY(y), mSX(sx), mSY(sy), mR(r) { mFile = file; } virtual void Execute() { Texture* find = (ScriptGL::FindTexture(mFile.Realign().c_str())); if (!find) return; glEnable(GL_TEXTURE_2D); if (mMode == GLEX_DRAW) { find->Draw(mX, mY); } else if (mMode == GLEX_CENTERED) { find->DrawCentered(mX, mY); } else if (mMode == GLEX_SCALED) { find->DrawScaled(mX, mY, mSX, mSY); } else if (mMode == GLEX_ROTATED) { find->DrawRotated(mX, mY, mSX, mSY, mR); } } virtual void Free() { mFile.Free(); } private: String2 mFile; int mMode; float mX, mY, mSX, mSY, mR; }; class GLRectangle : public GLOp { public: GLRectangle() {} GLRectangle(float x, float y, float w, float h) : mX(x), mY(y), mW(w), mH(h) {} virtual void Execute() { glBegin(GL_QUADS); glVertex2f(mX, mY); glVertex2f(mX + mW, mY); glVertex2f(mX + mW, mY + mH); glVertex2f(mX, mY + mH); glEnd(); } private: float mX, mY, mW, mH; }; class GLSetFont : public GLOp { public: GLSetFont() {} GLSetFont(const char* name, int height, Font::Rendering mode, int glow) : mHeight(height), mMode(mode), mGlow(glow), mName(name) { } virtual void Execute() { ScriptGL::mFont = FontManager::LoadFont(mName.Realign().c_str(), mHeight, mMode, mGlow); } private: String2 mName; int mHeight, mGlow; Font::Rendering mMode; }; #endif // __GLOPCODES_H__ <file_sep>/OpenGL_Pointers.cpp #include "OpenGL_Pointers.h" namespace OpenGLPtrs { MultiPointer(ptr_OPENGL_BOUND_TEXTURE, 0, 0, 0x0071a084, 0x0072A660); MultiPointer(ptr_OPENGL_SET_ALPHA_SOURCE, 0, 0, 0x0071a0f4, 0x0072A6E0); MultiPointer(ptr_OPENGL32_GLACCUM, 0, 0, 0x00856028, 0x0087710C); MultiPointer(ptr_OPENGL32_GLALPHAFUNC, 0, 0, 0x0085602C, 0x00877110); MultiPointer(ptr_OPENGL32_GLARETEXTURESRESIDENT, 0, 0, 0x00856030, 0x00877114); MultiPointer(ptr_OPENGL32_GLARRAYELEMENT, 0, 0, 0x00856034, 0x00877118); MultiPointer(ptr_OPENGL32_GLBEGIN, 0, 0, 0x00856038, 0x0087711C); MultiPointer(ptr_OPENGL32_GLBINDTEXTURE, 0, 0, 0x0085603C, 0x00877120); MultiPointer(ptr_OPENGL32_GLBITMAP, 0, 0, 0x00856040, 0x00877124); MultiPointer(ptr_OPENGL32_GLBLENDFUNC, 0, 0, 0x00856044, 0x00877128); MultiPointer(ptr_OPENGL32_GLCALLLIST, 0, 0, 0x00856048, 0x0087712C); MultiPointer(ptr_OPENGL32_GLCALLLISTS, 0, 0, 0x0085604C, 0x00877130); MultiPointer(ptr_OPENGL32_GLCLEAR, 0, 0, 0x00856050, 0x00877134); MultiPointer(ptr_OPENGL32_GLCLEARACCUM, 0, 0, 0x00856054, 0x00877138); MultiPointer(ptr_OPENGL32_GLCLEARCOLOR, 0, 0, 0x00856058, 0x0087713C); MultiPointer(ptr_OPENGL32_GLCLEARDEPTH, 0, 0, 0x0085605C, 0x00877140); MultiPointer(ptr_OPENGL32_GLCLEARINDEX, 0, 0, 0x00856060, 0x00877144); MultiPointer(ptr_OPENGL32_GLCLEARSTENCIL, 0, 0, 0x00856064, 0x00877148); MultiPointer(ptr_OPENGL32_GLCLIPPLANE, 0, 0, 0x00856068, 0x0087714C); MultiPointer(ptr_OPENGL32_GLCOLOR3B, 0, 0, 0x0085606C, 0x00877150); MultiPointer(ptr_OPENGL32_GLCOLOR3BV, 0, 0, 0x00856070, 0x00877154); MultiPointer(ptr_OPENGL32_GLCOLOR3D, 0, 0, 0x00856074, 0x00877158); MultiPointer(ptr_OPENGL32_GLCOLOR3DV, 0, 0, 0x00856078, 0x0087715C); MultiPointer(ptr_OPENGL32_GLCOLOR3F, 0, 0, 0x0085607C, 0x00877160); MultiPointer(ptr_OPENGL32_GLCOLOR3FV, 0, 0, 0x00856080, 0x00877164); MultiPointer(ptr_OPENGL32_GLCOLOR3I, 0, 0, 0x00856084, 0x00877168); MultiPointer(ptr_OPENGL32_GLCOLOR3IV, 0, 0, 0x00856088, 0x0087716C); MultiPointer(ptr_OPENGL32_GLCOLOR3S, 0, 0, 0x0085608C, 0x00877170); MultiPointer(ptr_OPENGL32_GLCOLOR3SV, 0, 0, 0x00856090, 0x00877174); MultiPointer(ptr_OPENGL32_GLCOLOR3UB, 0, 0, 0x00856094, 0x00877178); MultiPointer(ptr_OPENGL32_GLCOLOR3UBV, 0, 0, 0x00856098, 0x0087717C); MultiPointer(ptr_OPENGL32_GLCOLOR3UI, 0, 0, 0x0085609C, 0x00877180); MultiPointer(ptr_OPENGL32_GLCOLOR3UIV, 0, 0, 0x008560A0, 0x00877184); MultiPointer(ptr_OPENGL32_GLCOLOR3US, 0, 0, 0x008560A4, 0x00877188); MultiPointer(ptr_OPENGL32_GLCOLOR3USV, 0, 0, 0x008560A8, 0x0087718C); MultiPointer(ptr_OPENGL32_GLCOLOR4B, 0, 0, 0x008560AC, 0x00877190); MultiPointer(ptr_OPENGL32_GLCOLOR4BV, 0, 0, 0x008560B0, 0x00877194); MultiPointer(ptr_OPENGL32_GLCOLOR4D, 0, 0, 0x008560B4, 0x00877198); MultiPointer(ptr_OPENGL32_GLCOLOR4DV, 0, 0, 0x008560B8, 0x0087719C); MultiPointer(ptr_OPENGL32_GLCOLOR4F, 0, 0, 0x008560BC, 0x008771A0); MultiPointer(ptr_OPENGL32_GLCOLOR4FV, 0, 0, 0x008560C0, 0x008771A4); MultiPointer(ptr_OPENGL32_GLCOLOR4I, 0, 0, 0x008560C4, 0x008771A8); MultiPointer(ptr_OPENGL32_GLCOLOR4IV, 0, 0, 0x008560C8, 0x008771AC); MultiPointer(ptr_OPENGL32_GLCOLOR4S, 0, 0, 0x008560CC, 0x008771B0); MultiPointer(ptr_OPENGL32_GLCOLOR4SV, 0, 0, 0x008560D0, 0x008771B4); MultiPointer(ptr_OPENGL32_GLCOLOR4UB, 0, 0, 0x008560D4, 0x008771B8); MultiPointer(ptr_OPENGL32_GLCOLOR4UBV, 0, 0, 0x008560D8, 0x008771BC); MultiPointer(ptr_OPENGL32_GLCOLOR4UI, 0, 0, 0x008560DC, 0x008771C0); MultiPointer(ptr_OPENGL32_GLCOLOR4UIV, 0, 0, 0x008560E0, 0x008771C4); MultiPointer(ptr_OPENGL32_GLCOLOR4US, 0, 0, 0x008560E4, 0x008771C8); MultiPointer(ptr_OPENGL32_GLCOLOR4USV, 0, 0, 0x008560E8, 0x008771CC); MultiPointer(ptr_OPENGL32_GLCOLORMASK, 0, 0, 0x008560EC, 0x008771D0); MultiPointer(ptr_OPENGL32_GLCOLORMATERIAL, 0, 0, 0x008560F0, 0x008771D4); MultiPointer(ptr_OPENGL32_GLCOLORPOINTER, 0, 0, 0x008560F4, 0x008771D8); MultiPointer(ptr_OPENGL32_GLCOPYPIXELS, 0, 0, 0x008560F8, 0x008771DC); MultiPointer(ptr_OPENGL32_GLCOPYTEXIMAGE1D, 0, 0, 0x008560FC, 0x008771E0); MultiPointer(ptr_OPENGL32_GLCOPYTEXIMAGE2D, 0, 0, 0x00856100, 0x008771E4); MultiPointer(ptr_OPENGL32_GLCOPYTEXSUBIMAGE1D, 0, 0, 0x00856104, 0x008771E8); MultiPointer(ptr_OPENGL32_GLCOPYTEXSUBIMAGE2D, 0, 0, 0x00856108, 0x008771EC); MultiPointer(ptr_OPENGL32_GLCULLFACE, 0, 0, 0x0085610C, 0x008771F0); MultiPointer(ptr_OPENGL32_GLDELETELISTS, 0, 0, 0x00856110, 0x008771F4); MultiPointer(ptr_OPENGL32_GLDELETETEXTURES, 0, 0, 0x00856114, 0x008771F8); MultiPointer(ptr_OPENGL32_GLDEPTHFUNC, 0, 0, 0x00856118, 0x008771FC); MultiPointer(ptr_OPENGL32_GLDEPTHMASK, 0, 0, 0x0085611C, 0x00877200); MultiPointer(ptr_OPENGL32_GLDEPTHRANGE, 0, 0, 0x00856120, 0x00877204); MultiPointer(ptr_OPENGL32_GLDISABLE, 0, 0, 0x00856124, 0x00877208); MultiPointer(ptr_OPENGL32_GLDISABLECLIENTSTATE, 0, 0, 0x00856128, 0x0087720C); MultiPointer(ptr_OPENGL32_GLDRAWARRAYS, 0, 0, 0x0085612C, 0x00877210); MultiPointer(ptr_OPENGL32_GLDRAWBUFFER, 0, 0, 0x00856130, 0x00877214); MultiPointer(ptr_OPENGL32_GLDRAWELEMENTS, 0, 0, 0x00856134, 0x00877218); MultiPointer(ptr_OPENGL32_GLDRAWPIXELS, 0, 0, 0x00856138, 0x0087721C); MultiPointer(ptr_OPENGL32_GLEDGEFLAG, 0, 0, 0x0085613C, 0x00877220); MultiPointer(ptr_OPENGL32_GLEDGEFLAGPOINTER, 0, 0, 0x00856140, 0x00877224); MultiPointer(ptr_OPENGL32_GLEDGEFLAGV, 0, 0, 0x00856144, 0x00877228); MultiPointer(ptr_OPENGL32_GLENABLE, 0, 0, 0x00856148, 0x0087722C); MultiPointer(ptr_OPENGL32_GLENABLECLIENTSTATE, 0, 0, 0x0085614C, 0x00877230); MultiPointer(ptr_OPENGL32_GLEND, 0, 0, 0x00856150, 0x00877234); MultiPointer(ptr_OPENGL32_GLENDLIST, 0, 0, 0x00856154, 0x00877238); MultiPointer(ptr_OPENGL32_GLEVALCOORD1D, 0, 0, 0x00856158, 0x0087723C); MultiPointer(ptr_OPENGL32_GLEVALCOORD1DV, 0, 0, 0x0085615C, 0x00877240); MultiPointer(ptr_OPENGL32_GLEVALCOORD1F, 0, 0, 0x00856160, 0x00877244); MultiPointer(ptr_OPENGL32_GLEVALCOORD1FV, 0, 0, 0x00856164, 0x00877248); MultiPointer(ptr_OPENGL32_GLEVALCOORD2D, 0, 0, 0x00856168, 0x0087724C); MultiPointer(ptr_OPENGL32_GLEVALCOORD2DV, 0, 0, 0x0085616C, 0x00877250); MultiPointer(ptr_OPENGL32_GLEVALCOORD2F, 0, 0, 0x00856170, 0x00877254); MultiPointer(ptr_OPENGL32_GLEVALCOORD2FV, 0, 0, 0x00856174, 0x00877258); MultiPointer(ptr_OPENGL32_GLEVALMESH1, 0, 0, 0x00856178, 0x0087725C); MultiPointer(ptr_OPENGL32_GLEVALMESH2, 0, 0, 0x0085617C, 0x00877260); MultiPointer(ptr_OPENGL32_GLEVALPOINT1, 0, 0, 0x00856180, 0x00877264); MultiPointer(ptr_OPENGL32_GLEVALPOINT2, 0, 0, 0x00856184, 0x00877268); MultiPointer(ptr_OPENGL32_GLFEEDBACKBUFFER, 0, 0, 0x00856188, 0x0087726C); MultiPointer(ptr_OPENGL32_GLFINISH, 0, 0, 0x0085618C, 0x00877270); MultiPointer(ptr_OPENGL32_GLFLUSH, 0, 0, 0x00856190, 0x00877274); MultiPointer(ptr_OPENGL32_GLFOGF, 0, 0, 0x00856194, 0x00877278); MultiPointer(ptr_OPENGL32_GLFOGFV, 0, 0, 0x00856198, 0x0087727C); MultiPointer(ptr_OPENGL32_GLFOGI, 0, 0, 0x0085619C, 0x00877280); MultiPointer(ptr_OPENGL32_GLFOGIV, 0, 0, 0x008561A0, 0x00877284); MultiPointer(ptr_OPENGL32_GLFRONTFACE, 0, 0, 0x008561A4, 0x00877288); MultiPointer(ptr_OPENGL32_GLFRUSTUM, 0, 0, 0x008561A8, 0x0087728C); MultiPointer(ptr_OPENGL32_GLGENLISTS, 0, 0, 0x008561AC, 0x00877290); MultiPointer(ptr_OPENGL32_GLGENTEXTURES, 0, 0, 0x008561B0, 0x00877294); MultiPointer(ptr_OPENGL32_GLGETBOOLEANV, 0, 0, 0x008561B4, 0x00877298); MultiPointer(ptr_OPENGL32_GLGETCLIPPLANE, 0, 0, 0x008561B8, 0x0087729C); MultiPointer(ptr_OPENGL32_GLGETDOUBLEV, 0, 0, 0x008561BC, 0x008772A0); MultiPointer(ptr_OPENGL32_GLGETERROR, 0, 0, 0x008561C0, 0x008772A4); MultiPointer(ptr_OPENGL32_GLGETFLOATV, 0, 0, 0x008561C4, 0x008772A8); MultiPointer(ptr_OPENGL32_GLGETINTEGERV, 0, 0, 0x008561C8, 0x008772AC); MultiPointer(ptr_OPENGL32_GLGETLIGHTFV, 0, 0, 0x008561CC, 0x008772B0); MultiPointer(ptr_OPENGL32_GLGETLIGHTIV, 0, 0, 0x008561D0, 0x008772B4); MultiPointer(ptr_OPENGL32_GLGETMAPDV, 0, 0, 0x008561D4, 0x008772B8); MultiPointer(ptr_OPENGL32_GLGETMAPFV, 0, 0, 0x008561D8, 0x008772BC); MultiPointer(ptr_OPENGL32_GLGETMAPIV, 0, 0, 0x008561DC, 0x008772C0); MultiPointer(ptr_OPENGL32_GLGETMATERIALFV, 0, 0, 0x008561E0, 0x008772C4); MultiPointer(ptr_OPENGL32_GLGETMATERIALIV, 0, 0, 0x008561E4, 0x008772C8); MultiPointer(ptr_OPENGL32_GLGETPIXELMAPFV, 0, 0, 0x008561E8, 0x008772CC); MultiPointer(ptr_OPENGL32_GLGETPIXELMAPUIV, 0, 0, 0x008561EC, 0x008772D0); MultiPointer(ptr_OPENGL32_GLGETPIXELMAPUSV, 0, 0, 0x008561F0, 0x008772D4); MultiPointer(ptr_OPENGL32_GLGETPOINTERV, 0, 0, 0x008561F4, 0x008772D8); MultiPointer(ptr_OPENGL32_GLGETPOLYGONSTIPPLE, 0, 0, 0x008561F8, 0x008772DC); MultiPointer(ptr_OPENGL32_GLGETSTRING, 0, 0, 0x008561FC, 0x008772E0); MultiPointer(ptr_OPENGL32_GLGETTEXENVFV, 0, 0, 0x00856200, 0x008772E4); MultiPointer(ptr_OPENGL32_GLGETTEXENVIV, 0, 0, 0x00856204, 0x008772E8); MultiPointer(ptr_OPENGL32_GLGETTEXGENDV, 0, 0, 0x00856208, 0x008772EC); MultiPointer(ptr_OPENGL32_GLGETTEXGENFV, 0, 0, 0x0085620C, 0x008772F0); MultiPointer(ptr_OPENGL32_GLGETTEXGENIV, 0, 0, 0x00856210, 0x008772F4); MultiPointer(ptr_OPENGL32_GLGETTEXIMAGE, 0, 0, 0x00856214, 0x008772F8); MultiPointer(ptr_OPENGL32_GLGETTEXLEVELPARAMETERFV, 0, 0, 0x00856218, 0x008772FC); MultiPointer(ptr_OPENGL32_GLGETTEXLEVELPARAMETERIV, 0, 0, 0x0085621C, 0x00877300); MultiPointer(ptr_OPENGL32_GLGETTEXPARAMETERFV, 0, 0, 0x00856220, 0x00877304); MultiPointer(ptr_OPENGL32_GLGETTEXPARAMETERIV, 0, 0, 0x00856224, 0x00877308); MultiPointer(ptr_OPENGL32_GLHINT, 0, 0, 0x00856228, 0x0087730C); MultiPointer(ptr_OPENGL32_GLINDEXMASK, 0, 0, 0x0085622C, 0x00877310); MultiPointer(ptr_OPENGL32_GLINDEXPOINTER, 0, 0, 0x00856230, 0x00877314); MultiPointer(ptr_OPENGL32_GLINDEXD, 0, 0, 0x00856234, 0x00877318); MultiPointer(ptr_OPENGL32_GLINDEXDV, 0, 0, 0x00856238, 0x0087731C); MultiPointer(ptr_OPENGL32_GLINDEXF, 0, 0, 0x0085623C, 0x00877320); MultiPointer(ptr_OPENGL32_GLINDEXFV, 0, 0, 0x00856240, 0x00877324); MultiPointer(ptr_OPENGL32_GLINDEXI, 0, 0, 0x00856244, 0x00877328); MultiPointer(ptr_OPENGL32_GLINDEXIV, 0, 0, 0x00856248, 0x0087732C); MultiPointer(ptr_OPENGL32_GLINDEXS, 0, 0, 0x0085624C, 0x00877330); MultiPointer(ptr_OPENGL32_GLINDEXSV, 0, 0, 0x00856250, 0x00877334); MultiPointer(ptr_OPENGL32_GLINDEXUB, 0, 0, 0x00856254, 0x00877338); MultiPointer(ptr_OPENGL32_GLINDEXUBV, 0, 0, 0x00856258, 0x0087733C); MultiPointer(ptr_OPENGL32_GLINITNAMES, 0, 0, 0x0085625C, 0x00877340); MultiPointer(ptr_OPENGL32_GLINTERLEAVEDARRAYS, 0, 0, 0x00856260, 0x00877344); MultiPointer(ptr_OPENGL32_GLISENABLED, 0, 0, 0x00856264, 0x00877348); MultiPointer(ptr_OPENGL32_GLISLIST, 0, 0, 0x00856268, 0x0087734C); MultiPointer(ptr_OPENGL32_GLISTEXTURE, 0, 0, 0x0085626C, 0x00877350); MultiPointer(ptr_OPENGL32_GLLIGHTMODELF, 0, 0, 0x00856270, 0x00877354); MultiPointer(ptr_OPENGL32_GLLIGHTMODELFV, 0, 0, 0x00856274, 0x00877358); MultiPointer(ptr_OPENGL32_GLLIGHTMODELI, 0, 0, 0x00856278, 0x0087735C); MultiPointer(ptr_OPENGL32_GLLIGHTMODELIV, 0, 0, 0x0085627C, 0x00877360); MultiPointer(ptr_OPENGL32_GLLIGHTF, 0, 0, 0x00856280, 0x00877364); MultiPointer(ptr_OPENGL32_GLLIGHTFV, 0, 0, 0x00856284, 0x00877368); MultiPointer(ptr_OPENGL32_GLLIGHTI, 0, 0, 0x00856288, 0x0087736C); MultiPointer(ptr_OPENGL32_GLLIGHTIV, 0, 0, 0x0085628C, 0x00877370); MultiPointer(ptr_OPENGL32_GLLINESTIPPLE, 0, 0, 0x00856290, 0x00877374); MultiPointer(ptr_OPENGL32_GLLINEWIDTH, 0, 0, 0x00856294, 0x00877378); MultiPointer(ptr_OPENGL32_GLLISTBASE, 0, 0, 0x00856298, 0x0087737C); MultiPointer(ptr_OPENGL32_GLLOADIDENTITY, 0, 0, 0x0085629C, 0x00877380); MultiPointer(ptr_OPENGL32_GLLOADMATRIXD, 0, 0, 0x008562A0, 0x00877384); MultiPointer(ptr_OPENGL32_GLLOADMATRIXF, 0, 0, 0x008562A4, 0x00877388); MultiPointer(ptr_OPENGL32_GLLOADNAME, 0, 0, 0x008562A8, 0x0087738C); MultiPointer(ptr_OPENGL32_GLLOGICOP, 0, 0, 0x008562AC, 0x00877390); MultiPointer(ptr_OPENGL32_GLMAP1D, 0, 0, 0x008562B0, 0x00877394); MultiPointer(ptr_OPENGL32_GLMAP1F, 0, 0, 0x008562B4, 0x00877398); MultiPointer(ptr_OPENGL32_GLMAP2D, 0, 0, 0x008562B8, 0x0087739C); MultiPointer(ptr_OPENGL32_GLMAP2F, 0, 0, 0x008562BC, 0x008773A0); MultiPointer(ptr_OPENGL32_GLMAPGRID1D, 0, 0, 0x008562C0, 0x008773A4); MultiPointer(ptr_OPENGL32_GLMAPGRID1F, 0, 0, 0x008562C4, 0x008773A8); MultiPointer(ptr_OPENGL32_GLMAPGRID2D, 0, 0, 0x008562C8, 0x008773AC); MultiPointer(ptr_OPENGL32_GLMAPGRID2F, 0, 0, 0x008562CC, 0x008773B0); MultiPointer(ptr_OPENGL32_GLMATERIALF, 0, 0, 0x008562D0, 0x008773B4); MultiPointer(ptr_OPENGL32_GLMATERIALFV, 0, 0, 0x008562D4, 0x008773B8); MultiPointer(ptr_OPENGL32_GLMATERIALI, 0, 0, 0x008562D8, 0x008773BC); MultiPointer(ptr_OPENGL32_GLMATERIALIV, 0, 0, 0x008562DC, 0x008773C0); MultiPointer(ptr_OPENGL32_GLMATRIXMODE, 0, 0, 0x008562E0, 0x008773C4); MultiPointer(ptr_OPENGL32_GLMULTMATRIXD, 0, 0, 0x008562E4, 0x008773C8); MultiPointer(ptr_OPENGL32_GLMULTMATRIXF, 0, 0, 0x008562E8, 0x008773CC); MultiPointer(ptr_OPENGL32_GLNEWLIST, 0, 0, 0x008562EC, 0x008773D0); MultiPointer(ptr_OPENGL32_GLNORMAL3B, 0, 0, 0x008562F0, 0x008773D4); MultiPointer(ptr_OPENGL32_GLNORMAL3BV, 0, 0, 0x008562F4, 0x008773D8); MultiPointer(ptr_OPENGL32_GLNORMAL3D, 0, 0, 0x008562F8, 0x008773DC); MultiPointer(ptr_OPENGL32_GLNORMAL3DV, 0, 0, 0x008562FC, 0x008773E0); MultiPointer(ptr_OPENGL32_GLNORMAL3F, 0, 0, 0x00856300, 0x008773E4); MultiPointer(ptr_OPENGL32_GLNORMAL3FV, 0, 0, 0x00856304, 0x008773E8); MultiPointer(ptr_OPENGL32_GLNORMAL3I, 0, 0, 0x00856308, 0x008773EC); MultiPointer(ptr_OPENGL32_GLNORMAL3IV, 0, 0, 0x0085630C, 0x008773F0); MultiPointer(ptr_OPENGL32_GLNORMAL3S, 0, 0, 0x00856310, 0x008773F4); MultiPointer(ptr_OPENGL32_GLNORMAL3SV, 0, 0, 0x00856314, 0x008773F8); MultiPointer(ptr_OPENGL32_GLNORMALPOINTER, 0, 0, 0x00856318, 0x008773FC); MultiPointer(ptr_OPENGL32_GLORTHO, 0, 0, 0x0085631C, 0x00877400); MultiPointer(ptr_OPENGL32_GLPASSTHROUGH, 0, 0, 0x00856320, 0x00877404); MultiPointer(ptr_OPENGL32_GLPIXELMAPFV, 0, 0, 0x00856324, 0x00877408); MultiPointer(ptr_OPENGL32_GLPIXELMAPUIV, 0, 0, 0x00856328, 0x0087740C); MultiPointer(ptr_OPENGL32_GLPIXELMAPUSV, 0, 0, 0x0085632C, 0x00877410); MultiPointer(ptr_OPENGL32_GLPIXELSTOREF, 0, 0, 0x00856330, 0x00877414); MultiPointer(ptr_OPENGL32_GLPIXELSTOREI, 0, 0, 0x00856334, 0x00877418); MultiPointer(ptr_OPENGL32_GLPIXELTRANSFERF, 0, 0, 0x00856338, 0x0087741C); MultiPointer(ptr_OPENGL32_GLPIXELTRANSFERI, 0, 0, 0x0085633C, 0x00877420); MultiPointer(ptr_OPENGL32_GLPIXELZOOM, 0, 0, 0x00856340, 0x00877424); MultiPointer(ptr_OPENGL32_GLPOINTSIZE, 0, 0, 0x00856344, 0x00877428); MultiPointer(ptr_OPENGL32_GLPOLYGONMODE, 0, 0, 0x00856348, 0x0087742C); MultiPointer(ptr_OPENGL32_GLPOLYGONOFFSET, 0, 0, 0x0085634C, 0x00877430); MultiPointer(ptr_OPENGL32_GLPOLYGONSTIPPLE, 0, 0, 0x00856350, 0x00877434); MultiPointer(ptr_OPENGL32_GLPOPATTRIB, 0, 0, 0x00856354, 0x00877438); MultiPointer(ptr_OPENGL32_GLPOPCLIENTATTRIB, 0, 0, 0x00856358, 0x0087743C); MultiPointer(ptr_OPENGL32_GLPOPMATRIX, 0, 0, 0x0085635C, 0x00877440); MultiPointer(ptr_OPENGL32_GLPOPNAME, 0, 0, 0x00856360, 0x00877444); MultiPointer(ptr_OPENGL32_GLPRIORITIZETEXTURES, 0, 0, 0x00856364, 0x00877448); MultiPointer(ptr_OPENGL32_GLPUSHATTRIB, 0, 0, 0x00856368, 0x0087744C); MultiPointer(ptr_OPENGL32_GLPUSHCLIENTATTRIB, 0, 0, 0x0085636C, 0x00877450); MultiPointer(ptr_OPENGL32_GLPUSHMATRIX, 0, 0, 0x00856370, 0x00877454); MultiPointer(ptr_OPENGL32_GLPUSHNAME, 0, 0, 0x00856374, 0x00877458); MultiPointer(ptr_OPENGL32_GLRASTERPOS2D, 0, 0, 0x00856378, 0x0087745C); MultiPointer(ptr_OPENGL32_GLRASTERPOS2DV, 0, 0, 0x0085637C, 0x00877460); MultiPointer(ptr_OPENGL32_GLRASTERPOS2F, 0, 0, 0x00856380, 0x00877464); MultiPointer(ptr_OPENGL32_GLRASTERPOS2FV, 0, 0, 0x00856384, 0x00877468); MultiPointer(ptr_OPENGL32_GLRASTERPOS2I, 0, 0, 0x00856388, 0x0087746C); MultiPointer(ptr_OPENGL32_GLRASTERPOS2IV, 0, 0, 0x0085638C, 0x00877470); MultiPointer(ptr_OPENGL32_GLRASTERPOS2S, 0, 0, 0x00856390, 0x00877474); MultiPointer(ptr_OPENGL32_GLRASTERPOS2SV, 0, 0, 0x00856394, 0x00877478); MultiPointer(ptr_OPENGL32_GLRASTERPOS3D, 0, 0, 0x00856398, 0x0087747C); MultiPointer(ptr_OPENGL32_GLRASTERPOS3DV, 0, 0, 0x0085639C, 0x00877480); MultiPointer(ptr_OPENGL32_GLRASTERPOS3F, 0, 0, 0x008563A0, 0x00877484); MultiPointer(ptr_OPENGL32_GLRASTERPOS3FV, 0, 0, 0x008563A4, 0x00877488); MultiPointer(ptr_OPENGL32_GLRASTERPOS3I, 0, 0, 0x008563A8, 0x0087748C); MultiPointer(ptr_OPENGL32_GLRASTERPOS3IV, 0, 0, 0x008563AC, 0x00877490); MultiPointer(ptr_OPENGL32_GLRASTERPOS3S, 0, 0, 0x008563B0, 0x00877494); MultiPointer(ptr_OPENGL32_GLRASTERPOS3SV, 0, 0, 0x008563B4, 0x00877498); MultiPointer(ptr_OPENGL32_GLRASTERPOS4D, 0, 0, 0x008563B8, 0x0087749C); MultiPointer(ptr_OPENGL32_GLRASTERPOS4DV, 0, 0, 0x008563BC, 0x008774A0); MultiPointer(ptr_OPENGL32_GLRASTERPOS4F, 0, 0, 0x008563C0, 0x008774A4); MultiPointer(ptr_OPENGL32_GLRASTERPOS4FV, 0, 0, 0x008563C4, 0x008774A8); MultiPointer(ptr_OPENGL32_GLRASTERPOS4I, 0, 0, 0x008563C8, 0x008774AC); MultiPointer(ptr_OPENGL32_GLRASTERPOS4IV, 0, 0, 0x008563CC, 0x008774B0); MultiPointer(ptr_OPENGL32_GLRASTERPOS4S, 0, 0, 0x008563D0, 0x008774B4); MultiPointer(ptr_OPENGL32_GLRASTERPOS4SV, 0, 0, 0x008563D4, 0x008774B8); MultiPointer(ptr_OPENGL32_GLREADBUFFER, 0, 0, 0x008563D8, 0x008774BC); MultiPointer(ptr_OPENGL32_GLREADPIXELS, 0, 0, 0x008563DC, 0x008774C0); MultiPointer(ptr_OPENGL32_GLRECTD, 0, 0, 0x008563E0, 0x008774C4); MultiPointer(ptr_OPENGL32_GLRECTDV, 0, 0, 0x008563E4, 0x008774C8); MultiPointer(ptr_OPENGL32_GLRECTF, 0, 0, 0x008563E8, 0x008774CC); MultiPointer(ptr_OPENGL32_GLRECTFV, 0, 0, 0x008563EC, 0x008774D0); MultiPointer(ptr_OPENGL32_GLRECTI, 0, 0, 0x008563F0, 0x008774D4); MultiPointer(ptr_OPENGL32_GLRECTIV, 0, 0, 0x008563F4, 0x008774D8); MultiPointer(ptr_OPENGL32_GLRECTS, 0, 0, 0x008563F8, 0x008774DC); MultiPointer(ptr_OPENGL32_GLRECTSV, 0, 0, 0x008563FC, 0x008774E0); MultiPointer(ptr_OPENGL32_GLRENDERMODE, 0, 0, 0x00856400, 0x008774E4); MultiPointer(ptr_OPENGL32_GLROTATED, 0, 0, 0x00856404, 0x008774E8); MultiPointer(ptr_OPENGL32_GLROTATEF, 0, 0, 0x00856408, 0x008774EC); MultiPointer(ptr_OPENGL32_GLSCALED, 0, 0, 0x0085640C, 0x008774F0); MultiPointer(ptr_OPENGL32_GLSCALEF, 0, 0, 0x00856410, 0x008774F4); MultiPointer(ptr_OPENGL32_GLSCISSOR, 0, 0, 0x00856414, 0x008774F8); MultiPointer(ptr_OPENGL32_GLSELECTBUFFER, 0, 0, 0x00856418, 0x008774FC); MultiPointer(ptr_OPENGL32_GLSHADEMODEL, 0, 0, 0x0085641C, 0x00877500); MultiPointer(ptr_OPENGL32_GLSTENCILFUNC, 0, 0, 0x00856420, 0x00877504); MultiPointer(ptr_OPENGL32_GLSTENCILMASK, 0, 0, 0x00856424, 0x00877508); MultiPointer(ptr_OPENGL32_GLSTENCILOP, 0, 0, 0x00856428, 0x0087750C); MultiPointer(ptr_OPENGL32_GLTEXCOORD1D, 0, 0, 0x0085642C, 0x00877510); MultiPointer(ptr_OPENGL32_GLTEXCOORD1DV, 0, 0, 0x00856430, 0x00877514); MultiPointer(ptr_OPENGL32_GLTEXCOORD1F, 0, 0, 0x00856434, 0x00877518); MultiPointer(ptr_OPENGL32_GLTEXCOORD1FV, 0, 0, 0x00856438, 0x0087751C); MultiPointer(ptr_OPENGL32_GLTEXCOORD1I, 0, 0, 0x0085643C, 0x00877520); MultiPointer(ptr_OPENGL32_GLTEXCOORD1IV, 0, 0, 0x00856440, 0x00877524); MultiPointer(ptr_OPENGL32_GLTEXCOORD1S, 0, 0, 0x00856444, 0x00877528); MultiPointer(ptr_OPENGL32_GLTEXCOORD1SV, 0, 0, 0x00856448, 0x0087752C); MultiPointer(ptr_OPENGL32_GLTEXCOORD2D, 0, 0, 0x0085644C, 0x00877530); MultiPointer(ptr_OPENGL32_GLTEXCOORD2DV, 0, 0, 0x00856450, 0x00877534); MultiPointer(ptr_OPENGL32_GLTEXCOORD2F, 0, 0, 0x00856454, 0x00877538); MultiPointer(ptr_OPENGL32_GLTEXCOORD2FV, 0, 0, 0x00856458, 0x0087753C); MultiPointer(ptr_OPENGL32_GLTEXCOORD2I, 0, 0, 0x0085645C, 0x00877540); MultiPointer(ptr_OPENGL32_GLTEXCOORD2IV, 0, 0, 0x00856460, 0x00877544); MultiPointer(ptr_OPENGL32_GLTEXCOORD2S, 0, 0, 0x00856464, 0x00877548); MultiPointer(ptr_OPENGL32_GLTEXCOORD2SV, 0, 0, 0x00856468, 0x0087754C); MultiPointer(ptr_OPENGL32_GLTEXCOORD3D, 0, 0, 0x0085646C, 0x00877550); MultiPointer(ptr_OPENGL32_GLTEXCOORD3DV, 0, 0, 0x00856470, 0x00877554); MultiPointer(ptr_OPENGL32_GLTEXCOORD3F, 0, 0, 0x00856474, 0x00877558); MultiPointer(ptr_OPENGL32_GLTEXCOORD3FV, 0, 0, 0x00856478, 0x0087755C); MultiPointer(ptr_OPENGL32_GLTEXCOORD3I, 0, 0, 0x0085647C, 0x00877560); MultiPointer(ptr_OPENGL32_GLTEXCOORD3IV, 0, 0, 0x00856480, 0x00877564); MultiPointer(ptr_OPENGL32_GLTEXCOORD3S, 0, 0, 0x00856484, 0x00877568); MultiPointer(ptr_OPENGL32_GLTEXCOORD3SV, 0, 0, 0x00856488, 0x0087756C); MultiPointer(ptr_OPENGL32_GLTEXCOORD4D, 0, 0, 0x0085648C, 0x00877570); MultiPointer(ptr_OPENGL32_GLTEXCOORD4DV, 0, 0, 0x00856490, 0x00877574); MultiPointer(ptr_OPENGL32_GLTEXCOORD4F, 0, 0, 0x00856494, 0x00877578); MultiPointer(ptr_OPENGL32_GLTEXCOORD4FV, 0, 0, 0x00856498, 0x0087757C); MultiPointer(ptr_OPENGL32_GLTEXCOORD4I, 0, 0, 0x0085649C, 0x00877580); MultiPointer(ptr_OPENGL32_GLTEXCOORD4IV, 0, 0, 0x008564A0, 0x00877584); MultiPointer(ptr_OPENGL32_GLTEXCOORD4S, 0, 0, 0x008564A4, 0x00877588); MultiPointer(ptr_OPENGL32_GLTEXCOORD4SV, 0, 0, 0x008564A8, 0x0087758C); MultiPointer(ptr_OPENGL32_GLTEXCOORDPOINTER, 0, 0, 0x008564AC, 0x00877590); MultiPointer(ptr_OPENGL32_GLTEXENVF, 0, 0, 0x008564B0, 0x00877594); MultiPointer(ptr_OPENGL32_GLTEXENVFV, 0, 0, 0x008564B4, 0x00877598); MultiPointer(ptr_OPENGL32_GLTEXENVI, 0, 0, 0x008564B8, 0x0087759C); MultiPointer(ptr_OPENGL32_GLTEXENVIV, 0, 0, 0x008564BC, 0x008775A0); MultiPointer(ptr_OPENGL32_GLTEXGEND, 0, 0, 0x008564C0, 0x008775A4); MultiPointer(ptr_OPENGL32_GLTEXGENDV, 0, 0, 0x008564C4, 0x008775A8); MultiPointer(ptr_OPENGL32_GLTEXGENF, 0, 0, 0x008564C8, 0x008775AC); MultiPointer(ptr_OPENGL32_GLTEXGENFV, 0, 0, 0x008564CC, 0x008775B0); MultiPointer(ptr_OPENGL32_GLTEXGENI, 0, 0, 0x008564D0, 0x008775B4); MultiPointer(ptr_OPENGL32_GLTEXGENIV, 0, 0, 0x008564D4, 0x008775B8); MultiPointer(ptr_OPENGL32_GLTEXIMAGE1D, 0, 0, 0x008564D8, 0x008775BC); MultiPointer(ptr_OPENGL32_GLTEXIMAGE2D, 0, 0, 0x008564DC, 0x008775C0); MultiPointer(ptr_OPENGL32_GLTEXPARAMETERF, 0, 0, 0x008564E0, 0x008775C4); MultiPointer(ptr_OPENGL32_GLTEXPARAMETERFV, 0, 0, 0x008564E4, 0x008775C8); MultiPointer(ptr_OPENGL32_GLTEXPARAMETERI, 0, 0, 0x008564E8, 0x008775CC); MultiPointer(ptr_OPENGL32_GLTEXPARAMETERIV, 0, 0, 0x008564EC, 0x008775D0); MultiPointer(ptr_OPENGL32_GLTEXSUBIMAGE1D, 0, 0, 0x008564F0, 0x008775D4); MultiPointer(ptr_OPENGL32_GLTEXSUBIMAGE2D, 0, 0, 0x008564F4, 0x008775D8); MultiPointer(ptr_OPENGL32_GLTRANSLATED, 0, 0, 0x008564F8, 0x008775DC); MultiPointer(ptr_OPENGL32_GLTRANSLATEF, 0, 0, 0x008564FC, 0x008775E0); MultiPointer(ptr_OPENGL32_GLVERTEX2D, 0, 0, 0x00856500, 0x008775E4); MultiPointer(ptr_OPENGL32_GLVERTEX2DV, 0, 0, 0x00856504, 0x008775E8); MultiPointer(ptr_OPENGL32_GLVERTEX2F, 0, 0, 0x00856508, 0x008775EC); MultiPointer(ptr_OPENGL32_GLVERTEX2FV, 0, 0, 0x0085650C, 0x008775F0); MultiPointer(ptr_OPENGL32_GLVERTEX2I, 0, 0, 0x00856510, 0x008775F4); MultiPointer(ptr_OPENGL32_GLVERTEX2IV, 0, 0, 0x00856514, 0x008775F8); MultiPointer(ptr_OPENGL32_GLVERTEX2S, 0, 0, 0x00856518, 0x008775FC); MultiPointer(ptr_OPENGL32_GLVERTEX2SV, 0, 0, 0x0085651C, 0x00877600); MultiPointer(ptr_OPENGL32_GLVERTEX3D, 0, 0, 0x00856520, 0x00877604); MultiPointer(ptr_OPENGL32_GLVERTEX3DV, 0, 0, 0x00856524, 0x00877608); MultiPointer(ptr_OPENGL32_GLVERTEX3F, 0, 0, 0x00856528, 0x0087760C); MultiPointer(ptr_OPENGL32_GLVERTEX3FV, 0, 0, 0x0085652C, 0x00877610); MultiPointer(ptr_OPENGL32_GLVERTEX3I, 0, 0, 0x00856530, 0x00877614); MultiPointer(ptr_OPENGL32_GLVERTEX3IV, 0, 0, 0x00856534, 0x00877618); MultiPointer(ptr_OPENGL32_GLVERTEX3S, 0, 0, 0x00856538, 0x0087761C); MultiPointer(ptr_OPENGL32_GLVERTEX3SV, 0, 0, 0x0085653C, 0x00877620); MultiPointer(ptr_OPENGL32_GLVERTEX4D, 0, 0, 0x00856540, 0x00877624); MultiPointer(ptr_OPENGL32_GLVERTEX4DV, 0, 0, 0x00856544, 0x00877628); MultiPointer(ptr_OPENGL32_GLVERTEX4F, 0, 0, 0x00856548, 0x0087762C); MultiPointer(ptr_OPENGL32_GLVERTEX4FV, 0, 0, 0x0085654C, 0x00877630); MultiPointer(ptr_OPENGL32_GLVERTEX4I, 0, 0, 0x00856550, 0x00877634); MultiPointer(ptr_OPENGL32_GLVERTEX4IV, 0, 0, 0x00856554, 0x00877638); MultiPointer(ptr_OPENGL32_GLVERTEX4S, 0, 0, 0x00856558, 0x0087763C); MultiPointer(ptr_OPENGL32_GLVERTEX4SV, 0, 0, 0x0085655C, 0x00877640); MultiPointer(ptr_OPENGL32_GLVERTEXPOINTER, 0, 0, 0x00856560, 0x00877644); MultiPointer(ptr_OPENGL32_GLVIEWPORT, 0, 0, 0x00856564, 0x00877648); MultiPointer(ptr_OPENGL32_WGLCHOOSEPIXELFORMAT, 0, 0, 0x00856568, 0x0087764C); MultiPointer(ptr_OPENGL32_WGLCOPYCONTEXT, 0, 0, 0x0085656C, 0x00877650); MultiPointer(ptr_OPENGL32_WGLCREATECONTEXT, 0, 0, 0x00856570, 0x00877654); MultiPointer(ptr_OPENGL32_WGLCREATELAYERCONTEXT, 0, 0, 0x00856574, 0x00877658); MultiPointer(ptr_OPENGL32_WGLDELETECONTEXT, 0, 0, 0x00856578, 0x0087765C); MultiPointer(ptr_OPENGL32_WGLDESCRIBELAYERPLANE, 0, 0, 0x0085657C, 0x00877660); MultiPointer(ptr_OPENGL32_WGLDESCRIBEPIXELFORMAT, 0, 0, 0x00856580, 0x00877664); MultiPointer(ptr_OPENGL32_WGLGETCURRENTCONTEXT, 0, 0, 0x00856584, 0x00877668); MultiPointer(ptr_OPENGL32_WGLGETCURRENTDC, 0, 0, 0x00856588, 0x0087766C); MultiPointer(ptr_OPENGL32_WGLGETDEFAULTPROCADDRESS, 0, 0, 0x0085658C, 0x00877670); MultiPointer(ptr_OPENGL32_WGLGETLAYERPALETTEENTRIES, 0, 0, 0x00856590, 0x00877674); MultiPointer(ptr_OPENGL32_WGLGETPIXELFORMAT, 0, 0, 0x00856594, 0x00877678); MultiPointer(ptr_OPENGL32_WGLGETPROCADDRESS, 0, 0, 0x00856598, 0x0087767C); MultiPointer(ptr_OPENGL32_WGLMAKECURRENT, 0, 0, 0x0085659C, 0x00877680); MultiPointer(ptr_OPENGL32_WGLREALIZELAYERPALETTE, 0, 0, 0x008565A0, 0x00877684); MultiPointer(ptr_OPENGL32_WGLSETLAYERPALETTEENTRIES, 0, 0, 0x008565A4, 0x00877688); MultiPointer(ptr_OPENGL32_WGLSETPIXELFORMAT, 0, 0, 0x008565A8, 0x0087768C); MultiPointer(ptr_OPENGL32_WGLSHARELISTS, 0, 0, 0x008565AC, 0x00877690); MultiPointer(ptr_OPENGL32_WGLSWAPBUFFERS, 0, 0, 0x008565B0, 0x00877694); MultiPointer(ptr_OPENGL32_WGLSWAPLAYERBUFFERS, 0, 0, 0x008565B4, 0x00877698); MultiPointer(ptr_OPENGL32_WGLUSEFONTBITMAPSA, 0, 0, 0x008565B8, 0x0087769C); MultiPointer(ptr_OPENGL32_WGLUSEFONTBITMAPSW, 0, 0, 0x008565BC, 0x008776A0); MultiPointer(ptr_OPENGL32_WGLUSEFONTOUTLINESA, 0, 0, 0x008565C0, 0x008776A4); MultiPointer(ptr_OPENGL32_WGLUSEFONTOUTLINESW, 0, 0, 0x008565C4, 0x008776A8); };<file_sep>/FileSystem.cpp #include "FileSystem.h" void FileSystem::ProcessZip(const char* path) { unzFile zip = (unzOpen(path)); if (!zip) return; mZipHandles.Push(zip); if (unzGoToFirstFile(zip) == UNZ_OK) { String2 key; do { unz_file_info file_info; char name[512]; unzGetCurrentFileInfo(zip, &file_info, name, 511, NULL, 0, NULL, 0); char* slashf = (strrchr(name, '/')), * slashb = (strrchr(name, '\\')); char* base = (slashf) ? (slashf + 1) : (slashb) ? (slashb + 1) : name; key = base; // Con::Echo( " -- %s %s", name, mFiles.InsertUnique( name, file ) ? "ACCEPTED" : "REJECTED" ); ZipFile* fileinfo = new ZipFile(zip, file_info.uncompressed_size, unzGetOffset(zip)); if (!fileinfo || !mFiles.InsertUnique(key, fileinfo)) delete fileinfo; } while (unzGoToNextFile(zip) == UNZ_OK); } } void FileSystem::Scan(const char* path, bool zip_scan) { String2 search_path; search_path.Assign("%s/*", path); WIN32_FIND_DATA find_file; HANDLE find = FindFirstFile(search_path.c_str(), &find_file); if (find == INVALID_HANDLE_VALUE) { return; } String2 key, item_path; do { item_path.Assign("%s/%s", path, find_file.cFileName); if (find_file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if ((strcmp(find_file.cFileName, ".") != 0) && (strcmp(find_file.cFileName, "..") != 0)) { Scan(item_path.c_str(), zip_scan); } } else { if (zip_scan) { if (stristr(find_file.cFileName, ".zip")) ProcessZip(item_path.c_str()); } else { key = find_file.cFileName; DiskFile* fileinfo = new DiskFile(item_path); if (!fileinfo || !mFiles.InsertUnique(key, fileinfo)) delete fileinfo; } } } while (FindNextFile(find, &find_file) != 0); FindClose(find); } <file_sep>/Fear.h #ifndef __FEAR_H__ #define __FEAR_H__ #include "Memstar.h" #include <math.h> #include <string.h> #define PAD_PREFIX() p #define PAD( size ) char PAD_PREFIX()__LINE__[(size)]; template< class type > class Vector { public: class Iterator { public: Iterator(type* item) : mElement(item) {} type& value() { return (*mElement); } type& operator* () { return (*mElement); } Iterator& operator++ () { mElement++; return (*this); } bool operator== (const Iterator& b) { return (mElement == b.mElement); } bool operator!= (const Iterator& b) { return (mElement != b.mElement); } private: type* mElement; }; Iterator Begin() { return Iterator(mElements); } Iterator End() { return Iterator(mElements + mItems); } int mItems, mSize, mFlags; type* mElements; }; namespace Fear { struct Object { u32 vft; // 0x0000 const char* name; // 0x0004 PAD(0x003c - (0x0004 + 0x004)); u32 id; // 0x003c PAD(0x004c - (0x003c + 0x004)); }; /* 0x4c */ struct Sim : public Object { PAD(0x0080 - (0x004c + 0x000)); f32 Time; // 0x0080 template<class T> T* findObject(u32 id) { if (!this) return NULL; __asm { mov eax, this push eax mov edx, [id] mov ecx, [eax] call[ecx + 0x68] pop this } } template<class T> T* findObject(const char* nameOrId); f32 getTime(); static Sim* Client(); }; struct SimSet : public Object { Vector<Object*> mSet; // 0x0050 typedef Vector<Object*>::Iterator Iterator; Iterator Begin() { return(mSet.Begin()); } Iterator End() { return(mSet.End()); } }; struct Sky : public Object { PAD(0x00b8 - (0x004c + 0x000)); Vector3f skyColor; //0x00b8 Vector3f hazeColor; //0x00c4 PAD(0x011c - (0x00c4 + 0x00c)); f32 rotation; //0x011c PAD(0x0124 - (0x011c + 0x004)); f32 size; //0x0124 void calcPoints(); }; struct GFXBitmap { PAD(0x0010 - (0x0000 + 0x000)); u32 width; //0x0010 u32 height; //0x0014 PAD(0x0030 - (0x0014 + 0x004)); u32 flags; //0x0030 u32 paletteIdx; //0x0034 u8* bitmapData; //0x0038 u8* bitmapMips[7]; //0x0058 void* hidden; //0x005c u32 mipLevels; //0x0060 }; Sky* findSky(); struct OpenGLState { void* _glMultiTexCoord2fvARB; // 0x00 void* _glMultiTexCoord4fvARB; // 0x04 void* _glActiveTextureARB; // 0x08 u32 a; // 0x0c u32 b; // 0x10 u32 TEXTURE_2D0_ARB; // 0x14 u32 TEXTURE_2D1_ARB; // 0x18 u32 TEXTURE_ENV0_ARB; // 0x1c u32 TEXTURE_ENV1_ARB; // 0x20 u32 BLEND_SRC; // 0x24 u32 BLEND_DST; // 0x28 u32 ALPHA_TEST; // 0x2c u32 DEPTH_TEST; // 0x30 u32 e; // 0x34 u32 DEPTH_FUNC; // 0x38 u32 f; // 0x3c u32 TEXTURE_UNIT_ACTIVE; // 0x40 u32 GL_BOUNDTEXTURE0; // 0x44 u32 GL_BOUNDTEXTURE1; // 0x48 }; struct GraphicsAdapter { }; struct GridFile { PAD(0x0058 - (0x0000 + 0x000)); void* gridBlockArray; // 0x0058 PAD(0x0064 - (0x0058 + 0x004)); const char* dtfName; // 0x0064 inline u16* getMaterialBlock(u32 block) { __asm { mov eax, [this] mov eax, [eax + 0x58] mov edx, [block] lea eax, [eax + edx * 4] mov eax, [eax] mov eax, [eax] and eax, eax jz __not_loaded mov eax, [eax + 0x14] mov eax, [eax + 0x40] __not_loaded: } } }; struct SimTerrain : public Object { PAD(0x057c - (0x004c + 0x000)); GridFile* gf; // 0x057c PAD(0x0584 - (0x057c + 0x004)); void* terrainFile; // 0x0584 }; struct OpenGLTextureCache { struct MPCache { u8 data[256 * 4]; u8 dataTransparent[256 * 4]; u16 dataPacked[256]; u16 dataPackedTransparent[256]; u32 packedType; u32 packedTransparentType; s32 paletteIndex; }; PAD(0x0230 - (0x0000 + 0x000)); MPCache multiPalettes[16]; MPCache& getPalette(s32 index) { for (u32 i = 0; i < 16; i++) if (multiPalettes[i].paletteIndex == index) return multiPalettes[i]; return multiPalettes[0]; } void pbmpToRGBA(u8* in, RGBA* out, size_t bytes, s32 index) { RGBA* pal = (RGBA*)getPalette(index).data; for (size_t i = 0; i < bytes; i++, in++, out++) *out = pal[*in]; } }; struct OpenGLSurface : public Object { PAD(0x0158 - (0x004c + 0x000)); OpenGLTextureCache* textureCache; // 0x0158 }; bool getScreenDimensions(Vector2i* dim); struct SimGuiCtrl : public Object { PAD(0x019c - (0x004c + 0x000)); Vector2i pos; //0x019c Vector2i dimensions; //0x01a4 }; struct Herc : public Object { }; struct PlayerPSC : public Object { PAD(0x005c - (0x004c + 0x000)); Object* orbitCamera; //0x005c Object* flyCamera; //0x0060 Object* easyCamera; //0x0064 Object* editCamera; //0x0068 Object* splineCamera; //0x006c Herc* player; //0x0070 }; PlayerPSC* findPSC(); }; #endif // __FEAR_H__<file_sep>/Console.h #ifndef __CONSOLE_H__ #define __CONSOLE_H__ #include "Memstar.h" #include "StringConversions.h" #include "List.h" #include "MultiPointer.h" enum VariableType { VAR_bool = 1, VAR_int = 2, VAR_float = 3, VAR_double = 4, /* VAR_zeroToOne = 5, */ /* VAR_vector3F = 6 */ }; namespace Console { void addFunction(const char* name, void* cb); void addVariable(const char* name, const void* address, const VariableType var_type); void echo(const char* fmt, ...); const char* execFunction(u32 argc, char* function, ...); void eval(const char* cmd); bool functionExists(const char* name); const char* getVariable(const char* name); void setVariable(const char* name, const char* value); extern List<const char*> variables, functions; struct VariableConstructor { VariableConstructor(const char* scripted, void* address, VariableType type) : mName(scripted), mAddress(address), mType(type), mNext(mFirst) { mFirst = (this); } static void Process() { VariableConstructor* node = mFirst; for (; node; node = node->mNext) { addVariable(node->mName, node->mAddress, node->mType); variables.Push(node->mName); } } protected: const char* mName; void* mAddress; VariableType mType; VariableConstructor* mNext; static VariableConstructor* mFirst; }; struct ConsoleConstructor { ConsoleConstructor(const char* scripted, void* cb) : mName(scripted), mCallback(cb), mNext(mFirst) { mFirst = (this); } static void Process() { ConsoleConstructor* node = mFirst; for (; node; node = node->mNext) { addFunction(node->mName, node->mCallback); functions.Push(node->mName); } } protected: const char* mName; void* mCallback; ConsoleConstructor* mNext; int mPrivilegeLevel; static ConsoleConstructor* mFirst; }; }; // namespace Console #define BuiltInVariable( __scripted__, __type__, __name__, __default__ ) \ __type__ __name__ = __default__; \ static const Console::VariableConstructor vc##__name__( __scripted__, &__name__, VAR_##__type__ ) #define BuiltInFunction( __scripted__, __name__ ) \ const char * __stdcall __name__##bin(s32 argc, const char *self, const char *argv[]); \ NAKED const char *__name__##stub() { \ __asm { mov eax, [esp+4] } \ __asm { add eax, 4 } \ __asm { push eax } \ __asm { sub eax, 4 } \ __asm { push dword ptr [eax] } \ __asm { dec ecx } \ __asm { push ecx } \ __asm { call __name__##bin } \ __asm { retn 4 } \ } \ static const Console::ConsoleConstructor cc##__name__( __scripted__, __name__##stub ); \ const char * __stdcall __name__##bin(s32 argc, const char *self, const char *argv[]) #endif // __CONSOLE_H__ <file_sep>/FontManager.cpp #include "FontManager.h" #include "HashTable.h" #include "FileSystem.h" #include "OpenGL.h" #include "Callback.h" #include "Console.h" namespace FontManager { struct Key { Key() { } Key(const char* name, int pixel_height, Font::Rendering mode, int glow_radius) : mPixelHeight(pixel_height), mGlowRadius(glow_radius), mMode(mode) { strncpy(mName, name, 63); mName[63] = '\x0'; } bool operator== (const Key& b) const { return ((mPixelHeight == b.mPixelHeight) && (mGlowRadius == b.mGlowRadius) && (mMode == b.mMode) && (strcmp(mName, b.mName) == 0)); } char mName[64]; int mPixelHeight, mGlowRadius; Font::Rendering mMode; }; struct KeyUtil { unsigned int operator() (const Key& a) const { return (HashBytes((const unsigned char*)&a, sizeof(a))); } bool operator() (const Key& a, const Key& b) const { return (a == b); } }; typedef HashTable< Key, Font*, KeyUtil, ValueDeleter<Key, Font*>, KeyUtil > Hash; typedef Hash::Iterator Iterator; FileSystem mFiles(32); Hash mFonts(32); char mBuffer[256]; int mLastGarbageCollect = (GetTickCount()); void Close() { FileSystem::Iterator iter = mFiles.Begin(), end = mFiles.End(); while (iter != end) { if (stristr(iter.value()->Path(), ".ttf")) RemoveFontResource(iter.value()->Path()); // unregister from windows ++iter; } mFiles.Clear(); mFonts.Clear(); } /* Check for unused fonts every 5 seconds */ void GarbageCollect(bool endframe) { int ticks = (GetTickCount()); if (ticks - mLastGarbageCollect < 5000) return; mLastGarbageCollect = (ticks); Iterator iter = mFonts.Begin(), end = mFonts.End(); while (iter != end) { // dont gc the last font that was set if (ticks - iter.value()->LastUsed() > 30000) { Console::echo("FontManager: Garbage collecting %s", iter.key().mName); mFonts.Delete(iter); } else { ++iter; } } } Font* LoadFont(const char* name, int pixel_height, Font::Rendering mode, int glow_radius) { Key id(name, pixel_height, mode, glow_radius); Font** find = (mFonts.Find(id)), * font = (NULL); if (!find) { font = new Font(); if (!font || !font->Create(name, pixel_height, mode, glow_radius) || !mFonts.Insert(id, font)) { delete font; font = (NULL); } } else { font = (*find); } if (font) font->UpdateLastUsed(); return (font); } void Open() { Close(); mFiles.GrokNonZips("memstar/Fonts"); FileSystem::Iterator iter = mFiles.Begin(), end = mFiles.End(); while (iter != end) { // register the custom fonts with windows if (stristr(iter.value()->Path(), ".ttf")) AddFontResource(iter.value()->Path()); ++iter; } } struct Init { Init() { Callback::attach(Callback::OnEndframe, GarbageCollect); Open(); } ~Init() { Close(); } } init; }; // namespace FontManager<file_sep>/MultiPointer.h #ifndef __MULTIPOINTER_H__ #define __MULTIPOINTER_H__ #include "Memstar.h" #include "VersionSnoop.h" struct MultiPtr { u32 Pointers[4]; MultiPtr(u32 v0, u32 v2, u32 v3, u32 v4) { Pointers[v001000] = v0; Pointers[v001002] = v2; Pointers[v001003] = v3; Pointers[v001004] = v4; } u32 Get() { if (ResolvedPointer == vUnknown) { VERSION ver = VersionSnoop::GetVersion(); if (ver <= v001004 && ver >= v001000) { ResolvedPointer = Pointers[ver]; } } return ResolvedPointer; } private: u32 ResolvedPointer = vUnknown; }; #define MultiPointer(__name__, __val1__, __val2__, __val3__, __val4__) \ MultiPtr mptr_##__name__ = { __val1__, __val2__, __val3__, __val4__ }; \ static const u32 __name__ = mptr_##__name__##.Get() #define MultiPointer_Ext(__name__) \ extern const u32 __name__ #endif<file_sep>/Replacer.h #ifndef __TEXTUREREPLACER_H__ #define __TEXTUREREPLACER_H__ #include "Texture.h" struct Original { bool operator< (const Original& b) const { return (mCrc < b.mCrc); } unsigned int mCrc; char* mName; }; namespace Replacer { const String* FindOriginalName(unsigned int texture_crc); TextureWithMips* FindReplacement(const String* name); void Forget(); TextureWithMips* LastMatchedTexture(); bool LastScanWasReplaceable(); void Open(); }; #endif // __REPLACER_H__<file_sep>/VersionSnoop.cpp #include "Console.h" #include "Memstar.h" #include "VersionSnoop.h" #include "Callback.h" namespace VersionSnoop { const int MIN_VERSIONSNOOP_IMAGE_SIZE = 1400000; // 1.4 Mib VersionInfo version[4] = { { 0x006C3BA7, //PTR 0x61337365, //Value - "es3a" VERSION::v001000 // Version }, { 0x006c5fdc, //PTR 0x2, //Value VERSION::v001002 // Version }, { 0x006d726c, //PTR 0x3, //Value VERSION::v001003 // Version }, { 0x006e7384, //PTR 0x4, //Value VERSION::v001004 // Version } }; MODULEINFO info; LPMODULEINFO GetExecutingModuleInfo() { if (info.SizeOfImage == NULL) { HANDLE handle = GetCurrentProcess(); HMODULE module = GetModuleHandleW(NULL); GetModuleInformation(handle, module, &info, sizeof(info)); } return &info; } wchar_t* GetVersionString(VERSION in) { if (in == VERSION::vUnknown) { return VersionStrings[4]; } return VersionStrings[in]; } char* GetVersionCString(VERSION in) { if (in == VERSION::vUnknown) { return VersionCStrings[4]; } return VersionCStrings[in]; } VERSION GetVersion() { if (Version == VERSION::vUnknown) { return versionSnoop(); } return Version; } VERSION versionSnoop() { GetExecutingModuleInfo(); if (info.SizeOfImage <= MIN_VERSIONSNOOP_IMAGE_SIZE) { return VERSION::vNotGame; } for (int i = 0; i < 4; i++) { versionPtr = (DWORD*)version[i].PTR; if (*versionPtr == version[i].Value) { Version = version[i].Version; return Version; } } return VERSION::vUnknown; } struct Init { Init() { VERSION v = versionSnoop(); #ifdef _DEBUG wchar_t message[100]; swprintf_s(message, L"Detected Starsisge exectuable version: %s", GetVersionString(v)); MessageBoxW(NULL, message, L"Detection info", MB_OK | MB_ICONINFORMATION); #endif } } Init; };<file_sep>/Lib/List.h #ifndef __LIST_H__ #define __LIST_H__ #include "Memstar.h" #include "Sort.h" template< class type > class List { public: class Iterator { public: Iterator( type *item ) : mItem(item) {} type &value() { return ( *mItem ); } type *pointer() { return ( mItem ); } type &operator* () { return ( *mItem ); } Iterator &operator++ () { ++mItem; return ( *this ); } Iterator &operator-- () { --mItem; return ( *this ); } bool operator== ( const Iterator &b ) { return ( mItem == b.mItem ); } bool operator!= ( const Iterator &b ) { return ( mItem != b.mItem ); } bool operator>= ( const Iterator &b ) { return ( mItem >= b.mItem ); } bool operator<= ( const Iterator &b ) { return ( mItem <= b.mItem ); } bool operator> ( const Iterator &b ) { return ( mItem > b.mItem ); } bool operator< ( const Iterator &b ) { return ( mItem < b.mItem ); } private: type *mItem; }; List( ) { mHead = ( NULL ); mItemCount = 0; mCurAlloc = 0; } List( size_t reserve ) { mHead = ( NULL ); mItemCount = 0; mCurAlloc = 0; Resize( reserve ); } ~List( ) { Free( ); } void Clear( ) { mItemCount = 0; } void Free( ) { if ( !mHead ) return; Clear( ); free( mHead ); mHead = NULL; mCurAlloc = 0; } bool Add( const type &item ) { return ( Push( item ) ); } Iterator Begin( ) const { return ( Iterator( mHead ) ); } type *Allocate( size_t amount ) { if ( !ResizeUp( mItemCount + amount ) ) return ( NULL ); type *start = ( &mHead[ mItemCount ] ); mItemCount += ( amount ); return ( start ); } void Compact( ) { Resize( mItemCount ); } size_t Count( ) const { return ( mItemCount ); } void Delete( Iterator &iter ) { type *tmp = ( iter.pointer() ); if ( tmp < mHead || tmp >= mHead + mItemCount ) return; if ( tmp < ( mHead + mItemCount - 1 ) ) memcpy( tmp, mHead + mItemCount - 1, sizeof( type ) ); ResizeDown( --mItemCount ); } void Delete( const type &item ) { Delete( Find( item ) ); } Iterator End( ) const { return ( Iterator( mHead + mItemCount ) ); } Iterator Find( const type &item ) const { for ( size_t i = 0; i < mItemCount; i++ ) { if ( mHead[ i ] == item ) return ( Iterator( mHead + i ) ); } return ( End( ) ); } type *First( ) { if ( !mItemCount ) return ( NULL ); return ( mHead ); } type *Last( ) { if ( !mItemCount ) return ( NULL ); return ( mHead + mItemCount - 1 ); } type *New( ) { if ( !ResizeUp( mItemCount + 1 ) ) return ( NULL ); return ( &mHead[ mItemCount++ ] ); } type Pop( ) { if ( !mItemCount ) return ( NULL ); type item = mHead[ mItemCount - 1 ]; mItemCount -= 1; return ( item ); } bool Push( const type &item ) { if ( !ResizeUp( mItemCount + 1 ) ) return ( false ); mHead[ mItemCount++ ] = item; return ( true ); } void Release( size_t amount ) { mItemCount -= ( amount ); ResizeDown( mItemCount ); } bool Resize( size_t new_size ) { type *tmp = (type *)realloc( mHead, new_size * sizeof( type ) ); if ( tmp ) { mHead = tmp; mCurAlloc = new_size; } return ( tmp != NULL ); } template< class Compare > void Sort( Compare comp ) { IntroSort_Sort( mHead, mHead + mItemCount - 1, comp ); } void Sort( ) { Sort( Less<type>() ); } bool ResizeUp( size_t new_size ) { if ( new_size <= mCurAlloc ) return ( true ); return ( Resize( new_size << 1 ) ); } bool ResizeDown( size_t new_size ) { if ( new_size >= ( mCurAlloc >> 3 ) ) return ( true ); size_t resize = ( mCurAlloc >> 2 ); return ( Resize( resize ) ); } type &operator[]( const size_t index ) const { return ( *( mHead + index ) ); } type &operator[]( const size_t index ) { return ( *( mHead + index ) ); } protected: type *mHead; size_t mItemCount, mCurAlloc; }; #endif // __LIST_H__<file_sep>/Lib/Strings.h #ifndef __STRINGS_H__ #define __STRINGS_H__ #include "Memstar.h" #define Snprintf _snprintf #define SnprintfVarArg _vsnprintf #define __STRING2_SIZE__ ( 64 ) /* String is default String class String2 has a __STRING2_SIZE__ byte buffer on the stack so you can use it for small items without malloc'ing. For things like finding keys in a hash table, use String2() explicitly to construct your char* values to avoid memory allocation */ inline size_t smallestpow2( size_t amt, size_t smallest ) { if ( amt < smallest ) return ( smallest ); size_t val = 1; while ( val < amt ) val <<= 1; return ( val ); } class String { public: String( ) : mStr(NULL), mLen(0), mAlloc(0), mNoFree(true) { } String( const char *str ) : mStr(NULL), mLen(0), mAlloc(0), mNoFree(true) { Assign( strlen( str ), str ); } String( const char *str, size_t size ) : mStr(NULL), mLen(0), mAlloc(0), mNoFree(true) { Assign( size, str ); } String( const String &str ) : mStr(NULL), mLen(0), mAlloc(0), mNoFree(true) { Assign( str.Strlen(), str.mStr ); } ~String( ) { if ( !mNoFree ) free( mStr ); mStr = ( NULL ); } String &Append( const char *fmt, ... ) { // returns # of bytes not counting the null va_list args; va_start( args, fmt ); size_t req_bytes = ( SnprintfVarArg( NULL, 0, fmt, args ) + 1 ); va_end( args ); char stack[ 1024 ], *buffer = stack; if ( req_bytes > 1024 ) buffer = new char[ req_bytes ]; if ( buffer ) { va_start( args, fmt ); SnprintfVarArg( buffer, req_bytes, fmt, args ); va_end( args ); Append( req_bytes - 1, buffer ); if ( buffer != stack ) delete[] buffer; } return ( *this ); } String &Append( char ch ) { if ( Resize( mLen + 1 ) ) { mStr[ mLen++ ] = ( ch ); AppendNull( ); } return ( *this ); } String &Append( size_t len, const char *str ) { bool aliased = ( IsAliased( str ) ); size_t offs = aliased ? ( str - mStr ) : 0; if ( Resize( mLen + len ) ) { if ( aliased ) str = ( mStr + offs ); memcpy( mStr + mLen, str, len ); mLen += ( len ); AppendNull( ); } return ( *this ); } String &Assign( const char *fmt, ... ) { // returns # of bytes not counting the null va_list args; va_start( args, fmt ); size_t req_bytes = ( SnprintfVarArg( NULL, 0, fmt, args ) + 1 ); va_end( args ); char stack[ 1024 ], *buffer = stack; if ( req_bytes > 1024 ) buffer = new char[ req_bytes ]; if ( buffer ) { va_start( args, fmt ); SnprintfVarArg( buffer, req_bytes, fmt, args ); va_end( args ); Assign( req_bytes - 1, buffer ); if ( buffer != stack ) delete[] buffer; } return ( *this ); } String &Assign( char c ) { if ( Resize( mLen + 1 ) ) { mStr[ 0 ] = c; mLen = ( 1 ); AppendNull( ); } return ( *this ); } String &Assign( size_t len, const char *str ) { // assignment aliasing isn't a problem because resize never shrinks if ( Resize( len ) ) { memmove( mStr, str, len ); mLen = ( len ); AppendNull( ); } return ( *this ); } const char *c_str( ) const { return ( mStr ); } String &Clear( ) { mLen = ( 0 ); AppendNull( ); return ( *this ); } String &Compact( ) { size_t tmp = ( mAlloc ); mAlloc = ( 0 ); if ( !Resize( mLen ) ) mAlloc = ( tmp ); return ( *this ); } void Free( ) { if ( !mNoFree ) free( mStr ); mStr = ( NULL ); mLen = ( 0 ); mAlloc = ( 0 ); } bool Equals( const char *b ) const { return ( strcmp( mStr, b ) == 0 ); } bool Equals( const String &b ) const { return ( Equals( b.c_str() ) ); } bool IEquals( const char *b ) const { return ( _stricmp( mStr, b ) == 0 ); } bool IEquals( const String &b ) const { return ( IEquals( b.c_str() ) ); } size_t Length( ) const { return ( mStr ) ? ( Strlen( ) + 1 ) : 0; } String Left( size_t len ) const { return ( Mid( 0, len ) ); } String Right( size_t len ) const { size_t end = ( Strlen( ) ); return ( Mid( end - len, end ) ); } String Mid( size_t start, size_t end ) const { size_t last = ( Strlen( ) ); start = ( start < 0 ) ? 0 : ( start >= last ) ? last : start; end = ( end < 0 ) ? 0 : ( end >= last ) ? last : end; size_t len = ( end - start ); return ( String( mStr + start, len ) ); } size_t Strlen( ) const { return ( mLen ); } // [] char operator[]( size_t index ) const { if ( ( index >= 0 ) && ( index < Strlen( ) ) ) return ( mStr[ index ] ); return ( 0 ); } // = void operator= ( char c ) { Assign( c ); } void operator= ( int i ) { Assign( "%d", i ); } void operator= ( float f ) { Assign( "%f", f ); } void operator= ( const char *str ) { Assign( strlen( str ), str ); } void operator= ( const String &str ) { Assign( str.Strlen(), str.mStr ); } // += void operator+= ( char c ) { Append( c ); } void operator+= ( const char *str ) { Append( strlen( str ), str ); } void operator+= ( const String &str ) { Append( str.Strlen(), str.mStr ); } // == bool operator== ( const char *str ) const { return ( Equals( str ) ); } bool operator== ( const String &str ) const { return ( Equals( str ) ); } protected: // for String2 String( size_t stack_alloc, char *stack_ptr ) : mStr(stack_ptr), mLen(0), mAlloc(stack_alloc), mNoFree(true) { } void AppendNull( ) { if ( mStr ) mStr[ mLen ] = '\x0'; } bool IsAliased( const char *str ) { return ( ( str >= mStr ) && str <= ( mStr + mLen ) ); } virtual bool Resize( size_t new_size ) { // add the implicit null ++new_size; if ( mAlloc >= new_size ) return ( true ); new_size = ( smallestpow2( new_size, 8 ) ); char *tmp = (char *)realloc( mStr, new_size ); if ( tmp ) { mStr = ( tmp ); mAlloc = ( new_size ); mNoFree = ( false ); } return ( tmp != NULL ); } protected: char *mStr; size_t mLen, mAlloc; bool mNoFree; }; class String2 : public String { public: String2( ) : String( __STRING2_SIZE__, mStack ) { AppendNull( ); } String2( const char *str ) : String( __STRING2_SIZE__, mStack ) { Assign( strlen( str ), str ); } String2( const char *str, size_t size ) : String( __STRING2_SIZE__, mStack ) { Assign( size, str ); } String2( const String &str ) : String( __STRING2_SIZE__, mStack ) { Assign( str.Strlen(), str.c_str() ); } void Free( ) { if ( !mNoFree ) free( mStr ); mStr = ( mStack ); mNoFree = ( true ); } /* very evil: if the string object physically moves, call re-align to set mStr back to mStack if needed, otherwise mStr could point to bad memory. ex: List<>'s of mString2's which may get realloc'd */ String2 &Realign( ) { if ( mNoFree ) mStr = ( mStack ); return ( *this ); } void operator= ( char c ) { Assign( c ); } void operator= ( int i ) { Assign( "%d", i ); } void operator= ( float f ) { Assign( "%f", f ); } void operator= ( const char *str ) { Assign( strlen( str ), str ); } void operator= ( const String &str ) { Assign( str.Strlen(), str.c_str() ); } void operator= ( const String2 &str ) { Assign( str.Strlen(), str.c_str() ); } protected: virtual bool Resize( size_t new_size ) { // add the implicit null ++new_size; if ( mAlloc >= new_size ) return ( true ); // swap to heap based memory new_size = ( smallestpow2( new_size, 8 ) ); char *tmp = (char *)realloc( ( mStr == mStack ) ? NULL : mStr, new_size ); if ( tmp ) { if ( mStr == mStack ) { memcpy( tmp, mStack, Strlen() ); tmp[ mLen ] = '\x0'; } mNoFree = ( false ); mStr = ( tmp ); mAlloc = ( new_size ); } return ( tmp != NULL ); } // DooM III trick with stack based buffer for small strings to avoid memory allocation char mStack[ __STRING2_SIZE__ ]; }; /* Horribly bloated, but no other way around this. Append() with format strings would be better to use if you didn't mind losing fancy syntax tricks */ String operator+ ( const String &str, char c ); String operator+ ( const String &str, int i ); String operator+ ( const String &str, float f ); String operator+ ( const String &str, char *s ); String operator+ ( const String &str, const String &str2 ); String operator+ ( const String &str, const String2 &str2 ); String2 operator+ ( const String2 &str, char c ); String2 operator+ ( const String2 &str, int i ); String2 operator+ ( const String2 &str, float f ); String2 operator+ ( const String2 &str, char *s ); String2 operator+ ( const String2 &str, const String &str2 ); String2 operator+ ( const String2 &str, const String2 &str2 ); void htoa(const char *src, char *dst, int src_len, int max_dst); int atoh( const char *src, char *dst, int max_dst ); bool atohhl(const char *src, unsigned int *dst); const char *stristr(const char *haystack, const char *needle); #endif // __STRING_H__<file_sep>/Terrain.cpp #include "Fear.h" #include "Console.h" #include "OpenGL.h" #include "Hash.h" #include "Texture.h" #include "List.h" #include "Patch.h" #include "Replacer.h" #include "Callback.h" #include <stdio.h> namespace Replacer { extern bool prefShowMatchedTextures; } namespace Terrain { #define GridBlock_Material_Plain ( 0 ) #define GridBlock_Material_Rotate ( 1 ) #define GridBlock_Material_FlipX ( 2 ) #define GridBlock_Material_FlipY ( 4 ) #define GridSquare_Pinned ( 4 ) MultiPointer(ptr_OPENGL_FLUSH_TEXTURE_CACHE_VFT, 0, 0, 0, 0x0072A738); struct HiddenTexture { TextureWithMips* replacement, * originalUpsampled; u32 stamp; Fear::GFXBitmap* parent; }; BuiltInVariable("pref::memstarTerrain", bool, prefMemstarTerrain, true); RGBA canvas_1x1[1 * 1]; RGBA canvas_2x2[2 * 2]; RGBA canvas_4x4[4 * 4]; RGBA canvas_8x8[8 * 8]; RGBA canvas_16x16[16 * 16]; RGBA canvas_32x32[32 * 32]; RGBA canvas_64x64[64 * 64]; RGBA canvas_128x128[128 * 128]; RGBA canvas_256x256[256 * 256]; RGBA canvasDefault[128 * 128]; RGBA* canvasMipList[] = { canvas_256x256, canvas_128x128, canvas_64x64, canvas_32x32, canvas_16x16, canvas_8x8, canvas_4x4, canvas_2x2, canvas_1x1, NULL, }; // gathered data u32 Xd, Yd, RotateFlag, TileWidth, MipWidth; void* FixedUpMatMap, * PrimaryMatMap, * SecondaryMatMap; void* BaseAddr = NULL; Fear::GFXBitmap* SrcBM; RGBA** targetCanvas; /* List will not realloc down unless we call Delete, Release, or Pop. Clear()'ing the List will retain the allocated memory, so we can assume the List memory still stay constant. We should never need more than ~200 tiles. */ typedef List< HiddenTexture >::Iterator TileIterator; List< HiddenTexture > tiles(512); u32 uniqueStamp = 0; bool texImageMatch = false, texSubImageMatch = false; // terrain fixes MultiPointer(fnSetBool, 0, 0, 0, 0x005E6B80); MultiPointer(fnMipBlt, 0, 0, 0, 0x005FBED8); MultiPointer(ptr_patchMipBlt, 0, 0, 0, 0x005F692D); // redirect for MipBlt CodePatch patchMipBlt = { ptr_patchMipBlt, "\xE8\xA6\x55\x00\x00", "\xe9mipb", 5, false }; // check to bump block offset up to the next 256x256 grid MultiPointer(ptr_patchCreateFileFromGridFile, 0, 0, 0, 0x00605F26); CodePatch patchCreateFileFromGridFile = { ptr_patchCreateFileFromGridFile, "\x8B\xC8\x8B\x44\x24", "\xe9GFFC", 5, false }; // fix subdivide test MultiPointer(ptr_patchSubdivideTest, 0, 0, 0, 0x00601A9B); CodePatch patchSubdivideTest = { ptr_patchSubdivideTest, "\x66\x8B\x0B\x8B\x15", "\xe9subd", 5, false }; MultiPointer(ptr_patchForceTerrainRecache, 0, 0, 0, 0x006037D3); CodePatch patchForceTerrainRecache = { ptr_patchForceTerrainRecache, "\x0f\x84\x89\x01\x00\x00", "\x90\x90\x90\x90\x90\x90", 6, false }; MultiPointer(ptr_patchLeaveTerrainRenderLevelNonZero, 0, 0, 0, 0x006039BF); CodePatch patchLeaveTerrainRenderLevelNonZero = { ptr_patchLeaveTerrainRenderLevelNonZero, "\x83\xC4\x34\x5F\x5E", "\xE9LTRN", 5, false }; MultiPointer(ptr_patchLeaveTerrainRenderLevelNonZeroLoop, 0, 0, 0, 0x00603829); CodePatch patchLeaveTerrainRenderLevelNonZeroLoop = { ptr_patchLeaveTerrainRenderLevelNonZeroLoop, "\x81\xE2\xFF\x00\x00", "\xE9LTR2", 5, false }; MultiPointer(ptr_patchTerrainRenderLevelZeroLoop, 0, 0, 0, 0x006032E2); CodePatch patchTerrainRenderLevelZeroLoop = { ptr_patchTerrainRenderLevelZeroLoop, "\x81\xE2\xFF\x00\x00", "\xE9RLZL", 5, false }; struct TerrainBlock { }; struct TerrainFile { u32 squareSize; f32 visibleDistance, hazeDistance, screenSize; TerrainBlock* blockMap[3][3]; }; struct TerrainRenderState { PAD(0x4064 - (0x0000 + 0x000)); u32 squareSize; PAD(0x4078 - (0x4064 + 0x004)); f32 growFactor; PAD(0x4108 - (0x4078 + 0x004)); Fear::OpenGLSurface* gfxSurface; }; MultiPointer(ptr_TERRAIN_RENDER_STATE, 0, 0, 0, 0x00725B2C); TerrainRenderState* getTerrainRenderState() { __asm { push esi mov esi, ptr_TERRAIN_RENDER_STATE mov eax, ds: [esi] pop esi } } void forceTerrainRefresh() { patchForceTerrainRecache.Apply(true); } void revertTerrainRefresh() { patchForceTerrainRecache.Apply(false); } NAKED void OnLeaveTerrainRenderLevelNonZero() { __asm { call revertTerrainRefresh add esp, 0x34 pop edi pop esi pop ebx retn } } u32 fnFlushTextureCache; NAKED void OnFlushTextureCache() { __asm { pushad call forceTerrainRefresh popad jmp[fnFlushTextureCache] } } void MipBlt(u32 rotate_flag, RGBA* src_start, s32 src_inc, RGBA* dst_start, s32 tile_width, s32 src_adjust, s32 dst_adjust) { switch (rotate_flag) { case GridBlock_Material_Plain: break; case GridBlock_Material_Rotate: src_start += tile_width * tile_width - tile_width; src_inc = -tile_width; src_adjust = tile_width * tile_width + 1; break; case GridBlock_Material_FlipX: src_start += tile_width - 1; src_inc = -1; src_adjust = 2 * tile_width; break; case GridBlock_Material_FlipY: src_start += tile_width * tile_width - tile_width; src_adjust = -2 * tile_width; break; case GridBlock_Material_FlipX | GridBlock_Material_FlipY: src_start += tile_width * tile_width - 1; src_inc = -1; break; case GridBlock_Material_FlipX | GridBlock_Material_Rotate: src_start += tile_width * tile_width - 1; src_inc = -tile_width; src_adjust = tile_width * tile_width - 1; break; case GridBlock_Material_FlipY | GridBlock_Material_Rotate: src_inc = tile_width; src_adjust = -(tile_width * tile_width - 1); break; case GridBlock_Material_FlipX | GridBlock_Material_FlipY | GridBlock_Material_Rotate: src_start += tile_width - 1; src_inc = tile_width; src_adjust = -((tile_width * tile_width) + 1); break; } // use the simple version for tiles 2x2 or smaller if (tile_width <= 2) { RGBA* src = (src_start), * dst = (dst_start); for (s32 y = 0; y < tile_width; y++, src += src_adjust, dst += dst_adjust) { for (s32 x = 0; x < tile_width; x++, src += src_inc, dst++) *dst = *src; } return; } // RGBA is 4 bytes wide src_inc *= 4; src_adjust *= 4; dst_adjust *= 4; // do 4 texels at once __asm { mov esi, [src_start] mov edi, [dst_start] mov ebx, [src_inc] lea eax, [ebx * 2] add eax, ebx // src_inc * 3 mov ecx, [tile_width] __height_loop: mov edx, [tile_width] shr edx, 2 align 16 __width_loop : movd mm0, [esi + ebx] // src + ( src_inc * 1 ) movd mm2, [esi + eax] // src + ( src_inc * 3 ) movd mm3, [esi + ebx * 2] // src + ( src_inc * 2 ) movd mm1, [esi] // src psllq mm0, 32 psllq mm2, 32 por mm0, mm1 por mm2, mm3 movq[edi], mm0 movq[edi + 8], mm2 lea esi, [esi + ebx * 4] add edi, 16 dec edx jnz __width_loop add esi, [src_adjust] add edi, [dst_adjust] dec ecx jnz __height_loop emms } } bool MipBlt_Examine() { if (!OpenGL::IsActive() || !prefMemstarTerrain) return false; // sanity check the replacement anchor HiddenTexture* hidden = (HiddenTexture*)SrcBM->hidden; TextureWithMips* terrain = NULL; if (hidden) { if (hidden < &tiles[0] || hidden > &tiles[511]) { hidden = NULL; } else if (hidden >= &tiles[tiles.Count()]) { hidden = NULL; } else if (hidden->stamp != uniqueStamp) { hidden = NULL; } else if (hidden->parent != SrcBM) { hidden = NULL; } } if (hidden) { terrain = (hidden->replacement) ? hidden->replacement : hidden->originalUpsampled; } else { hidden = tiles.New(); hidden->stamp = uniqueStamp; hidden->parent = SrcBM; SrcBM->hidden = hidden; // hash the 16x16 mip const String* name = Replacer::FindOriginalName(HashBytes(SrcBM->bitmapMips[3], 16 * 16)); TextureWithMips* replacement = Replacer::FindReplacement(name); if (replacement) { if ((replacement->mWidth != replacement->mHeight) || (replacement->mWidth < 128) || !ISPOWOF2(replacement->mWidth)) { Console::echo("Terrain: %s has bad dimensions! Req: Width = Height, Width >= 128, Width is a power of 2", name->c_str()); replacement = NULL; } } if (replacement) { terrain = replacement; hidden->replacement = replacement; hidden->originalUpsampled = NULL; } else { // generate a texture from the default terrain tile terrain = new TextureWithMips(); terrain->New(SrcBM->width, SrcBM->height); getTerrainRenderState()->gfxSurface->textureCache->pbmpToRGBA(SrcBM->bitmapData, (RGBA*)terrain->mData, SrcBM->width * SrcBM->height, SrcBM->paletteIdx); hidden->replacement = NULL; hidden->originalUpsampled = terrain; } // will only do this once at most for any texture terrain->GenerateMipMaps(); } switch (TileWidth) { case 256: targetCanvas = &canvasMipList[0]; break; case 128: targetCanvas = &canvasMipList[1]; break; case 64: targetCanvas = &canvasMipList[2]; break; case 32: targetCanvas = &canvasMipList[3]; break; case 16: targetCanvas = &canvasMipList[4]; break; case 8: targetCanvas = &canvasMipList[5]; break; case 4: targetCanvas = &canvasMipList[6]; break; case 2: targetCanvas = &canvasMipList[7]; break; case 1: targetCanvas = &canvasMipList[8]; break; } RGBA* sourceCanvas; if (Replacer::prefShowMatchedTextures) { int color; switch (MipWidth) { case 64: color = 0x20; break; case 32: color = 0x40; break; case 16: color = 0x60; break; case 8: color = 0x80; break; case 4: color = 0xa0; break; case 2: color = 0xc0; break; case 1: color = 0xff; break; default: color = 0x80; break; } memset(canvasDefault, color, MipWidth * MipWidth * 4); sourceCanvas = canvasDefault; } else { u32 mipLevel = 0; u32 w = (terrain->mWidth >> 1); while (w > MipWidth) { w >>= 1; mipLevel++; } sourceCanvas = (RGBA*)terrain->mMipMaps[mipLevel]->mData; } s32 src_inc = 1; s32 src_adj = 0; RGBA* src_start = sourceCanvas; RGBA* dst_start = (*targetCanvas) + (Yd * TileWidth + Xd); s32 dst_adj = (TileWidth - MipWidth); s32 dst_width = MipWidth; MipBlt(RotateFlag, src_start, src_inc, dst_start, MipWidth, src_adj, dst_adj); return true; } MultiPointer(fnOnMipBltResume, 0, 0, 0, 0x005F6935); NAKED void OnMipBlt() { __asm { call OpenGL::IsActive and al, al jz gcMM_software // _baseAddr mov ecx, [ebp + 0xc] mov[BaseAddr], ecx // _stride mov ecx, [ebp + 0x10] mov[TileWidth], ecx // _matMap[mapI].flags & rotateMask mov edx, [ebp - 0x20] // yo + xo add edx, [ebp - 0x2c] // mapI // mov ebx, [ ebp + 0x18 ] // _matMap mov ebx, [ebp + 0x18] sub ebx, [PrimaryMatMap] cmp ebx, 256 * 256 * 2 jb __found_offset mov ebx, [ebp + 0x18] sub ebx, [SecondaryMatMap] __found_offset: add ebx, [FixedUpMatMap] mov ax, word ptr[ebx + edx * 2] and eax, 7 mov[RotateFlag], eax // pSrcBM = (*_matList)[ _matMap[mapI].index ].getTextureMap() movzx ecx, byte ptr[ebx + edx * 2 + 1] mov eax, [ebp + 0x14] mov ebx, [ebp + 0x14] mov eax, [eax + 0x1c] mov ebx, [ebx + 0x8] add ecx, ebx mov ebx, ecx lea ecx, [ebx + ecx * 8] lea ecx, [ebx + ecx * 2] shl ecx, 2 add eax, ecx mov eax, [eax] mov eax, [eax + 0x14] mov[SrcBM], eax mov ebx, eax // mipWidth mov eax, [ebx + 0x10] mov ecx, [ebp - 0x04] // mipSize sar eax, cl mov[MipWidth], eax // xd + yd mov eax, [ebp - 0x1c] mov[Yd], eax mov eax, [ebp - 0x28] mov[Xd], eax call MipBlt_Examine and al, al jnz gcMM_end // fall through to software gcMM_software : call[fnMipBlt] gcMM_end : add esp, 0x1c // adjust for the call to mipBlt jmp[fnOnMipBltResume] } } MultiPointer(fnOnCreateFileFromGridFileResume, 0, 0, 0, 0x00605F2C); NAKED void OnCreateFileFromGridFile() { __asm { push eax mov eax, [eax] mov[SecondaryMatMap], eax mov eax, [esp + 0xc] mov eax, [eax] mov[PrimaryMatMap], eax mov eax, [esp + 0x8] pop ecx jmp[fnOnCreateFileFromGridFileResume] } } void SubdivideTest_Examine(u8* subdivideFlag, u8* material, f32 distanceScale, f32 squareDistance, u32 nshift) { *subdivideFlag = 0; TerrainRenderState* trs = getTerrainRenderState(); trs->growFactor = 0; if ((squareDistance < 1) || (*material & GridSquare_Pinned)) { *subdivideFlag = 1; } else { f32 squareSize = (f32)(trs->squareSize << nshift); f32 detailDistance = (distanceScale * squareSize) - squareSize; if (squareDistance < detailDistance) { *subdivideFlag = 1; f32 clampDistance = 0.75f * detailDistance; if (squareDistance > clampDistance) trs->growFactor = (squareDistance - clampDistance) / (0.25f * detailDistance); } } } MultiPointer(fnResumeProcessCurrentBlock, 0, 0, 0, 0x00601B8E); NAKED void OnSubdivideTest() { __asm { pushad xor ecx, ecx mov cx, word ptr[ebx] push ecx // nshift push dword ptr[ebp - 0x14] // f32:squareDistance push dword ptr[ebp - 0x1c] // f32:distanceScale lea eax, [esi + 0x6] push eax // material lea eax, [ebp - 0x59] // bool:subdivideSquare push eax // subdivide flag call SubdivideTest_Examine add esp, 4 * 5 popad jmp[fnResumeProcessCurrentBlock] } } MultiPointer(fnResumeRenderLevelZeroLoop, 0, 0, 0, 0x006032FC); NAKED void OnRenderLevelZeroLoop() { __asm { cmp eax, 256 jb __use_secondary cmp eax, 256 + 256 jae __use_secondary cmp edx, 256 jb __use_secondary cmp edx, 256 + 256 jae __use_secondary mov ebx, [PrimaryMatMap] jmp __continue __use_secondary : mov ebx, [SecondaryMatMap] __continue : and edx, 0xff and eax, 0xff add eax, eax mov esi, [ecx + 0x4060] shl edx, 8 xor ecx, ecx jmp[fnResumeRenderLevelZeroLoop] } } MultiPointer(fnResumeOnTerrainRenderLevelNonZeroLoop, 0, 0, 0, 0x0060382F); NAKED void OnTerrainRenderLevelNonZeroLoop() { __asm { movzx ebx, word ptr[ecx + 0x8] cmp ebx, 256 jl __use_secondary cmp ebx, 256 + 256 jae __use_secondary movzx ebx, word ptr[ecx + 0xa] cmp ebx, 256 jl __use_secondary cmp ebx, 256 + 256 jae __use_secondary mov ebx, [PrimaryMatMap] jmp __continue __use_secondary : mov ebx, [SecondaryMatMap] __continue : mov[FixedUpMatMap], ebx and edx, 0xff jmp[fnResumeOnTerrainRenderLevelNonZeroLoop] } } RGBA** CheckForTerrainTile() { if (!prefMemstarTerrain || (!texImageMatch && !texSubImageMatch)) return NULL; if (tiles.Count() <= 1) forceTerrainRefresh(); // generate mips from the generated tile u32 width = TileWidth; RGBA** src = targetCanvas, ** dst = src + 1; while (width > 1) { u32 halfWidth = (width >> 1); Texture::HalveTexture(*src++, width, width, *dst++, halfWidth, halfWidth); width = halfWidth; } // reset the match variables BaseAddr = NULL; texImageMatch = false; texSubImageMatch = false; return targetCanvas; } // check for the original creation of a grid tile bool TexImageCheck(void* bmp) { texImageMatch = (BaseAddr == bmp); return texImageMatch; } bool TexSubImageCheck(void* bmp) { texSubImageMatch = (BaseAddr == bmp); return texSubImageMatch; } void OnOpenGL(bool isActive) { if (isActive) forceTerrainRefresh(); } void Reset() { // replacement textures will be deleted by the replacing engine TileIterator iter = tiles.Begin(), end = tiles.End(); while (iter != end) { delete iter.value().originalUpsampled; ++iter; } tiles.Clear(); uniqueStamp = GetTickCount(); BaseAddr = NULL; texImageMatch = false; texSubImageMatch = false; } void Open() { Callback::attach(Callback::OnOpenGL, OnOpenGL); patchMipBlt.DoctorRelative((u32)OnMipBlt, 1).Apply(true); patchCreateFileFromGridFile.DoctorRelative((u32)OnCreateFileFromGridFile, 1).Apply(true); patchSubdivideTest.DoctorRelative((u32)OnSubdivideTest, 1).Apply(true); patchLeaveTerrainRenderLevelNonZero.DoctorRelative((u32)OnLeaveTerrainRenderLevelNonZero, 1).Apply(true); patchLeaveTerrainRenderLevelNonZeroLoop.DoctorRelative((u32)OnTerrainRenderLevelNonZeroLoop, 1).Apply(true); patchTerrainRenderLevelZeroLoop.DoctorRelative((u32)OnRenderLevelZeroLoop, 1).Apply(true); fnFlushTextureCache = Patch::ReplaceHook((void*)ptr_OPENGL_FLUSH_TEXTURE_CACHE_VFT, OnFlushTextureCache); Reset(); } /* void funset(u16 *in, u16 val) { for (u32 i = 0; i < 256 * 256; i++) *in++ = val; } BuiltInFunction("tester", tester) { Fear::SimTerrain *ter = Fear::Sim::Client()->findObject<Fear::SimTerrain>(8); if (ter) { u32 *tf = (u32 *)ter->terrainFile; if (tf) { funset(*(u16 **)tf[4], fromstring<u32>(argv[0]) << 8); funset(*(u16 **)tf[8], fromstring<u32>(argv[1]) << 8); Console::echo("%x %x %x", tf[4], tf[5], tf[6]); Console::echo("%x %x %x", tf[7], tf[8], tf[9]); Console::echo("%x %x %x", tf[10], tf[11], tf[12]); } } return "true"; } */ struct Init { Init() { Open(); } ~Init() { Reset(); } } init; }; // namespace Terrain<file_sep>/Texture.cpp #include "OpenGL.h" #include "Texture.h" #include "Console.h" #include "Callback.h" unsigned int Texture::mMulTab[256 * 256]; bool Texture::mMulTabCalculated = (false); Texture::Hash Texture::mTexturesLoadedToOpenGL(128); /* Targa */ void TargaHeader::LoadPalette(unsigned char*& input, RGBA* pal) { for (int i = 0; i < colormap_length; i++) { RGBA& entry = (pal[i + colormap_index]); if (colormap_size == 16) { unsigned char c1 = (*input++), c2 = (*input++); entry.b = (c1 & 0x1f); entry.g = (c2 & 0x03) | ((c1 & 0xd0) >> 5); entry.r = (c2 & 0x7c) >> 2; entry.a = (c2 & 0x80) >> 7; } else { entry.b = (*input++); entry.g = (*input++); entry.r = (*input++); entry.a = (colormap_size == 32) ? (*input++) : 255; } } } void TargaHeader::LoadIndexed(unsigned char* input, RGBA* pixels, RGBA* pal) { pixels = (pixels + (height - 1) * width); int count = (width * height); int x = (width); if (image_type == TGA_INDEXED) { while (count) { x = (min(x, count)); count -= x; while (x--) *pixels++ = pal[*input++]; pixels -= (width * 2); x = (width); } } else if (image_type == TGA_INDEXED_RLE) { while (count) { unsigned char header = (*input++); bool packed = ((header & 0x80) == 0x80); int length = (header & 0x7f) + 1; length = (min(length, count)); count -= length; while (length) { int unpack = (min(x, length)); length -= (unpack); x -= (unpack); if (packed) { RGBA quad = (pal[*input++]); while (unpack--) *pixels++ = (quad); } else { while (unpack--) *pixels++ = (pal[*input++]); } if (x == 0) { pixels -= (width * 2); x = (width); } } } } } void TargaHeader::LoadRGB(unsigned char* input, RGBA* pixels) { pixels = (pixels + (height - 1) * width); int count = (width * height); int x = (width); if (image_type == TGA_RGB) { while (count) { x = (min(x, count)); count -= x; while (x--) { pixels->b = (*input++); pixels->g = (*input++); pixels->r = (*input++); pixels->a = (pixel_size == 32) ? (*input++) : 255; pixels++; } pixels -= (width * 2); x = (width); } } else if (image_type == TGA_RGB_RLE) { while (count) { unsigned char header = (*input++); bool packed = ((header & 0x80) == 0x80); int length = (header & 0x7f) + 1; length = (min(length, count)); count -= length; while (length) { int unpack = (min(x, length)); length -= (unpack); x -= (unpack); if (packed) { RGBA quad; quad.b = (*input++); quad.g = (*input++); quad.r = (*input++); quad.a = (pixel_size == 32) ? (*input++) : 255; while (unpack--) *pixels++ = (quad); } else { while (unpack--) { pixels->b = (*input++); pixels->g = (*input++); pixels->r = (*input++); pixels->a = (pixel_size == 32) ? (*input++) : 255; pixels++; } } if (x == 0) { pixels -= (width * 2); x = (width); } } } } } /* Texture */ /* Gaussian blurs the alpha channel and adds it back to the original image. About as fast as it's going to get.. */ void Texture::AlphaBloom(int blur_radius, int actual_width, int actual_height) { if (mWidth > 2048 || mHeight > 2048) return; // limit the width/height coverage if you like actual_width += (blur_radius * 2); actual_height += (blur_radius * 2); if (actual_width > mWidth) actual_width = (mWidth); if (actual_height > mHeight) actual_height = (mHeight); Texture::BuildMulTab(); int kernel_size = (blur_radius * 2 + 1); int half = (kernel_size / 2); float sigma = (kernel_size - 1) / 6.0f; // create the gaussian kernel int* kernel = new int[kernel_size]; int* k = (kernel + half); for (int i = -half; i <= half; i++) { float height = (1 / sqrtf(PI2 * sigma * sigma)) * (powf(E, -((i * i) / (2 * sigma * sigma)))); k[i] = (int)(height * 256) << 8; // offset for indexing into multab } // canvas to hold horiztonal blur unsigned char* canvas = new unsigned char[mWidth * mHeight]; memset(canvas, 0, mWidth * mHeight); // min/max/total weight tables for edges int _min[2048], _max[2048], _weight[2048]; // precompute spans & weight for (int x = 0; x < mWidth; x++) { _min[x] = (max(x - half, 0) - x); _max[x] = (min(x + half, mWidth - 1) - x); _weight[x] = 0; for (int i = _min[x]; i <= _max[x]; i++) _weight[x] += (k[i] >> 8); if (_weight[x] >= 253) _weight[x] = 256; } // horizontal pass for (int y = 0; y < actual_height; y++) { RGBA* in = (mData + (y * mWidth)); unsigned char* out = (canvas + (y * mWidth)); for (int x = 0; x < actual_width; x++, in++, out++) { int accum = (0), low = _min[x], high = _max[x]; int* weight = (&k[low]); RGBA* pixels = (&in[low]); // convolve the 1d filter for (; low <= high; low++, weight++, pixels++) accum += (mMulTab[*weight + pixels->a]); // assume weight is 1, proper sigma handles this but edges may fade a little *out = (accum >> 8); } } // precompute spans & weight for (int y = 0; y < mHeight; y++) { _min[y] = (max(y - half, 0) - y); _max[y] = (min(y + half, mHeight - 1) - y); _weight[y] = 0; for (int i = _min[y]; i <= _max[y]; i++) _weight[y] += (k[i] >> 8); } // vertical pass for (int y = 0; y < actual_height; y++) { unsigned char* in = (canvas + (y * mWidth)); RGBA* out = (mData + (y * mWidth)); for (int x = 0; x < actual_width; x++, in++, out++) { int accum = 0, low = _min[y], high = _max[y]; int* weight = (&k[low]); unsigned char* bytes = (&in[low * mWidth]); // convolve the 1d filter for (; low <= high; low++, weight++, bytes += mWidth) accum += (mMulTab[*weight + *bytes]); int final = (out->a + (accum >> 8)); out->a = (final > 255) ? 255 : final; } } delete[] canvas; delete[] kernel; } void Texture::Draw(float x, float y) { if (!BindToGraphicsCard()) return; glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x + mWidth, y); glTexCoord2f(1, 1); glVertex2f(x + mWidth, y + mHeight); glTexCoord2f(0, 1); glVertex2f(x, y + mHeight); glEnd(); } void Texture::DrawCentered(float x, float y) { Draw(x - (mWidth / 2.0f), y - (mHeight / 2.0f)); } void Texture::DrawTo(float x, float y, float width, float height) { if (!BindToGraphicsCard()) return; glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x + width, y); glTexCoord2f(1, 1); glVertex2f(x + width, y + height); glTexCoord2f(0, 1); glVertex2f(x, y + height); glEnd(); } void Texture::DrawPartial(float x, float y, float percent, int flags) { if (!BindToGraphicsCard()) return; float x1 = x, y1 = y, x2 = (x + mWidth), y2 = (y + mHeight); float tx1 = 0, ty1 = 0, tx2 = 1, ty2 = 1; float* screen, * tex, * src, dim; if (flags & TEXTURE_WIDTH) { dim = ((float)mWidth); src = (&x); if (flags & TEXTURE_INVERSE) { screen = (&x1); tex = (&tx1); //percent = ( 1.0f - percent ); } else { screen = (&x2); tex = (&tx2); } } else if (flags & TEXTURE_HEIGHT) { dim = ((float)mHeight); src = (&y); if (flags & TEXTURE_INVERSE) { screen = (&y2); tex = (&ty2); } else { screen = (&y1); tex = (&ty1); } } *tex = (percent); *screen = (*src + dim * percent); glBegin(GL_QUADS); glTexCoord2f(tx1, ty1); glVertex2f(x1, y1); glTexCoord2f(tx2, ty1); glVertex2f(x2, y1); glTexCoord2f(tx2, ty2); glVertex2f(x2, y2); glTexCoord2f(tx1, ty2); glVertex2f(x1, y2); glEnd(); /* glDisable( GL_TEXTURE_2D ); if ( flags & TEXTURE_INVERSE ) glColor4ub( 0, 255, 0, 128 ); else glColor4ub( 255, 0, 0, 128 ); glBegin( GL_QUADS ); glVertex2f( x1, y1 ); glVertex2f( x2, y1 ); glVertex2f( x2, y2 ); glVertex2f( x1, y2 ); glEnd( ); */ } void Texture::DrawRotated(float x, float y, float scale_x, float scale_y, float rotation) { if (!BindToGraphicsCard()) return; float halfx = (scale_x * (float)mWidth / 2.0f); float halfy = (scale_y * (float)mHeight / 2.0f); Vector2f texturecoords[4] = { Vector2f(0, 0), Vector2f(1, 0), Vector2f(1, 1), Vector2f(0, 1) }; Vector2f corners[4] = { Vector2f(-halfx, -halfy), Vector2f(halfx, -halfy), Vector2f(halfx, halfy), Vector2f(-halfx, halfy), }; Vector2f::Rotate(corners, 4, rotation); glBegin(GL_QUADS); for (int i = 0; i < 4; i++) { glTexCoord2f(texturecoords[i].x, texturecoords[i].y); glVertex2f(x + corners[i].x, y + corners[i].y); } glEnd(); } void Texture::DrawScaled(float x, float y, float scale_x, float scale_y) { if (!BindToGraphicsCard()) return; float width = (mWidth * scale_x); float height = (mHeight * scale_y); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(x, y); glTexCoord2f(1, 0); glVertex2f(x + width, y); glTexCoord2f(1, 1); glVertex2f(x + width, y + height); glTexCoord2f(0, 1); glVertex2f(x, y + height); glEnd(); } Texture* Texture::Duplicate() { Texture* dup = new Texture(); if (!dup) return (NULL); if (!Duplicate(*dup)) { delete dup; dup = NULL; } return (dup); } bool Texture::Duplicate(Texture& b) const { b.Free(); if (!mData) return (false); b.mWidth = mWidth; b.mHeight = mHeight; b.mData = (RGBA*)malloc(mWidth * mHeight * sizeof(RGBA)); memcpy(b.mData, mData, mWidth * mHeight * 4); return (true); } bool Texture::LoadTGA(unsigned char* input) { Free(); TargaHeader tga = *(TargaHeader*)input; input += (sizeof(tga)); input += (tga.id_length); if (tga.image_type == TGA_RGB || tga.image_type == TGA_RGB_RLE) { if (tga.pixel_size != 32 && tga.pixel_size != 24 || tga.colormap_type != 0) { Console::echo("TGA: Invalid pixel size"); return (false); } } else if (tga.image_type == TGA_INDEXED || tga.image_type == TGA_INDEXED_RLE) { if (tga.pixel_size != 8 || tga.colormap_type != 1) { Console::echo("TGA: Invalid pixel size"); return (false); } } else if (tga.image_type == TGA_GRAY) { Console::echo("TGA: Grayscale not supported"); return (false); } else { Console::echo("TGA: Unsupported image type"); return (false); } RGBA pal[256]; if (tga.colormap_type) tga.LoadPalette(input, pal); mWidth = (tga.width); mHeight = (tga.height); mData = (RGBA*)malloc(mWidth * mHeight * sizeof(RGBA)); switch (tga.image_type) { case TGA_INDEXED: case TGA_INDEXED_RLE: tga.LoadIndexed(input, mData, pal); break; case TGA_RGB: case TGA_RGB_RLE: tga.LoadRGB(input, mData); break; } if (tga.attributes & 0x20) { RGBA* flip = (RGBA*)malloc(mWidth * sizeof(RGBA)); for (int y = 0; y < mHeight / 2; y++) { RGBA* src = (mData + (y * mWidth)); RGBA* dst = (mData + (mHeight - y - 1) * mWidth); memcpy(flip, src, mWidth * sizeof(RGBA)); memcpy(src, dst, mWidth * sizeof(RGBA)); memcpy(dst, flip, mWidth * sizeof(RGBA)); } free(flip); } return (true); } bool Texture::New(int width, int height) { Free(); mData = (RGBA*)malloc(width * height * sizeof(RGBA)); if (!mData) return (false); memset(mData, 0, height * width * 4); mWidth = (width); mHeight = (height); return (true); } /* Virtuals */ void Texture::Free() { // HashTables mItemCount check should keep this from crashing ... if (mHandle) { // don't delete in UnloadFromGraphicsCard mTexturesLoadedToOpenGL.Delete(mHandle); UnloadFromGraphicsCard(); } free(mData); mHandle = mWidth = mHeight = 0; mData = NULL; } bool Texture::BindToGraphicsCard() { if (mHandle) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, mHandle); return (true); } if (!mData) return (false); glGenTextures(1, &(GLuint)mHandle); if (!mHandle) return (false); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, mHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); mTexturesLoadedToOpenGL.InsertUnique(mHandle, this); return (true); } void Texture::UnloadFromGraphicsCard() { if (mHandle) glDeleteTextures(1, &(GLuint)mHandle); mHandle = 0; } /* TextureWithMips */ void TextureWithMips::Free() { Texture::Free(); FreeMipMaps(); } void TextureWithMips::GenerateMipMaps() { RGBA* mipSrc = (mData); int width, height; int level = 0; if (!mipSrc || mMipMaps[0]) return; width = (mWidth); height = (mHeight); if (!ISPOWOF2(width) || !ISPOWOF2(height)) return; while ((width > 1) || (height > 1)) { int newWidth = (width >> 1); int newHeight = (height >> 1); if (newWidth <= 0) newWidth = 1; if (newHeight <= 0) newHeight = 1; mMipMaps[level] = new Texture(); mMipMaps[level]->New(newWidth, newHeight); Texture::HalveTexture(mipSrc, width, height, (RGBA*)mMipMaps[level]->mData, newWidth, newHeight); width = newWidth; height = newHeight; mipSrc = (mMipMaps[level++]->mData); } } void TextureWithMips::FreeMipMaps() { for (int i = 0; mMipMaps[i]; i++) { mMipMaps[i]->Free(); delete mMipMaps[i]; mMipMaps[i] = NULL; } } bool TextureWithMips::BindToGraphicsCard() { if (mHandle) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, mHandle); return (true); } if (!mData) return (false); glGenTextures(1, &(GLuint)mHandle); if (!mHandle) return (false); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, mHandle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData); GenerateMipMaps(); for (int i = 0; mMipMaps[i]; i++) glTexImage2D(GL_TEXTURE_2D, i + 1, GL_RGBA8, mMipMaps[i]->mWidth, mMipMaps[i]->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mMipMaps[i]->mData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); mTexturesLoadedToOpenGL.InsertUnique(mHandle, this); return (true); } /* Statics */ // Table of multiplications for up to 256x256 void Texture::BuildMulTab() { if (mMulTabCalculated) return; unsigned int i, j; for (i = 0; i < 256; i++) for (j = 0; j < 256; j++) mMulTab[(i << 8) + j] = (i * j); mMulTabCalculated = true; } // Not quite proper but this needs to be fast void Texture::HalveTexture(RGBA* src, int srcX, int srcY, RGBA* dst, int dstX, int dstY) { RGBA* in = (src), * out = (dst); if (!ISPOWOF2(srcX) || !ISPOWOF2(srcY)) return; if (srcY > 1 && srcX > 1) { __asm { mov esi, [dst] mov eax, [src] mov edx, [dstY] test edx, edx jle __done mov ecx, [srcX] shl ecx, 2 __yloop: mov edi, [dstX] pxor mm7, mm7 align 16 __xloop : movd mm0, [ecx + eax] movd mm1, [ecx + eax + 4] punpcklbw mm0, mm7 movd mm2, [eax + 4] punpcklbw mm1, mm7 movd mm3, [eax] punpcklbw mm2, mm7 punpcklbw mm3, mm7 paddw mm0, mm1 paddw mm2, mm3 paddw mm0, mm2 psrlw mm0, 2 packuswb mm0, mm7 add esi, 4 add eax, 8 dec edi movd[esi - 4], mm0 jne __xloop add eax, ecx dec edx jne __yloop __done : emms } } else { int until = (max(dstX, dstY)); for (int x = 0; x < until; x++, in += 2, out += 1) { out->r = (in->r + (in + 1)->r) >> 1; out->g = (in->g + (in + 1)->g) >> 1; out->b = (in->b + (in + 1)->b) >> 1; out->a = (in->a + (in + 1)->a) >> 1; } } } void Texture::UnloadAllFromGraphicsCard() { Hash::Iterator iter = (mTexturesLoadedToOpenGL.Begin()), end = (mTexturesLoadedToOpenGL.End()); while (iter != end) { iter.value()->UnloadFromGraphicsCard(); ++iter; } mTexturesLoadedToOpenGL.Clear(); } namespace TexturePurger { void OnOpenGL(bool state) { if (!state) Texture::UnloadAllFromGraphicsCard(); } struct Init { Init() { if (VersionSnoop::GetVersion() == VERSION::vNotGame) { return; } if (VersionSnoop::GetVersion() < VERSION::v001003) { return; } Callback::attach(Callback::OnOpenGL, OnOpenGL); } } init; }; <file_sep>/Lib/Hash.h #ifndef __HASH_H__ #define __HASH_H__ #include "Memstar.h" u32 HashString(const char *str); u32 HashBytes(const unsigned char *key, size_t len); #endif // __HASH_H__ <file_sep>/Lib/StringConversions.h #ifndef __STRINGCONVERSIONS_H__ #define __STRINGCONVERSIONS_H__ namespace StringConversions { char *getConversionBuffer(); int getConversionBufferSize(); template< class type > const char *tostring( const type &value ); template< class type > const char *tostring( const type &value1, const type &value2 ); template< class type > const char *tostring( const type &value, char *buffer, int buffersize ); template< class type > type fromstring( const char *string ); template< class type > void fromstring( const char *string, type &value1 ); template< class type > void fromstring( const char *string, type &value1, type &value2 ); const char *roundascii( const char *value, int digits ); const char *format( const char *fmt, ... ); const char *format( int buffersize, char *buffer, const char *fmt, ... ); const char *format( int buffersize, char *buffer, va_list &args, const char *fmt ); char *escapestring( const char *src, u32 dstlen, char *dst ); char *escapestring( const char *src ); }; // namespace StringConversions using namespace StringConversions; #endif // __STRINGCONVERSIONS_H__<file_sep>/Lib/BaseTypes.h #ifndef __BASETYPES_H__ #define __BASETYPES_H__ #include <math.h> typedef unsigned char u8; typedef signed char s8; typedef unsigned short u16; typedef signed short s16; typedef unsigned int u32; typedef signed int s32; typedef float f32; typedef double f64; #define ISPOWOF2(n) (!(n & (n - 1))) #define E 2.71828182845904523536f #define PI 3.14159265358979323846f #define PI2 ( PI * 2 ) struct Vector2i { Vector2i( ) { } Vector2i( s32 x, s32 y ) : x(x), y(y) { } Vector2i operator+ ( const Vector2i &b ) const { return ( Vector2i( x + b.x, y + b.y ) ); } Vector2i operator- ( const Vector2i &b ) const { return ( Vector2i( x - b.x, y - b.y ) ); } s32 x, y; }; struct Vector2f { Vector2f() {} Vector2f(f32 x, f32 y) : x(x), y(y) {} Vector2f Rotate(f32 radians) const { return ( Rotate( sinf( radians ), cosf( radians ) ) ); } Vector2f Rotate(f32 s, f32 c) const { return Vector2f( x * c - y * s, x * s + y * c ); } Vector2f operator- (const Vector2f &b) const { return Vector2f(x - b.x, y - b.y); } static void Rotate(Vector2f *a, s32 count, f32 radians) { f32 c = cosf( radians ), s = sinf( radians ); for ( ; count > 0; --count, ++a ) *a = a->Rotate( s, c ); } f32 x, y; }; struct Vector3f { Vector3f() {} Vector3f(f32 x, f32 y, f32 z) : x(x), y(y), z(z) {} f32 x, y, z; }; struct RGB { u8 r, g, b; }; class RGBf { f32 r, g, b; }; struct RGBAf { RGBAf( ) { } RGBAf( f32 r, f32 g, f32 b, f32 a ) : r(r), g(g), b(b), a(a) {} RGBAf( u8 r, u8 g, u8 b, u8 a ) : r(r), g(g), b(b), a(a) {} f32 r, g, b, a; }; struct RGBA { RGBA( ) { } RGBA(u8 r, u8 g, u8 b, u8 a) : r(r), g(g), b(b), a(a) {} RGB torgb() const { RGB color; color.r = r; color.g = g; color.b = b; return ( color ); } void operator= ( const RGBA &q ) { memcpy( this, &q, sizeof( *this ) ); } void operator+= ( const RGBA &q ) { r=min((r+q.r),255); g=min((g+q.g),255); b=min((b+q.b),255); a=min((a+q.a),255); } u8 r, g, b, a; }; class BGRA { public: u8 b, g, r, a; }; template <typename T> T Min(T a, T b) { return (a < b) ? a : b; } template <typename T> T Max(T a, T b) { return (a > b) ? a : b; } #endif // __BASETYPES_H__<file_sep>/OpenGL.cpp #include "OpenGL.h" #include "OpenGL_Pointers.h" #include "Callback.h" #include "Console.h" #include "Patch.h" #pragma warning( disable : 4035 ) // suppress "no return value" namespace Loader { extern u32 Crashed; }; namespace OpenGL { BuiltInVariable("pref::forceTrilinear", bool, glForceTrilinear, true); // outsourced setting mState to Hooks.cpp bool glActive = false; void* _wglMakeCurrent, * _glMultiTexCoord2fARB, * _glTexParameteri, * _setAlphaSource; u32 _glTexImage2d, _glTexSubImage2d; Fear::OpenGLState* mState; /* Helpers */ bool CheckBlendFunc(GLenum src, GLenum dst) { if (mState->BLEND_SRC == src && mState->BLEND_DST == dst) return true; mState->BLEND_SRC = src; mState->BLEND_DST = dst; return false; } bool CheckCap(GLenum cap, GLboolean state) { int want = (state) ? 1 : 0; bool already_set = false; switch (cap) { case GL_TEXTURE_2D: { already_set = (mState->TEXTURE_2D0_ARB == want); mState->TEXTURE_2D0_ARB = want; } break; case GL_ALPHA_TEST: { already_set = (mState->ALPHA_TEST == want); mState->ALPHA_TEST = want; } break; case GL_DEPTH_TEST: { already_set = (mState->DEPTH_TEST == want); mState->DEPTH_TEST = want; } break; } return already_set; } bool CheckTexEnv(GLint param) { if (mState->TEXTURE_ENV0_ARB == param) return true; mState->TEXTURE_ENV0_ARB = param; return false; } NAKED void setAlphaSource() { __asm { mov ecx, [eax + 0x158] mov[mState], ecx cmp dword ptr[esp], 0x47D250 // Planet::onRender jne __continue mov edx, 4 __continue: jmp[_setAlphaSource] } } NAKED void glTexParamateri() { __asm { cmp[glForceTrilinear], 0 je __check_nearest mov eax, [esp + 0x8] cmp eax, GL_TEXTURE_MAG_FILTER je __check_filter cmp eax, GL_TEXTURE_MIN_FILTER jne __done __check_filter : // 0x2700 - 0x2703 are ours mov eax, [esp + 0xc] cmp eax, GL_NEAREST_MIPMAP_NEAREST jb __check_nearest cmp eax, GL_LINEAR_MIPMAP_LINEAR ja __check_nearest mov dword ptr[esp + 0xc], GL_LINEAR_MIPMAP_LINEAR __check_nearest : mov eax, [esp + 0xc] cmp eax, GL_NEAREST jne __done // sky overlays are rendered with GL_NEAREST, let's go linear mov dword ptr[esp + 0xc], GL_LINEAR __done : jmp ds : [_glTexParameteri] } } bool IsActive() { return glActive; } // The second texture unit is left enabled sometimes, this will disable it void ShutdownTex1ARB() { mState->TEXTURE_2D0_ARB = 0; mState->TEXTURE_2D1_ARB = 0; mState->TEXTURE_UNIT_ACTIVE = 0; if (!mState->_glActiveTextureARB) return; __asm { mov ebx, [mState] push dword ptr GL_TEXTURE1_ARB call[ebx + 8] // glActiveTextureARB( GL_TEXTURE1_ARB ); push dword ptr GL_TEXTURE_2D mov esi, OpenGLPtrs::ptr_OPENGL32_GLDISABLE call ds:[esi] // glDisable( GL_TEXTURE_2D ); push dword ptr GL_TEXTURE0_ARB call[ebx + 8] // glActiveTextureARB( GL_TEXTURE0_ARB ); push dword ptr GL_TEXTURE_2D mov esi, OpenGLPtrs::ptr_OPENGL32_GLDISABLE call ds:[esi] // glDisable( GL_TEXTURE_2D ); } } BOOL __stdcall wglMakeCurrent(HDC hdc, HGLRC hglrc) { glActive = (hglrc != NULL); if (!glActive) Callback::trigger(Callback::OnOpenGL, false); BOOL result; __asm { push[hglrc] push[hdc] call[OpenGL::_wglMakeCurrent] movzx eax, al mov[result], eax } if (glActive) Callback::trigger(Callback::OnOpenGL, true); Console::echo("OpenGL is %s", glActive ? "active" : "not active"); return result; // return must be BOOL(32bit), not GLboolean(8bit) } void OnStarted(bool active) { _wglMakeCurrent = (void*)Patch::ReplaceHook((void*)OpenGLPtrs::ptr_OPENGL32_WGLMAKECURRENT, &wglMakeCurrent); _glTexParameteri = (void*)Patch::ReplaceHook((void*)OpenGLPtrs::ptr_OPENGL32_GLTEXPARAMETERI, &glTexParamateri); _setAlphaSource = (void*)Patch::ReplaceHook((void*)OpenGLPtrs::ptr_OPENGL_SET_ALPHA_SOURCE, &setAlphaSource); } struct Init { Init() { if (VersionSnoop::GetVersion() != VERSION::v001004) { return; } if (VersionSnoop::GetVersion() == VERSION::vNotGame) { return; } Callback::attach(Callback::OnStarted, OnStarted); } } init; }; // namespace OpenGL /* OpenGL Interface */ void glBegin(GLenum mode) { typedef void (GLAPIENTRY* fn)(GLenum mode); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLBEGIN)(mode); } void glBindTexture(GLenum target, GLuint texture) { typedef void (GLAPIENTRY* fn)(GLenum target, GLuint texture); int* bound = (int*)(OpenGLPtrs::ptr_OPENGL_BOUND_TEXTURE); if (*bound == texture && OpenGL::mState->GL_BOUNDTEXTURE0 == texture) return; *bound = (texture); OpenGL::mState->GL_BOUNDTEXTURE0 = (texture); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLBINDTEXTURE)(target, texture); } void glBlendFunc(GLenum sfactor, GLenum dfactor) { if (OpenGL::CheckBlendFunc(sfactor, dfactor)) return; typedef void (GLAPIENTRY* fn)(GLenum sfactor, GLenum dfactor); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLBLENDFUNC)(sfactor, dfactor); } void glCallLists(GLsizei n, GLenum type, const GLvoid* lists) { typedef void (GLAPIENTRY* fn)(GLsizei n, GLenum type, const GLvoid* lists); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLCALLLISTS)(n, type, lists); } void glCallList(GLuint list) { typedef void (GLAPIENTRY* fn)(GLuint a); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLCALLLIST)(list); } void glColor3ub(GLubyte red, GLubyte green, GLubyte blue) { typedef void (GLAPIENTRY* fn)(GLubyte red, GLubyte green, GLubyte blue); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLCOLOR3UB)(red, green, blue); } void glColor4ub(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha) { typedef void (GLAPIENTRY* fn)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLCOLOR4UB)(red, green, blue, alpha); } void glColorMask(GLboolean r, GLboolean g, GLboolean b, GLboolean a) { typedef void (GLAPIENTRY* fn)(GLboolean r, GLboolean g, GLboolean b, GLboolean a); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLCOLORMASK)(r, g, b, a); } void glDeleteLists(GLuint list, GLsizei range) { if (Loader::Crashed) return; typedef void (GLAPIENTRY* fn)(GLuint list, GLsizei range); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLDELETELISTS)(list, range); } void glDeleteTextures(GLsizei n, const GLuint* textures) { if (Loader::Crashed) return; typedef void (GLAPIENTRY* fn)(GLsizei n, const GLuint* textures); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLDELETETEXTURES)(n, textures); } void glDepthFunc(GLenum func) { typedef void (GLAPIENTRY* fn)(GLenum func); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLDEPTHFUNC)(func); } void glDepthMask(GLboolean flag) { typedef void (GLAPIENTRY* fn)(GLboolean flag); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLDEPTHMASK)(flag); } void glDepthRange(GLclampd znear, GLclampd zfar) { typedef void (GLAPIENTRY* fn)(GLclampd znear, GLclampd zfar); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLDEPTHRANGE)(znear, zfar); } void glDisable(GLenum cap) { if (OpenGL::CheckCap(cap, false)) return; typedef void (GLAPIENTRY* fn)(GLenum cap); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLDISABLE)(cap); } void glDrawPixels(GLsizei width, GLsizei height, GLenum format, GLenum pixeltype, const GLvoid* pixels) { typedef void (GLAPIENTRY* fn)(GLsizei width, GLsizei height, GLenum format, GLenum pixeltype, const GLvoid* pixels); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLDRAWPIXELS)(width, height, format, pixeltype, pixels); } void glEnable(GLenum cap) { if (OpenGL::CheckCap(cap, true)) return; typedef void (GLAPIENTRY* fn)(GLenum cap); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLENABLE)(cap); } void glEnd() { typedef void (GLAPIENTRY* fn)(); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLEND)(); } void glEndList() { typedef void (GLAPIENTRY* fn)(); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLENDLIST)(); } void glFlush() { typedef void (GLAPIENTRY* fn)(); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLFLUSH)(); } GLenum glGetError() { typedef GLenum(GLAPIENTRY* fn)(); return (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLGETERROR)(); } GLuint glGenLists(GLsizei range) { typedef GLuint(GLAPIENTRY* fn)(GLsizei range); return (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLGENLISTS)(range); } void glGenTextures(GLsizei n, GLuint* textures) { typedef void (GLAPIENTRY* fn)(GLsizei n, GLuint* textures); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLGENTEXTURES)(n, textures); } void glGetIntegerv(GLenum pname, GLint* params) { typedef void (GLAPIENTRY* fn)(GLenum pname, GLint* params); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLGETINTEGERV)(pname, params); } void glGetTexEnviv(GLenum target, GLenum pname, GLint* params) { typedef void (GLAPIENTRY* fn)(GLenum target, GLenum pname, GLint* params); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLGETTEXENVIV)(target, pname, params); } void glListBase(GLuint base) { typedef void (GLAPIENTRY* fn)(GLuint base); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLLISTBASE)(base); } void glLoadIdentity() { typedef void (GLAPIENTRY* fn)(); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLLOADIDENTITY)(); } void glPixelMapusv(GLenum map, GLsizei mapsize, const GLushort* values) { typedef void (GLAPIENTRY* fn)(GLenum map, GLsizei mapsize, const GLushort* values); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLPIXELMAPUSV)(map, mapsize, values); } void glMatrixMode(GLenum mode) { typedef void (GLAPIENTRY* fn)(GLenum mode); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLMATRIXMODE)(mode); } void glNewList(GLuint list, GLenum mode) { typedef void (GLAPIENTRY* fn)(GLuint list, GLenum mode); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLNEWLIST)(list, mode); } void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble znear, GLdouble zfar) { typedef void (GLAPIENTRY* fn)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble znear, GLdouble zfar); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLORTHO)(left, right, bottom, top, znear, zfar); } void glPixelTransferi(GLenum pname, GLint param) { typedef void (GLAPIENTRY* fn)(GLenum pname, GLint param); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLPIXELTRANSFERI)(pname, param); } void glPopMatrix() { typedef void (GLAPIENTRY* fn)(); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLPOPMATRIX)(); } void glPopAttrib() { typedef void (GLAPIENTRY* fn)(); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLPOPATTRIB)(); } void glPushAttrib(GLenum attrib) { typedef void (GLAPIENTRY* fn)(GLenum attrib); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLPUSHATTRIB)(attrib); } void glPushMatrix() { typedef void (GLAPIENTRY* fn)(); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLPUSHMATRIX)(); } void glRasterPos2i(GLint x, GLint y) { typedef void (GLAPIENTRY* fn)(GLint x, GLint y); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLRASTERPOS2I)(x, y); } void glReadBuffer(GLenum mode) { typedef void (GLAPIENTRY* fn)(GLenum mode); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLREADBUFFER)(mode); } void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum pixeltype, const GLvoid* pixels) { typedef void (GLAPIENTRY* fn)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum pixeltype, const GLvoid* pixels); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLREADPIXELS)(x, y, width, height, format, pixeltype, pixels); } void glScalef(GLfloat x, GLfloat y, GLfloat z) { typedef void (GLAPIENTRY* fn)(GLfloat x, GLfloat y, GLfloat z); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLSCALEF)(x, y, z); } void glScissor(GLint x, GLint y, GLsizei width, GLsizei height) { typedef void (GLAPIENTRY* fn)(GLint x, GLint y, GLsizei width, GLsizei height); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLSCISSOR)(x, y, width, height); } void glTexCoord2f(GLfloat s, GLfloat t) { typedef void (GLAPIENTRY* fn)(GLfloat s, GLfloat t); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLTEXCOORD2F)(s, t); } void glTexCoord2fv(Vector2f* v) { typedef void (GLAPIENTRY* fn)(Vector2f* v); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLTEXCOORD2FV)(v); } void glTexEnvi(GLenum target, GLenum pname, GLint param) { if (OpenGL::CheckTexEnv(param)) return; typedef void (GLAPIENTRY* fn)(GLenum target, GLenum pname, GLint param); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLTEXENVI)(target, pname, param); } void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels) { typedef void (GLAPIENTRY* fn)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLTEXIMAGE2D)(target, level, internalformat, width, height, border, format, type, pixels); } void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels) { typedef void (GLAPIENTRY* fn)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLTEXSUBIMAGE2D)(target, level, xoffset, yoffset, width, height, format, type, pixels); } void glTexParameteri(GLenum target, GLenum pname, GLint param) { typedef void (GLAPIENTRY* fn)(GLenum target, GLenum pname, GLint param); //(*( fn *)OPENGL32_GLTEXPARAMETERI)( target, pname, param ); ((fn)OpenGL::_glTexParameteri)(target, pname, param); // call it directly so we bypass our hook } void glTranslatef(GLfloat x, GLfloat y, GLfloat z) { typedef void (GLAPIENTRY* fn)(GLfloat x, GLfloat y, GLfloat z); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLTRANSLATEF)(x, y, z); } void glVertex2f(GLfloat x, GLfloat y) { typedef void (GLAPIENTRY* fn)(GLfloat x, GLfloat y); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLVERTEX2F)(x, y); } void glVertex2fv(Vector2f* v) { typedef void (GLAPIENTRY* fn)(Vector2f* v); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLVERTEX2FV)(v); } void glVertex2i(GLint x, GLint y) { typedef void (GLAPIENTRY* fn)(GLint x, GLint y); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLVERTEX2I)(x, y); } void glVertex3f(GLfloat x, GLfloat y, GLfloat z) { typedef void (GLAPIENTRY* fn)(GLfloat x, GLfloat y, GLfloat z); (*(fn*)OpenGLPtrs::ptr_OPENGL32_GLVERTEX3F)(x, y, z); } #pragma warning( default : 4035 ) <file_sep>/Lib/Hash.cpp #include "Hash.h" // case insensitive table static const u32 SBoxTable[256] = { 0x4660c395, 0x3baba6c5, 0x27ec605b, 0xdfc1d81a, 0xaaac4406, 0x3783e9b8, 0xa4e87c68, 0x62dc1b2a, 0xa8830d34, 0x10a56307, 0x4ba469e3, 0x54836450, 0x1b0223d4, 0x23312e32, 0xc04e13fe, 0x3b3d61fa, 0xdab2d0ea, 0x297286b1, 0x73dbf93f, 0x6bb1158b, 0x46867fe2, 0xb7fb5313, 0x3146f063, 0x4fd4c7cb, 0xa59780fa, 0x9fa38c24, 0x38c63986, 0xa0bac49f, 0xd47d3386, 0x49f44707, 0xa28dea30, 0xd0f30e6d, 0xd5ca7704, 0x934698e3, 0x1a1ddd6d, 0xfa026c39, 0xd72f0fe6, 0x4d52eb70, 0xe99126df, 0xdfdaed86, 0x4f649da8, 0x427212bb, 0xc728b983, 0x7ca5d563, 0x5e6164e5, 0xe41d3a24, 0x10018a23, 0x5a12e111, 0x999ebc05, 0xf1383400, 0x50b92a7c, 0xa37f7577, 0x2c126291, 0x9daf79b2, 0xdea086b1, 0x85b1f03d, 0x598ce687, 0xf3f5f6b9, 0xe55c5c74, 0x791733af, 0x39954ea8, 0xafcff761, 0x5fea64f1, 0x216d43b4, 0xd039f8c1, 0x1b826322, 0x6602a990, 0x7c1cef68, 0xe102458e, 0xa5564a67, 0x1136b393, 0x98dc0ea1, 0x3b6f59e5, 0x9efe981d, 0x35fafbe0, 0xc9949ec2, 0x62c765f9, 0x510cab26, 0xbe071300, 0x7ee1d449, 0xcc71beef, 0xfbb4284e, 0xbfc02ce7, 0xdf734c93, 0x2f8cebcd, 0xfeedc6ab, 0x5476ee54, 0xbd2b5ff9, 0xf4fd0352, 0x67f9d6ea, 0x7b70db05, 0x5c97ab61, 0x8076e10d, 0x48e4b3cc, 0x7c28ec12, 0xb17986e1, 0x01735836, 0x1b826322, 0x6602a990, 0x7c1cef68, 0xe102458e, 0xa5564a67, 0x1136b393, 0x98dc0ea1, 0x3b6f59e5, 0x9efe981d, 0x35fafbe0, 0xc9949ec2, 0x62c765f9, 0x510cab26, 0xbe071300, 0x7ee1d449, 0xcc71beef, 0xfbb4284e, 0xbfc02ce7, 0xdf734c93, 0x2f8cebcd, 0xfeedc6ab, 0x5476ee54, 0xbd2b5ff9, 0xf4fd0352, 0x67f9d6ea, 0x7b70db05, 0x5a5f5310, 0x482dd7aa, 0xa0a66735, 0x321ae71f, 0x8e8ad56c, 0x27a509c3, 0x1690b261, 0x4494b132, 0xc43a42a7, 0x3f60a7a6, 0xd63779ff, 0xe69c1659, 0xd15972c8, 0x5f6cdb0c, 0xb9415af2, 0x1261ad8d, 0xb70a6135, 0x52ceda5e, 0xd4591dc3, 0x442b793c, 0xe50e2dee, 0x6f90fc79, 0xd9ecc8f9, 0x063dd233, 0x6cf2e985, 0xe62cfbe9, 0x3466e821, 0x2c8377a2, 0x00b9f14e, 0x237c4751, 0x40d4a33b, 0x919df7e8, 0xa16991a4, 0xc5295033, 0x5c507944, 0x89510e2b, 0xb5f7d902, 0xd2d439a6, 0xc23e5216, 0xd52d9de3, 0x534a5e05, 0x762e73d4, 0x3c147760, 0x2d189706, 0x20aa0564, 0xb07bbc3b, 0x8183e2de, 0xebc28889, 0xf839ed29, 0x532278f7, 0x41f8b31b, 0x762e89c1, 0xa1e71830, 0xac049bfc, 0x9b7f839c, 0x8fd9208d, 0x2d2402ed, 0xf1f06670, 0x2711d695, 0x5b9e8fe4, 0xdc935762, 0xa56b794f, 0xd8666b88, 0x6872c274, 0xbc603be2, 0x2196689b, 0x5b2b5f7a, 0x00c77076, 0x16bfa292, 0xc2f86524, 0xdd92e83e, 0xab60a3d4, 0x92daf8bd, 0x1fe14c62, 0xf0ff82cc, 0xc0ed8d0a, 0x64356e4d, 0x7e996b28, 0x81aad3e8, 0x05a22d56, 0xc4b25d4f, 0x5e3683e5, 0x811c2881, 0x124b1041, 0xdb1b4f02, 0x5a72b5cc, 0x07f8d94e, 0xe5740463, 0x498632ad, 0x7357ffb1, 0x0dddd380, 0x3d095486, 0x2569b0a9, 0xd6e054ae, 0x14a47e22, 0x73ec8dcc, 0x004968cf, 0xe0c3a853, 0xc9b50a03, 0xe1b0eb17, 0x57c6f281, 0xc9f9377d, 0x43e03612, 0x9a0c4554, 0xbb2d83ff, 0xa818ffee, 0xf407db87, 0x175e3847, 0x5597168f, 0xd3d547a7, 0x78f3157c, 0xfc750f20, 0x9880a1c6, 0x1af41571, 0x95d01dfc, 0xa3968d62, 0xeae03cf8, 0x02ee4662, 0x5f1943ff, 0x252d9d1c, 0x6b718887, 0xe052f724, 0x4cefa30b, 0xdcc31a00, 0xe4d0024d, 0xdbb4534a, 0xce01f5c8, 0x0c072b61, 0x5d59736a, 0x60291da4, 0x1fbe2c71, 0x2f11d09c, 0x9dce266a, }; static const u32 HashM = 0x5bd1e995; u32 HashString(const char *str) { u32 h = 0xcafebabe; const u8 *key = (const u8 *)str; while (key[0]) { h = (h ^ SBoxTable[key[0]]) * 3; key++; } h ^= h >> 13; h *= HashM; h ^= h >> 15; return h; } u32 HashBytes(const unsigned char *key, size_t len) { const u8 r = 24; u32 h = len, k; const u8 *data = (const u8 *)key; for (; len >= 4; len -= 4, data += 4) { k = *(u32 *)data * HashM; k = (k ^ (k >> r)) * HashM; h = (h * HashM) ^ k; } k = 0; switch (len) { case 3: k ^= data[2] << 16; case 2: k ^= data[1] << 8; case 1: k ^= data[0]; k *= HashM; k = (k ^ (k >> r)) * HashM; h = (h * HashM) ^ k; default:; } h ^= h >> 13; h *= HashM; h ^= h >> 15; return h; } <file_sep>/Lib/Strings.cpp #include "Strings.h" String operator+ ( const String &str, char c ) { String tmp( str ); tmp.Append( c ); return ( tmp ); } String operator+ ( const String &str, int i ) { String tmp( str ); tmp.Append( "%d", i ); return ( tmp ); } String operator+ ( const String &str, float f ) { String tmp( str ); tmp.Append( "%8.8f", f ); return ( tmp ); } String operator+ ( const String &str, char *s ) { String tmp( str ); tmp.Append( strlen( s ) + 1, s ); return ( tmp ); } String operator+ ( const String &str, const String &str2 ) { String tmp( str ); tmp.Append( str2.Length() + 1, str2.c_str() ); return ( tmp ); } String operator+ ( const String &str, const String2 &str2 ) { String tmp( str ); tmp.Append( str2.Length() + 1, str2.c_str() ); return ( tmp ); } String2 operator+ ( const String2 &str, char c ) { String2 tmp( str ); tmp.Append( c ); return ( tmp ); } String2 operator+ ( const String2 &str, int i ) { String2 tmp( str ); tmp.Append( "%d", i ); return ( tmp ); } String2 operator+ ( const String2 &str, float f ) { String2 tmp( str ); tmp.Append( "%8.8f", f ); return ( tmp ); } String2 operator+ ( const String2 &str, char *s ) { String2 tmp( str ); tmp.Append( strlen( s ) + 1, s ); return ( tmp ); } String2 operator+ ( const String2 &str, const String &str2 ) { String2 tmp( str ); tmp.Append( str2.Length() + 1, str2.c_str() ); return ( tmp ); } String2 operator+ ( const String2 &str, const String2 &str2 ) { String2 tmp( str ); tmp.Append( str2.Length() + 1, str2.c_str() ); return ( tmp ); } static char ctob_table[ 256 ]; static bool ctob_loaded = false; /* character [0-0A-F] to binary [0..15] */ char ctob( char c ) { if ( c >= '0' && c <= '9' ) c -= '0'; else if ( c >= 'A' && c <= 'F' ) c -= ( 'A' - 10 ); else if ( c >= 'a' && c <= 'f' ) c -= ( 'a' - 10 ); else c = -1; return ( c ); } /* raw bytes to hex ascii */ void htoa(const char *src, char *dst, int src_len, int max_dst) { static char *hex_table = "0123456789abcdef"; int bytes_written = 0; while ( ( src_len-- > 0 ) && ( bytes_written + 3 <= max_dst ) ) { *dst++ = hex_table[ *(unsigned char*)src >> 4 ]; *dst++ = hex_table[ *(unsigned char*)src & 0xf ]; src++; bytes_written += 2; } if ( bytes_written < max_dst ) *dst = 0; } /* ascii hex to raw bytes */ int atoh( const char *src, char *dst, int max_dst ) { if (!ctob_loaded) { for (u32 i = 0; i < 256; i++) ctob_table[i] = ctob(i); ctob_loaded = true; } int bytes_written = 0; char upper, lower; if ( !src ) return ( bytes_written ); while ( *src && *(src + 1) && ( bytes_written < max_dst ) ) { upper = ctob_table[*src++]; lower = ctob_table[*src++]; if ( upper == -1 || lower == -1 ) break; dst[ bytes_written++ ] = ( upper << 4 ) | ( lower ); } return ( bytes_written ); } // ascii to hex - host long bool atohhl(const char *src, unsigned int *dst) { unsigned char tmp[ 4 ]; if (atoh(src, (char *)tmp, 4) != 4) return false; // swap to little endian *dst = ( ( tmp[ 3 ] ) | ( tmp[ 2 ] << 8 ) | ( tmp[ 1 ] << 16 ) | ( tmp[ 0 ] << 24 ) ); return true; } const char *stristr(const char *haystack, const char *needle) { const char *hend; const char *a, *b; if ( *needle == 0 ) return ( haystack ); hend = haystack + strlen( haystack ) - strlen( needle ) + 1; while ( haystack < hend ) { if ( toupper( *haystack ) == toupper( *needle ) ) { a = haystack; b = needle; for (;;) { if ( *b == 0 ) return ( haystack ); if ( toupper( *a++ ) != toupper( *b++ ) ) break; } } haystack++; } return ( 0 ); } <file_sep>/Lib/Sort.h #ifndef __SORT_H__ #define __SORT_H__ #include "Comparisons.h" template < class type > __inline void Swap( type *a, type *b ) { type temp = *a; *a = *b; *b = temp; } /* InsertionSort */ template < class type, class Compare > void InsertionSort_SortReckless( type *lower, type *upper, Compare comp ) { for ( type *i = lower; i <= upper; ++i ) { type *next = i - 1, tmp = *i; while ( comp( tmp, *next ) ) { *( next + 1 ) = *next; next--; } *( next + 1 ) = tmp; } } template < class type, class Compare > void InsertionSort_Sort( type *lower, type *upper, Compare comp ) { for ( type *i = lower + 1; i <= upper; ++i ) { type *last = i, *next = last - 1, tmp = *i; while ( last > lower && comp( tmp, *next ) ) { *last = *next; last = next--; } *last = tmp; } } template < class type > void InsertionSort_Sort( type *lower, type *upper ) { InsertionSort_Sort( lower, upper, Less<type>() ); } /* Heap Sort */ template < class type, class Compare > void HeapSort_Float( type *arr, int start, Compare comp ) { int child = start, root, remainder; while ( child > 0 ) { remainder = ( child - 1 ) & 1; root = ( ( child - 1 ) - remainder ) / 2; if ( comp( arr[ root ], arr[ child ] ) ) { Swap( &arr[ root ], &arr[ child ] ); child = root; } else { break; } } } template < class type, class Compare > void HeapSort_Sink( type *arr, int start, int count, Compare comp ) { int root = start, child; while ( ( root * 2 ) + 1 < count ) { child = ( root * 2 ) + 1; if ( child < ( count - 1 ) && comp( arr[ child ], arr[ child + 1 ] ) ) ++child; if ( comp( arr[ root ], arr[ child ] ) ) { Swap( &arr[ root ], &arr[ child ] ); root = child; } else { break; } } } template < class type, class Compare > void HeapSort_Sort( type *arr, int count, Compare comp ) { int start = 0, end = ( count - 1 ); while ( start <= ( count - 2 ) ) { ++start; HeapSort_Float( arr, start, comp ); } while ( end > 0 ) { Swap( &arr[ end ], &arr[ 0 ] ); HeapSort_Sink( arr, 0, end, comp ); end--; } } template < class type > void HeapSort_Sort( type *arr, int count ) { HeapSort_Sort( arr, count, Less<type>() ); } /* http://www.cs.rpi.edu/~musser/gp/introsort.ps IntroSort */ #define INTROSORT_THRESHOLD 16 __inline size_t log2( size_t n ) { size_t pow = 0; while ( n > 1 ) { n >>= 1; ++pow; } return ( pow ); } template < class type, class Compare > __inline type *median( type &a, type &b, type &c, Compare comp ) { if ( comp( a, b ) ) { if ( comp( b, c ) ) { return &b; } else if ( comp( a, c ) ) { return &c; } else { return &a; } } else if ( comp( a, c ) ) { return &a; } else if ( comp( b, c ) ) { return &c; } else { return &b; } } template < class type, class Compare > type *IntroSort_Partition( type *lower, type *upper, Compare comp ) { type pivot = *median( *lower, *( lower + ( upper - lower + 1 ) / 2 ), *upper, comp ); while ( true ) { while ( comp( *lower, pivot ) ) ++lower; while ( comp( pivot, *upper ) ) --upper; if ( lower >= upper ) return ( lower ); Swap( upper, lower ); ++lower; --upper; } } template < class type, class Compare > void IntroSort_SortLoop( type *lower, type *upper, size_t depth_limit, Compare comp ) { while ( upper - lower >= INTROSORT_THRESHOLD ) { if ( depth_limit <= 0 ) { HeapSort_Sort( lower, (int )( upper - lower + 1 ), comp ); return; } depth_limit--; type *mid = IntroSort_Partition( lower, upper, comp ); IntroSort_SortLoop( mid, upper, depth_limit, comp ); upper = mid - 1; } } template < class type, class Compare > void IntroSort_Sort( type *lower, type *upper, Compare comp ) { size_t items = ( upper - lower ) + 1; if ( items <= 1 ) return; IntroSort_SortLoop( lower, upper, log2( items ) * 2, comp ); if ( items > INTROSORT_THRESHOLD ) { InsertionSort_Sort( lower, lower + INTROSORT_THRESHOLD - 1, comp ); InsertionSort_SortReckless( lower + INTROSORT_THRESHOLD, upper, comp ); } else { InsertionSort_Sort( lower, upper, comp ); } } template < class type > void IntroSort_Sort( type *lower, type *upper ) { IntroSort_Sort( lower, upper, Less<type>() ); } #endif // __SORT_H__ <file_sep>/License.cpp #include "Console.h" #include "Callback.h" #include "Strings.h" #include "version.h" #include "resource.h" namespace Licence { BuiltInFunction("Memstar::version", version) { Console::echo("%s", VER_PRODUCTNAME_STR); Console::echo("------------------"); Console::echo("Version: %s", VER_FILEVERSION_STR); #ifdef VER_SPECIAL_STR Console::dbecho("Special Build Note: %s", VER_SPECIAL_STR); #endif #ifdef VER_PRIVATE_STR Console::dbecho("Private Build Note: %s", VER_PRIVATE_STR); #endif #ifdef VER_COMMENT_STR Console::echo("Build Note: %s", VER_COMMENT_STR); #endif Console::echo("------------------"); Console::echo("%s", VER_LEGALCOPYRIGHT_STR); Console::echo("This extension would not be possible without everyone that blazed the trail before me"); Console::echo("the initial versions were written and published by NoFix and floodyberry."); return "true"; } BuiltInFunction("Memstar::license", license) { //HRSRC licenseResource = FindResourceA(NULL, NULL, MAKEINTRESOURCEA(IDR_LICENSE1)); //HGLOBAL licenseLoad = LoadResource(NULL, licenseResource); MessageBoxW(NULL, L"This is from mem.dll!", L"Test!", MB_YESNOCANCEL | MB_ICONQUESTION | MB_SETFOREGROUND); return "true"; } #if 0 class LicenseHandler { public: static PHKEY key; static void OpenRegKey() { LSTATUS status = RegOpenCurrentUser(KEY_READ | KEY_WRITE, key); if (status != ERROR_SUCCESS) { // open file here } } static void WriteRegKey() { LSTATUS status = RegCreateKeyEx(HKEY_CURRENT_USER, "SOFTWARE\Dynamix\Starsiege\mem.dll", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_READ | KEY_WRITE, NULL, key, NULL); RegSetValueEx() } }; INT_PTR CALLBACK LicenseDialog(HWND hwind, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_INITDIALOG: } SetWindowLongA(hwind, DWL_MSGRESULT, IDCONTINUE); return TRUE; } void LicenseAgreement() { int choice = MessageBoxW(NULL, L"In order to use this copy of mem.dll, you must view and accept the license agreements", L"License Agreement Required", MB_OKCANCEL | MB_ICONASTERISK | MB_SETFOREGROUND); if (choice == IDCANCEL) { exit(EXIT_SUCCESS); } //DialogBoxA(NULL, MAKEINTRESOURCEA(IDD_PROPPAGE_SMALL), NULL, LicenseDialog); } struct Init { Init() { LicenseAgreement(); } } init; #endif } <file_sep>/version.h #pragma once #ifndef __VERSION_H__ #define __VERSION_H__ #include <winver.h> /** * Windows Version Info Flags */ #ifndef VER_PRERELEASE_BUILD #define VER_PRERELEASE_BUILD 0 #define VER_BUILDID 0 #endif #ifndef VER_PATCHED_BUILD #define VER_PATCHED_BUILD 0 #endif #ifndef VER_PRIVATE_BUILD #define VER_PRIVATE_BUILD 0 #endif #ifndef VER_SPECIAL_BUILD #define VER_SPECIAL_BUILD 0 #endif //#define VER_SPECIAL_STR "" //#define VER_PRIVATE_STR "" #define VER_COMMENT_STR "StarsiegePlayers Build on 2021-08-05" // Required Information #define VER_FILEVERSION 1,1,0,1 #define VER_FILEVERSIONSTR 1.1.0.1 #define VER_PRODUCTVERSION 1,1,0,1 #define VER_PRODUCTVERSIONSTR 1.1.0.1 #define VER_COMPANYNAME_STR "Starsiege Players Community" #define VER_PRODUCTNAME_STR "mem.dll replacement for Starsiege" #define VER_FILEDESCRIPTION_STR "Neo's replacment memstar dll" #define VER_INTERNALNAME_STR "memstar.dll" #define VER_LEGALCOPYRIGHT_STR "Copyright (C) 2021 Starsiege Players Community, et al." #define VER_ORIGINALFILENAME_STR "mem.dll" #define JOIN(a, b, c, d, e, f, g) JOIN_AGAIN(a, b, c, d, e, f, g) #define JOIN_AGAIN(a, b, c, d, e, f, g) a ## b ## c ## d ## e ## f ## g #define Q(x) #x #define QUOTE(x) Q(x) #ifdef _DEBUG #define VER_DEBUG_BUILD VS_FF_DEBUG #define VER_DEBUGBUILD_STR , Debug #else #define VER_DEBUG_BUILD 0 #define VER_DEBUGBUILD_STR , Release #endif #if VER_PRERELEASE_BUILD != 0 #undef VER_PRERELEASE_BUILD #define VER_PRERELEASE_BUILD VS_FF_PRERELEASE #ifdef VER_BUILDID #define VER_PRERELEASEBUILD_STR , Pre-Release VER_BUILDID #else #define VER_PRERELEASEBUILD_STR , Pre-Release #endif #ifdef VER_DEBUGBUILD_STR #undef VER_DEBUGBUILD_STR #define VER_DEBUGBUILD_STR #endif #else #define VER_PRERELEASEBUILD_STR #endif #if VER_PATCHED_BUILD != 0 #undef VER_PATCHED_BUILD #define VER_PATCHED_BUILD VS_FF_PATCHED #define VER_PATCHEDBUILD_STR , Patched #else #define VER_PATCHEDBUILD_STR #endif #if VER_PRIVATE_BUILD != 0 #undef VER_PRIVATE_BUILD #define VER_PRIVATE_BUILD VS_FF_PRIVATEBUILD #define VER_PRIVATEBUILD_STR , Private #else #define VER_PRIVATEBUILD_STR #endif #if VER_SPECIAL_BUILD != 0 #undef VER_SPECIAL_BUILD #define VER_SPECIAL_BUILD VS_FF_SPECIALBUILD #define VER_SPECIALBUILD_STR , Special #else #define VER_SPECIALBUILD_STR #endif #define VER_FILEVERSION_STR QUOTE(JOIN(VER_FILEVERSIONSTR, VER_DEBUGBUILD_STR, VER_PRERELEASEBUILD_STR, VER_PATCHEDBUILD_STR, VER_PRIVATEBUILD_STR, VER_SPECIALBUILD_STR, \0)) #define VER_PRODUCTVERSION_STR QUOTE(JOIN(VER_PRODUCTVERSIONSTR, VER_DEBUGBUILD_STR, VER_PRERELEASEBUILD_STR, VER_PATCHEDBUILD_STR, VER_PRIVATEBUILD_STR, VER_SPECIALBUILD_STR, \0)) #endif <file_sep>/ScriptGL.h #ifndef __SCRIPTGL_H__ #define __SCRIPTGL_H__ #include "Texture.h" #include "Font.h" namespace ScriptGL { Texture* FindTexture(const char* name); void OnPlayGUIPreDraw(); void OnPlayGUIPostDraw(); extern Font* mFont; extern int mBeginCount; }; #endif // __SCRIPTGL_H__<file_sep>/ScriptGL.cpp #include "ScriptGL.h" #include "FileSystem.h" #include "FontManager.h" #include "HashTable.h" #include "OpenGL.h" #include "Callback.h" #include "GLOpcodes.h" #include "Console.h" class ScriptTexture : public Texture { public: ScriptTexture() : Texture(), mLastUsed(GetTickCount()) { } ~ScriptTexture() { } int LastUsed() const { return (mLastUsed); } void UpdateLastUsed() { mLastUsed = GetTickCount(); } private: int mLastUsed; }; namespace ScriptGL { // types typedef HashTable< String, ScriptTexture*, IKeyCmp, ValueDeleter<String, ScriptTexture*> > ScriptTextureHash; typedef ScriptTextureHash::Iterator TextureIterator; #define __SCRIPTGL_PREDRAW__ ( 0 ) #define __SCRIPTGL_POSTDRAW__ ( 1 ) // glEnable / Disable BuiltInVariable("GL_TEXTURE_2D", int, _GL_TEXTURE_2D, GL_TEXTURE_2D); // glTexEnv BuiltInVariable("GL_DECAL", int, _GL_DECAL, GL_DECAL); BuiltInVariable("GL_MODULATE", int, _GL_MODULATE, GL_MODULATE); BuiltInVariable("GL_REPLACE", int, _GL_REPLACE, GL_REPLACE); // glBlendFunc BuiltInVariable("GL_ZERO", int, _GL_ZERO, GL_ZERO); BuiltInVariable("GL_ONE", int, _GL_ONE, GL_ONE); BuiltInVariable("GL_SRC_COLOR", int, _GL_SRC_COLOR, GL_SRC_COLOR); BuiltInVariable("GL_ONE_MINUS_SRC_COLOR", int, _GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR); BuiltInVariable("GL_SRC_ALPHA", int, _GL_SRC_ALPHA, GL_SRC_ALPHA); BuiltInVariable("GL_ONE_MINUS_SRC_ALPHA", int, _GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); BuiltInVariable("GL_SRC_ALPHA_SATURATE", int, _GL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE); BuiltInVariable("GL_DST_COLOR", int, _GL_DST_COLOR, GL_DST_COLOR); BuiltInVariable("GL_ONE_MINUS_DST_COLOR", int, _GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR); BuiltInVariable("GL_DST_ALPHA", int, _GL_DST_ALPHA, GL_DST_ALPHA); BuiltInVariable("GL_ONE_MINUS_DST_ALPHA", int, _GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA); // glBegin BuiltInVariable("GL_POINTS", int, _GL_POINTS, GL_POINTS); BuiltInVariable("GL_LINES", int, _GL_LINES, GL_LINES); BuiltInVariable("GL_LINE_LOOP", int, _GL_LINE_LOOP, GL_LINE_LOOP); BuiltInVariable("GL_LINE_STRIP", int, _GL_LINE_STRIP, GL_LINE_STRIP); BuiltInVariable("GL_TRIANGLES", int, _GL_TRIANGLES, GL_TRIANGLES); BuiltInVariable("GL_TRIANGLE_STRIP", int, _GL_TRIANGLE_STRIP, GL_TRIANGLE_STRIP); BuiltInVariable("GL_TRIANGLE_FAN", int, _GL_TRIANGLE_FAN, GL_TRIANGLE_FAN); BuiltInVariable("GL_QUADS", int, _GL_QUADS, GL_QUADS); BuiltInVariable("GL_QUAD_STRIP", int, _GL_QUAD_STRIP, GL_QUAD_STRIP); BuiltInVariable("GL_POLYGON", int, _GL_POLYGON, GL_POLYGON); // glDrawTexture BuiltInVariable("GLEX_DRAW", int, _GLEX_DRAW, GLEX_DRAW); BuiltInVariable("GLEX_CENTERED", int, _GLEX_CENTERED, GLEX_CENTERED); BuiltInVariable("GLEX_ROTATED", int, _GLEX_ROTATED, GLEX_ROTATED); BuiltInVariable("GLEX_SCALED", int, _GLEX_SCALED, GLEX_SCALED); // glSetFont BuiltInVariable("GLEX_PIXEL", int, _GLEX_FONT_PIXEL, GLEX_FONT_PIXEL); BuiltInVariable("GLEX_SMOOTH", int, _GLEX_FONT_SMOOTH, GLEX_FONT_SMOOTH); BuiltInVariable("ScriptGL::Latency", int, mLatency, 100); bool mCanDraw = false; int mLastGarbageCollect = 0; int mBeginCount = 0; int mLastGLDraw = 0; ScriptTextureHash mScriptTextures(32); FileSystem mFiles(32); Font* mFont = (NULL); GLCompiler mCompilers[2]; GLCompiler* mCompiler; bool Allowed() { return (mCanDraw); } void Close() { mScriptTextures.Clear(); mFiles.Clear(); } void DefaultSettings() { glDisable(GL_TEXTURE_2D); glDisable(GL_ALPHA_TEST); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, 0); } Texture* FindTexture(const char* name) { String2 key(name); ScriptTexture** find = mScriptTextures.Find(key); if (find) { (*find)->UpdateLastUsed(); return (*find); } ScriptTexture* tmp = new ScriptTexture(); if (!tmp || !mFiles.ReadTGA(key, *tmp) || !mScriptTextures.Insert(key, tmp)) { delete tmp; tmp = (NULL); } return (tmp); } void GarbageCollect(bool active) { mFont = (NULL); int ticks = (GetTickCount()); if (ticks - mLastGarbageCollect < 5000) return; mLastGarbageCollect = ticks; TextureIterator iter = mScriptTextures.Begin(), end = mScriptTextures.End(); while (iter != end) { if (ticks - iter.value()->LastUsed() > 30000) { Console::echo("ScriptGL: Garbage collecting %s", iter.key().c_str()); mScriptTextures.Delete(iter); } else { ++iter; } } } void Open() { Close(); mFiles.Grok("Memstar/ScriptGL"); } void OnDraw(int pre_or_post) { mCanDraw = (OpenGL::IsActive()); if (!Allowed()) return; mCompiler = (&mCompilers[pre_or_post]); int ticks = (GetTickCount()); if (ticks - mLastGLDraw >= mLatency) { char* function = (pre_or_post) ? "ScriptGL::playGUI::onPostDraw" : "ScriptGL::playGUI::onPreDraw"; Vector2i screen; Fear::getScreenDimensions(&screen); String2 dim; dim.Assign("%d %d", screen.x, screen.y); mCompiler->Clear(); if (Console::functionExists(function)) Console::execFunction(1, function, dim.c_str()); if (pre_or_post == __SCRIPTGL_POSTDRAW__) mLastGLDraw = (ticks); } DefaultSettings(); mCompiler->Execute(); mCanDraw = false; } BuiltInFunction("glBegin", _glBegin) { if (!Allowed()) return "false"; if (argc != 1) Console::echo("%s( <cap> )", self); else mCompiler->Push(GLBegin((GLenum)atoi(argv[0]))); return "true"; } BuiltInFunction("glBindTexture", _glBindTexture) { if (!Allowed()) return "false"; if (argc != 1) Console::echo("%s( <file.tga> )", self); else mCompiler->Push(GLBindTexture(argv[0])); return "true"; } BuiltInFunction("glBlendFunc", _glBlendFunc) { if (!Allowed()) return "false"; if (argc != 2) Console::echo("%s( <sFactor>, <dFactor> )", self); else mCompiler->Push(GLBlendFunc((GLenum)atoi(argv[0]), (GLenum)atoi(argv[1]))); return "true"; } BuiltInFunction("glColor4ub", _glColor4ub) { if (!Allowed()) return "false"; if (argc != 4) { Console::echo("%s( <r>, <g>, <b>, <a> ), Values in [0-255]", self); } else { GLubyte c[4]; for (int i = 0; i < 4; i++) c[i] = atoi(argv[i]); mCompiler->Push(GLColor4ub(c[0], c[1], c[2], c[3])); } return "true"; } BuiltInFunction("glDisable", _glDisable) { if (!Allowed()) return "false"; if (argc < 1) Console::echo("%s( <cap> )", self); else mCompiler->Push(GLDisable((GLenum)atoi(argv[0]))); return "true"; } BuiltInFunction("glEnable", _glEnable) { return "true"; } BuiltInFunction("glEnd", _glEnd) { if (!Allowed()) return "false"; mCompiler->Push(GLEnd()); return "true"; } BuiltInFunction("glTexCoord2f", _glTexCoord2f) { if (!Allowed()) return "false"; if (argc != 2) Console::echo("%s( <u>, <v> )", self); else mCompiler->Push(GLTexCoord2f(fromstring<f32>(argv[0]), fromstring<f32>(argv[1]))); return "true"; } BuiltInFunction("glTexEnvi", _glTexEnvi) { if (!Allowed()) return "false"; if (argc != 1) Console::echo("%s( <mode> )", self); else mCompiler->Push(GLTexEnvi(atoi(argv[0]))); return "true"; } BuiltInFunction("glVertex2i", _glVertex2i) { if (!Allowed()) return "false"; if (argc != 2) Console::echo("%s( <x>, <y> )", self); else mCompiler->Push(GLVertex2i((GLint)atoi(argv[0]), (GLint)atoi(argv[1]))); return "true"; } /* Pseudo-GL functions */ BuiltInFunction("glGetTextureDimensions", _glGetTextureDimensions) { if (argc != 1) { Console::echo("%s( <file.tga> )", self); } else { Texture* find = (FindTexture(argv[0])); if (find) { static char dim[256]; Snprintf(dim, 255, "%d %d", find->mWidth, find->mHeight); dim[255] = 0; return dim; } } return "0 0"; } BuiltInFunction("glDrawString", _glDrawString) { if (!Allowed()) return "false"; if (argc != 3) Console::echo("%s( <x>, <y>, <string> )", self); else mCompiler->Push(GLDrawString(atoi(argv[0]), atoi(argv[1]), argv[2])); return "true"; } BuiltInFunction("glDrawTexture", _glDrawTexture) { if (!Allowed()) return "false"; if (argc < 4) { Console::echo("%s( <file.tga>, $GLEX_(CENTERED/DRAW), <x>, <y> )", self); Console::echo("%s( <file.tga>, $GLEX_SCALED, <x>, <y>, <scale_x>, <scale_y> )", self); Console::echo("%s( <file.tga>, $GLEX_ROTATED, <x>, <y>, <scale_x>, <scale_y>, <radians> )", self); } else { int mode = (atoi(argv[1])); float x = 0, y = 0, sx = 1, sy = 1, r = 0; x = fromstring<f32>(argv[2]); y = fromstring<f32>(argv[3]); if (argc >= 6) { sx = fromstring<f32>(argv[4]); sy = fromstring<f32>(argv[5]); } if (argc >= 7) r = fromstring<f32>(argv[6]); mCompiler->Push(GLDrawTexture(argv[0], mode, x, y, sx, sy, r)); } return "true"; } BuiltInFunction("glGetStringDimensions", _glGetStringDimensions) { Vector2i dimensions(0, 0); if (argc != 1) { Console::echo("%s( <string> )", self); } else { if (mFont) dimensions = mFont->StringDimensions(argv[0]); } return tostring(dimensions); } BuiltInFunction("glRectangle", _glRectangle) { if (!Allowed()) return "false"; if (argc != 4) Console::echo("%s( <x>, <y>, <width>, <height> )", self); else mCompiler->Push(GLRectangle( fromstring<f32>(argv[0]), fromstring<f32>(argv[1]), fromstring<f32>(argv[2]), fromstring<f32>(argv[3]))); return "true"; } BuiltInFunction("glRescanTextureDirectory", _glRescanTextureDirectory) { Open(); return "true"; } BuiltInFunction("glSetFont", _glSetFont) { if (argc < 1) { Console::echo("%s( <font name>, [pixel height], $GLEX_(PIXELS/MOOTH), [glow radius] )", self); } else { Font::Rendering mode = (Font::Smooth); int pixel_height = 16; int glow_radius = 0; if (argc >= 2) pixel_height = (atoi(argv[1])); if (argc >= 3) mode = (Font::Rendering)(atoi(argv[2])); if (argc >= 4) glow_radius = (atoi(argv[3])); pixel_height = (pixel_height <= 6) ? 6 : (pixel_height > 1024) ? 1024 : pixel_height; glow_radius = (glow_radius < 2) ? 0 : (glow_radius > 16) ? 16 : glow_radius; if (mode != Font::Pixel && mode != Font::Smooth) mode = (Font::Pixel); // need to execute this now for glGetStringDimension calls GLSetFont setfont(argv[0], pixel_height, mode, glow_radius); setfont.Execute(); if (Allowed()) mCompiler->Push(setfont); } return "true"; } void OnGuiDraw(bool is_predraw) { OnDraw((is_predraw) ? __SCRIPTGL_PREDRAW__ : __SCRIPTGL_POSTDRAW__); } struct Init { Init() { Callback::attach(Callback::OnEndframe, GarbageCollect); Callback::attach(Callback::OnGuiDraw, OnGuiDraw); Open(); } ~Init() { Close(); mFont = (NULL); } } init; }; // namespace ScriptGL<file_sep>/Lib/Callback.h #ifndef __CALLBACK_H__ #define __CALLBACK_H__ namespace Callback { typedef void (*Listener)(bool status); enum Type { OnStarted = 0, OnEndframe, OnOpenGL, OnQuit, OnGuiDraw, NumCallbacks, }; void attach(const Type t, Listener cb); void trigger(const Type t, bool state); }; // namespace Callback #endif // __CALLBACK_H__ <file_sep>/StringFunctions.cpp #include "Console.h" #include "Strings.h" static const u32 stringBufferSize = (65535); static char stringBuffer[stringBufferSize + 1]; const char* substrhelper(const char* str, int start, int len, int srclen) { if ((start < 0) || (len <= 0) || (start >= srclen)) return ""; if (start + len > srclen) len = (srclen - start); if (len >= stringBufferSize) len = (stringBufferSize - 1); memcpy(stringBuffer, str + start, len); stringBuffer[len] = '\x0'; return (stringBuffer); } const char* padhelper(const char* str, int padlen, char padchar, char padjust) { int srclen = (strlen(str)); int needs = (padlen - srclen); if (needs <= 0) return (str); int left = 0, right = 0; switch (padjust) { case 'c': left = ((needs + 1) / 2); right = needs - left; break; case 'l': left = needs; break; case 'r': right = needs; break; } char* out = stringBuffer; if (left) { memset(out, padchar, left); out += left; } memcpy(out, str, srclen); out += srclen; if (right) { memset(out, padchar, right); out += right; } *out = '\x0'; return (stringBuffer); } BuiltInFunction("String::findSubStr", stringFindSubStr) { if (argc != 2) { Console::echo("wrong argcount to %s( str, find );", self); return "-1"; } const char* start = stristr(argv[0], argv[1]); if (!start) return ("-1"); return tostring(start - argv[0]); } BuiltInFunction("getWord", getWord) { if (argc != 2) { Console::echo("wrong argcount to %s(String,nWord)", self); return "-1"; } s32 word = atoi(argv[1]); if (word < 0) return "-1"; const char* in = argv[0]; for (int words = 0; *in; ++words) { while (*in == ' ') in++; if (!*in) { return "-1"; } else if (words == word) { char* out = stringBuffer, * end = stringBuffer + stringBufferSize; while (*in != ' ' && *in && (out < end)) *out++ = *in++; *out = NULL; return (stringBuffer); } else { while (*in && *in != ' ') in++; } } return "-1"; } BuiltInFunction("String::getSubStr", stringGetSubStr) { if (argc != 3) { Console::echo("wrong argcount to %s( str, start, length );", self); return ""; } const char* str = (argv[0]); int start = fromstring<int>(argv[1]), len = fromstring<int>(argv[2]), srclen = (strlen(str)); return (substrhelper(str, start, len, srclen)); } BuiltInFunction("String::Compare", stringCompare) { if (argc != 2) { Console::echo("wrong argcount to %s( str1, str2 );", self); return ""; } return tostring(strcmp(argv[0], argv[1])); } BuiltInFunction("String::NCompare", stringNCompare) { if (argc != 3) { Console::echo("wrong argcount to %s( str1, str2, length );", self); return ""; } return tostring(strncmp(argv[0], argv[1], fromstring<int>(argv[2]))); } BuiltInFunction("String::ICompare", stringICompare) { if (argc != 2) { Console::echo("wrong argcount to %s( str1, str2 );", self); return ""; } return tostring(_stricmp(argv[0], argv[1])); } BuiltInFunction("String::empty", stringEmpty) { if (argc != 1) { Console::echo("wrong argcount to %s( str );", self); return "true"; } const char* tempPtr = argv[0]; while (*tempPtr == ' ') tempPtr++; return (!*tempPtr) ? "true" : "false"; } // just replaces all spaces with the '_' char BuiltInFunction("String::convertSpaces", stringConvertSpaces) { if (argc != 1) { Console::echo("wrong argcount to %s( str );", self); return (""); } const char* src = (argv[0]); char* dest = stringBuffer; while (*src) *dest++ = (*src == ' ') ? '_' : *src++; *dest = '\x0'; return (stringBuffer); } // Zear extensions BuiltInFunction("String::left", stringLeft) { if (argc != 2) { Console::echo("wrong argcount to %s( str, length );", self); return ""; } const char* str = (argv[0]); int start = 0, len = fromstring<int>(argv[1]), srclen = (strlen(str)); return (substrhelper(str, start, len, srclen)); } BuiltInFunction("String::right", stringRight) { if (argc != 2) { Console::echo("wrong argcount to %s( str, length );", self); return ""; } const char* str = (argv[0]); int len = fromstring<int>(argv[1]), srclen = (strlen(str)), start = (srclen - len); if (start < 0) start = 0; return (substrhelper(str, start, len, srclen)); } BuiltInFunction("String::starts", stringStarts) { if (argc != 2) { Console::echo("wrong argcount to %s( str, start );", self); return ""; } const char* str = (argv[0]), * starts = (argv[1]); return (stristr(str, starts) == str) ? "true" : "false"; } BuiltInFunction("String::ends", stringEnds) { if (argc != 2) { Console::echo("wrong argcount to %s( str, end );", self); return ""; } const char* str = (argv[0]), * ends = (argv[1]); int srclen = strlen(str), endlen = strlen(ends); return (stristr(str, ends) == (str + (srclen - endlen))) ? "true" : "false"; } BuiltInFunction("String::insert", stringInsert) { if (argc != 3) { Console::echo("wrong argcount to %s( str, insert, index );", self); return ""; } const char* str = (argv[0]), * insert = (argv[1]); int index = (fromstring<int>(argv[2])); int srclen = strlen(str), ilen = strlen(insert); if (index > srclen) index = srclen; // copy leading bit if (index > 0) memcpy(stringBuffer, str, index); // copy inserted bit memcpy(stringBuffer + index, insert, ilen); // copy tail bit if (index < srclen) memcpy(stringBuffer + index + ilen, str + index, srclen - index); stringBuffer[ilen + srclen] = NULL; return (stringBuffer); } BuiltInFunction("String::len", stringLen) { if (argc != 1) { Console::echo("wrong argcount to %s( str );", self); return ""; } return (tostring(strlen(argv[0]))); } BuiltInFunction("String::length", stringLength) { if (argc != 1) { Console::echo("wrong argcount to %s( str );", self); return ""; } return (tostring(strlen(argv[0]))); } BuiltInFunction("chr", stringChr) { if (argc != 1) { Console::echo("wrong argcount to %s( ordinal );", self); return ""; } stringBuffer[0] = (unsigned char)(fromstring<int>(argv[0])); stringBuffer[1] = '\x0'; return (stringBuffer); } BuiltInFunction("ord", stringOrd) { if (argc != 1) { Console::echo("wrong argcount to %s( char );", self); return ""; } return (tostring(argv[0][0])); } BuiltInFunction("String::rpad", stringRPad) { if ((argc < 2) || (argc > 3)) { Console::echo("wrong argcount to %s( str, width, <padchar> );", self); return ""; } const char* str = argv[0]; int width = fromstring<int>(argv[1]); char pad = (argc == 3) ? argv[2][0] : ' '; return (padhelper(str, width, pad, 'r')); } BuiltInFunction("String::lpad", stringLPad) { if ((argc < 2) || (argc > 3)) { Console::echo("wrong argcount to %s( str, width, <padchar> );", self); return ""; } const char* str = argv[0]; int width = fromstring<int>(argv[1]); char pad = (argc == 3) ? argv[2][0] : ' '; return (padhelper(str, width, pad, 'l')); } BuiltInFunction("String::cpad", stringCPad) { if ((argc < 2) || (argc > 3)) { Console::echo("wrong argcount to %s( str, width, <padchar> );", self); return ""; } const char* str = argv[0]; int width = fromstring<int>(argv[1]); char pad = (argc == 3) ? argv[2][0] : ' '; return (padhelper(str, width, pad, 'c')); } BuiltInFunction("String::trim", stringTrim) { if (argc != 1) { Console::echo("wrong argcount to %s( str );", self); return ""; } const char* str = argv[0], * front = str, * back = str + strlen(str) - 1; while (*front == ' ') ++front; while (back >= str && *back == ' ') --back; if (front > back) return (""); memcpy(stringBuffer, front, back - front + 1); stringBuffer[back - front + 1] = '\x0'; return (stringBuffer); } BuiltInFunction("String::toupper", stringToupper) { if (argc != 1) { Console::echo("wrong argcount to %s( str );", self); return ""; } const char* str = argv[0]; char* out = stringBuffer; while (*str) *out++ = toupper(*str++); *out = NULL; return (stringBuffer); } BuiltInFunction("String::tolower", stringTolower) { if (argc != 1) { Console::echo("wrong argcount to %s( str );", self); return ""; } const char* str = argv[0]; char* out = stringBuffer; while (*str) *out++ = tolower(*str++); *out = NULL; return (stringBuffer); } BuiltInFunction("String::char", stringChar) { if (argc != 2) { Console::echo("wrong argcount to %s( str, charIndex );", self); return ""; } const char* str = argv[0]; char* out = stringBuffer; int idx = fromstring<int>(argv[1]); int len = strlen(str); if (idx < 0 || idx >= len) return (""); *out++ = str[idx]; *out = NULL; return (stringBuffer); } BuiltInFunction("String::Replace", stringReplace) { if (argc != 3) { Console::echo("wrong argcount to %s( str, search, replace );", self); return ""; } const char* str = argv[0], * search = argv[1], * replace = argv[2], * in = str, * found; char* out = stringBuffer, * end = out + stringBufferSize; size_t searchlen = strlen(search), replen = strlen(replace); while (out < end) { found = stristr(in, search); if (!found) break; size_t tocopy = Min(found - in, end - out); memcpy(out, in, tocopy); out += tocopy; tocopy = Min<size_t>(replen, end - out); memcpy(out, replace, tocopy); out += tocopy; in = found + searchlen; } while ((out < end) && *in) *out++ = *in++; *out = '\x0'; return (stringBuffer); } BuiltInFunction("sprintf", sprintf) { if ((argc < 1) || (argc > 11)) { Console::echo("wrong argcount to %s(string, [Arg1 ... Arg9] )", self); return ("false"); } const char* in = argv[0]; char* out = stringBuffer, * end = stringBuffer + stringBufferSize; while (*in && (out < end)) { if (*in == '%') { s32 idx = (in[1] - 48); // make sure the index refers to an actual argument if ((idx >= 1 && idx <= 9) && (idx <= (argc - 1))) { const char* str = argv[idx]; while (*str && (out < end)) *out++ = *str++; } else if (in[1] == '%') { *out++ = '%'; } // don't inc if it's the end of the string in += (in[1]) ? 2 : 1; } while (*in && (*in != '%') && (out < end)) *out++ = *in++; } *out = NULL; return (stringBuffer); } BuiltInFunction("strcat", strcat) { char* out = stringBuffer, * end = stringBuffer + stringBufferSize; for (s32 i = 0; i < argc; i++) { for (const char* in = argv[i]; *in && (out < end); ) *out++ = *in++; } *out = NULL; return stringBuffer; } BuiltInFunction("escapeString", escapeString) { if (argc != 1) { Console::echo("wrong argcount to %s( String )", self); return (""); } return escapestring(argv[0], stringBufferSize, stringBuffer); } BuiltInFunction("String::Escape", stringEscape) { if (argc != 1) { Console::echo("wrong argcount to %s( String )", self); return (""); } return escapestring(argv[0], stringBufferSize, stringBuffer); } BuiltInFunction("String::Dup", stringDup) { if (argc != 2) { Console::echo("wrong argcount to %s( String, DupCount )", self); return (""); } const char* str = argv[0]; int len = strlen(str), reps = fromstring<int>(argv[1]); char* out = stringBuffer, * end = stringBuffer + stringBufferSize; while ((reps > 0) && (out + len < end)) { memcpy(out, str, len); out += len; --reps; } *out = NULL; return (stringBuffer); } BuiltInFunction("String::explode", stringExplode) { if (argc != 3) { Console::echo("wrong argcount to %s( String, Seperator, ArrayName )", self); return "0"; } const char* in = argv[0], * sep = argv[1], * arrayname = argv[2]; int seplen = strlen(sep), inlen = strlen(in), items = 0; while (inlen > 0) { const char* pos = strstr(in, sep); int piecelen = (pos) ? pos - in : inlen; Console::setVariable(format("$%s%d", arrayname, items++), substrhelper(in, 0, piecelen, inlen)); in += piecelen + seplen; inlen -= piecelen + seplen; } return (tostring(items)); } <file_sep>/MS_Stub.cpp #include "Memstar.h" extern "C" DLLAPI void* MS_Calloc(size_t amt, size_t zero) { return calloc(amt, zero); } extern "C" DLLAPI void* MS_Malloc(size_t amt) { return malloc(amt); } extern "C" DLLAPI void MS_Free(void* block) { free(block); } extern "C" DLLAPI void* MS_Realloc(void* block, size_t amt) { return realloc(block, amt); } <file_sep>/VersionSnoop.h #ifndef __VERSIONSNOOP_H__ #define __VERSIONSNOOP_H__ #include "Memstar.h" const enum VERSION { vNotGame = -2, vUnknown = -1, v001000 = 0, v001002 = 1, v001003 = 2, v001004 = 3 }; static wchar_t* VersionStrings[5] = { L"V001.000R", L"V001.002R", L"V001.003R", L"V001.004R", L"Unknown", }; static char* VersionCStrings[5] = { "V001.000R", "V001.002R", "V001.003R", "V001.004R", "Unknown", }; namespace VersionSnoop { struct VersionInfo { u32 PTR; DWORD Value; VERSION Version; }; VERSION GetVersion(); VERSION versionSnoop(); wchar_t* GetVersionString(VERSION in); char* GetVersionCString(VERSION in); static DWORD* versionPtr; static VERSION Version = VERSION::vUnknown; }; #endif
76e463f9d95c2247a294e363de44c3b5c62ae58d
[ "Markdown", "C", "C++" ]
52
C
StarsiegePlayers/memstar
9e5e9b649d523834863736788f3ab121ad51e235
e4141b0cc81e8a7a24a376e8fbfe7df1226392a0
refs/heads/master
<repo_name>mayomi1/street-capital-conference<file_sep>/router.js express = require('express'); const TalkController = require('./controllers/talkController'); const SpeakerController = require('./controllers/speakerController'); const AttendeeController = require('./controllers/attendeeController'); module.exports = function (app) { // Initializing route groups const apiRoutes = express.Router(), talkRoutes = express.Router(), speakerRoutes = express.Router(), attendeeRoutes = express.Router(); apiRoutes.use('/talk', talkRoutes); apiRoutes.use('/attendee', attendeeRoutes); apiRoutes.use('/speaker', speakerRoutes); // route to Talk talkRoutes.get('/', TalkController.getAllTalk); talkRoutes.get('/:talk_id', TalkController.getTalk); talkRoutes.post('/', TalkController.createTalk); talkRoutes.delete('/:talk_id', TalkController.deleteTalk); // route to speaker speakerRoutes.post('/:talk_id', SpeakerController.addSpeaker); speakerRoutes.delete('/:speaker_id', SpeakerController.deleteSpeaker); //route to attendee attendeeRoutes.post('/:talk_id', AttendeeController.addAttendee); attendeeRoutes.delete('/:attendee_id', AttendeeController.deleteAttendee); // Set url for API group routes app.use('/api', apiRoutes); }; <file_sep>/models/talk.js const mongoose = require('mongoose'), Schema = mongoose.Schema; const speaker = require('./speaker'); const attendee = require('./attendee'); //================================ // Talk Schema //================================ const TalkSchema = new Schema({ title: { type: String }, abstract: { type: String }, room: { type: Number }, speaker: [{type: Schema.Types.ObjectId, ref: 'speaker'}], attendee: [{type: Schema.Types.ObjectId, ref: 'attendee'}] }, { timestamps: true }); const Talk = module.exports = mongoose.model('talk', TalkSchema); module.exports.getAllTalk = () => { return Talk.find({}); }; module.exports.findBy = (findWith) => { return Talk.find(findWith); }; module.exports.findOneTalk = (query) => { return Talk.findOne(query); }; module.exports.getTalkById = (id) => { return Talk.findById(id); }; module.exports.deleteTalk = (id) => { return Talk.findByIdAndRemove(id); }; <file_sep>/README.md # street-capital-conference<file_sep>/config/helper.js /** * Created by mayomi on 9/16/18 by 1:05 PM. */ const CONSTANT = require('./constant'); const TalkModel = require('../models/talk'); // Set user info from request exports.setUserInfo = function setUserInfo(request) { const getUserInfo = { _id: request._id, email: request.email, }; return getUserInfo; }; /** * return unknown error * @param res * @param err * @returns {*} */ exports.unknownError = (res, err) => { return res.json({ status: false, message: CONSTANT.unknownError, error: err.stack, data : null }) }; /** * Return a known Error * @param res * @param message * @returns {*} */ exports.knownError = (res, message) => { return res.json({ status: false, message: message, data : null }) }; /** * return a success response * @param res * @param message * @param data * @returns {*} */ exports.successResponse = (res, message, data) => { return res.json({ status: true, message: message, data: data, }) }; /** * return success response for authentication * @param res * @param token * @param userInfo * @returns {*} */ exports.successAuthResponse = (res, token, userInfo) => { return res.json({ status: true, token: token, user: userInfo, }); }; exports.checkAuthorization = (res, req) => { if(!req.user) { return res.json({ status: false, message: 'Authentication is required', }) } } exports.pushSpeaker2Talk = (talk_id, newModel) => { const query = { _id: talk_id }; TalkModel.findOneTalk(query).then(talk => { talk.speaker.push(newModel); talk.save(); }) }; exports.pushAttendee2Talk = (talk_id, newModel) => { const query = { _id: talk_id }; TalkModel.findOneTalk(query).then(talk => { talk.attendee.push(newModel); talk.save(); }) }; <file_sep>/models/attendee.js /** * Created by mayomi on 9/16/18 by 12:50 PM. */ const mongoose = require('mongoose'); mongoose.plugin(schema => { schema.options.usePushEach = true }); const Schema = mongoose.Schema; //================================ // Attendee Schema //================================ const AttendeeSchema = new Schema({ talk_id: { type: String }, name: { type: String }, company: { type: String }, email: { type: String }, registered: { type: Date, default: Date.now } }, { timestamps: true }); const Attendee = module.exports = mongoose.model('attendee', AttendeeSchema); module.exports.deleteAttendee = (id) => { return Attendee.findByIdAndRemove(id); }; <file_sep>/config/constant.js /** * Created by mayomi on 9/16/18 by 1:06 PM. */ module.exports = { 'emailErr': 'You must enter an email address.', 'emailExist': 'That email address is already in use.', 'passwordErr': 'You must enter a password.', 'phoneNumberErr': 'Phone number is required', 'unknownError': 'Please try again, an error occurred', 'secret': 'asas' }; <file_sep>/controllers/talkController.js /** * Created by mayomi on 9/16/18 by 1:03 PM. */ const Helper = require('../config/helper'); const knownError = Helper.knownError; const successResponse = Helper.successResponse; const unknownError = Helper.unknownError; const TalkModel = require('../models/talk'); exports.createTalk = (req, res) => { const { title, abstract, room} = req.body; // Check for requirement switch (true) { case !title: return knownError(res, 'Title is required'); case !abstract: return knownError(res, 'Abstract is required'); case !room: return knownError(res, 'Room is required'); case !Number.isInteger(Number(room)): return knownError(res, 'Room should be a number'); default: ''; } const newTalk = TalkModel({ title, abstract, room }); newTalk.save() .then(talk => successResponse(res, 'Your talk has been created', talk)) .catch(error => unknownError(res, error)) }; exports.getAllTalk = (req, res) => { TalkModel.find({}) .populate('speaker') .populate('attendee') .then(talk => successResponse(res, 'get all talk', talk)) .catch(error => unknownError(res, error)); }; exports.getTalk = (req, res) => { const talkId = req.params.talk_id; const findWith = { _id: talkId }; TalkModel.findBy(findWith) .populate('speaker') .populate('attendee') .then(talk => successResponse(res, 'get talk', talk)) .catch(error => unknownError(res, error)); }; exports.deleteTalk = (req, res) => { const {talk_id} = req.params; TalkModel.deleteTalk(talk_id) .then(()=>successResponse(res, 'Talk deleted', null)) .catch(error=>unknownError(res, error)) }
983b7aa49e62304cc82c48ef0d2020390ba7bb29
[ "JavaScript", "Markdown" ]
7
JavaScript
mayomi1/street-capital-conference
36b12ab1be56fe502c13ea262f3fd9c575a17f66
cb9b091e13efb37445db8d5cf241d7b9b14e286d
refs/heads/master
<repo_name>bhzunami/recrawl<file_sep>/crawler/reanalytics/spiders/homegate.py # -*- coding: utf-8 -*- """ The ad is in the div result-items-list class and every reulst has the id resultItemPanel0 with the number Links: https://www.homegate.ch/kaufen/immobilien/kanton-{kanton}/trefferliste?tab=list https://www.homegate.ch/mieten/immobilien/kanton-{kanton}/trefferliste?tab=list Author: <NAME> <<EMAIL>> """ import random import scrapy from ..models import Ad class Homegate(scrapy.Spider): """Homegate crawler """ name = "homegate" base_url = "https://homegate.ch" start_urls = ['https://www.homegate.ch/kaufen/immobilien/kanton-aargau/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-appenzellinnerrhoden/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-appenzellausserrhoden/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-baselland/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-baselstadt/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-bern/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-fribourg/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-genf/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-glarus/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-graubuenden/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-jura/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-luzern/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-neuchatel/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-nidwalden/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-obwalden/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-st-gallen/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-schaffhausen/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-schwyz/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-solothurn/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-thurgau/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-tessin/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-uri/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-vaud/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-wallis/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-zug/trefferliste?tab=list', 'https://www.homegate.ch/kaufen/immobilien/kanton-zurich/trefferliste?tab=list', # Rents 'https://www.homegate.ch/mieten/immobilien/kanton-aargau/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-appenzellinnerrhoden/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-appenzellausserrhoden/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-baselland/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-baselstadt/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-bern/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-fribourg/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-genf/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-glarus/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-graubuenden/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-jura/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-luzern/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-neuchatel/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-nidwalden/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-obwalden/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-st-gallen/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-schaffhausen/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-schwyz/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-solothurn/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-thurgau/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-tessin/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-uri/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-vaud/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-wallis/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-zug/trefferliste?tab=list', 'https://www.homegate.ch/mieten/immobilien/kanton-zurich/trefferliste?tab=list' ] @staticmethod def get_clean_url(url): """Returns clean ad url for storing in database """ return url.split('?')[0] def start_requests(self): """Start method """ # Go through all urls random.shuffle(self.start_urls) for url in self.start_urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): """Parse the page """ # Go through all ads link_path = '//div[starts-with(@id, "resultItemPanel")]' \ '/article/a[contains(@class, "detail-page-link")]/@href' for link in response.xpath(link_path).extract(): next_add = response.urljoin(link) yield scrapy.Request(next_add, callback=self.parse_ad) next_page_path = '//div[@class="paginator-container"]' \ '/ul/li[@class="next"]/a/@href' next_page_url = response.xpath(next_page_path).extract_first() if next_page_url: next_page = response.urljoin(next_page_url) yield scrapy.Request(next_page, callback=self.parse) def parse_ad(self, response): """Parse single add """ ad = Ad() # object id ad['object_id'] = response.url.split("/")[-1] ad['crawler'] = 'homegate' ad['url'] = self.get_clean_url(response.url) ad['buy'] = True if 'kaufen' in ad['url'] else False image_urls = response.xpath('//div[@id="detail-gallery-slides"]//img/@data-lazy').extract() ad['images'] = ', '.join([self.base_url+url for url in image_urls]) # Owner owner = '//div[contains(@class, "detail-owner")]/div[@class="infos"]/div[@class="description"]/p' ad['owner'] = response.xpath(owner).extract_first() # reference number ref_path = '//div[contains(@class, "ref")]/span[contains(@class, "text--ellipsis")]/text()' ad['reference_no'] = response.xpath(ref_path).extract_first() # Address address = response.xpath('//div[contains(@class, "detail-address")]/a') ad['street'] = address.xpath('h2/text()').extract_first() ad['place'] = address.xpath('span/text()').extract_first() # Prices price_path = '//div[contains(@class, "detail-price")]/ul/li/span/span/text()' prices = response.xpath(price_path).extract() # Before the price there is a 'CHF' if len(prices) == 6: # brutto, netto, additional ad['price_brutto'] = prices[1].replace("'", "").replace(".–", "") ad['price_netto'] = prices[3].replace("'", "").replace(".–", "") ad['additional_costs'] = prices[5].replace("'", "").replace(".–", "") elif len(prices) == 4: # price and netto ad['price_brutto'] = prices[1].replace("'", "").replace(".–", "") ad['price_netto'] = prices[3].replace("'", "").replace(".–", "") elif len(prices) == 2: ad['price_brutto'] = prices[1].replace("'", "").replace(".–", "") else: ad['price_brutto'] = prices[0] # Characteristics / Merkmale und Ausstattung characteristics_path = '//div[contains(@class, "detail-configuration")]/ul/li/text()' data = {} characteristics = response.xpath(characteristics_path).extract() for characteristic in characteristics: data[characteristic] = True ad['characteristics'] = data # Description description_path = '//div[contains(@class, "detail-description")]//text()' ad['description'] = ' '.join(response.xpath(description_path).extract()).replace("'", " ") # list key_path = '//div[contains(@class, "detail-key-data")]/ul/li[not(contains(@style, "display:none"))]' key_data = response.xpath(key_path) ad['additional_data'] = {} for data in key_data: key, *values = data.xpath('span//text()').extract() value = values[0] try: key = self.settings['KEY_FIGURES'][key] ad[key] = value except KeyError: self.logger.warning("This key not in database: {}".format(key)) ad['additional_data'][key] = value yield ad <file_sep>/crawler/reanalytics/settings.py # -*- coding: utf-8 -*- # Scrapy settings for reanalytics project # import os import datetime BOT_NAME = 'reanalytics' SPIDER_MODULES = ['reanalytics.spiders'] NEWSPIDER_MODULE = 'reanalytics.spiders' # OWN SETTINGS: DATABASE_URL = os.environ.get('DATABASE_URL', 'postgresql://localhost:5432/immo') #LOG_ENABLED = False #LOG_LEVEL = 'ERROR' LOG_STDOUT = True LOG_LEVEL = "ERROR" PROXY = os.environ.get('PROXY_URL', 'http://127.0.0.1:8888/?noconnect') API_SCRAPOXY = os.environ.get('API_SCRAPOXY', 'http://127.0.0.1:8889/api') API_SCRAPOXY_PASSWORD = os.environ.get('API_SCRAPOXY_PASSWORD', '<PASSWORD>') WAIT_FOR_SCALE = int(os.environ.get('WAIT_FOR_SCALE', 5)) WAIT_FOR_START = int(os.environ.get('WAIT_FOR_START', 5)) ADMIN_BASE_URL = 'https://api3.geo.admin.ch/rest/services/api/SearchServer' # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) CONCURRENT_REQUESTS = 4 # Anzahl maximalen gleichzeitigen Anfragen CONCURRENT_ITEMS = 100 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 5 # Wie lange wird gewartet bis zum nächsten request # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html DOWNLOADER_MIDDLEWARES = { 'reanalytics.middlewares.crawledURLCheck.CrawledURLCheck': 100, 'scrapoxy.downloadmiddlewares.proxy.ProxyMiddleware': 101, 'scrapoxy.downloadmiddlewares.wait.WaitMiddleware': 102, 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': None, } # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html EXTENSIONS = { 'reanalytics.extensions.crawlerStats.CrawlerStats': 100, # 'scrapy.extensions.telnet.TelnetConsole': None, } # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'reanalytics.pipelines.municipalityFinder.MunicipalityFinderPipeline': 110, 'reanalytics.pipelines.objectTypeFinder.ObjectTypeFinderPipeline': 120, 'reanalytics.pipelines.duplicateCheck.DuplicateCheckPipeline': 130, 'reanalytics.pipelines.coordinates.CoordinatesPipeline': 140, 'reanalytics.pipelines.databaseWriter.DatabaseWriterPipeline': 200, # 'reanalytics.pipelines.jsonWriter.JSONWriterPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' # FIELDS KEY_FIGURES = { 'Verkaufspreis': 'price_brutto', # homegate, immoscout24 'Preis': 'price_brutto', # newhome 'Bruttomiete (Monat)': 'price_brutto', # immoscout24 'Nebenkosten (Monat)': 'additional_costs', # immoscout24 'Nettomiete (Monat)': 'price_netto', # immoscout24 'Kaufpreis': 'price_brutto', # immoscout24 'Preis Garage': 'additional_costs', # newhome 'Preis Abstellplatz': 'additional_costs', # newhome 'Nettomiete / Monat': 'price_netto', # newhome 'Nebenkosten / Monat': 'additional_costs', # newhome 'Miete / Monat': 'price_brutto', # newhome 'Etage': 'floor', # homegate, urbanhome 'Stockwerk': 'floor', # newhome, immoscout24 'Anzahl Etagen': 'num_floors', # homegate 'Etagen im Haus': 'num_floors', # newhome, urbanhome 'Anzahl Stockwerke': 'num_floors', # immoscout24 'Verfügbar': 'available', # homegate, urbanhome 'Bezug': 'available', # newhome 'Verfügbarkeit': 'available', # immoscout24 'Objekttyp': 'objecttype', # homegate 'Objektart': 'objecttype', # newhome 'Zimmer': 'num_rooms', # homegate, newhome, urbanhome 'Anzahl Zimmer': 'num_rooms', 'Wohnfläche': 'living_area', # homegate, newhome, urbanhome, immoscout24 'Baujahr': 'build_year', # homegate, newhome, immoscout24 'Nutzfläche': 'effective_area', # homegate, immoscout24 'Kubatur': 'cubature', # homegate, newhome, immoscout24 'Raumhöhe': 'room_height', # homegate 'Grundstückfläche': 'plot_area', # homegate, newhome 'Grundstücksfläche': 'plot_area', # immoscout24 'Grundstück': 'plot_area', # urbanhome 'Zustand': 'condition', # newhome 'Letzte Renovation': 'last_renovation_year', # homegate, immoscout24 'Renoviert im Jahr': 'last_renovation_year', # newhome 'Immocode' : 'object_id', # newhome 'ImmoScout24-Code': 'object_id', # immoscout24 'Inserate-Nr': 'object_id', # urbanhome 'Objektnummer': 'reference_no', # newhome 'Referenz': 'reference_no', # immoscout24 'Objekt-Referenz': 'reference_no', # urbanhome 'Qualitätslabel': 'quality_label', # newhome } # Logging configuration current_time = datetime.datetime.now() LOGGING_SETTINGS = { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" } }, "handlers": { "console": { "class": "logging.StreamHandler", "level": "ERROR", "formatter": "simple", "stream": "ext://sys.stdout" }, "file_handler": { "class": "logging.handlers.RotatingFileHandler", "level": "INFO", "formatter": "simple", "filename": "logs/log_crawler-{}-{}-{}.log".format( current_time.day, current_time.month, current_time.year), "maxBytes": 10485760, "backupCount": 20, "encoding": "utf8" } }, "root": { "level": "INFO", "handlers": ["file_handler", "console"] }, "loggers": { "scrapy": { "level": "INFO", "handlers": ["console"], }, "scrapy.core.engine": { "level": "INFO", "handlers": ["file_handler"], }, "twisted": { "level": "ERROR", "handlers": ["file_handler"] }, "run": { "level": "INFO", "handlers": ["console", "file_handler"] }, "reanalytics": { "level": "ERROR", "handlers": ["console", "file_handler"], "propagate": "yes", } } } <file_sep>/superset/superset_config.py import os #--------------------------------------------------------- # Superset specific config #--------------------------------------------------------- ROW_LIMIT = int(os.environ.get('ROW_LIMIT', 5000)) SUPERSET_WORKERS = int(os.environ.get('SUPERSET_WORKERS', 4)) SUPERSET_WEBSERVER_PORT = int(os.environ.get('APP_PORT', 8088)) #--------------------------------------------------------- #--------------------------------------------------------- # Flask App Builder configuration #--------------------------------------------------------- # Your App secret key SECRET_KEY = os.environ.get('SECRET_KEY', 'G7_JNk:K[?=;_}>') # The SQLAlchemy connection string to your database backend # This connection defines the path to the database that stores your # superset metadata (slices, connections, tables, dashboards, ...). # Note that the connection information to connect to the datasources # you want to explore are managed directly in the web UI # SQLALCHEMY_DATABASE_URI = 'sqlite:////path/to/superset.db' DATABASE_USER = os.environ.get('DATABASE_USER', 'superset') DATABASE_PASSWORD = os.environ.get('DATABASE_PASSWORD', '<PASSWORD>') DATABSE_NAME = os.environ.get('DATABASE_NAME', 'superset') DATABASE_HOST = os.environ.get('DATABASE_HOST', 'localhost') SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://{}:{}@{}:5432/{}'.format(DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABSE_NAME) SQLALCHEMY_TRACK_MODIFICATIONS = True CACHE_CONFIG = { 'CACHE_TYPE': 'redis', 'CACHE_DEFAULT_TIMEOUT': 300, 'CACHE_KEY_PREFIX': 'superset_', 'CACHE_REDIS_HOST': 'redis', 'CACHE_REDIS_PORT': 6379, 'CACHE_REDIS_DB': 1, 'CACHE_REDIS_URL': 'redis://redis:6379/1'} # Flask-WTF flag for CSRF WTF_CSRF_ENABLED = True # Add endpoints that need to be exempt from CSRF protection WTF_CSRF_EXEMPT_LIST = [] # Set this API key to enable Mapbox visualizations MAPBOX_API_KEY = os.environ.get('MAPBOX_KEY', '')<file_sep>/scrapoxy/Dockerfile # To run the container: # docker run -e COMMANDER_PASSWORD='<PASSWORD>' \ # -e PROVIDERS_AWSEC2_ACCESSKEYID='YOUR ACCESS KEY ID' \ # -e PROVIDERS_AWSEC2_SECRETACCESSKEY='YOUR SECRET ACCESS KEY' \ # -it -p 8888 -p 8889 fabienvauchelles/scrapoxy # # Use the newest version of scaproxy because the old had an issue when shutown a instance it was not removed FROM mhart/alpine-node:6 EXPOSE 8888 8889 # Install the newest Scrapoxy RUN npm install -g scrapoxy # Add configuration ADD config.js . # Start scrapoxy CMD scrapoxy start config.js -d <file_sep>/crawler/run.py # -*- coding: utf-8 -*- """ https://github.com/fabienvauchelles/scrapoxy-python-api/blob/master/scrapoxy/downloadmiddlewares/scale.py https://github.com/fabienvauchelles/scrapoxy-python-api/blob/master/scrapoxy/commander.py """ import time import os import datetime import logging import csv import scrapy from scrapy.crawler import CrawlerProcess from scrapy.utils.log import configure_logging from reanalytics.spiders.homegate import Homegate from reanalytics.spiders.newhome import Newhome from reanalytics.spiders.immoscout24 import Immoscout24 from scrapy.utils.project import get_project_settings from scrapoxy.commander import Commander from threading import Thread from models import Advertisement from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine import pdb # Prepare log system, do not use scrpay as root logger if not os.path.isdir('logs'): os.mkdir('logs') logger = logging.getLogger("run") class Crawlers(Thread): def __init__(self, process, spiders): Thread.__init__(self) self.process = process self.spiders = spiders def run(self): for spider in self.spiders: self.process.crawl(spider) self.process.start() logger.debug("Finish with crawler thread") class App(object): def __init__(self): self.settings = get_project_settings() self.commander = Commander(self.settings.get('API_SCRAPOXY'), self.settings.get('API_SCRAPOXY_PASSWORD')) configure_logging(settings=None, install_root_handler=False) logging.config.dictConfig(self.settings['LOGGING_SETTINGS']) def prepare_instances(self): if len(self.settings.get('DOWNLOADER_MIDDLEWARES', {})) <= 1: logger.info("Do not run crawler over proxy") return min_sc, required_sc, max_sc = self.commander.get_scaling() required_sc = max_sc self.commander.update_scaling(min_sc, required_sc, max_sc) wait_for_scale = self.settings.get('WAIT_FOR_SCALE') time.sleep(wait_for_scale) def runCrawlers(self): process = CrawlerProcess(self.settings) crawl_thread = Crawlers(process=process, spiders=[Homegate, Newhome, Immoscout24]) crawl_thread.start() rounds = 0 while crawl_thread.is_alive(): if rounds == (4320): # 4320*10(sleep) = 12h logger.info("Run into time out") break rounds += 1 time.sleep(10) logger.debug("Stopping all crawlers..") process.stop() while crawl_thread.is_alive(): logger.debug("Wait for crawlers to clean up...") time.sleep(100) def shutdown_instances(self): if len(self.settings.get('DOWNLOADER_MIDDLEWARES', {})) <= 1: logger.info("Nothing to stop, because no instances were started") return min_sc, required_sc, max_sc = self.commander.get_scaling() self.commander.update_scaling(min_sc, 0, max_sc) def getCrawledData(self): engine = create_engine(self.settings.get('DATABASE_URL')) Session = sessionmaker(bind=engine, expire_on_commit=True) session = Session() from_time = datetime.datetime.now() - datetime.timedelta(days=1) ads = session.query(Advertisement).filter(Advertisement.last_seen >= from_time).all() with open("crawled_ads.csv", "w", newline="") as csvfile: csvwriter = csv.writer(csvfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL) csvwriter.writerow([column.key for column in Advertisement.__table__.columns]) for ad in ads: csvwriter.writerow(list(ad)) print(len(ads)) def main(): # Wait 5 seconds until all containers are started time.sleep(5) app = App() app.prepare_instances() app.runCrawlers() app.shutdown_instances() if __name__ == "__main__": main() <file_sep>/crawler/reanalytics/pipelines/objectTypeFinder.py # -*- coding: utf-8 -*- """ Find the correct municipality """ import logging from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from models import ObjectType from ..settings import DATABASE_URL logger = logging.getLogger(__name__) class ObjectTypeFinderPipeline(object): def open_spider(self, spider): """ Initializes database connection and sessionmaker. Creates deals table. """ engine = create_engine(DATABASE_URL) self.Session = sessionmaker(bind=engine, expire_on_commit=True) self.session = None def process_item(self, item, spider): self.session = self.Session() object_str = item.get('objecttype', '').lower() # Check if the type of the object is already in the Database # If we do not have the type we store a new type. logger.debug("Search for type %s", object_str) obtype = self.session.query(ObjectType).filter(ObjectType.name == object_str).first() if not obtype: logger.info("New objecttype found: {}".format(object_str)) # Store new ObjectType obtype = ObjectType(name=object_str) self.session.add(obtype) # To get the new id self.session.commit() logger.debug("Objecttype stored with id: %i", obtype.id) # Set the correct id item['obtype_id'] = obtype.id self.session.close() return item # def close_spider(self, spider): # self.session.close()<file_sep>/models/models/__init__.py from .municipality import Municipality from .objectType import ObjectType from .advertisement import Advertisement from .ad_view import AD_View from .crawler_stats import CrawlerStats <file_sep>/models/models/ad_view.py # -*- coding: utf-8 -*- """ """ from sqlalchemy import Column, Integer, String, Float, Boolean from .utils import Base class AD_View(Base): """View class to select from view """ __tablename__ = 'ad_view' id = Column(Integer, primary_key=True) living_area = Column(Float) floor = Column(Integer) price_brutto = Column(Float) price_brutto_m2 = Column(Float) build_year = Column(Integer) num_rooms = Column(Integer) was_renovated = Column(Boolean) last_construction = Column(Integer) otype = Column(String) municipality = Column(String) canton_id = Column(String) district_id = Column(String) mountain_region_id = Column(String) language_region_id = Column(String) job_market_region_id = Column(String) agglomeration_id = Column(String) metropole_region_id = Column(String) tourism_region_id = Column(String) is_town = Column(Integer) lat = Column(Float) long = Column(Float) ogroup = Column(String) tags = Column(String) avg_room_area = Column(Float)<file_sep>/models/models/crawler_stats.py # -*- coding: utf-8 -*- """ Statistical data for a crawler """ from sqlalchemy import Column, Integer, String, DateTime, ForeignKey from .utils import Base class CrawlerStats(Base): """Advertisment class to store in the database """ __tablename__ = 'crawler_stats' id = Column(Integer, primary_key=True) crawler = Column(String) # The name of the crawler started = Column(DateTime) ended = Column(DateTime) errors = Column(Integer) exceptions = Column(Integer) warnings = Column(Integer) infos = Column(Integer) requests = Column(Integer) responses = Column(Integer) ignored = Column(Integer) items = Column(Integer) finish_reason = Column(String) def __init__(self, data): self.merge(data) def merge(self, data): self.crawler = data.get('crawler') self.started = data.get('start_time') self.ended = data.get('finish_time') self.errors = data.get('log_count/ERROR') self.exceptions = data.get('downloader/exception_count') self.warnings = data.get('log_count/WARNING') self.infos = data.get('log_count/INFO') self.requests = data.get('downloader/request_count') self.responses = data.get('downloader/response_count') self.ignored = data.get('downloader/exception_type_count/scrapy.exceptions.IgnoreRequest') self.items = data.get('item_scraped_count') self.finish_reason = data.get('finish_reason') def __str__(self): return "CrawlerStats [crawler={}, started={}, ended={}, items_scraped={}]".format(self.crawler, self.started, self.ended, self.items) <file_sep>/db/create_db_docker.sh #!/bin/bash set -e psql -v ON_ERROR_STOP=1 --username "$POSTGRES_ADMIN" postgres <<-EOSQL GRANT ALL PRIVILEGES ON DATABASE $DATABASE_NAME TO $POSTGRES_USER; CREATE DATABASE metabase OWNER $POSTGRES_USER; GRANT ALL PRIVILEGES ON DATABASE metabase TO $POSTGRES_USER; CREATE DATABASE superset OWNER $POSTGRES_USER; GRANT ALL PRIVILEGES ON DATABASE superset TO $POSTGRES_USER; EOSQL echo "Import schema" psql --username "$POSTGRES_USER" "$DATABASE_NAME" < /docker-entrypoint-initdb.d/database_schema.schema echo "Import Municipalities" psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" "$DATABASE_NAME" <<-EOSQL \copy municipalities from '/docker-entrypoint-initdb.d/municipalities_import.csv' delimiter ';' csv HEADER quote e'\x01'; EOSQL echo "Import Object_types" psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" "$DATABASE_NAME" <<-EOSQL \copy object_types from '/docker-entrypoint-initdb.d/object_types_import.csv' delimiter ';' csv HEADER; EOSQL <file_sep>/crawler/reanalytics/extensions/crawlerStats.py import logging from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from scrapy import signals from models import CrawlerStats as Stats from ..settings import DATABASE_URL class CrawlerStats(object): def __init__(self, crawler): self.crawler = crawler engine = create_engine(DATABASE_URL) self.Session = sessionmaker(bind=engine, expire_on_commit=True) crawler.signals.connect(self.spider_opened, signal=signals.spider_opened) crawler.signals.connect(self.spider_closed, signal=signals.spider_closed) @classmethod def from_crawler(cls, crawler): return cls(crawler) def spider_opened(self, spider): self.crawler.stats.set_value('crawler', spider.name) def spider_closed(self, spider): self.session = self.Session() try: stats = Stats(self.crawler.stats.get_stats()) self.session.add(stats) self.session.commit() except Exception as exception: logging.error("Could not save crawler statistics %s cause %s", stats, exception) self.session.rollback() finally: self.session.close() <file_sep>/README.md # Crawler for real estate Start the application with `docker-compose`: ```shell docker-compuse up -d ``` Every container needs his own environment variables which are set in the *.env files: ## Environment files Every thing that can be configured should be done over an environment file for the docker container. ***scrapy.env*** | Value | Description | | ----------------| ------------- | | PROXY_URL | URL to reach the scrapoxy | | API_SCRAPOXY | URL to reach the scrapoxy api | | WAIT_FOR_SCALE | How long the scrapy pause when an instance is scaled | | WAIT_FOR_START | How long the scrapy should wait when started up before crawling | ***scrapy.secrets.env*** | Value | Description | | ------------------------| ------------- | | DATABASE_URL | The database url | | API_SCRAPOXY_PASSWORD | The password to login to the scrapoxy | ***scrapoxy.env*** | Value | Description | | ----------------------------------------- | ------------- | | PROVIDERS_AWSEC2_REGION | In which region should the proxy server start | | PROVIDERS_AWSEC2_INSTANCE_INSTANCETYPE | Which type should be used | | PROVIDERS_AWSEC2_INSTANCE_IMAGEID | The image which should be used when creating the server | | PROVIDERS_AWSEC2_INSTANCE_SECURITYGROUPS | The security groups the machine belongs to | | PROVIDERS_AWSEC2_MAXRUNNINGINSTANCES | How many instances can be run at the same time max | | PROVIDERS_AWSEC2_TAG | Tags which are set to the machines | | INSTANCE_SCALING_MIN | How many instances should always run | | INSTANCE_SCALING_MAX | How big is the step to increase the number of instances | | INSTANCE_AUTORESTART_MINDELAY | How long can an instance live at minimum | | INSTANCE_AUTORESTART_MAXDELAY | How long can an instance live at maximum | ***scrapoxy.secrets.env*** | Value | Description | | ----------------------------------| ------------- | | COMMANDER_PASSWORD | The password for login in to the web interface of scrapoxy | | PROVIDERS_AWSEC2_ACCESSKEYID | The amazon access key id | | PROVIDERS_AWSEC2_SECRETACCESSKEY | The amazon secret access key | ***database.env*** | Value | Description | | ------------------------| ------------- | | PGDATA | Where is the database stored in the filesystem | ***database.secrets.env*** | Value | Description | | -------------------| ------------- | | POSTGRES_PASSWORD | Password for the database | | POSTGRES_USER | User for the database | | DATABASE_NAME | The database name | ## Amazon EC2 To run scrapoxy on amazon it is suggested to copy an existing AMI to your favorite region. Suggestet AMI: `eu-west-1 / t2.nano: ami-06220275`.<file_sep>/superset/startup.sh #!/bin/bash set -e if [ ! -f /tmp/superset_done ]; then # Create an admin user fabmanager create-admin --app superset \ --username $SUPERSET_USER \ --firstname $SUPERSET_FIRSTNAME \ --lastname $SUPERSET_LASTNAME \ --email $SUPERSET_EMAIL \ --password $<PASSWORD> && \ superset db upgrade && \ superset init echo "OK" > /tmp/superset_done fi # Create default roles and permissions superset runserver<file_sep>/requirements.txt asn1crypto==0.23.0 attrs==17.3.0 Automat==0.6.0 certifi==2017.11.5 cffi==1.11.2 chardet==3.0.4 constantly==15.1.0 cryptography==2.1.3 cssselect==1.0.1 hyperlink==17.3.1 idna==2.6 incremental==17.5.0 lxml==4.1.1 -e git+https://github.com/bhzunami/recrawl.git@a2fca389fbe08a29f92f806c36c28f56137e22c4#egg=models&subdirectory=models parsel==1.2.0 psycopg2==2.7.3.2 pyasn1==0.3.7 pyasn1-modules==0.1.5 pycparser==2.18 PyDispatcher==2.0.5 pyOpenSSL==17.3.0 queuelib==1.4.2 requests==2.18.4 scrapoxy==1.9 Scrapy==1.4.0 service-identity==17.0.0 six==1.11.0 SQLAlchemy==1.1.15 Twisted==17.9.0 urllib3==1.22 w3lib==1.18.0 zope.interface==4.4.3 <file_sep>/db/create_database_local.sh #!/bin/bash set -e dropdb --if-exists --username "$POSTGRES_ADMIN" immo dropdb --if-exists --username "$POSTGRES_ADMIN" metabase dropdb --if-exists --username "$POSTGRES_ADMIN" superset dropuser --if-exists immo psql -v ON_ERROR_STOP=1 --username "$POSTGRES_ADMIN" postgres <<-EOSQL CREATE USER $POSTGRES_USER WITH PASSWORD '$<PASSWORD>'; CREATE DATABASE $DATABASE_NAME OWNER $POSTGRES_USER; GRANT ALL PRIVILEGES ON DATABASE $DATABASE_NAME TO $POSTGRES_USER; CREATE DATABASE metabase OWNER $POSTGRES_USER; GRANT ALL PRIVILEGES ON DATABASE metabase TO $POSTGRES_USER CREATE DATABASE superset OWNER $POSTGRES_USER; GRANT ALL PRIVILEGES ON DATABASE superset TO $POSTGRES_USER EOSQL echo "Import schema" psql --username "$POSTGRES_USER" "$DATABASE_NAME" < database_schema.schema echo "Import Municipalities" psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" "$DATABASE_NAME" <<-EOSQL \copy municipalities from './municipalities_import.csv' delimiter ';' csv HEADER quote e'\x01'; EOSQL echo "Import Object_types" psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" "$DATABASE_NAME" <<-EOSQL \copy object_types from './object_types_import.csv' delimiter ';' csv HEADER; EOSQL<file_sep>/crawler/reanalytics/middlewares/crawledURLCheck.py # -*- coding: utf-8 -*- """ Checks if the given URL was already processed """ import logging import datetime from scrapy.exceptions import IgnoreRequest from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from models import Advertisement from ..settings import DATABASE_URL logger = logging.getLogger(__name__) class CrawledURLCheck(object): def __init__(self): engine = create_engine(DATABASE_URL) self.Session = sessionmaker(bind=engine, expire_on_commit=True) def process_request(self, request, spider): """check if the url was already crawled """ if type(spider).__name__ == "DefaultSpider": return None clean_url = spider.get_clean_url(request.url) # Do not check start_urls because these are not added to the database if clean_url in [spider.get_clean_url(u) for u in spider.start_urls]: return None logger.debug("Check if URL[{}] is in database for Spider[{}]".format(clean_url, spider.name)) session = self.Session() advertisement = session.query(Advertisement).filter(Advertisement.url == clean_url).first() if advertisement: logger.info("The URL '{}' was already crawled. Update last seen".format(clean_url)) advertisement.last_seen = datetime.datetime.now() session.add(advertisement) session.commit() raise IgnoreRequest session.close() return None <file_sep>/crawler/reanalytics/spiders/immoscout24.py # -*- coding: utf-8 -*- import random import scrapy from ..models import Ad class Immoscout24(scrapy.Spider): name = "immoscout24" start_urls = [ 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-aargau?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-appenzell-ai?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-appenzell-ar?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-basel-landschaft?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-basel-stadt?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-bern?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-freiburg?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-genf?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-glarus?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-graubuenden?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-jura?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-luzern?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-neuenburg?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-nidwalden?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-obwalden?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-st-gallen?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-schaffhausen?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-schwyz?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-solothurn?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-thurgau?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-tessin?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-uri?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-waadt?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-wallis?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-zug?ps=120', 'https://www.immoscout24.ch/de/immobilien/kaufen/kanton-zuerich?ps=120', # RENTS 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-aargau?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-appenzell-ai?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-appenzell-ar?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-basel-landschaft?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-basel-stadt?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-bern?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-freiburg?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-genf?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-glarus?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-graubuenden?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-jura?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-luzern?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-neuenburg?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-nidwalden?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-obwalden?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-st-gallen?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-schaffhausen?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-schwyz?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-solothurn?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-thurgau?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-tessin?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-uri?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-waadt?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-wallis?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-zug?ps=120', 'https://www.immoscout24.ch/de/immobilien/mieten/kanton-zuerich?ps=120'] def get_clean_url(self, url): """Returns clean ad url for storing in database """ return url.split('?')[0] def start_requests(self): # the l parameter describes the canton id random.shuffle(self.start_urls) for url in self.start_urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): """ Parse the ad list """ # find ads ad_link_path = '//a[@class="item-title"]/@href' for link in response.xpath(ad_link_path).extract(): next_ad = response.urljoin(link) yield scrapy.Request(next_ad, callback=self.parse_ad) # find next page next_page_link = '//a[contains(@class, "next") and not(contains(@class, "disabled"))]/@href' next_page_url = response.xpath(next_page_link).extract_first() if next_page_url: next_page = response.urljoin(next_page_url) yield scrapy.Request(next_page, callback=self.parse) def parse_ad(self, response): ad = Ad() ad['crawler'] = 'immoscout24' ad['url'] = self.get_clean_url(response.url) ad['buy'] = True if 'kaufen' in ad['url'] else False ad['objecttype'] = response.url.split("/")[5].split("-")[0] ad['images'] = ', '.join(response.xpath('//div[contains(@class, "swiper-lazy")]/img/@data-src').extract()) ad['additional_data'] = {} ad['characteristics'] = {} # immoscout does have gibberish div names -> we are interessted in the h2 for selector in response.xpath('//h2'): article = selector.xpath('..') title = selector.xpath('text()').extract_first() if not title: continue title = title.lower() if 'zimmer' in title: ad['num_rooms'] = float(title.split()[0]) if 'standort' in title: address = article.xpath('p/text()').extract() # Missing street if len(address) == 4: ad['street'] = None ad['place'] = "{} {}".format(address[0], address[2]) elif len(address) == 5: ad['street'] = address[0] ad['place'] = "{} {}".format(address[1], address[3]) if 'hauptangaben' in title or 'preis' in title or 'grössenangaben' in title: for element in article.xpath('table/tbody/tr'): try: key, value = element.xpath('td/text()') except ValueError as e: self.logger.debug("Could not extract key value for {}".format(element.xpath('td/text()').extract())) continue key = key.extract() try: key = self.settings['KEY_FIGURES'][key] ad[key] = value.extract() except KeyError: ad['characteristics'][key] = value.extract() if 'beschreibung' in title: ad['description'] = ' '.join(article.xpath('.//p//text()').extract()) if 'innenraum' in title or 'aussenraum' in title or 'technik' in title: for element in article.xpath('table/tbody/tr'): try: key, value = element.xpath('td/text()').extract() ad['characteristics'][key] = value except ValueError: key = element.xpath('td[1]/text()').extract_first() ad['characteristics'][key] = True if 'merkmale' in title: for element in article.xpath('table/tbody/tr'): try: key, value = element.xpath('td/text()') except ValueError as e: key = element.xpath('td[1]/text()').extract_first() ad['characteristics'][key] = True continue key = key.extract() try: key = self.settings['KEY_FIGURES'][key] ad[key] = value.extract() except KeyError: ad['characteristics'][key] = value.extract() yield ad <file_sep>/docker-compose.yml version: '2.1' services: crawler: build: context: . dockerfile: Dockerfile-crawler links: - scrapoxy - database env_file: - crawler/scrapy.env - crawler/scrapy.secrets.env hostname: scrapy volumes: - ./data/logs:/usr/src/app/logs - ./data/share:/tmp/share network_mode: bridge metabase: image: metabase/metabase:v0.27.2 env_file: - metabase/metabase.env - metabase/metabase.secrets.env links: - database ports: - "49302:3000" network_mode: bridge superset: build: context: ./superset dockerfile: Dockerfile env_file: - superset/superset.env - superset/superset.secrets.env ports: - "49303:8088" links: - database - redis hostname: superset network_mode: "bridge" volumes: - ./data/share:/tmp/share redis: image: redis restart: always network_mode: bridge scrapoxy: build: context: ./scrapoxy dockerfile: Dockerfile env_file: - crawler/scrapoxy.env - crawler/scrapoxy.secrets.env ports: - "49301:8889" expose: - 8888 - 8889 network_mode: bridge database: build: context: . dockerfile: Dockerfile-db volumes: - ./data/database:/var/lib/postgresql/data/pgdata - ./data/share:/tmp/share env_file: - db/database.env - db/database.secrets.env network_mode: bridge<file_sep>/superset/Dockerfile FROM debian:stretch # Superset version ARG SUPERSET_VERSION=0.22.1 # Configure environment ENV LANG=C.UTF-8 \ LC_ALL=C.UTF-8 \ PYTHONPATH=/etc/superset:$PYTHONPATH \ SUPERSET_VERSION=${SUPERSET_VERSION} \ SUPERSET_HOME=/home/superset # Create superset user & install dependencies RUN useradd -U -m superset && \ apt-get update && \ apt-get install -y \ build-essential \ curl \ default-libmysqlclient-dev \ libffi-dev \ libldap2-dev \ libpq-dev \ libsasl2-dev \ libssl-dev \ openjdk-8-jdk \ python3-dev \ python3-pip && \ pip3 install \ flask-cors==3.0.3 \ flask-mail==0.9.1 \ gevent==1.2.2 \ impyla==0.14.0 \ psycopg2==2.6.1 \ redis==2.10.5 \ superset==${SUPERSET_VERSION} # Configure Filesystem WORKDIR /home/superset COPY superset_config.py /home/superset/superset_config.py COPY startup.sh /home/superset/startup.sh # Deploy application #HEALTHCHECK CMD ["curl", "-f", "http://localhost:8088/health"] USER superset ENTRYPOINT ["/home/superset/startup.sh"] <file_sep>/scrapoxy/config.js 'use strict'; // Check configuration checkConfig(process.env.COMMANDER_PASSWORD, 'COMMANDER_PASSWORD'); if (emptyConfig(process.env.PROVIDERS_TYPE)) { checkConfig(process.env.PROVIDERS_AWSEC2_ACCESSKEYID, 'PROVIDERS_AWSEC2_ACCESSKEYID'); checkConfig(process.env.PROVIDERS_AWSEC2_SECRETACCESSKEY, 'PROVIDERS_AWSEC2_SECRETACCESSKEY'); } // Export configuration module.exports = { proxy: { port: parseInt(process.env.PROXY_PORT || '8888'), }, commander: { port: parseInt(process.env.COMMANDER_PORT || '8889'), password: <PASSWORD>, }, instance: { checkDelay: parseInt(process.env.INSTANCE_CHECKDELAY || '10000'), checkAliveDelay: parseInt(process.env.INSTANCE_CHECKALIVEDELAY || '20000'), stopIfCrashedDelay: parseInt(process.env.INSTANCE_STOPIFCRASHEDDELAY || '300000'), addProxyNameInRequest: process.env.INSTANCE_ADDPROXYNAMEINREQUEST === 'false', autorestart: { minDelay: parseInt(process.env.INSTANCE_AUTORESTART_MINDELAY || '3600000'), maxDelay: parseInt(process.env.INSTANCE_AUTORESTART_MAXDELAY || '43200000'), }, port: parseInt(process.env.INSTANCE_PORT || '3128'), scaling: { min: parseInt(process.env.INSTANCE_SCALING_MIN || '1'), max: parseInt(process.env.INSTANCE_SCALING_MAX || '2'), downscaleDelay: parseInt(process.env.INSTANCE_SCALING_DOWNSCALEDELAY || '600000'), }, }, providers: { type: process.env.PROVIDERS_TYPE || 'awsec2', awsec2: { accessKeyId: process.env.PROVIDERS_AWSEC2_ACCESSKEYID, secretAccessKey: process.env.PROVIDERS_AWSEC2_SECRETACCESSKEY, region: process.env.PROVIDERS_AWSEC2_REGION || 'eu-west-1', instance: { InstanceType: process.env.PROVIDERS_AWSEC2_INSTANCE_INSTANCETYPE || 't1.micro', ImageId: process.env.PROVIDERS_AWSEC2_INSTANCE_IMAGEID || 'ami-c74d0db4', SecurityGroups: [ process.env.PROVIDERS_AWSEC2_INSTANCE_SECURITYGROUPS || 'forward-proxy' ], }, tag: process.env.PROVIDERS_AWSEC2_TAG || 'Proxy', maxRunningInstances: parseInt(process.env.PROVIDERS_AWSEC2_MAXRUNNINGINSTANCES || '10'), }, ovhcloud: { endpoint: process.env.PROVIDERS_OVHCLOUD_ENDPOINT, appKey: process.env.PROVIDERS_OVHCLOUD_APPKEY, appSecret: process.env.PROVIDERS_OVHCLOUD_APPSECRET, consumerKey: process.env.PROVIDERS_OVHCLOUD_CONSUMERKEY, serviceId: process.env.PROVIDERS_OVHCLOUD_SERVICEID, region: process.env.PROVIDERS_OVHCLOUD_REGION, sshKeyName: process.env.PROVIDERS_OVHCLOUD_SSHKEYNAME, flavorName: process.env.PROVIDERS_OVHCLOUD_FLAVORNAME, snapshotName: process.env.PROVIDERS_OVHCLOUD_SNAPSHOTNAME, name: process.env.PROVIDERS_OVHCLOUD_NAME || 'Proxy', maxRunningInstances: parseInt(process.env.PROVIDERS_OVHCLOUD_MAXRUNNINGINSTANCES || '10'), }, digitalocean: { token: process.env.PROVIDERS_DIGITALOCEAN_TOKEN, region: process.env.PROVIDERS_DIGITALOCEAN_REGION, size: process.env.PROVIDERS_DIGITALOCEAN_SIZE, sshKeyName: process.env.PROVIDERS_DIGITALOCEAN_SSHKEYNAME, imageName: process.env.PROVIDERS_DIGITALOCEAN_IMAGENAME, name: process.env.PROVIDERS_DIGITALOCEAN_NAME || 'Proxy', maxRunningInstances: parseInt(process.env.PROVIDERS_DIGITALOCEAN_MAXRUNNINGINSTANCES || '10'), }, }, stats: { retention: parseInt(process.env.STATS_RETENTION || '86400000'), samplingDelay: parseInt(process.env.STATS_SAMPLINGDELAY || '1000'), }, }; //////////// function emptyConfig(value) { return !value || value.length <= 0; } function checkConfig(value, name) { if (emptyConfig(value)) { throw new Error(`Cannot find environment variable ${name}`); } } <file_sep>/models/models/municipality.py from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Float from sqlalchemy.orm import relationship from sqlalchemy.dialects.postgresql import JSON from .utils import Base class Municipality(Base): """ """ __tablename__ = 'municipalities' id = Column(Integer, primary_key=True) bfsnr = Column(Integer) zip = Column(Integer) name = Column(String) canton_id = Column(Integer) district_id = Column(Integer) planning_region_id = Column(Integer) mountain_region_id = Column(Integer) ase = Column(Integer) greater_region_id = Column(Integer) language_region_id = Column(Integer) ms_region_id = Column(Integer) job_market_region_id = Column(Integer) agglomeration_id = Column(Integer) metropole_region_id = Column(Integer) tourism_region_id = Column(Integer) municipal_size_class_id = Column(Integer) urban_character_id = Column(Integer) agglomeration_size_class_id = Column(Integer) is_town = Column(Integer) degurba_id = Column(Integer) municipal_type22_id = Column(Integer) municipal_type9_id = Column(Integer) ms_region_typology_id = Column(Integer) lv03_easting = Column(Float) lv03_northing = Column(Float) alternate_names = Column(JSON) lat = Column(Float) long = Column(Float) noise_level = Column(Float) steuerfuss_gde = Column(Float) steuerfuss_kanton = Column(Float) <file_sep>/crawler/reanalytics/models/__init__.py from .ad import Ad <file_sep>/crawler/reanalytics/pipelines/coordinates.py # -*- coding: utf-8 -*- """ Get longitude and latitude from the openstreetmap Example for URL request https://api3.geo.admin.ch/rest/services/api/SearchServer?searchText=Holeestrass3 160&type=locations&limit=5 """ import logging import requests from ..settings import ADMIN_BASE_URL logger = logging.getLogger(__name__) class CoordinatesPipeline(object): """ Get longitude and latitude for a specific address from the api3.geo.admin.ch """ def process_item(self, item, spider): """after item is processed """ logger.debug("Execute coordinate assignment for item %s %s from Spider[%s]", item.get('street', None), item.get('place', None), spider.name) if not item.get('street', None) or 'auf anfrage' in item.get('street', '').lower(): logger.info("Ignore street %s for finding coordinates", item.get('street', None)) item['street'] = '' params = {'type': 'locations', 'limit': 1, 'searchText': '{} {}'.format(item.get('street', ''), item.get('place', ''))} req = requests.get(ADMIN_BASE_URL, params=params) if req.status_code != 200: logger.warning("Could not get long and lat for addres %s, %s", item.get('street', None), item.get('place', None)) return item # At the moment always get frist element response = req.json() item['address_fuzzy'] = False if response.get("fuzzy", False): item['address_fuzzy'] = True logger.info("Request for address %s seems fuzzy", params.get('searchText', '')) addresses = response.get('results', []) # Did not get an answer if len(addresses) != 1: logger.warning("Could not get long lat for address %s", params.get('searchText', '')) return item address = addresses[0] item['longitude'] = address.get('attrs', {}).get('lon', None) item['latitude'] = address.get('attrs', {}).get('lat', None) item['lv03_easting'] = address.get('attrs', {}).get('y', None) item['lv03_northing'] = address.get('attrs', {}).get('x', None) logger.debug("Found long {} lat {} for address {}".format(item.get('longitude', None), item.get('latitude', None), params.get('searchText', None))) return item
755098bb901830709765625a3535e2b5f69d8088
[ "YAML", "Markdown", "JavaScript", "Python", "Text", "Dockerfile", "Shell" ]
23
Python
bhzunami/recrawl
987bc32cd934904c4615719ad41a3e10f4d6c804
7b3f4ab7ddf06ceae3386734b1ea049058a0847b
refs/heads/master
<file_sep>package gitDemoProjectv1; public class Test { public static void main(String[] args) { String hangry = "yes"; if (hangry == "yes") System.out.println("eat something... "); else { System.out.println("Do work..."); } } }
0a4d099f85da784db10dcc8ca28b3786cc0c64de
[ "Java" ]
1
Java
ronnie3276/gitDemoProjectv1
ed74936ba6f6c57025699f78220928a7586db3b7
4fa1cb326923dabd93383054ea45e834680bfa94
refs/heads/master
<file_sep>package samaritano.event; import java.lang.reflect.Method; final class Subscriber { static Subscriber create(EventManager manager, EventListener listener, Method method, Class<?>[] parameters) { return new Subscriber(manager, listener, method, parameters); } private final EventManager manager; private final EventListener listener; private final Method method; private final Class<?>[] parameters; private Subscriber(EventManager manager, EventListener listener, Method method, Class<?>[] parameters) { this.manager = manager; this.listener = listener; this.method = method; this.parameters = parameters; } EventManager manager() { return manager; } EventListener listener() { return listener; } Method method() { return method; } Class<?>[] parameters() { return parameters; } }<file_sep>package samaritano.logging; import samaritano.inject.Inject; final class DefaultLogger extends AbstractLogger { DefaultLogger(Outputter outputter, Level defaultLevel) { super(outputter, defaultLevel); } @Inject DefaultLogger(Outputter outputter) { this(outputter, Level.ALL); } }<file_sep>package samaritano.event; final class NoSubscription { private NoSubscription() { } }<file_sep>package samaritano.inject.binder; import samaritano.inject.Injector; import samaritano.inject.Key; import samaritano.inject.Provider; final class ProviderBinding<T> extends AbstractBinding<T> { static <T> ProviderBinding<T> get(Key<T> key, Provider<T> provider) { return new ProviderBinding<>(key, provider); } private final Provider<T> provider; ProviderBinding(Key<T> key, Provider<T> provider) { super(key); this.provider = provider; } @Override public T instanceOf(Key<T> key, Injector injector) throws Exception { return provider.provide(); } }<file_sep>Samaritano ========= A certain _Samaritan_, as he travelled, came where he was. When he saw, he was moved with compassion, came to him, and bound up his wounds, pouring on oil and wine. He set him on his own animal, and brought him to an inn, and took care of him. On the next day, when he departed, he took out two denarii, and gave them to the host, and said to him, take care of him. As the good Samaritan of men, so too comes a good Samaritan for developers. The Samaritan is compassionate and caring, thinking of what he can do for another man. To be as a caretaker, not a hinderence; there when you need him.<file_sep>package samaritano.inject; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import samaritano.inject.binder.ConstantBindingBuilder; import samaritano.inject.binder.LinkedBindingBuilder; import samaritano.inject.binder.ProviderBindingBuilder; abstract class AbstractBinder implements Binder { private final Map<Key<?>, Binding<?>> bindings = new HashMap<>(); @Override public final Map<Key<?>, Binding<?>> bindings() { return bindings; } @Override @SuppressWarnings("unchecked") public final <T> Binding<T> getBinding(Key<T> key) { return (Binding<T>) bindings().get(key); } @Override @SuppressWarnings("unchecked") public final <T> Collection<Binding<T>> getBindings(Class<T> type) { Set<Binding<T>> results = new HashSet<>(); bindings.entrySet().stream() .filter(e -> e.getKey().type().equals(type)) .forEach(e -> results.add((Binding<T>) e.getValue())); return results; } @Override public final <T> void bind(Binding<T> binding) { bindings().put(binding.key(), binding); } @Override public final <T> LinkedBindingBuilder<T> bind(Class<T> type) { return LinkedBindingBuilder.get(this, type); } @Override public final <T> ConstantBindingBuilder<T> bind(T value) { return ConstantBindingBuilder.get(this, value); } @Override public final <T> ProviderBindingBuilder<T> bind(Provider<T> provider) { return ProviderBindingBuilder.get(this, provider); } @Override public final void install(Module module) { module.configure(this); } }<file_sep>package samaritano.event; import static java.util.Collections.unmodifiableCollection; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashSet; import java.util.Set; import samaritano.collect.HashMultimap; import samaritano.collect.Multimap; final class SubscriberRegistry { static SubscriberRegistry create(EventManager manager) { return new SubscriberRegistry(manager); } private final EventManager manager; private final Multimap<Class<? extends Event>, Subscriber> subscribers = HashMultimap .create(); private SubscriberRegistry(EventManager manager) { this.manager = manager; } @SuppressWarnings("unchecked") void register(EventListener listener) { for (Method method : findSubscriptionMethods(listener)) { method.setAccessible(true); Class<?> event = method.getAnnotation(Subscribe.class).value(); Class<?>[] parameters = method.getParameterTypes(); if (NoSubscription.class.equals(event)) event = parameters[0]; subscribers.put((Class<? extends Event>) event, Subscriber.create(manager, listener, method, parameters)); } } Collection<Subscriber> findSubscribers(Event event) { return unmodifiableCollection(subscribers.get(event.getClass())); } private static Iterable<Method> findSubscriptionMethods(EventListener listener) { Set<Method> methods = new HashSet<>(); for (Method method : listener.getClass().getDeclaredMethods()) if (method.isAnnotationPresent(Subscribe.class)) methods.add(method); return methods; } }<file_sep>package samaritano.inject; public interface Injector { <T> T instanceOf(Key<T> key); <T> T instanceOf(Class<T> type); Binder binder(); }<file_sep>package samaritano.logging; public interface Logger { Logger info(Object message); Logger error(Object message); Logger warn(Object message); Logger debug(Object message); Level level(); Logger setLevel(Level level); }<file_sep>package samaritano.inject; import java.util.HashMap; import java.util.Map; public enum Scopes implements Scope { DEFAULT, SINGLETON { private final Map<Class<?>, Object> singletons = new HashMap<>(); @Override public <T> T apply(Key<T> key, T object) { if (!singletons.containsKey(key.type())) singletons.put(key.type(), object); return object; } @Override @SuppressWarnings("unchecked") public <T> T resolve(Key<T> key) { Object object = singletons.get(key.type()); return object == null ? null : (T) object; } }; @Override public <T> T apply(Key<T> key, T object) { return object; } @Override public <T> T resolve(Key<T> key) { return null; } }<file_sep>package samaritano.logging; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; final class SystemErrorOutputter implements Outputter { private static final DateTimeFormatter FORMATTER = DateTimeFormatter .ofPattern("MMM d, yyyy h:mm:ss a"); @Override public void showLog(Object message, Level level) { StackTraceElement trace = new Throwable().getStackTrace()[3]; System.err.println(LocalDateTime.now().format(FORMATTER) + " " + trace.getClassName() + " " + trace.getMethodName()); System.err.println(level.name() + ": " + message); } }<file_sep>package samaritano.inject; public final class DependencyInjection { private static final Injector injector = new DefaultInjector(new DefaultBinder()); private DependencyInjection() { } public static Injector createInjector(Module... modules) { for (Module module : modules) injector.binder().install(module); return injector; } }<file_sep>package samaritano.inject.binder; import samaritano.inject.Binder; import samaritano.inject.Binding; import samaritano.inject.Scope; public final class ScopedBindingBuilder<T> extends TypedBindingBuilder<T> { public static <T> ScopedBindingBuilder<T> get(Binder binder, Class<T> type, Binding<T> binding) { return new ScopedBindingBuilder<T>(binder, type, binding); } private final Binding<T> binding; private ScopedBindingBuilder(Binder binder, Class<T> type, Binding<T> binding) { super(binder, type); this.binding = binding; } public void in(Scope scope) { binder().bind(ScopedBinding.get(binding, scope)); } }<file_sep>package samaritano.inject; import java.lang.annotation.Annotation; import samaritano.Nullable; public final class Key<T> { public static <T> Key<T> of(Class<T> type) { return of(type, null); } public static <T> Key<T> of(Class<T> type, @Nullable Class<? extends Annotation> annotation) { return new Key<T>(type, annotation); } private final Class<T> type; private Class<? extends Annotation> annotation; private Key(Class<T> type, @Nullable Class<? extends Annotation> annotation) { this.type = type; this.annotation = annotation; } public Class<T> type() { return type; } public Class<? extends Annotation> annotation() { return annotation; } @Override public int hashCode() { int hash = 0; if (annotation != null) hash = annotation.hashCode(); return type.hashCode() ^ hash; } @Override public boolean equals(Object o) { if (!(o instanceof Key)) return false; Key<?> key = (Key<?>) o; return hashCode() == key.hashCode(); } }<file_sep>package samaritano.affirm; final class TruthAffirmative implements Affirmative<Boolean> { @Override public boolean affirm(Boolean reference, Object... values) { return reference; } }<file_sep>package samaritano.collect; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; public final class HashMultimap<K, V> extends AbstractMultimap<K, V> { public static <K, V> Multimap<K, V> create() { return new HashMultimap<>(); } private HashMultimap() { super(new HashMap<>()); } @Override protected Collection<V> generateCollection() { return new ArrayList<>(); } }<file_sep>package samaritano.inject; public interface Scope { <T> T apply(Key<T> key, T object); <T> T resolve(Key<T> key); }<file_sep>package samaritano.event; import static java.util.stream.Stream.of; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Iterator; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import samaritano.inject.Injector; public final class DefaultEventManager implements EventManager { private final SubscriberRegistry registry = SubscriberRegistry.create(this); private final Set<Injector> injectors = new HashSet<>(); @Override public void register(EventListener listener) { registry.register(listener); } @Override public void register(Injector injector) { injectors.add(injector); } @Override public void post(Event event) { registry.findSubscribers(event).forEach(subscriber -> { try { Class<?>[] types = subscriber.parameters(); Object[] parameters = new Object[types.length]; if (types.length > 1 || !event.getClass().equals(types[0])) { for (int i = 0; i < types.length; i++) parameters[i] = scout(event, types[i]); } else parameters[0] = event; subscriber.method().invoke(subscriber.listener(), parameters); } catch (Exception e) { throw new RuntimeException(e); } }); } @SuppressWarnings("unchecked") private <T> T scout(Event event, Class<?> parameter) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<? extends Event> type = event.getClass(); // Return event if parameter requires it if (parameter.equals(type)) return (T) event; // Check for available methods Optional<Method> method = findMethod(type, parameter); if (method.isPresent()) { method.get().setAccessible(true); return (T) method.get().invoke(event); } // Check for available fields Optional<Field> field = findField(type, parameter); if (field.isPresent()) { field.get().setAccessible(true); return (T) field.get().get(event); } // Finally, check the injectors for any matches Optional<Object> object = findObject(type, parameter); if (object.isPresent()) return (T) object.get(); // We can't find anything, shouldn't be possible. throw new NullPointerException(); } private static Optional<Field> findField(Class<? extends Event> t, Class<?> p) { return of(t.getDeclaredFields()).filter(f -> p.equals(f.getType()) && f.isAnnotationPresent(Provide.class)).findFirst(); } private static Optional<Method> findMethod(Class<? extends Event> t, Class<?> p) { return of(t.getDeclaredMethods()).filter(m -> m.getParameterCount() == 0 && p.equals(m.getReturnType()) && m.isAnnotationPresent(Provide.class)).findFirst(); } private Optional<Object> findObject(Class<? extends Event> t, Class<?> p) { Iterator<?> iterator = injectors.stream().map(i -> { return i.instanceOf(p); }).collect(Collectors.toSet()).iterator(); while (iterator.hasNext()) { Object result = iterator.next(); if (result != null) return Optional.of(result); } return Optional.empty(); } }<file_sep>package samaritano; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) public @interface Nullable { }<file_sep>package samaritano.inject.binder; import samaritano.inject.Binding; import samaritano.inject.Key; abstract class AbstractBinding<T> implements Binding<T> { private final Key<T> key; AbstractBinding(Key<T> key) { this.key = key; } @Override public final Key<T> key() { return key; } }<file_sep>package samaritano.inject.binder; import java.lang.annotation.Annotation; import samaritano.inject.Binder; import samaritano.inject.Key; import samaritano.inject.Provider; public final class ProviderBindingBuilder<T> extends AbstractBindingBuilder { public static <T> ProviderBindingBuilder<T> get(Binder binder, Provider<T> provider) { return new ProviderBindingBuilder<>(binder, provider); } private final Provider<T> provider; private ProviderBindingBuilder(Binder binder, Provider<T> provider) { super(binder); this.provider = provider; } @SuppressWarnings("unchecked") public void to(Class<? extends Annotation> annotation) { try { Class<T> type = (Class<T>) provider.getClass().getMethod("provide").getReturnType(); if (type == null) throw new NullPointerException(); binder().bind(ProviderBinding.get(Key.of(type, annotation), provider)); } catch (NoSuchMethodException | SecurityException | NullPointerException e) { throw new Error(e); } } }<file_sep>package samaritano; import java.util.HashMap; import java.util.Map; import samaritano.affirm.Affirm; public final class Primitives { private static final Map<Class<?>, Class<?>> wrappers = new HashMap<>(); static { wrappers.put(boolean.class, Boolean.class); wrappers.put(byte.class, Byte.class); wrappers.put(short.class, Short.class); wrappers.put(char.class, Character.class); wrappers.put(int.class, Integer.class); wrappers.put(long.class, Long.class); wrappers.put(float.class, Float.class); wrappers.put(double.class, Double.class); } public static Class<?> wrap(Class<?> type) { Affirm.notNull(type); if (!type.isPrimitive()) return type; return wrappers.get(type); } }
d8439f9af40a6f3b53be3879aa38a9b9fdf58391
[ "Markdown", "Java" ]
22
Java
Jire/samaritano
f04c7c2c4b448a4cb9d0c8fc270a6d1ff62412d9
6afddef4f85e777cadc8c127bcb3cc2d811c17b5